3 * (c) 1995 Microsoft Corporation. All rights reserved.
4 * Developed by hip communications inc., http://info.hip.com/info/
5 * Portions (c) 1993 Intergraph Corporation. All rights reserved.
7 * You may distribute under the terms of either the GNU General Public
8 * License or the Artistic License, as specified in the README file.
11 #define WIN32_LEAN_AND_MEAN
12 #define WIN32IO_IS_STDIO
22 /* ugliness to work around a buggy struct definition in lmwksta.h */
29 #endif /* __MINGW32__ */
31 /* #include "config.h" */
33 #define PERLIO_NOT_STDIO 0
34 #if !defined(PERLIO_IS_STDIO) && !defined(USE_SFIO)
48 /* assert.h conflicts with #define of assert in perl.h */
55 #if defined(_MSC_VER) || defined(__MINGW32__)
56 #include <sys/utime.h>
62 /* Mingw32 defaults to globing command line
63 * So we turn it off like this:
70 #define EXECF_SPAWN_NOWAIT 3
72 #if defined(PERL_OBJECT)
73 #undef win32_get_privlib
74 #define win32_get_privlib g_win32_get_privlib
75 #undef win32_get_sitelib
76 #define win32_get_sitelib g_win32_get_sitelib
78 #define do_aspawn g_do_aspawn
80 #define do_spawn g_do_spawn
82 #define Perl_do_exec g_do_exec
84 #define getlogin g_getlogin
87 static void get_shell(void);
88 static long tokenize(char *str, char **dest, char ***destv);
89 int do_spawn2(pTHX_ char *cmd, int exectype);
90 static BOOL has_shell_metachars(char *ptr);
91 static long filetime_to_clock(PFILETIME ft);
92 static BOOL filetime_from_time(PFILETIME ft, time_t t);
93 static char * get_emd_part(char **leading, char *trailing, ...);
94 static void remove_dead_process(long deceased);
95 static long find_pid(int pid);
96 static char * qualified_path(const char *cmd);
98 HANDLE w32_perldll_handle = INVALID_HANDLE_VALUE;
99 char w32_module_name[MAX_PATH+1];
100 static DWORD w32_platform = (DWORD)-1;
103 # ifdef USE_DECLSPEC_THREAD
104 __declspec(thread) char strerror_buffer[512];
105 __declspec(thread) char getlogin_buffer[128];
106 __declspec(thread) char w32_perllib_root[MAX_PATH+1];
107 # ifdef HAVE_DES_FCRYPT
108 __declspec(thread) char crypt_buffer[30];
111 # define strerror_buffer (thr->i.Wstrerror_buffer)
112 # define getlogin_buffer (thr->i.Wgetlogin_buffer)
113 # define w32_perllib_root (thr->i.Ww32_perllib_root)
114 # define crypt_buffer (thr->i.Wcrypt_buffer)
117 static char strerror_buffer[512];
118 static char getlogin_buffer[128];
119 static char w32_perllib_root[MAX_PATH+1];
120 # ifdef HAVE_DES_FCRYPT
121 static char crypt_buffer[30];
128 return (win32_os_id() == VER_PLATFORM_WIN32_WINDOWS);
134 return (win32_os_id() == VER_PLATFORM_WIN32_NT);
137 /* *ptr is expected to point to valid allocated space (can't be NULL) */
139 GetRegStrFromKey(HKEY hkey, const char *lpszValueName, char** ptr, DWORD* lpDataLen)
141 /* Retrieve a REG_SZ or REG_EXPAND_SZ from the registry */
144 const char *subkey = "Software\\Perl";
148 retval = RegOpenKeyEx(hkey, subkey, 0, KEY_READ, &handle);
149 if (retval == ERROR_SUCCESS) {
150 retval = RegQueryValueEx(handle, lpszValueName, 0, &type, NULL, lpDataLen);
151 if (retval == ERROR_SUCCESS && type == REG_SZ) {
153 Renew(*ptr, *lpDataLen, char);
154 retval = RegQueryValueEx(handle, lpszValueName, 0, NULL,
155 (PBYTE)*ptr, lpDataLen);
156 if (retval == ERROR_SUCCESS)
164 /* *ptr is expected to point to valid allocated space (can't be NULL) */
166 GetRegStr(const char *lpszValueName, char** ptr, DWORD* lpDataLen)
168 char *str = GetRegStrFromKey(HKEY_CURRENT_USER, lpszValueName, ptr, lpDataLen);
170 str = GetRegStrFromKey(HKEY_LOCAL_MACHINE, lpszValueName, ptr, lpDataLen);
174 /* *prev_path is expected to point to valid allocated space (can't be NULL) */
176 get_emd_part(char **prev_path, char *trailing_path, ...)
180 char mod_name[MAX_PATH+1];
184 int oldsize, newsize;
186 va_start(ap, trailing_path);
187 strip = va_arg(ap, char *);
189 sprintf(base, "%5.3f",
190 (double)PERL_REVISION + ((double)PERL_VERSION / (double)1000));
192 if (!*w32_module_name) {
193 GetModuleFileName((HMODULE)((w32_perldll_handle == INVALID_HANDLE_VALUE)
194 ? GetModuleHandle(NULL)
195 : w32_perldll_handle),
196 w32_module_name, sizeof(w32_module_name));
198 /* try to get full path to binary (which may be mangled when perl is
199 * run from a 16-bit app) */
200 /*PerlIO_printf(PerlIO_stderr(), "Before %s\n", w32_module_name);*/
201 (void)win32_longpath(w32_module_name);
202 /*PerlIO_printf(PerlIO_stderr(), "After %s\n", w32_module_name);*/
204 /* normalize to forward slashes */
205 ptr = w32_module_name;
212 strcpy(mod_name, w32_module_name);
213 ptr = strrchr(mod_name, '/');
214 while (ptr && strip) {
215 /* look for directories to skip back */
218 ptr = strrchr(mod_name, '/');
219 /* avoid stripping component if there is no slash,
220 * or it doesn't match ... */
221 if (!ptr || stricmp(ptr+1, strip) != 0) {
222 /* ... but not if component matches 5.00X* */
223 if (!ptr || !(*strip == '5' && *(ptr+1) == '5'
224 && strncmp(strip, base, 5) == 0
225 && strncmp(ptr+1, base, 5) == 0))
231 strip = va_arg(ap, char *);
239 strcpy(++ptr, trailing_path);
241 /* only add directory if it exists */
242 if (GetFileAttributes(mod_name) != (DWORD) -1) {
243 /* directory exists */
245 newsize = strlen(mod_name) + 1;
246 oldsize = strlen(*prev_path) + 1;
247 newsize += oldsize; /* includes plus 1 for ';' */
248 Renew(*prev_path, newsize, char);
249 (*prev_path)[oldsize-1] = ';';
250 strcpy(&(*prev_path)[oldsize], mod_name);
258 win32_get_privlib(pTHX_ char *pl)
260 char *stdlib = "lib";
261 char buffer[MAX_PATH+1];
265 SV *sv = sv_2mortal(newSVpvn("",127));
267 /* $stdlib = $HKCU{"lib-$]"} || $HKLM{"lib-$]"} || $HKCU{"lib"} || $HKLM{"lib"} || ""; */
268 sprintf(buffer, "%s-%s", stdlib, pl);
270 if (!GetRegStr(buffer, path, &datalen))
271 (void)GetRegStr(stdlib, path, &datalen);
273 /* $stdlib .= ";$EMD/../../lib" */
274 (void)get_emd_part(path, stdlib, ARCHNAME, "bin", Nullch);
275 SvCUR_set(sv, strlen(*path));
276 SvLEN_set(sv, SvCUR(sv)+1);
281 win32_get_sitelib(pTHX_ char *pl)
283 char *sitelib = "sitelib";
285 char pathstr[MAX_PATH+1];
287 char **path1, *str1 = Nullch;
288 char **path2, *str2 = Nullch;
291 SV *sv1 = sv_2mortal(newSVpvn("",127));
292 SV *sv2 = sv_2mortal(newSVpvn("",127));
294 /* $HKCU{"sitelib-$]"} || $HKLM{"sitelib-$]"} . ---; */
295 sprintf(regstr, "%s-%s", sitelib, pl);
297 (void)GetRegStr(regstr, path1, &datalen);
300 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/site/$]/lib"; */
301 sprintf(pathstr, "site/%s/lib", pl);
302 str1 = get_emd_part(path1, pathstr, ARCHNAME, "bin", pl, Nullch);
303 if (!str1 && strlen(pl) == 7) {
304 /* pl may have been SUBVERSION-specific; try again without
306 sprintf(pathstr, "site/%.5s/lib", pl);
307 str1 = get_emd_part(path1, pathstr, ARCHNAME, "bin", pl, Nullch);
310 /* $HKCU{'sitelib'} || $HKLM{'sitelib'} . ---; */
312 (void)GetRegStr(sitelib, path2, &datalen);
315 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/site/lib"; */
316 str2 = get_emd_part(path2, "site/lib", ARCHNAME, "bin", pl, Nullch);
318 SvCUR_set(sv1, strlen(*path1));
319 SvLEN_set(sv1, SvCUR(sv1)+1);
320 SvCUR_set(sv2, strlen(*path2));
321 SvLEN_set(sv2, SvCUR(sv2)+1);
328 sv_catpvn(sv1, ";", 1);
336 has_shell_metachars(char *ptr)
342 * Scan string looking for redirection (< or >) or pipe
343 * characters (|) that are not in a quoted string.
344 * Shell variable interpolation (%VAR%) can also happen inside strings.
376 #if !defined(PERL_OBJECT)
377 /* since the current process environment is being updated in util.c
378 * the library functions will get the correct environment
381 Perl_my_popen(pTHX_ char *cmd, char *mode)
384 #define fixcmd(x) { \
385 char *pspace = strchr((x),' '); \
388 while (p < pspace) { \
399 PERL_FLUSHALL_FOR_CHILD;
400 return win32_popen(cmd, mode);
404 Perl_my_pclose(pTHX_ PerlIO *fp)
406 return win32_pclose(fp);
410 DllExport unsigned long
413 static OSVERSIONINFO osver;
415 if (osver.dwPlatformId != w32_platform) {
416 memset(&osver, 0, sizeof(OSVERSIONINFO));
417 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
418 GetVersionEx(&osver);
419 w32_platform = osver.dwPlatformId;
421 return (unsigned long)w32_platform;
424 /* Tokenize a string. Words are null-separated, and the list
425 * ends with a doubled null. Any character (except null and
426 * including backslash) may be escaped by preceding it with a
427 * backslash (the backslash will be stripped).
428 * Returns number of words in result buffer.
431 tokenize(char *str, char **dest, char ***destv)
433 char *retstart = Nullch;
434 char **retvstart = 0;
438 int slen = strlen(str);
440 register char **retv;
441 New(1307, ret, slen+2, char);
442 New(1308, retv, (slen+3)/2, char*);
450 if (*ret == '\\' && *str)
452 else if (*ret == ' ') {
468 retvstart[items] = Nullch;
481 if (!w32_perlshell_tokens) {
482 /* we don't use COMSPEC here for two reasons:
483 * 1. the same reason perl on UNIX doesn't use SHELL--rampant and
484 * uncontrolled unportability of the ensuing scripts.
485 * 2. PERL5SHELL could be set to a shell that may not be fit for
486 * interactive use (which is what most programs look in COMSPEC
489 char* defaultshell = (IsWinNT() ? "cmd.exe /x/c" : "command.com /c");
490 char *usershell = getenv("PERL5SHELL");
491 w32_perlshell_items = tokenize(usershell ? usershell : defaultshell,
492 &w32_perlshell_tokens,
498 do_aspawn(pTHX_ void *vreally, void **vmark, void **vsp)
500 SV *really = (SV*)vreally;
501 SV **mark = (SV**)vmark;
514 New(1306, argv, (sp - mark) + w32_perlshell_items + 2, char*);
516 if (SvNIOKp(*(mark+1)) && !SvPOKp(*(mark+1))) {
521 while (++mark <= sp) {
522 if (*mark && (str = SvPV_nolen(*mark)))
529 status = win32_spawnvp(flag,
530 (const char*)(really ? SvPV_nolen(really) : argv[0]),
531 (const char* const*)argv);
533 if (status < 0 && (errno == ENOEXEC || errno == ENOENT)) {
534 /* possible shell-builtin, invoke with shell */
536 sh_items = w32_perlshell_items;
538 argv[index+sh_items] = argv[index];
539 while (--sh_items >= 0)
540 argv[sh_items] = w32_perlshell_vec[sh_items];
542 status = win32_spawnvp(flag,
543 (const char*)(really ? SvPV_nolen(really) : argv[0]),
544 (const char* const*)argv);
547 if (flag != P_NOWAIT) {
550 Perl_warn(aTHX_ "Can't spawn \"%s\": %s", argv[0], strerror(errno));
555 PL_statusvalue = status;
562 do_spawn2(pTHX_ char *cmd, int exectype)
568 BOOL needToTry = TRUE;
572 /* Save an extra exec if possible. See if there are shell
573 * metacharacters in it */
574 if (!has_shell_metachars(cmd)) {
575 New(1301,argv, strlen(cmd) / 2 + 2, char*);
576 New(1302,cmd2, strlen(cmd) + 1, char);
579 for (s = cmd2; *s;) {
580 while (*s && isSPACE(*s))
584 while (*s && !isSPACE(*s))
593 status = win32_spawnvp(P_WAIT, argv[0],
594 (const char* const*)argv);
596 case EXECF_SPAWN_NOWAIT:
597 status = win32_spawnvp(P_NOWAIT, argv[0],
598 (const char* const*)argv);
601 status = win32_execvp(argv[0], (const char* const*)argv);
604 if (status != -1 || errno == 0)
614 New(1306, argv, w32_perlshell_items + 2, char*);
615 while (++i < w32_perlshell_items)
616 argv[i] = w32_perlshell_vec[i];
621 status = win32_spawnvp(P_WAIT, argv[0],
622 (const char* const*)argv);
624 case EXECF_SPAWN_NOWAIT:
625 status = win32_spawnvp(P_NOWAIT, argv[0],
626 (const char* const*)argv);
629 status = win32_execvp(argv[0], (const char* const*)argv);
635 if (exectype != EXECF_SPAWN_NOWAIT) {
638 Perl_warn(aTHX_ "Can't %s \"%s\": %s",
639 (exectype == EXECF_EXEC ? "exec" : "spawn"),
640 cmd, strerror(errno));
645 PL_statusvalue = status;
651 do_spawn(pTHX_ char *cmd)
653 return do_spawn2(aTHX_ cmd, EXECF_SPAWN);
657 do_spawn_nowait(pTHX_ char *cmd)
659 return do_spawn2(aTHX_ cmd, EXECF_SPAWN_NOWAIT);
663 Perl_do_exec(pTHX_ char *cmd)
665 do_spawn2(aTHX_ cmd, EXECF_EXEC);
669 /* The idea here is to read all the directory names into a string table
670 * (separated by nulls) and when one of the other dir functions is called
671 * return the pointer to the current file name.
674 win32_opendir(char *filename)
680 char scanname[MAX_PATH+3];
682 WIN32_FIND_DATAA aFindData;
683 WIN32_FIND_DATAW wFindData;
685 char buffer[MAX_PATH*2];
686 WCHAR wbuffer[MAX_PATH];
690 len = strlen(filename);
694 /* check to see if filename is a directory */
695 if (win32_stat(filename, &sbuf) < 0 || !S_ISDIR(sbuf.st_mode))
698 /* Get us a DIR structure */
699 Newz(1303, p, 1, DIR);
703 /* Create the search pattern */
704 strcpy(scanname, filename);
706 /* bare drive name means look in cwd for drive */
707 if (len == 2 && isALPHA(scanname[0]) && scanname[1] == ':') {
708 scanname[len++] = '.';
709 scanname[len++] = '/';
711 else if (scanname[len-1] != '/' && scanname[len-1] != '\\') {
712 scanname[len++] = '/';
714 scanname[len++] = '*';
715 scanname[len] = '\0';
717 /* do the FindFirstFile call */
719 A2WHELPER(scanname, wbuffer, sizeof(wbuffer));
720 fh = FindFirstFileW(wbuffer, &wFindData);
723 fh = FindFirstFileA(scanname, &aFindData);
725 if (fh == INVALID_HANDLE_VALUE) {
726 /* FindFirstFile() fails on empty drives! */
727 if (GetLastError() == ERROR_FILE_NOT_FOUND)
733 /* now allocate the first part of the string table for
734 * the filenames that we find.
737 W2AHELPER(wFindData.cFileName, buffer, sizeof(buffer));
741 ptr = aFindData.cFileName;
744 New(1304, p->start, idx, char);
745 if (p->start == NULL)
746 Perl_croak_nocontext("opendir: malloc failed!\n");
747 strcpy(p->start, ptr);
750 /* loop finding all the files that match the wildcard
751 * (which should be all of them in this directory!).
752 * the variable idx should point one past the null terminator
753 * of the previous string found.
756 ? FindNextFileW(fh, &wFindData)
757 : FindNextFileA(fh, &aFindData)) {
759 W2AHELPER(wFindData.cFileName, buffer, sizeof(buffer));
761 /* ptr is set above to the correct area */
763 /* bump the string table size by enough for the
764 * new name and it's null terminator
766 Renew(p->start, idx+len+1, char);
767 if (p->start == NULL)
768 Perl_croak_nocontext("opendir: malloc failed!\n");
769 strcpy(&p->start[idx], ptr);
780 /* Readdir just returns the current string pointer and bumps the
781 * string pointer to the nDllExport entry.
784 win32_readdir(DIR *dirp)
787 static int dummy = 0;
790 /* first set up the structure to return */
791 len = strlen(dirp->curr);
792 strcpy(dirp->dirstr.d_name, dirp->curr);
793 dirp->dirstr.d_namlen = len;
796 dirp->dirstr.d_ino = dummy++;
798 /* Now set up for the nDllExport call to readdir */
799 dirp->curr += len + 1;
800 if (dirp->curr >= (dirp->start + dirp->size)) {
804 return &(dirp->dirstr);
810 /* Telldir returns the current string pointer position */
812 win32_telldir(DIR *dirp)
814 return (long) dirp->curr;
818 /* Seekdir moves the string pointer to a previously saved position
822 win32_seekdir(DIR *dirp, long loc)
824 dirp->curr = (char *)loc;
827 /* Rewinddir resets the string pointer to the start */
829 win32_rewinddir(DIR *dirp)
831 dirp->curr = dirp->start;
834 /* free the memory allocated by opendir */
836 win32_closedir(DIR *dirp)
839 Safefree(dirp->start);
852 * Just pretend that everyone is a superuser. NT will let us know if
853 * we don\'t really have permission to do something.
856 #define ROOT_UID ((uid_t)0)
857 #define ROOT_GID ((gid_t)0)
886 return (auid == ROOT_UID ? 0 : -1);
892 return (agid == ROOT_GID ? 0 : -1);
899 char *buf = getlogin_buffer;
900 DWORD size = sizeof(getlogin_buffer);
901 if (GetUserName(buf,&size))
907 chown(const char *path, uid_t owner, gid_t group)
918 for (child = 0 ; child < w32_num_children ; ++child) {
919 if (w32_child_pids[child] == pid)
926 remove_dead_process(long child)
930 CloseHandle(w32_child_handles[child]);
931 Copy(&w32_child_handles[child+1], &w32_child_handles[child],
932 (w32_num_children-child-1), HANDLE);
933 Copy(&w32_child_pids[child+1], &w32_child_pids[child],
934 (w32_num_children-child-1), DWORD);
940 win32_kill(int pid, int sig)
943 hProcess = OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid);
944 if (hProcess && TerminateProcess(hProcess, sig))
945 CloseHandle(hProcess);
957 DllExport unsigned int
958 win32_sleep(unsigned int t)
965 win32_stat(const char *path, struct stat *buffer)
968 int l = strlen(path);
970 WCHAR wbuffer[MAX_PATH];
973 switch(path[l - 1]) {
974 /* FindFirstFile() and stat() are buggy with a trailing
975 * backslash, so change it to a forward slash :-( */
977 strncpy(t, path, l-1);
982 /* FindFirstFile() is buggy with "x:", so add a dot :-( */
984 if (l == 2 && isALPHA(path[0])) {
985 t[0] = path[0]; t[1] = ':'; t[2] = '.'; t[3] = '\0';
995 A2WHELPER(path, wbuffer, sizeof(wbuffer));
996 res = _wstat(wbuffer, (struct _stat *)buffer);
999 res = stat(path, buffer);
1002 /* CRT is buggy on sharenames, so make sure it really isn't.
1003 * XXX using GetFileAttributesEx() will enable us to set
1004 * buffer->st_*time (but note that's not available on the
1005 * Windows of 1995) */
1008 r = GetFileAttributesW(wbuffer);
1011 r = GetFileAttributesA(path);
1013 if (r != 0xffffffff && (r & FILE_ATTRIBUTE_DIRECTORY)) {
1014 /* buffer may still contain old garbage since stat() failed */
1015 Zero(buffer, 1, struct stat);
1016 buffer->st_mode = S_IFDIR | S_IREAD;
1018 if (!(r & FILE_ATTRIBUTE_READONLY))
1019 buffer->st_mode |= S_IWRITE | S_IEXEC;
1024 if (l == 3 && isALPHA(path[0]) && path[1] == ':'
1025 && (path[2] == '\\' || path[2] == '/'))
1027 /* The drive can be inaccessible, some _stat()s are buggy */
1029 ? !GetVolumeInformationW(wbuffer,NULL,0,NULL,NULL,NULL,NULL,0)
1030 : !GetVolumeInformationA(path,NULL,0,NULL,NULL,NULL,NULL,0)) {
1036 if (S_ISDIR(buffer->st_mode))
1037 buffer->st_mode |= S_IWRITE | S_IEXEC;
1038 else if (S_ISREG(buffer->st_mode)) {
1039 if (l >= 4 && path[l-4] == '.') {
1040 const char *e = path + l - 3;
1041 if (strnicmp(e,"exe",3)
1042 && strnicmp(e,"bat",3)
1043 && strnicmp(e,"com",3)
1044 && (IsWin95() || strnicmp(e,"cmd",3)))
1045 buffer->st_mode &= ~S_IEXEC;
1047 buffer->st_mode |= S_IEXEC;
1050 buffer->st_mode &= ~S_IEXEC;
1057 /* Find the longname of a given path. path is destructively modified.
1058 * It should have space for at least MAX_PATH characters. */
1060 win32_longpath(char *path)
1062 WIN32_FIND_DATA fdata;
1064 char tmpbuf[MAX_PATH+1];
1065 char *tmpstart = tmpbuf;
1072 if (isALPHA(path[0]) && path[1] == ':' &&
1073 (path[2] == '/' || path[2] == '\\'))
1076 *tmpstart++ = path[0];
1080 else if ((path[0] == '/' || path[0] == '\\') &&
1081 (path[1] == '/' || path[1] == '\\'))
1084 *tmpstart++ = path[0];
1085 *tmpstart++ = path[1];
1086 /* copy machine name */
1087 while (*start && *start != '/' && *start != '\\')
1088 *tmpstart++ = *start++;
1090 *tmpstart++ = *start;
1092 /* copy share name */
1093 while (*start && *start != '/' && *start != '\\')
1094 *tmpstart++ = *start++;
1098 if (sep == '/' || sep == '\\')
1102 /* walk up to slash */
1103 while (*start && *start != '/' && *start != '\\')
1106 /* discard doubled slashes */
1107 while (*start && (start[1] == '/' || start[1] == '\\'))
1111 /* stop and find full name of component */
1113 fhand = FindFirstFile(path,&fdata);
1114 if (fhand != INVALID_HANDLE_VALUE) {
1115 strcpy(tmpstart, fdata.cFileName);
1116 tmpstart += strlen(fdata.cFileName);
1124 /* failed a step, just return without side effects */
1125 /*PerlIO_printf(PerlIO_stderr(), "Failed to find %s\n", path);*/
1130 strcpy(path,tmpbuf);
1134 #ifndef USE_WIN32_RTL_ENV
1137 win32_getenv(const char *name)
1141 static char *curitem = Nullch; /* XXX threadead */
1142 static WCHAR *wCuritem = (WCHAR*)Nullch; /* XXX threadead */
1143 static DWORD curlen = 0, wCurlen = 0;/* XXX threadead */
1144 WCHAR wBuffer[MAX_PATH];
1150 New(1306,wCuritem,wCurlen,WCHAR);
1155 New(1305,curitem,curlen,char);
1159 A2WHELPER(name, wBuffer, sizeof(wBuffer));
1160 needlen = GetEnvironmentVariableW(wBuffer,wCuritem,wCurlen);
1163 needlen = GetEnvironmentVariableA(name,curitem,curlen);
1166 while (needlen > wCurlen) {
1167 Renew(wCuritem,needlen,WCHAR);
1169 needlen = GetEnvironmentVariableW(wBuffer,wCuritem,wCurlen);
1171 if (needlen > curlen) {
1172 Renew(curitem,needlen,char);
1175 W2AHELPER(wCuritem, curitem, curlen);
1178 while (needlen > curlen) {
1179 Renew(curitem,needlen,char);
1181 needlen = GetEnvironmentVariableA(name,curitem,curlen);
1186 /* allow any environment variables that begin with 'PERL'
1187 to be stored in the registry */
1191 if (strncmp(name, "PERL", 4) == 0) {
1197 curitem = GetRegStr(name, &curitem, &curlen);
1200 if (curitem && *curitem == '\0')
1207 win32_putenv(const char *name)
1213 int length, relval = -1;
1218 length = strlen(name)+1;
1219 New(1309,wCuritem,length,WCHAR);
1220 A2WHELPER(name, wCuritem, length*2);
1221 wVal = wcschr(wCuritem, '=');
1224 if(SetEnvironmentVariableW(wCuritem, *wVal ? wVal : NULL))
1230 New(1309,curitem,strlen(name)+1,char);
1231 strcpy(curitem, name);
1232 val = strchr(curitem, '=');
1234 /* The sane way to deal with the environment.
1235 * Has these advantages over putenv() & co.:
1236 * * enables us to store a truly empty value in the
1237 * environment (like in UNIX).
1238 * * we don't have to deal with RTL globals, bugs and leaks.
1240 * Why you may want to enable USE_WIN32_RTL_ENV:
1241 * * environ[] and RTL functions will not reflect changes,
1242 * which might be an issue if extensions want to access
1243 * the env. via RTL. This cuts both ways, since RTL will
1244 * not see changes made by extensions that call the Win32
1245 * functions directly, either.
1249 if(SetEnvironmentVariableA(curitem, *val ? val : NULL))
1261 filetime_to_clock(PFILETIME ft)
1263 __int64 qw = ft->dwHighDateTime;
1265 qw |= ft->dwLowDateTime;
1266 qw /= 10000; /* File time ticks at 0.1uS, clock at 1mS */
1271 win32_times(struct tms *timebuf)
1276 if (GetProcessTimes(GetCurrentProcess(), &dummy, &dummy,
1278 timebuf->tms_utime = filetime_to_clock(&user);
1279 timebuf->tms_stime = filetime_to_clock(&kernel);
1280 timebuf->tms_cutime = 0;
1281 timebuf->tms_cstime = 0;
1284 /* That failed - e.g. Win95 fallback to clock() */
1285 clock_t t = clock();
1286 timebuf->tms_utime = t;
1287 timebuf->tms_stime = 0;
1288 timebuf->tms_cutime = 0;
1289 timebuf->tms_cstime = 0;
1294 /* fix utime() so it works on directories in NT
1295 * thanks to Jan Dubois <jan.dubois@ibm.net>
1298 filetime_from_time(PFILETIME pFileTime, time_t Time)
1300 struct tm *pTM = gmtime(&Time);
1301 SYSTEMTIME SystemTime;
1306 SystemTime.wYear = pTM->tm_year + 1900;
1307 SystemTime.wMonth = pTM->tm_mon + 1;
1308 SystemTime.wDay = pTM->tm_mday;
1309 SystemTime.wHour = pTM->tm_hour;
1310 SystemTime.wMinute = pTM->tm_min;
1311 SystemTime.wSecond = pTM->tm_sec;
1312 SystemTime.wMilliseconds = 0;
1314 return SystemTimeToFileTime(&SystemTime, pFileTime);
1318 win32_utime(const char *filename, struct utimbuf *times)
1324 struct utimbuf TimeBuffer;
1325 WCHAR wbuffer[MAX_PATH];
1331 A2WHELPER(filename, wbuffer, sizeof(wbuffer));
1332 rc = _wutime(wbuffer, (struct _utimbuf*)times);
1335 rc = utime(filename, times);
1337 /* EACCES: path specifies directory or readonly file */
1338 if (rc == 0 || errno != EACCES /* || !IsWinNT() */)
1341 if (times == NULL) {
1342 times = &TimeBuffer;
1343 time(×->actime);
1344 times->modtime = times->actime;
1347 /* This will (and should) still fail on readonly files */
1349 handle = CreateFileW(wbuffer, GENERIC_READ | GENERIC_WRITE,
1350 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1351 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1354 handle = CreateFileA(filename, GENERIC_READ | GENERIC_WRITE,
1355 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1356 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1358 if (handle == INVALID_HANDLE_VALUE)
1361 if (GetFileTime(handle, &ftCreate, &ftAccess, &ftWrite) &&
1362 filetime_from_time(&ftAccess, times->actime) &&
1363 filetime_from_time(&ftWrite, times->modtime) &&
1364 SetFileTime(handle, &ftCreate, &ftAccess, &ftWrite))
1369 CloseHandle(handle);
1374 win32_uname(struct utsname *name)
1376 struct hostent *hep;
1377 STRLEN nodemax = sizeof(name->nodename)-1;
1378 OSVERSIONINFO osver;
1380 memset(&osver, 0, sizeof(OSVERSIONINFO));
1381 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1382 if (GetVersionEx(&osver)) {
1384 switch (osver.dwPlatformId) {
1385 case VER_PLATFORM_WIN32_WINDOWS:
1386 strcpy(name->sysname, "Windows");
1388 case VER_PLATFORM_WIN32_NT:
1389 strcpy(name->sysname, "Windows NT");
1391 case VER_PLATFORM_WIN32s:
1392 strcpy(name->sysname, "Win32s");
1395 strcpy(name->sysname, "Win32 Unknown");
1400 sprintf(name->release, "%d.%d",
1401 osver.dwMajorVersion, osver.dwMinorVersion);
1404 sprintf(name->version, "Build %d",
1405 osver.dwPlatformId == VER_PLATFORM_WIN32_NT
1406 ? osver.dwBuildNumber : (osver.dwBuildNumber & 0xffff));
1407 if (osver.szCSDVersion[0]) {
1408 char *buf = name->version + strlen(name->version);
1409 sprintf(buf, " (%s)", osver.szCSDVersion);
1413 *name->sysname = '\0';
1414 *name->version = '\0';
1415 *name->release = '\0';
1419 hep = win32_gethostbyname("localhost");
1421 STRLEN len = strlen(hep->h_name);
1422 if (len <= nodemax) {
1423 strcpy(name->nodename, hep->h_name);
1426 strncpy(name->nodename, hep->h_name, nodemax);
1427 name->nodename[nodemax] = '\0';
1432 if (!GetComputerName(name->nodename, &sz))
1433 *name->nodename = '\0';
1436 /* machine (architecture) */
1440 GetSystemInfo(&info);
1442 #if defined(__BORLANDC__) || defined(__MINGW32__)
1443 switch (info.u.s.wProcessorArchitecture) {
1445 switch (info.wProcessorArchitecture) {
1447 case PROCESSOR_ARCHITECTURE_INTEL:
1448 arch = "x86"; break;
1449 case PROCESSOR_ARCHITECTURE_MIPS:
1450 arch = "mips"; break;
1451 case PROCESSOR_ARCHITECTURE_ALPHA:
1452 arch = "alpha"; break;
1453 case PROCESSOR_ARCHITECTURE_PPC:
1454 arch = "ppc"; break;
1456 arch = "unknown"; break;
1458 strcpy(name->machine, arch);
1464 win32_waitpid(int pid, int *status, int flags)
1469 return win32_wait(status);
1471 long child = find_pid(pid);
1473 HANDLE hProcess = w32_child_handles[child];
1474 DWORD waitcode = WaitForSingleObject(hProcess, INFINITE);
1475 if (waitcode != WAIT_FAILED) {
1476 if (GetExitCodeProcess(hProcess, &waitcode)) {
1477 *status = (int)((waitcode & 0xff) << 8);
1478 retval = (int)w32_child_pids[child];
1479 remove_dead_process(child);
1487 retval = cwait(status, pid, WAIT_CHILD);
1488 /* cwait() returns "correctly" on Borland */
1489 #ifndef __BORLANDC__
1495 return retval >= 0 ? pid : retval;
1499 win32_wait(int *status)
1501 /* XXX this wait emulation only knows about processes
1502 * spawned via win32_spawnvp(P_NOWAIT, ...).
1505 DWORD exitcode, waitcode;
1508 if (!w32_num_children) {
1513 /* if a child exists, wait for it to die */
1514 waitcode = WaitForMultipleObjects(w32_num_children,
1518 if (waitcode != WAIT_FAILED) {
1519 if (waitcode >= WAIT_ABANDONED_0
1520 && waitcode < WAIT_ABANDONED_0 + w32_num_children)
1521 i = waitcode - WAIT_ABANDONED_0;
1523 i = waitcode - WAIT_OBJECT_0;
1524 if (GetExitCodeProcess(w32_child_handles[i], &exitcode) ) {
1525 *status = (int)((exitcode & 0xff) << 8);
1526 retval = (int)w32_child_pids[i];
1527 remove_dead_process(i);
1533 errno = GetLastError();
1537 static UINT timerid = 0;
1539 static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
1542 KillTimer(NULL,timerid);
1547 DllExport unsigned int
1548 win32_alarm(unsigned int sec)
1551 * the 'obvious' implentation is SetTimer() with a callback
1552 * which does whatever receiving SIGALRM would do
1553 * we cannot use SIGALRM even via raise() as it is not
1554 * one of the supported codes in <signal.h>
1556 * Snag is unless something is looking at the message queue
1557 * nothing happens :-(
1562 timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
1564 Perl_croak_nocontext("Cannot set timer");
1570 KillTimer(NULL,timerid);
1577 #if defined(HAVE_DES_FCRYPT) || defined(PERL_OBJECT)
1578 #ifdef HAVE_DES_FCRYPT
1579 extern char * des_fcrypt(const char *txt, const char *salt, char *cbuf);
1583 win32_crypt(const char *txt, const char *salt)
1585 #ifdef HAVE_DES_FCRYPT
1588 return des_fcrypt(txt, salt, crypt_buffer);
1590 die("The crypt() function is unimplemented due to excessive paranoia.");
1596 #ifdef USE_FIXED_OSFHANDLE
1598 EXTERN_C int __cdecl _alloc_osfhnd(void);
1599 EXTERN_C int __cdecl _set_osfhnd(int fh, long value);
1600 EXTERN_C void __cdecl _lock_fhandle(int);
1601 EXTERN_C void __cdecl _unlock_fhandle(int);
1602 EXTERN_C void __cdecl _unlock(int);
1604 #if (_MSC_VER >= 1000)
1606 long osfhnd; /* underlying OS file HANDLE */
1607 char osfile; /* attributes of file (e.g., open in text mode?) */
1608 char pipech; /* one char buffer for handles opened on pipes */
1609 #if defined (_MT) && !defined (DLL_FOR_WIN32S)
1611 CRITICAL_SECTION lock;
1612 #endif /* defined (_MT) && !defined (DLL_FOR_WIN32S) */
1615 EXTERN_C ioinfo * __pioinfo[];
1617 #define IOINFO_L2E 5
1618 #define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
1619 #define _pioinfo(i) (__pioinfo[i >> IOINFO_L2E] + (i & (IOINFO_ARRAY_ELTS - 1)))
1620 #define _osfile(i) (_pioinfo(i)->osfile)
1622 #else /* (_MSC_VER >= 1000) */
1623 extern char _osfile[];
1624 #endif /* (_MSC_VER >= 1000) */
1626 #define FOPEN 0x01 /* file handle open */
1627 #define FAPPEND 0x20 /* file handle opened O_APPEND */
1628 #define FDEV 0x40 /* file handle refers to device */
1629 #define FTEXT 0x80 /* file handle is in text mode */
1631 #define _STREAM_LOCKS 26 /* Table of stream locks */
1632 #define _LAST_STREAM_LOCK (_STREAM_LOCKS+_NSTREAM_-1) /* Last stream lock */
1633 #define _FH_LOCKS (_LAST_STREAM_LOCK+1) /* Table of fh locks */
1636 *int my_open_osfhandle(long osfhandle, int flags) - open C Runtime file handle
1639 * This function allocates a free C Runtime file handle and associates
1640 * it with the Win32 HANDLE specified by the first parameter. This is a
1641 * temperary fix for WIN95's brain damage GetFileType() error on socket
1642 * we just bypass that call for socket
1645 * long osfhandle - Win32 HANDLE to associate with C Runtime file handle.
1646 * int flags - flags to associate with C Runtime file handle.
1649 * returns index of entry in fh, if successful
1650 * return -1, if no free entry is found
1654 *******************************************************************************/
1657 my_open_osfhandle(long osfhandle, int flags)
1660 char fileflags; /* _osfile flags */
1662 /* copy relevant flags from second parameter */
1665 if (flags & O_APPEND)
1666 fileflags |= FAPPEND;
1671 /* attempt to allocate a C Runtime file handle */
1672 if ((fh = _alloc_osfhnd()) == -1) {
1673 errno = EMFILE; /* too many open files */
1674 _doserrno = 0L; /* not an OS error */
1675 return -1; /* return error to caller */
1678 /* the file is open. now, set the info in _osfhnd array */
1679 _set_osfhnd(fh, osfhandle);
1681 fileflags |= FOPEN; /* mark as open */
1683 #if (_MSC_VER >= 1000)
1684 _osfile(fh) = fileflags; /* set osfile entry */
1685 _unlock_fhandle(fh);
1687 _osfile[fh] = fileflags; /* set osfile entry */
1688 _unlock(fh+_FH_LOCKS); /* unlock handle */
1691 return fh; /* return handle */
1694 #define _open_osfhandle my_open_osfhandle
1695 #endif /* USE_FIXED_OSFHANDLE */
1697 /* simulate flock by locking a range on the file */
1699 #define LK_ERR(f,i) ((f) ? (i = 0) : (errno = GetLastError()))
1700 #define LK_LEN 0xffff0000
1703 win32_flock(int fd, int oper)
1711 Perl_croak_nocontext("flock() unimplemented on this platform");
1714 fh = (HANDLE)_get_osfhandle(fd);
1715 memset(&o, 0, sizeof(o));
1718 case LOCK_SH: /* shared lock */
1719 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
1721 case LOCK_EX: /* exclusive lock */
1722 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
1724 case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
1725 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
1727 case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
1728 LK_ERR(LockFileEx(fh,
1729 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
1730 0, LK_LEN, 0, &o),i);
1732 case LOCK_UN: /* unlock lock */
1733 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, 0, &o),i);
1735 default: /* unknown */
1746 * redirected io subsystem for all XS modules
1759 return (&(_environ));
1762 /* the rest are the remapped stdio routines */
1782 win32_ferror(FILE *fp)
1784 return (ferror(fp));
1789 win32_feof(FILE *fp)
1795 * Since the errors returned by the socket error function
1796 * WSAGetLastError() are not known by the library routine strerror
1797 * we have to roll our own.
1801 win32_strerror(int e)
1803 #ifndef __BORLANDC__ /* Borland intolerance */
1804 extern int sys_nerr;
1808 if (e < 0 || e > sys_nerr) {
1813 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
1814 strerror_buffer, sizeof(strerror_buffer), NULL) == 0)
1815 strcpy(strerror_buffer, "Unknown Error");
1817 return strerror_buffer;
1823 win32_str_os_error(pTHX_ void *sv, DWORD dwErr)
1827 dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
1828 |FORMAT_MESSAGE_IGNORE_INSERTS
1829 |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
1830 dwErr, 0, (char *)&sMsg, 1, NULL);
1832 while (0 < dwLen && isSPACE(sMsg[--dwLen]))
1834 if ('.' != sMsg[dwLen])
1839 sMsg = (char*)LocalAlloc(0, 64/**sizeof(TCHAR)*/);
1841 dwLen = sprintf(sMsg,
1842 "Unknown error #0x%lX (lookup 0x%lX)",
1843 dwErr, GetLastError());
1847 sv_setpvn((SV*)sv, sMsg, dwLen);
1854 win32_fprintf(FILE *fp, const char *format, ...)
1857 va_start(marker, format); /* Initialize variable arguments. */
1859 return (vfprintf(fp, format, marker));
1863 win32_printf(const char *format, ...)
1866 va_start(marker, format); /* Initialize variable arguments. */
1868 return (vprintf(format, marker));
1872 win32_vfprintf(FILE *fp, const char *format, va_list args)
1874 return (vfprintf(fp, format, args));
1878 win32_vprintf(const char *format, va_list args)
1880 return (vprintf(format, args));
1884 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
1886 return fread(buf, size, count, fp);
1890 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
1892 return fwrite(buf, size, count, fp);
1895 #define MODE_SIZE 10
1898 win32_fopen(const char *filename, const char *mode)
1900 WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH];
1901 if (stricmp(filename, "/dev/null")==0)
1907 A2WHELPER(mode, wMode, sizeof(wMode));
1908 A2WHELPER(filename, wBuffer, sizeof(wBuffer));
1909 return _wfopen(wBuffer, wMode);
1911 return fopen(filename, mode);
1914 #ifndef USE_SOCKETS_AS_HANDLES
1916 #define fdopen my_fdopen
1920 win32_fdopen(int handle, const char *mode)
1922 WCHAR wMode[MODE_SIZE];
1926 A2WHELPER(mode, wMode, sizeof(wMode));
1927 return _wfdopen(handle, wMode);
1929 return fdopen(handle, (char *) mode);
1933 win32_freopen(const char *path, const char *mode, FILE *stream)
1935 WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH];
1937 if (stricmp(path, "/dev/null")==0)
1942 A2WHELPER(mode, wMode, sizeof(wMode));
1943 A2WHELPER(path, wBuffer, sizeof(wBuffer));
1944 return _wfreopen(wBuffer, wMode, stream);
1946 return freopen(path, mode, stream);
1950 win32_fclose(FILE *pf)
1952 return my_fclose(pf); /* defined in win32sck.c */
1956 win32_fputs(const char *s,FILE *pf)
1958 return fputs(s, pf);
1962 win32_fputc(int c,FILE *pf)
1968 win32_ungetc(int c,FILE *pf)
1970 return ungetc(c,pf);
1974 win32_getc(FILE *pf)
1980 win32_fileno(FILE *pf)
1986 win32_clearerr(FILE *pf)
1993 win32_fflush(FILE *pf)
1999 win32_ftell(FILE *pf)
2005 win32_fseek(FILE *pf,long offset,int origin)
2007 return fseek(pf, offset, origin);
2011 win32_fgetpos(FILE *pf,fpos_t *p)
2013 return fgetpos(pf, p);
2017 win32_fsetpos(FILE *pf,const fpos_t *p)
2019 return fsetpos(pf, p);
2023 win32_rewind(FILE *pf)
2043 win32_fstat(int fd,struct stat *sbufptr)
2045 return fstat(fd,sbufptr);
2049 win32_pipe(int *pfd, unsigned int size, int mode)
2051 return _pipe(pfd, size, mode);
2055 * a popen() clone that respects PERL5SHELL
2059 win32_popen(const char *command, const char *mode)
2061 #ifdef USE_RTL_POPEN
2062 return _popen(command, mode);
2070 /* establish which ends read and write */
2071 if (strchr(mode,'w')) {
2072 stdfd = 0; /* stdin */
2076 else if (strchr(mode,'r')) {
2077 stdfd = 1; /* stdout */
2084 /* set the correct mode */
2085 if (strchr(mode,'b'))
2087 else if (strchr(mode,'t'))
2090 ourmode = _fmode & (O_TEXT | O_BINARY);
2092 /* the child doesn't inherit handles */
2093 ourmode |= O_NOINHERIT;
2095 if (win32_pipe( p, 512, ourmode) == -1)
2098 /* save current stdfd */
2099 if ((oldfd = win32_dup(stdfd)) == -1)
2102 /* make stdfd go to child end of pipe (implicitly closes stdfd) */
2103 /* stdfd will be inherited by the child */
2104 if (win32_dup2(p[child], stdfd) == -1)
2107 /* close the child end in parent */
2108 win32_close(p[child]);
2110 /* start the child */
2114 if ((childpid = do_spawn_nowait(aTHX_ (char*)command)) == -1)
2117 /* revert stdfd to whatever it was before */
2118 if (win32_dup2(oldfd, stdfd) == -1)
2121 /* close saved handle */
2124 sv_setiv(*av_fetch(w32_fdpid, p[parent], TRUE), childpid);
2126 /* set process id so that it can be returned by perl's open() */
2127 PL_forkprocess = childpid;
2130 /* we have an fd, return a file stream */
2131 return (win32_fdopen(p[parent], (char *)mode));
2134 /* we don't need to check for errors here */
2138 win32_dup2(oldfd, stdfd);
2143 #endif /* USE_RTL_POPEN */
2151 win32_pclose(FILE *pf)
2153 #ifdef USE_RTL_POPEN
2158 int childpid, status;
2161 sv = *av_fetch(w32_fdpid, win32_fileno(pf), TRUE);
2163 childpid = SvIVX(sv);
2175 if (win32_waitpid(childpid, &status, 0) == -1)
2180 #endif /* USE_RTL_POPEN */
2184 win32_rename(const char *oname, const char *newname)
2186 WCHAR wOldName[MAX_PATH];
2187 WCHAR wNewName[MAX_PATH];
2189 /* XXX despite what the documentation says about MoveFileEx(),
2190 * it doesn't work under Windows95!
2196 A2WHELPER(oname, wOldName, sizeof(wOldName));
2197 A2WHELPER(newname, wNewName, sizeof(wNewName));
2198 bResult = MoveFileExW(wOldName,wNewName,
2199 MOVEFILE_COPY_ALLOWED|MOVEFILE_REPLACE_EXISTING);
2202 bResult = MoveFileExA(oname,newname,
2203 MOVEFILE_COPY_ALLOWED|MOVEFILE_REPLACE_EXISTING);
2206 DWORD err = GetLastError();
2208 case ERROR_BAD_NET_NAME:
2209 case ERROR_BAD_NETPATH:
2210 case ERROR_BAD_PATHNAME:
2211 case ERROR_FILE_NOT_FOUND:
2212 case ERROR_FILENAME_EXCED_RANGE:
2213 case ERROR_INVALID_DRIVE:
2214 case ERROR_NO_MORE_FILES:
2215 case ERROR_PATH_NOT_FOUND:
2228 char tmpname[MAX_PATH+1];
2229 char dname[MAX_PATH+1];
2230 char *endname = Nullch;
2232 DWORD from_attr, to_attr;
2234 /* if oname doesn't exist, do nothing */
2235 from_attr = GetFileAttributes(oname);
2236 if (from_attr == 0xFFFFFFFF) {
2241 /* if newname exists, rename it to a temporary name so that we
2242 * don't delete it in case oname happens to be the same file
2243 * (but perhaps accessed via a different path)
2245 to_attr = GetFileAttributes(newname);
2246 if (to_attr != 0xFFFFFFFF) {
2247 /* if newname is a directory, we fail
2248 * XXX could overcome this with yet more convoluted logic */
2249 if (to_attr & FILE_ATTRIBUTE_DIRECTORY) {
2253 tmplen = strlen(newname);
2254 strcpy(tmpname,newname);
2255 endname = tmpname+tmplen;
2256 for (; endname > tmpname ; --endname) {
2257 if (*endname == '/' || *endname == '\\') {
2262 if (endname > tmpname)
2263 endname = strcpy(dname,tmpname);
2267 /* get a temporary filename in same directory
2268 * XXX is this really the best we can do? */
2269 if (!GetTempFileName((LPCTSTR)endname, "plr", 0, tmpname)) {
2273 DeleteFile(tmpname);
2275 retval = rename(newname, tmpname);
2282 /* rename oname to newname */
2283 retval = rename(oname, newname);
2285 /* if we created a temporary file before ... */
2286 if (endname != Nullch) {
2287 /* ...and rename succeeded, delete temporary file/directory */
2289 DeleteFile(tmpname);
2290 /* else restore it to what it was */
2292 (void)rename(tmpname, newname);
2299 win32_setmode(int fd, int mode)
2301 return setmode(fd, mode);
2305 win32_lseek(int fd, long offset, int origin)
2307 return lseek(fd, offset, origin);
2317 win32_open(const char *path, int flag, ...)
2321 WCHAR wBuffer[MAX_PATH];
2325 pmode = va_arg(ap, int);
2328 if (stricmp(path, "/dev/null")==0)
2333 A2WHELPER(path, wBuffer, sizeof(wBuffer));
2334 return _wopen(wBuffer, flag, pmode);
2336 return open(path,flag,pmode);
2358 win32_dup2(int fd1,int fd2)
2360 return dup2(fd1,fd2);
2364 win32_read(int fd, void *buf, unsigned int cnt)
2366 return read(fd, buf, cnt);
2370 win32_write(int fd, const void *buf, unsigned int cnt)
2372 return write(fd, buf, cnt);
2376 win32_mkdir(const char *dir, int mode)
2378 return mkdir(dir); /* just ignore mode */
2382 win32_rmdir(const char *dir)
2388 win32_chdir(const char *dir)
2394 create_command_line(const char* command, const char * const *args)
2397 char *cmd, *ptr, *arg;
2398 STRLEN len = strlen(command) + 1;
2401 for (index = 0; (ptr = (char*)args[index]) != NULL; ++index)
2402 len += strlen(ptr) + 1;
2404 New(1310, cmd, len, char);
2406 strcpy(ptr, command);
2408 for (index = 0; (arg = (char*)args[index]) != NULL; ++index) {
2418 qualified_path(const char *cmd)
2421 char *fullcmd, *curfullcmd;
2428 fullcmd = (char*)cmd;
2430 if (*fullcmd == '/' || *fullcmd == '\\')
2437 pathstr = win32_getenv("PATH");
2438 New(0, fullcmd, MAX_PATH+1, char);
2439 curfullcmd = fullcmd;
2444 /* start by appending the name to the current prefix */
2445 strcpy(curfullcmd, cmd);
2446 curfullcmd += cmdlen;
2448 /* if it doesn't end with '.', or has no extension, try adding
2449 * a trailing .exe first */
2450 if (cmd[cmdlen-1] != '.'
2451 && (cmdlen < 4 || cmd[cmdlen-4] != '.'))
2453 strcpy(curfullcmd, ".exe");
2454 res = GetFileAttributes(fullcmd);
2455 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
2460 /* that failed, try the bare name */
2461 res = GetFileAttributes(fullcmd);
2462 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
2465 /* quit if no other path exists, or if cmd already has path */
2466 if (!pathstr || !*pathstr || has_slash)
2469 /* skip leading semis */
2470 while (*pathstr == ';')
2473 /* build a new prefix from scratch */
2474 curfullcmd = fullcmd;
2475 while (*pathstr && *pathstr != ';') {
2476 if (*pathstr == '"') { /* foo;"baz;etc";bar */
2477 pathstr++; /* skip initial '"' */
2478 while (*pathstr && *pathstr != '"') {
2479 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
2480 *curfullcmd++ = *pathstr;
2484 pathstr++; /* skip trailing '"' */
2487 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
2488 *curfullcmd++ = *pathstr;
2493 pathstr++; /* skip trailing semi */
2494 if (curfullcmd > fullcmd /* append a dir separator */
2495 && curfullcmd[-1] != '/' && curfullcmd[-1] != '\\')
2497 *curfullcmd++ = '\\';
2505 /* XXX this needs to be made more compatible with the spawnvp()
2506 * provided by the various RTLs. In particular, searching for
2507 * *.{com,bat,cmd} files (as done by the RTLs) is unimplemented.
2508 * This doesn't significantly affect perl itself, because we
2509 * always invoke things using PERL5SHELL if a direct attempt to
2510 * spawn the executable fails.
2512 * XXX splitting and rejoining the commandline between do_aspawn()
2513 * and win32_spawnvp() could also be avoided.
2517 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
2519 #ifdef USE_RTL_SPAWNVP
2520 return spawnvp(mode, cmdname, (char * const *)argv);
2523 STARTUPINFO StartupInfo;
2524 PROCESS_INFORMATION ProcessInformation;
2528 char *cmd = create_command_line(cmdname, strcmp(cmdname, argv[0]) == 0
2530 char *fullcmd = Nullch;
2533 case P_NOWAIT: /* asynch + remember result */
2534 if (w32_num_children >= MAXIMUM_WAIT_OBJECTS) {
2540 case P_WAIT: /* synchronous execution */
2542 default: /* invalid mode */
2547 memset(&StartupInfo,0,sizeof(StartupInfo));
2548 StartupInfo.cb = sizeof(StartupInfo);
2549 StartupInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
2550 StartupInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
2551 StartupInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
2552 if (StartupInfo.hStdInput != INVALID_HANDLE_VALUE &&
2553 StartupInfo.hStdOutput != INVALID_HANDLE_VALUE &&
2554 StartupInfo.hStdError != INVALID_HANDLE_VALUE)
2556 StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
2559 create |= CREATE_NEW_CONSOLE;
2563 StartupInfo.dwFlags |= STARTF_USESHOWWINDOW;
2564 StartupInfo.wShowWindow = SW_HIDE;
2568 if (!CreateProcess(cmdname, /* search PATH to find executable */
2569 cmd, /* executable, and its arguments */
2570 NULL, /* process attributes */
2571 NULL, /* thread attributes */
2572 TRUE, /* inherit handles */
2573 create, /* creation flags */
2574 NULL, /* inherit environment */
2575 NULL, /* inherit cwd */
2577 &ProcessInformation))
2579 /* initial NULL argument to CreateProcess() does a PATH
2580 * search, but it always first looks in the directory
2581 * where the current process was started, which behavior
2582 * is undesirable for backward compatibility. So we
2583 * jump through our own hoops by picking out the path
2584 * we really want it to use. */
2586 fullcmd = qualified_path(cmdname);
2597 if (mode == P_NOWAIT) {
2598 /* asynchronous spawn -- store handle, return PID */
2599 w32_child_handles[w32_num_children] = ProcessInformation.hProcess;
2600 ret = w32_child_pids[w32_num_children] = ProcessInformation.dwProcessId;
2604 WaitForSingleObject(ProcessInformation.hProcess, INFINITE);
2605 GetExitCodeProcess(ProcessInformation.hProcess, &ret);
2606 CloseHandle(ProcessInformation.hProcess);
2609 CloseHandle(ProcessInformation.hThread);
2618 win32_execv(const char *cmdname, const char *const *argv)
2620 return execv(cmdname, (char *const *)argv);
2624 win32_execvp(const char *cmdname, const char *const *argv)
2626 return execvp(cmdname, (char *const *)argv);
2630 win32_perror(const char *str)
2636 win32_setbuf(FILE *pf, char *buf)
2642 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
2644 return setvbuf(pf, buf, type, size);
2648 win32_flushall(void)
2654 win32_fcloseall(void)
2660 win32_fgets(char *s, int n, FILE *pf)
2662 return fgets(s, n, pf);
2672 win32_fgetc(FILE *pf)
2678 win32_putc(int c, FILE *pf)
2684 win32_puts(const char *s)
2696 win32_putchar(int c)
2703 #ifndef USE_PERL_SBRK
2705 static char *committed = NULL;
2706 static char *base = NULL;
2707 static char *reserved = NULL;
2708 static char *brk = NULL;
2709 static DWORD pagesize = 0;
2710 static DWORD allocsize = 0;
2718 GetSystemInfo(&info);
2719 /* Pretend page size is larger so we don't perpetually
2720 * call the OS to commit just one page ...
2722 pagesize = info.dwPageSize << 3;
2723 allocsize = info.dwAllocationGranularity;
2725 /* This scheme fails eventually if request for contiguous
2726 * block is denied so reserve big blocks - this is only
2727 * address space not memory ...
2729 if (brk+need >= reserved)
2731 DWORD size = 64*1024*1024;
2733 if (committed && reserved && committed < reserved)
2735 /* Commit last of previous chunk cannot span allocations */
2736 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
2738 committed = reserved;
2740 /* Reserve some (more) space
2741 * Note this is a little sneaky, 1st call passes NULL as reserved
2742 * so lets system choose where we start, subsequent calls pass
2743 * the old end address so ask for a contiguous block
2745 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
2748 reserved = addr+size;
2763 if (brk > committed)
2765 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
2766 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
2781 win32_malloc(size_t size)
2783 return malloc(size);
2787 win32_calloc(size_t numitems, size_t size)
2789 return calloc(numitems,size);
2793 win32_realloc(void *block, size_t size)
2795 return realloc(block,size);
2799 win32_free(void *block)
2806 win32_open_osfhandle(long handle, int flags)
2808 return _open_osfhandle(handle, flags);
2812 win32_get_osfhandle(int fd)
2814 return _get_osfhandle(fd);
2818 win32_dynaload(aTHX_ const char*filename)
2823 WCHAR wfilename[MAX_PATH];
2824 A2WHELPER(filename, wfilename, sizeof(wfilename));
2825 hModule = LoadLibraryExW(wfilename, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
2828 hModule = LoadLibraryExA(filename, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
2834 win32_add_host(char *nameId, void *data)
2837 * This must be called before the script is parsed,
2838 * therefore no locking of threads is needed
2842 struct host_link *link;
2843 New(1314, link, 1, struct host_link);
2844 link->host_data = data;
2845 link->nameId = nameId;
2846 link->next = w32_host_link;
2847 w32_host_link = link;
2852 win32_get_host_data(char *nameId)
2856 struct host_link *link = w32_host_link;
2858 if(strEQ(link->nameId, nameId))
2859 return link->host_data;
2873 SV *sv = sv_newmortal();
2874 /* Make one call with zero size - return value is required size */
2875 DWORD len = GetCurrentDirectory((DWORD)0,NULL);
2876 SvUPGRADE(sv,SVt_PV);
2878 SvCUR(sv) = GetCurrentDirectory((DWORD) SvLEN(sv), SvPVX(sv));
2881 * then it worked, set PV valid,
2882 * else leave it 'undef'
2898 Perl_croak(aTHX_ "usage: Win32::SetCurrentDirectory($cwd)");
2899 if (SetCurrentDirectory(SvPV_nolen(ST(0))))
2906 XS(w32_GetNextAvailDrive)
2910 char root[] = "_:\\";
2915 if (GetDriveType(root) == 1) {
2924 XS(w32_GetLastError)
2928 XSRETURN_IV(GetLastError());
2932 XS(w32_SetLastError)
2936 Perl_croak(aTHX_ "usage: Win32::SetLastError($error)");
2937 SetLastError(SvIV(ST(0)));
2945 char *name = getlogin_buffer;
2946 DWORD size = sizeof(getlogin_buffer);
2948 if (GetUserName(name,&size)) {
2949 /* size includes NULL */
2950 ST(0) = sv_2mortal(newSVpvn(name,size-1));
2960 char name[MAX_COMPUTERNAME_LENGTH+1];
2961 DWORD size = sizeof(name);
2963 if (GetComputerName(name,&size)) {
2964 /* size does NOT include NULL :-( */
2965 ST(0) = sv_2mortal(newSVpvn(name,size));
2976 #ifndef HAS_NETWKSTAGETINFO
2977 /* mingw32 (and Win95) don't have NetWksta*(), so do it the old way */
2979 DWORD size = sizeof(name);
2981 if (GetUserName(name,&size)) {
2983 DWORD sidlen = sizeof(sid);
2985 DWORD dnamelen = sizeof(dname);
2987 if (LookupAccountName(NULL, name, (PSID)&sid, &sidlen,
2988 dname, &dnamelen, &snu)) {
2989 XSRETURN_PV(dname); /* all that for this */
2993 /* this way is more reliable, in case user has a local account.
2994 * XXX need dynamic binding of netapi32.dll symbols or this will fail on
2995 * Win95. Probably makes more sense to move it into libwin32. */
2997 DWORD dnamelen = sizeof(dname);
2998 PWKSTA_INFO_100 pwi;
3000 if (NERR_Success == NetWkstaGetInfo(NULL, 100, (LPBYTE*)&pwi)) {
3001 if (pwi->wki100_langroup && *(pwi->wki100_langroup)) {
3002 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_langroup,
3003 -1, (LPSTR)dname, dnamelen, NULL, NULL);
3006 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_computername,
3007 -1, (LPSTR)dname, dnamelen, NULL, NULL);
3009 NetApiBufferFree(pwi);
3021 DWORD flags, filecomplen;
3022 if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
3023 &flags, fsname, sizeof(fsname))) {
3024 if (GIMME_V == G_ARRAY) {
3025 XPUSHs(sv_2mortal(newSVpvn(fsname,strlen(fsname))));
3026 XPUSHs(sv_2mortal(newSViv(flags)));
3027 XPUSHs(sv_2mortal(newSViv(filecomplen)));
3032 XSRETURN_PV(fsname);
3038 XS(w32_GetOSVersion)
3041 OSVERSIONINFO osver;
3043 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
3044 if (GetVersionEx(&osver)) {
3045 XPUSHs(newSVpvn(osver.szCSDVersion, strlen(osver.szCSDVersion)));
3046 XPUSHs(newSViv(osver.dwMajorVersion));
3047 XPUSHs(newSViv(osver.dwMinorVersion));
3048 XPUSHs(newSViv(osver.dwBuildNumber));
3049 XPUSHs(newSViv(osver.dwPlatformId));
3061 XSRETURN_IV(IsWinNT());
3069 XSRETURN_IV(IsWin95());
3073 XS(w32_FormatMessage)
3080 Perl_croak(aTHX_ "usage: Win32::FormatMessage($errno)");
3082 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
3083 &source, SvIV(ST(0)), 0,
3084 msgbuf, sizeof(msgbuf)-1, NULL))
3085 XSRETURN_PV(msgbuf);
3095 PROCESS_INFORMATION stProcInfo;
3096 STARTUPINFO stStartInfo;
3097 BOOL bSuccess = FALSE;
3100 Perl_croak(aTHX_ "usage: Win32::Spawn($cmdName, $args, $PID)");
3102 cmd = SvPV_nolen(ST(0));
3103 args = SvPV_nolen(ST(1));
3105 memset(&stStartInfo, 0, sizeof(stStartInfo)); /* Clear the block */
3106 stStartInfo.cb = sizeof(stStartInfo); /* Set the structure size */
3107 stStartInfo.dwFlags = STARTF_USESHOWWINDOW; /* Enable wShowWindow control */
3108 stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE; /* Start min (normal) */
3111 cmd, /* Image path */
3112 args, /* Arguments for command line */
3113 NULL, /* Default process security */
3114 NULL, /* Default thread security */
3115 FALSE, /* Must be TRUE to use std handles */
3116 NORMAL_PRIORITY_CLASS, /* No special scheduling */
3117 NULL, /* Inherit our environment block */
3118 NULL, /* Inherit our currrent directory */
3119 &stStartInfo, /* -> Startup info */
3120 &stProcInfo)) /* <- Process info (if OK) */
3122 CloseHandle(stProcInfo.hThread);/* library source code does this. */
3123 sv_setiv(ST(2), stProcInfo.dwProcessId);
3126 XSRETURN_IV(bSuccess);
3130 XS(w32_GetTickCount)
3133 DWORD msec = GetTickCount();
3141 XS(w32_GetShortPathName)
3148 Perl_croak(aTHX_ "usage: Win32::GetShortPathName($longPathName)");
3150 shortpath = sv_mortalcopy(ST(0));
3151 SvUPGRADE(shortpath, SVt_PV);
3152 /* src == target is allowed */
3154 len = GetShortPathName(SvPVX(shortpath),
3157 } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
3159 SvCUR_set(shortpath,len);
3167 XS(w32_GetFullPathName)
3176 Perl_croak(aTHX_ "usage: Win32::GetFullPathName($filename)");
3179 fullpath = sv_mortalcopy(filename);
3180 SvUPGRADE(fullpath, SVt_PV);
3182 len = GetFullPathName(SvPVX(filename),
3186 } while (len >= SvLEN(fullpath) && sv_grow(fullpath,len+1));
3188 if (GIMME_V == G_ARRAY) {
3190 XST_mPV(1,filepart);
3191 len = filepart - SvPVX(fullpath);
3194 SvCUR_set(fullpath,len);
3202 XS(w32_GetLongPathName)
3206 char tmpbuf[MAX_PATH+1];
3211 Perl_croak(aTHX_ "usage: Win32::GetLongPathName($pathname)");
3214 pathstr = SvPV(path,len);
3215 strcpy(tmpbuf, pathstr);
3216 pathstr = win32_longpath(tmpbuf);
3218 ST(0) = sv_2mortal(newSVpvn(pathstr, strlen(pathstr)));
3229 Perl_croak(aTHX_ "usage: Win32::Sleep($milliseconds)");
3239 Perl_croak(aTHX_ "usage: Win32::CopyFile($from, $to, $overwrite)");
3240 if (CopyFile(SvPV_nolen(ST(0)), SvPV_nolen(ST(1)), !SvTRUE(ST(2))))
3246 Perl_init_os_extras(pTHX)
3248 char *file = __FILE__;
3252 w32_perlshell_tokens = Nullch;
3253 w32_perlshell_items = -1;
3254 w32_fdpid = newAV(); /* XXX needs to be in Perl_win32_init()? */
3255 New(1313, w32_children, 1, child_tab);
3256 w32_num_children = 0;
3258 /* these names are Activeware compatible */
3259 newXS("Win32::GetCwd", w32_GetCwd, file);
3260 newXS("Win32::SetCwd", w32_SetCwd, file);
3261 newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
3262 newXS("Win32::GetLastError", w32_GetLastError, file);
3263 newXS("Win32::SetLastError", w32_SetLastError, file);
3264 newXS("Win32::LoginName", w32_LoginName, file);
3265 newXS("Win32::NodeName", w32_NodeName, file);
3266 newXS("Win32::DomainName", w32_DomainName, file);
3267 newXS("Win32::FsType", w32_FsType, file);
3268 newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
3269 newXS("Win32::IsWinNT", w32_IsWinNT, file);
3270 newXS("Win32::IsWin95", w32_IsWin95, file);
3271 newXS("Win32::FormatMessage", w32_FormatMessage, file);
3272 newXS("Win32::Spawn", w32_Spawn, file);
3273 newXS("Win32::GetTickCount", w32_GetTickCount, file);
3274 newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
3275 newXS("Win32::GetFullPathName", w32_GetFullPathName, file);
3276 newXS("Win32::GetLongPathName", w32_GetLongPathName, file);
3277 newXS("Win32::CopyFile", w32_CopyFile, file);
3278 newXS("Win32::Sleep", w32_Sleep, file);
3280 /* XXX Bloat Alert! The following Activeware preloads really
3281 * ought to be part of Win32::Sys::*, so they're not included
3284 /* LookupAccountName
3286 * InitiateSystemShutdown
3287 * AbortSystemShutdown
3288 * ExpandEnvrironmentStrings
3293 Perl_win32_init(int *argcp, char ***argvp)
3295 /* Disable floating point errors, Perl will trap the ones we
3296 * care about. VC++ RTL defaults to switching these off
3297 * already, but the Borland RTL doesn't. Since we don't
3298 * want to be at the vendor's whim on the default, we set
3299 * it explicitly here.
3301 #if !defined(_ALPHA_) && !defined(__GNUC__)
3302 _control87(MCW_EM, MCW_EM);
3307 #ifdef USE_BINMODE_SCRIPTS
3310 win32_strip_return(SV *sv)
3312 char *s = SvPVX(sv);
3313 char *e = s+SvCUR(sv);
3317 if (*s == '\r' && s[1] == '\n')
3327 SvCUR_set(sv,d-SvPVX(sv));