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:
69 #if defined(__MINGW32__)
73 #if defined(__BORLANDC__)
75 # define _utimbuf utimbuf
80 #define EXECF_SPAWN_NOWAIT 3
82 #if defined(PERL_IMPLICIT_SYS)
83 # undef win32_get_privlib
84 # define win32_get_privlib g_win32_get_privlib
85 # undef win32_get_sitelib
86 # define win32_get_sitelib g_win32_get_sitelib
88 # define do_spawn g_do_spawn
90 # define getlogin g_getlogin
93 #if defined(PERL_OBJECT)
95 # define do_aspawn g_do_aspawn
97 # define Perl_do_exec g_do_exec
100 static void get_shell(void);
101 static long tokenize(const char *str, char **dest, char ***destv);
102 int do_spawn2(char *cmd, int exectype);
103 static BOOL has_shell_metachars(char *ptr);
104 static long filetime_to_clock(PFILETIME ft);
105 static BOOL filetime_from_time(PFILETIME ft, time_t t);
106 static char * get_emd_part(SV **leading, char *trailing, ...);
107 static void remove_dead_process(long deceased);
108 static long find_pid(int pid);
109 static char * qualified_path(const char *cmd);
111 HANDLE w32_perldll_handle = INVALID_HANDLE_VALUE;
112 char w32_module_name[MAX_PATH+1];
113 static DWORD w32_platform = (DWORD)-1;
116 # ifdef USE_DECLSPEC_THREAD
117 __declspec(thread) char strerror_buffer[512];
118 __declspec(thread) char getlogin_buffer[128];
119 __declspec(thread) char w32_perllib_root[MAX_PATH+1];
120 # ifdef HAVE_DES_FCRYPT
121 __declspec(thread) char crypt_buffer[30];
124 # define strerror_buffer (thr->i.Wstrerror_buffer)
125 # define getlogin_buffer (thr->i.Wgetlogin_buffer)
126 # define w32_perllib_root (thr->i.Ww32_perllib_root)
127 # define crypt_buffer (thr->i.Wcrypt_buffer)
130 static char strerror_buffer[512];
131 static char getlogin_buffer[128];
132 static char w32_perllib_root[MAX_PATH+1];
133 # ifdef HAVE_DES_FCRYPT
134 static char crypt_buffer[30];
141 return (win32_os_id() == VER_PLATFORM_WIN32_WINDOWS);
147 return (win32_os_id() == VER_PLATFORM_WIN32_NT);
150 /* *svp (if non-NULL) is expected to be POK (valid allocated SvPVX(*svp)) */
152 get_regstr_from(HKEY hkey, const char *valuename, SV **svp)
154 /* Retrieve a REG_SZ or REG_EXPAND_SZ from the registry */
157 const char *subkey = "Software\\Perl";
161 retval = RegOpenKeyEx(hkey, subkey, 0, KEY_READ, &handle);
162 if (retval == ERROR_SUCCESS) {
164 retval = RegQueryValueEx(handle, valuename, 0, &type, NULL, &datalen);
165 if (retval == ERROR_SUCCESS && type == REG_SZ) {
168 *svp = sv_2mortal(newSVpvn("",0));
169 SvGROW(*svp, datalen);
170 retval = RegQueryValueEx(handle, valuename, 0, NULL,
171 (PBYTE)SvPVX(*svp), &datalen);
172 if (retval == ERROR_SUCCESS) {
174 SvCUR_set(*svp,datalen-1);
182 /* *svp (if non-NULL) is expected to be POK (valid allocated SvPVX(*svp)) */
184 get_regstr(const char *valuename, SV **svp)
186 char *str = get_regstr_from(HKEY_CURRENT_USER, valuename, svp);
188 str = get_regstr_from(HKEY_LOCAL_MACHINE, valuename, svp);
192 /* *prev_pathp (if non-NULL) is expected to be POK (valid allocated SvPVX(sv)) */
194 get_emd_part(SV **prev_pathp, char *trailing_path, ...)
198 char mod_name[MAX_PATH+1];
202 int oldsize, newsize;
204 va_start(ap, trailing_path);
205 strip = va_arg(ap, char *);
207 sprintf(base, "%5.3f",
208 (double)PERL_REVISION + ((double)PERL_VERSION / (double)1000));
210 if (!*w32_module_name) {
211 GetModuleFileName((HMODULE)((w32_perldll_handle == INVALID_HANDLE_VALUE)
212 ? GetModuleHandle(NULL)
213 : w32_perldll_handle),
214 w32_module_name, sizeof(w32_module_name));
216 /* try to get full path to binary (which may be mangled when perl is
217 * run from a 16-bit app) */
218 /*PerlIO_printf(Perl_debug_log, "Before %s\n", w32_module_name);*/
219 (void)win32_longpath(w32_module_name);
220 /*PerlIO_printf(Perl_debug_log, "After %s\n", w32_module_name);*/
222 /* normalize to forward slashes */
223 ptr = w32_module_name;
230 strcpy(mod_name, w32_module_name);
231 ptr = strrchr(mod_name, '/');
232 while (ptr && strip) {
233 /* look for directories to skip back */
236 ptr = strrchr(mod_name, '/');
237 /* avoid stripping component if there is no slash,
238 * or it doesn't match ... */
239 if (!ptr || stricmp(ptr+1, strip) != 0) {
240 /* ... but not if component matches 5.00X* */
241 if (!ptr || !(*strip == '5' && *(ptr+1) == '5'
242 && strncmp(strip, base, 5) == 0
243 && strncmp(ptr+1, base, 5) == 0))
249 strip = va_arg(ap, char *);
257 strcpy(++ptr, trailing_path);
259 /* only add directory if it exists */
260 if (GetFileAttributes(mod_name) != (DWORD) -1) {
261 /* directory exists */
264 *prev_pathp = sv_2mortal(newSVpvn("",0));
265 sv_catpvn(*prev_pathp, ";", 1);
266 sv_catpv(*prev_pathp, mod_name);
267 return SvPVX(*prev_pathp);
274 win32_get_privlib(char *pl)
277 char *stdlib = "lib";
278 char buffer[MAX_PATH+1];
281 /* $stdlib = $HKCU{"lib-$]"} || $HKLM{"lib-$]"} || $HKCU{"lib"} || $HKLM{"lib"} || ""; */
282 sprintf(buffer, "%s-%s", stdlib, pl);
283 if (!get_regstr(buffer, &sv))
284 (void)get_regstr(stdlib, &sv);
286 /* $stdlib .= ";$EMD/../../lib" */
287 return get_emd_part(&sv, stdlib, ARCHNAME, "bin", Nullch);
291 win32_get_sitelib(char *pl)
294 char *sitelib = "sitelib";
296 char pathstr[MAX_PATH+1];
302 /* $HKCU{"sitelib-$]"} || $HKLM{"sitelib-$]"} . ---; */
303 sprintf(regstr, "%s-%s", sitelib, pl);
304 (void)get_regstr(regstr, &sv1);
307 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/site/$]/lib"; */
308 sprintf(pathstr, "site/%s/lib", pl);
309 (void)get_emd_part(&sv1, pathstr, ARCHNAME, "bin", pl, Nullch);
310 if (!sv1 && strlen(pl) == 7) {
311 /* pl may have been SUBVERSION-specific; try again without
313 sprintf(pathstr, "site/%.5s/lib", pl);
314 (void)get_emd_part(&sv1, pathstr, ARCHNAME, "bin", pl, Nullch);
317 /* $HKCU{'sitelib'} || $HKLM{'sitelib'} . ---; */
318 (void)get_regstr(sitelib, &sv2);
321 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/site/lib"; */
322 (void)get_emd_part(&sv2, "site/lib", ARCHNAME, "bin", pl, Nullch);
331 sv_catpvn(sv1, ";", 1);
339 has_shell_metachars(char *ptr)
345 * Scan string looking for redirection (< or >) or pipe
346 * characters (|) that are not in a quoted string.
347 * Shell variable interpolation (%VAR%) can also happen inside strings.
379 #if !defined(PERL_IMPLICIT_SYS)
380 /* since the current process environment is being updated in util.c
381 * the library functions will get the correct environment
384 Perl_my_popen(pTHX_ char *cmd, char *mode)
387 #define fixcmd(x) { \
388 char *pspace = strchr((x),' '); \
391 while (p < pspace) { \
402 PERL_FLUSHALL_FOR_CHILD;
403 return win32_popen(cmd, mode);
407 Perl_my_pclose(pTHX_ PerlIO *fp)
409 return win32_pclose(fp);
413 DllExport unsigned long
416 static OSVERSIONINFO osver;
418 if (osver.dwPlatformId != w32_platform) {
419 memset(&osver, 0, sizeof(OSVERSIONINFO));
420 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
421 GetVersionEx(&osver);
422 w32_platform = osver.dwPlatformId;
424 return (unsigned long)w32_platform;
427 /* Tokenize a string. Words are null-separated, and the list
428 * ends with a doubled null. Any character (except null and
429 * including backslash) may be escaped by preceding it with a
430 * backslash (the backslash will be stripped).
431 * Returns number of words in result buffer.
434 tokenize(const char *str, char **dest, char ***destv)
436 char *retstart = Nullch;
437 char **retvstart = 0;
441 int slen = strlen(str);
443 register char **retv;
444 New(1307, ret, slen+2, char);
445 New(1308, retv, (slen+3)/2, char*);
453 if (*ret == '\\' && *str)
455 else if (*ret == ' ') {
471 retvstart[items] = Nullch;
484 if (!w32_perlshell_tokens) {
485 /* we don't use COMSPEC here for two reasons:
486 * 1. the same reason perl on UNIX doesn't use SHELL--rampant and
487 * uncontrolled unportability of the ensuing scripts.
488 * 2. PERL5SHELL could be set to a shell that may not be fit for
489 * interactive use (which is what most programs look in COMSPEC
492 const char* defaultshell = (IsWinNT()
493 ? "cmd.exe /x/c" : "command.com /c");
494 const char *usershell = getenv("PERL5SHELL");
495 w32_perlshell_items = tokenize(usershell ? usershell : defaultshell,
496 &w32_perlshell_tokens,
502 do_aspawn(void *vreally, void **vmark, void **vsp)
505 SV *really = (SV*)vreally;
506 SV **mark = (SV**)vmark;
518 New(1306, argv, (sp - mark) + w32_perlshell_items + 2, char*);
520 if (SvNIOKp(*(mark+1)) && !SvPOKp(*(mark+1))) {
525 while (++mark <= sp) {
526 if (*mark && (str = SvPV_nolen(*mark)))
533 status = win32_spawnvp(flag,
534 (const char*)(really ? SvPV_nolen(really) : argv[0]),
535 (const char* const*)argv);
537 if (status < 0 && (errno == ENOEXEC || errno == ENOENT)) {
538 /* possible shell-builtin, invoke with shell */
540 sh_items = w32_perlshell_items;
542 argv[index+sh_items] = argv[index];
543 while (--sh_items >= 0)
544 argv[sh_items] = w32_perlshell_vec[sh_items];
546 status = win32_spawnvp(flag,
547 (const char*)(really ? SvPV_nolen(really) : argv[0]),
548 (const char* const*)argv);
551 if (flag != P_NOWAIT) {
554 if (ckWARN(WARN_EXEC))
555 Perl_warner(aTHX_ WARN_EXEC, "Can't spawn \"%s\": %s", argv[0], strerror(errno));
560 PL_statusvalue = status;
567 do_spawn2(char *cmd, int exectype)
574 BOOL needToTry = TRUE;
577 /* Save an extra exec if possible. See if there are shell
578 * metacharacters in it */
579 if (!has_shell_metachars(cmd)) {
580 New(1301,argv, strlen(cmd) / 2 + 2, char*);
581 New(1302,cmd2, strlen(cmd) + 1, char);
584 for (s = cmd2; *s;) {
585 while (*s && isSPACE(*s))
589 while (*s && !isSPACE(*s))
598 status = win32_spawnvp(P_WAIT, argv[0],
599 (const char* const*)argv);
601 case EXECF_SPAWN_NOWAIT:
602 status = win32_spawnvp(P_NOWAIT, argv[0],
603 (const char* const*)argv);
606 status = win32_execvp(argv[0], (const char* const*)argv);
609 if (status != -1 || errno == 0)
619 New(1306, argv, w32_perlshell_items + 2, char*);
620 while (++i < w32_perlshell_items)
621 argv[i] = w32_perlshell_vec[i];
626 status = win32_spawnvp(P_WAIT, argv[0],
627 (const char* const*)argv);
629 case EXECF_SPAWN_NOWAIT:
630 status = win32_spawnvp(P_NOWAIT, argv[0],
631 (const char* const*)argv);
634 status = win32_execvp(argv[0], (const char* const*)argv);
640 if (exectype != EXECF_SPAWN_NOWAIT) {
643 if (ckWARN(WARN_EXEC))
644 Perl_warner(aTHX_ WARN_EXEC, "Can't %s \"%s\": %s",
645 (exectype == EXECF_EXEC ? "exec" : "spawn"),
646 cmd, strerror(errno));
651 PL_statusvalue = status;
659 return do_spawn2(cmd, EXECF_SPAWN);
663 do_spawn_nowait(char *cmd)
665 return do_spawn2(cmd, EXECF_SPAWN_NOWAIT);
669 Perl_do_exec(pTHX_ char *cmd)
671 do_spawn2(cmd, EXECF_EXEC);
675 /* The idea here is to read all the directory names into a string table
676 * (separated by nulls) and when one of the other dir functions is called
677 * return the pointer to the current file name.
680 win32_opendir(char *filename)
686 char scanname[MAX_PATH+3];
688 WIN32_FIND_DATAA aFindData;
689 WIN32_FIND_DATAW wFindData;
691 char buffer[MAX_PATH*2];
692 WCHAR wbuffer[MAX_PATH];
695 len = strlen(filename);
699 /* check to see if filename is a directory */
700 if (win32_stat(filename, &sbuf) < 0 || !S_ISDIR(sbuf.st_mode))
703 /* Get us a DIR structure */
704 Newz(1303, dirp, 1, DIR);
706 /* Create the search pattern */
707 strcpy(scanname, filename);
709 /* bare drive name means look in cwd for drive */
710 if (len == 2 && isALPHA(scanname[0]) && scanname[1] == ':') {
711 scanname[len++] = '.';
712 scanname[len++] = '/';
714 else if (scanname[len-1] != '/' && scanname[len-1] != '\\') {
715 scanname[len++] = '/';
717 scanname[len++] = '*';
718 scanname[len] = '\0';
720 /* do the FindFirstFile call */
722 A2WHELPER(scanname, wbuffer, sizeof(wbuffer));
723 fh = FindFirstFileW(wbuffer, &wFindData);
726 fh = FindFirstFileA(scanname, &aFindData);
729 if (fh == INVALID_HANDLE_VALUE) {
730 DWORD err = GetLastError();
731 /* FindFirstFile() fails on empty drives! */
733 case ERROR_FILE_NOT_FOUND:
735 case ERROR_NO_MORE_FILES:
736 case ERROR_PATH_NOT_FOUND:
739 case ERROR_NOT_ENOUGH_MEMORY:
750 /* now allocate the first part of the string table for
751 * the filenames that we find.
754 W2AHELPER(wFindData.cFileName, buffer, sizeof(buffer));
758 ptr = aFindData.cFileName;
765 New(1304, dirp->start, dirp->size, char);
766 strcpy(dirp->start, ptr);
768 dirp->end = dirp->curr = dirp->start;
774 /* Readdir just returns the current string pointer and bumps the
775 * string pointer to the nDllExport entry.
777 DllExport struct direct *
778 win32_readdir(DIR *dirp)
783 /* first set up the structure to return */
784 len = strlen(dirp->curr);
785 strcpy(dirp->dirstr.d_name, dirp->curr);
786 dirp->dirstr.d_namlen = len;
789 dirp->dirstr.d_ino = dirp->curr - dirp->start;
791 /* Now set up for the next call to readdir */
792 dirp->curr += len + 1;
793 if (dirp->curr >= dirp->end) {
797 WIN32_FIND_DATAW wFindData;
798 WIN32_FIND_DATAA aFindData;
799 char buffer[MAX_PATH*2];
801 /* finding the next file that matches the wildcard
802 * (which should be all of them in this directory!).
805 res = FindNextFileW(dirp->handle, &wFindData);
807 W2AHELPER(wFindData.cFileName, buffer, sizeof(buffer));
812 res = FindNextFileA(dirp->handle, &aFindData);
814 ptr = aFindData.cFileName;
817 long endpos = dirp->end - dirp->start;
818 long newsize = endpos + strlen(ptr) + 1;
819 /* bump the string table size by enough for the
820 * new name and it's null terminator */
821 while (newsize > dirp->size) {
822 long curpos = dirp->curr - dirp->start;
824 Renew(dirp->start, dirp->size, char);
825 dirp->curr = dirp->start + curpos;
827 strcpy(dirp->start + endpos, ptr);
828 dirp->end = dirp->start + newsize;
834 return &(dirp->dirstr);
840 /* Telldir returns the current string pointer position */
842 win32_telldir(DIR *dirp)
844 return (dirp->curr - dirp->start);
848 /* Seekdir moves the string pointer to a previously saved position
849 * (returned by telldir).
852 win32_seekdir(DIR *dirp, long loc)
854 dirp->curr = dirp->start + loc;
857 /* Rewinddir resets the string pointer to the start */
859 win32_rewinddir(DIR *dirp)
861 dirp->curr = dirp->start;
864 /* free the memory allocated by opendir */
866 win32_closedir(DIR *dirp)
869 if (dirp->handle != INVALID_HANDLE_VALUE)
870 FindClose(dirp->handle);
871 Safefree(dirp->start);
884 * Just pretend that everyone is a superuser. NT will let us know if
885 * we don\'t really have permission to do something.
888 #define ROOT_UID ((uid_t)0)
889 #define ROOT_GID ((gid_t)0)
918 return (auid == ROOT_UID ? 0 : -1);
924 return (agid == ROOT_GID ? 0 : -1);
931 char *buf = getlogin_buffer;
932 DWORD size = sizeof(getlogin_buffer);
933 if (GetUserName(buf,&size))
939 chown(const char *path, uid_t owner, gid_t group)
950 for (child = 0 ; child < w32_num_children ; ++child) {
951 if (w32_child_pids[child] == pid)
958 remove_dead_process(long child)
962 CloseHandle(w32_child_handles[child]);
963 Copy(&w32_child_handles[child+1], &w32_child_handles[child],
964 (w32_num_children-child-1), HANDLE);
965 Copy(&w32_child_pids[child+1], &w32_child_pids[child],
966 (w32_num_children-child-1), DWORD);
972 win32_kill(int pid, int sig)
975 hProcess = OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid);
976 if (hProcess && TerminateProcess(hProcess, sig))
977 CloseHandle(hProcess);
989 DllExport unsigned int
990 win32_sleep(unsigned int t)
997 win32_stat(const char *path, struct stat *buffer)
1001 int l = strlen(path);
1003 WCHAR wbuffer[MAX_PATH];
1006 switch(path[l - 1]) {
1007 /* FindFirstFile() and stat() are buggy with a trailing
1008 * backslash, so change it to a forward slash :-( */
1010 strncpy(t, path, l-1);
1015 /* FindFirstFile() is buggy with "x:", so add a dot :-( */
1017 if (l == 2 && isALPHA(path[0])) {
1018 t[0] = path[0]; t[1] = ':'; t[2] = '.'; t[3] = '\0';
1026 A2WHELPER(path, wbuffer, sizeof(wbuffer));
1027 res = _wstat(wbuffer, (struct _stat *)buffer);
1030 res = stat(path, buffer);
1033 /* CRT is buggy on sharenames, so make sure it really isn't.
1034 * XXX using GetFileAttributesEx() will enable us to set
1035 * buffer->st_*time (but note that's not available on the
1036 * Windows of 1995) */
1039 r = GetFileAttributesW(wbuffer);
1042 r = GetFileAttributesA(path);
1044 if (r != 0xffffffff && (r & FILE_ATTRIBUTE_DIRECTORY)) {
1045 /* buffer may still contain old garbage since stat() failed */
1046 Zero(buffer, 1, struct stat);
1047 buffer->st_mode = S_IFDIR | S_IREAD;
1049 if (!(r & FILE_ATTRIBUTE_READONLY))
1050 buffer->st_mode |= S_IWRITE | S_IEXEC;
1055 if (l == 3 && isALPHA(path[0]) && path[1] == ':'
1056 && (path[2] == '\\' || path[2] == '/'))
1058 /* The drive can be inaccessible, some _stat()s are buggy */
1060 ? !GetVolumeInformationW(wbuffer,NULL,0,NULL,NULL,NULL,NULL,0)
1061 : !GetVolumeInformationA(path,NULL,0,NULL,NULL,NULL,NULL,0)) {
1067 if (S_ISDIR(buffer->st_mode))
1068 buffer->st_mode |= S_IWRITE | S_IEXEC;
1069 else if (S_ISREG(buffer->st_mode)) {
1070 if (l >= 4 && path[l-4] == '.') {
1071 const char *e = path + l - 3;
1072 if (strnicmp(e,"exe",3)
1073 && strnicmp(e,"bat",3)
1074 && strnicmp(e,"com",3)
1075 && (IsWin95() || strnicmp(e,"cmd",3)))
1076 buffer->st_mode &= ~S_IEXEC;
1078 buffer->st_mode |= S_IEXEC;
1081 buffer->st_mode &= ~S_IEXEC;
1088 /* Find the longname of a given path. path is destructively modified.
1089 * It should have space for at least MAX_PATH characters. */
1091 win32_longpath(char *path)
1093 WIN32_FIND_DATA fdata;
1095 char tmpbuf[MAX_PATH+1];
1096 char *tmpstart = tmpbuf;
1103 if (isALPHA(path[0]) && path[1] == ':' &&
1104 (path[2] == '/' || path[2] == '\\'))
1107 *tmpstart++ = path[0];
1111 else if ((path[0] == '/' || path[0] == '\\') &&
1112 (path[1] == '/' || path[1] == '\\'))
1115 *tmpstart++ = path[0];
1116 *tmpstart++ = path[1];
1117 /* copy machine name */
1118 while (*start && *start != '/' && *start != '\\')
1119 *tmpstart++ = *start++;
1121 *tmpstart++ = *start;
1123 /* copy share name */
1124 while (*start && *start != '/' && *start != '\\')
1125 *tmpstart++ = *start++;
1129 if (sep == '/' || sep == '\\')
1133 /* walk up to slash */
1134 while (*start && *start != '/' && *start != '\\')
1137 /* discard doubled slashes */
1138 while (*start && (start[1] == '/' || start[1] == '\\'))
1142 /* stop and find full name of component */
1144 fhand = FindFirstFile(path,&fdata);
1145 if (fhand != INVALID_HANDLE_VALUE) {
1146 strcpy(tmpstart, fdata.cFileName);
1147 tmpstart += strlen(fdata.cFileName);
1155 /* failed a step, just return without side effects */
1156 /*PerlIO_printf(Perl_debug_log, "Failed to find %s\n", path);*/
1161 strcpy(path,tmpbuf);
1165 #ifndef USE_WIN32_RTL_ENV
1168 win32_getenv(const char *name)
1171 WCHAR wBuffer[MAX_PATH];
1173 SV *curitem = Nullsv;
1176 A2WHELPER(name, wBuffer, sizeof(wBuffer));
1177 needlen = GetEnvironmentVariableW(wBuffer, NULL, 0);
1180 needlen = GetEnvironmentVariableA(name,NULL,0);
1182 curitem = sv_2mortal(newSVpvn("", 0));
1186 SvGROW(curitem, (needlen+1)*sizeof(WCHAR));
1187 needlen = GetEnvironmentVariableW(wBuffer,
1188 (WCHAR*)SvPVX(curitem),
1190 } while (needlen >= SvLEN(curitem)/sizeof(WCHAR));
1191 SvCUR_set(curitem, (needlen*sizeof(WCHAR))+1);
1192 acuritem = sv_2mortal(newSVsv(curitem));
1193 W2AHELPER((WCHAR*)SvPVX(acuritem), SvPVX(curitem), SvCUR(curitem));
1197 SvGROW(curitem, needlen+1);
1198 needlen = GetEnvironmentVariableA(name,SvPVX(curitem),
1200 } while (needlen >= SvLEN(curitem));
1201 SvCUR_set(curitem, needlen);
1205 /* allow any environment variables that begin with 'PERL'
1206 to be stored in the registry */
1207 if (strncmp(name, "PERL", 4) == 0)
1208 (void)get_regstr(name, &curitem);
1210 if (curitem && SvCUR(curitem))
1211 return SvPVX(curitem);
1217 win32_putenv(const char *name)
1224 int length, relval = -1;
1228 length = strlen(name)+1;
1229 New(1309,wCuritem,length,WCHAR);
1230 A2WHELPER(name, wCuritem, length*sizeof(WCHAR));
1231 wVal = wcschr(wCuritem, '=');
1234 if(SetEnvironmentVariableW(wCuritem, *wVal ? wVal : NULL))
1240 New(1309,curitem,strlen(name)+1,char);
1241 strcpy(curitem, name);
1242 val = strchr(curitem, '=');
1244 /* The sane way to deal with the environment.
1245 * Has these advantages over putenv() & co.:
1246 * * enables us to store a truly empty value in the
1247 * environment (like in UNIX).
1248 * * we don't have to deal with RTL globals, bugs and leaks.
1250 * Why you may want to enable USE_WIN32_RTL_ENV:
1251 * * environ[] and RTL functions will not reflect changes,
1252 * which might be an issue if extensions want to access
1253 * the env. via RTL. This cuts both ways, since RTL will
1254 * not see changes made by extensions that call the Win32
1255 * functions directly, either.
1259 if(SetEnvironmentVariableA(curitem, *val ? val : NULL))
1271 filetime_to_clock(PFILETIME ft)
1273 __int64 qw = ft->dwHighDateTime;
1275 qw |= ft->dwLowDateTime;
1276 qw /= 10000; /* File time ticks at 0.1uS, clock at 1mS */
1281 win32_times(struct tms *timebuf)
1286 if (GetProcessTimes(GetCurrentProcess(), &dummy, &dummy,
1288 timebuf->tms_utime = filetime_to_clock(&user);
1289 timebuf->tms_stime = filetime_to_clock(&kernel);
1290 timebuf->tms_cutime = 0;
1291 timebuf->tms_cstime = 0;
1294 /* That failed - e.g. Win95 fallback to clock() */
1295 clock_t t = clock();
1296 timebuf->tms_utime = t;
1297 timebuf->tms_stime = 0;
1298 timebuf->tms_cutime = 0;
1299 timebuf->tms_cstime = 0;
1304 /* fix utime() so it works on directories in NT */
1306 filetime_from_time(PFILETIME pFileTime, time_t Time)
1308 struct tm *pTM = localtime(&Time);
1309 SYSTEMTIME SystemTime;
1315 SystemTime.wYear = pTM->tm_year + 1900;
1316 SystemTime.wMonth = pTM->tm_mon + 1;
1317 SystemTime.wDay = pTM->tm_mday;
1318 SystemTime.wHour = pTM->tm_hour;
1319 SystemTime.wMinute = pTM->tm_min;
1320 SystemTime.wSecond = pTM->tm_sec;
1321 SystemTime.wMilliseconds = 0;
1323 return SystemTimeToFileTime(&SystemTime, &LocalTime) &&
1324 LocalFileTimeToFileTime(&LocalTime, pFileTime);
1328 win32_utime(const char *filename, struct utimbuf *times)
1335 struct utimbuf TimeBuffer;
1336 WCHAR wbuffer[MAX_PATH];
1340 A2WHELPER(filename, wbuffer, sizeof(wbuffer));
1341 rc = _wutime(wbuffer, (struct _utimbuf*)times);
1344 rc = utime(filename, times);
1346 /* EACCES: path specifies directory or readonly file */
1347 if (rc == 0 || errno != EACCES /* || !IsWinNT() */)
1350 if (times == NULL) {
1351 times = &TimeBuffer;
1352 time(×->actime);
1353 times->modtime = times->actime;
1356 /* This will (and should) still fail on readonly files */
1358 handle = CreateFileW(wbuffer, GENERIC_READ | GENERIC_WRITE,
1359 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1360 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1363 handle = CreateFileA(filename, GENERIC_READ | GENERIC_WRITE,
1364 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1365 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1367 if (handle == INVALID_HANDLE_VALUE)
1370 if (GetFileTime(handle, &ftCreate, &ftAccess, &ftWrite) &&
1371 filetime_from_time(&ftAccess, times->actime) &&
1372 filetime_from_time(&ftWrite, times->modtime) &&
1373 SetFileTime(handle, &ftCreate, &ftAccess, &ftWrite))
1378 CloseHandle(handle);
1383 win32_uname(struct utsname *name)
1385 struct hostent *hep;
1386 STRLEN nodemax = sizeof(name->nodename)-1;
1387 OSVERSIONINFO osver;
1389 memset(&osver, 0, sizeof(OSVERSIONINFO));
1390 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1391 if (GetVersionEx(&osver)) {
1393 switch (osver.dwPlatformId) {
1394 case VER_PLATFORM_WIN32_WINDOWS:
1395 strcpy(name->sysname, "Windows");
1397 case VER_PLATFORM_WIN32_NT:
1398 strcpy(name->sysname, "Windows NT");
1400 case VER_PLATFORM_WIN32s:
1401 strcpy(name->sysname, "Win32s");
1404 strcpy(name->sysname, "Win32 Unknown");
1409 sprintf(name->release, "%d.%d",
1410 osver.dwMajorVersion, osver.dwMinorVersion);
1413 sprintf(name->version, "Build %d",
1414 osver.dwPlatformId == VER_PLATFORM_WIN32_NT
1415 ? osver.dwBuildNumber : (osver.dwBuildNumber & 0xffff));
1416 if (osver.szCSDVersion[0]) {
1417 char *buf = name->version + strlen(name->version);
1418 sprintf(buf, " (%s)", osver.szCSDVersion);
1422 *name->sysname = '\0';
1423 *name->version = '\0';
1424 *name->release = '\0';
1428 hep = win32_gethostbyname("localhost");
1430 STRLEN len = strlen(hep->h_name);
1431 if (len <= nodemax) {
1432 strcpy(name->nodename, hep->h_name);
1435 strncpy(name->nodename, hep->h_name, nodemax);
1436 name->nodename[nodemax] = '\0';
1441 if (!GetComputerName(name->nodename, &sz))
1442 *name->nodename = '\0';
1445 /* machine (architecture) */
1449 GetSystemInfo(&info);
1451 #if defined(__BORLANDC__) || defined(__MINGW32__)
1452 switch (info.u.s.wProcessorArchitecture) {
1454 switch (info.wProcessorArchitecture) {
1456 case PROCESSOR_ARCHITECTURE_INTEL:
1457 arch = "x86"; break;
1458 case PROCESSOR_ARCHITECTURE_MIPS:
1459 arch = "mips"; break;
1460 case PROCESSOR_ARCHITECTURE_ALPHA:
1461 arch = "alpha"; break;
1462 case PROCESSOR_ARCHITECTURE_PPC:
1463 arch = "ppc"; break;
1465 arch = "unknown"; break;
1467 strcpy(name->machine, arch);
1473 win32_waitpid(int pid, int *status, int flags)
1478 return win32_wait(status);
1480 long child = find_pid(pid);
1482 HANDLE hProcess = w32_child_handles[child];
1483 DWORD waitcode = WaitForSingleObject(hProcess, INFINITE);
1484 if (waitcode != WAIT_FAILED) {
1485 if (GetExitCodeProcess(hProcess, &waitcode)) {
1486 *status = (int)((waitcode & 0xff) << 8);
1487 retval = (int)w32_child_pids[child];
1488 remove_dead_process(child);
1496 retval = cwait(status, pid, WAIT_CHILD);
1497 /* cwait() returns "correctly" on Borland */
1498 #ifndef __BORLANDC__
1504 return retval >= 0 ? pid : retval;
1508 win32_wait(int *status)
1510 /* XXX this wait emulation only knows about processes
1511 * spawned via win32_spawnvp(P_NOWAIT, ...).
1515 DWORD exitcode, waitcode;
1517 if (!w32_num_children) {
1522 /* if a child exists, wait for it to die */
1523 waitcode = WaitForMultipleObjects(w32_num_children,
1527 if (waitcode != WAIT_FAILED) {
1528 if (waitcode >= WAIT_ABANDONED_0
1529 && waitcode < WAIT_ABANDONED_0 + w32_num_children)
1530 i = waitcode - WAIT_ABANDONED_0;
1532 i = waitcode - WAIT_OBJECT_0;
1533 if (GetExitCodeProcess(w32_child_handles[i], &exitcode) ) {
1534 *status = (int)((exitcode & 0xff) << 8);
1535 retval = (int)w32_child_pids[i];
1536 remove_dead_process(i);
1542 errno = GetLastError();
1546 static UINT timerid = 0;
1548 static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
1551 KillTimer(NULL,timerid);
1556 DllExport unsigned int
1557 win32_alarm(unsigned int sec)
1560 * the 'obvious' implentation is SetTimer() with a callback
1561 * which does whatever receiving SIGALRM would do
1562 * we cannot use SIGALRM even via raise() as it is not
1563 * one of the supported codes in <signal.h>
1565 * Snag is unless something is looking at the message queue
1566 * nothing happens :-(
1571 timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
1573 Perl_croak_nocontext("Cannot set timer");
1579 KillTimer(NULL,timerid);
1586 #if defined(HAVE_DES_FCRYPT) || defined(PERL_OBJECT)
1587 #ifdef HAVE_DES_FCRYPT
1588 extern char * des_fcrypt(const char *txt, const char *salt, char *cbuf);
1592 win32_crypt(const char *txt, const char *salt)
1595 #ifdef HAVE_DES_FCRYPT
1597 return des_fcrypt(txt, salt, crypt_buffer);
1599 die("The crypt() function is unimplemented due to excessive paranoia.");
1605 #ifdef USE_FIXED_OSFHANDLE
1607 EXTERN_C int __cdecl _alloc_osfhnd(void);
1608 EXTERN_C int __cdecl _set_osfhnd(int fh, long value);
1609 EXTERN_C void __cdecl _lock_fhandle(int);
1610 EXTERN_C void __cdecl _unlock_fhandle(int);
1611 EXTERN_C void __cdecl _unlock(int);
1613 #if (_MSC_VER >= 1000)
1615 long osfhnd; /* underlying OS file HANDLE */
1616 char osfile; /* attributes of file (e.g., open in text mode?) */
1617 char pipech; /* one char buffer for handles opened on pipes */
1618 #if defined (_MT) && !defined (DLL_FOR_WIN32S)
1620 CRITICAL_SECTION lock;
1621 #endif /* defined (_MT) && !defined (DLL_FOR_WIN32S) */
1624 EXTERN_C ioinfo * __pioinfo[];
1626 #define IOINFO_L2E 5
1627 #define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
1628 #define _pioinfo(i) (__pioinfo[i >> IOINFO_L2E] + (i & (IOINFO_ARRAY_ELTS - 1)))
1629 #define _osfile(i) (_pioinfo(i)->osfile)
1631 #else /* (_MSC_VER >= 1000) */
1632 extern char _osfile[];
1633 #endif /* (_MSC_VER >= 1000) */
1635 #define FOPEN 0x01 /* file handle open */
1636 #define FAPPEND 0x20 /* file handle opened O_APPEND */
1637 #define FDEV 0x40 /* file handle refers to device */
1638 #define FTEXT 0x80 /* file handle is in text mode */
1640 #define _STREAM_LOCKS 26 /* Table of stream locks */
1641 #define _LAST_STREAM_LOCK (_STREAM_LOCKS+_NSTREAM_-1) /* Last stream lock */
1642 #define _FH_LOCKS (_LAST_STREAM_LOCK+1) /* Table of fh locks */
1645 *int my_open_osfhandle(long osfhandle, int flags) - open C Runtime file handle
1648 * This function allocates a free C Runtime file handle and associates
1649 * it with the Win32 HANDLE specified by the first parameter. This is a
1650 * temperary fix for WIN95's brain damage GetFileType() error on socket
1651 * we just bypass that call for socket
1654 * long osfhandle - Win32 HANDLE to associate with C Runtime file handle.
1655 * int flags - flags to associate with C Runtime file handle.
1658 * returns index of entry in fh, if successful
1659 * return -1, if no free entry is found
1663 *******************************************************************************/
1666 my_open_osfhandle(long osfhandle, int flags)
1669 char fileflags; /* _osfile flags */
1671 /* copy relevant flags from second parameter */
1674 if (flags & O_APPEND)
1675 fileflags |= FAPPEND;
1680 /* attempt to allocate a C Runtime file handle */
1681 if ((fh = _alloc_osfhnd()) == -1) {
1682 errno = EMFILE; /* too many open files */
1683 _doserrno = 0L; /* not an OS error */
1684 return -1; /* return error to caller */
1687 /* the file is open. now, set the info in _osfhnd array */
1688 _set_osfhnd(fh, osfhandle);
1690 fileflags |= FOPEN; /* mark as open */
1692 #if (_MSC_VER >= 1000)
1693 _osfile(fh) = fileflags; /* set osfile entry */
1694 _unlock_fhandle(fh);
1696 _osfile[fh] = fileflags; /* set osfile entry */
1697 _unlock(fh+_FH_LOCKS); /* unlock handle */
1700 return fh; /* return handle */
1703 #define _open_osfhandle my_open_osfhandle
1704 #endif /* USE_FIXED_OSFHANDLE */
1706 /* simulate flock by locking a range on the file */
1708 #define LK_ERR(f,i) ((f) ? (i = 0) : (errno = GetLastError()))
1709 #define LK_LEN 0xffff0000
1712 win32_flock(int fd, int oper)
1720 Perl_croak_nocontext("flock() unimplemented on this platform");
1723 fh = (HANDLE)_get_osfhandle(fd);
1724 memset(&o, 0, sizeof(o));
1727 case LOCK_SH: /* shared lock */
1728 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
1730 case LOCK_EX: /* exclusive lock */
1731 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
1733 case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
1734 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
1736 case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
1737 LK_ERR(LockFileEx(fh,
1738 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
1739 0, LK_LEN, 0, &o),i);
1741 case LOCK_UN: /* unlock lock */
1742 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, 0, &o),i);
1744 default: /* unknown */
1755 * redirected io subsystem for all XS modules
1768 return (&(_environ));
1771 /* the rest are the remapped stdio routines */
1791 win32_ferror(FILE *fp)
1793 return (ferror(fp));
1798 win32_feof(FILE *fp)
1804 * Since the errors returned by the socket error function
1805 * WSAGetLastError() are not known by the library routine strerror
1806 * we have to roll our own.
1810 win32_strerror(int e)
1812 #ifndef __BORLANDC__ /* Borland intolerance */
1813 extern int sys_nerr;
1817 if (e < 0 || e > sys_nerr) {
1822 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
1823 strerror_buffer, sizeof(strerror_buffer), NULL) == 0)
1824 strcpy(strerror_buffer, "Unknown Error");
1826 return strerror_buffer;
1832 win32_str_os_error(void *sv, DWORD dwErr)
1836 dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
1837 |FORMAT_MESSAGE_IGNORE_INSERTS
1838 |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
1839 dwErr, 0, (char *)&sMsg, 1, NULL);
1840 /* strip trailing whitespace and period */
1843 --dwLen; /* dwLen doesn't include trailing null */
1844 } while (0 < dwLen && isSPACE(sMsg[dwLen]));
1845 if ('.' != sMsg[dwLen])
1850 sMsg = (char*)LocalAlloc(0, 64/**sizeof(TCHAR)*/);
1852 dwLen = sprintf(sMsg,
1853 "Unknown error #0x%lX (lookup 0x%lX)",
1854 dwErr, GetLastError());
1858 sv_setpvn((SV*)sv, sMsg, dwLen);
1865 win32_fprintf(FILE *fp, const char *format, ...)
1868 va_start(marker, format); /* Initialize variable arguments. */
1870 return (vfprintf(fp, format, marker));
1874 win32_printf(const char *format, ...)
1877 va_start(marker, format); /* Initialize variable arguments. */
1879 return (vprintf(format, marker));
1883 win32_vfprintf(FILE *fp, const char *format, va_list args)
1885 return (vfprintf(fp, format, args));
1889 win32_vprintf(const char *format, va_list args)
1891 return (vprintf(format, args));
1895 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
1897 return fread(buf, size, count, fp);
1901 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
1903 return fwrite(buf, size, count, fp);
1906 #define MODE_SIZE 10
1909 win32_fopen(const char *filename, const char *mode)
1912 WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH];
1917 if (stricmp(filename, "/dev/null")==0)
1921 A2WHELPER(mode, wMode, sizeof(wMode));
1922 A2WHELPER(filename, wBuffer, sizeof(wBuffer));
1923 return _wfopen(wBuffer, wMode);
1925 return fopen(filename, mode);
1928 #ifndef USE_SOCKETS_AS_HANDLES
1930 #define fdopen my_fdopen
1934 win32_fdopen(int handle, const char *mode)
1937 WCHAR wMode[MODE_SIZE];
1939 A2WHELPER(mode, wMode, sizeof(wMode));
1940 return _wfdopen(handle, wMode);
1942 return fdopen(handle, (char *) mode);
1946 win32_freopen(const char *path, const char *mode, FILE *stream)
1949 WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH];
1950 if (stricmp(path, "/dev/null")==0)
1954 A2WHELPER(mode, wMode, sizeof(wMode));
1955 A2WHELPER(path, wBuffer, sizeof(wBuffer));
1956 return _wfreopen(wBuffer, wMode, stream);
1958 return freopen(path, mode, stream);
1962 win32_fclose(FILE *pf)
1964 return my_fclose(pf); /* defined in win32sck.c */
1968 win32_fputs(const char *s,FILE *pf)
1970 return fputs(s, pf);
1974 win32_fputc(int c,FILE *pf)
1980 win32_ungetc(int c,FILE *pf)
1982 return ungetc(c,pf);
1986 win32_getc(FILE *pf)
1992 win32_fileno(FILE *pf)
1998 win32_clearerr(FILE *pf)
2005 win32_fflush(FILE *pf)
2011 win32_ftell(FILE *pf)
2017 win32_fseek(FILE *pf,long offset,int origin)
2019 return fseek(pf, offset, origin);
2023 win32_fgetpos(FILE *pf,fpos_t *p)
2025 return fgetpos(pf, p);
2029 win32_fsetpos(FILE *pf,const fpos_t *p)
2031 return fsetpos(pf, p);
2035 win32_rewind(FILE *pf)
2055 win32_fstat(int fd,struct stat *sbufptr)
2057 return fstat(fd,sbufptr);
2061 win32_pipe(int *pfd, unsigned int size, int mode)
2063 return _pipe(pfd, size, mode);
2067 * a popen() clone that respects PERL5SHELL
2071 win32_popen(const char *command, const char *mode)
2073 #ifdef USE_RTL_POPEN
2074 return _popen(command, mode);
2082 /* establish which ends read and write */
2083 if (strchr(mode,'w')) {
2084 stdfd = 0; /* stdin */
2088 else if (strchr(mode,'r')) {
2089 stdfd = 1; /* stdout */
2096 /* set the correct mode */
2097 if (strchr(mode,'b'))
2099 else if (strchr(mode,'t'))
2102 ourmode = _fmode & (O_TEXT | O_BINARY);
2104 /* the child doesn't inherit handles */
2105 ourmode |= O_NOINHERIT;
2107 if (win32_pipe( p, 512, ourmode) == -1)
2110 /* save current stdfd */
2111 if ((oldfd = win32_dup(stdfd)) == -1)
2114 /* make stdfd go to child end of pipe (implicitly closes stdfd) */
2115 /* stdfd will be inherited by the child */
2116 if (win32_dup2(p[child], stdfd) == -1)
2119 /* close the child end in parent */
2120 win32_close(p[child]);
2122 /* start the child */
2125 if ((childpid = do_spawn_nowait((char*)command)) == -1)
2128 /* revert stdfd to whatever it was before */
2129 if (win32_dup2(oldfd, stdfd) == -1)
2132 /* close saved handle */
2135 sv_setiv(*av_fetch(w32_fdpid, p[parent], TRUE), childpid);
2137 /* set process id so that it can be returned by perl's open() */
2138 PL_forkprocess = childpid;
2141 /* we have an fd, return a file stream */
2142 return (win32_fdopen(p[parent], (char *)mode));
2145 /* we don't need to check for errors here */
2149 win32_dup2(oldfd, stdfd);
2154 #endif /* USE_RTL_POPEN */
2162 win32_pclose(FILE *pf)
2164 #ifdef USE_RTL_POPEN
2168 int childpid, status;
2171 sv = *av_fetch(w32_fdpid, win32_fileno(pf), TRUE);
2173 childpid = SvIVX(sv);
2185 if (win32_waitpid(childpid, &status, 0) == -1)
2190 #endif /* USE_RTL_POPEN */
2194 win32_rename(const char *oname, const char *newname)
2196 WCHAR wOldName[MAX_PATH];
2197 WCHAR wNewName[MAX_PATH];
2199 /* XXX despite what the documentation says about MoveFileEx(),
2200 * it doesn't work under Windows95!
2205 A2WHELPER(oname, wOldName, sizeof(wOldName));
2206 A2WHELPER(newname, wNewName, sizeof(wNewName));
2207 bResult = MoveFileExW(wOldName,wNewName,
2208 MOVEFILE_COPY_ALLOWED|MOVEFILE_REPLACE_EXISTING);
2211 bResult = MoveFileExA(oname,newname,
2212 MOVEFILE_COPY_ALLOWED|MOVEFILE_REPLACE_EXISTING);
2215 DWORD err = GetLastError();
2217 case ERROR_BAD_NET_NAME:
2218 case ERROR_BAD_NETPATH:
2219 case ERROR_BAD_PATHNAME:
2220 case ERROR_FILE_NOT_FOUND:
2221 case ERROR_FILENAME_EXCED_RANGE:
2222 case ERROR_INVALID_DRIVE:
2223 case ERROR_NO_MORE_FILES:
2224 case ERROR_PATH_NOT_FOUND:
2237 char tmpname[MAX_PATH+1];
2238 char dname[MAX_PATH+1];
2239 char *endname = Nullch;
2241 DWORD from_attr, to_attr;
2243 /* if oname doesn't exist, do nothing */
2244 from_attr = GetFileAttributes(oname);
2245 if (from_attr == 0xFFFFFFFF) {
2250 /* if newname exists, rename it to a temporary name so that we
2251 * don't delete it in case oname happens to be the same file
2252 * (but perhaps accessed via a different path)
2254 to_attr = GetFileAttributes(newname);
2255 if (to_attr != 0xFFFFFFFF) {
2256 /* if newname is a directory, we fail
2257 * XXX could overcome this with yet more convoluted logic */
2258 if (to_attr & FILE_ATTRIBUTE_DIRECTORY) {
2262 tmplen = strlen(newname);
2263 strcpy(tmpname,newname);
2264 endname = tmpname+tmplen;
2265 for (; endname > tmpname ; --endname) {
2266 if (*endname == '/' || *endname == '\\') {
2271 if (endname > tmpname)
2272 endname = strcpy(dname,tmpname);
2276 /* get a temporary filename in same directory
2277 * XXX is this really the best we can do? */
2278 if (!GetTempFileName((LPCTSTR)endname, "plr", 0, tmpname)) {
2282 DeleteFile(tmpname);
2284 retval = rename(newname, tmpname);
2291 /* rename oname to newname */
2292 retval = rename(oname, newname);
2294 /* if we created a temporary file before ... */
2295 if (endname != Nullch) {
2296 /* ...and rename succeeded, delete temporary file/directory */
2298 DeleteFile(tmpname);
2299 /* else restore it to what it was */
2301 (void)rename(tmpname, newname);
2308 win32_setmode(int fd, int mode)
2310 return setmode(fd, mode);
2314 win32_lseek(int fd, long offset, int origin)
2316 return lseek(fd, offset, origin);
2326 win32_open(const char *path, int flag, ...)
2331 WCHAR wBuffer[MAX_PATH];
2334 pmode = va_arg(ap, int);
2337 if (stricmp(path, "/dev/null")==0)
2341 A2WHELPER(path, wBuffer, sizeof(wBuffer));
2342 return _wopen(wBuffer, flag, pmode);
2344 return open(path,flag,pmode);
2366 win32_dup2(int fd1,int fd2)
2368 return dup2(fd1,fd2);
2372 win32_read(int fd, void *buf, unsigned int cnt)
2374 return read(fd, buf, cnt);
2378 win32_write(int fd, const void *buf, unsigned int cnt)
2380 return write(fd, buf, cnt);
2384 win32_mkdir(const char *dir, int mode)
2386 return mkdir(dir); /* just ignore mode */
2390 win32_rmdir(const char *dir)
2396 win32_chdir(const char *dir)
2402 create_command_line(const char* command, const char * const *args)
2406 char *cmd, *ptr, *arg;
2407 STRLEN len = strlen(command) + 1;
2409 for (index = 0; (ptr = (char*)args[index]) != NULL; ++index)
2410 len += strlen(ptr) + 1;
2412 New(1310, cmd, len, char);
2414 strcpy(ptr, command);
2416 for (index = 0; (arg = (char*)args[index]) != NULL; ++index) {
2426 qualified_path(const char *cmd)
2430 char *fullcmd, *curfullcmd;
2436 fullcmd = (char*)cmd;
2438 if (*fullcmd == '/' || *fullcmd == '\\')
2445 pathstr = win32_getenv("PATH");
2446 New(0, fullcmd, MAX_PATH+1, char);
2447 curfullcmd = fullcmd;
2452 /* start by appending the name to the current prefix */
2453 strcpy(curfullcmd, cmd);
2454 curfullcmd += cmdlen;
2456 /* if it doesn't end with '.', or has no extension, try adding
2457 * a trailing .exe first */
2458 if (cmd[cmdlen-1] != '.'
2459 && (cmdlen < 4 || cmd[cmdlen-4] != '.'))
2461 strcpy(curfullcmd, ".exe");
2462 res = GetFileAttributes(fullcmd);
2463 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
2468 /* that failed, try the bare name */
2469 res = GetFileAttributes(fullcmd);
2470 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
2473 /* quit if no other path exists, or if cmd already has path */
2474 if (!pathstr || !*pathstr || has_slash)
2477 /* skip leading semis */
2478 while (*pathstr == ';')
2481 /* build a new prefix from scratch */
2482 curfullcmd = fullcmd;
2483 while (*pathstr && *pathstr != ';') {
2484 if (*pathstr == '"') { /* foo;"baz;etc";bar */
2485 pathstr++; /* skip initial '"' */
2486 while (*pathstr && *pathstr != '"') {
2487 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
2488 *curfullcmd++ = *pathstr;
2492 pathstr++; /* skip trailing '"' */
2495 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
2496 *curfullcmd++ = *pathstr;
2501 pathstr++; /* skip trailing semi */
2502 if (curfullcmd > fullcmd /* append a dir separator */
2503 && curfullcmd[-1] != '/' && curfullcmd[-1] != '\\')
2505 *curfullcmd++ = '\\';
2513 /* The following are just place holders.
2514 * Some hosts may provide and environment that the OS is
2515 * not tracking, therefore, these host must provide that
2516 * environment and the current directory to CreateProcess
2526 free_childenv(void* d)
2537 free_childdir(char* d)
2542 /* XXX this needs to be made more compatible with the spawnvp()
2543 * provided by the various RTLs. In particular, searching for
2544 * *.{com,bat,cmd} files (as done by the RTLs) is unimplemented.
2545 * This doesn't significantly affect perl itself, because we
2546 * always invoke things using PERL5SHELL if a direct attempt to
2547 * spawn the executable fails.
2549 * XXX splitting and rejoining the commandline between do_aspawn()
2550 * and win32_spawnvp() could also be avoided.
2554 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
2556 #ifdef USE_RTL_SPAWNVP
2557 return spawnvp(mode, cmdname, (char * const *)argv);
2563 STARTUPINFO StartupInfo;
2564 PROCESS_INFORMATION ProcessInformation;
2567 char *cmd = create_command_line(cmdname, strcmp(cmdname, argv[0]) == 0
2569 char *fullcmd = Nullch;
2571 env = PerlEnv_get_childenv();
2572 dir = PerlEnv_get_childdir();
2575 case P_NOWAIT: /* asynch + remember result */
2576 if (w32_num_children >= MAXIMUM_WAIT_OBJECTS) {
2582 case P_WAIT: /* synchronous execution */
2584 default: /* invalid mode */
2589 memset(&StartupInfo,0,sizeof(StartupInfo));
2590 StartupInfo.cb = sizeof(StartupInfo);
2591 StartupInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
2592 StartupInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
2593 StartupInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
2594 if (StartupInfo.hStdInput != INVALID_HANDLE_VALUE &&
2595 StartupInfo.hStdOutput != INVALID_HANDLE_VALUE &&
2596 StartupInfo.hStdError != INVALID_HANDLE_VALUE)
2598 StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
2601 create |= CREATE_NEW_CONSOLE;
2605 if (!CreateProcess(cmdname, /* search PATH to find executable */
2606 cmd, /* executable, and its arguments */
2607 NULL, /* process attributes */
2608 NULL, /* thread attributes */
2609 TRUE, /* inherit handles */
2610 create, /* creation flags */
2611 (LPVOID)env, /* inherit environment */
2612 dir, /* inherit cwd */
2614 &ProcessInformation))
2616 /* initial NULL argument to CreateProcess() does a PATH
2617 * search, but it always first looks in the directory
2618 * where the current process was started, which behavior
2619 * is undesirable for backward compatibility. So we
2620 * jump through our own hoops by picking out the path
2621 * we really want it to use. */
2623 fullcmd = qualified_path(cmdname);
2634 if (mode == P_NOWAIT) {
2635 /* asynchronous spawn -- store handle, return PID */
2636 w32_child_handles[w32_num_children] = ProcessInformation.hProcess;
2637 w32_child_pids[w32_num_children] = ProcessInformation.dwProcessId;
2638 ret = (int)ProcessInformation.dwProcessId;
2643 WaitForSingleObject(ProcessInformation.hProcess, INFINITE);
2644 GetExitCodeProcess(ProcessInformation.hProcess, &status);
2646 CloseHandle(ProcessInformation.hProcess);
2649 CloseHandle(ProcessInformation.hThread);
2652 PerlEnv_free_childenv(env);
2653 PerlEnv_free_childdir(dir);
2661 win32_execv(const char *cmdname, const char *const *argv)
2663 return execv(cmdname, (char *const *)argv);
2667 win32_execvp(const char *cmdname, const char *const *argv)
2669 return execvp(cmdname, (char *const *)argv);
2673 win32_perror(const char *str)
2679 win32_setbuf(FILE *pf, char *buf)
2685 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
2687 return setvbuf(pf, buf, type, size);
2691 win32_flushall(void)
2697 win32_fcloseall(void)
2703 win32_fgets(char *s, int n, FILE *pf)
2705 return fgets(s, n, pf);
2715 win32_fgetc(FILE *pf)
2721 win32_putc(int c, FILE *pf)
2727 win32_puts(const char *s)
2739 win32_putchar(int c)
2746 #ifndef USE_PERL_SBRK
2748 static char *committed = NULL;
2749 static char *base = NULL;
2750 static char *reserved = NULL;
2751 static char *brk = NULL;
2752 static DWORD pagesize = 0;
2753 static DWORD allocsize = 0;
2761 GetSystemInfo(&info);
2762 /* Pretend page size is larger so we don't perpetually
2763 * call the OS to commit just one page ...
2765 pagesize = info.dwPageSize << 3;
2766 allocsize = info.dwAllocationGranularity;
2768 /* This scheme fails eventually if request for contiguous
2769 * block is denied so reserve big blocks - this is only
2770 * address space not memory ...
2772 if (brk+need >= reserved)
2774 DWORD size = 64*1024*1024;
2776 if (committed && reserved && committed < reserved)
2778 /* Commit last of previous chunk cannot span allocations */
2779 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
2781 committed = reserved;
2783 /* Reserve some (more) space
2784 * Note this is a little sneaky, 1st call passes NULL as reserved
2785 * so lets system choose where we start, subsequent calls pass
2786 * the old end address so ask for a contiguous block
2788 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
2791 reserved = addr+size;
2806 if (brk > committed)
2808 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
2809 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
2824 win32_malloc(size_t size)
2826 return malloc(size);
2830 win32_calloc(size_t numitems, size_t size)
2832 return calloc(numitems,size);
2836 win32_realloc(void *block, size_t size)
2838 return realloc(block,size);
2842 win32_free(void *block)
2849 win32_open_osfhandle(long handle, int flags)
2851 return _open_osfhandle(handle, flags);
2855 win32_get_osfhandle(int fd)
2857 return _get_osfhandle(fd);
2861 win32_dynaload(const char* filename)
2866 WCHAR wfilename[MAX_PATH];
2867 A2WHELPER(filename, wfilename, sizeof(wfilename));
2868 hModule = LoadLibraryExW(wfilename, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
2871 hModule = LoadLibraryExA(filename, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
2877 win32_add_host(char *nameId, void *data)
2880 * This must be called before the script is parsed,
2881 * therefore no locking of threads is needed
2884 struct host_link *link;
2885 New(1314, link, 1, struct host_link);
2886 link->host_data = data;
2887 link->nameId = nameId;
2888 link->next = w32_host_link;
2889 w32_host_link = link;
2894 win32_get_host_data(char *nameId)
2897 struct host_link *link = w32_host_link;
2899 if(strEQ(link->nameId, nameId))
2900 return link->host_data;
2914 SV *sv = sv_newmortal();
2915 /* Make one call with zero size - return value is required size */
2916 DWORD len = GetCurrentDirectory((DWORD)0,NULL);
2917 SvUPGRADE(sv,SVt_PV);
2919 SvCUR(sv) = GetCurrentDirectory((DWORD) SvLEN(sv), SvPVX(sv));
2922 * then it worked, set PV valid,
2923 * else leave it 'undef'
2939 Perl_croak(aTHX_ "usage: Win32::SetCurrentDirectory($cwd)");
2940 if (SetCurrentDirectory(SvPV_nolen(ST(0))))
2947 XS(w32_GetNextAvailDrive)
2951 char root[] = "_:\\";
2956 if (GetDriveType(root) == 1) {
2965 XS(w32_GetLastError)
2969 XSRETURN_IV(GetLastError());
2973 XS(w32_SetLastError)
2977 Perl_croak(aTHX_ "usage: Win32::SetLastError($error)");
2978 SetLastError(SvIV(ST(0)));
2986 char *name = getlogin_buffer;
2987 DWORD size = sizeof(getlogin_buffer);
2989 if (GetUserName(name,&size)) {
2990 /* size includes NULL */
2991 ST(0) = sv_2mortal(newSVpvn(name,size-1));
3001 char name[MAX_COMPUTERNAME_LENGTH+1];
3002 DWORD size = sizeof(name);
3004 if (GetComputerName(name,&size)) {
3005 /* size does NOT include NULL :-( */
3006 ST(0) = sv_2mortal(newSVpvn(name,size));
3017 #ifndef HAS_NETWKSTAGETINFO
3018 /* mingw32 (and Win95) don't have NetWksta*(), so do it the old way */
3020 DWORD size = sizeof(name);
3022 if (GetUserName(name,&size)) {
3024 DWORD sidlen = sizeof(sid);
3026 DWORD dnamelen = sizeof(dname);
3028 if (LookupAccountName(NULL, name, (PSID)&sid, &sidlen,
3029 dname, &dnamelen, &snu)) {
3030 XSRETURN_PV(dname); /* all that for this */
3034 /* this way is more reliable, in case user has a local account.
3035 * XXX need dynamic binding of netapi32.dll symbols or this will fail on
3036 * Win95. Probably makes more sense to move it into libwin32. */
3038 DWORD dnamelen = sizeof(dname);
3039 PWKSTA_INFO_100 pwi;
3041 if (NERR_Success == NetWkstaGetInfo(NULL, 100, (LPBYTE*)&pwi)) {
3042 if (pwi->wki100_langroup && *(pwi->wki100_langroup)) {
3043 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_langroup,
3044 -1, (LPSTR)dname, dnamelen, NULL, NULL);
3047 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_computername,
3048 -1, (LPSTR)dname, dnamelen, NULL, NULL);
3050 NetApiBufferFree(pwi);
3062 DWORD flags, filecomplen;
3063 if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
3064 &flags, fsname, sizeof(fsname))) {
3065 if (GIMME_V == G_ARRAY) {
3066 XPUSHs(sv_2mortal(newSVpvn(fsname,strlen(fsname))));
3067 XPUSHs(sv_2mortal(newSViv(flags)));
3068 XPUSHs(sv_2mortal(newSViv(filecomplen)));
3073 XSRETURN_PV(fsname);
3079 XS(w32_GetOSVersion)
3082 OSVERSIONINFO osver;
3084 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
3085 if (GetVersionEx(&osver)) {
3086 XPUSHs(newSVpvn(osver.szCSDVersion, strlen(osver.szCSDVersion)));
3087 XPUSHs(newSViv(osver.dwMajorVersion));
3088 XPUSHs(newSViv(osver.dwMinorVersion));
3089 XPUSHs(newSViv(osver.dwBuildNumber));
3090 XPUSHs(newSViv(osver.dwPlatformId));
3102 XSRETURN_IV(IsWinNT());
3110 XSRETURN_IV(IsWin95());
3114 XS(w32_FormatMessage)
3121 Perl_croak(aTHX_ "usage: Win32::FormatMessage($errno)");
3123 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
3124 &source, SvIV(ST(0)), 0,
3125 msgbuf, sizeof(msgbuf)-1, NULL))
3126 XSRETURN_PV(msgbuf);
3136 PROCESS_INFORMATION stProcInfo;
3137 STARTUPINFO stStartInfo;
3138 BOOL bSuccess = FALSE;
3141 Perl_croak(aTHX_ "usage: Win32::Spawn($cmdName, $args, $PID)");
3143 cmd = SvPV_nolen(ST(0));
3144 args = SvPV_nolen(ST(1));
3146 memset(&stStartInfo, 0, sizeof(stStartInfo)); /* Clear the block */
3147 stStartInfo.cb = sizeof(stStartInfo); /* Set the structure size */
3148 stStartInfo.dwFlags = STARTF_USESHOWWINDOW; /* Enable wShowWindow control */
3149 stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE; /* Start min (normal) */
3152 cmd, /* Image path */
3153 args, /* Arguments for command line */
3154 NULL, /* Default process security */
3155 NULL, /* Default thread security */
3156 FALSE, /* Must be TRUE to use std handles */
3157 NORMAL_PRIORITY_CLASS, /* No special scheduling */
3158 NULL, /* Inherit our environment block */
3159 NULL, /* Inherit our currrent directory */
3160 &stStartInfo, /* -> Startup info */
3161 &stProcInfo)) /* <- Process info (if OK) */
3163 CloseHandle(stProcInfo.hThread);/* library source code does this. */
3164 sv_setiv(ST(2), stProcInfo.dwProcessId);
3167 XSRETURN_IV(bSuccess);
3171 XS(w32_GetTickCount)
3174 DWORD msec = GetTickCount();
3182 XS(w32_GetShortPathName)
3189 Perl_croak(aTHX_ "usage: Win32::GetShortPathName($longPathName)");
3191 shortpath = sv_mortalcopy(ST(0));
3192 SvUPGRADE(shortpath, SVt_PV);
3193 /* src == target is allowed */
3195 len = GetShortPathName(SvPVX(shortpath),
3198 } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
3200 SvCUR_set(shortpath,len);
3208 XS(w32_GetFullPathName)
3217 Perl_croak(aTHX_ "usage: Win32::GetFullPathName($filename)");
3220 fullpath = sv_mortalcopy(filename);
3221 SvUPGRADE(fullpath, SVt_PV);
3223 len = GetFullPathName(SvPVX(filename),
3227 } while (len >= SvLEN(fullpath) && sv_grow(fullpath,len+1));
3229 if (GIMME_V == G_ARRAY) {
3231 XST_mPV(1,filepart);
3232 len = filepart - SvPVX(fullpath);
3235 SvCUR_set(fullpath,len);
3243 XS(w32_GetLongPathName)
3247 char tmpbuf[MAX_PATH+1];
3252 Perl_croak(aTHX_ "usage: Win32::GetLongPathName($pathname)");
3255 pathstr = SvPV(path,len);
3256 strcpy(tmpbuf, pathstr);
3257 pathstr = win32_longpath(tmpbuf);
3259 ST(0) = sv_2mortal(newSVpvn(pathstr, strlen(pathstr)));
3270 Perl_croak(aTHX_ "usage: Win32::Sleep($milliseconds)");
3280 Perl_croak(aTHX_ "usage: Win32::CopyFile($from, $to, $overwrite)");
3281 if (CopyFile(SvPV_nolen(ST(0)), SvPV_nolen(ST(1)), !SvTRUE(ST(2))))
3287 Perl_init_os_extras(void)
3290 char *file = __FILE__;
3293 w32_perlshell_tokens = Nullch;
3294 w32_perlshell_items = -1;
3295 w32_fdpid = newAV(); /* XXX needs to be in Perl_win32_init()? */
3296 New(1313, w32_children, 1, child_tab);
3297 w32_num_children = 0;
3299 /* these names are Activeware compatible */
3300 newXS("Win32::GetCwd", w32_GetCwd, file);
3301 newXS("Win32::SetCwd", w32_SetCwd, file);
3302 newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
3303 newXS("Win32::GetLastError", w32_GetLastError, file);
3304 newXS("Win32::SetLastError", w32_SetLastError, file);
3305 newXS("Win32::LoginName", w32_LoginName, file);
3306 newXS("Win32::NodeName", w32_NodeName, file);
3307 newXS("Win32::DomainName", w32_DomainName, file);
3308 newXS("Win32::FsType", w32_FsType, file);
3309 newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
3310 newXS("Win32::IsWinNT", w32_IsWinNT, file);
3311 newXS("Win32::IsWin95", w32_IsWin95, file);
3312 newXS("Win32::FormatMessage", w32_FormatMessage, file);
3313 newXS("Win32::Spawn", w32_Spawn, file);
3314 newXS("Win32::GetTickCount", w32_GetTickCount, file);
3315 newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
3316 newXS("Win32::GetFullPathName", w32_GetFullPathName, file);
3317 newXS("Win32::GetLongPathName", w32_GetLongPathName, file);
3318 newXS("Win32::CopyFile", w32_CopyFile, file);
3319 newXS("Win32::Sleep", w32_Sleep, file);
3321 /* XXX Bloat Alert! The following Activeware preloads really
3322 * ought to be part of Win32::Sys::*, so they're not included
3325 /* LookupAccountName
3327 * InitiateSystemShutdown
3328 * AbortSystemShutdown
3329 * ExpandEnvrironmentStrings
3334 Perl_win32_init(int *argcp, char ***argvp)
3336 /* Disable floating point errors, Perl will trap the ones we
3337 * care about. VC++ RTL defaults to switching these off
3338 * already, but the Borland RTL doesn't. Since we don't
3339 * want to be at the vendor's whim on the default, we set
3340 * it explicitly here.
3342 #if !defined(_ALPHA_) && !defined(__GNUC__)
3343 _control87(MCW_EM, MCW_EM);
3348 #ifdef USE_BINMODE_SCRIPTS
3351 win32_strip_return(SV *sv)
3353 char *s = SvPVX(sv);
3354 char *e = s+SvCUR(sv);
3358 if (*s == '\r' && s[1] == '\n')
3368 SvCUR_set(sv,d-SvPVX(sv));