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);
140 GetRegStrFromKey(HKEY hkey, const char *lpszValueName, char** ptr, DWORD* lpDataLen)
141 { /* Retrieve a REG_SZ or REG_EXPAND_SZ from the registry */
144 const char *subkey = "Software\\Perl";
147 retval = RegOpenKeyEx(hkey, subkey, 0, KEY_READ, &handle);
148 if (retval == ERROR_SUCCESS){
149 retval = RegQueryValueEx(handle, lpszValueName, 0, &type, NULL, lpDataLen);
150 if (retval == ERROR_SUCCESS && type == REG_SZ) {
152 Renew(*ptr, *lpDataLen, char);
155 New(1312, *ptr, *lpDataLen, char);
157 retval = RegQueryValueEx(handle, lpszValueName, 0, NULL, (PBYTE)*ptr, lpDataLen);
158 if (retval != ERROR_SUCCESS) {
169 GetRegStr(const char *lpszValueName, char** ptr, DWORD* lpDataLen)
171 *ptr = GetRegStrFromKey(HKEY_CURRENT_USER, lpszValueName, ptr, lpDataLen);
174 *ptr = GetRegStrFromKey(HKEY_LOCAL_MACHINE, lpszValueName, ptr, lpDataLen);
180 get_emd_part(char *prev_path, char *trailing_path, ...)
184 char mod_name[MAX_PATH+1];
188 int oldsize, newsize;
190 va_start(ap, trailing_path);
191 strip = va_arg(ap, char *);
193 sprintf(base, "%5.3f",
194 (double)PERL_REVISION + ((double)PERL_VERSION / (double)1000));
196 if (!*w32_module_name) {
197 GetModuleFileName((HMODULE)((w32_perldll_handle == INVALID_HANDLE_VALUE)
198 ? GetModuleHandle(NULL)
199 : w32_perldll_handle),
200 w32_module_name, sizeof(w32_module_name));
202 /* try to get full path to binary (which may be mangled when perl is
203 * run from a 16-bit app) */
204 /*PerlIO_printf(PerlIO_stderr(), "Before %s\n", w32_module_name);*/
205 (void)win32_longpath(w32_module_name);
206 /*PerlIO_printf(PerlIO_stderr(), "After %s\n", w32_module_name);*/
208 /* normalize to forward slashes */
209 ptr = w32_module_name;
216 strcpy(mod_name, w32_module_name);
217 ptr = strrchr(mod_name, '/');
218 while (ptr && strip) {
219 /* look for directories to skip back */
222 ptr = strrchr(mod_name, '/');
223 if (!ptr || stricmp(ptr+1, strip) != 0) {
224 if(!(*strip == '5' && *(ptr+1) == '5'
225 && strncmp(strip, base, 5) == 0
226 && strncmp(ptr+1, base, 5) == 0))
232 strip = va_arg(ap, char *);
240 strcpy(++ptr, trailing_path);
242 /* only add directory if it exists */
243 if(GetFileAttributes(mod_name) != (DWORD) -1) {
244 /* directory exists */
245 newsize = strlen(mod_name) + 1;
247 oldsize = strlen(prev_path) + 1;
248 newsize += oldsize; /* includes plus 1 for ';' */
249 Renew(prev_path, newsize, char);
250 prev_path[oldsize-1] = ';';
251 strcpy(&prev_path[oldsize], mod_name);
254 New(1311, prev_path, newsize, char);
255 strcpy(prev_path, mod_name);
263 win32_get_privlib(char *pl)
265 char *stdlib = "lib";
266 char buffer[MAX_PATH+1];
270 /* $stdlib = $HKCU{"lib-$]"} || $HKLM{"lib-$]"} || $HKCU{"lib"} || $HKLM{"lib"} || ""; */
271 sprintf(buffer, "%s-%s", stdlib, pl);
272 path = GetRegStr(buffer, &path, &datalen);
274 path = GetRegStr(stdlib, &path, &datalen);
276 /* $stdlib .= ";$EMD/../../lib" */
277 return get_emd_part(path, stdlib, ARCHNAME, "bin", Nullch);
281 win32_get_sitelib(char *pl)
283 char *sitelib = "sitelib";
285 char pathstr[MAX_PATH+1];
287 char *path1 = Nullch;
288 char *path2 = Nullch;
291 /* $HKCU{"sitelib-$]"} || $HKLM{"sitelib-$]"} . ---; */
292 sprintf(regstr, "%s-%s", sitelib, pl);
293 path1 = GetRegStr(regstr, &path1, &datalen);
296 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/site/$]/lib"; */
297 sprintf(pathstr, "site/%s/lib", pl);
298 path1 = get_emd_part(path1, pathstr, ARCHNAME, "bin", pl, Nullch);
300 /* $HKCU{'sitelib'} || $HKLM{'sitelib'} . ---; */
301 path2 = GetRegStr(sitelib, &path2, &datalen);
304 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/site/lib"; */
305 path2 = get_emd_part(path2, "site/lib", ARCHNAME, "bin", pl, Nullch);
314 newsize = len + strlen(path2) + 2; /* plus one for ';' */
316 Renew(path1, newsize, char);
318 strcpy(&path1[len], path2);
326 has_shell_metachars(char *ptr)
332 * Scan string looking for redirection (< or >) or pipe
333 * characters (|) that are not in a quoted string.
334 * Shell variable interpolation (%VAR%) can also happen inside strings.
366 #if !defined(PERL_OBJECT)
367 /* since the current process environment is being updated in util.c
368 * the library functions will get the correct environment
371 my_popen(char *cmd, char *mode)
374 #define fixcmd(x) { \
375 char *pspace = strchr((x),' '); \
378 while (p < pspace) { \
389 PERL_FLUSHALL_FOR_CHILD;
390 return win32_popen(cmd, mode);
394 my_pclose(PerlIO *fp)
396 return win32_pclose(fp);
403 static OSVERSIONINFO osver;
405 if (osver.dwPlatformId != w32_platform) {
406 memset(&osver, 0, sizeof(OSVERSIONINFO));
407 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
408 GetVersionEx(&osver);
409 w32_platform = osver.dwPlatformId;
411 return (w32_platform);
414 /* Tokenize a string. Words are null-separated, and the list
415 * ends with a doubled null. Any character (except null and
416 * including backslash) may be escaped by preceding it with a
417 * backslash (the backslash will be stripped).
418 * Returns number of words in result buffer.
421 tokenize(char *str, char **dest, char ***destv)
423 char *retstart = Nullch;
424 char **retvstart = 0;
427 int slen = strlen(str);
429 register char **retv;
430 New(1307, ret, slen+2, char);
431 New(1308, retv, (slen+3)/2, char*);
439 if (*ret == '\\' && *str)
441 else if (*ret == ' ') {
457 retvstart[items] = Nullch;
469 if (!w32_perlshell_tokens) {
470 /* we don't use COMSPEC here for two reasons:
471 * 1. the same reason perl on UNIX doesn't use SHELL--rampant and
472 * uncontrolled unportability of the ensuing scripts.
473 * 2. PERL5SHELL could be set to a shell that may not be fit for
474 * interactive use (which is what most programs look in COMSPEC
477 char* defaultshell = (IsWinNT() ? "cmd.exe /x/c" : "command.com /c");
478 char *usershell = getenv("PERL5SHELL");
479 w32_perlshell_items = tokenize(usershell ? usershell : defaultshell,
480 &w32_perlshell_tokens,
486 do_aspawn(void *vreally, void **vmark, void **vsp)
488 SV *really = (SV*)vreally;
489 SV **mark = (SV**)vmark;
501 New(1306, argv, (sp - mark) + w32_perlshell_items + 2, char*);
503 if (SvNIOKp(*(mark+1)) && !SvPOKp(*(mark+1))) {
508 while (++mark <= sp) {
509 if (*mark && (str = SvPV_nolen(*mark)))
516 status = win32_spawnvp(flag,
517 (const char*)(really ? SvPV_nolen(really) : argv[0]),
518 (const char* const*)argv);
520 if (status < 0 && (errno == ENOEXEC || errno == ENOENT)) {
521 /* possible shell-builtin, invoke with shell */
523 sh_items = w32_perlshell_items;
525 argv[index+sh_items] = argv[index];
526 while (--sh_items >= 0)
527 argv[sh_items] = w32_perlshell_vec[sh_items];
529 status = win32_spawnvp(flag,
530 (const char*)(really ? SvPV_nolen(really) : argv[0]),
531 (const char* const*)argv);
534 if (flag != P_NOWAIT) {
537 warn("Can't spawn \"%s\": %s", argv[0], strerror(errno));
542 PL_statusvalue = status;
549 do_spawn2(char *cmd, int exectype)
555 BOOL needToTry = TRUE;
558 /* Save an extra exec if possible. See if there are shell
559 * metacharacters in it */
560 if (!has_shell_metachars(cmd)) {
561 New(1301,argv, strlen(cmd) / 2 + 2, char*);
562 New(1302,cmd2, strlen(cmd) + 1, char);
565 for (s = cmd2; *s;) {
566 while (*s && isspace(*s))
570 while (*s && !isspace(*s))
579 status = win32_spawnvp(P_WAIT, argv[0],
580 (const char* const*)argv);
582 case EXECF_SPAWN_NOWAIT:
583 status = win32_spawnvp(P_NOWAIT, argv[0],
584 (const char* const*)argv);
587 status = win32_execvp(argv[0], (const char* const*)argv);
590 if (status != -1 || errno == 0)
600 New(1306, argv, w32_perlshell_items + 2, char*);
601 while (++i < w32_perlshell_items)
602 argv[i] = w32_perlshell_vec[i];
607 status = win32_spawnvp(P_WAIT, argv[0],
608 (const char* const*)argv);
610 case EXECF_SPAWN_NOWAIT:
611 status = win32_spawnvp(P_NOWAIT, argv[0],
612 (const char* const*)argv);
615 status = win32_execvp(argv[0], (const char* const*)argv);
621 if (exectype != EXECF_SPAWN_NOWAIT) {
624 warn("Can't %s \"%s\": %s",
625 (exectype == EXECF_EXEC ? "exec" : "spawn"),
626 cmd, strerror(errno));
631 PL_statusvalue = status;
639 return do_spawn2(cmd, EXECF_SPAWN);
643 do_spawn_nowait(char *cmd)
645 return do_spawn2(cmd, EXECF_SPAWN_NOWAIT);
651 do_spawn2(cmd, EXECF_EXEC);
655 /* The idea here is to read all the directory names into a string table
656 * (separated by nulls) and when one of the other dir functions is called
657 * return the pointer to the current file name.
660 win32_opendir(char *filename)
665 char scanname[MAX_PATH+3];
667 WIN32_FIND_DATA FindData;
670 len = strlen(filename);
674 /* check to see if filename is a directory */
675 if (win32_stat(filename, &sbuf) < 0 || !S_ISDIR(sbuf.st_mode))
678 /* Get us a DIR structure */
679 Newz(1303, p, 1, DIR);
683 /* Create the search pattern */
684 strcpy(scanname, filename);
685 if (scanname[len-1] != '/' && scanname[len-1] != '\\')
686 scanname[len++] = '/';
687 scanname[len++] = '*';
688 scanname[len] = '\0';
690 /* do the FindFirstFile call */
691 fh = FindFirstFile(scanname, &FindData);
692 if (fh == INVALID_HANDLE_VALUE) {
693 /* FindFirstFile() fails on empty drives! */
694 if (GetLastError() == ERROR_FILE_NOT_FOUND)
700 /* now allocate the first part of the string table for
701 * the filenames that we find.
703 idx = strlen(FindData.cFileName)+1;
704 New(1304, p->start, idx, char);
705 if (p->start == NULL)
706 croak("opendir: malloc failed!\n");
707 strcpy(p->start, FindData.cFileName);
710 /* loop finding all the files that match the wildcard
711 * (which should be all of them in this directory!).
712 * the variable idx should point one past the null terminator
713 * of the previous string found.
715 while (FindNextFile(fh, &FindData)) {
716 len = strlen(FindData.cFileName);
717 /* bump the string table size by enough for the
718 * new name and it's null terminator
720 Renew(p->start, idx+len+1, char);
721 if (p->start == NULL)
722 croak("opendir: malloc failed!\n");
723 strcpy(&p->start[idx], FindData.cFileName);
734 /* Readdir just returns the current string pointer and bumps the
735 * string pointer to the nDllExport entry.
738 win32_readdir(DIR *dirp)
741 static int dummy = 0;
744 /* first set up the structure to return */
745 len = strlen(dirp->curr);
746 strcpy(dirp->dirstr.d_name, dirp->curr);
747 dirp->dirstr.d_namlen = len;
750 dirp->dirstr.d_ino = dummy++;
752 /* Now set up for the nDllExport call to readdir */
753 dirp->curr += len + 1;
754 if (dirp->curr >= (dirp->start + dirp->size)) {
758 return &(dirp->dirstr);
764 /* Telldir returns the current string pointer position */
766 win32_telldir(DIR *dirp)
768 return (long) dirp->curr;
772 /* Seekdir moves the string pointer to a previously saved position
776 win32_seekdir(DIR *dirp, long loc)
778 dirp->curr = (char *)loc;
781 /* Rewinddir resets the string pointer to the start */
783 win32_rewinddir(DIR *dirp)
785 dirp->curr = dirp->start;
788 /* free the memory allocated by opendir */
790 win32_closedir(DIR *dirp)
792 Safefree(dirp->start);
805 * Just pretend that everyone is a superuser. NT will let us know if
806 * we don\'t really have permission to do something.
809 #define ROOT_UID ((uid_t)0)
810 #define ROOT_GID ((gid_t)0)
839 return (auid == ROOT_UID ? 0 : -1);
845 return (agid == ROOT_GID ? 0 : -1);
852 char *buf = getlogin_buffer;
853 DWORD size = sizeof(getlogin_buffer);
854 if (GetUserName(buf,&size))
860 chown(const char *path, uid_t owner, gid_t group)
870 for (child = 0 ; child < w32_num_children ; ++child) {
871 if (w32_child_pids[child] == pid)
878 remove_dead_process(long child)
881 CloseHandle(w32_child_handles[child]);
882 Copy(&w32_child_handles[child+1], &w32_child_handles[child],
883 (w32_num_children-child-1), HANDLE);
884 Copy(&w32_child_pids[child+1], &w32_child_pids[child],
885 (w32_num_children-child-1), DWORD);
891 win32_kill(int pid, int sig)
894 hProcess = OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid);
895 if (hProcess && TerminateProcess(hProcess, sig))
896 CloseHandle(hProcess);
908 DllExport unsigned int
909 win32_sleep(unsigned int t)
916 win32_stat(const char *path, struct stat *buffer)
919 int l = strlen(path);
923 switch(path[l - 1]) {
924 /* FindFirstFile() and stat() are buggy with a trailing
925 * backslash, so change it to a forward slash :-( */
927 strncpy(t, path, l-1);
932 /* FindFirstFile() is buggy with "x:", so add a slash :-( */
934 if (l == 2 && isALPHA(path[0])) {
935 t[0] = path[0]; t[1] = ':'; t[2] = '/'; t[3] = '\0';
942 res = stat(path,buffer);
944 /* CRT is buggy on sharenames, so make sure it really isn't.
945 * XXX using GetFileAttributesEx() will enable us to set
946 * buffer->st_*time (but note that's not available on the
947 * Windows of 1995) */
948 DWORD r = GetFileAttributes(path);
949 if (r != 0xffffffff && (r & FILE_ATTRIBUTE_DIRECTORY)) {
950 /* buffer may still contain old garbage since stat() failed */
951 Zero(buffer, 1, struct stat);
952 buffer->st_mode = S_IFDIR | S_IREAD;
954 if (!(r & FILE_ATTRIBUTE_READONLY))
955 buffer->st_mode |= S_IWRITE | S_IEXEC;
960 if (l == 3 && isALPHA(path[0]) && path[1] == ':'
961 && (path[2] == '\\' || path[2] == '/'))
963 /* The drive can be inaccessible, some _stat()s are buggy */
964 if (!GetVolumeInformation(path,NULL,0,NULL,NULL,NULL,NULL,0)) {
970 if (S_ISDIR(buffer->st_mode))
971 buffer->st_mode |= S_IWRITE | S_IEXEC;
972 else if (S_ISREG(buffer->st_mode)) {
973 if (l >= 4 && path[l-4] == '.') {
974 const char *e = path + l - 3;
975 if (strnicmp(e,"exe",3)
976 && strnicmp(e,"bat",3)
977 && strnicmp(e,"com",3)
978 && (IsWin95() || strnicmp(e,"cmd",3)))
979 buffer->st_mode &= ~S_IEXEC;
981 buffer->st_mode |= S_IEXEC;
984 buffer->st_mode &= ~S_IEXEC;
991 /* Find the longname of a given path. path is destructively modified.
992 * It should have space for at least MAX_PATH characters. */
994 win32_longpath(char *path)
996 WIN32_FIND_DATA fdata;
998 char tmpbuf[MAX_PATH+1];
999 char *tmpstart = tmpbuf;
1006 if (isALPHA(path[0]) && path[1] == ':' &&
1007 (path[2] == '/' || path[2] == '\\'))
1010 *tmpstart++ = path[0];
1014 else if ((path[0] == '/' || path[0] == '\\') &&
1015 (path[1] == '/' || path[1] == '\\'))
1020 /* copy machine name */
1021 while (*start && *start != '/' && *start != '\\')
1022 *tmpstart++ = *start++;
1026 /* copy share name */
1027 while (*start && *start != '/' && *start != '\\')
1028 *tmpstart++ = *start++;
1032 if (sep == '/' || sep == '\\')
1036 /* walk up to slash */
1037 while (*start && *start != '/' && *start != '\\')
1040 /* discard doubled slashes */
1041 while (*start && (start[1] == '/' || start[1] == '\\'))
1045 /* stop and find full name of component */
1047 fhand = FindFirstFile(path,&fdata);
1048 if (fhand != INVALID_HANDLE_VALUE) {
1049 strcpy(tmpstart, fdata.cFileName);
1050 tmpstart += strlen(fdata.cFileName);
1058 /* failed a step, just return without side effects */
1059 /*PerlIO_printf(PerlIO_stderr(), "Failed to find %s\n", path);*/
1064 strcpy(path,tmpbuf);
1068 #ifndef USE_WIN32_RTL_ENV
1071 win32_getenv(const char *name)
1073 static char *curitem = Nullch; /* XXX threadead */
1074 static DWORD curlen = 0; /* XXX threadead */
1078 New(1305,curitem,curlen,char);
1081 needlen = GetEnvironmentVariable(name,curitem,curlen);
1083 while (needlen > curlen) {
1084 Renew(curitem,needlen,char);
1086 needlen = GetEnvironmentVariable(name,curitem,curlen);
1090 /* allow any environment variables that begin with 'PERL'
1091 to be stored in the registry */
1095 if (strncmp(name, "PERL", 4) == 0) {
1101 curitem = GetRegStr(name, &curitem, &curlen);
1104 if (curitem && *curitem == '\0')
1111 win32_putenv(const char *name)
1117 New(1309,curitem,strlen(name)+1,char);
1118 strcpy(curitem, name);
1119 val = strchr(curitem, '=');
1121 /* The sane way to deal with the environment.
1122 * Has these advantages over putenv() & co.:
1123 * * enables us to store a truly empty value in the
1124 * environment (like in UNIX).
1125 * * we don't have to deal with RTL globals, bugs and leaks.
1127 * Why you may want to enable USE_WIN32_RTL_ENV:
1128 * * environ[] and RTL functions will not reflect changes,
1129 * which might be an issue if extensions want to access
1130 * the env. via RTL. This cuts both ways, since RTL will
1131 * not see changes made by extensions that call the Win32
1132 * functions directly, either.
1136 if(SetEnvironmentVariable(curitem, *val ? val : NULL))
1147 filetime_to_clock(PFILETIME ft)
1149 __int64 qw = ft->dwHighDateTime;
1151 qw |= ft->dwLowDateTime;
1152 qw /= 10000; /* File time ticks at 0.1uS, clock at 1mS */
1157 win32_times(struct tms *timebuf)
1162 if (GetProcessTimes(GetCurrentProcess(), &dummy, &dummy,
1164 timebuf->tms_utime = filetime_to_clock(&user);
1165 timebuf->tms_stime = filetime_to_clock(&kernel);
1166 timebuf->tms_cutime = 0;
1167 timebuf->tms_cstime = 0;
1170 /* That failed - e.g. Win95 fallback to clock() */
1171 clock_t t = clock();
1172 timebuf->tms_utime = t;
1173 timebuf->tms_stime = 0;
1174 timebuf->tms_cutime = 0;
1175 timebuf->tms_cstime = 0;
1180 /* fix utime() so it works on directories in NT
1181 * thanks to Jan Dubois <jan.dubois@ibm.net>
1184 filetime_from_time(PFILETIME pFileTime, time_t Time)
1186 struct tm *pTM = gmtime(&Time);
1187 SYSTEMTIME SystemTime;
1192 SystemTime.wYear = pTM->tm_year + 1900;
1193 SystemTime.wMonth = pTM->tm_mon + 1;
1194 SystemTime.wDay = pTM->tm_mday;
1195 SystemTime.wHour = pTM->tm_hour;
1196 SystemTime.wMinute = pTM->tm_min;
1197 SystemTime.wSecond = pTM->tm_sec;
1198 SystemTime.wMilliseconds = 0;
1200 return SystemTimeToFileTime(&SystemTime, pFileTime);
1204 win32_utime(const char *filename, struct utimbuf *times)
1210 struct utimbuf TimeBuffer;
1212 int rc = utime(filename,times);
1213 /* EACCES: path specifies directory or readonly file */
1214 if (rc == 0 || errno != EACCES /* || !IsWinNT() */)
1217 if (times == NULL) {
1218 times = &TimeBuffer;
1219 time(×->actime);
1220 times->modtime = times->actime;
1223 /* This will (and should) still fail on readonly files */
1224 handle = CreateFile(filename, GENERIC_READ | GENERIC_WRITE,
1225 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1226 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1227 if (handle == INVALID_HANDLE_VALUE)
1230 if (GetFileTime(handle, &ftCreate, &ftAccess, &ftWrite) &&
1231 filetime_from_time(&ftAccess, times->actime) &&
1232 filetime_from_time(&ftWrite, times->modtime) &&
1233 SetFileTime(handle, &ftCreate, &ftAccess, &ftWrite))
1238 CloseHandle(handle);
1243 win32_uname(struct utsname *name)
1245 struct hostent *hep;
1246 STRLEN nodemax = sizeof(name->nodename)-1;
1247 OSVERSIONINFO osver;
1249 memset(&osver, 0, sizeof(OSVERSIONINFO));
1250 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1251 if (GetVersionEx(&osver)) {
1253 switch (osver.dwPlatformId) {
1254 case VER_PLATFORM_WIN32_WINDOWS:
1255 strcpy(name->sysname, "Windows");
1257 case VER_PLATFORM_WIN32_NT:
1258 strcpy(name->sysname, "Windows NT");
1260 case VER_PLATFORM_WIN32s:
1261 strcpy(name->sysname, "Win32s");
1264 strcpy(name->sysname, "Win32 Unknown");
1269 sprintf(name->release, "%d.%d",
1270 osver.dwMajorVersion, osver.dwMinorVersion);
1273 sprintf(name->version, "Build %d",
1274 osver.dwPlatformId == VER_PLATFORM_WIN32_NT
1275 ? osver.dwBuildNumber : (osver.dwBuildNumber & 0xffff));
1276 if (osver.szCSDVersion[0]) {
1277 char *buf = name->version + strlen(name->version);
1278 sprintf(buf, " (%s)", osver.szCSDVersion);
1282 *name->sysname = '\0';
1283 *name->version = '\0';
1284 *name->release = '\0';
1288 hep = win32_gethostbyname("localhost");
1290 STRLEN len = strlen(hep->h_name);
1291 if (len <= nodemax) {
1292 strcpy(name->nodename, hep->h_name);
1295 strncpy(name->nodename, hep->h_name, nodemax);
1296 name->nodename[nodemax] = '\0';
1301 if (!GetComputerName(name->nodename, &sz))
1302 *name->nodename = '\0';
1305 /* machine (architecture) */
1309 GetSystemInfo(&info);
1312 switch (info.u.s.wProcessorArchitecture) {
1314 switch (info.wProcessorArchitecture) {
1316 case PROCESSOR_ARCHITECTURE_INTEL:
1317 arch = "x86"; break;
1318 case PROCESSOR_ARCHITECTURE_MIPS:
1319 arch = "mips"; break;
1320 case PROCESSOR_ARCHITECTURE_ALPHA:
1321 arch = "alpha"; break;
1322 case PROCESSOR_ARCHITECTURE_PPC:
1323 arch = "ppc"; break;
1325 arch = "unknown"; break;
1327 strcpy(name->machine, arch);
1333 win32_waitpid(int pid, int *status, int flags)
1337 return win32_wait(status);
1339 long child = find_pid(pid);
1341 HANDLE hProcess = w32_child_handles[child];
1342 DWORD waitcode = WaitForSingleObject(hProcess, INFINITE);
1343 if (waitcode != WAIT_FAILED) {
1344 if (GetExitCodeProcess(hProcess, &waitcode)) {
1345 *status = (int)((waitcode & 0xff) << 8);
1346 retval = (int)w32_child_pids[child];
1347 remove_dead_process(child);
1355 retval = cwait(status, pid, WAIT_CHILD);
1356 /* cwait() returns "correctly" on Borland */
1357 #ifndef __BORLANDC__
1363 return retval >= 0 ? pid : retval;
1367 win32_wait(int *status)
1369 /* XXX this wait emulation only knows about processes
1370 * spawned via win32_spawnvp(P_NOWAIT, ...).
1373 DWORD exitcode, waitcode;
1375 if (!w32_num_children) {
1380 /* if a child exists, wait for it to die */
1381 waitcode = WaitForMultipleObjects(w32_num_children,
1385 if (waitcode != WAIT_FAILED) {
1386 if (waitcode >= WAIT_ABANDONED_0
1387 && waitcode < WAIT_ABANDONED_0 + w32_num_children)
1388 i = waitcode - WAIT_ABANDONED_0;
1390 i = waitcode - WAIT_OBJECT_0;
1391 if (GetExitCodeProcess(w32_child_handles[i], &exitcode) ) {
1392 *status = (int)((exitcode & 0xff) << 8);
1393 retval = (int)w32_child_pids[i];
1394 remove_dead_process(i);
1400 errno = GetLastError();
1404 static UINT timerid = 0;
1406 static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
1408 KillTimer(NULL,timerid);
1413 DllExport unsigned int
1414 win32_alarm(unsigned int sec)
1417 * the 'obvious' implentation is SetTimer() with a callback
1418 * which does whatever receiving SIGALRM would do
1419 * we cannot use SIGALRM even via raise() as it is not
1420 * one of the supported codes in <signal.h>
1422 * Snag is unless something is looking at the message queue
1423 * nothing happens :-(
1427 timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
1429 croak("Cannot set timer");
1435 KillTimer(NULL,timerid);
1442 #if defined(HAVE_DES_FCRYPT) || defined(PERL_OBJECT)
1443 #ifdef HAVE_DES_FCRYPT
1444 extern char * des_fcrypt(const char *txt, const char *salt, char *cbuf);
1448 win32_crypt(const char *txt, const char *salt)
1450 #ifdef HAVE_DES_FCRYPT
1452 return des_fcrypt(txt, salt, crypt_buffer);
1454 die("The crypt() function is unimplemented due to excessive paranoia.");
1460 #ifdef USE_FIXED_OSFHANDLE
1462 EXTERN_C int __cdecl _alloc_osfhnd(void);
1463 EXTERN_C int __cdecl _set_osfhnd(int fh, long value);
1464 EXTERN_C void __cdecl _lock_fhandle(int);
1465 EXTERN_C void __cdecl _unlock_fhandle(int);
1466 EXTERN_C void __cdecl _unlock(int);
1468 #if (_MSC_VER >= 1000)
1470 long osfhnd; /* underlying OS file HANDLE */
1471 char osfile; /* attributes of file (e.g., open in text mode?) */
1472 char pipech; /* one char buffer for handles opened on pipes */
1473 #if defined (_MT) && !defined (DLL_FOR_WIN32S)
1475 CRITICAL_SECTION lock;
1476 #endif /* defined (_MT) && !defined (DLL_FOR_WIN32S) */
1479 EXTERN_C ioinfo * __pioinfo[];
1481 #define IOINFO_L2E 5
1482 #define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
1483 #define _pioinfo(i) (__pioinfo[i >> IOINFO_L2E] + (i & (IOINFO_ARRAY_ELTS - 1)))
1484 #define _osfile(i) (_pioinfo(i)->osfile)
1486 #else /* (_MSC_VER >= 1000) */
1487 extern char _osfile[];
1488 #endif /* (_MSC_VER >= 1000) */
1490 #define FOPEN 0x01 /* file handle open */
1491 #define FAPPEND 0x20 /* file handle opened O_APPEND */
1492 #define FDEV 0x40 /* file handle refers to device */
1493 #define FTEXT 0x80 /* file handle is in text mode */
1495 #define _STREAM_LOCKS 26 /* Table of stream locks */
1496 #define _LAST_STREAM_LOCK (_STREAM_LOCKS+_NSTREAM_-1) /* Last stream lock */
1497 #define _FH_LOCKS (_LAST_STREAM_LOCK+1) /* Table of fh locks */
1500 *int my_open_osfhandle(long osfhandle, int flags) - open C Runtime file handle
1503 * This function allocates a free C Runtime file handle and associates
1504 * it with the Win32 HANDLE specified by the first parameter. This is a
1505 * temperary fix for WIN95's brain damage GetFileType() error on socket
1506 * we just bypass that call for socket
1509 * long osfhandle - Win32 HANDLE to associate with C Runtime file handle.
1510 * int flags - flags to associate with C Runtime file handle.
1513 * returns index of entry in fh, if successful
1514 * return -1, if no free entry is found
1518 *******************************************************************************/
1521 my_open_osfhandle(long osfhandle, int flags)
1524 char fileflags; /* _osfile flags */
1526 /* copy relevant flags from second parameter */
1529 if (flags & O_APPEND)
1530 fileflags |= FAPPEND;
1535 /* attempt to allocate a C Runtime file handle */
1536 if ((fh = _alloc_osfhnd()) == -1) {
1537 errno = EMFILE; /* too many open files */
1538 _doserrno = 0L; /* not an OS error */
1539 return -1; /* return error to caller */
1542 /* the file is open. now, set the info in _osfhnd array */
1543 _set_osfhnd(fh, osfhandle);
1545 fileflags |= FOPEN; /* mark as open */
1547 #if (_MSC_VER >= 1000)
1548 _osfile(fh) = fileflags; /* set osfile entry */
1549 _unlock_fhandle(fh);
1551 _osfile[fh] = fileflags; /* set osfile entry */
1552 _unlock(fh+_FH_LOCKS); /* unlock handle */
1555 return fh; /* return handle */
1558 #define _open_osfhandle my_open_osfhandle
1559 #endif /* USE_FIXED_OSFHANDLE */
1561 /* simulate flock by locking a range on the file */
1563 #define LK_ERR(f,i) ((f) ? (i = 0) : (errno = GetLastError()))
1564 #define LK_LEN 0xffff0000
1567 win32_flock(int fd, int oper)
1574 croak("flock() unimplemented on this platform");
1577 fh = (HANDLE)_get_osfhandle(fd);
1578 memset(&o, 0, sizeof(o));
1581 case LOCK_SH: /* shared lock */
1582 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
1584 case LOCK_EX: /* exclusive lock */
1585 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
1587 case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
1588 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
1590 case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
1591 LK_ERR(LockFileEx(fh,
1592 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
1593 0, LK_LEN, 0, &o),i);
1595 case LOCK_UN: /* unlock lock */
1596 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, 0, &o),i);
1598 default: /* unknown */
1609 * redirected io subsystem for all XS modules
1622 return (&(_environ));
1625 /* the rest are the remapped stdio routines */
1645 win32_ferror(FILE *fp)
1647 return (ferror(fp));
1652 win32_feof(FILE *fp)
1658 * Since the errors returned by the socket error function
1659 * WSAGetLastError() are not known by the library routine strerror
1660 * we have to roll our own.
1664 win32_strerror(int e)
1666 #ifndef __BORLANDC__ /* Borland intolerance */
1667 extern int sys_nerr;
1671 if (e < 0 || e > sys_nerr) {
1676 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
1677 strerror_buffer, sizeof(strerror_buffer), NULL) == 0)
1678 strcpy(strerror_buffer, "Unknown Error");
1680 return strerror_buffer;
1686 win32_str_os_error(void *sv, DWORD dwErr)
1690 dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
1691 |FORMAT_MESSAGE_IGNORE_INSERTS
1692 |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
1693 dwErr, 0, (char *)&sMsg, 1, NULL);
1695 while (0 < dwLen && isspace(sMsg[--dwLen]))
1697 if ('.' != sMsg[dwLen])
1702 sMsg = (char*)LocalAlloc(0, 64/**sizeof(TCHAR)*/);
1703 dwLen = sprintf(sMsg,
1704 "Unknown error #0x%lX (lookup 0x%lX)",
1705 dwErr, GetLastError());
1707 sv_setpvn((SV*)sv, sMsg, dwLen);
1713 win32_fprintf(FILE *fp, const char *format, ...)
1716 va_start(marker, format); /* Initialize variable arguments. */
1718 return (vfprintf(fp, format, marker));
1722 win32_printf(const char *format, ...)
1725 va_start(marker, format); /* Initialize variable arguments. */
1727 return (vprintf(format, marker));
1731 win32_vfprintf(FILE *fp, const char *format, va_list args)
1733 return (vfprintf(fp, format, args));
1737 win32_vprintf(const char *format, va_list args)
1739 return (vprintf(format, args));
1743 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
1745 return fread(buf, size, count, fp);
1749 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
1751 return fwrite(buf, size, count, fp);
1755 win32_fopen(const char *filename, const char *mode)
1757 if (stricmp(filename, "/dev/null")==0)
1758 return fopen("NUL", mode);
1759 return fopen(filename, mode);
1762 #ifndef USE_SOCKETS_AS_HANDLES
1764 #define fdopen my_fdopen
1768 win32_fdopen( int handle, const char *mode)
1770 return fdopen(handle, (char *) mode);
1774 win32_freopen( const char *path, const char *mode, FILE *stream)
1776 if (stricmp(path, "/dev/null")==0)
1777 return freopen("NUL", mode, stream);
1778 return freopen(path, mode, stream);
1782 win32_fclose(FILE *pf)
1784 return my_fclose(pf); /* defined in win32sck.c */
1788 win32_fputs(const char *s,FILE *pf)
1790 return fputs(s, pf);
1794 win32_fputc(int c,FILE *pf)
1800 win32_ungetc(int c,FILE *pf)
1802 return ungetc(c,pf);
1806 win32_getc(FILE *pf)
1812 win32_fileno(FILE *pf)
1818 win32_clearerr(FILE *pf)
1825 win32_fflush(FILE *pf)
1831 win32_ftell(FILE *pf)
1837 win32_fseek(FILE *pf,long offset,int origin)
1839 return fseek(pf, offset, origin);
1843 win32_fgetpos(FILE *pf,fpos_t *p)
1845 return fgetpos(pf, p);
1849 win32_fsetpos(FILE *pf,const fpos_t *p)
1851 return fsetpos(pf, p);
1855 win32_rewind(FILE *pf)
1875 win32_fstat(int fd,struct stat *sbufptr)
1877 return fstat(fd,sbufptr);
1881 win32_pipe(int *pfd, unsigned int size, int mode)
1883 return _pipe(pfd, size, mode);
1887 * a popen() clone that respects PERL5SHELL
1891 win32_popen(const char *command, const char *mode)
1893 #ifdef USE_RTL_POPEN
1894 return _popen(command, mode);
1902 /* establish which ends read and write */
1903 if (strchr(mode,'w')) {
1904 stdfd = 0; /* stdin */
1908 else if (strchr(mode,'r')) {
1909 stdfd = 1; /* stdout */
1916 /* set the correct mode */
1917 if (strchr(mode,'b'))
1919 else if (strchr(mode,'t'))
1922 ourmode = _fmode & (O_TEXT | O_BINARY);
1924 /* the child doesn't inherit handles */
1925 ourmode |= O_NOINHERIT;
1927 if (win32_pipe( p, 512, ourmode) == -1)
1930 /* save current stdfd */
1931 if ((oldfd = win32_dup(stdfd)) == -1)
1934 /* make stdfd go to child end of pipe (implicitly closes stdfd) */
1935 /* stdfd will be inherited by the child */
1936 if (win32_dup2(p[child], stdfd) == -1)
1939 /* close the child end in parent */
1940 win32_close(p[child]);
1942 /* start the child */
1943 if ((childpid = do_spawn_nowait((char*)command)) == -1)
1946 /* revert stdfd to whatever it was before */
1947 if (win32_dup2(oldfd, stdfd) == -1)
1950 /* close saved handle */
1953 sv_setiv(*av_fetch(w32_fdpid, p[parent], TRUE), childpid);
1955 /* we have an fd, return a file stream */
1956 return (win32_fdopen(p[parent], (char *)mode));
1959 /* we don't need to check for errors here */
1963 win32_dup2(oldfd, stdfd);
1968 #endif /* USE_RTL_POPEN */
1976 win32_pclose(FILE *pf)
1978 #ifdef USE_RTL_POPEN
1982 int childpid, status;
1985 sv = *av_fetch(w32_fdpid, win32_fileno(pf), TRUE);
1987 childpid = SvIVX(sv);
1999 if (win32_waitpid(childpid, &status, 0) == -1)
2004 #endif /* USE_RTL_POPEN */
2008 win32_rename(const char *oname, const char *newname)
2010 /* XXX despite what the documentation says about MoveFileEx(),
2011 * it doesn't work under Windows95!
2014 if (!MoveFileEx(oname,newname,
2015 MOVEFILE_COPY_ALLOWED|MOVEFILE_REPLACE_EXISTING)) {
2016 DWORD err = GetLastError();
2018 case ERROR_BAD_NET_NAME:
2019 case ERROR_BAD_NETPATH:
2020 case ERROR_BAD_PATHNAME:
2021 case ERROR_FILE_NOT_FOUND:
2022 case ERROR_FILENAME_EXCED_RANGE:
2023 case ERROR_INVALID_DRIVE:
2024 case ERROR_NO_MORE_FILES:
2025 case ERROR_PATH_NOT_FOUND:
2038 char tmpname[MAX_PATH+1];
2039 char dname[MAX_PATH+1];
2040 char *endname = Nullch;
2042 DWORD from_attr, to_attr;
2044 /* if oname doesn't exist, do nothing */
2045 from_attr = GetFileAttributes(oname);
2046 if (from_attr == 0xFFFFFFFF) {
2051 /* if newname exists, rename it to a temporary name so that we
2052 * don't delete it in case oname happens to be the same file
2053 * (but perhaps accessed via a different path)
2055 to_attr = GetFileAttributes(newname);
2056 if (to_attr != 0xFFFFFFFF) {
2057 /* if newname is a directory, we fail
2058 * XXX could overcome this with yet more convoluted logic */
2059 if (to_attr & FILE_ATTRIBUTE_DIRECTORY) {
2063 tmplen = strlen(newname);
2064 strcpy(tmpname,newname);
2065 endname = tmpname+tmplen;
2066 for (; endname > tmpname ; --endname) {
2067 if (*endname == '/' || *endname == '\\') {
2072 if (endname > tmpname)
2073 endname = strcpy(dname,tmpname);
2077 /* get a temporary filename in same directory
2078 * XXX is this really the best we can do? */
2079 if (!GetTempFileName((LPCTSTR)endname, "plr", 0, tmpname)) {
2083 DeleteFile(tmpname);
2085 retval = rename(newname, tmpname);
2092 /* rename oname to newname */
2093 retval = rename(oname, newname);
2095 /* if we created a temporary file before ... */
2096 if (endname != Nullch) {
2097 /* ...and rename succeeded, delete temporary file/directory */
2099 DeleteFile(tmpname);
2100 /* else restore it to what it was */
2102 (void)rename(tmpname, newname);
2109 win32_setmode(int fd, int mode)
2111 return setmode(fd, mode);
2115 win32_lseek(int fd, long offset, int origin)
2117 return lseek(fd, offset, origin);
2127 win32_open(const char *path, int flag, ...)
2133 pmode = va_arg(ap, int);
2136 if (stricmp(path, "/dev/null")==0)
2137 return open("NUL", flag, pmode);
2138 return open(path,flag,pmode);
2160 win32_dup2(int fd1,int fd2)
2162 return dup2(fd1,fd2);
2166 win32_read(int fd, void *buf, unsigned int cnt)
2168 return read(fd, buf, cnt);
2172 win32_write(int fd, const void *buf, unsigned int cnt)
2174 return write(fd, buf, cnt);
2178 win32_mkdir(const char *dir, int mode)
2180 return mkdir(dir); /* just ignore mode */
2184 win32_rmdir(const char *dir)
2190 win32_chdir(const char *dir)
2196 create_command_line(const char* command, const char * const *args)
2199 char *cmd, *ptr, *arg;
2200 STRLEN len = strlen(command) + 1;
2202 for (index = 0; (ptr = (char*)args[index]) != NULL; ++index)
2203 len += strlen(ptr) + 1;
2205 New(1310, cmd, len, char);
2207 strcpy(ptr, command);
2209 for (index = 0; (arg = (char*)args[index]) != NULL; ++index) {
2219 qualified_path(const char *cmd)
2222 char *fullcmd, *curfullcmd;
2228 fullcmd = (char*)cmd;
2230 if (*fullcmd == '/' || *fullcmd == '\\')
2237 pathstr = win32_getenv("PATH");
2238 New(0, fullcmd, MAX_PATH+1, char);
2239 curfullcmd = fullcmd;
2244 /* start by appending the name to the current prefix */
2245 strcpy(curfullcmd, cmd);
2246 curfullcmd += cmdlen;
2248 /* if it doesn't end with '.', or has no extension, try adding
2249 * a trailing .exe first */
2250 if (cmd[cmdlen-1] != '.'
2251 && (cmdlen < 4 || cmd[cmdlen-4] != '.'))
2253 strcpy(curfullcmd, ".exe");
2254 res = GetFileAttributes(fullcmd);
2255 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
2260 /* that failed, try the bare name */
2261 res = GetFileAttributes(fullcmd);
2262 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
2265 /* quit if no other path exists, or if cmd already has path */
2266 if (!pathstr || !*pathstr || has_slash)
2269 /* skip leading semis */
2270 while (*pathstr == ';')
2273 /* build a new prefix from scratch */
2274 curfullcmd = fullcmd;
2275 while (*pathstr && *pathstr != ';') {
2276 if (*pathstr == '"') { /* foo;"baz;etc";bar */
2277 pathstr++; /* skip initial '"' */
2278 while (*pathstr && *pathstr != '"') {
2279 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
2280 *curfullcmd++ = *pathstr;
2284 pathstr++; /* skip trailing '"' */
2287 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
2288 *curfullcmd++ = *pathstr;
2293 pathstr++; /* skip trailing semi */
2294 if (curfullcmd > fullcmd /* append a dir separator */
2295 && curfullcmd[-1] != '/' && curfullcmd[-1] != '\\')
2297 *curfullcmd++ = '\\';
2305 /* XXX this needs to be made more compatible with the spawnvp()
2306 * provided by the various RTLs. In particular, searching for
2307 * *.{com,bat,cmd} files (as done by the RTLs) is unimplemented.
2308 * This doesn't significantly affect perl itself, because we
2309 * always invoke things using PERL5SHELL if a direct attempt to
2310 * spawn the executable fails.
2312 * XXX splitting and rejoining the commandline between do_aspawn()
2313 * and win32_spawnvp() could also be avoided.
2317 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
2319 #ifdef USE_RTL_SPAWNVP
2320 return spawnvp(mode, cmdname, (char * const *)argv);
2323 STARTUPINFO StartupInfo;
2324 PROCESS_INFORMATION ProcessInformation;
2327 char *cmd = create_command_line(cmdname, strcmp(cmdname, argv[0]) == 0
2329 char *fullcmd = Nullch;
2332 case P_NOWAIT: /* asynch + remember result */
2333 if (w32_num_children >= MAXIMUM_WAIT_OBJECTS) {
2339 case P_WAIT: /* synchronous execution */
2341 default: /* invalid mode */
2346 memset(&StartupInfo,0,sizeof(StartupInfo));
2347 StartupInfo.cb = sizeof(StartupInfo);
2348 StartupInfo.wShowWindow = SW_SHOWDEFAULT;
2351 if (!CreateProcess(cmdname, /* search PATH to find executable */
2352 cmd, /* executable, and its arguments */
2353 NULL, /* process attributes */
2354 NULL, /* thread attributes */
2355 TRUE, /* inherit handles */
2356 create, /* creation flags */
2357 NULL, /* inherit environment */
2358 NULL, /* inherit cwd */
2360 &ProcessInformation))
2362 /* initial NULL argument to CreateProcess() does a PATH
2363 * search, but it always first looks in the directory
2364 * where the current process was started, which behavior
2365 * is undesirable for backward compatibility. So we
2366 * jump through our own hoops by picking out the path
2367 * we really want it to use. */
2369 fullcmd = qualified_path(cmdname);
2380 if (mode == P_NOWAIT) {
2381 /* asynchronous spawn -- store handle, return PID */
2382 w32_child_handles[w32_num_children] = ProcessInformation.hProcess;
2383 ret = w32_child_pids[w32_num_children] = ProcessInformation.dwProcessId;
2387 WaitForSingleObject(ProcessInformation.hProcess, INFINITE);
2388 GetExitCodeProcess(ProcessInformation.hProcess, &ret);
2389 CloseHandle(ProcessInformation.hProcess);
2392 CloseHandle(ProcessInformation.hThread);
2401 win32_execv(const char *cmdname, const char *const *argv)
2403 return execv(cmdname, (char *const *)argv);
2407 win32_execvp(const char *cmdname, const char *const *argv)
2409 return execvp(cmdname, (char *const *)argv);
2413 win32_perror(const char *str)
2419 win32_setbuf(FILE *pf, char *buf)
2425 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
2427 return setvbuf(pf, buf, type, size);
2431 win32_flushall(void)
2437 win32_fcloseall(void)
2443 win32_fgets(char *s, int n, FILE *pf)
2445 return fgets(s, n, pf);
2455 win32_fgetc(FILE *pf)
2461 win32_putc(int c, FILE *pf)
2467 win32_puts(const char *s)
2479 win32_putchar(int c)
2486 #ifndef USE_PERL_SBRK
2488 static char *committed = NULL;
2489 static char *base = NULL;
2490 static char *reserved = NULL;
2491 static char *brk = NULL;
2492 static DWORD pagesize = 0;
2493 static DWORD allocsize = 0;
2501 GetSystemInfo(&info);
2502 /* Pretend page size is larger so we don't perpetually
2503 * call the OS to commit just one page ...
2505 pagesize = info.dwPageSize << 3;
2506 allocsize = info.dwAllocationGranularity;
2508 /* This scheme fails eventually if request for contiguous
2509 * block is denied so reserve big blocks - this is only
2510 * address space not memory ...
2512 if (brk+need >= reserved)
2514 DWORD size = 64*1024*1024;
2516 if (committed && reserved && committed < reserved)
2518 /* Commit last of previous chunk cannot span allocations */
2519 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
2521 committed = reserved;
2523 /* Reserve some (more) space
2524 * Note this is a little sneaky, 1st call passes NULL as reserved
2525 * so lets system choose where we start, subsequent calls pass
2526 * the old end address so ask for a contiguous block
2528 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
2531 reserved = addr+size;
2546 if (brk > committed)
2548 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
2549 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
2564 win32_malloc(size_t size)
2566 return malloc(size);
2570 win32_calloc(size_t numitems, size_t size)
2572 return calloc(numitems,size);
2576 win32_realloc(void *block, size_t size)
2578 return realloc(block,size);
2582 win32_free(void *block)
2589 win32_open_osfhandle(long handle, int flags)
2591 return _open_osfhandle(handle, flags);
2595 win32_get_osfhandle(int fd)
2597 return _get_osfhandle(fd);
2608 SV *sv = sv_newmortal();
2609 /* Make one call with zero size - return value is required size */
2610 DWORD len = GetCurrentDirectory((DWORD)0,NULL);
2611 SvUPGRADE(sv,SVt_PV);
2613 SvCUR(sv) = GetCurrentDirectory((DWORD) SvLEN(sv), SvPVX(sv));
2616 * then it worked, set PV valid,
2617 * else leave it 'undef'
2633 croak("usage: Win32::SetCurrentDirectory($cwd)");
2634 if (SetCurrentDirectory(SvPV_nolen(ST(0))))
2641 XS(w32_GetNextAvailDrive)
2645 char root[] = "_:\\";
2650 if (GetDriveType(root) == 1) {
2659 XS(w32_GetLastError)
2663 XSRETURN_IV(GetLastError());
2667 XS(w32_SetLastError)
2671 croak("usage: Win32::SetLastError($error)");
2672 SetLastError(SvIV(ST(0)));
2680 char *name = getlogin_buffer;
2681 DWORD size = sizeof(getlogin_buffer);
2683 if (GetUserName(name,&size)) {
2684 /* size includes NULL */
2685 ST(0) = sv_2mortal(newSVpvn(name,size-1));
2695 char name[MAX_COMPUTERNAME_LENGTH+1];
2696 DWORD size = sizeof(name);
2698 if (GetComputerName(name,&size)) {
2699 /* size does NOT include NULL :-( */
2700 ST(0) = sv_2mortal(newSVpvn(name,size));
2711 #ifndef HAS_NETWKSTAGETINFO
2712 /* mingw32 (and Win95) don't have NetWksta*(), so do it the old way */
2714 DWORD size = sizeof(name);
2716 if (GetUserName(name,&size)) {
2718 DWORD sidlen = sizeof(sid);
2720 DWORD dnamelen = sizeof(dname);
2722 if (LookupAccountName(NULL, name, (PSID)&sid, &sidlen,
2723 dname, &dnamelen, &snu)) {
2724 XSRETURN_PV(dname); /* all that for this */
2728 /* this way is more reliable, in case user has a local account.
2729 * XXX need dynamic binding of netapi32.dll symbols or this will fail on
2730 * Win95. Probably makes more sense to move it into libwin32. */
2732 DWORD dnamelen = sizeof(dname);
2733 PWKSTA_INFO_100 pwi;
2735 if (NERR_Success == NetWkstaGetInfo(NULL, 100, (LPBYTE*)&pwi)) {
2736 if (pwi->wki100_langroup && *(pwi->wki100_langroup)) {
2737 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_langroup,
2738 -1, (LPSTR)dname, dnamelen, NULL, NULL);
2741 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_computername,
2742 -1, (LPSTR)dname, dnamelen, NULL, NULL);
2744 NetApiBufferFree(pwi);
2756 DWORD flags, filecomplen;
2757 if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
2758 &flags, fsname, sizeof(fsname))) {
2759 if (GIMME_V == G_ARRAY) {
2760 XPUSHs(sv_2mortal(newSVpvn(fsname,strlen(fsname))));
2761 XPUSHs(sv_2mortal(newSViv(flags)));
2762 XPUSHs(sv_2mortal(newSViv(filecomplen)));
2767 XSRETURN_PV(fsname);
2773 XS(w32_GetOSVersion)
2776 OSVERSIONINFO osver;
2778 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
2779 if (GetVersionEx(&osver)) {
2780 XPUSHs(newSVpvn(osver.szCSDVersion, strlen(osver.szCSDVersion)));
2781 XPUSHs(newSViv(osver.dwMajorVersion));
2782 XPUSHs(newSViv(osver.dwMinorVersion));
2783 XPUSHs(newSViv(osver.dwBuildNumber));
2784 XPUSHs(newSViv(osver.dwPlatformId));
2796 XSRETURN_IV(IsWinNT());
2804 XSRETURN_IV(IsWin95());
2808 XS(w32_FormatMessage)
2815 croak("usage: Win32::FormatMessage($errno)");
2817 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
2818 &source, SvIV(ST(0)), 0,
2819 msgbuf, sizeof(msgbuf)-1, NULL))
2820 XSRETURN_PV(msgbuf);
2830 PROCESS_INFORMATION stProcInfo;
2831 STARTUPINFO stStartInfo;
2832 BOOL bSuccess = FALSE;
2835 croak("usage: Win32::Spawn($cmdName, $args, $PID)");
2837 cmd = SvPV_nolen(ST(0));
2838 args = SvPV_nolen(ST(1));
2840 memset(&stStartInfo, 0, sizeof(stStartInfo)); /* Clear the block */
2841 stStartInfo.cb = sizeof(stStartInfo); /* Set the structure size */
2842 stStartInfo.dwFlags = STARTF_USESHOWWINDOW; /* Enable wShowWindow control */
2843 stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE; /* Start min (normal) */
2846 cmd, /* Image path */
2847 args, /* Arguments for command line */
2848 NULL, /* Default process security */
2849 NULL, /* Default thread security */
2850 FALSE, /* Must be TRUE to use std handles */
2851 NORMAL_PRIORITY_CLASS, /* No special scheduling */
2852 NULL, /* Inherit our environment block */
2853 NULL, /* Inherit our currrent directory */
2854 &stStartInfo, /* -> Startup info */
2855 &stProcInfo)) /* <- Process info (if OK) */
2857 CloseHandle(stProcInfo.hThread);/* library source code does this. */
2858 sv_setiv(ST(2), stProcInfo.dwProcessId);
2861 XSRETURN_IV(bSuccess);
2865 XS(w32_GetTickCount)
2868 DWORD msec = GetTickCount();
2876 XS(w32_GetShortPathName)
2883 croak("usage: Win32::GetShortPathName($longPathName)");
2885 shortpath = sv_mortalcopy(ST(0));
2886 SvUPGRADE(shortpath, SVt_PV);
2887 /* src == target is allowed */
2889 len = GetShortPathName(SvPVX(shortpath),
2892 } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
2894 SvCUR_set(shortpath,len);
2902 XS(w32_GetFullPathName)
2911 croak("usage: Win32::GetFullPathName($filename)");
2914 fullpath = sv_mortalcopy(filename);
2915 SvUPGRADE(fullpath, SVt_PV);
2917 len = GetFullPathName(SvPVX(filename),
2921 } while (len >= SvLEN(fullpath) && sv_grow(fullpath,len+1));
2923 if (GIMME_V == G_ARRAY) {
2925 XST_mPV(1,filepart);
2926 len = filepart - SvPVX(fullpath);
2929 SvCUR_set(fullpath,len);
2937 XS(w32_GetLongPathName)
2941 char tmpbuf[MAX_PATH+1];
2946 croak("usage: Win32::GetLongPathName($pathname)");
2949 pathstr = SvPV(path,len);
2950 strcpy(tmpbuf, pathstr);
2951 pathstr = win32_longpath(tmpbuf);
2953 ST(0) = sv_2mortal(newSVpvn(pathstr, strlen(pathstr)));
2964 croak("usage: Win32::Sleep($milliseconds)");
2974 croak("usage: Win32::CopyFile($from, $to, $overwrite)");
2975 if (CopyFile(SvPV_nolen(ST(0)), SvPV_nolen(ST(1)), !SvTRUE(ST(2))))
2981 Perl_init_os_extras()
2983 char *file = __FILE__;
2986 w32_perlshell_tokens = Nullch;
2987 w32_perlshell_items = -1;
2988 w32_fdpid = newAV(); /* XXX needs to be in Perl_win32_init()? */
2989 New(1313, w32_children, 1, child_tab);
2990 w32_num_children = 0;
2992 /* these names are Activeware compatible */
2993 newXS("Win32::GetCwd", w32_GetCwd, file);
2994 newXS("Win32::SetCwd", w32_SetCwd, file);
2995 newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
2996 newXS("Win32::GetLastError", w32_GetLastError, file);
2997 newXS("Win32::SetLastError", w32_SetLastError, file);
2998 newXS("Win32::LoginName", w32_LoginName, file);
2999 newXS("Win32::NodeName", w32_NodeName, file);
3000 newXS("Win32::DomainName", w32_DomainName, file);
3001 newXS("Win32::FsType", w32_FsType, file);
3002 newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
3003 newXS("Win32::IsWinNT", w32_IsWinNT, file);
3004 newXS("Win32::IsWin95", w32_IsWin95, file);
3005 newXS("Win32::FormatMessage", w32_FormatMessage, file);
3006 newXS("Win32::Spawn", w32_Spawn, file);
3007 newXS("Win32::GetTickCount", w32_GetTickCount, file);
3008 newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
3009 newXS("Win32::GetFullPathName", w32_GetFullPathName, file);
3010 newXS("Win32::GetLongPathName", w32_GetLongPathName, file);
3011 newXS("Win32::CopyFile", w32_CopyFile, file);
3012 newXS("Win32::Sleep", w32_Sleep, file);
3014 /* XXX Bloat Alert! The following Activeware preloads really
3015 * ought to be part of Win32::Sys::*, so they're not included
3018 /* LookupAccountName
3020 * InitiateSystemShutdown
3021 * AbortSystemShutdown
3022 * ExpandEnvrironmentStrings
3027 Perl_win32_init(int *argcp, char ***argvp)
3029 /* Disable floating point errors, Perl will trap the ones we
3030 * care about. VC++ RTL defaults to switching these off
3031 * already, but the Borland RTL doesn't. Since we don't
3032 * want to be at the vendor's whim on the default, we set
3033 * it explicitly here.
3035 #if !defined(_ALPHA_) && !defined(__GNUC__)
3036 _control87(MCW_EM, MCW_EM);
3041 #ifdef USE_BINMODE_SCRIPTS
3044 win32_strip_return(SV *sv)
3046 char *s = SvPVX(sv);
3047 char *e = s+SvCUR(sv);
3051 if (*s == '\r' && s[1] == '\n')
3061 SvCUR_set(sv,d-SvPVX(sv));