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)
44 extern CPerlObj* pPerl;
51 /* assert.h conflicts with #define of assert in perl.h */
58 #if defined(_MSC_VER) || defined(__MINGW32__)
59 #include <sys/utime.h>
65 /* Mingw32 defaults to globing command line
66 * So we turn it off like this:
73 #define EXECF_SPAWN_NOWAIT 3
75 #if defined(PERL_OBJECT)
76 #undef win32_get_privlib
77 #define win32_get_privlib g_win32_get_privlib
78 #undef win32_get_sitelib
79 #define win32_get_sitelib g_win32_get_sitelib
81 #define do_aspawn g_do_aspawn
83 #define do_spawn g_do_spawn
85 #define do_exec g_do_exec
87 #define getlogin g_getlogin
90 static DWORD os_id(void);
91 static void get_shell(void);
92 static long tokenize(char *str, char **dest, char ***destv);
93 int do_spawn2(pTHX_ char *cmd, int exectype);
94 static BOOL has_shell_metachars(char *ptr);
95 static long filetime_to_clock(PFILETIME ft);
96 static BOOL filetime_from_time(PFILETIME ft, time_t t);
97 static char * get_emd_part(char **leading, char *trailing, ...);
98 static void remove_dead_process(long deceased);
99 static long find_pid(int pid);
100 static char * qualified_path(const char *cmd);
102 HANDLE w32_perldll_handle = INVALID_HANDLE_VALUE;
103 char w32_module_name[MAX_PATH+1];
104 static DWORD w32_platform = (DWORD)-1;
107 # ifdef USE_DECLSPEC_THREAD
108 __declspec(thread) char strerror_buffer[512];
109 __declspec(thread) char getlogin_buffer[128];
110 __declspec(thread) char w32_perllib_root[MAX_PATH+1];
111 # ifdef HAVE_DES_FCRYPT
112 __declspec(thread) char crypt_buffer[30];
115 # define strerror_buffer (thr->i.Wstrerror_buffer)
116 # define getlogin_buffer (thr->i.Wgetlogin_buffer)
117 # define w32_perllib_root (thr->i.Ww32_perllib_root)
118 # define crypt_buffer (thr->i.Wcrypt_buffer)
121 static char strerror_buffer[512];
122 static char getlogin_buffer[128];
123 static char w32_perllib_root[MAX_PATH+1];
124 # ifdef HAVE_DES_FCRYPT
125 static char crypt_buffer[30];
132 return (os_id() == VER_PLATFORM_WIN32_WINDOWS);
138 return (os_id() == VER_PLATFORM_WIN32_NT);
141 /* *ptr is expected to point to valid allocated space (can't be NULL) */
143 GetRegStrFromKey(HKEY hkey, const char *lpszValueName, char** ptr, DWORD* lpDataLen)
145 /* Retrieve a REG_SZ or REG_EXPAND_SZ from the registry */
148 const char *subkey = "Software\\Perl";
152 retval = RegOpenKeyEx(hkey, subkey, 0, KEY_READ, &handle);
153 if (retval == ERROR_SUCCESS) {
154 retval = RegQueryValueEx(handle, lpszValueName, 0, &type, NULL, lpDataLen);
155 if (retval == ERROR_SUCCESS && type == REG_SZ) {
156 Renew(*ptr, *lpDataLen, char);
157 retval = RegQueryValueEx(handle, lpszValueName, 0, NULL,
158 (PBYTE)*ptr, lpDataLen);
159 if (retval == ERROR_SUCCESS)
167 /* *ptr is expected to point to valid allocated space (can't be NULL) */
169 GetRegStr(const char *lpszValueName, char** ptr, DWORD* lpDataLen)
171 char *str = GetRegStrFromKey(HKEY_CURRENT_USER, lpszValueName, ptr, lpDataLen);
173 str = GetRegStrFromKey(HKEY_LOCAL_MACHINE, lpszValueName, ptr, lpDataLen);
177 /* *prev_path is expected to point to valid allocated space (can't be NULL) */
179 get_emd_part(char **prev_path, char *trailing_path, ...)
183 char mod_name[MAX_PATH+1];
187 int oldsize, newsize;
189 va_start(ap, trailing_path);
190 strip = va_arg(ap, char *);
192 sprintf(base, "%5.3f",
193 (double)PERL_REVISION + ((double)PERL_VERSION / (double)1000));
195 if (!*w32_module_name) {
196 GetModuleFileName((HMODULE)((w32_perldll_handle == INVALID_HANDLE_VALUE)
197 ? GetModuleHandle(NULL)
198 : w32_perldll_handle),
199 w32_module_name, sizeof(w32_module_name));
201 /* try to get full path to binary (which may be mangled when perl is
202 * run from a 16-bit app) */
203 /*PerlIO_printf(PerlIO_stderr(), "Before %s\n", w32_module_name);*/
204 (void)win32_longpath(w32_module_name);
205 /*PerlIO_printf(PerlIO_stderr(), "After %s\n", w32_module_name);*/
207 /* normalize to forward slashes */
208 ptr = w32_module_name;
215 strcpy(mod_name, w32_module_name);
216 ptr = strrchr(mod_name, '/');
217 while (ptr && strip) {
218 /* look for directories to skip back */
221 ptr = strrchr(mod_name, '/');
222 if (!ptr || stricmp(ptr+1, strip) != 0) {
223 if(!(*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 */
244 newsize = strlen(mod_name) + 1;
245 oldsize = strlen(*prev_path) + 1;
246 newsize += oldsize; /* includes plus 1 for ';' */
247 Renew(*prev_path, newsize, char);
248 (*prev_path)[oldsize-1] = ';';
249 strcpy(&(*prev_path)[oldsize], mod_name);
257 win32_get_privlib(pTHX_ char *pl)
259 char *stdlib = "lib";
260 char buffer[MAX_PATH+1];
263 SV *sv = sv_2mortal(newSVpvn("",127));
265 /* $stdlib = $HKCU{"lib-$]"} || $HKLM{"lib-$]"} || $HKCU{"lib"} || $HKLM{"lib"} || ""; */
266 sprintf(buffer, "%s-%s", stdlib, pl);
268 if (!GetRegStr(buffer, path, &datalen))
269 (void)GetRegStr(stdlib, path, &datalen);
271 /* $stdlib .= ";$EMD/../../lib" */
272 (void)get_emd_part(path, stdlib, ARCHNAME, "bin", Nullch);
273 SvCUR_set(sv, strlen(*path));
274 SvLEN_set(sv, SvCUR(sv)+1);
279 win32_get_sitelib(pTHX_ char *pl)
281 char *sitelib = "sitelib";
283 char pathstr[MAX_PATH+1];
285 char **path1, *str1 = Nullch;
286 char **path2, *str2 = Nullch;
288 SV *sv1 = sv_2mortal(newSVpvn("",127));
289 SV *sv2 = sv_2mortal(newSVpvn("",127));
291 /* $HKCU{"sitelib-$]"} || $HKLM{"sitelib-$]"} . ---; */
292 sprintf(regstr, "%s-%s", sitelib, pl);
294 (void)GetRegStr(regstr, path1, &datalen);
297 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/site/$]/lib"; */
298 sprintf(pathstr, "site/%s/lib", pl);
299 str1 = get_emd_part(path1, pathstr, ARCHNAME, "bin", pl, Nullch);
300 if (!str1 && strlen(pl) == 7) {
301 /* pl may have been SUBVERSION-specific; try again without
303 sprintf(pathstr, "site/%.5s/lib", pl);
304 str1 = get_emd_part(path1, pathstr, ARCHNAME, "bin", pl, Nullch);
307 /* $HKCU{'sitelib'} || $HKLM{'sitelib'} . ---; */
309 (void)GetRegStr(sitelib, path2, &datalen);
312 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/site/lib"; */
313 str2 = get_emd_part(path2, "site/lib", ARCHNAME, "bin", pl, Nullch);
315 SvCUR_set(sv1, strlen(*path1));
316 SvLEN_set(sv1, SvCUR(sv1)+1);
317 SvCUR_set(sv2, strlen(*path2));
318 SvLEN_set(sv2, SvCUR(sv2)+1);
325 sv_catpvn(sv1, ";", 1);
333 has_shell_metachars(char *ptr)
339 * Scan string looking for redirection (< or >) or pipe
340 * characters (|) that are not in a quoted string.
341 * Shell variable interpolation (%VAR%) can also happen inside strings.
373 #if !defined(PERL_OBJECT)
374 /* since the current process environment is being updated in util.c
375 * the library functions will get the correct environment
378 Perl_my_popen(pTHX_ char *cmd, char *mode)
381 #define fixcmd(x) { \
382 char *pspace = strchr((x),' '); \
385 while (p < pspace) { \
396 PERL_FLUSHALL_FOR_CHILD;
397 return win32_popen(cmd, mode);
401 Perl_my_pclose(pTHX_ PerlIO *fp)
403 return win32_pclose(fp);
410 static OSVERSIONINFO osver;
412 if (osver.dwPlatformId != w32_platform) {
413 memset(&osver, 0, sizeof(OSVERSIONINFO));
414 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
415 GetVersionEx(&osver);
416 w32_platform = osver.dwPlatformId;
418 return (w32_platform);
421 /* Tokenize a string. Words are null-separated, and the list
422 * ends with a doubled null. Any character (except null and
423 * including backslash) may be escaped by preceding it with a
424 * backslash (the backslash will be stripped).
425 * Returns number of words in result buffer.
428 tokenize(char *str, char **dest, char ***destv)
430 char *retstart = Nullch;
431 char **retvstart = 0;
434 int slen = strlen(str);
436 register char **retv;
437 New(1307, ret, slen+2, char);
438 New(1308, retv, (slen+3)/2, char*);
446 if (*ret == '\\' && *str)
448 else if (*ret == ' ') {
464 retvstart[items] = Nullch;
476 if (!w32_perlshell_tokens) {
477 /* we don't use COMSPEC here for two reasons:
478 * 1. the same reason perl on UNIX doesn't use SHELL--rampant and
479 * uncontrolled unportability of the ensuing scripts.
480 * 2. PERL5SHELL could be set to a shell that may not be fit for
481 * interactive use (which is what most programs look in COMSPEC
484 char* defaultshell = (IsWinNT() ? "cmd.exe /x/c" : "command.com /c");
485 char *usershell = getenv("PERL5SHELL");
486 w32_perlshell_items = tokenize(usershell ? usershell : defaultshell,
487 &w32_perlshell_tokens,
493 do_aspawn(pTHX_ void *vreally, void **vmark, void **vsp)
495 SV *really = (SV*)vreally;
496 SV **mark = (SV**)vmark;
508 New(1306, argv, (sp - mark) + w32_perlshell_items + 2, char*);
510 if (SvNIOKp(*(mark+1)) && !SvPOKp(*(mark+1))) {
515 while (++mark <= sp) {
516 if (*mark && (str = SvPV_nolen(*mark)))
523 status = win32_spawnvp(flag,
524 (const char*)(really ? SvPV_nolen(really) : argv[0]),
525 (const char* const*)argv);
527 if (status < 0 && (errno == ENOEXEC || errno == ENOENT)) {
528 /* possible shell-builtin, invoke with shell */
530 sh_items = w32_perlshell_items;
532 argv[index+sh_items] = argv[index];
533 while (--sh_items >= 0)
534 argv[sh_items] = w32_perlshell_vec[sh_items];
536 status = win32_spawnvp(flag,
537 (const char*)(really ? SvPV_nolen(really) : argv[0]),
538 (const char* const*)argv);
541 if (flag != P_NOWAIT) {
544 Perl_warn(aTHX_ "Can't spawn \"%s\": %s", argv[0], strerror(errno));
549 PL_statusvalue = status;
556 do_spawn2(pTHX_ char *cmd, int exectype)
562 BOOL needToTry = TRUE;
565 /* Save an extra exec if possible. See if there are shell
566 * metacharacters in it */
567 if (!has_shell_metachars(cmd)) {
568 New(1301,argv, strlen(cmd) / 2 + 2, char*);
569 New(1302,cmd2, strlen(cmd) + 1, char);
572 for (s = cmd2; *s;) {
573 while (*s && isSPACE(*s))
577 while (*s && !isSPACE(*s))
586 status = win32_spawnvp(P_WAIT, argv[0],
587 (const char* const*)argv);
589 case EXECF_SPAWN_NOWAIT:
590 status = win32_spawnvp(P_NOWAIT, argv[0],
591 (const char* const*)argv);
594 status = win32_execvp(argv[0], (const char* const*)argv);
597 if (status != -1 || errno == 0)
607 New(1306, argv, w32_perlshell_items + 2, char*);
608 while (++i < w32_perlshell_items)
609 argv[i] = w32_perlshell_vec[i];
614 status = win32_spawnvp(P_WAIT, argv[0],
615 (const char* const*)argv);
617 case EXECF_SPAWN_NOWAIT:
618 status = win32_spawnvp(P_NOWAIT, argv[0],
619 (const char* const*)argv);
622 status = win32_execvp(argv[0], (const char* const*)argv);
628 if (exectype != EXECF_SPAWN_NOWAIT) {
631 Perl_warn(aTHX_ "Can't %s \"%s\": %s",
632 (exectype == EXECF_EXEC ? "exec" : "spawn"),
633 cmd, strerror(errno));
638 PL_statusvalue = status;
644 do_spawn(pTHX_ char *cmd)
646 return do_spawn2(aTHX_ cmd, EXECF_SPAWN);
650 do_spawn_nowait(pTHX_ char *cmd)
652 return do_spawn2(aTHX_ cmd, EXECF_SPAWN_NOWAIT);
656 Perl_do_exec(pTHX_ char *cmd)
658 do_spawn2(aTHX_ cmd, EXECF_EXEC);
662 /* The idea here is to read all the directory names into a string table
663 * (separated by nulls) and when one of the other dir functions is called
664 * return the pointer to the current file name.
667 win32_opendir(char *filename)
673 char scanname[MAX_PATH+3];
675 WIN32_FIND_DATAA aFindData;
676 WIN32_FIND_DATAW wFindData;
678 char buffer[MAX_PATH*2];
679 WCHAR wbuffer[MAX_PATH];
682 len = strlen(filename);
686 /* check to see if filename is a directory */
687 if (win32_stat(filename, &sbuf) < 0 || !S_ISDIR(sbuf.st_mode))
690 /* Get us a DIR structure */
691 Newz(1303, p, 1, DIR);
695 /* Create the search pattern */
696 strcpy(scanname, filename);
698 /* bare drive name means look in cwd for drive */
699 if (len == 2 && isALPHA(scanname[0]) && scanname[1] == ':') {
700 scanname[len++] = '.';
701 scanname[len++] = '/';
703 else if (scanname[len-1] != '/' && scanname[len-1] != '\\') {
704 scanname[len++] = '/';
706 scanname[len++] = '*';
707 scanname[len] = '\0';
709 /* do the FindFirstFile call */
711 A2WHELPER(scanname, wbuffer, sizeof(wbuffer), GETINTERPMODE());
712 fh = FindFirstFileW(wbuffer, &wFindData);
715 fh = FindFirstFileA(scanname, &aFindData);
717 if (fh == INVALID_HANDLE_VALUE) {
718 /* FindFirstFile() fails on empty drives! */
719 if (GetLastError() == ERROR_FILE_NOT_FOUND)
725 /* now allocate the first part of the string table for
726 * the filenames that we find.
729 W2AHELPER(wFindData.cFileName, buffer, sizeof(buffer), GETINTERPMODE());
733 ptr = aFindData.cFileName;
736 New(1304, p->start, idx, char);
737 if (p->start == NULL)
738 Perl_croak_nocontext("opendir: malloc failed!\n");
739 strcpy(p->start, ptr);
742 /* loop finding all the files that match the wildcard
743 * (which should be all of them in this directory!).
744 * the variable idx should point one past the null terminator
745 * of the previous string found.
748 ? FindNextFileW(fh, &wFindData)
749 : FindNextFileA(fh, &aFindData)) {
751 W2AHELPER(wFindData.cFileName, buffer, sizeof(buffer), GETINTERPMODE());
753 /* ptr is set above to the correct area */
755 /* bump the string table size by enough for the
756 * new name and it's null terminator
758 Renew(p->start, idx+len+1, char);
759 if (p->start == NULL)
760 Perl_croak_nocontext("opendir: malloc failed!\n");
761 strcpy(&p->start[idx], ptr);
772 /* Readdir just returns the current string pointer and bumps the
773 * string pointer to the nDllExport entry.
776 win32_readdir(DIR *dirp)
779 static int dummy = 0;
782 /* first set up the structure to return */
783 len = strlen(dirp->curr);
784 strcpy(dirp->dirstr.d_name, dirp->curr);
785 dirp->dirstr.d_namlen = len;
788 dirp->dirstr.d_ino = dummy++;
790 /* Now set up for the nDllExport call to readdir */
791 dirp->curr += len + 1;
792 if (dirp->curr >= (dirp->start + dirp->size)) {
796 return &(dirp->dirstr);
802 /* Telldir returns the current string pointer position */
804 win32_telldir(DIR *dirp)
806 return (long) dirp->curr;
810 /* Seekdir moves the string pointer to a previously saved position
814 win32_seekdir(DIR *dirp, long loc)
816 dirp->curr = (char *)loc;
819 /* Rewinddir resets the string pointer to the start */
821 win32_rewinddir(DIR *dirp)
823 dirp->curr = dirp->start;
826 /* free the memory allocated by opendir */
828 win32_closedir(DIR *dirp)
830 Safefree(dirp->start);
843 * Just pretend that everyone is a superuser. NT will let us know if
844 * we don\'t really have permission to do something.
847 #define ROOT_UID ((uid_t)0)
848 #define ROOT_GID ((gid_t)0)
877 return (auid == ROOT_UID ? 0 : -1);
883 return (agid == ROOT_GID ? 0 : -1);
890 char *buf = getlogin_buffer;
891 DWORD size = sizeof(getlogin_buffer);
892 if (GetUserName(buf,&size))
898 chown(const char *path, uid_t owner, gid_t group)
908 for (child = 0 ; child < w32_num_children ; ++child) {
909 if (w32_child_pids[child] == pid)
916 remove_dead_process(long child)
919 CloseHandle(w32_child_handles[child]);
920 Copy(&w32_child_handles[child+1], &w32_child_handles[child],
921 (w32_num_children-child-1), HANDLE);
922 Copy(&w32_child_pids[child+1], &w32_child_pids[child],
923 (w32_num_children-child-1), DWORD);
929 win32_kill(int pid, int sig)
932 hProcess = OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid);
933 if (hProcess && TerminateProcess(hProcess, sig))
934 CloseHandle(hProcess);
946 DllExport unsigned int
947 win32_sleep(unsigned int t)
954 win32_stat(const char *path, struct stat *buffer)
957 int l = strlen(path);
959 WCHAR wbuffer[MAX_PATH];
962 switch(path[l - 1]) {
963 /* FindFirstFile() and stat() are buggy with a trailing
964 * backslash, so change it to a forward slash :-( */
966 strncpy(t, path, l-1);
971 /* FindFirstFile() is buggy with "x:", so add a dot :-( */
973 if (l == 2 && isALPHA(path[0])) {
974 t[0] = path[0]; t[1] = ':'; t[2] = '.'; t[3] = '\0';
983 A2WHELPER(path, wbuffer, sizeof(wbuffer), GETINTERPMODE());
984 res = _wstat(wbuffer, (struct _stat *)buffer);
987 res = stat(path, buffer);
990 /* CRT is buggy on sharenames, so make sure it really isn't.
991 * XXX using GetFileAttributesEx() will enable us to set
992 * buffer->st_*time (but note that's not available on the
993 * Windows of 1995) */
996 r = GetFileAttributesW(wbuffer);
999 r = GetFileAttributesA(path);
1001 if (r != 0xffffffff && (r & FILE_ATTRIBUTE_DIRECTORY)) {
1002 /* buffer may still contain old garbage since stat() failed */
1003 Zero(buffer, 1, struct stat);
1004 buffer->st_mode = S_IFDIR | S_IREAD;
1006 if (!(r & FILE_ATTRIBUTE_READONLY))
1007 buffer->st_mode |= S_IWRITE | S_IEXEC;
1012 if (l == 3 && isALPHA(path[0]) && path[1] == ':'
1013 && (path[2] == '\\' || path[2] == '/'))
1015 /* The drive can be inaccessible, some _stat()s are buggy */
1017 ? !GetVolumeInformationW(wbuffer,NULL,0,NULL,NULL,NULL,NULL,0)
1018 : !GetVolumeInformationA(path,NULL,0,NULL,NULL,NULL,NULL,0)) {
1024 if (S_ISDIR(buffer->st_mode))
1025 buffer->st_mode |= S_IWRITE | S_IEXEC;
1026 else if (S_ISREG(buffer->st_mode)) {
1027 if (l >= 4 && path[l-4] == '.') {
1028 const char *e = path + l - 3;
1029 if (strnicmp(e,"exe",3)
1030 && strnicmp(e,"bat",3)
1031 && strnicmp(e,"com",3)
1032 && (IsWin95() || strnicmp(e,"cmd",3)))
1033 buffer->st_mode &= ~S_IEXEC;
1035 buffer->st_mode |= S_IEXEC;
1038 buffer->st_mode &= ~S_IEXEC;
1045 /* Find the longname of a given path. path is destructively modified.
1046 * It should have space for at least MAX_PATH characters. */
1048 win32_longpath(char *path)
1050 WIN32_FIND_DATA fdata;
1052 char tmpbuf[MAX_PATH+1];
1053 char *tmpstart = tmpbuf;
1060 if (isALPHA(path[0]) && path[1] == ':' &&
1061 (path[2] == '/' || path[2] == '\\'))
1064 *tmpstart++ = path[0];
1068 else if ((path[0] == '/' || path[0] == '\\') &&
1069 (path[1] == '/' || path[1] == '\\'))
1072 *tmpstart++ = path[0];
1073 *tmpstart++ = path[1];
1074 /* copy machine name */
1075 while (*start && *start != '/' && *start != '\\')
1076 *tmpstart++ = *start++;
1078 *tmpstart++ = *start;
1080 /* copy share name */
1081 while (*start && *start != '/' && *start != '\\')
1082 *tmpstart++ = *start++;
1086 if (sep == '/' || sep == '\\')
1090 /* walk up to slash */
1091 while (*start && *start != '/' && *start != '\\')
1094 /* discard doubled slashes */
1095 while (*start && (start[1] == '/' || start[1] == '\\'))
1099 /* stop and find full name of component */
1101 fhand = FindFirstFile(path,&fdata);
1102 if (fhand != INVALID_HANDLE_VALUE) {
1103 strcpy(tmpstart, fdata.cFileName);
1104 tmpstart += strlen(fdata.cFileName);
1112 /* failed a step, just return without side effects */
1113 /*PerlIO_printf(PerlIO_stderr(), "Failed to find %s\n", path);*/
1118 strcpy(path,tmpbuf);
1122 #ifndef USE_WIN32_RTL_ENV
1125 win32_getenv(const char *name)
1128 static char *curitem = Nullch; /* XXX threadead */
1129 static WCHAR *wCuritem = (WCHAR*)Nullch; /* XXX threadead */
1130 static DWORD curlen = 0, wCurlen = 0;/* XXX threadead */
1131 WCHAR wBuffer[MAX_PATH];
1137 New(1306,wCuritem,wCurlen,WCHAR);
1142 New(1305,curitem,curlen,char);
1146 A2WHELPER(name, wBuffer, sizeof(wBuffer), GETINTERPMODE());
1147 needlen = GetEnvironmentVariableW(wBuffer,wCuritem,wCurlen);
1150 needlen = GetEnvironmentVariableA(name,curitem,curlen);
1153 while (needlen > wCurlen) {
1154 Renew(wCuritem,needlen,WCHAR);
1156 needlen = GetEnvironmentVariableW(wBuffer,wCuritem,wCurlen);
1158 if (needlen > curlen) {
1159 Renew(curitem,needlen,char);
1162 W2AHELPER(wCuritem, curitem, curlen, GETINTERPMODE());
1165 while (needlen > curlen) {
1166 Renew(curitem,needlen,char);
1168 needlen = GetEnvironmentVariableA(name,curitem,curlen);
1173 /* allow any environment variables that begin with 'PERL'
1174 to be stored in the registry */
1178 if (strncmp(name, "PERL", 4) == 0) {
1184 curitem = GetRegStr(name, &curitem, &curlen);
1187 if (curitem && *curitem == '\0')
1194 win32_putenv(const char *name)
1200 int length, relval = -1;
1204 length = strlen(name)+1;
1205 New(1309,wCuritem,length,WCHAR);
1206 A2WHELPER(name, wCuritem, length*2, GETINTERPMODE());
1207 wVal = wcschr(wCuritem, '=');
1210 if(SetEnvironmentVariableW(wCuritem, *wVal ? wVal : NULL))
1216 New(1309,curitem,strlen(name)+1,char);
1217 strcpy(curitem, name);
1218 val = strchr(curitem, '=');
1220 /* The sane way to deal with the environment.
1221 * Has these advantages over putenv() & co.:
1222 * * enables us to store a truly empty value in the
1223 * environment (like in UNIX).
1224 * * we don't have to deal with RTL globals, bugs and leaks.
1226 * Why you may want to enable USE_WIN32_RTL_ENV:
1227 * * environ[] and RTL functions will not reflect changes,
1228 * which might be an issue if extensions want to access
1229 * the env. via RTL. This cuts both ways, since RTL will
1230 * not see changes made by extensions that call the Win32
1231 * functions directly, either.
1235 if(SetEnvironmentVariableA(curitem, *val ? val : NULL))
1247 filetime_to_clock(PFILETIME ft)
1249 __int64 qw = ft->dwHighDateTime;
1251 qw |= ft->dwLowDateTime;
1252 qw /= 10000; /* File time ticks at 0.1uS, clock at 1mS */
1257 win32_times(struct tms *timebuf)
1262 if (GetProcessTimes(GetCurrentProcess(), &dummy, &dummy,
1264 timebuf->tms_utime = filetime_to_clock(&user);
1265 timebuf->tms_stime = filetime_to_clock(&kernel);
1266 timebuf->tms_cutime = 0;
1267 timebuf->tms_cstime = 0;
1270 /* That failed - e.g. Win95 fallback to clock() */
1271 clock_t t = clock();
1272 timebuf->tms_utime = t;
1273 timebuf->tms_stime = 0;
1274 timebuf->tms_cutime = 0;
1275 timebuf->tms_cstime = 0;
1280 /* fix utime() so it works on directories in NT
1281 * thanks to Jan Dubois <jan.dubois@ibm.net>
1284 filetime_from_time(PFILETIME pFileTime, time_t Time)
1286 struct tm *pTM = gmtime(&Time);
1287 SYSTEMTIME SystemTime;
1292 SystemTime.wYear = pTM->tm_year + 1900;
1293 SystemTime.wMonth = pTM->tm_mon + 1;
1294 SystemTime.wDay = pTM->tm_mday;
1295 SystemTime.wHour = pTM->tm_hour;
1296 SystemTime.wMinute = pTM->tm_min;
1297 SystemTime.wSecond = pTM->tm_sec;
1298 SystemTime.wMilliseconds = 0;
1300 return SystemTimeToFileTime(&SystemTime, pFileTime);
1304 win32_utime(const char *filename, struct utimbuf *times)
1310 struct utimbuf TimeBuffer;
1311 WCHAR wbuffer[MAX_PATH];
1316 A2WHELPER(filename, wbuffer, sizeof(wbuffer), GETINTERPMODE());
1317 rc = _wutime(wbuffer, (struct _utimbuf*)times);
1320 rc = utime(filename, times);
1322 /* EACCES: path specifies directory or readonly file */
1323 if (rc == 0 || errno != EACCES /* || !IsWinNT() */)
1326 if (times == NULL) {
1327 times = &TimeBuffer;
1328 time(×->actime);
1329 times->modtime = times->actime;
1332 /* This will (and should) still fail on readonly files */
1334 handle = CreateFileW(wbuffer, GENERIC_READ | GENERIC_WRITE,
1335 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1336 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1339 handle = CreateFileA(filename, GENERIC_READ | GENERIC_WRITE,
1340 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1341 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1343 if (handle == INVALID_HANDLE_VALUE)
1346 if (GetFileTime(handle, &ftCreate, &ftAccess, &ftWrite) &&
1347 filetime_from_time(&ftAccess, times->actime) &&
1348 filetime_from_time(&ftWrite, times->modtime) &&
1349 SetFileTime(handle, &ftCreate, &ftAccess, &ftWrite))
1354 CloseHandle(handle);
1359 win32_uname(struct utsname *name)
1361 struct hostent *hep;
1362 STRLEN nodemax = sizeof(name->nodename)-1;
1363 OSVERSIONINFO osver;
1365 memset(&osver, 0, sizeof(OSVERSIONINFO));
1366 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1367 if (GetVersionEx(&osver)) {
1369 switch (osver.dwPlatformId) {
1370 case VER_PLATFORM_WIN32_WINDOWS:
1371 strcpy(name->sysname, "Windows");
1373 case VER_PLATFORM_WIN32_NT:
1374 strcpy(name->sysname, "Windows NT");
1376 case VER_PLATFORM_WIN32s:
1377 strcpy(name->sysname, "Win32s");
1380 strcpy(name->sysname, "Win32 Unknown");
1385 sprintf(name->release, "%d.%d",
1386 osver.dwMajorVersion, osver.dwMinorVersion);
1389 sprintf(name->version, "Build %d",
1390 osver.dwPlatformId == VER_PLATFORM_WIN32_NT
1391 ? osver.dwBuildNumber : (osver.dwBuildNumber & 0xffff));
1392 if (osver.szCSDVersion[0]) {
1393 char *buf = name->version + strlen(name->version);
1394 sprintf(buf, " (%s)", osver.szCSDVersion);
1398 *name->sysname = '\0';
1399 *name->version = '\0';
1400 *name->release = '\0';
1404 hep = win32_gethostbyname("localhost");
1406 STRLEN len = strlen(hep->h_name);
1407 if (len <= nodemax) {
1408 strcpy(name->nodename, hep->h_name);
1411 strncpy(name->nodename, hep->h_name, nodemax);
1412 name->nodename[nodemax] = '\0';
1417 if (!GetComputerName(name->nodename, &sz))
1418 *name->nodename = '\0';
1421 /* machine (architecture) */
1425 GetSystemInfo(&info);
1428 switch (info.DUMMYUNIONNAME.DUMMYSTRUCTNAME.wProcessorArchitecture) {
1431 switch (info.u.s.wProcessorArchitecture) {
1433 switch (info.wProcessorArchitecture) {
1436 case PROCESSOR_ARCHITECTURE_INTEL:
1437 arch = "x86"; break;
1438 case PROCESSOR_ARCHITECTURE_MIPS:
1439 arch = "mips"; break;
1440 case PROCESSOR_ARCHITECTURE_ALPHA:
1441 arch = "alpha"; break;
1442 case PROCESSOR_ARCHITECTURE_PPC:
1443 arch = "ppc"; break;
1445 arch = "unknown"; break;
1447 strcpy(name->machine, arch);
1453 win32_waitpid(int pid, int *status, int flags)
1457 return win32_wait(status);
1459 long child = find_pid(pid);
1461 HANDLE hProcess = w32_child_handles[child];
1462 DWORD waitcode = WaitForSingleObject(hProcess, INFINITE);
1463 if (waitcode != WAIT_FAILED) {
1464 if (GetExitCodeProcess(hProcess, &waitcode)) {
1465 *status = (int)((waitcode & 0xff) << 8);
1466 retval = (int)w32_child_pids[child];
1467 remove_dead_process(child);
1475 retval = cwait(status, pid, WAIT_CHILD);
1476 /* cwait() returns "correctly" on Borland */
1477 #ifndef __BORLANDC__
1483 return retval >= 0 ? pid : retval;
1487 win32_wait(int *status)
1489 /* XXX this wait emulation only knows about processes
1490 * spawned via win32_spawnvp(P_NOWAIT, ...).
1493 DWORD exitcode, waitcode;
1495 if (!w32_num_children) {
1500 /* if a child exists, wait for it to die */
1501 waitcode = WaitForMultipleObjects(w32_num_children,
1505 if (waitcode != WAIT_FAILED) {
1506 if (waitcode >= WAIT_ABANDONED_0
1507 && waitcode < WAIT_ABANDONED_0 + w32_num_children)
1508 i = waitcode - WAIT_ABANDONED_0;
1510 i = waitcode - WAIT_OBJECT_0;
1511 if (GetExitCodeProcess(w32_child_handles[i], &exitcode) ) {
1512 *status = (int)((exitcode & 0xff) << 8);
1513 retval = (int)w32_child_pids[i];
1514 remove_dead_process(i);
1520 errno = GetLastError();
1524 static UINT timerid = 0;
1526 static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
1528 KillTimer(NULL,timerid);
1533 DllExport unsigned int
1534 win32_alarm(unsigned int sec)
1537 * the 'obvious' implentation is SetTimer() with a callback
1538 * which does whatever receiving SIGALRM would do
1539 * we cannot use SIGALRM even via raise() as it is not
1540 * one of the supported codes in <signal.h>
1542 * Snag is unless something is looking at the message queue
1543 * nothing happens :-(
1547 timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
1549 Perl_croak_nocontext("Cannot set timer");
1555 KillTimer(NULL,timerid);
1562 #if defined(HAVE_DES_FCRYPT) || defined(PERL_OBJECT)
1563 #ifdef HAVE_DES_FCRYPT
1564 extern char * des_fcrypt(const char *txt, const char *salt, char *cbuf);
1568 win32_crypt(const char *txt, const char *salt)
1570 #ifdef HAVE_DES_FCRYPT
1572 return des_fcrypt(txt, salt, crypt_buffer);
1574 die("The crypt() function is unimplemented due to excessive paranoia.");
1580 #ifdef USE_FIXED_OSFHANDLE
1582 EXTERN_C int __cdecl _alloc_osfhnd(void);
1583 EXTERN_C int __cdecl _set_osfhnd(int fh, long value);
1584 EXTERN_C void __cdecl _lock_fhandle(int);
1585 EXTERN_C void __cdecl _unlock_fhandle(int);
1586 EXTERN_C void __cdecl _unlock(int);
1588 #if (_MSC_VER >= 1000)
1590 long osfhnd; /* underlying OS file HANDLE */
1591 char osfile; /* attributes of file (e.g., open in text mode?) */
1592 char pipech; /* one char buffer for handles opened on pipes */
1593 #if defined (_MT) && !defined (DLL_FOR_WIN32S)
1595 CRITICAL_SECTION lock;
1596 #endif /* defined (_MT) && !defined (DLL_FOR_WIN32S) */
1599 EXTERN_C ioinfo * __pioinfo[];
1601 #define IOINFO_L2E 5
1602 #define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
1603 #define _pioinfo(i) (__pioinfo[i >> IOINFO_L2E] + (i & (IOINFO_ARRAY_ELTS - 1)))
1604 #define _osfile(i) (_pioinfo(i)->osfile)
1606 #else /* (_MSC_VER >= 1000) */
1607 extern char _osfile[];
1608 #endif /* (_MSC_VER >= 1000) */
1610 #define FOPEN 0x01 /* file handle open */
1611 #define FAPPEND 0x20 /* file handle opened O_APPEND */
1612 #define FDEV 0x40 /* file handle refers to device */
1613 #define FTEXT 0x80 /* file handle is in text mode */
1615 #define _STREAM_LOCKS 26 /* Table of stream locks */
1616 #define _LAST_STREAM_LOCK (_STREAM_LOCKS+_NSTREAM_-1) /* Last stream lock */
1617 #define _FH_LOCKS (_LAST_STREAM_LOCK+1) /* Table of fh locks */
1620 *int my_open_osfhandle(long osfhandle, int flags) - open C Runtime file handle
1623 * This function allocates a free C Runtime file handle and associates
1624 * it with the Win32 HANDLE specified by the first parameter. This is a
1625 * temperary fix for WIN95's brain damage GetFileType() error on socket
1626 * we just bypass that call for socket
1629 * long osfhandle - Win32 HANDLE to associate with C Runtime file handle.
1630 * int flags - flags to associate with C Runtime file handle.
1633 * returns index of entry in fh, if successful
1634 * return -1, if no free entry is found
1638 *******************************************************************************/
1641 my_open_osfhandle(long osfhandle, int flags)
1644 char fileflags; /* _osfile flags */
1646 /* copy relevant flags from second parameter */
1649 if (flags & O_APPEND)
1650 fileflags |= FAPPEND;
1655 /* attempt to allocate a C Runtime file handle */
1656 if ((fh = _alloc_osfhnd()) == -1) {
1657 errno = EMFILE; /* too many open files */
1658 _doserrno = 0L; /* not an OS error */
1659 return -1; /* return error to caller */
1662 /* the file is open. now, set the info in _osfhnd array */
1663 _set_osfhnd(fh, osfhandle);
1665 fileflags |= FOPEN; /* mark as open */
1667 #if (_MSC_VER >= 1000)
1668 _osfile(fh) = fileflags; /* set osfile entry */
1669 _unlock_fhandle(fh);
1671 _osfile[fh] = fileflags; /* set osfile entry */
1672 _unlock(fh+_FH_LOCKS); /* unlock handle */
1675 return fh; /* return handle */
1678 #define _open_osfhandle my_open_osfhandle
1679 #endif /* USE_FIXED_OSFHANDLE */
1681 /* simulate flock by locking a range on the file */
1683 #define LK_ERR(f,i) ((f) ? (i = 0) : (errno = GetLastError()))
1684 #define LK_LEN 0xffff0000
1687 win32_flock(int fd, int oper)
1694 Perl_croak_nocontext("flock() unimplemented on this platform");
1697 fh = (HANDLE)_get_osfhandle(fd);
1698 memset(&o, 0, sizeof(o));
1701 case LOCK_SH: /* shared lock */
1702 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
1704 case LOCK_EX: /* exclusive lock */
1705 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
1707 case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
1708 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
1710 case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
1711 LK_ERR(LockFileEx(fh,
1712 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
1713 0, LK_LEN, 0, &o),i);
1715 case LOCK_UN: /* unlock lock */
1716 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, 0, &o),i);
1718 default: /* unknown */
1729 * redirected io subsystem for all XS modules
1742 return (&(_environ));
1745 /* the rest are the remapped stdio routines */
1765 win32_ferror(FILE *fp)
1767 return (ferror(fp));
1772 win32_feof(FILE *fp)
1778 * Since the errors returned by the socket error function
1779 * WSAGetLastError() are not known by the library routine strerror
1780 * we have to roll our own.
1784 win32_strerror(int e)
1786 #ifndef __BORLANDC__ /* Borland intolerance */
1787 extern int sys_nerr;
1791 if (e < 0 || e > sys_nerr) {
1796 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
1797 strerror_buffer, sizeof(strerror_buffer), NULL) == 0)
1798 strcpy(strerror_buffer, "Unknown Error");
1800 return strerror_buffer;
1806 win32_str_os_error(pTHX_ void *sv, DWORD dwErr)
1810 dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
1811 |FORMAT_MESSAGE_IGNORE_INSERTS
1812 |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
1813 dwErr, 0, (char *)&sMsg, 1, NULL);
1815 while (0 < dwLen && isSPACE(sMsg[--dwLen]))
1817 if ('.' != sMsg[dwLen])
1822 sMsg = (char*)LocalAlloc(0, 64/**sizeof(TCHAR)*/);
1824 dwLen = sprintf(sMsg,
1825 "Unknown error #0x%lX (lookup 0x%lX)",
1826 dwErr, GetLastError());
1829 sv_setpvn((SV*)sv, sMsg, dwLen);
1836 win32_fprintf(FILE *fp, const char *format, ...)
1839 va_start(marker, format); /* Initialize variable arguments. */
1841 return (vfprintf(fp, format, marker));
1845 win32_printf(const char *format, ...)
1848 va_start(marker, format); /* Initialize variable arguments. */
1850 return (vprintf(format, marker));
1854 win32_vfprintf(FILE *fp, const char *format, va_list args)
1856 return (vfprintf(fp, format, args));
1860 win32_vprintf(const char *format, va_list args)
1862 return (vprintf(format, args));
1866 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
1868 return fread(buf, size, count, fp);
1872 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
1874 return fwrite(buf, size, count, fp);
1877 #define MODE_SIZE 10
1880 win32_fopen(const char *filename, const char *mode)
1882 WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH];
1883 if (stricmp(filename, "/dev/null")==0)
1888 A2WHELPER(mode, wMode, sizeof(wMode), GETINTERPMODE());
1889 A2WHELPER(filename, wBuffer, sizeof(wBuffer), GETINTERPMODE());
1890 return _wfopen(wBuffer, wMode);
1892 return fopen(filename, mode);
1895 #ifndef USE_SOCKETS_AS_HANDLES
1897 #define fdopen my_fdopen
1901 win32_fdopen(int handle, const char *mode)
1903 WCHAR wMode[MODE_SIZE];
1906 A2WHELPER(mode, wMode, sizeof(wMode), GETINTERPMODE());
1907 return _wfdopen(handle, wMode);
1909 return fdopen(handle, (char *) mode);
1913 win32_freopen(const char *path, const char *mode, FILE *stream)
1915 WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH];
1916 if (stricmp(path, "/dev/null")==0)
1921 A2WHELPER(mode, wMode, sizeof(wMode), GETINTERPMODE());
1922 A2WHELPER(path, wBuffer, sizeof(wBuffer), GETINTERPMODE());
1923 return _wfreopen(wBuffer, wMode, stream);
1925 return freopen(path, mode, stream);
1929 win32_fclose(FILE *pf)
1931 return my_fclose(pf); /* defined in win32sck.c */
1935 win32_fputs(const char *s,FILE *pf)
1937 return fputs(s, pf);
1941 win32_fputc(int c,FILE *pf)
1947 win32_ungetc(int c,FILE *pf)
1949 return ungetc(c,pf);
1953 win32_getc(FILE *pf)
1959 win32_fileno(FILE *pf)
1965 win32_clearerr(FILE *pf)
1972 win32_fflush(FILE *pf)
1978 win32_ftell(FILE *pf)
1984 win32_fseek(FILE *pf,long offset,int origin)
1986 return fseek(pf, offset, origin);
1990 win32_fgetpos(FILE *pf,fpos_t *p)
1992 return fgetpos(pf, p);
1996 win32_fsetpos(FILE *pf,const fpos_t *p)
1998 return fsetpos(pf, p);
2002 win32_rewind(FILE *pf)
2022 win32_fstat(int fd,struct stat *sbufptr)
2024 return fstat(fd,sbufptr);
2028 win32_pipe(int *pfd, unsigned int size, int mode)
2030 return _pipe(pfd, size, mode);
2034 * a popen() clone that respects PERL5SHELL
2038 win32_popen(const char *command, const char *mode)
2040 #ifdef USE_RTL_POPEN
2041 return _popen(command, mode);
2049 /* establish which ends read and write */
2050 if (strchr(mode,'w')) {
2051 stdfd = 0; /* stdin */
2055 else if (strchr(mode,'r')) {
2056 stdfd = 1; /* stdout */
2063 /* set the correct mode */
2064 if (strchr(mode,'b'))
2066 else if (strchr(mode,'t'))
2069 ourmode = _fmode & (O_TEXT | O_BINARY);
2071 /* the child doesn't inherit handles */
2072 ourmode |= O_NOINHERIT;
2074 if (win32_pipe( p, 512, ourmode) == -1)
2077 /* save current stdfd */
2078 if ((oldfd = win32_dup(stdfd)) == -1)
2081 /* make stdfd go to child end of pipe (implicitly closes stdfd) */
2082 /* stdfd will be inherited by the child */
2083 if (win32_dup2(p[child], stdfd) == -1)
2086 /* close the child end in parent */
2087 win32_close(p[child]);
2089 /* start the child */
2092 if ((childpid = do_spawn_nowait(aTHX_ (char*)command)) == -1)
2095 /* revert stdfd to whatever it was before */
2096 if (win32_dup2(oldfd, stdfd) == -1)
2099 /* close saved handle */
2102 sv_setiv(*av_fetch(w32_fdpid, p[parent], TRUE), childpid);
2105 /* we have an fd, return a file stream */
2106 return (win32_fdopen(p[parent], (char *)mode));
2109 /* we don't need to check for errors here */
2113 win32_dup2(oldfd, stdfd);
2118 #endif /* USE_RTL_POPEN */
2126 win32_pclose(FILE *pf)
2128 #ifdef USE_RTL_POPEN
2132 int childpid, status;
2135 sv = *av_fetch(w32_fdpid, win32_fileno(pf), TRUE);
2137 childpid = SvIVX(sv);
2149 if (win32_waitpid(childpid, &status, 0) == -1)
2154 #endif /* USE_RTL_POPEN */
2158 win32_rename(const char *oname, const char *newname)
2160 WCHAR wOldName[MAX_PATH];
2161 WCHAR wNewName[MAX_PATH];
2163 /* XXX despite what the documentation says about MoveFileEx(),
2164 * it doesn't work under Windows95!
2169 A2WHELPER(oname, wOldName, sizeof(wOldName), GETINTERPMODE());
2170 A2WHELPER(newname, wNewName, sizeof(wNewName), GETINTERPMODE());
2171 bResult = MoveFileExW(wOldName,wNewName,
2172 MOVEFILE_COPY_ALLOWED|MOVEFILE_REPLACE_EXISTING);
2175 bResult = MoveFileExA(oname,newname,
2176 MOVEFILE_COPY_ALLOWED|MOVEFILE_REPLACE_EXISTING);
2179 DWORD err = GetLastError();
2181 case ERROR_BAD_NET_NAME:
2182 case ERROR_BAD_NETPATH:
2183 case ERROR_BAD_PATHNAME:
2184 case ERROR_FILE_NOT_FOUND:
2185 case ERROR_FILENAME_EXCED_RANGE:
2186 case ERROR_INVALID_DRIVE:
2187 case ERROR_NO_MORE_FILES:
2188 case ERROR_PATH_NOT_FOUND:
2201 char tmpname[MAX_PATH+1];
2202 char dname[MAX_PATH+1];
2203 char *endname = Nullch;
2205 DWORD from_attr, to_attr;
2207 /* if oname doesn't exist, do nothing */
2208 from_attr = GetFileAttributes(oname);
2209 if (from_attr == 0xFFFFFFFF) {
2214 /* if newname exists, rename it to a temporary name so that we
2215 * don't delete it in case oname happens to be the same file
2216 * (but perhaps accessed via a different path)
2218 to_attr = GetFileAttributes(newname);
2219 if (to_attr != 0xFFFFFFFF) {
2220 /* if newname is a directory, we fail
2221 * XXX could overcome this with yet more convoluted logic */
2222 if (to_attr & FILE_ATTRIBUTE_DIRECTORY) {
2226 tmplen = strlen(newname);
2227 strcpy(tmpname,newname);
2228 endname = tmpname+tmplen;
2229 for (; endname > tmpname ; --endname) {
2230 if (*endname == '/' || *endname == '\\') {
2235 if (endname > tmpname)
2236 endname = strcpy(dname,tmpname);
2240 /* get a temporary filename in same directory
2241 * XXX is this really the best we can do? */
2242 if (!GetTempFileName((LPCTSTR)endname, "plr", 0, tmpname)) {
2246 DeleteFile(tmpname);
2248 retval = rename(newname, tmpname);
2255 /* rename oname to newname */
2256 retval = rename(oname, newname);
2258 /* if we created a temporary file before ... */
2259 if (endname != Nullch) {
2260 /* ...and rename succeeded, delete temporary file/directory */
2262 DeleteFile(tmpname);
2263 /* else restore it to what it was */
2265 (void)rename(tmpname, newname);
2272 win32_setmode(int fd, int mode)
2274 return setmode(fd, mode);
2278 win32_lseek(int fd, long offset, int origin)
2280 return lseek(fd, offset, origin);
2290 win32_open(const char *path, int flag, ...)
2294 WCHAR wBuffer[MAX_PATH];
2297 pmode = va_arg(ap, int);
2300 if (stricmp(path, "/dev/null")==0)
2305 A2WHELPER(path, wBuffer, sizeof(wBuffer), GETINTERPMODE());
2306 return _wopen(wBuffer, flag, pmode);
2308 return open(path,flag,pmode);
2330 win32_dup2(int fd1,int fd2)
2332 return dup2(fd1,fd2);
2336 win32_read(int fd, void *buf, unsigned int cnt)
2338 return read(fd, buf, cnt);
2342 win32_write(int fd, const void *buf, unsigned int cnt)
2344 return write(fd, buf, cnt);
2348 win32_mkdir(const char *dir, int mode)
2350 return mkdir(dir); /* just ignore mode */
2354 win32_rmdir(const char *dir)
2360 win32_chdir(const char *dir)
2366 create_command_line(const char* command, const char * const *args)
2369 char *cmd, *ptr, *arg;
2370 STRLEN len = strlen(command) + 1;
2372 for (index = 0; (ptr = (char*)args[index]) != NULL; ++index)
2373 len += strlen(ptr) + 1;
2375 New(1310, cmd, len, char);
2377 strcpy(ptr, command);
2379 for (index = 0; (arg = (char*)args[index]) != NULL; ++index) {
2389 qualified_path(const char *cmd)
2392 char *fullcmd, *curfullcmd;
2398 fullcmd = (char*)cmd;
2400 if (*fullcmd == '/' || *fullcmd == '\\')
2407 pathstr = win32_getenv("PATH");
2408 New(0, fullcmd, MAX_PATH+1, char);
2409 curfullcmd = fullcmd;
2414 /* start by appending the name to the current prefix */
2415 strcpy(curfullcmd, cmd);
2416 curfullcmd += cmdlen;
2418 /* if it doesn't end with '.', or has no extension, try adding
2419 * a trailing .exe first */
2420 if (cmd[cmdlen-1] != '.'
2421 && (cmdlen < 4 || cmd[cmdlen-4] != '.'))
2423 strcpy(curfullcmd, ".exe");
2424 res = GetFileAttributes(fullcmd);
2425 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
2430 /* that failed, try the bare name */
2431 res = GetFileAttributes(fullcmd);
2432 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
2435 /* quit if no other path exists, or if cmd already has path */
2436 if (!pathstr || !*pathstr || has_slash)
2439 /* skip leading semis */
2440 while (*pathstr == ';')
2443 /* build a new prefix from scratch */
2444 curfullcmd = fullcmd;
2445 while (*pathstr && *pathstr != ';') {
2446 if (*pathstr == '"') { /* foo;"baz;etc";bar */
2447 pathstr++; /* skip initial '"' */
2448 while (*pathstr && *pathstr != '"') {
2449 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
2450 *curfullcmd++ = *pathstr;
2454 pathstr++; /* skip trailing '"' */
2457 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
2458 *curfullcmd++ = *pathstr;
2463 pathstr++; /* skip trailing semi */
2464 if (curfullcmd > fullcmd /* append a dir separator */
2465 && curfullcmd[-1] != '/' && curfullcmd[-1] != '\\')
2467 *curfullcmd++ = '\\';
2475 /* XXX this needs to be made more compatible with the spawnvp()
2476 * provided by the various RTLs. In particular, searching for
2477 * *.{com,bat,cmd} files (as done by the RTLs) is unimplemented.
2478 * This doesn't significantly affect perl itself, because we
2479 * always invoke things using PERL5SHELL if a direct attempt to
2480 * spawn the executable fails.
2482 * XXX splitting and rejoining the commandline between do_aspawn()
2483 * and win32_spawnvp() could also be avoided.
2487 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
2489 #ifdef USE_RTL_SPAWNVP
2490 return spawnvp(mode, cmdname, (char * const *)argv);
2493 STARTUPINFO StartupInfo;
2494 PROCESS_INFORMATION ProcessInformation;
2497 char *cmd = create_command_line(cmdname, strcmp(cmdname, argv[0]) == 0
2499 char *fullcmd = Nullch;
2502 case P_NOWAIT: /* asynch + remember result */
2503 if (w32_num_children >= MAXIMUM_WAIT_OBJECTS) {
2509 case P_WAIT: /* synchronous execution */
2511 default: /* invalid mode */
2516 memset(&StartupInfo,0,sizeof(StartupInfo));
2517 StartupInfo.cb = sizeof(StartupInfo);
2518 StartupInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
2519 StartupInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
2520 StartupInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
2521 if (StartupInfo.hStdInput != INVALID_HANDLE_VALUE &&
2522 StartupInfo.hStdOutput != INVALID_HANDLE_VALUE &&
2523 StartupInfo.hStdError != INVALID_HANDLE_VALUE)
2525 StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
2528 create |= CREATE_NEW_CONSOLE;
2532 StartupInfo.dwFlags |= STARTF_USESHOWWINDOW;
2533 StartupInfo.wShowWindow = SW_HIDE;
2537 if (!CreateProcess(cmdname, /* search PATH to find executable */
2538 cmd, /* executable, and its arguments */
2539 NULL, /* process attributes */
2540 NULL, /* thread attributes */
2541 TRUE, /* inherit handles */
2542 create, /* creation flags */
2543 NULL, /* inherit environment */
2544 NULL, /* inherit cwd */
2546 &ProcessInformation))
2548 /* initial NULL argument to CreateProcess() does a PATH
2549 * search, but it always first looks in the directory
2550 * where the current process was started, which behavior
2551 * is undesirable for backward compatibility. So we
2552 * jump through our own hoops by picking out the path
2553 * we really want it to use. */
2555 fullcmd = qualified_path(cmdname);
2566 if (mode == P_NOWAIT) {
2567 /* asynchronous spawn -- store handle, return PID */
2568 w32_child_handles[w32_num_children] = ProcessInformation.hProcess;
2569 ret = w32_child_pids[w32_num_children] = ProcessInformation.dwProcessId;
2573 WaitForSingleObject(ProcessInformation.hProcess, INFINITE);
2574 GetExitCodeProcess(ProcessInformation.hProcess, &ret);
2575 CloseHandle(ProcessInformation.hProcess);
2578 CloseHandle(ProcessInformation.hThread);
2587 win32_execv(const char *cmdname, const char *const *argv)
2589 return execv(cmdname, (char *const *)argv);
2593 win32_execvp(const char *cmdname, const char *const *argv)
2595 return execvp(cmdname, (char *const *)argv);
2599 win32_perror(const char *str)
2605 win32_setbuf(FILE *pf, char *buf)
2611 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
2613 return setvbuf(pf, buf, type, size);
2617 win32_flushall(void)
2623 win32_fcloseall(void)
2629 win32_fgets(char *s, int n, FILE *pf)
2631 return fgets(s, n, pf);
2641 win32_fgetc(FILE *pf)
2647 win32_putc(int c, FILE *pf)
2653 win32_puts(const char *s)
2665 win32_putchar(int c)
2672 #ifndef USE_PERL_SBRK
2674 static char *committed = NULL;
2675 static char *base = NULL;
2676 static char *reserved = NULL;
2677 static char *brk = NULL;
2678 static DWORD pagesize = 0;
2679 static DWORD allocsize = 0;
2687 GetSystemInfo(&info);
2688 /* Pretend page size is larger so we don't perpetually
2689 * call the OS to commit just one page ...
2691 pagesize = info.dwPageSize << 3;
2692 allocsize = info.dwAllocationGranularity;
2694 /* This scheme fails eventually if request for contiguous
2695 * block is denied so reserve big blocks - this is only
2696 * address space not memory ...
2698 if (brk+need >= reserved)
2700 DWORD size = 64*1024*1024;
2702 if (committed && reserved && committed < reserved)
2704 /* Commit last of previous chunk cannot span allocations */
2705 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
2707 committed = reserved;
2709 /* Reserve some (more) space
2710 * Note this is a little sneaky, 1st call passes NULL as reserved
2711 * so lets system choose where we start, subsequent calls pass
2712 * the old end address so ask for a contiguous block
2714 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
2717 reserved = addr+size;
2732 if (brk > committed)
2734 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
2735 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
2750 win32_malloc(size_t size)
2752 return malloc(size);
2756 win32_calloc(size_t numitems, size_t size)
2758 return calloc(numitems,size);
2762 win32_realloc(void *block, size_t size)
2764 return realloc(block,size);
2768 win32_free(void *block)
2775 win32_open_osfhandle(long handle, int flags)
2777 return _open_osfhandle(handle, flags);
2781 win32_get_osfhandle(int fd)
2783 return _get_osfhandle(fd);
2794 SV *sv = sv_newmortal();
2795 /* Make one call with zero size - return value is required size */
2796 DWORD len = GetCurrentDirectory((DWORD)0,NULL);
2797 SvUPGRADE(sv,SVt_PV);
2799 SvCUR(sv) = GetCurrentDirectory((DWORD) SvLEN(sv), SvPVX(sv));
2802 * then it worked, set PV valid,
2803 * else leave it 'undef'
2819 Perl_croak(aTHX_ "usage: Win32::SetCurrentDirectory($cwd)");
2820 if (SetCurrentDirectory(SvPV_nolen(ST(0))))
2827 XS(w32_GetNextAvailDrive)
2831 char root[] = "_:\\";
2836 if (GetDriveType(root) == 1) {
2845 XS(w32_GetLastError)
2849 XSRETURN_IV(GetLastError());
2853 XS(w32_SetLastError)
2857 Perl_croak(aTHX_ "usage: Win32::SetLastError($error)");
2858 SetLastError(SvIV(ST(0)));
2866 char *name = getlogin_buffer;
2867 DWORD size = sizeof(getlogin_buffer);
2869 if (GetUserName(name,&size)) {
2870 /* size includes NULL */
2871 ST(0) = sv_2mortal(newSVpvn(name,size-1));
2881 char name[MAX_COMPUTERNAME_LENGTH+1];
2882 DWORD size = sizeof(name);
2884 if (GetComputerName(name,&size)) {
2885 /* size does NOT include NULL :-( */
2886 ST(0) = sv_2mortal(newSVpvn(name,size));
2897 #ifndef HAS_NETWKSTAGETINFO
2898 /* mingw32 (and Win95) don't have NetWksta*(), so do it the old way */
2900 DWORD size = sizeof(name);
2902 if (GetUserName(name,&size)) {
2904 DWORD sidlen = sizeof(sid);
2906 DWORD dnamelen = sizeof(dname);
2908 if (LookupAccountName(NULL, name, (PSID)&sid, &sidlen,
2909 dname, &dnamelen, &snu)) {
2910 XSRETURN_PV(dname); /* all that for this */
2914 /* this way is more reliable, in case user has a local account.
2915 * XXX need dynamic binding of netapi32.dll symbols or this will fail on
2916 * Win95. Probably makes more sense to move it into libwin32. */
2918 DWORD dnamelen = sizeof(dname);
2919 PWKSTA_INFO_100 pwi;
2921 if (NERR_Success == NetWkstaGetInfo(NULL, 100, (LPBYTE*)&pwi)) {
2922 if (pwi->wki100_langroup && *(pwi->wki100_langroup)) {
2923 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_langroup,
2924 -1, (LPSTR)dname, dnamelen, NULL, NULL);
2927 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_computername,
2928 -1, (LPSTR)dname, dnamelen, NULL, NULL);
2930 NetApiBufferFree(pwi);
2942 DWORD flags, filecomplen;
2943 if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
2944 &flags, fsname, sizeof(fsname))) {
2945 if (GIMME_V == G_ARRAY) {
2946 XPUSHs(sv_2mortal(newSVpvn(fsname,strlen(fsname))));
2947 XPUSHs(sv_2mortal(newSViv(flags)));
2948 XPUSHs(sv_2mortal(newSViv(filecomplen)));
2953 XSRETURN_PV(fsname);
2959 XS(w32_GetOSVersion)
2962 OSVERSIONINFO osver;
2964 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
2965 if (GetVersionEx(&osver)) {
2966 XPUSHs(newSVpvn(osver.szCSDVersion, strlen(osver.szCSDVersion)));
2967 XPUSHs(newSViv(osver.dwMajorVersion));
2968 XPUSHs(newSViv(osver.dwMinorVersion));
2969 XPUSHs(newSViv(osver.dwBuildNumber));
2970 XPUSHs(newSViv(osver.dwPlatformId));
2982 XSRETURN_IV(IsWinNT());
2990 XSRETURN_IV(IsWin95());
2994 XS(w32_FormatMessage)
3001 Perl_croak(aTHX_ "usage: Win32::FormatMessage($errno)");
3003 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
3004 &source, SvIV(ST(0)), 0,
3005 msgbuf, sizeof(msgbuf)-1, NULL))
3006 XSRETURN_PV(msgbuf);
3016 PROCESS_INFORMATION stProcInfo;
3017 STARTUPINFO stStartInfo;
3018 BOOL bSuccess = FALSE;
3021 Perl_croak(aTHX_ "usage: Win32::Spawn($cmdName, $args, $PID)");
3023 cmd = SvPV_nolen(ST(0));
3024 args = SvPV_nolen(ST(1));
3026 memset(&stStartInfo, 0, sizeof(stStartInfo)); /* Clear the block */
3027 stStartInfo.cb = sizeof(stStartInfo); /* Set the structure size */
3028 stStartInfo.dwFlags = STARTF_USESHOWWINDOW; /* Enable wShowWindow control */
3029 stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE; /* Start min (normal) */
3032 cmd, /* Image path */
3033 args, /* Arguments for command line */
3034 NULL, /* Default process security */
3035 NULL, /* Default thread security */
3036 FALSE, /* Must be TRUE to use std handles */
3037 NORMAL_PRIORITY_CLASS, /* No special scheduling */
3038 NULL, /* Inherit our environment block */
3039 NULL, /* Inherit our currrent directory */
3040 &stStartInfo, /* -> Startup info */
3041 &stProcInfo)) /* <- Process info (if OK) */
3043 CloseHandle(stProcInfo.hThread);/* library source code does this. */
3044 sv_setiv(ST(2), stProcInfo.dwProcessId);
3047 XSRETURN_IV(bSuccess);
3051 XS(w32_GetTickCount)
3054 DWORD msec = GetTickCount();
3062 XS(w32_GetShortPathName)
3069 Perl_croak(aTHX_ "usage: Win32::GetShortPathName($longPathName)");
3071 shortpath = sv_mortalcopy(ST(0));
3072 SvUPGRADE(shortpath, SVt_PV);
3073 /* src == target is allowed */
3075 len = GetShortPathName(SvPVX(shortpath),
3078 } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
3080 SvCUR_set(shortpath,len);
3088 XS(w32_GetFullPathName)
3097 Perl_croak(aTHX_ "usage: Win32::GetFullPathName($filename)");
3100 fullpath = sv_mortalcopy(filename);
3101 SvUPGRADE(fullpath, SVt_PV);
3103 len = GetFullPathName(SvPVX(filename),
3107 } while (len >= SvLEN(fullpath) && sv_grow(fullpath,len+1));
3109 if (GIMME_V == G_ARRAY) {
3111 XST_mPV(1,filepart);
3112 len = filepart - SvPVX(fullpath);
3115 SvCUR_set(fullpath,len);
3123 XS(w32_GetLongPathName)
3127 char tmpbuf[MAX_PATH+1];
3132 Perl_croak(aTHX_ "usage: Win32::GetLongPathName($pathname)");
3135 pathstr = SvPV(path,len);
3136 strcpy(tmpbuf, pathstr);
3137 pathstr = win32_longpath(tmpbuf);
3139 ST(0) = sv_2mortal(newSVpvn(pathstr, strlen(pathstr)));
3150 Perl_croak(aTHX_ "usage: Win32::Sleep($milliseconds)");
3160 Perl_croak(aTHX_ "usage: Win32::CopyFile($from, $to, $overwrite)");
3161 if (CopyFile(SvPV_nolen(ST(0)), SvPV_nolen(ST(1)), !SvTRUE(ST(2))))
3167 Perl_init_os_extras(pTHX)
3169 char *file = __FILE__;
3172 w32_perlshell_tokens = Nullch;
3173 w32_perlshell_items = -1;
3174 w32_fdpid = newAV(); /* XXX needs to be in Perl_win32_init()? */
3175 New(1313, w32_children, 1, child_tab);
3176 w32_num_children = 0;
3178 /* these names are Activeware compatible */
3179 newXS("Win32::GetCwd", w32_GetCwd, file);
3180 newXS("Win32::SetCwd", w32_SetCwd, file);
3181 newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
3182 newXS("Win32::GetLastError", w32_GetLastError, file);
3183 newXS("Win32::SetLastError", w32_SetLastError, file);
3184 newXS("Win32::LoginName", w32_LoginName, file);
3185 newXS("Win32::NodeName", w32_NodeName, file);
3186 newXS("Win32::DomainName", w32_DomainName, file);
3187 newXS("Win32::FsType", w32_FsType, file);
3188 newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
3189 newXS("Win32::IsWinNT", w32_IsWinNT, file);
3190 newXS("Win32::IsWin95", w32_IsWin95, file);
3191 newXS("Win32::FormatMessage", w32_FormatMessage, file);
3192 newXS("Win32::Spawn", w32_Spawn, file);
3193 newXS("Win32::GetTickCount", w32_GetTickCount, file);
3194 newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
3195 newXS("Win32::GetFullPathName", w32_GetFullPathName, file);
3196 newXS("Win32::GetLongPathName", w32_GetLongPathName, file);
3197 newXS("Win32::CopyFile", w32_CopyFile, file);
3198 newXS("Win32::Sleep", w32_Sleep, file);
3200 /* XXX Bloat Alert! The following Activeware preloads really
3201 * ought to be part of Win32::Sys::*, so they're not included
3204 /* LookupAccountName
3206 * InitiateSystemShutdown
3207 * AbortSystemShutdown
3208 * ExpandEnvrironmentStrings
3213 Perl_win32_init(int *argcp, char ***argvp)
3215 /* Disable floating point errors, Perl will trap the ones we
3216 * care about. VC++ RTL defaults to switching these off
3217 * already, but the Borland RTL doesn't. Since we don't
3218 * want to be at the vendor's whim on the default, we set
3219 * it explicitly here.
3221 #if !defined(_ALPHA_) && !defined(__GNUC__)
3222 _control87(MCW_EM, MCW_EM);
3227 #ifdef USE_BINMODE_SCRIPTS
3230 win32_strip_return(SV *sv)
3232 char *s = SvPVX(sv);
3233 char *e = s+SvCUR(sv);
3237 if (*s == '\r' && s[1] == '\n')
3247 SvCUR_set(sv,d-SvPVX(sv));