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)
43 #define PERL_NO_GET_CONTEXT
49 /* assert.h conflicts with #define of assert in perl.h */
56 #if defined(_MSC_VER) || defined(__MINGW32__)
57 #include <sys/utime.h>
63 /* Mingw32 defaults to globing command line
64 * So we turn it off like this:
71 # define _utimbuf utimbuf
76 #define EXECF_SPAWN_NOWAIT 3
78 #if defined(PERL_IMPLICIT_SYS)
79 # undef win32_get_privlib
80 # define win32_get_privlib g_win32_get_privlib
81 # undef win32_get_sitelib
82 # define win32_get_sitelib g_win32_get_sitelib
84 # define do_spawn g_do_spawn
86 # define getlogin g_getlogin
89 #if defined(PERL_OBJECT)
91 # define do_aspawn g_do_aspawn
93 # define Perl_do_exec g_do_exec
96 static void get_shell(void);
97 static long tokenize(char *str, char **dest, char ***destv);
98 int do_spawn2(char *cmd, int exectype);
99 static BOOL has_shell_metachars(char *ptr);
100 static long filetime_to_clock(PFILETIME ft);
101 static BOOL filetime_from_time(PFILETIME ft, time_t t);
102 static char * get_emd_part(SV **leading, char *trailing, ...);
103 static void remove_dead_process(long deceased);
104 static long find_pid(int pid);
105 static char * qualified_path(const char *cmd);
107 HANDLE w32_perldll_handle = INVALID_HANDLE_VALUE;
108 char w32_module_name[MAX_PATH+1];
109 static DWORD w32_platform = (DWORD)-1;
112 # ifdef USE_DECLSPEC_THREAD
113 __declspec(thread) char strerror_buffer[512];
114 __declspec(thread) char getlogin_buffer[128];
115 __declspec(thread) char w32_perllib_root[MAX_PATH+1];
116 # ifdef HAVE_DES_FCRYPT
117 __declspec(thread) char crypt_buffer[30];
120 # define strerror_buffer (thr->i.Wstrerror_buffer)
121 # define getlogin_buffer (thr->i.Wgetlogin_buffer)
122 # define w32_perllib_root (thr->i.Ww32_perllib_root)
123 # define crypt_buffer (thr->i.Wcrypt_buffer)
126 static char strerror_buffer[512];
127 static char getlogin_buffer[128];
128 static char w32_perllib_root[MAX_PATH+1];
129 # ifdef HAVE_DES_FCRYPT
130 static char crypt_buffer[30];
137 return (win32_os_id() == VER_PLATFORM_WIN32_WINDOWS);
143 return (win32_os_id() == VER_PLATFORM_WIN32_NT);
146 /* *svp (if non-NULL) is expected to be POK (valid allocated SvPVX(*svp)) */
148 get_regstr_from(HKEY hkey, const char *valuename, SV **svp)
150 /* Retrieve a REG_SZ or REG_EXPAND_SZ from the registry */
153 const char *subkey = "Software\\Perl";
157 retval = RegOpenKeyEx(hkey, subkey, 0, KEY_READ, &handle);
158 if (retval == ERROR_SUCCESS) {
160 retval = RegQueryValueEx(handle, valuename, 0, &type, NULL, &datalen);
161 if (retval == ERROR_SUCCESS && type == REG_SZ) {
164 *svp = sv_2mortal(newSVpvn("",0));
165 SvGROW(*svp, datalen);
166 retval = RegQueryValueEx(handle, valuename, 0, NULL,
167 (PBYTE)SvPVX(*svp), &datalen);
168 if (retval == ERROR_SUCCESS) {
170 SvCUR_set(*svp,datalen-1);
178 /* *svp (if non-NULL) is expected to be POK (valid allocated SvPVX(*svp)) */
180 get_regstr(const char *valuename, SV **svp)
182 char *str = get_regstr_from(HKEY_CURRENT_USER, valuename, svp);
184 str = get_regstr_from(HKEY_LOCAL_MACHINE, valuename, svp);
188 /* *prev_pathp (if non-NULL) is expected to be POK (valid allocated SvPVX(sv)) */
190 get_emd_part(SV **prev_pathp, char *trailing_path, ...)
194 char mod_name[MAX_PATH+1];
198 int oldsize, newsize;
200 va_start(ap, trailing_path);
201 strip = va_arg(ap, char *);
203 sprintf(base, "%5.3f",
204 (double)PERL_REVISION + ((double)PERL_VERSION / (double)1000));
206 if (!*w32_module_name) {
207 GetModuleFileName((HMODULE)((w32_perldll_handle == INVALID_HANDLE_VALUE)
208 ? GetModuleHandle(NULL)
209 : w32_perldll_handle),
210 w32_module_name, sizeof(w32_module_name));
212 /* try to get full path to binary (which may be mangled when perl is
213 * run from a 16-bit app) */
214 /*PerlIO_printf(Perl_debug_log, "Before %s\n", w32_module_name);*/
215 (void)win32_longpath(w32_module_name);
216 /*PerlIO_printf(Perl_debug_log, "After %s\n", w32_module_name);*/
218 /* normalize to forward slashes */
219 ptr = w32_module_name;
226 strcpy(mod_name, w32_module_name);
227 ptr = strrchr(mod_name, '/');
228 while (ptr && strip) {
229 /* look for directories to skip back */
232 ptr = strrchr(mod_name, '/');
233 /* avoid stripping component if there is no slash,
234 * or it doesn't match ... */
235 if (!ptr || stricmp(ptr+1, strip) != 0) {
236 /* ... but not if component matches 5.00X* */
237 if (!ptr || !(*strip == '5' && *(ptr+1) == '5'
238 && strncmp(strip, base, 5) == 0
239 && strncmp(ptr+1, base, 5) == 0))
245 strip = va_arg(ap, char *);
253 strcpy(++ptr, trailing_path);
255 /* only add directory if it exists */
256 if (GetFileAttributes(mod_name) != (DWORD) -1) {
257 /* directory exists */
260 *prev_pathp = sv_2mortal(newSVpvn("",0));
261 sv_catpvn(*prev_pathp, ";", 1);
262 sv_catpv(*prev_pathp, mod_name);
263 return SvPVX(*prev_pathp);
270 win32_get_privlib(char *pl)
273 char *stdlib = "lib";
274 char buffer[MAX_PATH+1];
277 /* $stdlib = $HKCU{"lib-$]"} || $HKLM{"lib-$]"} || $HKCU{"lib"} || $HKLM{"lib"} || ""; */
278 sprintf(buffer, "%s-%s", stdlib, pl);
279 if (!get_regstr(buffer, &sv))
280 (void)get_regstr(stdlib, &sv);
282 /* $stdlib .= ";$EMD/../../lib" */
283 return get_emd_part(&sv, stdlib, ARCHNAME, "bin", Nullch);
287 win32_get_sitelib(char *pl)
290 char *sitelib = "sitelib";
292 char pathstr[MAX_PATH+1];
298 /* $HKCU{"sitelib-$]"} || $HKLM{"sitelib-$]"} . ---; */
299 sprintf(regstr, "%s-%s", sitelib, pl);
300 (void)get_regstr(regstr, &sv1);
303 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/site/$]/lib"; */
304 sprintf(pathstr, "site/%s/lib", pl);
305 (void)get_emd_part(&sv1, pathstr, ARCHNAME, "bin", pl, Nullch);
306 if (!sv1 && strlen(pl) == 7) {
307 /* pl may have been SUBVERSION-specific; try again without
309 sprintf(pathstr, "site/%.5s/lib", pl);
310 (void)get_emd_part(&sv1, pathstr, ARCHNAME, "bin", pl, Nullch);
313 /* $HKCU{'sitelib'} || $HKLM{'sitelib'} . ---; */
314 (void)get_regstr(sitelib, &sv2);
317 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/site/lib"; */
318 (void)get_emd_part(&sv2, "site/lib", ARCHNAME, "bin", pl, Nullch);
327 sv_catpvn(sv1, ";", 1);
335 has_shell_metachars(char *ptr)
341 * Scan string looking for redirection (< or >) or pipe
342 * characters (|) that are not in a quoted string.
343 * Shell variable interpolation (%VAR%) can also happen inside strings.
375 #if !defined(PERL_IMPLICIT_SYS)
376 /* since the current process environment is being updated in util.c
377 * the library functions will get the correct environment
380 Perl_my_popen(pTHX_ char *cmd, char *mode)
383 #define fixcmd(x) { \
384 char *pspace = strchr((x),' '); \
387 while (p < pspace) { \
398 PERL_FLUSHALL_FOR_CHILD;
399 return win32_popen(cmd, mode);
403 Perl_my_pclose(pTHX_ PerlIO *fp)
405 return win32_pclose(fp);
409 DllExport unsigned long
412 static OSVERSIONINFO osver;
414 if (osver.dwPlatformId != w32_platform) {
415 memset(&osver, 0, sizeof(OSVERSIONINFO));
416 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
417 GetVersionEx(&osver);
418 w32_platform = osver.dwPlatformId;
420 return (unsigned long)w32_platform;
423 /* Tokenize a string. Words are null-separated, and the list
424 * ends with a doubled null. Any character (except null and
425 * including backslash) may be escaped by preceding it with a
426 * backslash (the backslash will be stripped).
427 * Returns number of words in result buffer.
430 tokenize(char *str, char **dest, char ***destv)
432 char *retstart = Nullch;
433 char **retvstart = 0;
437 int slen = strlen(str);
439 register char **retv;
440 New(1307, ret, slen+2, char);
441 New(1308, retv, (slen+3)/2, char*);
449 if (*ret == '\\' && *str)
451 else if (*ret == ' ') {
467 retvstart[items] = Nullch;
480 if (!w32_perlshell_tokens) {
481 /* we don't use COMSPEC here for two reasons:
482 * 1. the same reason perl on UNIX doesn't use SHELL--rampant and
483 * uncontrolled unportability of the ensuing scripts.
484 * 2. PERL5SHELL could be set to a shell that may not be fit for
485 * interactive use (which is what most programs look in COMSPEC
488 char* defaultshell = (IsWinNT() ? "cmd.exe /x/c" : "command.com /c");
489 char *usershell = getenv("PERL5SHELL");
490 w32_perlshell_items = tokenize(usershell ? usershell : defaultshell,
491 &w32_perlshell_tokens,
497 do_aspawn(void *vreally, void **vmark, void **vsp)
500 SV *really = (SV*)vreally;
501 SV **mark = (SV**)vmark;
513 New(1306, argv, (sp - mark) + w32_perlshell_items + 2, char*);
515 if (SvNIOKp(*(mark+1)) && !SvPOKp(*(mark+1))) {
520 while (++mark <= sp) {
521 if (*mark && (str = SvPV_nolen(*mark)))
528 status = win32_spawnvp(flag,
529 (const char*)(really ? SvPV_nolen(really) : argv[0]),
530 (const char* const*)argv);
532 if (status < 0 && (errno == ENOEXEC || errno == ENOENT)) {
533 /* possible shell-builtin, invoke with shell */
535 sh_items = w32_perlshell_items;
537 argv[index+sh_items] = argv[index];
538 while (--sh_items >= 0)
539 argv[sh_items] = w32_perlshell_vec[sh_items];
541 status = win32_spawnvp(flag,
542 (const char*)(really ? SvPV_nolen(really) : argv[0]),
543 (const char* const*)argv);
546 if (flag != P_NOWAIT) {
549 if (ckWARN(WARN_EXEC))
550 Perl_warner(aTHX_ WARN_EXEC, "Can't spawn \"%s\": %s", argv[0], strerror(errno));
555 PL_statusvalue = status;
562 do_spawn2(char *cmd, int exectype)
569 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 if (ckWARN(WARN_EXEC))
639 Perl_warner(aTHX_ WARN_EXEC, "Can't %s \"%s\": %s",
640 (exectype == EXECF_EXEC ? "exec" : "spawn"),
641 cmd, strerror(errno));
646 PL_statusvalue = status;
654 return do_spawn2(cmd, EXECF_SPAWN);
658 do_spawn_nowait(char *cmd)
660 return do_spawn2(cmd, EXECF_SPAWN_NOWAIT);
664 Perl_do_exec(pTHX_ char *cmd)
666 do_spawn2(cmd, EXECF_EXEC);
670 /* The idea here is to read all the directory names into a string table
671 * (separated by nulls) and when one of the other dir functions is called
672 * return the pointer to the current file name.
675 win32_opendir(char *filename)
681 char scanname[MAX_PATH+3];
683 WIN32_FIND_DATAA aFindData;
684 WIN32_FIND_DATAW wFindData;
686 char buffer[MAX_PATH*2];
687 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, dirp, 1, DIR);
701 /* Create the search pattern */
702 strcpy(scanname, filename);
704 /* bare drive name means look in cwd for drive */
705 if (len == 2 && isALPHA(scanname[0]) && scanname[1] == ':') {
706 scanname[len++] = '.';
707 scanname[len++] = '/';
709 else if (scanname[len-1] != '/' && scanname[len-1] != '\\') {
710 scanname[len++] = '/';
712 scanname[len++] = '*';
713 scanname[len] = '\0';
715 /* do the FindFirstFile call */
717 A2WHELPER(scanname, wbuffer, sizeof(wbuffer));
718 fh = FindFirstFileW(wbuffer, &wFindData);
721 fh = FindFirstFileA(scanname, &aFindData);
724 if (fh == INVALID_HANDLE_VALUE) {
725 DWORD err = GetLastError();
726 /* FindFirstFile() fails on empty drives! */
728 case ERROR_FILE_NOT_FOUND:
730 case ERROR_NO_MORE_FILES:
731 case ERROR_PATH_NOT_FOUND:
734 case ERROR_NOT_ENOUGH_MEMORY:
745 /* now allocate the first part of the string table for
746 * the filenames that we find.
749 W2AHELPER(wFindData.cFileName, buffer, sizeof(buffer));
753 ptr = aFindData.cFileName;
760 New(1304, dirp->start, dirp->size, char);
761 strcpy(dirp->start, ptr);
763 dirp->end = dirp->curr = dirp->start;
769 /* Readdir just returns the current string pointer and bumps the
770 * string pointer to the nDllExport entry.
772 DllExport struct direct *
773 win32_readdir(DIR *dirp)
778 /* first set up the structure to return */
779 len = strlen(dirp->curr);
780 strcpy(dirp->dirstr.d_name, dirp->curr);
781 dirp->dirstr.d_namlen = len;
784 dirp->dirstr.d_ino = dirp->curr - dirp->start;
786 /* Now set up for the next call to readdir */
787 dirp->curr += len + 1;
788 if (dirp->curr >= dirp->end) {
792 WIN32_FIND_DATAW wFindData;
793 WIN32_FIND_DATAA aFindData;
794 char buffer[MAX_PATH*2];
796 /* finding the next file that matches the wildcard
797 * (which should be all of them in this directory!).
800 res = FindNextFileW(dirp->handle, &wFindData);
802 W2AHELPER(wFindData.cFileName, buffer, sizeof(buffer));
807 res = FindNextFileA(dirp->handle, &aFindData);
809 ptr = aFindData.cFileName;
812 long endpos = dirp->end - dirp->start;
813 long newsize = endpos + strlen(ptr) + 1;
814 /* bump the string table size by enough for the
815 * new name and it's null terminator */
816 while (newsize > dirp->size) {
817 long curpos = dirp->curr - dirp->start;
819 Renew(dirp->start, dirp->size, char);
820 dirp->curr = dirp->start + curpos;
822 strcpy(dirp->start + endpos, ptr);
823 dirp->end = dirp->start + newsize;
829 return &(dirp->dirstr);
835 /* Telldir returns the current string pointer position */
837 win32_telldir(DIR *dirp)
839 return (dirp->curr - dirp->start);
843 /* Seekdir moves the string pointer to a previously saved position
844 * (returned by telldir).
847 win32_seekdir(DIR *dirp, long loc)
849 dirp->curr = dirp->start + loc;
852 /* Rewinddir resets the string pointer to the start */
854 win32_rewinddir(DIR *dirp)
856 dirp->curr = dirp->start;
859 /* free the memory allocated by opendir */
861 win32_closedir(DIR *dirp)
864 if (dirp->handle != INVALID_HANDLE_VALUE)
865 FindClose(dirp->handle);
866 Safefree(dirp->start);
879 * Just pretend that everyone is a superuser. NT will let us know if
880 * we don\'t really have permission to do something.
883 #define ROOT_UID ((uid_t)0)
884 #define ROOT_GID ((gid_t)0)
913 return (auid == ROOT_UID ? 0 : -1);
919 return (agid == ROOT_GID ? 0 : -1);
926 char *buf = getlogin_buffer;
927 DWORD size = sizeof(getlogin_buffer);
928 if (GetUserName(buf,&size))
934 chown(const char *path, uid_t owner, gid_t group)
945 for (child = 0 ; child < w32_num_children ; ++child) {
946 if (w32_child_pids[child] == pid)
953 remove_dead_process(long child)
957 CloseHandle(w32_child_handles[child]);
958 Copy(&w32_child_handles[child+1], &w32_child_handles[child],
959 (w32_num_children-child-1), HANDLE);
960 Copy(&w32_child_pids[child+1], &w32_child_pids[child],
961 (w32_num_children-child-1), DWORD);
967 win32_kill(int pid, int sig)
970 hProcess = OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid);
971 if (hProcess && TerminateProcess(hProcess, sig))
972 CloseHandle(hProcess);
984 DllExport unsigned int
985 win32_sleep(unsigned int t)
992 win32_stat(const char *path, struct stat *buffer)
996 int l = strlen(path);
998 WCHAR wbuffer[MAX_PATH];
1001 switch(path[l - 1]) {
1002 /* FindFirstFile() and stat() are buggy with a trailing
1003 * backslash, so change it to a forward slash :-( */
1005 strncpy(t, path, l-1);
1010 /* FindFirstFile() is buggy with "x:", so add a dot :-( */
1012 if (l == 2 && isALPHA(path[0])) {
1013 t[0] = path[0]; t[1] = ':'; t[2] = '.'; t[3] = '\0';
1021 A2WHELPER(path, wbuffer, sizeof(wbuffer));
1022 res = _wstat(wbuffer, (struct _stat *)buffer);
1025 res = stat(path, buffer);
1028 /* CRT is buggy on sharenames, so make sure it really isn't.
1029 * XXX using GetFileAttributesEx() will enable us to set
1030 * buffer->st_*time (but note that's not available on the
1031 * Windows of 1995) */
1034 r = GetFileAttributesW(wbuffer);
1037 r = GetFileAttributesA(path);
1039 if (r != 0xffffffff && (r & FILE_ATTRIBUTE_DIRECTORY)) {
1040 /* buffer may still contain old garbage since stat() failed */
1041 Zero(buffer, 1, struct stat);
1042 buffer->st_mode = S_IFDIR | S_IREAD;
1044 if (!(r & FILE_ATTRIBUTE_READONLY))
1045 buffer->st_mode |= S_IWRITE | S_IEXEC;
1050 if (l == 3 && isALPHA(path[0]) && path[1] == ':'
1051 && (path[2] == '\\' || path[2] == '/'))
1053 /* The drive can be inaccessible, some _stat()s are buggy */
1055 ? !GetVolumeInformationW(wbuffer,NULL,0,NULL,NULL,NULL,NULL,0)
1056 : !GetVolumeInformationA(path,NULL,0,NULL,NULL,NULL,NULL,0)) {
1062 if (S_ISDIR(buffer->st_mode))
1063 buffer->st_mode |= S_IWRITE | S_IEXEC;
1064 else if (S_ISREG(buffer->st_mode)) {
1065 if (l >= 4 && path[l-4] == '.') {
1066 const char *e = path + l - 3;
1067 if (strnicmp(e,"exe",3)
1068 && strnicmp(e,"bat",3)
1069 && strnicmp(e,"com",3)
1070 && (IsWin95() || strnicmp(e,"cmd",3)))
1071 buffer->st_mode &= ~S_IEXEC;
1073 buffer->st_mode |= S_IEXEC;
1076 buffer->st_mode &= ~S_IEXEC;
1083 /* Find the longname of a given path. path is destructively modified.
1084 * It should have space for at least MAX_PATH characters. */
1086 win32_longpath(char *path)
1088 WIN32_FIND_DATA fdata;
1090 char tmpbuf[MAX_PATH+1];
1091 char *tmpstart = tmpbuf;
1098 if (isALPHA(path[0]) && path[1] == ':' &&
1099 (path[2] == '/' || path[2] == '\\'))
1102 *tmpstart++ = path[0];
1106 else if ((path[0] == '/' || path[0] == '\\') &&
1107 (path[1] == '/' || path[1] == '\\'))
1110 *tmpstart++ = path[0];
1111 *tmpstart++ = path[1];
1112 /* copy machine name */
1113 while (*start && *start != '/' && *start != '\\')
1114 *tmpstart++ = *start++;
1116 *tmpstart++ = *start;
1118 /* copy share name */
1119 while (*start && *start != '/' && *start != '\\')
1120 *tmpstart++ = *start++;
1124 if (sep == '/' || sep == '\\')
1128 /* walk up to slash */
1129 while (*start && *start != '/' && *start != '\\')
1132 /* discard doubled slashes */
1133 while (*start && (start[1] == '/' || start[1] == '\\'))
1137 /* stop and find full name of component */
1139 fhand = FindFirstFile(path,&fdata);
1140 if (fhand != INVALID_HANDLE_VALUE) {
1141 strcpy(tmpstart, fdata.cFileName);
1142 tmpstart += strlen(fdata.cFileName);
1150 /* failed a step, just return without side effects */
1151 /*PerlIO_printf(Perl_debug_log, "Failed to find %s\n", path);*/
1156 strcpy(path,tmpbuf);
1160 #ifndef USE_WIN32_RTL_ENV
1163 win32_getenv(const char *name)
1166 WCHAR wBuffer[MAX_PATH];
1168 SV *curitem = Nullsv;
1171 A2WHELPER(name, wBuffer, sizeof(wBuffer));
1172 needlen = GetEnvironmentVariableW(wBuffer, NULL, 0);
1175 needlen = GetEnvironmentVariableA(name,NULL,0);
1177 curitem = sv_2mortal(newSVpvn("", 0));
1181 SvGROW(curitem, (needlen+1)*sizeof(WCHAR));
1182 needlen = GetEnvironmentVariableW(wBuffer,
1183 (WCHAR*)SvPVX(curitem),
1185 } while (needlen >= SvLEN(curitem)/sizeof(WCHAR));
1186 SvCUR_set(curitem, (needlen*sizeof(WCHAR))+1);
1187 acuritem = sv_2mortal(newSVsv(curitem));
1188 W2AHELPER((WCHAR*)SvPVX(acuritem), SvPVX(curitem), SvCUR(curitem));
1192 SvGROW(curitem, needlen+1);
1193 needlen = GetEnvironmentVariableA(name,SvPVX(curitem),
1195 } while (needlen >= SvLEN(curitem));
1196 SvCUR_set(curitem, needlen);
1200 /* allow any environment variables that begin with 'PERL'
1201 to be stored in the registry */
1202 if (strncmp(name, "PERL", 4) == 0)
1203 (void)get_regstr(name, &curitem);
1205 if (curitem && SvCUR(curitem))
1206 return SvPVX(curitem);
1212 win32_putenv(const char *name)
1219 int length, relval = -1;
1223 length = strlen(name)+1;
1224 New(1309,wCuritem,length,WCHAR);
1225 A2WHELPER(name, wCuritem, length*sizeof(WCHAR));
1226 wVal = wcschr(wCuritem, '=');
1229 if(SetEnvironmentVariableW(wCuritem, *wVal ? wVal : NULL))
1235 New(1309,curitem,strlen(name)+1,char);
1236 strcpy(curitem, name);
1237 val = strchr(curitem, '=');
1239 /* The sane way to deal with the environment.
1240 * Has these advantages over putenv() & co.:
1241 * * enables us to store a truly empty value in the
1242 * environment (like in UNIX).
1243 * * we don't have to deal with RTL globals, bugs and leaks.
1245 * Why you may want to enable USE_WIN32_RTL_ENV:
1246 * * environ[] and RTL functions will not reflect changes,
1247 * which might be an issue if extensions want to access
1248 * the env. via RTL. This cuts both ways, since RTL will
1249 * not see changes made by extensions that call the Win32
1250 * functions directly, either.
1254 if(SetEnvironmentVariableA(curitem, *val ? val : NULL))
1266 filetime_to_clock(PFILETIME ft)
1268 __int64 qw = ft->dwHighDateTime;
1270 qw |= ft->dwLowDateTime;
1271 qw /= 10000; /* File time ticks at 0.1uS, clock at 1mS */
1276 win32_times(struct tms *timebuf)
1281 if (GetProcessTimes(GetCurrentProcess(), &dummy, &dummy,
1283 timebuf->tms_utime = filetime_to_clock(&user);
1284 timebuf->tms_stime = filetime_to_clock(&kernel);
1285 timebuf->tms_cutime = 0;
1286 timebuf->tms_cstime = 0;
1289 /* That failed - e.g. Win95 fallback to clock() */
1290 clock_t t = clock();
1291 timebuf->tms_utime = t;
1292 timebuf->tms_stime = 0;
1293 timebuf->tms_cutime = 0;
1294 timebuf->tms_cstime = 0;
1299 /* fix utime() so it works on directories in NT */
1301 filetime_from_time(PFILETIME pFileTime, time_t Time)
1303 struct tm *pTM = localtime(&Time);
1304 SYSTEMTIME SystemTime;
1310 SystemTime.wYear = pTM->tm_year + 1900;
1311 SystemTime.wMonth = pTM->tm_mon + 1;
1312 SystemTime.wDay = pTM->tm_mday;
1313 SystemTime.wHour = pTM->tm_hour;
1314 SystemTime.wMinute = pTM->tm_min;
1315 SystemTime.wSecond = pTM->tm_sec;
1316 SystemTime.wMilliseconds = 0;
1318 return SystemTimeToFileTime(&SystemTime, &LocalTime) &&
1319 LocalFileTimeToFileTime(&LocalTime, pFileTime);
1323 win32_utime(const char *filename, struct utimbuf *times)
1330 struct utimbuf TimeBuffer;
1331 WCHAR wbuffer[MAX_PATH];
1335 A2WHELPER(filename, wbuffer, sizeof(wbuffer));
1336 rc = _wutime(wbuffer, (struct _utimbuf*)times);
1339 rc = utime(filename, times);
1341 /* EACCES: path specifies directory or readonly file */
1342 if (rc == 0 || errno != EACCES /* || !IsWinNT() */)
1345 if (times == NULL) {
1346 times = &TimeBuffer;
1347 time(×->actime);
1348 times->modtime = times->actime;
1351 /* This will (and should) still fail on readonly files */
1353 handle = CreateFileW(wbuffer, GENERIC_READ | GENERIC_WRITE,
1354 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1355 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1358 handle = CreateFileA(filename, GENERIC_READ | GENERIC_WRITE,
1359 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1360 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1362 if (handle == INVALID_HANDLE_VALUE)
1365 if (GetFileTime(handle, &ftCreate, &ftAccess, &ftWrite) &&
1366 filetime_from_time(&ftAccess, times->actime) &&
1367 filetime_from_time(&ftWrite, times->modtime) &&
1368 SetFileTime(handle, &ftCreate, &ftAccess, &ftWrite))
1373 CloseHandle(handle);
1378 win32_uname(struct utsname *name)
1380 struct hostent *hep;
1381 STRLEN nodemax = sizeof(name->nodename)-1;
1382 OSVERSIONINFO osver;
1384 memset(&osver, 0, sizeof(OSVERSIONINFO));
1385 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1386 if (GetVersionEx(&osver)) {
1388 switch (osver.dwPlatformId) {
1389 case VER_PLATFORM_WIN32_WINDOWS:
1390 strcpy(name->sysname, "Windows");
1392 case VER_PLATFORM_WIN32_NT:
1393 strcpy(name->sysname, "Windows NT");
1395 case VER_PLATFORM_WIN32s:
1396 strcpy(name->sysname, "Win32s");
1399 strcpy(name->sysname, "Win32 Unknown");
1404 sprintf(name->release, "%d.%d",
1405 osver.dwMajorVersion, osver.dwMinorVersion);
1408 sprintf(name->version, "Build %d",
1409 osver.dwPlatformId == VER_PLATFORM_WIN32_NT
1410 ? osver.dwBuildNumber : (osver.dwBuildNumber & 0xffff));
1411 if (osver.szCSDVersion[0]) {
1412 char *buf = name->version + strlen(name->version);
1413 sprintf(buf, " (%s)", osver.szCSDVersion);
1417 *name->sysname = '\0';
1418 *name->version = '\0';
1419 *name->release = '\0';
1423 hep = win32_gethostbyname("localhost");
1425 STRLEN len = strlen(hep->h_name);
1426 if (len <= nodemax) {
1427 strcpy(name->nodename, hep->h_name);
1430 strncpy(name->nodename, hep->h_name, nodemax);
1431 name->nodename[nodemax] = '\0';
1436 if (!GetComputerName(name->nodename, &sz))
1437 *name->nodename = '\0';
1440 /* machine (architecture) */
1444 GetSystemInfo(&info);
1446 #if defined(__BORLANDC__) || defined(__MINGW32__)
1447 switch (info.u.s.wProcessorArchitecture) {
1449 switch (info.wProcessorArchitecture) {
1451 case PROCESSOR_ARCHITECTURE_INTEL:
1452 arch = "x86"; break;
1453 case PROCESSOR_ARCHITECTURE_MIPS:
1454 arch = "mips"; break;
1455 case PROCESSOR_ARCHITECTURE_ALPHA:
1456 arch = "alpha"; break;
1457 case PROCESSOR_ARCHITECTURE_PPC:
1458 arch = "ppc"; break;
1460 arch = "unknown"; break;
1462 strcpy(name->machine, arch);
1468 win32_waitpid(int pid, int *status, int flags)
1473 return win32_wait(status);
1475 long child = find_pid(pid);
1477 HANDLE hProcess = w32_child_handles[child];
1478 DWORD waitcode = WaitForSingleObject(hProcess, INFINITE);
1479 if (waitcode != WAIT_FAILED) {
1480 if (GetExitCodeProcess(hProcess, &waitcode)) {
1481 *status = (int)((waitcode & 0xff) << 8);
1482 retval = (int)w32_child_pids[child];
1483 remove_dead_process(child);
1491 retval = cwait(status, pid, WAIT_CHILD);
1492 /* cwait() returns "correctly" on Borland */
1493 #ifndef __BORLANDC__
1499 return retval >= 0 ? pid : retval;
1503 win32_wait(int *status)
1505 /* XXX this wait emulation only knows about processes
1506 * spawned via win32_spawnvp(P_NOWAIT, ...).
1510 DWORD exitcode, waitcode;
1512 if (!w32_num_children) {
1517 /* if a child exists, wait for it to die */
1518 waitcode = WaitForMultipleObjects(w32_num_children,
1522 if (waitcode != WAIT_FAILED) {
1523 if (waitcode >= WAIT_ABANDONED_0
1524 && waitcode < WAIT_ABANDONED_0 + w32_num_children)
1525 i = waitcode - WAIT_ABANDONED_0;
1527 i = waitcode - WAIT_OBJECT_0;
1528 if (GetExitCodeProcess(w32_child_handles[i], &exitcode) ) {
1529 *status = (int)((exitcode & 0xff) << 8);
1530 retval = (int)w32_child_pids[i];
1531 remove_dead_process(i);
1537 errno = GetLastError();
1541 static UINT timerid = 0;
1543 static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
1546 KillTimer(NULL,timerid);
1551 DllExport unsigned int
1552 win32_alarm(unsigned int sec)
1555 * the 'obvious' implentation is SetTimer() with a callback
1556 * which does whatever receiving SIGALRM would do
1557 * we cannot use SIGALRM even via raise() as it is not
1558 * one of the supported codes in <signal.h>
1560 * Snag is unless something is looking at the message queue
1561 * nothing happens :-(
1566 timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
1568 Perl_croak_nocontext("Cannot set timer");
1574 KillTimer(NULL,timerid);
1581 #if defined(HAVE_DES_FCRYPT) || defined(PERL_OBJECT)
1582 #ifdef HAVE_DES_FCRYPT
1583 extern char * des_fcrypt(const char *txt, const char *salt, char *cbuf);
1587 win32_crypt(const char *txt, const char *salt)
1590 #ifdef HAVE_DES_FCRYPT
1592 return des_fcrypt(txt, salt, crypt_buffer);
1594 die("The crypt() function is unimplemented due to excessive paranoia.");
1600 #ifdef USE_FIXED_OSFHANDLE
1602 EXTERN_C int __cdecl _alloc_osfhnd(void);
1603 EXTERN_C int __cdecl _set_osfhnd(int fh, long value);
1604 EXTERN_C void __cdecl _lock_fhandle(int);
1605 EXTERN_C void __cdecl _unlock_fhandle(int);
1606 EXTERN_C void __cdecl _unlock(int);
1608 #if (_MSC_VER >= 1000)
1610 long osfhnd; /* underlying OS file HANDLE */
1611 char osfile; /* attributes of file (e.g., open in text mode?) */
1612 char pipech; /* one char buffer for handles opened on pipes */
1613 #if defined (_MT) && !defined (DLL_FOR_WIN32S)
1615 CRITICAL_SECTION lock;
1616 #endif /* defined (_MT) && !defined (DLL_FOR_WIN32S) */
1619 EXTERN_C ioinfo * __pioinfo[];
1621 #define IOINFO_L2E 5
1622 #define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
1623 #define _pioinfo(i) (__pioinfo[i >> IOINFO_L2E] + (i & (IOINFO_ARRAY_ELTS - 1)))
1624 #define _osfile(i) (_pioinfo(i)->osfile)
1626 #else /* (_MSC_VER >= 1000) */
1627 extern char _osfile[];
1628 #endif /* (_MSC_VER >= 1000) */
1630 #define FOPEN 0x01 /* file handle open */
1631 #define FAPPEND 0x20 /* file handle opened O_APPEND */
1632 #define FDEV 0x40 /* file handle refers to device */
1633 #define FTEXT 0x80 /* file handle is in text mode */
1635 #define _STREAM_LOCKS 26 /* Table of stream locks */
1636 #define _LAST_STREAM_LOCK (_STREAM_LOCKS+_NSTREAM_-1) /* Last stream lock */
1637 #define _FH_LOCKS (_LAST_STREAM_LOCK+1) /* Table of fh locks */
1640 *int my_open_osfhandle(long osfhandle, int flags) - open C Runtime file handle
1643 * This function allocates a free C Runtime file handle and associates
1644 * it with the Win32 HANDLE specified by the first parameter. This is a
1645 * temperary fix for WIN95's brain damage GetFileType() error on socket
1646 * we just bypass that call for socket
1649 * long osfhandle - Win32 HANDLE to associate with C Runtime file handle.
1650 * int flags - flags to associate with C Runtime file handle.
1653 * returns index of entry in fh, if successful
1654 * return -1, if no free entry is found
1658 *******************************************************************************/
1661 my_open_osfhandle(long osfhandle, int flags)
1664 char fileflags; /* _osfile flags */
1666 /* copy relevant flags from second parameter */
1669 if (flags & O_APPEND)
1670 fileflags |= FAPPEND;
1675 /* attempt to allocate a C Runtime file handle */
1676 if ((fh = _alloc_osfhnd()) == -1) {
1677 errno = EMFILE; /* too many open files */
1678 _doserrno = 0L; /* not an OS error */
1679 return -1; /* return error to caller */
1682 /* the file is open. now, set the info in _osfhnd array */
1683 _set_osfhnd(fh, osfhandle);
1685 fileflags |= FOPEN; /* mark as open */
1687 #if (_MSC_VER >= 1000)
1688 _osfile(fh) = fileflags; /* set osfile entry */
1689 _unlock_fhandle(fh);
1691 _osfile[fh] = fileflags; /* set osfile entry */
1692 _unlock(fh+_FH_LOCKS); /* unlock handle */
1695 return fh; /* return handle */
1698 #define _open_osfhandle my_open_osfhandle
1699 #endif /* USE_FIXED_OSFHANDLE */
1701 /* simulate flock by locking a range on the file */
1703 #define LK_ERR(f,i) ((f) ? (i = 0) : (errno = GetLastError()))
1704 #define LK_LEN 0xffff0000
1707 win32_flock(int fd, int oper)
1715 Perl_croak_nocontext("flock() unimplemented on this platform");
1718 fh = (HANDLE)_get_osfhandle(fd);
1719 memset(&o, 0, sizeof(o));
1722 case LOCK_SH: /* shared lock */
1723 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
1725 case LOCK_EX: /* exclusive lock */
1726 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
1728 case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
1729 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
1731 case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
1732 LK_ERR(LockFileEx(fh,
1733 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
1734 0, LK_LEN, 0, &o),i);
1736 case LOCK_UN: /* unlock lock */
1737 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, 0, &o),i);
1739 default: /* unknown */
1750 * redirected io subsystem for all XS modules
1763 return (&(_environ));
1766 /* the rest are the remapped stdio routines */
1786 win32_ferror(FILE *fp)
1788 return (ferror(fp));
1793 win32_feof(FILE *fp)
1799 * Since the errors returned by the socket error function
1800 * WSAGetLastError() are not known by the library routine strerror
1801 * we have to roll our own.
1805 win32_strerror(int e)
1807 #ifndef __BORLANDC__ /* Borland intolerance */
1808 extern int sys_nerr;
1812 if (e < 0 || e > sys_nerr) {
1817 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
1818 strerror_buffer, sizeof(strerror_buffer), NULL) == 0)
1819 strcpy(strerror_buffer, "Unknown Error");
1821 return strerror_buffer;
1827 win32_str_os_error(void *sv, DWORD dwErr)
1831 dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
1832 |FORMAT_MESSAGE_IGNORE_INSERTS
1833 |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
1834 dwErr, 0, (char *)&sMsg, 1, NULL);
1835 /* strip trailing whitespace and period */
1838 --dwLen; /* dwLen doesn't include trailing null */
1839 } while (0 < dwLen && isSPACE(sMsg[dwLen]));
1840 if ('.' != sMsg[dwLen])
1845 sMsg = (char*)LocalAlloc(0, 64/**sizeof(TCHAR)*/);
1847 dwLen = sprintf(sMsg,
1848 "Unknown error #0x%lX (lookup 0x%lX)",
1849 dwErr, GetLastError());
1853 sv_setpvn((SV*)sv, sMsg, dwLen);
1860 win32_fprintf(FILE *fp, const char *format, ...)
1863 va_start(marker, format); /* Initialize variable arguments. */
1865 return (vfprintf(fp, format, marker));
1869 win32_printf(const char *format, ...)
1872 va_start(marker, format); /* Initialize variable arguments. */
1874 return (vprintf(format, marker));
1878 win32_vfprintf(FILE *fp, const char *format, va_list args)
1880 return (vfprintf(fp, format, args));
1884 win32_vprintf(const char *format, va_list args)
1886 return (vprintf(format, args));
1890 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
1892 return fread(buf, size, count, fp);
1896 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
1898 return fwrite(buf, size, count, fp);
1901 #define MODE_SIZE 10
1904 win32_fopen(const char *filename, const char *mode)
1907 WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH];
1912 if (stricmp(filename, "/dev/null")==0)
1916 A2WHELPER(mode, wMode, sizeof(wMode));
1917 A2WHELPER(filename, wBuffer, sizeof(wBuffer));
1918 return _wfopen(wBuffer, wMode);
1920 return fopen(filename, mode);
1923 #ifndef USE_SOCKETS_AS_HANDLES
1925 #define fdopen my_fdopen
1929 win32_fdopen(int handle, const char *mode)
1932 WCHAR wMode[MODE_SIZE];
1934 A2WHELPER(mode, wMode, sizeof(wMode));
1935 return _wfdopen(handle, wMode);
1937 return fdopen(handle, (char *) mode);
1941 win32_freopen(const char *path, const char *mode, FILE *stream)
1944 WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH];
1945 if (stricmp(path, "/dev/null")==0)
1949 A2WHELPER(mode, wMode, sizeof(wMode));
1950 A2WHELPER(path, wBuffer, sizeof(wBuffer));
1951 return _wfreopen(wBuffer, wMode, stream);
1953 return freopen(path, mode, stream);
1957 win32_fclose(FILE *pf)
1959 return my_fclose(pf); /* defined in win32sck.c */
1963 win32_fputs(const char *s,FILE *pf)
1965 return fputs(s, pf);
1969 win32_fputc(int c,FILE *pf)
1975 win32_ungetc(int c,FILE *pf)
1977 return ungetc(c,pf);
1981 win32_getc(FILE *pf)
1987 win32_fileno(FILE *pf)
1993 win32_clearerr(FILE *pf)
2000 win32_fflush(FILE *pf)
2006 win32_ftell(FILE *pf)
2012 win32_fseek(FILE *pf,long offset,int origin)
2014 return fseek(pf, offset, origin);
2018 win32_fgetpos(FILE *pf,fpos_t *p)
2020 return fgetpos(pf, p);
2024 win32_fsetpos(FILE *pf,const fpos_t *p)
2026 return fsetpos(pf, p);
2030 win32_rewind(FILE *pf)
2050 win32_fstat(int fd,struct stat *sbufptr)
2052 return fstat(fd,sbufptr);
2056 win32_pipe(int *pfd, unsigned int size, int mode)
2058 return _pipe(pfd, size, mode);
2062 * a popen() clone that respects PERL5SHELL
2066 win32_popen(const char *command, const char *mode)
2068 #ifdef USE_RTL_POPEN
2069 return _popen(command, mode);
2077 /* establish which ends read and write */
2078 if (strchr(mode,'w')) {
2079 stdfd = 0; /* stdin */
2083 else if (strchr(mode,'r')) {
2084 stdfd = 1; /* stdout */
2091 /* set the correct mode */
2092 if (strchr(mode,'b'))
2094 else if (strchr(mode,'t'))
2097 ourmode = _fmode & (O_TEXT | O_BINARY);
2099 /* the child doesn't inherit handles */
2100 ourmode |= O_NOINHERIT;
2102 if (win32_pipe( p, 512, ourmode) == -1)
2105 /* save current stdfd */
2106 if ((oldfd = win32_dup(stdfd)) == -1)
2109 /* make stdfd go to child end of pipe (implicitly closes stdfd) */
2110 /* stdfd will be inherited by the child */
2111 if (win32_dup2(p[child], stdfd) == -1)
2114 /* close the child end in parent */
2115 win32_close(p[child]);
2117 /* start the child */
2120 if ((childpid = do_spawn_nowait((char*)command)) == -1)
2123 /* revert stdfd to whatever it was before */
2124 if (win32_dup2(oldfd, stdfd) == -1)
2127 /* close saved handle */
2130 sv_setiv(*av_fetch(w32_fdpid, p[parent], TRUE), childpid);
2132 /* set process id so that it can be returned by perl's open() */
2133 PL_forkprocess = childpid;
2136 /* we have an fd, return a file stream */
2137 return (win32_fdopen(p[parent], (char *)mode));
2140 /* we don't need to check for errors here */
2144 win32_dup2(oldfd, stdfd);
2149 #endif /* USE_RTL_POPEN */
2157 win32_pclose(FILE *pf)
2159 #ifdef USE_RTL_POPEN
2163 int childpid, status;
2166 sv = *av_fetch(w32_fdpid, win32_fileno(pf), TRUE);
2168 childpid = SvIVX(sv);
2180 if (win32_waitpid(childpid, &status, 0) == -1)
2185 #endif /* USE_RTL_POPEN */
2189 win32_rename(const char *oname, const char *newname)
2191 WCHAR wOldName[MAX_PATH];
2192 WCHAR wNewName[MAX_PATH];
2194 /* XXX despite what the documentation says about MoveFileEx(),
2195 * it doesn't work under Windows95!
2200 A2WHELPER(oname, wOldName, sizeof(wOldName));
2201 A2WHELPER(newname, wNewName, sizeof(wNewName));
2202 bResult = MoveFileExW(wOldName,wNewName,
2203 MOVEFILE_COPY_ALLOWED|MOVEFILE_REPLACE_EXISTING);
2206 bResult = MoveFileExA(oname,newname,
2207 MOVEFILE_COPY_ALLOWED|MOVEFILE_REPLACE_EXISTING);
2210 DWORD err = GetLastError();
2212 case ERROR_BAD_NET_NAME:
2213 case ERROR_BAD_NETPATH:
2214 case ERROR_BAD_PATHNAME:
2215 case ERROR_FILE_NOT_FOUND:
2216 case ERROR_FILENAME_EXCED_RANGE:
2217 case ERROR_INVALID_DRIVE:
2218 case ERROR_NO_MORE_FILES:
2219 case ERROR_PATH_NOT_FOUND:
2232 char tmpname[MAX_PATH+1];
2233 char dname[MAX_PATH+1];
2234 char *endname = Nullch;
2236 DWORD from_attr, to_attr;
2238 /* if oname doesn't exist, do nothing */
2239 from_attr = GetFileAttributes(oname);
2240 if (from_attr == 0xFFFFFFFF) {
2245 /* if newname exists, rename it to a temporary name so that we
2246 * don't delete it in case oname happens to be the same file
2247 * (but perhaps accessed via a different path)
2249 to_attr = GetFileAttributes(newname);
2250 if (to_attr != 0xFFFFFFFF) {
2251 /* if newname is a directory, we fail
2252 * XXX could overcome this with yet more convoluted logic */
2253 if (to_attr & FILE_ATTRIBUTE_DIRECTORY) {
2257 tmplen = strlen(newname);
2258 strcpy(tmpname,newname);
2259 endname = tmpname+tmplen;
2260 for (; endname > tmpname ; --endname) {
2261 if (*endname == '/' || *endname == '\\') {
2266 if (endname > tmpname)
2267 endname = strcpy(dname,tmpname);
2271 /* get a temporary filename in same directory
2272 * XXX is this really the best we can do? */
2273 if (!GetTempFileName((LPCTSTR)endname, "plr", 0, tmpname)) {
2277 DeleteFile(tmpname);
2279 retval = rename(newname, tmpname);
2286 /* rename oname to newname */
2287 retval = rename(oname, newname);
2289 /* if we created a temporary file before ... */
2290 if (endname != Nullch) {
2291 /* ...and rename succeeded, delete temporary file/directory */
2293 DeleteFile(tmpname);
2294 /* else restore it to what it was */
2296 (void)rename(tmpname, newname);
2303 win32_setmode(int fd, int mode)
2305 return setmode(fd, mode);
2309 win32_lseek(int fd, long offset, int origin)
2311 return lseek(fd, offset, origin);
2321 win32_open(const char *path, int flag, ...)
2326 WCHAR wBuffer[MAX_PATH];
2329 pmode = va_arg(ap, int);
2332 if (stricmp(path, "/dev/null")==0)
2336 A2WHELPER(path, wBuffer, sizeof(wBuffer));
2337 return _wopen(wBuffer, flag, pmode);
2339 return open(path,flag,pmode);
2361 win32_dup2(int fd1,int fd2)
2363 return dup2(fd1,fd2);
2367 win32_read(int fd, void *buf, unsigned int cnt)
2369 return read(fd, buf, cnt);
2373 win32_write(int fd, const void *buf, unsigned int cnt)
2375 return write(fd, buf, cnt);
2379 win32_mkdir(const char *dir, int mode)
2381 return mkdir(dir); /* just ignore mode */
2385 win32_rmdir(const char *dir)
2391 win32_chdir(const char *dir)
2397 create_command_line(const char* command, const char * const *args)
2401 char *cmd, *ptr, *arg;
2402 STRLEN len = strlen(command) + 1;
2404 for (index = 0; (ptr = (char*)args[index]) != NULL; ++index)
2405 len += strlen(ptr) + 1;
2407 New(1310, cmd, len, char);
2409 strcpy(ptr, command);
2411 for (index = 0; (arg = (char*)args[index]) != NULL; ++index) {
2421 qualified_path(const char *cmd)
2425 char *fullcmd, *curfullcmd;
2431 fullcmd = (char*)cmd;
2433 if (*fullcmd == '/' || *fullcmd == '\\')
2440 pathstr = win32_getenv("PATH");
2441 New(0, fullcmd, MAX_PATH+1, char);
2442 curfullcmd = fullcmd;
2447 /* start by appending the name to the current prefix */
2448 strcpy(curfullcmd, cmd);
2449 curfullcmd += cmdlen;
2451 /* if it doesn't end with '.', or has no extension, try adding
2452 * a trailing .exe first */
2453 if (cmd[cmdlen-1] != '.'
2454 && (cmdlen < 4 || cmd[cmdlen-4] != '.'))
2456 strcpy(curfullcmd, ".exe");
2457 res = GetFileAttributes(fullcmd);
2458 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
2463 /* that failed, try the bare name */
2464 res = GetFileAttributes(fullcmd);
2465 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
2468 /* quit if no other path exists, or if cmd already has path */
2469 if (!pathstr || !*pathstr || has_slash)
2472 /* skip leading semis */
2473 while (*pathstr == ';')
2476 /* build a new prefix from scratch */
2477 curfullcmd = fullcmd;
2478 while (*pathstr && *pathstr != ';') {
2479 if (*pathstr == '"') { /* foo;"baz;etc";bar */
2480 pathstr++; /* skip initial '"' */
2481 while (*pathstr && *pathstr != '"') {
2482 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
2483 *curfullcmd++ = *pathstr;
2487 pathstr++; /* skip trailing '"' */
2490 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
2491 *curfullcmd++ = *pathstr;
2496 pathstr++; /* skip trailing semi */
2497 if (curfullcmd > fullcmd /* append a dir separator */
2498 && curfullcmd[-1] != '/' && curfullcmd[-1] != '\\')
2500 *curfullcmd++ = '\\';
2508 /* The following are just place holders.
2509 * Some hosts may provide and environment that the OS is
2510 * not tracking, therefore, these host must provide that
2511 * environment and the current directory to CreateProcess
2521 free_childenv(void* d)
2532 free_childdir(char* d)
2537 /* XXX this needs to be made more compatible with the spawnvp()
2538 * provided by the various RTLs. In particular, searching for
2539 * *.{com,bat,cmd} files (as done by the RTLs) is unimplemented.
2540 * This doesn't significantly affect perl itself, because we
2541 * always invoke things using PERL5SHELL if a direct attempt to
2542 * spawn the executable fails.
2544 * XXX splitting and rejoining the commandline between do_aspawn()
2545 * and win32_spawnvp() could also be avoided.
2549 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
2551 #ifdef USE_RTL_SPAWNVP
2552 return spawnvp(mode, cmdname, (char * const *)argv);
2558 STARTUPINFO StartupInfo;
2559 PROCESS_INFORMATION ProcessInformation;
2562 char *cmd = create_command_line(cmdname, strcmp(cmdname, argv[0]) == 0
2564 char *fullcmd = Nullch;
2566 env = PerlEnv_get_childenv();
2567 dir = PerlEnv_get_childdir();
2570 case P_NOWAIT: /* asynch + remember result */
2571 if (w32_num_children >= MAXIMUM_WAIT_OBJECTS) {
2577 case P_WAIT: /* synchronous execution */
2579 default: /* invalid mode */
2584 memset(&StartupInfo,0,sizeof(StartupInfo));
2585 StartupInfo.cb = sizeof(StartupInfo);
2586 StartupInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
2587 StartupInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
2588 StartupInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
2589 if (StartupInfo.hStdInput != INVALID_HANDLE_VALUE &&
2590 StartupInfo.hStdOutput != INVALID_HANDLE_VALUE &&
2591 StartupInfo.hStdError != INVALID_HANDLE_VALUE)
2593 StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
2596 create |= CREATE_NEW_CONSOLE;
2600 if (!CreateProcess(cmdname, /* search PATH to find executable */
2601 cmd, /* executable, and its arguments */
2602 NULL, /* process attributes */
2603 NULL, /* thread attributes */
2604 TRUE, /* inherit handles */
2605 create, /* creation flags */
2606 (LPVOID)env, /* inherit environment */
2607 dir, /* inherit cwd */
2609 &ProcessInformation))
2611 /* initial NULL argument to CreateProcess() does a PATH
2612 * search, but it always first looks in the directory
2613 * where the current process was started, which behavior
2614 * is undesirable for backward compatibility. So we
2615 * jump through our own hoops by picking out the path
2616 * we really want it to use. */
2618 fullcmd = qualified_path(cmdname);
2629 if (mode == P_NOWAIT) {
2630 /* asynchronous spawn -- store handle, return PID */
2631 w32_child_handles[w32_num_children] = ProcessInformation.hProcess;
2632 ret = w32_child_pids[w32_num_children] = ProcessInformation.dwProcessId;
2636 WaitForSingleObject(ProcessInformation.hProcess, INFINITE);
2637 GetExitCodeProcess(ProcessInformation.hProcess, &ret);
2638 CloseHandle(ProcessInformation.hProcess);
2641 CloseHandle(ProcessInformation.hThread);
2644 PerlEnv_free_childenv(env);
2645 PerlEnv_free_childdir(dir);
2653 win32_execv(const char *cmdname, const char *const *argv)
2655 return execv(cmdname, (char *const *)argv);
2659 win32_execvp(const char *cmdname, const char *const *argv)
2661 return execvp(cmdname, (char *const *)argv);
2665 win32_perror(const char *str)
2671 win32_setbuf(FILE *pf, char *buf)
2677 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
2679 return setvbuf(pf, buf, type, size);
2683 win32_flushall(void)
2689 win32_fcloseall(void)
2695 win32_fgets(char *s, int n, FILE *pf)
2697 return fgets(s, n, pf);
2707 win32_fgetc(FILE *pf)
2713 win32_putc(int c, FILE *pf)
2719 win32_puts(const char *s)
2731 win32_putchar(int c)
2738 #ifndef USE_PERL_SBRK
2740 static char *committed = NULL;
2741 static char *base = NULL;
2742 static char *reserved = NULL;
2743 static char *brk = NULL;
2744 static DWORD pagesize = 0;
2745 static DWORD allocsize = 0;
2753 GetSystemInfo(&info);
2754 /* Pretend page size is larger so we don't perpetually
2755 * call the OS to commit just one page ...
2757 pagesize = info.dwPageSize << 3;
2758 allocsize = info.dwAllocationGranularity;
2760 /* This scheme fails eventually if request for contiguous
2761 * block is denied so reserve big blocks - this is only
2762 * address space not memory ...
2764 if (brk+need >= reserved)
2766 DWORD size = 64*1024*1024;
2768 if (committed && reserved && committed < reserved)
2770 /* Commit last of previous chunk cannot span allocations */
2771 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
2773 committed = reserved;
2775 /* Reserve some (more) space
2776 * Note this is a little sneaky, 1st call passes NULL as reserved
2777 * so lets system choose where we start, subsequent calls pass
2778 * the old end address so ask for a contiguous block
2780 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
2783 reserved = addr+size;
2798 if (brk > committed)
2800 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
2801 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
2816 win32_malloc(size_t size)
2818 return malloc(size);
2822 win32_calloc(size_t numitems, size_t size)
2824 return calloc(numitems,size);
2828 win32_realloc(void *block, size_t size)
2830 return realloc(block,size);
2834 win32_free(void *block)
2841 win32_open_osfhandle(long handle, int flags)
2843 return _open_osfhandle(handle, flags);
2847 win32_get_osfhandle(int fd)
2849 return _get_osfhandle(fd);
2853 win32_dynaload(const char* filename)
2858 WCHAR wfilename[MAX_PATH];
2859 A2WHELPER(filename, wfilename, sizeof(wfilename));
2860 hModule = LoadLibraryExW(wfilename, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
2863 hModule = LoadLibraryExA(filename, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
2869 win32_add_host(char *nameId, void *data)
2872 * This must be called before the script is parsed,
2873 * therefore no locking of threads is needed
2876 struct host_link *link;
2877 New(1314, link, 1, struct host_link);
2878 link->host_data = data;
2879 link->nameId = nameId;
2880 link->next = w32_host_link;
2881 w32_host_link = link;
2886 win32_get_host_data(char *nameId)
2889 struct host_link *link = w32_host_link;
2891 if(strEQ(link->nameId, nameId))
2892 return link->host_data;
2906 SV *sv = sv_newmortal();
2907 /* Make one call with zero size - return value is required size */
2908 DWORD len = GetCurrentDirectory((DWORD)0,NULL);
2909 SvUPGRADE(sv,SVt_PV);
2911 SvCUR(sv) = GetCurrentDirectory((DWORD) SvLEN(sv), SvPVX(sv));
2914 * then it worked, set PV valid,
2915 * else leave it 'undef'
2931 Perl_croak(aTHX_ "usage: Win32::SetCurrentDirectory($cwd)");
2932 if (SetCurrentDirectory(SvPV_nolen(ST(0))))
2939 XS(w32_GetNextAvailDrive)
2943 char root[] = "_:\\";
2948 if (GetDriveType(root) == 1) {
2957 XS(w32_GetLastError)
2961 XSRETURN_IV(GetLastError());
2965 XS(w32_SetLastError)
2969 Perl_croak(aTHX_ "usage: Win32::SetLastError($error)");
2970 SetLastError(SvIV(ST(0)));
2978 char *name = getlogin_buffer;
2979 DWORD size = sizeof(getlogin_buffer);
2981 if (GetUserName(name,&size)) {
2982 /* size includes NULL */
2983 ST(0) = sv_2mortal(newSVpvn(name,size-1));
2993 char name[MAX_COMPUTERNAME_LENGTH+1];
2994 DWORD size = sizeof(name);
2996 if (GetComputerName(name,&size)) {
2997 /* size does NOT include NULL :-( */
2998 ST(0) = sv_2mortal(newSVpvn(name,size));
3009 #ifndef HAS_NETWKSTAGETINFO
3010 /* mingw32 (and Win95) don't have NetWksta*(), so do it the old way */
3012 DWORD size = sizeof(name);
3014 if (GetUserName(name,&size)) {
3016 DWORD sidlen = sizeof(sid);
3018 DWORD dnamelen = sizeof(dname);
3020 if (LookupAccountName(NULL, name, (PSID)&sid, &sidlen,
3021 dname, &dnamelen, &snu)) {
3022 XSRETURN_PV(dname); /* all that for this */
3026 /* this way is more reliable, in case user has a local account.
3027 * XXX need dynamic binding of netapi32.dll symbols or this will fail on
3028 * Win95. Probably makes more sense to move it into libwin32. */
3030 DWORD dnamelen = sizeof(dname);
3031 PWKSTA_INFO_100 pwi;
3033 if (NERR_Success == NetWkstaGetInfo(NULL, 100, (LPBYTE*)&pwi)) {
3034 if (pwi->wki100_langroup && *(pwi->wki100_langroup)) {
3035 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_langroup,
3036 -1, (LPSTR)dname, dnamelen, NULL, NULL);
3039 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_computername,
3040 -1, (LPSTR)dname, dnamelen, NULL, NULL);
3042 NetApiBufferFree(pwi);
3054 DWORD flags, filecomplen;
3055 if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
3056 &flags, fsname, sizeof(fsname))) {
3057 if (GIMME_V == G_ARRAY) {
3058 XPUSHs(sv_2mortal(newSVpvn(fsname,strlen(fsname))));
3059 XPUSHs(sv_2mortal(newSViv(flags)));
3060 XPUSHs(sv_2mortal(newSViv(filecomplen)));
3065 XSRETURN_PV(fsname);
3071 XS(w32_GetOSVersion)
3074 OSVERSIONINFO osver;
3076 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
3077 if (GetVersionEx(&osver)) {
3078 XPUSHs(newSVpvn(osver.szCSDVersion, strlen(osver.szCSDVersion)));
3079 XPUSHs(newSViv(osver.dwMajorVersion));
3080 XPUSHs(newSViv(osver.dwMinorVersion));
3081 XPUSHs(newSViv(osver.dwBuildNumber));
3082 XPUSHs(newSViv(osver.dwPlatformId));
3094 XSRETURN_IV(IsWinNT());
3102 XSRETURN_IV(IsWin95());
3106 XS(w32_FormatMessage)
3113 Perl_croak(aTHX_ "usage: Win32::FormatMessage($errno)");
3115 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
3116 &source, SvIV(ST(0)), 0,
3117 msgbuf, sizeof(msgbuf)-1, NULL))
3118 XSRETURN_PV(msgbuf);
3128 PROCESS_INFORMATION stProcInfo;
3129 STARTUPINFO stStartInfo;
3130 BOOL bSuccess = FALSE;
3133 Perl_croak(aTHX_ "usage: Win32::Spawn($cmdName, $args, $PID)");
3135 cmd = SvPV_nolen(ST(0));
3136 args = SvPV_nolen(ST(1));
3138 memset(&stStartInfo, 0, sizeof(stStartInfo)); /* Clear the block */
3139 stStartInfo.cb = sizeof(stStartInfo); /* Set the structure size */
3140 stStartInfo.dwFlags = STARTF_USESHOWWINDOW; /* Enable wShowWindow control */
3141 stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE; /* Start min (normal) */
3144 cmd, /* Image path */
3145 args, /* Arguments for command line */
3146 NULL, /* Default process security */
3147 NULL, /* Default thread security */
3148 FALSE, /* Must be TRUE to use std handles */
3149 NORMAL_PRIORITY_CLASS, /* No special scheduling */
3150 NULL, /* Inherit our environment block */
3151 NULL, /* Inherit our currrent directory */
3152 &stStartInfo, /* -> Startup info */
3153 &stProcInfo)) /* <- Process info (if OK) */
3155 CloseHandle(stProcInfo.hThread);/* library source code does this. */
3156 sv_setiv(ST(2), stProcInfo.dwProcessId);
3159 XSRETURN_IV(bSuccess);
3163 XS(w32_GetTickCount)
3166 DWORD msec = GetTickCount();
3174 XS(w32_GetShortPathName)
3181 Perl_croak(aTHX_ "usage: Win32::GetShortPathName($longPathName)");
3183 shortpath = sv_mortalcopy(ST(0));
3184 SvUPGRADE(shortpath, SVt_PV);
3185 /* src == target is allowed */
3187 len = GetShortPathName(SvPVX(shortpath),
3190 } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
3192 SvCUR_set(shortpath,len);
3200 XS(w32_GetFullPathName)
3209 Perl_croak(aTHX_ "usage: Win32::GetFullPathName($filename)");
3212 fullpath = sv_mortalcopy(filename);
3213 SvUPGRADE(fullpath, SVt_PV);
3215 len = GetFullPathName(SvPVX(filename),
3219 } while (len >= SvLEN(fullpath) && sv_grow(fullpath,len+1));
3221 if (GIMME_V == G_ARRAY) {
3223 XST_mPV(1,filepart);
3224 len = filepart - SvPVX(fullpath);
3227 SvCUR_set(fullpath,len);
3235 XS(w32_GetLongPathName)
3239 char tmpbuf[MAX_PATH+1];
3244 Perl_croak(aTHX_ "usage: Win32::GetLongPathName($pathname)");
3247 pathstr = SvPV(path,len);
3248 strcpy(tmpbuf, pathstr);
3249 pathstr = win32_longpath(tmpbuf);
3251 ST(0) = sv_2mortal(newSVpvn(pathstr, strlen(pathstr)));
3262 Perl_croak(aTHX_ "usage: Win32::Sleep($milliseconds)");
3272 Perl_croak(aTHX_ "usage: Win32::CopyFile($from, $to, $overwrite)");
3273 if (CopyFile(SvPV_nolen(ST(0)), SvPV_nolen(ST(1)), !SvTRUE(ST(2))))
3279 Perl_init_os_extras(void)
3282 char *file = __FILE__;
3285 w32_perlshell_tokens = Nullch;
3286 w32_perlshell_items = -1;
3287 w32_fdpid = newAV(); /* XXX needs to be in Perl_win32_init()? */
3288 New(1313, w32_children, 1, child_tab);
3289 w32_num_children = 0;
3291 /* these names are Activeware compatible */
3292 newXS("Win32::GetCwd", w32_GetCwd, file);
3293 newXS("Win32::SetCwd", w32_SetCwd, file);
3294 newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
3295 newXS("Win32::GetLastError", w32_GetLastError, file);
3296 newXS("Win32::SetLastError", w32_SetLastError, file);
3297 newXS("Win32::LoginName", w32_LoginName, file);
3298 newXS("Win32::NodeName", w32_NodeName, file);
3299 newXS("Win32::DomainName", w32_DomainName, file);
3300 newXS("Win32::FsType", w32_FsType, file);
3301 newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
3302 newXS("Win32::IsWinNT", w32_IsWinNT, file);
3303 newXS("Win32::IsWin95", w32_IsWin95, file);
3304 newXS("Win32::FormatMessage", w32_FormatMessage, file);
3305 newXS("Win32::Spawn", w32_Spawn, file);
3306 newXS("Win32::GetTickCount", w32_GetTickCount, file);
3307 newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
3308 newXS("Win32::GetFullPathName", w32_GetFullPathName, file);
3309 newXS("Win32::GetLongPathName", w32_GetLongPathName, file);
3310 newXS("Win32::CopyFile", w32_CopyFile, file);
3311 newXS("Win32::Sleep", w32_Sleep, file);
3313 /* XXX Bloat Alert! The following Activeware preloads really
3314 * ought to be part of Win32::Sys::*, so they're not included
3317 /* LookupAccountName
3319 * InitiateSystemShutdown
3320 * AbortSystemShutdown
3321 * ExpandEnvrironmentStrings
3326 Perl_win32_init(int *argcp, char ***argvp)
3328 /* Disable floating point errors, Perl will trap the ones we
3329 * care about. VC++ RTL defaults to switching these off
3330 * already, but the Borland RTL doesn't. Since we don't
3331 * want to be at the vendor's whim on the default, we set
3332 * it explicitly here.
3334 #if !defined(_ALPHA_) && !defined(__GNUC__)
3335 _control87(MCW_EM, MCW_EM);
3340 #ifdef USE_BINMODE_SCRIPTS
3343 win32_strip_return(SV *sv)
3345 char *s = SvPVX(sv);
3346 char *e = s+SvCUR(sv);
3350 if (*s == '\r' && s[1] == '\n')
3360 SvCUR_set(sv,d-SvPVX(sv));