3 * (c) 1995 Microsoft Corporation. All rights reserved.
4 * Developed by hip communications inc., http://info.hip.com/info/
5 * Portions (c) 1993 Intergraph Corporation. All rights reserved.
7 * You may distribute under the terms of either the GNU General Public
8 * License or the Artistic License, as specified in the README file.
11 #define WIN32_LEAN_AND_MEAN
12 #define WIN32IO_IS_STDIO
22 /* ugliness to work around a buggy struct definition in lmwksta.h */
29 #endif /* __MINGW32__ */
31 /* #include "config.h" */
33 #define PERLIO_NOT_STDIO 0
34 #if !defined(PERLIO_IS_STDIO) && !defined(USE_SFIO)
44 extern CPerlObj* pPerl;
51 /* assert.h conflicts with #define of assert in perl.h */
58 #if defined(_MSC_VER) || defined(__MINGW32__)
59 #include <sys/utime.h>
65 /* Mingw32 defaults to globing command line
66 * So we turn it off like this:
73 #define EXECF_SPAWN_NOWAIT 3
75 #if defined(PERL_OBJECT)
76 #undef win32_get_privlib
77 #define win32_get_privlib g_win32_get_privlib
78 #undef win32_get_sitelib
79 #define win32_get_sitelib g_win32_get_sitelib
81 #define do_aspawn g_do_aspawn
83 #define do_spawn g_do_spawn
85 #define do_exec g_do_exec
87 #define getlogin g_getlogin
90 static DWORD os_id(void);
91 static void get_shell(void);
92 static long tokenize(char *str, char **dest, char ***destv);
93 int do_spawn2(char *cmd, int exectype);
94 static BOOL has_shell_metachars(char *ptr);
95 static long filetime_to_clock(PFILETIME ft);
96 static BOOL filetime_from_time(PFILETIME ft, time_t t);
97 static char * get_emd_part(char **leading, char *trailing, ...);
98 static void remove_dead_process(long deceased);
99 static long find_pid(int pid);
100 static char * qualified_path(const char *cmd);
102 HANDLE w32_perldll_handle = INVALID_HANDLE_VALUE;
103 char w32_module_name[MAX_PATH+1];
104 static DWORD w32_platform = (DWORD)-1;
107 # ifdef USE_DECLSPEC_THREAD
108 __declspec(thread) char strerror_buffer[512];
109 __declspec(thread) char getlogin_buffer[128];
110 __declspec(thread) char w32_perllib_root[MAX_PATH+1];
111 # ifdef HAVE_DES_FCRYPT
112 __declspec(thread) char crypt_buffer[30];
115 # define strerror_buffer (thr->i.Wstrerror_buffer)
116 # define getlogin_buffer (thr->i.Wgetlogin_buffer)
117 # define w32_perllib_root (thr->i.Ww32_perllib_root)
118 # define crypt_buffer (thr->i.Wcrypt_buffer)
121 static char strerror_buffer[512];
122 static char getlogin_buffer[128];
123 static char w32_perllib_root[MAX_PATH+1];
124 # ifdef HAVE_DES_FCRYPT
125 static char crypt_buffer[30];
131 return (os_id() == VER_PLATFORM_WIN32_WINDOWS);
136 return (os_id() == VER_PLATFORM_WIN32_NT);
139 /* *ptr is expected to point to valid allocated space (can't be NULL) */
141 GetRegStrFromKey(HKEY hkey, const char *lpszValueName, char** ptr, DWORD* lpDataLen)
143 /* Retrieve a REG_SZ or REG_EXPAND_SZ from the registry */
146 const char *subkey = "Software\\Perl";
150 retval = RegOpenKeyEx(hkey, subkey, 0, KEY_READ, &handle);
151 if (retval == ERROR_SUCCESS) {
152 retval = RegQueryValueEx(handle, lpszValueName, 0, &type, NULL, lpDataLen);
153 if (retval == ERROR_SUCCESS && type == REG_SZ) {
154 Renew(*ptr, *lpDataLen, char);
155 retval = RegQueryValueEx(handle, lpszValueName, 0, NULL,
156 (PBYTE)*ptr, lpDataLen);
157 if (retval == ERROR_SUCCESS)
165 /* *ptr is expected to point to valid allocated space (can't be NULL) */
167 GetRegStr(const char *lpszValueName, char** ptr, DWORD* lpDataLen)
169 char *str = GetRegStrFromKey(HKEY_CURRENT_USER, lpszValueName, ptr, lpDataLen);
171 str = GetRegStrFromKey(HKEY_LOCAL_MACHINE, lpszValueName, ptr, lpDataLen);
175 /* *prev_path is expected to point to valid allocated space (can't be NULL) */
177 get_emd_part(char **prev_path, char *trailing_path, ...)
181 char mod_name[MAX_PATH+1];
185 int oldsize, newsize;
187 va_start(ap, trailing_path);
188 strip = va_arg(ap, char *);
190 sprintf(base, "%5.3f",
191 (double)PERL_REVISION + ((double)PERL_VERSION / (double)1000));
193 if (!*w32_module_name) {
194 GetModuleFileName((HMODULE)((w32_perldll_handle == INVALID_HANDLE_VALUE)
195 ? GetModuleHandle(NULL)
196 : w32_perldll_handle),
197 w32_module_name, sizeof(w32_module_name));
199 /* try to get full path to binary (which may be mangled when perl is
200 * run from a 16-bit app) */
201 /*PerlIO_printf(PerlIO_stderr(), "Before %s\n", w32_module_name);*/
202 (void)win32_longpath(w32_module_name);
203 /*PerlIO_printf(PerlIO_stderr(), "After %s\n", w32_module_name);*/
205 /* normalize to forward slashes */
206 ptr = w32_module_name;
213 strcpy(mod_name, w32_module_name);
214 ptr = strrchr(mod_name, '/');
215 while (ptr && strip) {
216 /* look for directories to skip back */
219 ptr = strrchr(mod_name, '/');
220 if (!ptr || stricmp(ptr+1, strip) != 0) {
221 if(!(*strip == '5' && *(ptr+1) == '5'
222 && strncmp(strip, base, 5) == 0
223 && strncmp(ptr+1, base, 5) == 0))
229 strip = va_arg(ap, char *);
237 strcpy(++ptr, trailing_path);
239 /* only add directory if it exists */
240 if (GetFileAttributes(mod_name) != (DWORD) -1) {
241 /* directory exists */
242 newsize = strlen(mod_name) + 1;
243 oldsize = strlen(*prev_path) + 1;
244 newsize += oldsize; /* includes plus 1 for ';' */
245 Renew(*prev_path, newsize, char);
246 (*prev_path)[oldsize-1] = ';';
247 strcpy(&(*prev_path)[oldsize], mod_name);
255 win32_get_privlib(char *pl)
257 char *stdlib = "lib";
258 char buffer[MAX_PATH+1];
261 SV *sv = sv_2mortal(newSVpvn("",127));
263 /* $stdlib = $HKCU{"lib-$]"} || $HKLM{"lib-$]"} || $HKCU{"lib"} || $HKLM{"lib"} || ""; */
264 sprintf(buffer, "%s-%s", stdlib, pl);
266 if (!GetRegStr(buffer, path, &datalen))
267 (void)GetRegStr(stdlib, path, &datalen);
269 /* $stdlib .= ";$EMD/../../lib" */
270 (void)get_emd_part(path, stdlib, ARCHNAME, "bin", Nullch);
271 SvCUR_set(sv, strlen(*path));
272 SvLEN_set(sv, SvCUR(sv)+1);
277 win32_get_sitelib(char *pl)
279 char *sitelib = "sitelib";
281 char pathstr[MAX_PATH+1];
283 char **path1, *str1 = Nullch;
284 char **path2, *str2 = Nullch;
286 SV *sv1 = sv_2mortal(newSVpvn("",127));
287 SV *sv2 = sv_2mortal(newSVpvn("",127));
289 /* $HKCU{"sitelib-$]"} || $HKLM{"sitelib-$]"} . ---; */
290 sprintf(regstr, "%s-%s", sitelib, pl);
292 (void)GetRegStr(regstr, path1, &datalen);
295 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/site/$]/lib"; */
296 sprintf(pathstr, "site/%s/lib", pl);
297 str1 = get_emd_part(path1, pathstr, ARCHNAME, "bin", pl, Nullch);
298 if (!str1 && strlen(pl) == 7) {
299 /* pl may have been SUBVERSION-specific; try again without
301 sprintf(pathstr, "site/%.5s/lib", pl);
302 str1 = get_emd_part(path1, pathstr, ARCHNAME, "bin", pl, Nullch);
305 /* $HKCU{'sitelib'} || $HKLM{'sitelib'} . ---; */
307 (void)GetRegStr(sitelib, path2, &datalen);
310 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/site/lib"; */
311 str2 = get_emd_part(path2, "site/lib", ARCHNAME, "bin", pl, Nullch);
313 SvCUR_set(sv1, strlen(*path1));
314 SvLEN_set(sv1, SvCUR(sv1)+1);
315 SvCUR_set(sv2, strlen(*path2));
316 SvLEN_set(sv2, SvCUR(sv2)+1);
323 sv_catpvn(sv1, ";", 1);
331 has_shell_metachars(char *ptr)
337 * Scan string looking for redirection (< or >) or pipe
338 * characters (|) that are not in a quoted string.
339 * Shell variable interpolation (%VAR%) can also happen inside strings.
371 #if !defined(PERL_OBJECT)
372 /* since the current process environment is being updated in util.c
373 * the library functions will get the correct environment
376 my_popen(char *cmd, char *mode)
379 #define fixcmd(x) { \
380 char *pspace = strchr((x),' '); \
383 while (p < pspace) { \
394 PERL_FLUSHALL_FOR_CHILD;
395 return win32_popen(cmd, mode);
399 my_pclose(PerlIO *fp)
401 return win32_pclose(fp);
408 static OSVERSIONINFO osver;
410 if (osver.dwPlatformId != w32_platform) {
411 memset(&osver, 0, sizeof(OSVERSIONINFO));
412 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
413 GetVersionEx(&osver);
414 w32_platform = osver.dwPlatformId;
416 return (w32_platform);
419 /* Tokenize a string. Words are null-separated, and the list
420 * ends with a doubled null. Any character (except null and
421 * including backslash) may be escaped by preceding it with a
422 * backslash (the backslash will be stripped).
423 * Returns number of words in result buffer.
426 tokenize(char *str, char **dest, char ***destv)
428 char *retstart = Nullch;
429 char **retvstart = 0;
432 int slen = strlen(str);
434 register char **retv;
435 New(1307, ret, slen+2, char);
436 New(1308, retv, (slen+3)/2, char*);
444 if (*ret == '\\' && *str)
446 else if (*ret == ' ') {
462 retvstart[items] = Nullch;
474 if (!w32_perlshell_tokens) {
475 /* we don't use COMSPEC here for two reasons:
476 * 1. the same reason perl on UNIX doesn't use SHELL--rampant and
477 * uncontrolled unportability of the ensuing scripts.
478 * 2. PERL5SHELL could be set to a shell that may not be fit for
479 * interactive use (which is what most programs look in COMSPEC
482 char* defaultshell = (IsWinNT() ? "cmd.exe /x/c" : "command.com /c");
483 char *usershell = getenv("PERL5SHELL");
484 w32_perlshell_items = tokenize(usershell ? usershell : defaultshell,
485 &w32_perlshell_tokens,
491 do_aspawn(void *vreally, void **vmark, void **vsp)
493 SV *really = (SV*)vreally;
494 SV **mark = (SV**)vmark;
506 New(1306, argv, (sp - mark) + w32_perlshell_items + 2, char*);
508 if (SvNIOKp(*(mark+1)) && !SvPOKp(*(mark+1))) {
513 while (++mark <= sp) {
514 if (*mark && (str = SvPV_nolen(*mark)))
521 status = win32_spawnvp(flag,
522 (const char*)(really ? SvPV_nolen(really) : argv[0]),
523 (const char* const*)argv);
525 if (status < 0 && (errno == ENOEXEC || errno == ENOENT)) {
526 /* possible shell-builtin, invoke with shell */
528 sh_items = w32_perlshell_items;
530 argv[index+sh_items] = argv[index];
531 while (--sh_items >= 0)
532 argv[sh_items] = w32_perlshell_vec[sh_items];
534 status = win32_spawnvp(flag,
535 (const char*)(really ? SvPV_nolen(really) : argv[0]),
536 (const char* const*)argv);
539 if (flag != P_NOWAIT) {
542 warn("Can't spawn \"%s\": %s", argv[0], strerror(errno));
547 PL_statusvalue = status;
554 do_spawn2(char *cmd, int exectype)
560 BOOL needToTry = TRUE;
563 /* Save an extra exec if possible. See if there are shell
564 * metacharacters in it */
565 if (!has_shell_metachars(cmd)) {
566 New(1301,argv, strlen(cmd) / 2 + 2, char*);
567 New(1302,cmd2, strlen(cmd) + 1, char);
570 for (s = cmd2; *s;) {
571 while (*s && isSPACE(*s))
575 while (*s && !isSPACE(*s))
584 status = win32_spawnvp(P_WAIT, argv[0],
585 (const char* const*)argv);
587 case EXECF_SPAWN_NOWAIT:
588 status = win32_spawnvp(P_NOWAIT, argv[0],
589 (const char* const*)argv);
592 status = win32_execvp(argv[0], (const char* const*)argv);
595 if (status != -1 || errno == 0)
605 New(1306, argv, w32_perlshell_items + 2, char*);
606 while (++i < w32_perlshell_items)
607 argv[i] = w32_perlshell_vec[i];
612 status = win32_spawnvp(P_WAIT, argv[0],
613 (const char* const*)argv);
615 case EXECF_SPAWN_NOWAIT:
616 status = win32_spawnvp(P_NOWAIT, argv[0],
617 (const char* const*)argv);
620 status = win32_execvp(argv[0], (const char* const*)argv);
626 if (exectype != EXECF_SPAWN_NOWAIT) {
629 warn("Can't %s \"%s\": %s",
630 (exectype == EXECF_EXEC ? "exec" : "spawn"),
631 cmd, strerror(errno));
636 PL_statusvalue = status;
644 return do_spawn2(cmd, EXECF_SPAWN);
648 do_spawn_nowait(char *cmd)
650 return do_spawn2(cmd, EXECF_SPAWN_NOWAIT);
656 do_spawn2(cmd, EXECF_EXEC);
660 /* The idea here is to read all the directory names into a string table
661 * (separated by nulls) and when one of the other dir functions is called
662 * return the pointer to the current file name.
665 win32_opendir(char *filename)
670 char scanname[MAX_PATH+3];
672 WIN32_FIND_DATA FindData;
675 len = strlen(filename);
679 /* check to see if filename is a directory */
680 if (win32_stat(filename, &sbuf) < 0 || !S_ISDIR(sbuf.st_mode))
683 /* Get us a DIR structure */
684 Newz(1303, p, 1, DIR);
688 /* Create the search pattern */
689 strcpy(scanname, filename);
691 /* bare drive name means look in cwd for drive */
692 if (len == 2 && isALPHA(scanname[0]) && scanname[1] == ':') {
693 scanname[len++] = '.';
694 scanname[len++] = '/';
696 else if (scanname[len-1] != '/' && scanname[len-1] != '\\') {
697 scanname[len++] = '/';
699 scanname[len++] = '*';
700 scanname[len] = '\0';
702 /* do the FindFirstFile call */
703 fh = FindFirstFile(scanname, &FindData);
704 if (fh == INVALID_HANDLE_VALUE) {
705 /* FindFirstFile() fails on empty drives! */
706 if (GetLastError() == ERROR_FILE_NOT_FOUND)
712 /* now allocate the first part of the string table for
713 * the filenames that we find.
715 idx = strlen(FindData.cFileName)+1;
716 New(1304, p->start, idx, char);
717 if (p->start == NULL)
718 croak("opendir: malloc failed!\n");
719 strcpy(p->start, FindData.cFileName);
722 /* loop finding all the files that match the wildcard
723 * (which should be all of them in this directory!).
724 * the variable idx should point one past the null terminator
725 * of the previous string found.
727 while (FindNextFile(fh, &FindData)) {
728 len = strlen(FindData.cFileName);
729 /* bump the string table size by enough for the
730 * new name and it's null terminator
732 Renew(p->start, idx+len+1, char);
733 if (p->start == NULL)
734 croak("opendir: malloc failed!\n");
735 strcpy(&p->start[idx], FindData.cFileName);
746 /* Readdir just returns the current string pointer and bumps the
747 * string pointer to the nDllExport entry.
750 win32_readdir(DIR *dirp)
753 static int dummy = 0;
756 /* first set up the structure to return */
757 len = strlen(dirp->curr);
758 strcpy(dirp->dirstr.d_name, dirp->curr);
759 dirp->dirstr.d_namlen = len;
762 dirp->dirstr.d_ino = dummy++;
764 /* Now set up for the nDllExport call to readdir */
765 dirp->curr += len + 1;
766 if (dirp->curr >= (dirp->start + dirp->size)) {
770 return &(dirp->dirstr);
776 /* Telldir returns the current string pointer position */
778 win32_telldir(DIR *dirp)
780 return (long) dirp->curr;
784 /* Seekdir moves the string pointer to a previously saved position
788 win32_seekdir(DIR *dirp, long loc)
790 dirp->curr = (char *)loc;
793 /* Rewinddir resets the string pointer to the start */
795 win32_rewinddir(DIR *dirp)
797 dirp->curr = dirp->start;
800 /* free the memory allocated by opendir */
802 win32_closedir(DIR *dirp)
804 Safefree(dirp->start);
817 * Just pretend that everyone is a superuser. NT will let us know if
818 * we don\'t really have permission to do something.
821 #define ROOT_UID ((uid_t)0)
822 #define ROOT_GID ((gid_t)0)
851 return (auid == ROOT_UID ? 0 : -1);
857 return (agid == ROOT_GID ? 0 : -1);
864 char *buf = getlogin_buffer;
865 DWORD size = sizeof(getlogin_buffer);
866 if (GetUserName(buf,&size))
872 chown(const char *path, uid_t owner, gid_t group)
882 for (child = 0 ; child < w32_num_children ; ++child) {
883 if (w32_child_pids[child] == pid)
890 remove_dead_process(long child)
893 CloseHandle(w32_child_handles[child]);
894 Copy(&w32_child_handles[child+1], &w32_child_handles[child],
895 (w32_num_children-child-1), HANDLE);
896 Copy(&w32_child_pids[child+1], &w32_child_pids[child],
897 (w32_num_children-child-1), DWORD);
903 win32_kill(int pid, int sig)
906 hProcess = OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid);
907 if (hProcess && TerminateProcess(hProcess, sig))
908 CloseHandle(hProcess);
920 DllExport unsigned int
921 win32_sleep(unsigned int t)
928 win32_stat(const char *path, struct stat *buffer)
931 int l = strlen(path);
935 switch(path[l - 1]) {
936 /* FindFirstFile() and stat() are buggy with a trailing
937 * backslash, so change it to a forward slash :-( */
939 strncpy(t, path, l-1);
944 /* FindFirstFile() is buggy with "x:", so add a dot :-( */
946 if (l == 2 && isALPHA(path[0])) {
947 t[0] = path[0]; t[1] = ':'; t[2] = '.'; t[3] = '\0';
954 res = stat(path,buffer);
956 /* CRT is buggy on sharenames, so make sure it really isn't.
957 * XXX using GetFileAttributesEx() will enable us to set
958 * buffer->st_*time (but note that's not available on the
959 * Windows of 1995) */
960 DWORD r = GetFileAttributes(path);
961 if (r != 0xffffffff && (r & FILE_ATTRIBUTE_DIRECTORY)) {
962 /* buffer may still contain old garbage since stat() failed */
963 Zero(buffer, 1, struct stat);
964 buffer->st_mode = S_IFDIR | S_IREAD;
966 if (!(r & FILE_ATTRIBUTE_READONLY))
967 buffer->st_mode |= S_IWRITE | S_IEXEC;
972 if (l == 3 && isALPHA(path[0]) && path[1] == ':'
973 && (path[2] == '\\' || path[2] == '/'))
975 /* The drive can be inaccessible, some _stat()s are buggy */
976 if (!GetVolumeInformation(path,NULL,0,NULL,NULL,NULL,NULL,0)) {
982 if (S_ISDIR(buffer->st_mode))
983 buffer->st_mode |= S_IWRITE | S_IEXEC;
984 else if (S_ISREG(buffer->st_mode)) {
985 if (l >= 4 && path[l-4] == '.') {
986 const char *e = path + l - 3;
987 if (strnicmp(e,"exe",3)
988 && strnicmp(e,"bat",3)
989 && strnicmp(e,"com",3)
990 && (IsWin95() || strnicmp(e,"cmd",3)))
991 buffer->st_mode &= ~S_IEXEC;
993 buffer->st_mode |= S_IEXEC;
996 buffer->st_mode &= ~S_IEXEC;
1003 /* Find the longname of a given path. path is destructively modified.
1004 * It should have space for at least MAX_PATH characters. */
1006 win32_longpath(char *path)
1008 WIN32_FIND_DATA fdata;
1010 char tmpbuf[MAX_PATH+1];
1011 char *tmpstart = tmpbuf;
1018 if (isALPHA(path[0]) && path[1] == ':' &&
1019 (path[2] == '/' || path[2] == '\\'))
1022 *tmpstart++ = path[0];
1026 else if ((path[0] == '/' || path[0] == '\\') &&
1027 (path[1] == '/' || path[1] == '\\'))
1030 *tmpstart++ = path[0];
1031 *tmpstart++ = path[1];
1032 /* copy machine name */
1033 while (*start && *start != '/' && *start != '\\')
1034 *tmpstart++ = *start++;
1036 *tmpstart++ = *start;
1038 /* copy share name */
1039 while (*start && *start != '/' && *start != '\\')
1040 *tmpstart++ = *start++;
1044 if (sep == '/' || sep == '\\')
1048 /* walk up to slash */
1049 while (*start && *start != '/' && *start != '\\')
1052 /* discard doubled slashes */
1053 while (*start && (start[1] == '/' || start[1] == '\\'))
1057 /* stop and find full name of component */
1059 fhand = FindFirstFile(path,&fdata);
1060 if (fhand != INVALID_HANDLE_VALUE) {
1061 strcpy(tmpstart, fdata.cFileName);
1062 tmpstart += strlen(fdata.cFileName);
1070 /* failed a step, just return without side effects */
1071 /*PerlIO_printf(PerlIO_stderr(), "Failed to find %s\n", path);*/
1076 strcpy(path,tmpbuf);
1080 #ifndef USE_WIN32_RTL_ENV
1083 win32_getenv(const char *name)
1085 static char *curitem = Nullch; /* XXX threadead */
1086 static DWORD curlen = 0; /* XXX threadead */
1090 New(1305,curitem,curlen,char);
1093 needlen = GetEnvironmentVariable(name,curitem,curlen);
1095 while (needlen > curlen) {
1096 Renew(curitem,needlen,char);
1098 needlen = GetEnvironmentVariable(name,curitem,curlen);
1102 /* allow any environment variables that begin with 'PERL'
1103 to be stored in the registry */
1107 if (strncmp(name, "PERL", 4) == 0) {
1113 curitem = GetRegStr(name, &curitem, &curlen);
1116 if (curitem && *curitem == '\0')
1123 win32_putenv(const char *name)
1129 New(1309,curitem,strlen(name)+1,char);
1130 strcpy(curitem, name);
1131 val = strchr(curitem, '=');
1133 /* The sane way to deal with the environment.
1134 * Has these advantages over putenv() & co.:
1135 * * enables us to store a truly empty value in the
1136 * environment (like in UNIX).
1137 * * we don't have to deal with RTL globals, bugs and leaks.
1139 * Why you may want to enable USE_WIN32_RTL_ENV:
1140 * * environ[] and RTL functions will not reflect changes,
1141 * which might be an issue if extensions want to access
1142 * the env. via RTL. This cuts both ways, since RTL will
1143 * not see changes made by extensions that call the Win32
1144 * functions directly, either.
1148 if(SetEnvironmentVariable(curitem, *val ? val : NULL))
1159 filetime_to_clock(PFILETIME ft)
1161 __int64 qw = ft->dwHighDateTime;
1163 qw |= ft->dwLowDateTime;
1164 qw /= 10000; /* File time ticks at 0.1uS, clock at 1mS */
1169 win32_times(struct tms *timebuf)
1174 if (GetProcessTimes(GetCurrentProcess(), &dummy, &dummy,
1176 timebuf->tms_utime = filetime_to_clock(&user);
1177 timebuf->tms_stime = filetime_to_clock(&kernel);
1178 timebuf->tms_cutime = 0;
1179 timebuf->tms_cstime = 0;
1182 /* That failed - e.g. Win95 fallback to clock() */
1183 clock_t t = clock();
1184 timebuf->tms_utime = t;
1185 timebuf->tms_stime = 0;
1186 timebuf->tms_cutime = 0;
1187 timebuf->tms_cstime = 0;
1192 /* fix utime() so it works on directories in NT
1193 * thanks to Jan Dubois <jan.dubois@ibm.net>
1196 filetime_from_time(PFILETIME pFileTime, time_t Time)
1198 struct tm *pTM = gmtime(&Time);
1199 SYSTEMTIME SystemTime;
1204 SystemTime.wYear = pTM->tm_year + 1900;
1205 SystemTime.wMonth = pTM->tm_mon + 1;
1206 SystemTime.wDay = pTM->tm_mday;
1207 SystemTime.wHour = pTM->tm_hour;
1208 SystemTime.wMinute = pTM->tm_min;
1209 SystemTime.wSecond = pTM->tm_sec;
1210 SystemTime.wMilliseconds = 0;
1212 return SystemTimeToFileTime(&SystemTime, pFileTime);
1216 win32_utime(const char *filename, struct utimbuf *times)
1222 struct utimbuf TimeBuffer;
1224 int rc = utime(filename,times);
1225 /* EACCES: path specifies directory or readonly file */
1226 if (rc == 0 || errno != EACCES /* || !IsWinNT() */)
1229 if (times == NULL) {
1230 times = &TimeBuffer;
1231 time(×->actime);
1232 times->modtime = times->actime;
1235 /* This will (and should) still fail on readonly files */
1236 handle = CreateFile(filename, GENERIC_READ | GENERIC_WRITE,
1237 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1238 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1239 if (handle == INVALID_HANDLE_VALUE)
1242 if (GetFileTime(handle, &ftCreate, &ftAccess, &ftWrite) &&
1243 filetime_from_time(&ftAccess, times->actime) &&
1244 filetime_from_time(&ftWrite, times->modtime) &&
1245 SetFileTime(handle, &ftCreate, &ftAccess, &ftWrite))
1250 CloseHandle(handle);
1255 win32_uname(struct utsname *name)
1257 struct hostent *hep;
1258 STRLEN nodemax = sizeof(name->nodename)-1;
1259 OSVERSIONINFO osver;
1261 memset(&osver, 0, sizeof(OSVERSIONINFO));
1262 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1263 if (GetVersionEx(&osver)) {
1265 switch (osver.dwPlatformId) {
1266 case VER_PLATFORM_WIN32_WINDOWS:
1267 strcpy(name->sysname, "Windows");
1269 case VER_PLATFORM_WIN32_NT:
1270 strcpy(name->sysname, "Windows NT");
1272 case VER_PLATFORM_WIN32s:
1273 strcpy(name->sysname, "Win32s");
1276 strcpy(name->sysname, "Win32 Unknown");
1281 sprintf(name->release, "%d.%d",
1282 osver.dwMajorVersion, osver.dwMinorVersion);
1285 sprintf(name->version, "Build %d",
1286 osver.dwPlatformId == VER_PLATFORM_WIN32_NT
1287 ? osver.dwBuildNumber : (osver.dwBuildNumber & 0xffff));
1288 if (osver.szCSDVersion[0]) {
1289 char *buf = name->version + strlen(name->version);
1290 sprintf(buf, " (%s)", osver.szCSDVersion);
1294 *name->sysname = '\0';
1295 *name->version = '\0';
1296 *name->release = '\0';
1300 hep = win32_gethostbyname("localhost");
1302 STRLEN len = strlen(hep->h_name);
1303 if (len <= nodemax) {
1304 strcpy(name->nodename, hep->h_name);
1307 strncpy(name->nodename, hep->h_name, nodemax);
1308 name->nodename[nodemax] = '\0';
1313 if (!GetComputerName(name->nodename, &sz))
1314 *name->nodename = '\0';
1317 /* machine (architecture) */
1321 GetSystemInfo(&info);
1324 switch (info.DUMMYUNIONNAME.DUMMYSTRUCTNAME.wProcessorArchitecture) {
1327 switch (info.u.s.wProcessorArchitecture) {
1329 switch (info.wProcessorArchitecture) {
1332 case PROCESSOR_ARCHITECTURE_INTEL:
1333 arch = "x86"; break;
1334 case PROCESSOR_ARCHITECTURE_MIPS:
1335 arch = "mips"; break;
1336 case PROCESSOR_ARCHITECTURE_ALPHA:
1337 arch = "alpha"; break;
1338 case PROCESSOR_ARCHITECTURE_PPC:
1339 arch = "ppc"; break;
1341 arch = "unknown"; break;
1343 strcpy(name->machine, arch);
1349 win32_waitpid(int pid, int *status, int flags)
1353 return win32_wait(status);
1355 long child = find_pid(pid);
1357 HANDLE hProcess = w32_child_handles[child];
1358 DWORD waitcode = WaitForSingleObject(hProcess, INFINITE);
1359 if (waitcode != WAIT_FAILED) {
1360 if (GetExitCodeProcess(hProcess, &waitcode)) {
1361 *status = (int)((waitcode & 0xff) << 8);
1362 retval = (int)w32_child_pids[child];
1363 remove_dead_process(child);
1371 retval = cwait(status, pid, WAIT_CHILD);
1372 /* cwait() returns "correctly" on Borland */
1373 #ifndef __BORLANDC__
1379 return retval >= 0 ? pid : retval;
1383 win32_wait(int *status)
1385 /* XXX this wait emulation only knows about processes
1386 * spawned via win32_spawnvp(P_NOWAIT, ...).
1389 DWORD exitcode, waitcode;
1391 if (!w32_num_children) {
1396 /* if a child exists, wait for it to die */
1397 waitcode = WaitForMultipleObjects(w32_num_children,
1401 if (waitcode != WAIT_FAILED) {
1402 if (waitcode >= WAIT_ABANDONED_0
1403 && waitcode < WAIT_ABANDONED_0 + w32_num_children)
1404 i = waitcode - WAIT_ABANDONED_0;
1406 i = waitcode - WAIT_OBJECT_0;
1407 if (GetExitCodeProcess(w32_child_handles[i], &exitcode) ) {
1408 *status = (int)((exitcode & 0xff) << 8);
1409 retval = (int)w32_child_pids[i];
1410 remove_dead_process(i);
1416 errno = GetLastError();
1420 static UINT timerid = 0;
1422 static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
1424 KillTimer(NULL,timerid);
1429 DllExport unsigned int
1430 win32_alarm(unsigned int sec)
1433 * the 'obvious' implentation is SetTimer() with a callback
1434 * which does whatever receiving SIGALRM would do
1435 * we cannot use SIGALRM even via raise() as it is not
1436 * one of the supported codes in <signal.h>
1438 * Snag is unless something is looking at the message queue
1439 * nothing happens :-(
1443 timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
1445 croak("Cannot set timer");
1451 KillTimer(NULL,timerid);
1458 #if defined(HAVE_DES_FCRYPT) || defined(PERL_OBJECT)
1459 #ifdef HAVE_DES_FCRYPT
1460 extern char * des_fcrypt(const char *txt, const char *salt, char *cbuf);
1464 win32_crypt(const char *txt, const char *salt)
1466 #ifdef HAVE_DES_FCRYPT
1468 return des_fcrypt(txt, salt, crypt_buffer);
1470 die("The crypt() function is unimplemented due to excessive paranoia.");
1476 #ifdef USE_FIXED_OSFHANDLE
1478 EXTERN_C int __cdecl _alloc_osfhnd(void);
1479 EXTERN_C int __cdecl _set_osfhnd(int fh, long value);
1480 EXTERN_C void __cdecl _lock_fhandle(int);
1481 EXTERN_C void __cdecl _unlock_fhandle(int);
1482 EXTERN_C void __cdecl _unlock(int);
1484 #if (_MSC_VER >= 1000)
1486 long osfhnd; /* underlying OS file HANDLE */
1487 char osfile; /* attributes of file (e.g., open in text mode?) */
1488 char pipech; /* one char buffer for handles opened on pipes */
1489 #if defined (_MT) && !defined (DLL_FOR_WIN32S)
1491 CRITICAL_SECTION lock;
1492 #endif /* defined (_MT) && !defined (DLL_FOR_WIN32S) */
1495 EXTERN_C ioinfo * __pioinfo[];
1497 #define IOINFO_L2E 5
1498 #define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
1499 #define _pioinfo(i) (__pioinfo[i >> IOINFO_L2E] + (i & (IOINFO_ARRAY_ELTS - 1)))
1500 #define _osfile(i) (_pioinfo(i)->osfile)
1502 #else /* (_MSC_VER >= 1000) */
1503 extern char _osfile[];
1504 #endif /* (_MSC_VER >= 1000) */
1506 #define FOPEN 0x01 /* file handle open */
1507 #define FAPPEND 0x20 /* file handle opened O_APPEND */
1508 #define FDEV 0x40 /* file handle refers to device */
1509 #define FTEXT 0x80 /* file handle is in text mode */
1511 #define _STREAM_LOCKS 26 /* Table of stream locks */
1512 #define _LAST_STREAM_LOCK (_STREAM_LOCKS+_NSTREAM_-1) /* Last stream lock */
1513 #define _FH_LOCKS (_LAST_STREAM_LOCK+1) /* Table of fh locks */
1516 *int my_open_osfhandle(long osfhandle, int flags) - open C Runtime file handle
1519 * This function allocates a free C Runtime file handle and associates
1520 * it with the Win32 HANDLE specified by the first parameter. This is a
1521 * temperary fix for WIN95's brain damage GetFileType() error on socket
1522 * we just bypass that call for socket
1525 * long osfhandle - Win32 HANDLE to associate with C Runtime file handle.
1526 * int flags - flags to associate with C Runtime file handle.
1529 * returns index of entry in fh, if successful
1530 * return -1, if no free entry is found
1534 *******************************************************************************/
1537 my_open_osfhandle(long osfhandle, int flags)
1540 char fileflags; /* _osfile flags */
1542 /* copy relevant flags from second parameter */
1545 if (flags & O_APPEND)
1546 fileflags |= FAPPEND;
1551 /* attempt to allocate a C Runtime file handle */
1552 if ((fh = _alloc_osfhnd()) == -1) {
1553 errno = EMFILE; /* too many open files */
1554 _doserrno = 0L; /* not an OS error */
1555 return -1; /* return error to caller */
1558 /* the file is open. now, set the info in _osfhnd array */
1559 _set_osfhnd(fh, osfhandle);
1561 fileflags |= FOPEN; /* mark as open */
1563 #if (_MSC_VER >= 1000)
1564 _osfile(fh) = fileflags; /* set osfile entry */
1565 _unlock_fhandle(fh);
1567 _osfile[fh] = fileflags; /* set osfile entry */
1568 _unlock(fh+_FH_LOCKS); /* unlock handle */
1571 return fh; /* return handle */
1574 #define _open_osfhandle my_open_osfhandle
1575 #endif /* USE_FIXED_OSFHANDLE */
1577 /* simulate flock by locking a range on the file */
1579 #define LK_ERR(f,i) ((f) ? (i = 0) : (errno = GetLastError()))
1580 #define LK_LEN 0xffff0000
1583 win32_flock(int fd, int oper)
1590 croak("flock() unimplemented on this platform");
1593 fh = (HANDLE)_get_osfhandle(fd);
1594 memset(&o, 0, sizeof(o));
1597 case LOCK_SH: /* shared lock */
1598 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
1600 case LOCK_EX: /* exclusive lock */
1601 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
1603 case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
1604 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
1606 case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
1607 LK_ERR(LockFileEx(fh,
1608 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
1609 0, LK_LEN, 0, &o),i);
1611 case LOCK_UN: /* unlock lock */
1612 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, 0, &o),i);
1614 default: /* unknown */
1625 * redirected io subsystem for all XS modules
1638 return (&(_environ));
1641 /* the rest are the remapped stdio routines */
1661 win32_ferror(FILE *fp)
1663 return (ferror(fp));
1668 win32_feof(FILE *fp)
1674 * Since the errors returned by the socket error function
1675 * WSAGetLastError() are not known by the library routine strerror
1676 * we have to roll our own.
1680 win32_strerror(int e)
1682 #ifndef __BORLANDC__ /* Borland intolerance */
1683 extern int sys_nerr;
1687 if (e < 0 || e > sys_nerr) {
1692 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
1693 strerror_buffer, sizeof(strerror_buffer), NULL) == 0)
1694 strcpy(strerror_buffer, "Unknown Error");
1696 return strerror_buffer;
1702 win32_str_os_error(void *sv, DWORD dwErr)
1706 dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
1707 |FORMAT_MESSAGE_IGNORE_INSERTS
1708 |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
1709 dwErr, 0, (char *)&sMsg, 1, NULL);
1711 while (0 < dwLen && isSPACE(sMsg[--dwLen]))
1713 if ('.' != sMsg[dwLen])
1718 sMsg = (char*)LocalAlloc(0, 64/**sizeof(TCHAR)*/);
1720 dwLen = sprintf(sMsg,
1721 "Unknown error #0x%lX (lookup 0x%lX)",
1722 dwErr, GetLastError());
1725 sv_setpvn((SV*)sv, sMsg, dwLen);
1732 win32_fprintf(FILE *fp, const char *format, ...)
1735 va_start(marker, format); /* Initialize variable arguments. */
1737 return (vfprintf(fp, format, marker));
1741 win32_printf(const char *format, ...)
1744 va_start(marker, format); /* Initialize variable arguments. */
1746 return (vprintf(format, marker));
1750 win32_vfprintf(FILE *fp, const char *format, va_list args)
1752 return (vfprintf(fp, format, args));
1756 win32_vprintf(const char *format, va_list args)
1758 return (vprintf(format, args));
1762 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
1764 return fread(buf, size, count, fp);
1768 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
1770 return fwrite(buf, size, count, fp);
1774 win32_fopen(const char *filename, const char *mode)
1776 if (stricmp(filename, "/dev/null")==0)
1777 return fopen("NUL", mode);
1778 return fopen(filename, mode);
1781 #ifndef USE_SOCKETS_AS_HANDLES
1783 #define fdopen my_fdopen
1787 win32_fdopen( int handle, const char *mode)
1789 return fdopen(handle, (char *) mode);
1793 win32_freopen( const char *path, const char *mode, FILE *stream)
1795 if (stricmp(path, "/dev/null")==0)
1796 return freopen("NUL", mode, stream);
1797 return freopen(path, mode, stream);
1801 win32_fclose(FILE *pf)
1803 return my_fclose(pf); /* defined in win32sck.c */
1807 win32_fputs(const char *s,FILE *pf)
1809 return fputs(s, pf);
1813 win32_fputc(int c,FILE *pf)
1819 win32_ungetc(int c,FILE *pf)
1821 return ungetc(c,pf);
1825 win32_getc(FILE *pf)
1831 win32_fileno(FILE *pf)
1837 win32_clearerr(FILE *pf)
1844 win32_fflush(FILE *pf)
1850 win32_ftell(FILE *pf)
1856 win32_fseek(FILE *pf,long offset,int origin)
1858 return fseek(pf, offset, origin);
1862 win32_fgetpos(FILE *pf,fpos_t *p)
1864 return fgetpos(pf, p);
1868 win32_fsetpos(FILE *pf,const fpos_t *p)
1870 return fsetpos(pf, p);
1874 win32_rewind(FILE *pf)
1894 win32_fstat(int fd,struct stat *sbufptr)
1896 return fstat(fd,sbufptr);
1900 win32_pipe(int *pfd, unsigned int size, int mode)
1902 return _pipe(pfd, size, mode);
1906 * a popen() clone that respects PERL5SHELL
1910 win32_popen(const char *command, const char *mode)
1912 #ifdef USE_RTL_POPEN
1913 return _popen(command, mode);
1921 /* establish which ends read and write */
1922 if (strchr(mode,'w')) {
1923 stdfd = 0; /* stdin */
1927 else if (strchr(mode,'r')) {
1928 stdfd = 1; /* stdout */
1935 /* set the correct mode */
1936 if (strchr(mode,'b'))
1938 else if (strchr(mode,'t'))
1941 ourmode = _fmode & (O_TEXT | O_BINARY);
1943 /* the child doesn't inherit handles */
1944 ourmode |= O_NOINHERIT;
1946 if (win32_pipe( p, 512, ourmode) == -1)
1949 /* save current stdfd */
1950 if ((oldfd = win32_dup(stdfd)) == -1)
1953 /* make stdfd go to child end of pipe (implicitly closes stdfd) */
1954 /* stdfd will be inherited by the child */
1955 if (win32_dup2(p[child], stdfd) == -1)
1958 /* close the child end in parent */
1959 win32_close(p[child]);
1961 /* start the child */
1962 if ((childpid = do_spawn_nowait((char*)command)) == -1)
1965 /* revert stdfd to whatever it was before */
1966 if (win32_dup2(oldfd, stdfd) == -1)
1969 /* close saved handle */
1972 sv_setiv(*av_fetch(w32_fdpid, p[parent], TRUE), childpid);
1974 /* we have an fd, return a file stream */
1975 return (win32_fdopen(p[parent], (char *)mode));
1978 /* we don't need to check for errors here */
1982 win32_dup2(oldfd, stdfd);
1987 #endif /* USE_RTL_POPEN */
1995 win32_pclose(FILE *pf)
1997 #ifdef USE_RTL_POPEN
2001 int childpid, status;
2004 sv = *av_fetch(w32_fdpid, win32_fileno(pf), TRUE);
2006 childpid = SvIVX(sv);
2018 if (win32_waitpid(childpid, &status, 0) == -1)
2023 #endif /* USE_RTL_POPEN */
2027 win32_rename(const char *oname, const char *newname)
2029 /* XXX despite what the documentation says about MoveFileEx(),
2030 * it doesn't work under Windows95!
2033 if (!MoveFileEx(oname,newname,
2034 MOVEFILE_COPY_ALLOWED|MOVEFILE_REPLACE_EXISTING)) {
2035 DWORD err = GetLastError();
2037 case ERROR_BAD_NET_NAME:
2038 case ERROR_BAD_NETPATH:
2039 case ERROR_BAD_PATHNAME:
2040 case ERROR_FILE_NOT_FOUND:
2041 case ERROR_FILENAME_EXCED_RANGE:
2042 case ERROR_INVALID_DRIVE:
2043 case ERROR_NO_MORE_FILES:
2044 case ERROR_PATH_NOT_FOUND:
2057 char tmpname[MAX_PATH+1];
2058 char dname[MAX_PATH+1];
2059 char *endname = Nullch;
2061 DWORD from_attr, to_attr;
2063 /* if oname doesn't exist, do nothing */
2064 from_attr = GetFileAttributes(oname);
2065 if (from_attr == 0xFFFFFFFF) {
2070 /* if newname exists, rename it to a temporary name so that we
2071 * don't delete it in case oname happens to be the same file
2072 * (but perhaps accessed via a different path)
2074 to_attr = GetFileAttributes(newname);
2075 if (to_attr != 0xFFFFFFFF) {
2076 /* if newname is a directory, we fail
2077 * XXX could overcome this with yet more convoluted logic */
2078 if (to_attr & FILE_ATTRIBUTE_DIRECTORY) {
2082 tmplen = strlen(newname);
2083 strcpy(tmpname,newname);
2084 endname = tmpname+tmplen;
2085 for (; endname > tmpname ; --endname) {
2086 if (*endname == '/' || *endname == '\\') {
2091 if (endname > tmpname)
2092 endname = strcpy(dname,tmpname);
2096 /* get a temporary filename in same directory
2097 * XXX is this really the best we can do? */
2098 if (!GetTempFileName((LPCTSTR)endname, "plr", 0, tmpname)) {
2102 DeleteFile(tmpname);
2104 retval = rename(newname, tmpname);
2111 /* rename oname to newname */
2112 retval = rename(oname, newname);
2114 /* if we created a temporary file before ... */
2115 if (endname != Nullch) {
2116 /* ...and rename succeeded, delete temporary file/directory */
2118 DeleteFile(tmpname);
2119 /* else restore it to what it was */
2121 (void)rename(tmpname, newname);
2128 win32_setmode(int fd, int mode)
2130 return setmode(fd, mode);
2134 win32_lseek(int fd, long offset, int origin)
2136 return lseek(fd, offset, origin);
2146 win32_open(const char *path, int flag, ...)
2152 pmode = va_arg(ap, int);
2155 if (stricmp(path, "/dev/null")==0)
2156 return open("NUL", flag, pmode);
2157 return open(path,flag,pmode);
2179 win32_dup2(int fd1,int fd2)
2181 return dup2(fd1,fd2);
2185 win32_read(int fd, void *buf, unsigned int cnt)
2187 return read(fd, buf, cnt);
2191 win32_write(int fd, const void *buf, unsigned int cnt)
2193 return write(fd, buf, cnt);
2197 win32_mkdir(const char *dir, int mode)
2199 return mkdir(dir); /* just ignore mode */
2203 win32_rmdir(const char *dir)
2209 win32_chdir(const char *dir)
2215 create_command_line(const char* command, const char * const *args)
2218 char *cmd, *ptr, *arg;
2219 STRLEN len = strlen(command) + 1;
2221 for (index = 0; (ptr = (char*)args[index]) != NULL; ++index)
2222 len += strlen(ptr) + 1;
2224 New(1310, cmd, len, char);
2226 strcpy(ptr, command);
2228 for (index = 0; (arg = (char*)args[index]) != NULL; ++index) {
2238 qualified_path(const char *cmd)
2241 char *fullcmd, *curfullcmd;
2247 fullcmd = (char*)cmd;
2249 if (*fullcmd == '/' || *fullcmd == '\\')
2256 pathstr = win32_getenv("PATH");
2257 New(0, fullcmd, MAX_PATH+1, char);
2258 curfullcmd = fullcmd;
2263 /* start by appending the name to the current prefix */
2264 strcpy(curfullcmd, cmd);
2265 curfullcmd += cmdlen;
2267 /* if it doesn't end with '.', or has no extension, try adding
2268 * a trailing .exe first */
2269 if (cmd[cmdlen-1] != '.'
2270 && (cmdlen < 4 || cmd[cmdlen-4] != '.'))
2272 strcpy(curfullcmd, ".exe");
2273 res = GetFileAttributes(fullcmd);
2274 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
2279 /* that failed, try the bare name */
2280 res = GetFileAttributes(fullcmd);
2281 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
2284 /* quit if no other path exists, or if cmd already has path */
2285 if (!pathstr || !*pathstr || has_slash)
2288 /* skip leading semis */
2289 while (*pathstr == ';')
2292 /* build a new prefix from scratch */
2293 curfullcmd = fullcmd;
2294 while (*pathstr && *pathstr != ';') {
2295 if (*pathstr == '"') { /* foo;"baz;etc";bar */
2296 pathstr++; /* skip initial '"' */
2297 while (*pathstr && *pathstr != '"') {
2298 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
2299 *curfullcmd++ = *pathstr;
2303 pathstr++; /* skip trailing '"' */
2306 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
2307 *curfullcmd++ = *pathstr;
2312 pathstr++; /* skip trailing semi */
2313 if (curfullcmd > fullcmd /* append a dir separator */
2314 && curfullcmd[-1] != '/' && curfullcmd[-1] != '\\')
2316 *curfullcmd++ = '\\';
2324 /* XXX this needs to be made more compatible with the spawnvp()
2325 * provided by the various RTLs. In particular, searching for
2326 * *.{com,bat,cmd} files (as done by the RTLs) is unimplemented.
2327 * This doesn't significantly affect perl itself, because we
2328 * always invoke things using PERL5SHELL if a direct attempt to
2329 * spawn the executable fails.
2331 * XXX splitting and rejoining the commandline between do_aspawn()
2332 * and win32_spawnvp() could also be avoided.
2336 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
2338 #ifdef USE_RTL_SPAWNVP
2339 return spawnvp(mode, cmdname, (char * const *)argv);
2342 STARTUPINFO StartupInfo;
2343 PROCESS_INFORMATION ProcessInformation;
2346 char *cmd = create_command_line(cmdname, strcmp(cmdname, argv[0]) == 0
2348 char *fullcmd = Nullch;
2351 case P_NOWAIT: /* asynch + remember result */
2352 if (w32_num_children >= MAXIMUM_WAIT_OBJECTS) {
2358 case P_WAIT: /* synchronous execution */
2360 default: /* invalid mode */
2365 memset(&StartupInfo,0,sizeof(StartupInfo));
2366 StartupInfo.cb = sizeof(StartupInfo);
2367 StartupInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
2368 StartupInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
2369 StartupInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
2370 if (StartupInfo.hStdInput != INVALID_HANDLE_VALUE &&
2371 StartupInfo.hStdOutput != INVALID_HANDLE_VALUE &&
2372 StartupInfo.hStdError != INVALID_HANDLE_VALUE)
2374 StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
2377 create |= CREATE_NEW_CONSOLE;
2381 StartupInfo.dwFlags |= STARTF_USESHOWWINDOW;
2382 StartupInfo.wShowWindow = SW_HIDE;
2386 if (!CreateProcess(cmdname, /* search PATH to find executable */
2387 cmd, /* executable, and its arguments */
2388 NULL, /* process attributes */
2389 NULL, /* thread attributes */
2390 TRUE, /* inherit handles */
2391 create, /* creation flags */
2392 NULL, /* inherit environment */
2393 NULL, /* inherit cwd */
2395 &ProcessInformation))
2397 /* initial NULL argument to CreateProcess() does a PATH
2398 * search, but it always first looks in the directory
2399 * where the current process was started, which behavior
2400 * is undesirable for backward compatibility. So we
2401 * jump through our own hoops by picking out the path
2402 * we really want it to use. */
2404 fullcmd = qualified_path(cmdname);
2415 if (mode == P_NOWAIT) {
2416 /* asynchronous spawn -- store handle, return PID */
2417 w32_child_handles[w32_num_children] = ProcessInformation.hProcess;
2418 ret = w32_child_pids[w32_num_children] = ProcessInformation.dwProcessId;
2422 WaitForSingleObject(ProcessInformation.hProcess, INFINITE);
2423 GetExitCodeProcess(ProcessInformation.hProcess, &ret);
2424 CloseHandle(ProcessInformation.hProcess);
2427 CloseHandle(ProcessInformation.hThread);
2436 win32_execv(const char *cmdname, const char *const *argv)
2438 return execv(cmdname, (char *const *)argv);
2442 win32_execvp(const char *cmdname, const char *const *argv)
2444 return execvp(cmdname, (char *const *)argv);
2448 win32_perror(const char *str)
2454 win32_setbuf(FILE *pf, char *buf)
2460 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
2462 return setvbuf(pf, buf, type, size);
2466 win32_flushall(void)
2472 win32_fcloseall(void)
2478 win32_fgets(char *s, int n, FILE *pf)
2480 return fgets(s, n, pf);
2490 win32_fgetc(FILE *pf)
2496 win32_putc(int c, FILE *pf)
2502 win32_puts(const char *s)
2514 win32_putchar(int c)
2521 #ifndef USE_PERL_SBRK
2523 static char *committed = NULL;
2524 static char *base = NULL;
2525 static char *reserved = NULL;
2526 static char *brk = NULL;
2527 static DWORD pagesize = 0;
2528 static DWORD allocsize = 0;
2536 GetSystemInfo(&info);
2537 /* Pretend page size is larger so we don't perpetually
2538 * call the OS to commit just one page ...
2540 pagesize = info.dwPageSize << 3;
2541 allocsize = info.dwAllocationGranularity;
2543 /* This scheme fails eventually if request for contiguous
2544 * block is denied so reserve big blocks - this is only
2545 * address space not memory ...
2547 if (brk+need >= reserved)
2549 DWORD size = 64*1024*1024;
2551 if (committed && reserved && committed < reserved)
2553 /* Commit last of previous chunk cannot span allocations */
2554 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
2556 committed = reserved;
2558 /* Reserve some (more) space
2559 * Note this is a little sneaky, 1st call passes NULL as reserved
2560 * so lets system choose where we start, subsequent calls pass
2561 * the old end address so ask for a contiguous block
2563 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
2566 reserved = addr+size;
2581 if (brk > committed)
2583 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
2584 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
2599 win32_malloc(size_t size)
2601 return malloc(size);
2605 win32_calloc(size_t numitems, size_t size)
2607 return calloc(numitems,size);
2611 win32_realloc(void *block, size_t size)
2613 return realloc(block,size);
2617 win32_free(void *block)
2624 win32_open_osfhandle(long handle, int flags)
2626 return _open_osfhandle(handle, flags);
2630 win32_get_osfhandle(int fd)
2632 return _get_osfhandle(fd);
2643 SV *sv = sv_newmortal();
2644 /* Make one call with zero size - return value is required size */
2645 DWORD len = GetCurrentDirectory((DWORD)0,NULL);
2646 SvUPGRADE(sv,SVt_PV);
2648 SvCUR(sv) = GetCurrentDirectory((DWORD) SvLEN(sv), SvPVX(sv));
2651 * then it worked, set PV valid,
2652 * else leave it 'undef'
2668 croak("usage: Win32::SetCurrentDirectory($cwd)");
2669 if (SetCurrentDirectory(SvPV_nolen(ST(0))))
2676 XS(w32_GetNextAvailDrive)
2680 char root[] = "_:\\";
2685 if (GetDriveType(root) == 1) {
2694 XS(w32_GetLastError)
2698 XSRETURN_IV(GetLastError());
2702 XS(w32_SetLastError)
2706 croak("usage: Win32::SetLastError($error)");
2707 SetLastError(SvIV(ST(0)));
2715 char *name = getlogin_buffer;
2716 DWORD size = sizeof(getlogin_buffer);
2718 if (GetUserName(name,&size)) {
2719 /* size includes NULL */
2720 ST(0) = sv_2mortal(newSVpvn(name,size-1));
2730 char name[MAX_COMPUTERNAME_LENGTH+1];
2731 DWORD size = sizeof(name);
2733 if (GetComputerName(name,&size)) {
2734 /* size does NOT include NULL :-( */
2735 ST(0) = sv_2mortal(newSVpvn(name,size));
2746 #ifndef HAS_NETWKSTAGETINFO
2747 /* mingw32 (and Win95) don't have NetWksta*(), so do it the old way */
2749 DWORD size = sizeof(name);
2751 if (GetUserName(name,&size)) {
2753 DWORD sidlen = sizeof(sid);
2755 DWORD dnamelen = sizeof(dname);
2757 if (LookupAccountName(NULL, name, (PSID)&sid, &sidlen,
2758 dname, &dnamelen, &snu)) {
2759 XSRETURN_PV(dname); /* all that for this */
2763 /* this way is more reliable, in case user has a local account.
2764 * XXX need dynamic binding of netapi32.dll symbols or this will fail on
2765 * Win95. Probably makes more sense to move it into libwin32. */
2767 DWORD dnamelen = sizeof(dname);
2768 PWKSTA_INFO_100 pwi;
2770 if (NERR_Success == NetWkstaGetInfo(NULL, 100, (LPBYTE*)&pwi)) {
2771 if (pwi->wki100_langroup && *(pwi->wki100_langroup)) {
2772 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_langroup,
2773 -1, (LPSTR)dname, dnamelen, NULL, NULL);
2776 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_computername,
2777 -1, (LPSTR)dname, dnamelen, NULL, NULL);
2779 NetApiBufferFree(pwi);
2791 DWORD flags, filecomplen;
2792 if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
2793 &flags, fsname, sizeof(fsname))) {
2794 if (GIMME_V == G_ARRAY) {
2795 XPUSHs(sv_2mortal(newSVpvn(fsname,strlen(fsname))));
2796 XPUSHs(sv_2mortal(newSViv(flags)));
2797 XPUSHs(sv_2mortal(newSViv(filecomplen)));
2802 XSRETURN_PV(fsname);
2808 XS(w32_GetOSVersion)
2811 OSVERSIONINFO osver;
2813 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
2814 if (GetVersionEx(&osver)) {
2815 XPUSHs(newSVpvn(osver.szCSDVersion, strlen(osver.szCSDVersion)));
2816 XPUSHs(newSViv(osver.dwMajorVersion));
2817 XPUSHs(newSViv(osver.dwMinorVersion));
2818 XPUSHs(newSViv(osver.dwBuildNumber));
2819 XPUSHs(newSViv(osver.dwPlatformId));
2831 XSRETURN_IV(IsWinNT());
2839 XSRETURN_IV(IsWin95());
2843 XS(w32_FormatMessage)
2850 croak("usage: Win32::FormatMessage($errno)");
2852 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
2853 &source, SvIV(ST(0)), 0,
2854 msgbuf, sizeof(msgbuf)-1, NULL))
2855 XSRETURN_PV(msgbuf);
2865 PROCESS_INFORMATION stProcInfo;
2866 STARTUPINFO stStartInfo;
2867 BOOL bSuccess = FALSE;
2870 croak("usage: Win32::Spawn($cmdName, $args, $PID)");
2872 cmd = SvPV_nolen(ST(0));
2873 args = SvPV_nolen(ST(1));
2875 memset(&stStartInfo, 0, sizeof(stStartInfo)); /* Clear the block */
2876 stStartInfo.cb = sizeof(stStartInfo); /* Set the structure size */
2877 stStartInfo.dwFlags = STARTF_USESHOWWINDOW; /* Enable wShowWindow control */
2878 stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE; /* Start min (normal) */
2881 cmd, /* Image path */
2882 args, /* Arguments for command line */
2883 NULL, /* Default process security */
2884 NULL, /* Default thread security */
2885 FALSE, /* Must be TRUE to use std handles */
2886 NORMAL_PRIORITY_CLASS, /* No special scheduling */
2887 NULL, /* Inherit our environment block */
2888 NULL, /* Inherit our currrent directory */
2889 &stStartInfo, /* -> Startup info */
2890 &stProcInfo)) /* <- Process info (if OK) */
2892 CloseHandle(stProcInfo.hThread);/* library source code does this. */
2893 sv_setiv(ST(2), stProcInfo.dwProcessId);
2896 XSRETURN_IV(bSuccess);
2900 XS(w32_GetTickCount)
2903 DWORD msec = GetTickCount();
2911 XS(w32_GetShortPathName)
2918 croak("usage: Win32::GetShortPathName($longPathName)");
2920 shortpath = sv_mortalcopy(ST(0));
2921 SvUPGRADE(shortpath, SVt_PV);
2922 /* src == target is allowed */
2924 len = GetShortPathName(SvPVX(shortpath),
2927 } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
2929 SvCUR_set(shortpath,len);
2937 XS(w32_GetFullPathName)
2946 croak("usage: Win32::GetFullPathName($filename)");
2949 fullpath = sv_mortalcopy(filename);
2950 SvUPGRADE(fullpath, SVt_PV);
2952 len = GetFullPathName(SvPVX(filename),
2956 } while (len >= SvLEN(fullpath) && sv_grow(fullpath,len+1));
2958 if (GIMME_V == G_ARRAY) {
2960 XST_mPV(1,filepart);
2961 len = filepart - SvPVX(fullpath);
2964 SvCUR_set(fullpath,len);
2972 XS(w32_GetLongPathName)
2976 char tmpbuf[MAX_PATH+1];
2981 croak("usage: Win32::GetLongPathName($pathname)");
2984 pathstr = SvPV(path,len);
2985 strcpy(tmpbuf, pathstr);
2986 pathstr = win32_longpath(tmpbuf);
2988 ST(0) = sv_2mortal(newSVpvn(pathstr, strlen(pathstr)));
2999 croak("usage: Win32::Sleep($milliseconds)");
3009 croak("usage: Win32::CopyFile($from, $to, $overwrite)");
3010 if (CopyFile(SvPV_nolen(ST(0)), SvPV_nolen(ST(1)), !SvTRUE(ST(2))))
3016 Perl_init_os_extras()
3018 char *file = __FILE__;
3021 w32_perlshell_tokens = Nullch;
3022 w32_perlshell_items = -1;
3023 w32_fdpid = newAV(); /* XXX needs to be in Perl_win32_init()? */
3024 New(1313, w32_children, 1, child_tab);
3025 w32_num_children = 0;
3027 /* these names are Activeware compatible */
3028 newXS("Win32::GetCwd", w32_GetCwd, file);
3029 newXS("Win32::SetCwd", w32_SetCwd, file);
3030 newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
3031 newXS("Win32::GetLastError", w32_GetLastError, file);
3032 newXS("Win32::SetLastError", w32_SetLastError, file);
3033 newXS("Win32::LoginName", w32_LoginName, file);
3034 newXS("Win32::NodeName", w32_NodeName, file);
3035 newXS("Win32::DomainName", w32_DomainName, file);
3036 newXS("Win32::FsType", w32_FsType, file);
3037 newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
3038 newXS("Win32::IsWinNT", w32_IsWinNT, file);
3039 newXS("Win32::IsWin95", w32_IsWin95, file);
3040 newXS("Win32::FormatMessage", w32_FormatMessage, file);
3041 newXS("Win32::Spawn", w32_Spawn, file);
3042 newXS("Win32::GetTickCount", w32_GetTickCount, file);
3043 newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
3044 newXS("Win32::GetFullPathName", w32_GetFullPathName, file);
3045 newXS("Win32::GetLongPathName", w32_GetLongPathName, file);
3046 newXS("Win32::CopyFile", w32_CopyFile, file);
3047 newXS("Win32::Sleep", w32_Sleep, file);
3049 /* XXX Bloat Alert! The following Activeware preloads really
3050 * ought to be part of Win32::Sys::*, so they're not included
3053 /* LookupAccountName
3055 * InitiateSystemShutdown
3056 * AbortSystemShutdown
3057 * ExpandEnvrironmentStrings
3062 Perl_win32_init(int *argcp, char ***argvp)
3064 /* Disable floating point errors, Perl will trap the ones we
3065 * care about. VC++ RTL defaults to switching these off
3066 * already, but the Borland RTL doesn't. Since we don't
3067 * want to be at the vendor's whim on the default, we set
3068 * it explicitly here.
3070 #if !defined(_ALPHA_) && !defined(__GNUC__)
3071 _control87(MCW_EM, MCW_EM);
3076 #ifdef USE_BINMODE_SCRIPTS
3079 win32_strip_return(SV *sv)
3081 char *s = SvPVX(sv);
3082 char *e = s+SvCUR(sv);
3086 if (*s == '\r' && s[1] == '\n')
3096 SvCUR_set(sv,d-SvPVX(sv));