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 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);
254 win32_get_privlib(char *pl)
256 char *stdlib = "lib";
257 char buffer[MAX_PATH+1];
260 SV *sv = sv_2mortal(newSVpvn("",127));
262 /* $stdlib = $HKCU{"lib-$]"} || $HKLM{"lib-$]"} || $HKCU{"lib"} || $HKLM{"lib"} || ""; */
263 sprintf(buffer, "%s-%s", stdlib, pl);
265 if (!GetRegStr(buffer, path, &datalen))
266 (void)GetRegStr(stdlib, path, &datalen);
268 /* $stdlib .= ";$EMD/../../lib" */
269 (void)get_emd_part(path, stdlib, ARCHNAME, "bin", Nullch);
270 SvCUR_set(sv, strlen(*path));
271 SvLEN_set(sv, SvCUR(sv)+1);
276 win32_get_sitelib(char *pl)
278 char *sitelib = "sitelib";
280 char pathstr[MAX_PATH+1];
282 char **path1, *str1 = Nullch;
283 char **path2, *str2 = Nullch;
285 SV *sv1 = sv_2mortal(newSVpvn("",127));
286 SV *sv2 = sv_2mortal(newSVpvn("",127));
288 /* $HKCU{"sitelib-$]"} || $HKLM{"sitelib-$]"} . ---; */
289 sprintf(regstr, "%s-%s", sitelib, pl);
291 (void)GetRegStr(regstr, path1, &datalen);
294 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/site/$]/lib"; */
295 sprintf(pathstr, "site/%s/lib", pl);
296 str1 = get_emd_part(path1, pathstr, ARCHNAME, "bin", pl, Nullch);
298 /* $HKCU{'sitelib'} || $HKLM{'sitelib'} . ---; */
300 (void)GetRegStr(sitelib, path2, &datalen);
303 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/site/lib"; */
304 str2 = get_emd_part(path2, "site/lib", ARCHNAME, "bin", pl, Nullch);
306 SvCUR_set(sv1, strlen(*path1));
307 SvLEN_set(sv1, SvCUR(sv1)+1);
308 SvCUR_set(sv2, strlen(*path2));
309 SvLEN_set(sv2, SvCUR(sv2)+1);
316 sv_catpvn(sv1, ";", 1);
324 has_shell_metachars(char *ptr)
330 * Scan string looking for redirection (< or >) or pipe
331 * characters (|) that are not in a quoted string.
332 * Shell variable interpolation (%VAR%) can also happen inside strings.
364 #if !defined(PERL_OBJECT)
365 /* since the current process environment is being updated in util.c
366 * the library functions will get the correct environment
369 my_popen(char *cmd, char *mode)
372 #define fixcmd(x) { \
373 char *pspace = strchr((x),' '); \
376 while (p < pspace) { \
387 PERL_FLUSHALL_FOR_CHILD;
388 return win32_popen(cmd, mode);
392 my_pclose(PerlIO *fp)
394 return win32_pclose(fp);
401 static OSVERSIONINFO osver;
403 if (osver.dwPlatformId != w32_platform) {
404 memset(&osver, 0, sizeof(OSVERSIONINFO));
405 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
406 GetVersionEx(&osver);
407 w32_platform = osver.dwPlatformId;
409 return (w32_platform);
412 /* Tokenize a string. Words are null-separated, and the list
413 * ends with a doubled null. Any character (except null and
414 * including backslash) may be escaped by preceding it with a
415 * backslash (the backslash will be stripped).
416 * Returns number of words in result buffer.
419 tokenize(char *str, char **dest, char ***destv)
421 char *retstart = Nullch;
422 char **retvstart = 0;
425 int slen = strlen(str);
427 register char **retv;
428 New(1307, ret, slen+2, char);
429 New(1308, retv, (slen+3)/2, char*);
437 if (*ret == '\\' && *str)
439 else if (*ret == ' ') {
455 retvstart[items] = Nullch;
467 if (!w32_perlshell_tokens) {
468 /* we don't use COMSPEC here for two reasons:
469 * 1. the same reason perl on UNIX doesn't use SHELL--rampant and
470 * uncontrolled unportability of the ensuing scripts.
471 * 2. PERL5SHELL could be set to a shell that may not be fit for
472 * interactive use (which is what most programs look in COMSPEC
475 char* defaultshell = (IsWinNT() ? "cmd.exe /x/c" : "command.com /c");
476 char *usershell = getenv("PERL5SHELL");
477 w32_perlshell_items = tokenize(usershell ? usershell : defaultshell,
478 &w32_perlshell_tokens,
484 do_aspawn(void *vreally, void **vmark, void **vsp)
486 SV *really = (SV*)vreally;
487 SV **mark = (SV**)vmark;
499 New(1306, argv, (sp - mark) + w32_perlshell_items + 2, char*);
501 if (SvNIOKp(*(mark+1)) && !SvPOKp(*(mark+1))) {
506 while (++mark <= sp) {
507 if (*mark && (str = SvPV_nolen(*mark)))
514 status = win32_spawnvp(flag,
515 (const char*)(really ? SvPV_nolen(really) : argv[0]),
516 (const char* const*)argv);
518 if (status < 0 && (errno == ENOEXEC || errno == ENOENT)) {
519 /* possible shell-builtin, invoke with shell */
521 sh_items = w32_perlshell_items;
523 argv[index+sh_items] = argv[index];
524 while (--sh_items >= 0)
525 argv[sh_items] = w32_perlshell_vec[sh_items];
527 status = win32_spawnvp(flag,
528 (const char*)(really ? SvPV_nolen(really) : argv[0]),
529 (const char* const*)argv);
532 if (flag != P_NOWAIT) {
535 warn("Can't spawn \"%s\": %s", argv[0], strerror(errno));
540 PL_statusvalue = status;
547 do_spawn2(char *cmd, int exectype)
553 BOOL needToTry = TRUE;
556 /* Save an extra exec if possible. See if there are shell
557 * metacharacters in it */
558 if (!has_shell_metachars(cmd)) {
559 New(1301,argv, strlen(cmd) / 2 + 2, char*);
560 New(1302,cmd2, strlen(cmd) + 1, char);
563 for (s = cmd2; *s;) {
564 while (*s && isspace(*s))
568 while (*s && !isspace(*s))
577 status = win32_spawnvp(P_WAIT, argv[0],
578 (const char* const*)argv);
580 case EXECF_SPAWN_NOWAIT:
581 status = win32_spawnvp(P_NOWAIT, argv[0],
582 (const char* const*)argv);
585 status = win32_execvp(argv[0], (const char* const*)argv);
588 if (status != -1 || errno == 0)
598 New(1306, argv, w32_perlshell_items + 2, char*);
599 while (++i < w32_perlshell_items)
600 argv[i] = w32_perlshell_vec[i];
605 status = win32_spawnvp(P_WAIT, argv[0],
606 (const char* const*)argv);
608 case EXECF_SPAWN_NOWAIT:
609 status = win32_spawnvp(P_NOWAIT, argv[0],
610 (const char* const*)argv);
613 status = win32_execvp(argv[0], (const char* const*)argv);
619 if (exectype != EXECF_SPAWN_NOWAIT) {
622 warn("Can't %s \"%s\": %s",
623 (exectype == EXECF_EXEC ? "exec" : "spawn"),
624 cmd, strerror(errno));
629 PL_statusvalue = status;
637 return do_spawn2(cmd, EXECF_SPAWN);
641 do_spawn_nowait(char *cmd)
643 return do_spawn2(cmd, EXECF_SPAWN_NOWAIT);
649 do_spawn2(cmd, EXECF_EXEC);
653 /* The idea here is to read all the directory names into a string table
654 * (separated by nulls) and when one of the other dir functions is called
655 * return the pointer to the current file name.
658 win32_opendir(char *filename)
663 char scanname[MAX_PATH+3];
665 WIN32_FIND_DATA FindData;
668 len = strlen(filename);
672 /* check to see if filename is a directory */
673 if (win32_stat(filename, &sbuf) < 0 || !S_ISDIR(sbuf.st_mode))
676 /* Get us a DIR structure */
677 Newz(1303, p, 1, DIR);
681 /* Create the search pattern */
682 strcpy(scanname, filename);
684 /* bare drive name means look in cwd for drive */
685 if (len == 2 && isALPHA(scanname[0]) && scanname[1] == ':') {
686 scanname[len++] = '.';
687 scanname[len++] = '/';
689 else if (scanname[len-1] != '/' && scanname[len-1] != '\\') {
690 scanname[len++] = '/';
692 scanname[len++] = '*';
693 scanname[len] = '\0';
695 /* do the FindFirstFile call */
696 fh = FindFirstFile(scanname, &FindData);
697 if (fh == INVALID_HANDLE_VALUE) {
698 /* FindFirstFile() fails on empty drives! */
699 if (GetLastError() == ERROR_FILE_NOT_FOUND)
705 /* now allocate the first part of the string table for
706 * the filenames that we find.
708 idx = strlen(FindData.cFileName)+1;
709 New(1304, p->start, idx, char);
710 if (p->start == NULL)
711 croak("opendir: malloc failed!\n");
712 strcpy(p->start, FindData.cFileName);
715 /* loop finding all the files that match the wildcard
716 * (which should be all of them in this directory!).
717 * the variable idx should point one past the null terminator
718 * of the previous string found.
720 while (FindNextFile(fh, &FindData)) {
721 len = strlen(FindData.cFileName);
722 /* bump the string table size by enough for the
723 * new name and it's null terminator
725 Renew(p->start, idx+len+1, char);
726 if (p->start == NULL)
727 croak("opendir: malloc failed!\n");
728 strcpy(&p->start[idx], FindData.cFileName);
739 /* Readdir just returns the current string pointer and bumps the
740 * string pointer to the nDllExport entry.
743 win32_readdir(DIR *dirp)
746 static int dummy = 0;
749 /* first set up the structure to return */
750 len = strlen(dirp->curr);
751 strcpy(dirp->dirstr.d_name, dirp->curr);
752 dirp->dirstr.d_namlen = len;
755 dirp->dirstr.d_ino = dummy++;
757 /* Now set up for the nDllExport call to readdir */
758 dirp->curr += len + 1;
759 if (dirp->curr >= (dirp->start + dirp->size)) {
763 return &(dirp->dirstr);
769 /* Telldir returns the current string pointer position */
771 win32_telldir(DIR *dirp)
773 return (long) dirp->curr;
777 /* Seekdir moves the string pointer to a previously saved position
781 win32_seekdir(DIR *dirp, long loc)
783 dirp->curr = (char *)loc;
786 /* Rewinddir resets the string pointer to the start */
788 win32_rewinddir(DIR *dirp)
790 dirp->curr = dirp->start;
793 /* free the memory allocated by opendir */
795 win32_closedir(DIR *dirp)
797 Safefree(dirp->start);
810 * Just pretend that everyone is a superuser. NT will let us know if
811 * we don\'t really have permission to do something.
814 #define ROOT_UID ((uid_t)0)
815 #define ROOT_GID ((gid_t)0)
844 return (auid == ROOT_UID ? 0 : -1);
850 return (agid == ROOT_GID ? 0 : -1);
857 char *buf = getlogin_buffer;
858 DWORD size = sizeof(getlogin_buffer);
859 if (GetUserName(buf,&size))
865 chown(const char *path, uid_t owner, gid_t group)
875 for (child = 0 ; child < w32_num_children ; ++child) {
876 if (w32_child_pids[child] == pid)
883 remove_dead_process(long child)
886 CloseHandle(w32_child_handles[child]);
887 Copy(&w32_child_handles[child+1], &w32_child_handles[child],
888 (w32_num_children-child-1), HANDLE);
889 Copy(&w32_child_pids[child+1], &w32_child_pids[child],
890 (w32_num_children-child-1), DWORD);
896 win32_kill(int pid, int sig)
899 hProcess = OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid);
900 if (hProcess && TerminateProcess(hProcess, sig))
901 CloseHandle(hProcess);
913 DllExport unsigned int
914 win32_sleep(unsigned int t)
921 win32_stat(const char *path, struct stat *buffer)
924 int l = strlen(path);
928 switch(path[l - 1]) {
929 /* FindFirstFile() and stat() are buggy with a trailing
930 * backslash, so change it to a forward slash :-( */
932 strncpy(t, path, l-1);
937 /* FindFirstFile() is buggy with "x:", so add a dot :-( */
939 if (l == 2 && isALPHA(path[0])) {
940 t[0] = path[0]; t[1] = ':'; t[2] = '.'; t[3] = '\0';
947 res = stat(path,buffer);
949 /* CRT is buggy on sharenames, so make sure it really isn't.
950 * XXX using GetFileAttributesEx() will enable us to set
951 * buffer->st_*time (but note that's not available on the
952 * Windows of 1995) */
953 DWORD r = GetFileAttributes(path);
954 if (r != 0xffffffff && (r & FILE_ATTRIBUTE_DIRECTORY)) {
955 /* buffer may still contain old garbage since stat() failed */
956 Zero(buffer, 1, struct stat);
957 buffer->st_mode = S_IFDIR | S_IREAD;
959 if (!(r & FILE_ATTRIBUTE_READONLY))
960 buffer->st_mode |= S_IWRITE | S_IEXEC;
965 if (l == 3 && isALPHA(path[0]) && path[1] == ':'
966 && (path[2] == '\\' || path[2] == '/'))
968 /* The drive can be inaccessible, some _stat()s are buggy */
969 if (!GetVolumeInformation(path,NULL,0,NULL,NULL,NULL,NULL,0)) {
975 if (S_ISDIR(buffer->st_mode))
976 buffer->st_mode |= S_IWRITE | S_IEXEC;
977 else if (S_ISREG(buffer->st_mode)) {
978 if (l >= 4 && path[l-4] == '.') {
979 const char *e = path + l - 3;
980 if (strnicmp(e,"exe",3)
981 && strnicmp(e,"bat",3)
982 && strnicmp(e,"com",3)
983 && (IsWin95() || strnicmp(e,"cmd",3)))
984 buffer->st_mode &= ~S_IEXEC;
986 buffer->st_mode |= S_IEXEC;
989 buffer->st_mode &= ~S_IEXEC;
996 /* Find the longname of a given path. path is destructively modified.
997 * It should have space for at least MAX_PATH characters. */
999 win32_longpath(char *path)
1001 WIN32_FIND_DATA fdata;
1003 char tmpbuf[MAX_PATH+1];
1004 char *tmpstart = tmpbuf;
1011 if (isALPHA(path[0]) && path[1] == ':' &&
1012 (path[2] == '/' || path[2] == '\\'))
1015 *tmpstart++ = path[0];
1019 else if ((path[0] == '/' || path[0] == '\\') &&
1020 (path[1] == '/' || path[1] == '\\'))
1023 *tmpstart++ = path[0];
1024 *tmpstart++ = path[1];
1025 /* copy machine name */
1026 while (*start && *start != '/' && *start != '\\')
1027 *tmpstart++ = *start++;
1029 *tmpstart++ = *start;
1031 /* copy share name */
1032 while (*start && *start != '/' && *start != '\\')
1033 *tmpstart++ = *start++;
1037 if (sep == '/' || sep == '\\')
1041 /* walk up to slash */
1042 while (*start && *start != '/' && *start != '\\')
1045 /* discard doubled slashes */
1046 while (*start && (start[1] == '/' || start[1] == '\\'))
1050 /* stop and find full name of component */
1052 fhand = FindFirstFile(path,&fdata);
1053 if (fhand != INVALID_HANDLE_VALUE) {
1054 strcpy(tmpstart, fdata.cFileName);
1055 tmpstart += strlen(fdata.cFileName);
1063 /* failed a step, just return without side effects */
1064 /*PerlIO_printf(PerlIO_stderr(), "Failed to find %s\n", path);*/
1069 strcpy(path,tmpbuf);
1073 #ifndef USE_WIN32_RTL_ENV
1076 win32_getenv(const char *name)
1078 static char *curitem = Nullch; /* XXX threadead */
1079 static DWORD curlen = 0; /* XXX threadead */
1083 New(1305,curitem,curlen,char);
1086 needlen = GetEnvironmentVariable(name,curitem,curlen);
1088 while (needlen > curlen) {
1089 Renew(curitem,needlen,char);
1091 needlen = GetEnvironmentVariable(name,curitem,curlen);
1095 /* allow any environment variables that begin with 'PERL'
1096 to be stored in the registry */
1100 if (strncmp(name, "PERL", 4) == 0) {
1106 curitem = GetRegStr(name, &curitem, &curlen);
1109 if (curitem && *curitem == '\0')
1116 win32_putenv(const char *name)
1122 New(1309,curitem,strlen(name)+1,char);
1123 strcpy(curitem, name);
1124 val = strchr(curitem, '=');
1126 /* The sane way to deal with the environment.
1127 * Has these advantages over putenv() & co.:
1128 * * enables us to store a truly empty value in the
1129 * environment (like in UNIX).
1130 * * we don't have to deal with RTL globals, bugs and leaks.
1132 * Why you may want to enable USE_WIN32_RTL_ENV:
1133 * * environ[] and RTL functions will not reflect changes,
1134 * which might be an issue if extensions want to access
1135 * the env. via RTL. This cuts both ways, since RTL will
1136 * not see changes made by extensions that call the Win32
1137 * functions directly, either.
1141 if(SetEnvironmentVariable(curitem, *val ? val : NULL))
1152 filetime_to_clock(PFILETIME ft)
1154 __int64 qw = ft->dwHighDateTime;
1156 qw |= ft->dwLowDateTime;
1157 qw /= 10000; /* File time ticks at 0.1uS, clock at 1mS */
1162 win32_times(struct tms *timebuf)
1167 if (GetProcessTimes(GetCurrentProcess(), &dummy, &dummy,
1169 timebuf->tms_utime = filetime_to_clock(&user);
1170 timebuf->tms_stime = filetime_to_clock(&kernel);
1171 timebuf->tms_cutime = 0;
1172 timebuf->tms_cstime = 0;
1175 /* That failed - e.g. Win95 fallback to clock() */
1176 clock_t t = clock();
1177 timebuf->tms_utime = t;
1178 timebuf->tms_stime = 0;
1179 timebuf->tms_cutime = 0;
1180 timebuf->tms_cstime = 0;
1185 /* fix utime() so it works on directories in NT
1186 * thanks to Jan Dubois <jan.dubois@ibm.net>
1189 filetime_from_time(PFILETIME pFileTime, time_t Time)
1191 struct tm *pTM = gmtime(&Time);
1192 SYSTEMTIME SystemTime;
1197 SystemTime.wYear = pTM->tm_year + 1900;
1198 SystemTime.wMonth = pTM->tm_mon + 1;
1199 SystemTime.wDay = pTM->tm_mday;
1200 SystemTime.wHour = pTM->tm_hour;
1201 SystemTime.wMinute = pTM->tm_min;
1202 SystemTime.wSecond = pTM->tm_sec;
1203 SystemTime.wMilliseconds = 0;
1205 return SystemTimeToFileTime(&SystemTime, pFileTime);
1209 win32_utime(const char *filename, struct utimbuf *times)
1215 struct utimbuf TimeBuffer;
1217 int rc = utime(filename,times);
1218 /* EACCES: path specifies directory or readonly file */
1219 if (rc == 0 || errno != EACCES /* || !IsWinNT() */)
1222 if (times == NULL) {
1223 times = &TimeBuffer;
1224 time(×->actime);
1225 times->modtime = times->actime;
1228 /* This will (and should) still fail on readonly files */
1229 handle = CreateFile(filename, GENERIC_READ | GENERIC_WRITE,
1230 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1231 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1232 if (handle == INVALID_HANDLE_VALUE)
1235 if (GetFileTime(handle, &ftCreate, &ftAccess, &ftWrite) &&
1236 filetime_from_time(&ftAccess, times->actime) &&
1237 filetime_from_time(&ftWrite, times->modtime) &&
1238 SetFileTime(handle, &ftCreate, &ftAccess, &ftWrite))
1243 CloseHandle(handle);
1248 win32_uname(struct utsname *name)
1250 struct hostent *hep;
1251 STRLEN nodemax = sizeof(name->nodename)-1;
1252 OSVERSIONINFO osver;
1254 memset(&osver, 0, sizeof(OSVERSIONINFO));
1255 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1256 if (GetVersionEx(&osver)) {
1258 switch (osver.dwPlatformId) {
1259 case VER_PLATFORM_WIN32_WINDOWS:
1260 strcpy(name->sysname, "Windows");
1262 case VER_PLATFORM_WIN32_NT:
1263 strcpy(name->sysname, "Windows NT");
1265 case VER_PLATFORM_WIN32s:
1266 strcpy(name->sysname, "Win32s");
1269 strcpy(name->sysname, "Win32 Unknown");
1274 sprintf(name->release, "%d.%d",
1275 osver.dwMajorVersion, osver.dwMinorVersion);
1278 sprintf(name->version, "Build %d",
1279 osver.dwPlatformId == VER_PLATFORM_WIN32_NT
1280 ? osver.dwBuildNumber : (osver.dwBuildNumber & 0xffff));
1281 if (osver.szCSDVersion[0]) {
1282 char *buf = name->version + strlen(name->version);
1283 sprintf(buf, " (%s)", osver.szCSDVersion);
1287 *name->sysname = '\0';
1288 *name->version = '\0';
1289 *name->release = '\0';
1293 hep = win32_gethostbyname("localhost");
1295 STRLEN len = strlen(hep->h_name);
1296 if (len <= nodemax) {
1297 strcpy(name->nodename, hep->h_name);
1300 strncpy(name->nodename, hep->h_name, nodemax);
1301 name->nodename[nodemax] = '\0';
1306 if (!GetComputerName(name->nodename, &sz))
1307 *name->nodename = '\0';
1310 /* machine (architecture) */
1314 GetSystemInfo(&info);
1317 switch (info.u.s.wProcessorArchitecture) {
1319 switch (info.wProcessorArchitecture) {
1321 case PROCESSOR_ARCHITECTURE_INTEL:
1322 arch = "x86"; break;
1323 case PROCESSOR_ARCHITECTURE_MIPS:
1324 arch = "mips"; break;
1325 case PROCESSOR_ARCHITECTURE_ALPHA:
1326 arch = "alpha"; break;
1327 case PROCESSOR_ARCHITECTURE_PPC:
1328 arch = "ppc"; break;
1330 arch = "unknown"; break;
1332 strcpy(name->machine, arch);
1338 win32_waitpid(int pid, int *status, int flags)
1342 return win32_wait(status);
1344 long child = find_pid(pid);
1346 HANDLE hProcess = w32_child_handles[child];
1347 DWORD waitcode = WaitForSingleObject(hProcess, INFINITE);
1348 if (waitcode != WAIT_FAILED) {
1349 if (GetExitCodeProcess(hProcess, &waitcode)) {
1350 *status = (int)((waitcode & 0xff) << 8);
1351 retval = (int)w32_child_pids[child];
1352 remove_dead_process(child);
1360 retval = cwait(status, pid, WAIT_CHILD);
1361 /* cwait() returns "correctly" on Borland */
1362 #ifndef __BORLANDC__
1368 return retval >= 0 ? pid : retval;
1372 win32_wait(int *status)
1374 /* XXX this wait emulation only knows about processes
1375 * spawned via win32_spawnvp(P_NOWAIT, ...).
1378 DWORD exitcode, waitcode;
1380 if (!w32_num_children) {
1385 /* if a child exists, wait for it to die */
1386 waitcode = WaitForMultipleObjects(w32_num_children,
1390 if (waitcode != WAIT_FAILED) {
1391 if (waitcode >= WAIT_ABANDONED_0
1392 && waitcode < WAIT_ABANDONED_0 + w32_num_children)
1393 i = waitcode - WAIT_ABANDONED_0;
1395 i = waitcode - WAIT_OBJECT_0;
1396 if (GetExitCodeProcess(w32_child_handles[i], &exitcode) ) {
1397 *status = (int)((exitcode & 0xff) << 8);
1398 retval = (int)w32_child_pids[i];
1399 remove_dead_process(i);
1405 errno = GetLastError();
1409 static UINT timerid = 0;
1411 static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
1413 KillTimer(NULL,timerid);
1418 DllExport unsigned int
1419 win32_alarm(unsigned int sec)
1422 * the 'obvious' implentation is SetTimer() with a callback
1423 * which does whatever receiving SIGALRM would do
1424 * we cannot use SIGALRM even via raise() as it is not
1425 * one of the supported codes in <signal.h>
1427 * Snag is unless something is looking at the message queue
1428 * nothing happens :-(
1432 timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
1434 croak("Cannot set timer");
1440 KillTimer(NULL,timerid);
1447 #if defined(HAVE_DES_FCRYPT) || defined(PERL_OBJECT)
1448 #ifdef HAVE_DES_FCRYPT
1449 extern char * des_fcrypt(const char *txt, const char *salt, char *cbuf);
1453 win32_crypt(const char *txt, const char *salt)
1455 #ifdef HAVE_DES_FCRYPT
1457 return des_fcrypt(txt, salt, crypt_buffer);
1459 die("The crypt() function is unimplemented due to excessive paranoia.");
1465 #ifdef USE_FIXED_OSFHANDLE
1467 EXTERN_C int __cdecl _alloc_osfhnd(void);
1468 EXTERN_C int __cdecl _set_osfhnd(int fh, long value);
1469 EXTERN_C void __cdecl _lock_fhandle(int);
1470 EXTERN_C void __cdecl _unlock_fhandle(int);
1471 EXTERN_C void __cdecl _unlock(int);
1473 #if (_MSC_VER >= 1000)
1475 long osfhnd; /* underlying OS file HANDLE */
1476 char osfile; /* attributes of file (e.g., open in text mode?) */
1477 char pipech; /* one char buffer for handles opened on pipes */
1478 #if defined (_MT) && !defined (DLL_FOR_WIN32S)
1480 CRITICAL_SECTION lock;
1481 #endif /* defined (_MT) && !defined (DLL_FOR_WIN32S) */
1484 EXTERN_C ioinfo * __pioinfo[];
1486 #define IOINFO_L2E 5
1487 #define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
1488 #define _pioinfo(i) (__pioinfo[i >> IOINFO_L2E] + (i & (IOINFO_ARRAY_ELTS - 1)))
1489 #define _osfile(i) (_pioinfo(i)->osfile)
1491 #else /* (_MSC_VER >= 1000) */
1492 extern char _osfile[];
1493 #endif /* (_MSC_VER >= 1000) */
1495 #define FOPEN 0x01 /* file handle open */
1496 #define FAPPEND 0x20 /* file handle opened O_APPEND */
1497 #define FDEV 0x40 /* file handle refers to device */
1498 #define FTEXT 0x80 /* file handle is in text mode */
1500 #define _STREAM_LOCKS 26 /* Table of stream locks */
1501 #define _LAST_STREAM_LOCK (_STREAM_LOCKS+_NSTREAM_-1) /* Last stream lock */
1502 #define _FH_LOCKS (_LAST_STREAM_LOCK+1) /* Table of fh locks */
1505 *int my_open_osfhandle(long osfhandle, int flags) - open C Runtime file handle
1508 * This function allocates a free C Runtime file handle and associates
1509 * it with the Win32 HANDLE specified by the first parameter. This is a
1510 * temperary fix for WIN95's brain damage GetFileType() error on socket
1511 * we just bypass that call for socket
1514 * long osfhandle - Win32 HANDLE to associate with C Runtime file handle.
1515 * int flags - flags to associate with C Runtime file handle.
1518 * returns index of entry in fh, if successful
1519 * return -1, if no free entry is found
1523 *******************************************************************************/
1526 my_open_osfhandle(long osfhandle, int flags)
1529 char fileflags; /* _osfile flags */
1531 /* copy relevant flags from second parameter */
1534 if (flags & O_APPEND)
1535 fileflags |= FAPPEND;
1540 /* attempt to allocate a C Runtime file handle */
1541 if ((fh = _alloc_osfhnd()) == -1) {
1542 errno = EMFILE; /* too many open files */
1543 _doserrno = 0L; /* not an OS error */
1544 return -1; /* return error to caller */
1547 /* the file is open. now, set the info in _osfhnd array */
1548 _set_osfhnd(fh, osfhandle);
1550 fileflags |= FOPEN; /* mark as open */
1552 #if (_MSC_VER >= 1000)
1553 _osfile(fh) = fileflags; /* set osfile entry */
1554 _unlock_fhandle(fh);
1556 _osfile[fh] = fileflags; /* set osfile entry */
1557 _unlock(fh+_FH_LOCKS); /* unlock handle */
1560 return fh; /* return handle */
1563 #define _open_osfhandle my_open_osfhandle
1564 #endif /* USE_FIXED_OSFHANDLE */
1566 /* simulate flock by locking a range on the file */
1568 #define LK_ERR(f,i) ((f) ? (i = 0) : (errno = GetLastError()))
1569 #define LK_LEN 0xffff0000
1572 win32_flock(int fd, int oper)
1579 croak("flock() unimplemented on this platform");
1582 fh = (HANDLE)_get_osfhandle(fd);
1583 memset(&o, 0, sizeof(o));
1586 case LOCK_SH: /* shared lock */
1587 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
1589 case LOCK_EX: /* exclusive lock */
1590 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
1592 case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
1593 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
1595 case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
1596 LK_ERR(LockFileEx(fh,
1597 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
1598 0, LK_LEN, 0, &o),i);
1600 case LOCK_UN: /* unlock lock */
1601 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, 0, &o),i);
1603 default: /* unknown */
1614 * redirected io subsystem for all XS modules
1627 return (&(_environ));
1630 /* the rest are the remapped stdio routines */
1650 win32_ferror(FILE *fp)
1652 return (ferror(fp));
1657 win32_feof(FILE *fp)
1663 * Since the errors returned by the socket error function
1664 * WSAGetLastError() are not known by the library routine strerror
1665 * we have to roll our own.
1669 win32_strerror(int e)
1671 #ifndef __BORLANDC__ /* Borland intolerance */
1672 extern int sys_nerr;
1676 if (e < 0 || e > sys_nerr) {
1681 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
1682 strerror_buffer, sizeof(strerror_buffer), NULL) == 0)
1683 strcpy(strerror_buffer, "Unknown Error");
1685 return strerror_buffer;
1691 win32_str_os_error(void *sv, DWORD dwErr)
1695 dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
1696 |FORMAT_MESSAGE_IGNORE_INSERTS
1697 |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
1698 dwErr, 0, (char *)&sMsg, 1, NULL);
1700 while (0 < dwLen && isspace(sMsg[--dwLen]))
1702 if ('.' != sMsg[dwLen])
1707 sMsg = (char*)LocalAlloc(0, 64/**sizeof(TCHAR)*/);
1708 dwLen = sprintf(sMsg,
1709 "Unknown error #0x%lX (lookup 0x%lX)",
1710 dwErr, GetLastError());
1712 sv_setpvn((SV*)sv, sMsg, dwLen);
1718 win32_fprintf(FILE *fp, const char *format, ...)
1721 va_start(marker, format); /* Initialize variable arguments. */
1723 return (vfprintf(fp, format, marker));
1727 win32_printf(const char *format, ...)
1730 va_start(marker, format); /* Initialize variable arguments. */
1732 return (vprintf(format, marker));
1736 win32_vfprintf(FILE *fp, const char *format, va_list args)
1738 return (vfprintf(fp, format, args));
1742 win32_vprintf(const char *format, va_list args)
1744 return (vprintf(format, args));
1748 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
1750 return fread(buf, size, count, fp);
1754 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
1756 return fwrite(buf, size, count, fp);
1760 win32_fopen(const char *filename, const char *mode)
1762 if (stricmp(filename, "/dev/null")==0)
1763 return fopen("NUL", mode);
1764 return fopen(filename, mode);
1767 #ifndef USE_SOCKETS_AS_HANDLES
1769 #define fdopen my_fdopen
1773 win32_fdopen( int handle, const char *mode)
1775 return fdopen(handle, (char *) mode);
1779 win32_freopen( const char *path, const char *mode, FILE *stream)
1781 if (stricmp(path, "/dev/null")==0)
1782 return freopen("NUL", mode, stream);
1783 return freopen(path, mode, stream);
1787 win32_fclose(FILE *pf)
1789 return my_fclose(pf); /* defined in win32sck.c */
1793 win32_fputs(const char *s,FILE *pf)
1795 return fputs(s, pf);
1799 win32_fputc(int c,FILE *pf)
1805 win32_ungetc(int c,FILE *pf)
1807 return ungetc(c,pf);
1811 win32_getc(FILE *pf)
1817 win32_fileno(FILE *pf)
1823 win32_clearerr(FILE *pf)
1830 win32_fflush(FILE *pf)
1836 win32_ftell(FILE *pf)
1842 win32_fseek(FILE *pf,long offset,int origin)
1844 return fseek(pf, offset, origin);
1848 win32_fgetpos(FILE *pf,fpos_t *p)
1850 return fgetpos(pf, p);
1854 win32_fsetpos(FILE *pf,const fpos_t *p)
1856 return fsetpos(pf, p);
1860 win32_rewind(FILE *pf)
1880 win32_fstat(int fd,struct stat *sbufptr)
1882 return fstat(fd,sbufptr);
1886 win32_pipe(int *pfd, unsigned int size, int mode)
1888 return _pipe(pfd, size, mode);
1892 * a popen() clone that respects PERL5SHELL
1896 win32_popen(const char *command, const char *mode)
1898 #ifdef USE_RTL_POPEN
1899 return _popen(command, mode);
1907 /* establish which ends read and write */
1908 if (strchr(mode,'w')) {
1909 stdfd = 0; /* stdin */
1913 else if (strchr(mode,'r')) {
1914 stdfd = 1; /* stdout */
1921 /* set the correct mode */
1922 if (strchr(mode,'b'))
1924 else if (strchr(mode,'t'))
1927 ourmode = _fmode & (O_TEXT | O_BINARY);
1929 /* the child doesn't inherit handles */
1930 ourmode |= O_NOINHERIT;
1932 if (win32_pipe( p, 512, ourmode) == -1)
1935 /* save current stdfd */
1936 if ((oldfd = win32_dup(stdfd)) == -1)
1939 /* make stdfd go to child end of pipe (implicitly closes stdfd) */
1940 /* stdfd will be inherited by the child */
1941 if (win32_dup2(p[child], stdfd) == -1)
1944 /* close the child end in parent */
1945 win32_close(p[child]);
1947 /* start the child */
1948 if ((childpid = do_spawn_nowait((char*)command)) == -1)
1951 /* revert stdfd to whatever it was before */
1952 if (win32_dup2(oldfd, stdfd) == -1)
1955 /* close saved handle */
1958 sv_setiv(*av_fetch(w32_fdpid, p[parent], TRUE), childpid);
1960 /* we have an fd, return a file stream */
1961 return (win32_fdopen(p[parent], (char *)mode));
1964 /* we don't need to check for errors here */
1968 win32_dup2(oldfd, stdfd);
1973 #endif /* USE_RTL_POPEN */
1981 win32_pclose(FILE *pf)
1983 #ifdef USE_RTL_POPEN
1987 int childpid, status;
1990 sv = *av_fetch(w32_fdpid, win32_fileno(pf), TRUE);
1992 childpid = SvIVX(sv);
2004 if (win32_waitpid(childpid, &status, 0) == -1)
2009 #endif /* USE_RTL_POPEN */
2013 win32_rename(const char *oname, const char *newname)
2015 /* XXX despite what the documentation says about MoveFileEx(),
2016 * it doesn't work under Windows95!
2019 if (!MoveFileEx(oname,newname,
2020 MOVEFILE_COPY_ALLOWED|MOVEFILE_REPLACE_EXISTING)) {
2021 DWORD err = GetLastError();
2023 case ERROR_BAD_NET_NAME:
2024 case ERROR_BAD_NETPATH:
2025 case ERROR_BAD_PATHNAME:
2026 case ERROR_FILE_NOT_FOUND:
2027 case ERROR_FILENAME_EXCED_RANGE:
2028 case ERROR_INVALID_DRIVE:
2029 case ERROR_NO_MORE_FILES:
2030 case ERROR_PATH_NOT_FOUND:
2043 char tmpname[MAX_PATH+1];
2044 char dname[MAX_PATH+1];
2045 char *endname = Nullch;
2047 DWORD from_attr, to_attr;
2049 /* if oname doesn't exist, do nothing */
2050 from_attr = GetFileAttributes(oname);
2051 if (from_attr == 0xFFFFFFFF) {
2056 /* if newname exists, rename it to a temporary name so that we
2057 * don't delete it in case oname happens to be the same file
2058 * (but perhaps accessed via a different path)
2060 to_attr = GetFileAttributes(newname);
2061 if (to_attr != 0xFFFFFFFF) {
2062 /* if newname is a directory, we fail
2063 * XXX could overcome this with yet more convoluted logic */
2064 if (to_attr & FILE_ATTRIBUTE_DIRECTORY) {
2068 tmplen = strlen(newname);
2069 strcpy(tmpname,newname);
2070 endname = tmpname+tmplen;
2071 for (; endname > tmpname ; --endname) {
2072 if (*endname == '/' || *endname == '\\') {
2077 if (endname > tmpname)
2078 endname = strcpy(dname,tmpname);
2082 /* get a temporary filename in same directory
2083 * XXX is this really the best we can do? */
2084 if (!GetTempFileName((LPCTSTR)endname, "plr", 0, tmpname)) {
2088 DeleteFile(tmpname);
2090 retval = rename(newname, tmpname);
2097 /* rename oname to newname */
2098 retval = rename(oname, newname);
2100 /* if we created a temporary file before ... */
2101 if (endname != Nullch) {
2102 /* ...and rename succeeded, delete temporary file/directory */
2104 DeleteFile(tmpname);
2105 /* else restore it to what it was */
2107 (void)rename(tmpname, newname);
2114 win32_setmode(int fd, int mode)
2116 return setmode(fd, mode);
2120 win32_lseek(int fd, long offset, int origin)
2122 return lseek(fd, offset, origin);
2132 win32_open(const char *path, int flag, ...)
2138 pmode = va_arg(ap, int);
2141 if (stricmp(path, "/dev/null")==0)
2142 return open("NUL", flag, pmode);
2143 return open(path,flag,pmode);
2165 win32_dup2(int fd1,int fd2)
2167 return dup2(fd1,fd2);
2171 win32_read(int fd, void *buf, unsigned int cnt)
2173 return read(fd, buf, cnt);
2177 win32_write(int fd, const void *buf, unsigned int cnt)
2179 return write(fd, buf, cnt);
2183 win32_mkdir(const char *dir, int mode)
2185 return mkdir(dir); /* just ignore mode */
2189 win32_rmdir(const char *dir)
2195 win32_chdir(const char *dir)
2201 create_command_line(const char* command, const char * const *args)
2204 char *cmd, *ptr, *arg;
2205 STRLEN len = strlen(command) + 1;
2207 for (index = 0; (ptr = (char*)args[index]) != NULL; ++index)
2208 len += strlen(ptr) + 1;
2210 New(1310, cmd, len, char);
2212 strcpy(ptr, command);
2214 for (index = 0; (arg = (char*)args[index]) != NULL; ++index) {
2224 qualified_path(const char *cmd)
2227 char *fullcmd, *curfullcmd;
2233 fullcmd = (char*)cmd;
2235 if (*fullcmd == '/' || *fullcmd == '\\')
2242 pathstr = win32_getenv("PATH");
2243 New(0, fullcmd, MAX_PATH+1, char);
2244 curfullcmd = fullcmd;
2249 /* start by appending the name to the current prefix */
2250 strcpy(curfullcmd, cmd);
2251 curfullcmd += cmdlen;
2253 /* if it doesn't end with '.', or has no extension, try adding
2254 * a trailing .exe first */
2255 if (cmd[cmdlen-1] != '.'
2256 && (cmdlen < 4 || cmd[cmdlen-4] != '.'))
2258 strcpy(curfullcmd, ".exe");
2259 res = GetFileAttributes(fullcmd);
2260 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
2265 /* that failed, try the bare name */
2266 res = GetFileAttributes(fullcmd);
2267 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
2270 /* quit if no other path exists, or if cmd already has path */
2271 if (!pathstr || !*pathstr || has_slash)
2274 /* skip leading semis */
2275 while (*pathstr == ';')
2278 /* build a new prefix from scratch */
2279 curfullcmd = fullcmd;
2280 while (*pathstr && *pathstr != ';') {
2281 if (*pathstr == '"') { /* foo;"baz;etc";bar */
2282 pathstr++; /* skip initial '"' */
2283 while (*pathstr && *pathstr != '"') {
2284 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
2285 *curfullcmd++ = *pathstr;
2289 pathstr++; /* skip trailing '"' */
2292 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
2293 *curfullcmd++ = *pathstr;
2298 pathstr++; /* skip trailing semi */
2299 if (curfullcmd > fullcmd /* append a dir separator */
2300 && curfullcmd[-1] != '/' && curfullcmd[-1] != '\\')
2302 *curfullcmd++ = '\\';
2310 /* XXX this needs to be made more compatible with the spawnvp()
2311 * provided by the various RTLs. In particular, searching for
2312 * *.{com,bat,cmd} files (as done by the RTLs) is unimplemented.
2313 * This doesn't significantly affect perl itself, because we
2314 * always invoke things using PERL5SHELL if a direct attempt to
2315 * spawn the executable fails.
2317 * XXX splitting and rejoining the commandline between do_aspawn()
2318 * and win32_spawnvp() could also be avoided.
2322 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
2324 #ifdef USE_RTL_SPAWNVP
2325 return spawnvp(mode, cmdname, (char * const *)argv);
2328 STARTUPINFO StartupInfo;
2329 PROCESS_INFORMATION ProcessInformation;
2332 char *cmd = create_command_line(cmdname, strcmp(cmdname, argv[0]) == 0
2334 char *fullcmd = Nullch;
2337 case P_NOWAIT: /* asynch + remember result */
2338 if (w32_num_children >= MAXIMUM_WAIT_OBJECTS) {
2344 case P_WAIT: /* synchronous execution */
2346 default: /* invalid mode */
2351 memset(&StartupInfo,0,sizeof(StartupInfo));
2352 StartupInfo.cb = sizeof(StartupInfo);
2353 StartupInfo.wShowWindow = SW_SHOWDEFAULT;
2356 if (!CreateProcess(cmdname, /* search PATH to find executable */
2357 cmd, /* executable, and its arguments */
2358 NULL, /* process attributes */
2359 NULL, /* thread attributes */
2360 TRUE, /* inherit handles */
2361 create, /* creation flags */
2362 NULL, /* inherit environment */
2363 NULL, /* inherit cwd */
2365 &ProcessInformation))
2367 /* initial NULL argument to CreateProcess() does a PATH
2368 * search, but it always first looks in the directory
2369 * where the current process was started, which behavior
2370 * is undesirable for backward compatibility. So we
2371 * jump through our own hoops by picking out the path
2372 * we really want it to use. */
2374 fullcmd = qualified_path(cmdname);
2385 if (mode == P_NOWAIT) {
2386 /* asynchronous spawn -- store handle, return PID */
2387 w32_child_handles[w32_num_children] = ProcessInformation.hProcess;
2388 ret = w32_child_pids[w32_num_children] = ProcessInformation.dwProcessId;
2392 WaitForSingleObject(ProcessInformation.hProcess, INFINITE);
2393 GetExitCodeProcess(ProcessInformation.hProcess, &ret);
2394 CloseHandle(ProcessInformation.hProcess);
2397 CloseHandle(ProcessInformation.hThread);
2406 win32_execv(const char *cmdname, const char *const *argv)
2408 return execv(cmdname, (char *const *)argv);
2412 win32_execvp(const char *cmdname, const char *const *argv)
2414 return execvp(cmdname, (char *const *)argv);
2418 win32_perror(const char *str)
2424 win32_setbuf(FILE *pf, char *buf)
2430 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
2432 return setvbuf(pf, buf, type, size);
2436 win32_flushall(void)
2442 win32_fcloseall(void)
2448 win32_fgets(char *s, int n, FILE *pf)
2450 return fgets(s, n, pf);
2460 win32_fgetc(FILE *pf)
2466 win32_putc(int c, FILE *pf)
2472 win32_puts(const char *s)
2484 win32_putchar(int c)
2491 #ifndef USE_PERL_SBRK
2493 static char *committed = NULL;
2494 static char *base = NULL;
2495 static char *reserved = NULL;
2496 static char *brk = NULL;
2497 static DWORD pagesize = 0;
2498 static DWORD allocsize = 0;
2506 GetSystemInfo(&info);
2507 /* Pretend page size is larger so we don't perpetually
2508 * call the OS to commit just one page ...
2510 pagesize = info.dwPageSize << 3;
2511 allocsize = info.dwAllocationGranularity;
2513 /* This scheme fails eventually if request for contiguous
2514 * block is denied so reserve big blocks - this is only
2515 * address space not memory ...
2517 if (brk+need >= reserved)
2519 DWORD size = 64*1024*1024;
2521 if (committed && reserved && committed < reserved)
2523 /* Commit last of previous chunk cannot span allocations */
2524 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
2526 committed = reserved;
2528 /* Reserve some (more) space
2529 * Note this is a little sneaky, 1st call passes NULL as reserved
2530 * so lets system choose where we start, subsequent calls pass
2531 * the old end address so ask for a contiguous block
2533 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
2536 reserved = addr+size;
2551 if (brk > committed)
2553 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
2554 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
2569 win32_malloc(size_t size)
2571 return malloc(size);
2575 win32_calloc(size_t numitems, size_t size)
2577 return calloc(numitems,size);
2581 win32_realloc(void *block, size_t size)
2583 return realloc(block,size);
2587 win32_free(void *block)
2594 win32_open_osfhandle(long handle, int flags)
2596 return _open_osfhandle(handle, flags);
2600 win32_get_osfhandle(int fd)
2602 return _get_osfhandle(fd);
2613 SV *sv = sv_newmortal();
2614 /* Make one call with zero size - return value is required size */
2615 DWORD len = GetCurrentDirectory((DWORD)0,NULL);
2616 SvUPGRADE(sv,SVt_PV);
2618 SvCUR(sv) = GetCurrentDirectory((DWORD) SvLEN(sv), SvPVX(sv));
2621 * then it worked, set PV valid,
2622 * else leave it 'undef'
2638 croak("usage: Win32::SetCurrentDirectory($cwd)");
2639 if (SetCurrentDirectory(SvPV_nolen(ST(0))))
2646 XS(w32_GetNextAvailDrive)
2650 char root[] = "_:\\";
2655 if (GetDriveType(root) == 1) {
2664 XS(w32_GetLastError)
2668 XSRETURN_IV(GetLastError());
2672 XS(w32_SetLastError)
2676 croak("usage: Win32::SetLastError($error)");
2677 SetLastError(SvIV(ST(0)));
2685 char *name = getlogin_buffer;
2686 DWORD size = sizeof(getlogin_buffer);
2688 if (GetUserName(name,&size)) {
2689 /* size includes NULL */
2690 ST(0) = sv_2mortal(newSVpvn(name,size-1));
2700 char name[MAX_COMPUTERNAME_LENGTH+1];
2701 DWORD size = sizeof(name);
2703 if (GetComputerName(name,&size)) {
2704 /* size does NOT include NULL :-( */
2705 ST(0) = sv_2mortal(newSVpvn(name,size));
2716 #ifndef HAS_NETWKSTAGETINFO
2717 /* mingw32 (and Win95) don't have NetWksta*(), so do it the old way */
2719 DWORD size = sizeof(name);
2721 if (GetUserName(name,&size)) {
2723 DWORD sidlen = sizeof(sid);
2725 DWORD dnamelen = sizeof(dname);
2727 if (LookupAccountName(NULL, name, (PSID)&sid, &sidlen,
2728 dname, &dnamelen, &snu)) {
2729 XSRETURN_PV(dname); /* all that for this */
2733 /* this way is more reliable, in case user has a local account.
2734 * XXX need dynamic binding of netapi32.dll symbols or this will fail on
2735 * Win95. Probably makes more sense to move it into libwin32. */
2737 DWORD dnamelen = sizeof(dname);
2738 PWKSTA_INFO_100 pwi;
2740 if (NERR_Success == NetWkstaGetInfo(NULL, 100, (LPBYTE*)&pwi)) {
2741 if (pwi->wki100_langroup && *(pwi->wki100_langroup)) {
2742 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_langroup,
2743 -1, (LPSTR)dname, dnamelen, NULL, NULL);
2746 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_computername,
2747 -1, (LPSTR)dname, dnamelen, NULL, NULL);
2749 NetApiBufferFree(pwi);
2761 DWORD flags, filecomplen;
2762 if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
2763 &flags, fsname, sizeof(fsname))) {
2764 if (GIMME_V == G_ARRAY) {
2765 XPUSHs(sv_2mortal(newSVpvn(fsname,strlen(fsname))));
2766 XPUSHs(sv_2mortal(newSViv(flags)));
2767 XPUSHs(sv_2mortal(newSViv(filecomplen)));
2772 XSRETURN_PV(fsname);
2778 XS(w32_GetOSVersion)
2781 OSVERSIONINFO osver;
2783 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
2784 if (GetVersionEx(&osver)) {
2785 XPUSHs(newSVpvn(osver.szCSDVersion, strlen(osver.szCSDVersion)));
2786 XPUSHs(newSViv(osver.dwMajorVersion));
2787 XPUSHs(newSViv(osver.dwMinorVersion));
2788 XPUSHs(newSViv(osver.dwBuildNumber));
2789 XPUSHs(newSViv(osver.dwPlatformId));
2801 XSRETURN_IV(IsWinNT());
2809 XSRETURN_IV(IsWin95());
2813 XS(w32_FormatMessage)
2820 croak("usage: Win32::FormatMessage($errno)");
2822 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
2823 &source, SvIV(ST(0)), 0,
2824 msgbuf, sizeof(msgbuf)-1, NULL))
2825 XSRETURN_PV(msgbuf);
2835 PROCESS_INFORMATION stProcInfo;
2836 STARTUPINFO stStartInfo;
2837 BOOL bSuccess = FALSE;
2840 croak("usage: Win32::Spawn($cmdName, $args, $PID)");
2842 cmd = SvPV_nolen(ST(0));
2843 args = SvPV_nolen(ST(1));
2845 memset(&stStartInfo, 0, sizeof(stStartInfo)); /* Clear the block */
2846 stStartInfo.cb = sizeof(stStartInfo); /* Set the structure size */
2847 stStartInfo.dwFlags = STARTF_USESHOWWINDOW; /* Enable wShowWindow control */
2848 stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE; /* Start min (normal) */
2851 cmd, /* Image path */
2852 args, /* Arguments for command line */
2853 NULL, /* Default process security */
2854 NULL, /* Default thread security */
2855 FALSE, /* Must be TRUE to use std handles */
2856 NORMAL_PRIORITY_CLASS, /* No special scheduling */
2857 NULL, /* Inherit our environment block */
2858 NULL, /* Inherit our currrent directory */
2859 &stStartInfo, /* -> Startup info */
2860 &stProcInfo)) /* <- Process info (if OK) */
2862 CloseHandle(stProcInfo.hThread);/* library source code does this. */
2863 sv_setiv(ST(2), stProcInfo.dwProcessId);
2866 XSRETURN_IV(bSuccess);
2870 XS(w32_GetTickCount)
2873 DWORD msec = GetTickCount();
2881 XS(w32_GetShortPathName)
2888 croak("usage: Win32::GetShortPathName($longPathName)");
2890 shortpath = sv_mortalcopy(ST(0));
2891 SvUPGRADE(shortpath, SVt_PV);
2892 /* src == target is allowed */
2894 len = GetShortPathName(SvPVX(shortpath),
2897 } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
2899 SvCUR_set(shortpath,len);
2907 XS(w32_GetFullPathName)
2916 croak("usage: Win32::GetFullPathName($filename)");
2919 fullpath = sv_mortalcopy(filename);
2920 SvUPGRADE(fullpath, SVt_PV);
2922 len = GetFullPathName(SvPVX(filename),
2926 } while (len >= SvLEN(fullpath) && sv_grow(fullpath,len+1));
2928 if (GIMME_V == G_ARRAY) {
2930 XST_mPV(1,filepart);
2931 len = filepart - SvPVX(fullpath);
2934 SvCUR_set(fullpath,len);
2942 XS(w32_GetLongPathName)
2946 char tmpbuf[MAX_PATH+1];
2951 croak("usage: Win32::GetLongPathName($pathname)");
2954 pathstr = SvPV(path,len);
2955 strcpy(tmpbuf, pathstr);
2956 pathstr = win32_longpath(tmpbuf);
2958 ST(0) = sv_2mortal(newSVpvn(pathstr, strlen(pathstr)));
2969 croak("usage: Win32::Sleep($milliseconds)");
2979 croak("usage: Win32::CopyFile($from, $to, $overwrite)");
2980 if (CopyFile(SvPV_nolen(ST(0)), SvPV_nolen(ST(1)), !SvTRUE(ST(2))))
2986 Perl_init_os_extras()
2988 char *file = __FILE__;
2991 w32_perlshell_tokens = Nullch;
2992 w32_perlshell_items = -1;
2993 w32_fdpid = newAV(); /* XXX needs to be in Perl_win32_init()? */
2994 New(1313, w32_children, 1, child_tab);
2995 w32_num_children = 0;
2997 /* these names are Activeware compatible */
2998 newXS("Win32::GetCwd", w32_GetCwd, file);
2999 newXS("Win32::SetCwd", w32_SetCwd, file);
3000 newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
3001 newXS("Win32::GetLastError", w32_GetLastError, file);
3002 newXS("Win32::SetLastError", w32_SetLastError, file);
3003 newXS("Win32::LoginName", w32_LoginName, file);
3004 newXS("Win32::NodeName", w32_NodeName, file);
3005 newXS("Win32::DomainName", w32_DomainName, file);
3006 newXS("Win32::FsType", w32_FsType, file);
3007 newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
3008 newXS("Win32::IsWinNT", w32_IsWinNT, file);
3009 newXS("Win32::IsWin95", w32_IsWin95, file);
3010 newXS("Win32::FormatMessage", w32_FormatMessage, file);
3011 newXS("Win32::Spawn", w32_Spawn, file);
3012 newXS("Win32::GetTickCount", w32_GetTickCount, file);
3013 newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
3014 newXS("Win32::GetFullPathName", w32_GetFullPathName, file);
3015 newXS("Win32::GetLongPathName", w32_GetLongPathName, file);
3016 newXS("Win32::CopyFile", w32_CopyFile, file);
3017 newXS("Win32::Sleep", w32_Sleep, file);
3019 /* XXX Bloat Alert! The following Activeware preloads really
3020 * ought to be part of Win32::Sys::*, so they're not included
3023 /* LookupAccountName
3025 * InitiateSystemShutdown
3026 * AbortSystemShutdown
3027 * ExpandEnvrironmentStrings
3032 Perl_win32_init(int *argcp, char ***argvp)
3034 /* Disable floating point errors, Perl will trap the ones we
3035 * care about. VC++ RTL defaults to switching these off
3036 * already, but the Borland RTL doesn't. Since we don't
3037 * want to be at the vendor's whim on the default, we set
3038 * it explicitly here.
3040 #if !defined(_ALPHA_) && !defined(__GNUC__)
3041 _control87(MCW_EM, MCW_EM);
3046 #ifdef USE_BINMODE_SCRIPTS
3049 win32_strip_return(SV *sv)
3051 char *s = SvPVX(sv);
3052 char *e = s+SvCUR(sv);
3056 if (*s == '\r' && s[1] == '\n')
3066 SvCUR_set(sv,d-SvPVX(sv));