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 static DWORD w32_platform = (DWORD)-1;
106 # ifdef USE_DECLSPEC_THREAD
107 __declspec(thread) char strerror_buffer[512];
108 __declspec(thread) char getlogin_buffer[128];
109 __declspec(thread) char w32_perllib_root[MAX_PATH+1];
110 # ifdef HAVE_DES_FCRYPT
111 __declspec(thread) char crypt_buffer[30];
114 # define strerror_buffer (thr->i.Wstrerror_buffer)
115 # define getlogin_buffer (thr->i.Wgetlogin_buffer)
116 # define w32_perllib_root (thr->i.Ww32_perllib_root)
117 # define crypt_buffer (thr->i.Wcrypt_buffer)
120 static char strerror_buffer[512];
121 static char getlogin_buffer[128];
122 static char w32_perllib_root[MAX_PATH+1];
123 # ifdef HAVE_DES_FCRYPT
124 static char crypt_buffer[30];
130 return (os_id() == VER_PLATFORM_WIN32_WINDOWS);
135 return (os_id() == VER_PLATFORM_WIN32_NT);
139 GetRegStrFromKey(HKEY hkey, const char *lpszValueName, char** ptr, DWORD* lpDataLen)
140 { /* Retrieve a REG_SZ or REG_EXPAND_SZ from the registry */
143 const char *subkey = "Software\\Perl";
146 retval = RegOpenKeyEx(hkey, subkey, 0, KEY_READ, &handle);
147 if (retval == ERROR_SUCCESS){
148 retval = RegQueryValueEx(handle, lpszValueName, 0, &type, NULL, lpDataLen);
149 if (retval == ERROR_SUCCESS && type == REG_SZ) {
151 Renew(*ptr, *lpDataLen, char);
154 New(1312, *ptr, *lpDataLen, char);
156 retval = RegQueryValueEx(handle, lpszValueName, 0, NULL, (PBYTE)*ptr, lpDataLen);
157 if (retval != ERROR_SUCCESS) {
168 GetRegStr(const char *lpszValueName, char** ptr, DWORD* lpDataLen)
170 *ptr = GetRegStrFromKey(HKEY_CURRENT_USER, lpszValueName, ptr, lpDataLen);
173 *ptr = GetRegStrFromKey(HKEY_LOCAL_MACHINE, lpszValueName, ptr, lpDataLen);
179 get_emd_part(char *prev_path, char *trailing_path, ...)
183 char mod_name[MAX_PATH+1];
187 int oldsize, newsize;
189 va_start(ap, trailing_path);
190 strip = va_arg(ap, char *);
192 sprintf(base, "%5.3f",
193 (double)PERL_REVISION + ((double)PERL_VERSION / (double)1000));
195 GetModuleFileName((HMODULE)((w32_perldll_handle == INVALID_HANDLE_VALUE)
196 ? GetModuleHandle(NULL) : w32_perldll_handle),
197 mod_name, sizeof(mod_name));
198 /* try to get full path to binary (which may be mangled when perl is
199 * run from a 16-bit app */
200 (void)GetFullPathName(mod_name, sizeof(mod_name), mod_name, &ptr);
202 /* normalize to forward slashes */
208 ptr = strrchr(mod_name, '/');
209 while (ptr && strip) {
210 /* look for directories to skip back */
213 ptr = strrchr(mod_name, '/');
214 if (!ptr || stricmp(ptr+1, strip) != 0) {
215 if(!(*strip == '5' && *(ptr+1) == '5'
216 && strncmp(strip, base, 5) == 0
217 && strncmp(ptr+1, base, 5) == 0))
223 strip = va_arg(ap, char *);
231 strcpy(++ptr, trailing_path);
233 /* only add directory if it exists */
234 if(GetFileAttributes(mod_name) != (DWORD) -1) {
235 /* directory exists */
236 newsize = strlen(mod_name) + 1;
238 oldsize = strlen(prev_path) + 1;
239 newsize += oldsize; /* includes plus 1 for ';' */
240 Renew(prev_path, newsize, char);
241 prev_path[oldsize-1] = ';';
242 strcpy(&prev_path[oldsize], mod_name);
245 New(1311, prev_path, newsize, char);
246 strcpy(prev_path, mod_name);
254 win32_get_privlib(char *pl)
256 char *stdlib = "lib";
257 char buffer[MAX_PATH+1];
261 /* $stdlib = $HKCU{"lib-$]"} || $HKLM{"lib-$]"} || $HKCU{"lib"} || $HKLM{"lib"} || ""; */
262 sprintf(buffer, "%s-%s", stdlib, pl);
263 path = GetRegStr(buffer, &path, &datalen);
265 path = GetRegStr(stdlib, &path, &datalen);
267 /* $stdlib .= ";$EMD/../../lib" */
268 return get_emd_part(path, stdlib, ARCHNAME, "bin", Nullch);
272 win32_get_sitelib(char *pl)
274 char *sitelib = "sitelib";
276 char pathstr[MAX_PATH+1];
278 char *path1 = Nullch;
279 char *path2 = Nullch;
282 /* $HKCU{"sitelib-$]"} || $HKLM{"sitelib-$]"} . ---; */
283 sprintf(regstr, "%s-%s", sitelib, pl);
284 path1 = GetRegStr(regstr, &path1, &datalen);
287 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/site/$]/lib"; */
288 sprintf(pathstr, "site/%s/lib", pl);
289 path1 = get_emd_part(path1, pathstr, ARCHNAME, "bin", pl, Nullch);
291 /* $HKCU{'sitelib'} || $HKLM{'sitelib'} . ---; */
292 path2 = GetRegStr(sitelib, &path2, &datalen);
295 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/site/lib"; */
296 path2 = get_emd_part(path2, "site/lib", ARCHNAME, "bin", pl, Nullch);
305 newsize = len + strlen(path2) + 2; /* plus one for ';' */
307 Renew(path1, newsize, char);
309 strcpy(&path1[len], path2);
317 has_shell_metachars(char *ptr)
323 * Scan string looking for redirection (< or >) or pipe
324 * characters (|) that are not in a quoted string.
325 * Shell variable interpolation (%VAR%) can also happen inside strings.
357 #if !defined(PERL_OBJECT)
358 /* since the current process environment is being updated in util.c
359 * the library functions will get the correct environment
362 my_popen(char *cmd, char *mode)
365 #define fixcmd(x) { \
366 char *pspace = strchr((x),' '); \
369 while (p < pspace) { \
380 win32_fflush(stdout);
381 win32_fflush(stderr);
382 return win32_popen(cmd, mode);
386 my_pclose(PerlIO *fp)
388 return win32_pclose(fp);
395 static OSVERSIONINFO osver;
397 if (osver.dwPlatformId != w32_platform) {
398 memset(&osver, 0, sizeof(OSVERSIONINFO));
399 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
400 GetVersionEx(&osver);
401 w32_platform = osver.dwPlatformId;
403 return (w32_platform);
406 /* Tokenize a string. Words are null-separated, and the list
407 * ends with a doubled null. Any character (except null and
408 * including backslash) may be escaped by preceding it with a
409 * backslash (the backslash will be stripped).
410 * Returns number of words in result buffer.
413 tokenize(char *str, char **dest, char ***destv)
415 char *retstart = Nullch;
416 char **retvstart = 0;
419 int slen = strlen(str);
421 register char **retv;
422 New(1307, ret, slen+2, char);
423 New(1308, retv, (slen+3)/2, char*);
431 if (*ret == '\\' && *str)
433 else if (*ret == ' ') {
449 retvstart[items] = Nullch;
461 if (!w32_perlshell_tokens) {
462 /* we don't use COMSPEC here for two reasons:
463 * 1. the same reason perl on UNIX doesn't use SHELL--rampant and
464 * uncontrolled unportability of the ensuing scripts.
465 * 2. PERL5SHELL could be set to a shell that may not be fit for
466 * interactive use (which is what most programs look in COMSPEC
469 char* defaultshell = (IsWinNT() ? "cmd.exe /x/c" : "command.com /c");
470 char *usershell = getenv("PERL5SHELL");
471 w32_perlshell_items = tokenize(usershell ? usershell : defaultshell,
472 &w32_perlshell_tokens,
478 do_aspawn(void *vreally, void **vmark, void **vsp)
480 SV *really = (SV*)vreally;
481 SV **mark = (SV**)vmark;
493 New(1306, argv, (sp - mark) + w32_perlshell_items + 2, char*);
495 if (SvNIOKp(*(mark+1)) && !SvPOKp(*(mark+1))) {
500 while (++mark <= sp) {
501 if (*mark && (str = SvPV_nolen(*mark)))
508 status = win32_spawnvp(flag,
509 (const char*)(really ? SvPV_nolen(really) : argv[0]),
510 (const char* const*)argv);
512 if (status < 0 && (errno == ENOEXEC || errno == ENOENT)) {
513 /* possible shell-builtin, invoke with shell */
515 sh_items = w32_perlshell_items;
517 argv[index+sh_items] = argv[index];
518 while (--sh_items >= 0)
519 argv[sh_items] = w32_perlshell_vec[sh_items];
521 status = win32_spawnvp(flag,
522 (const char*)(really ? SvPV_nolen(really) : argv[0]),
523 (const char* const*)argv);
526 if (flag != P_NOWAIT) {
529 warn("Can't spawn \"%s\": %s", argv[0], strerror(errno));
534 PL_statusvalue = status;
541 do_spawn2(char *cmd, int exectype)
547 BOOL needToTry = TRUE;
550 /* Save an extra exec if possible. See if there are shell
551 * metacharacters in it */
552 if (!has_shell_metachars(cmd)) {
553 New(1301,argv, strlen(cmd) / 2 + 2, char*);
554 New(1302,cmd2, strlen(cmd) + 1, char);
557 for (s = cmd2; *s;) {
558 while (*s && isspace(*s))
562 while (*s && !isspace(*s))
571 status = win32_spawnvp(P_WAIT, argv[0],
572 (const char* const*)argv);
574 case EXECF_SPAWN_NOWAIT:
575 status = win32_spawnvp(P_NOWAIT, argv[0],
576 (const char* const*)argv);
579 status = win32_execvp(argv[0], (const char* const*)argv);
582 if (status != -1 || errno == 0)
592 New(1306, argv, w32_perlshell_items + 2, char*);
593 while (++i < w32_perlshell_items)
594 argv[i] = w32_perlshell_vec[i];
599 status = win32_spawnvp(P_WAIT, argv[0],
600 (const char* const*)argv);
602 case EXECF_SPAWN_NOWAIT:
603 status = win32_spawnvp(P_NOWAIT, argv[0],
604 (const char* const*)argv);
607 status = win32_execvp(argv[0], (const char* const*)argv);
613 if (exectype != EXECF_SPAWN_NOWAIT) {
616 warn("Can't %s \"%s\": %s",
617 (exectype == EXECF_EXEC ? "exec" : "spawn"),
618 cmd, strerror(errno));
623 PL_statusvalue = status;
631 return do_spawn2(cmd, EXECF_SPAWN);
635 do_spawn_nowait(char *cmd)
637 return do_spawn2(cmd, EXECF_SPAWN_NOWAIT);
643 do_spawn2(cmd, EXECF_EXEC);
647 /* The idea here is to read all the directory names into a string table
648 * (separated by nulls) and when one of the other dir functions is called
649 * return the pointer to the current file name.
652 win32_opendir(char *filename)
657 char scanname[MAX_PATH+3];
659 WIN32_FIND_DATA FindData;
662 len = strlen(filename);
666 /* check to see if filename is a directory */
667 if (win32_stat(filename, &sbuf) < 0 || !S_ISDIR(sbuf.st_mode))
670 /* Get us a DIR structure */
671 Newz(1303, p, 1, DIR);
675 /* Create the search pattern */
676 strcpy(scanname, filename);
677 if (scanname[len-1] != '/' && scanname[len-1] != '\\')
678 scanname[len++] = '/';
679 scanname[len++] = '*';
680 scanname[len] = '\0';
682 /* do the FindFirstFile call */
683 fh = FindFirstFile(scanname, &FindData);
684 if (fh == INVALID_HANDLE_VALUE) {
685 /* FindFirstFile() fails on empty drives! */
686 if (GetLastError() == ERROR_FILE_NOT_FOUND)
692 /* now allocate the first part of the string table for
693 * the filenames that we find.
695 idx = strlen(FindData.cFileName)+1;
696 New(1304, p->start, idx, char);
697 if (p->start == NULL)
698 croak("opendir: malloc failed!\n");
699 strcpy(p->start, FindData.cFileName);
702 /* loop finding all the files that match the wildcard
703 * (which should be all of them in this directory!).
704 * the variable idx should point one past the null terminator
705 * of the previous string found.
707 while (FindNextFile(fh, &FindData)) {
708 len = strlen(FindData.cFileName);
709 /* bump the string table size by enough for the
710 * new name and it's null terminator
712 Renew(p->start, idx+len+1, char);
713 if (p->start == NULL)
714 croak("opendir: malloc failed!\n");
715 strcpy(&p->start[idx], FindData.cFileName);
726 /* Readdir just returns the current string pointer and bumps the
727 * string pointer to the nDllExport entry.
730 win32_readdir(DIR *dirp)
733 static int dummy = 0;
736 /* first set up the structure to return */
737 len = strlen(dirp->curr);
738 strcpy(dirp->dirstr.d_name, dirp->curr);
739 dirp->dirstr.d_namlen = len;
742 dirp->dirstr.d_ino = dummy++;
744 /* Now set up for the nDllExport call to readdir */
745 dirp->curr += len + 1;
746 if (dirp->curr >= (dirp->start + dirp->size)) {
750 return &(dirp->dirstr);
756 /* Telldir returns the current string pointer position */
758 win32_telldir(DIR *dirp)
760 return (long) dirp->curr;
764 /* Seekdir moves the string pointer to a previously saved position
768 win32_seekdir(DIR *dirp, long loc)
770 dirp->curr = (char *)loc;
773 /* Rewinddir resets the string pointer to the start */
775 win32_rewinddir(DIR *dirp)
777 dirp->curr = dirp->start;
780 /* free the memory allocated by opendir */
782 win32_closedir(DIR *dirp)
784 Safefree(dirp->start);
797 * Just pretend that everyone is a superuser. NT will let us know if
798 * we don\'t really have permission to do something.
801 #define ROOT_UID ((uid_t)0)
802 #define ROOT_GID ((gid_t)0)
831 return (auid == ROOT_UID ? 0 : -1);
837 return (agid == ROOT_GID ? 0 : -1);
844 char *buf = getlogin_buffer;
845 DWORD size = sizeof(getlogin_buffer);
846 if (GetUserName(buf,&size))
852 chown(const char *path, uid_t owner, gid_t group)
862 for (child = 0 ; child < w32_num_children ; ++child) {
863 if (w32_child_pids[child] == pid)
870 remove_dead_process(long child)
873 CloseHandle(w32_child_handles[child]);
874 Copy(&w32_child_handles[child+1], &w32_child_handles[child],
875 (w32_num_children-child-1), HANDLE);
876 Copy(&w32_child_pids[child+1], &w32_child_pids[child],
877 (w32_num_children-child-1), DWORD);
883 win32_kill(int pid, int sig)
886 hProcess = OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid);
887 if (hProcess && TerminateProcess(hProcess, sig))
888 CloseHandle(hProcess);
900 DllExport unsigned int
901 win32_sleep(unsigned int t)
908 win32_stat(const char *path, struct stat *buffer)
911 int l = strlen(path);
915 switch(path[l - 1]) {
916 /* FindFirstFile() and stat() are buggy with a trailing
917 * backslash, so change it to a forward slash :-( */
919 strncpy(t, path, l-1);
924 /* FindFirstFile() is buggy with "x:", so add a slash :-( */
926 if (l == 2 && isALPHA(path[0])) {
927 t[0] = path[0]; t[1] = ':'; t[2] = '/'; t[3] = '\0';
934 res = stat(path,buffer);
936 /* CRT is buggy on sharenames, so make sure it really isn't.
937 * XXX using GetFileAttributesEx() will enable us to set
938 * buffer->st_*time (but note that's not available on the
939 * Windows of 1995) */
940 DWORD r = GetFileAttributes(path);
941 if (r != 0xffffffff && (r & FILE_ATTRIBUTE_DIRECTORY)) {
942 /* buffer may still contain old garbage since stat() failed */
943 Zero(buffer, 1, struct stat);
944 buffer->st_mode = S_IFDIR | S_IREAD;
946 if (!(r & FILE_ATTRIBUTE_READONLY))
947 buffer->st_mode |= S_IWRITE | S_IEXEC;
952 if (l == 3 && isALPHA(path[0]) && path[1] == ':'
953 && (path[2] == '\\' || path[2] == '/'))
955 /* The drive can be inaccessible, some _stat()s are buggy */
956 if (!GetVolumeInformation(path,NULL,0,NULL,NULL,NULL,NULL,0)) {
962 if (S_ISDIR(buffer->st_mode))
963 buffer->st_mode |= S_IWRITE | S_IEXEC;
964 else if (S_ISREG(buffer->st_mode)) {
965 if (l >= 4 && path[l-4] == '.') {
966 const char *e = path + l - 3;
967 if (strnicmp(e,"exe",3)
968 && strnicmp(e,"bat",3)
969 && strnicmp(e,"com",3)
970 && (IsWin95() || strnicmp(e,"cmd",3)))
971 buffer->st_mode &= ~S_IEXEC;
973 buffer->st_mode |= S_IEXEC;
976 buffer->st_mode &= ~S_IEXEC;
983 #ifndef USE_WIN32_RTL_ENV
986 win32_getenv(const char *name)
988 static char *curitem = Nullch; /* XXX threadead */
989 static DWORD curlen = 0; /* XXX threadead */
993 New(1305,curitem,curlen,char);
996 needlen = GetEnvironmentVariable(name,curitem,curlen);
998 while (needlen > curlen) {
999 Renew(curitem,needlen,char);
1001 needlen = GetEnvironmentVariable(name,curitem,curlen);
1005 /* allow any environment variables that begin with 'PERL'
1006 to be stored in the registry */
1010 if (strncmp(name, "PERL", 4) == 0) {
1016 curitem = GetRegStr(name, &curitem, &curlen);
1019 if (curitem && *curitem == '\0')
1026 win32_putenv(const char *name)
1032 New(1309,curitem,strlen(name)+1,char);
1033 strcpy(curitem, name);
1034 val = strchr(curitem, '=');
1036 /* The sane way to deal with the environment.
1037 * Has these advantages over putenv() & co.:
1038 * * enables us to store a truly empty value in the
1039 * environment (like in UNIX).
1040 * * we don't have to deal with RTL globals, bugs and leaks.
1042 * Why you may want to enable USE_WIN32_RTL_ENV:
1043 * * environ[] and RTL functions will not reflect changes,
1044 * which might be an issue if extensions want to access
1045 * the env. via RTL. This cuts both ways, since RTL will
1046 * not see changes made by extensions that call the Win32
1047 * functions directly, either.
1051 if(SetEnvironmentVariable(curitem, *val ? val : NULL))
1062 filetime_to_clock(PFILETIME ft)
1064 __int64 qw = ft->dwHighDateTime;
1066 qw |= ft->dwLowDateTime;
1067 qw /= 10000; /* File time ticks at 0.1uS, clock at 1mS */
1072 win32_times(struct tms *timebuf)
1077 if (GetProcessTimes(GetCurrentProcess(), &dummy, &dummy,
1079 timebuf->tms_utime = filetime_to_clock(&user);
1080 timebuf->tms_stime = filetime_to_clock(&kernel);
1081 timebuf->tms_cutime = 0;
1082 timebuf->tms_cstime = 0;
1085 /* That failed - e.g. Win95 fallback to clock() */
1086 clock_t t = clock();
1087 timebuf->tms_utime = t;
1088 timebuf->tms_stime = 0;
1089 timebuf->tms_cutime = 0;
1090 timebuf->tms_cstime = 0;
1095 /* fix utime() so it works on directories in NT
1096 * thanks to Jan Dubois <jan.dubois@ibm.net>
1099 filetime_from_time(PFILETIME pFileTime, time_t Time)
1101 struct tm *pTM = gmtime(&Time);
1102 SYSTEMTIME SystemTime;
1107 SystemTime.wYear = pTM->tm_year + 1900;
1108 SystemTime.wMonth = pTM->tm_mon + 1;
1109 SystemTime.wDay = pTM->tm_mday;
1110 SystemTime.wHour = pTM->tm_hour;
1111 SystemTime.wMinute = pTM->tm_min;
1112 SystemTime.wSecond = pTM->tm_sec;
1113 SystemTime.wMilliseconds = 0;
1115 return SystemTimeToFileTime(&SystemTime, pFileTime);
1119 win32_utime(const char *filename, struct utimbuf *times)
1125 struct utimbuf TimeBuffer;
1127 int rc = utime(filename,times);
1128 /* EACCES: path specifies directory or readonly file */
1129 if (rc == 0 || errno != EACCES /* || !IsWinNT() */)
1132 if (times == NULL) {
1133 times = &TimeBuffer;
1134 time(×->actime);
1135 times->modtime = times->actime;
1138 /* This will (and should) still fail on readonly files */
1139 handle = CreateFile(filename, GENERIC_READ | GENERIC_WRITE,
1140 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1141 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1142 if (handle == INVALID_HANDLE_VALUE)
1145 if (GetFileTime(handle, &ftCreate, &ftAccess, &ftWrite) &&
1146 filetime_from_time(&ftAccess, times->actime) &&
1147 filetime_from_time(&ftWrite, times->modtime) &&
1148 SetFileTime(handle, &ftCreate, &ftAccess, &ftWrite))
1153 CloseHandle(handle);
1158 win32_uname(struct utsname *name)
1160 struct hostent *hep;
1161 STRLEN nodemax = sizeof(name->nodename)-1;
1162 OSVERSIONINFO osver;
1164 memset(&osver, 0, sizeof(OSVERSIONINFO));
1165 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1166 if (GetVersionEx(&osver)) {
1168 switch (osver.dwPlatformId) {
1169 case VER_PLATFORM_WIN32_WINDOWS:
1170 strcpy(name->sysname, "Windows");
1172 case VER_PLATFORM_WIN32_NT:
1173 strcpy(name->sysname, "Windows NT");
1175 case VER_PLATFORM_WIN32s:
1176 strcpy(name->sysname, "Win32s");
1179 strcpy(name->sysname, "Win32 Unknown");
1184 sprintf(name->release, "%d.%d",
1185 osver.dwMajorVersion, osver.dwMinorVersion);
1188 sprintf(name->version, "Build %d",
1189 osver.dwPlatformId == VER_PLATFORM_WIN32_NT
1190 ? osver.dwBuildNumber : (osver.dwBuildNumber & 0xffff));
1191 if (osver.szCSDVersion[0]) {
1192 char *buf = name->version + strlen(name->version);
1193 sprintf(buf, " (%s)", osver.szCSDVersion);
1197 *name->sysname = '\0';
1198 *name->version = '\0';
1199 *name->release = '\0';
1203 hep = win32_gethostbyname("localhost");
1205 STRLEN len = strlen(hep->h_name);
1206 if (len <= nodemax) {
1207 strcpy(name->nodename, hep->h_name);
1210 strncpy(name->nodename, hep->h_name, nodemax);
1211 name->nodename[nodemax] = '\0';
1216 if (!GetComputerName(name->nodename, &sz))
1217 *name->nodename = '\0';
1220 /* machine (architecture) */
1224 GetSystemInfo(&info);
1225 switch (info.wProcessorArchitecture) {
1226 case PROCESSOR_ARCHITECTURE_INTEL:
1227 arch = "x86"; break;
1228 case PROCESSOR_ARCHITECTURE_MIPS:
1229 arch = "mips"; break;
1230 case PROCESSOR_ARCHITECTURE_ALPHA:
1231 arch = "alpha"; break;
1232 case PROCESSOR_ARCHITECTURE_PPC:
1233 arch = "ppc"; break;
1235 arch = "unknown"; break;
1237 strcpy(name->machine, arch);
1243 win32_waitpid(int pid, int *status, int flags)
1247 return win32_wait(status);
1249 long child = find_pid(pid);
1251 HANDLE hProcess = w32_child_handles[child];
1252 DWORD waitcode = WaitForSingleObject(hProcess, INFINITE);
1253 if (waitcode != WAIT_FAILED) {
1254 if (GetExitCodeProcess(hProcess, &waitcode)) {
1255 *status = (int)((waitcode & 0xff) << 8);
1256 retval = (int)w32_child_pids[child];
1257 remove_dead_process(child);
1265 retval = cwait(status, pid, WAIT_CHILD);
1266 /* cwait() returns "correctly" on Borland */
1267 #ifndef __BORLANDC__
1273 return retval >= 0 ? pid : retval;
1277 win32_wait(int *status)
1279 /* XXX this wait emulation only knows about processes
1280 * spawned via win32_spawnvp(P_NOWAIT, ...).
1283 DWORD exitcode, waitcode;
1285 if (!w32_num_children) {
1290 /* if a child exists, wait for it to die */
1291 waitcode = WaitForMultipleObjects(w32_num_children,
1295 if (waitcode != WAIT_FAILED) {
1296 if (waitcode >= WAIT_ABANDONED_0
1297 && waitcode < WAIT_ABANDONED_0 + w32_num_children)
1298 i = waitcode - WAIT_ABANDONED_0;
1300 i = waitcode - WAIT_OBJECT_0;
1301 if (GetExitCodeProcess(w32_child_handles[i], &exitcode) ) {
1302 *status = (int)((exitcode & 0xff) << 8);
1303 retval = (int)w32_child_pids[i];
1304 remove_dead_process(i);
1310 errno = GetLastError();
1314 static UINT timerid = 0;
1316 static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
1318 KillTimer(NULL,timerid);
1323 DllExport unsigned int
1324 win32_alarm(unsigned int sec)
1327 * the 'obvious' implentation is SetTimer() with a callback
1328 * which does whatever receiving SIGALRM would do
1329 * we cannot use SIGALRM even via raise() as it is not
1330 * one of the supported codes in <signal.h>
1332 * Snag is unless something is looking at the message queue
1333 * nothing happens :-(
1337 timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
1339 croak("Cannot set timer");
1345 KillTimer(NULL,timerid);
1352 #if defined(HAVE_DES_FCRYPT) || defined(PERL_OBJECT)
1353 #ifdef HAVE_DES_FCRYPT
1354 extern char * des_fcrypt(const char *txt, const char *salt, char *cbuf);
1358 win32_crypt(const char *txt, const char *salt)
1360 #ifdef HAVE_DES_FCRYPT
1362 return des_fcrypt(txt, salt, crypt_buffer);
1364 die("The crypt() function is unimplemented due to excessive paranoia.");
1370 #ifdef USE_FIXED_OSFHANDLE
1372 EXTERN_C int __cdecl _alloc_osfhnd(void);
1373 EXTERN_C int __cdecl _set_osfhnd(int fh, long value);
1374 EXTERN_C void __cdecl _lock_fhandle(int);
1375 EXTERN_C void __cdecl _unlock_fhandle(int);
1376 EXTERN_C void __cdecl _unlock(int);
1378 #if (_MSC_VER >= 1000)
1380 long osfhnd; /* underlying OS file HANDLE */
1381 char osfile; /* attributes of file (e.g., open in text mode?) */
1382 char pipech; /* one char buffer for handles opened on pipes */
1383 #if defined (_MT) && !defined (DLL_FOR_WIN32S)
1385 CRITICAL_SECTION lock;
1386 #endif /* defined (_MT) && !defined (DLL_FOR_WIN32S) */
1389 EXTERN_C ioinfo * __pioinfo[];
1391 #define IOINFO_L2E 5
1392 #define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
1393 #define _pioinfo(i) (__pioinfo[i >> IOINFO_L2E] + (i & (IOINFO_ARRAY_ELTS - 1)))
1394 #define _osfile(i) (_pioinfo(i)->osfile)
1396 #else /* (_MSC_VER >= 1000) */
1397 extern char _osfile[];
1398 #endif /* (_MSC_VER >= 1000) */
1400 #define FOPEN 0x01 /* file handle open */
1401 #define FAPPEND 0x20 /* file handle opened O_APPEND */
1402 #define FDEV 0x40 /* file handle refers to device */
1403 #define FTEXT 0x80 /* file handle is in text mode */
1405 #define _STREAM_LOCKS 26 /* Table of stream locks */
1406 #define _LAST_STREAM_LOCK (_STREAM_LOCKS+_NSTREAM_-1) /* Last stream lock */
1407 #define _FH_LOCKS (_LAST_STREAM_LOCK+1) /* Table of fh locks */
1410 *int my_open_osfhandle(long osfhandle, int flags) - open C Runtime file handle
1413 * This function allocates a free C Runtime file handle and associates
1414 * it with the Win32 HANDLE specified by the first parameter. This is a
1415 * temperary fix for WIN95's brain damage GetFileType() error on socket
1416 * we just bypass that call for socket
1419 * long osfhandle - Win32 HANDLE to associate with C Runtime file handle.
1420 * int flags - flags to associate with C Runtime file handle.
1423 * returns index of entry in fh, if successful
1424 * return -1, if no free entry is found
1428 *******************************************************************************/
1431 my_open_osfhandle(long osfhandle, int flags)
1434 char fileflags; /* _osfile flags */
1436 /* copy relevant flags from second parameter */
1439 if (flags & O_APPEND)
1440 fileflags |= FAPPEND;
1445 /* attempt to allocate a C Runtime file handle */
1446 if ((fh = _alloc_osfhnd()) == -1) {
1447 errno = EMFILE; /* too many open files */
1448 _doserrno = 0L; /* not an OS error */
1449 return -1; /* return error to caller */
1452 /* the file is open. now, set the info in _osfhnd array */
1453 _set_osfhnd(fh, osfhandle);
1455 fileflags |= FOPEN; /* mark as open */
1457 #if (_MSC_VER >= 1000)
1458 _osfile(fh) = fileflags; /* set osfile entry */
1459 _unlock_fhandle(fh);
1461 _osfile[fh] = fileflags; /* set osfile entry */
1462 _unlock(fh+_FH_LOCKS); /* unlock handle */
1465 return fh; /* return handle */
1468 #define _open_osfhandle my_open_osfhandle
1469 #endif /* USE_FIXED_OSFHANDLE */
1471 /* simulate flock by locking a range on the file */
1473 #define LK_ERR(f,i) ((f) ? (i = 0) : (errno = GetLastError()))
1474 #define LK_LEN 0xffff0000
1477 win32_flock(int fd, int oper)
1484 croak("flock() unimplemented on this platform");
1487 fh = (HANDLE)_get_osfhandle(fd);
1488 memset(&o, 0, sizeof(o));
1491 case LOCK_SH: /* shared lock */
1492 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
1494 case LOCK_EX: /* exclusive lock */
1495 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
1497 case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
1498 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
1500 case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
1501 LK_ERR(LockFileEx(fh,
1502 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
1503 0, LK_LEN, 0, &o),i);
1505 case LOCK_UN: /* unlock lock */
1506 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, 0, &o),i);
1508 default: /* unknown */
1519 * redirected io subsystem for all XS modules
1532 return (&(_environ));
1535 /* the rest are the remapped stdio routines */
1555 win32_ferror(FILE *fp)
1557 return (ferror(fp));
1562 win32_feof(FILE *fp)
1568 * Since the errors returned by the socket error function
1569 * WSAGetLastError() are not known by the library routine strerror
1570 * we have to roll our own.
1574 win32_strerror(int e)
1576 #ifndef __BORLANDC__ /* Borland intolerance */
1577 extern int sys_nerr;
1581 if (e < 0 || e > sys_nerr) {
1586 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
1587 strerror_buffer, sizeof(strerror_buffer), NULL) == 0)
1588 strcpy(strerror_buffer, "Unknown Error");
1590 return strerror_buffer;
1596 win32_str_os_error(void *sv, DWORD dwErr)
1600 dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
1601 |FORMAT_MESSAGE_IGNORE_INSERTS
1602 |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
1603 dwErr, 0, (char *)&sMsg, 1, NULL);
1605 while (0 < dwLen && isspace(sMsg[--dwLen]))
1607 if ('.' != sMsg[dwLen])
1612 sMsg = (char*)LocalAlloc(0, 64/**sizeof(TCHAR)*/);
1613 dwLen = sprintf(sMsg,
1614 "Unknown error #0x%lX (lookup 0x%lX)",
1615 dwErr, GetLastError());
1617 sv_setpvn((SV*)sv, sMsg, dwLen);
1623 win32_fprintf(FILE *fp, const char *format, ...)
1626 va_start(marker, format); /* Initialize variable arguments. */
1628 return (vfprintf(fp, format, marker));
1632 win32_printf(const char *format, ...)
1635 va_start(marker, format); /* Initialize variable arguments. */
1637 return (vprintf(format, marker));
1641 win32_vfprintf(FILE *fp, const char *format, va_list args)
1643 return (vfprintf(fp, format, args));
1647 win32_vprintf(const char *format, va_list args)
1649 return (vprintf(format, args));
1653 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
1655 return fread(buf, size, count, fp);
1659 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
1661 return fwrite(buf, size, count, fp);
1665 win32_fopen(const char *filename, const char *mode)
1667 if (stricmp(filename, "/dev/null")==0)
1668 return fopen("NUL", mode);
1669 return fopen(filename, mode);
1672 #ifndef USE_SOCKETS_AS_HANDLES
1674 #define fdopen my_fdopen
1678 win32_fdopen( int handle, const char *mode)
1680 return fdopen(handle, (char *) mode);
1684 win32_freopen( const char *path, const char *mode, FILE *stream)
1686 if (stricmp(path, "/dev/null")==0)
1687 return freopen("NUL", mode, stream);
1688 return freopen(path, mode, stream);
1692 win32_fclose(FILE *pf)
1694 return my_fclose(pf); /* defined in win32sck.c */
1698 win32_fputs(const char *s,FILE *pf)
1700 return fputs(s, pf);
1704 win32_fputc(int c,FILE *pf)
1710 win32_ungetc(int c,FILE *pf)
1712 return ungetc(c,pf);
1716 win32_getc(FILE *pf)
1722 win32_fileno(FILE *pf)
1728 win32_clearerr(FILE *pf)
1735 win32_fflush(FILE *pf)
1741 win32_ftell(FILE *pf)
1747 win32_fseek(FILE *pf,long offset,int origin)
1749 return fseek(pf, offset, origin);
1753 win32_fgetpos(FILE *pf,fpos_t *p)
1755 return fgetpos(pf, p);
1759 win32_fsetpos(FILE *pf,const fpos_t *p)
1761 return fsetpos(pf, p);
1765 win32_rewind(FILE *pf)
1785 win32_fstat(int fd,struct stat *sbufptr)
1787 return fstat(fd,sbufptr);
1791 win32_pipe(int *pfd, unsigned int size, int mode)
1793 return _pipe(pfd, size, mode);
1797 * a popen() clone that respects PERL5SHELL
1801 win32_popen(const char *command, const char *mode)
1803 #ifdef USE_RTL_POPEN
1804 return _popen(command, mode);
1812 /* establish which ends read and write */
1813 if (strchr(mode,'w')) {
1814 stdfd = 0; /* stdin */
1818 else if (strchr(mode,'r')) {
1819 stdfd = 1; /* stdout */
1826 /* set the correct mode */
1827 if (strchr(mode,'b'))
1829 else if (strchr(mode,'t'))
1832 ourmode = _fmode & (O_TEXT | O_BINARY);
1834 /* the child doesn't inherit handles */
1835 ourmode |= O_NOINHERIT;
1837 if (win32_pipe( p, 512, ourmode) == -1)
1840 /* save current stdfd */
1841 if ((oldfd = win32_dup(stdfd)) == -1)
1844 /* make stdfd go to child end of pipe (implicitly closes stdfd) */
1845 /* stdfd will be inherited by the child */
1846 if (win32_dup2(p[child], stdfd) == -1)
1849 /* close the child end in parent */
1850 win32_close(p[child]);
1852 /* start the child */
1853 if ((childpid = do_spawn_nowait((char*)command)) == -1)
1856 /* revert stdfd to whatever it was before */
1857 if (win32_dup2(oldfd, stdfd) == -1)
1860 /* close saved handle */
1863 sv_setiv(*av_fetch(w32_fdpid, p[parent], TRUE), childpid);
1865 /* we have an fd, return a file stream */
1866 return (win32_fdopen(p[parent], (char *)mode));
1869 /* we don't need to check for errors here */
1873 win32_dup2(oldfd, stdfd);
1878 #endif /* USE_RTL_POPEN */
1886 win32_pclose(FILE *pf)
1888 #ifdef USE_RTL_POPEN
1892 int childpid, status;
1895 sv = *av_fetch(w32_fdpid, win32_fileno(pf), TRUE);
1897 childpid = SvIVX(sv);
1909 if (win32_waitpid(childpid, &status, 0) == -1)
1914 #endif /* USE_RTL_POPEN */
1918 win32_rename(const char *oname, const char *newname)
1920 /* XXX despite what the documentation says about MoveFileEx(),
1921 * it doesn't work under Windows95!
1924 if (!MoveFileEx(oname,newname,
1925 MOVEFILE_COPY_ALLOWED|MOVEFILE_REPLACE_EXISTING)) {
1926 DWORD err = GetLastError();
1928 case ERROR_BAD_NET_NAME:
1929 case ERROR_BAD_NETPATH:
1930 case ERROR_BAD_PATHNAME:
1931 case ERROR_FILE_NOT_FOUND:
1932 case ERROR_FILENAME_EXCED_RANGE:
1933 case ERROR_INVALID_DRIVE:
1934 case ERROR_NO_MORE_FILES:
1935 case ERROR_PATH_NOT_FOUND:
1948 char tmpname[MAX_PATH+1];
1949 char dname[MAX_PATH+1];
1950 char *endname = Nullch;
1952 DWORD from_attr, to_attr;
1954 /* if oname doesn't exist, do nothing */
1955 from_attr = GetFileAttributes(oname);
1956 if (from_attr == 0xFFFFFFFF) {
1961 /* if newname exists, rename it to a temporary name so that we
1962 * don't delete it in case oname happens to be the same file
1963 * (but perhaps accessed via a different path)
1965 to_attr = GetFileAttributes(newname);
1966 if (to_attr != 0xFFFFFFFF) {
1967 /* if newname is a directory, we fail
1968 * XXX could overcome this with yet more convoluted logic */
1969 if (to_attr & FILE_ATTRIBUTE_DIRECTORY) {
1973 tmplen = strlen(newname);
1974 strcpy(tmpname,newname);
1975 endname = tmpname+tmplen;
1976 for (; endname > tmpname ; --endname) {
1977 if (*endname == '/' || *endname == '\\') {
1982 if (endname > tmpname)
1983 endname = strcpy(dname,tmpname);
1987 /* get a temporary filename in same directory
1988 * XXX is this really the best we can do? */
1989 if (!GetTempFileName((LPCTSTR)endname, "plr", 0, tmpname)) {
1993 DeleteFile(tmpname);
1995 retval = rename(newname, tmpname);
2002 /* rename oname to newname */
2003 retval = rename(oname, newname);
2005 /* if we created a temporary file before ... */
2006 if (endname != Nullch) {
2007 /* ...and rename succeeded, delete temporary file/directory */
2009 DeleteFile(tmpname);
2010 /* else restore it to what it was */
2012 (void)rename(tmpname, newname);
2019 win32_setmode(int fd, int mode)
2021 return setmode(fd, mode);
2025 win32_lseek(int fd, long offset, int origin)
2027 return lseek(fd, offset, origin);
2037 win32_open(const char *path, int flag, ...)
2043 pmode = va_arg(ap, int);
2046 if (stricmp(path, "/dev/null")==0)
2047 return open("NUL", flag, pmode);
2048 return open(path,flag,pmode);
2070 win32_dup2(int fd1,int fd2)
2072 return dup2(fd1,fd2);
2076 win32_read(int fd, void *buf, unsigned int cnt)
2078 return read(fd, buf, cnt);
2082 win32_write(int fd, const void *buf, unsigned int cnt)
2084 return write(fd, buf, cnt);
2088 win32_mkdir(const char *dir, int mode)
2090 return mkdir(dir); /* just ignore mode */
2094 win32_rmdir(const char *dir)
2100 win32_chdir(const char *dir)
2106 create_command_line(const char* command, const char * const *args)
2109 char *cmd, *ptr, *arg;
2110 STRLEN len = strlen(command) + 1;
2112 for (index = 0; (ptr = (char*)args[index]) != NULL; ++index)
2113 len += strlen(ptr) + 1;
2115 New(1310, cmd, len, char);
2117 strcpy(ptr, command);
2119 for (index = 0; (arg = (char*)args[index]) != NULL; ++index) {
2129 qualified_path(const char *cmd)
2132 char *fullcmd, *curfullcmd;
2138 fullcmd = (char*)cmd;
2140 if (*fullcmd == '/' || *fullcmd == '\\')
2147 pathstr = win32_getenv("PATH");
2148 New(0, fullcmd, MAX_PATH+1, char);
2149 curfullcmd = fullcmd;
2154 /* start by appending the name to the current prefix */
2155 strcpy(curfullcmd, cmd);
2156 curfullcmd += cmdlen;
2158 /* if it doesn't end with '.', or has no extension, try adding
2159 * a trailing .exe first */
2160 if (cmd[cmdlen-1] != '.'
2161 && (cmdlen < 4 || cmd[cmdlen-4] != '.'))
2163 strcpy(curfullcmd, ".exe");
2164 res = GetFileAttributes(fullcmd);
2165 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
2170 /* that failed, try the bare name */
2171 res = GetFileAttributes(fullcmd);
2172 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
2175 /* quit if no other path exists, or if cmd already has path */
2176 if (!pathstr || !*pathstr || has_slash)
2179 /* skip leading semis */
2180 while (*pathstr == ';')
2183 /* build a new prefix from scratch */
2184 curfullcmd = fullcmd;
2185 while (*pathstr && *pathstr != ';') {
2186 if (*pathstr == '"') { /* foo;"baz;etc";bar */
2187 pathstr++; /* skip initial '"' */
2188 while (*pathstr && *pathstr != '"') {
2189 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
2190 *curfullcmd++ = *pathstr;
2194 pathstr++; /* skip trailing '"' */
2197 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
2198 *curfullcmd++ = *pathstr;
2203 pathstr++; /* skip trailing semi */
2204 if (curfullcmd > fullcmd /* append a dir separator */
2205 && curfullcmd[-1] != '/' && curfullcmd[-1] != '\\')
2207 *curfullcmd++ = '\\';
2215 /* XXX this needs to be made more compatible with the spawnvp()
2216 * provided by the various RTLs. In particular, searching for
2217 * *.{com,bat,cmd} files (as done by the RTLs) is unimplemented.
2218 * This doesn't significantly affect perl itself, because we
2219 * always invoke things using PERL5SHELL if a direct attempt to
2220 * spawn the executable fails.
2222 * XXX splitting and rejoining the commandline between do_aspawn()
2223 * and win32_spawnvp() could also be avoided.
2227 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
2229 #ifdef USE_RTL_SPAWNVP
2230 return spawnvp(mode, cmdname, (char * const *)argv);
2233 STARTUPINFO StartupInfo;
2234 PROCESS_INFORMATION ProcessInformation;
2237 char *cmd = create_command_line(cmdname, strcmp(cmdname, argv[0]) == 0
2239 char *fullcmd = Nullch;
2242 case P_NOWAIT: /* asynch + remember result */
2243 if (w32_num_children >= MAXIMUM_WAIT_OBJECTS) {
2249 case P_WAIT: /* synchronous execution */
2251 default: /* invalid mode */
2256 memset(&StartupInfo,0,sizeof(StartupInfo));
2257 StartupInfo.cb = sizeof(StartupInfo);
2258 StartupInfo.wShowWindow = SW_SHOWDEFAULT;
2261 if (!CreateProcess(cmdname, /* search PATH to find executable */
2262 cmd, /* executable, and its arguments */
2263 NULL, /* process attributes */
2264 NULL, /* thread attributes */
2265 TRUE, /* inherit handles */
2266 create, /* creation flags */
2267 NULL, /* inherit environment */
2268 NULL, /* inherit cwd */
2270 &ProcessInformation))
2272 /* initial NULL argument to CreateProcess() does a PATH
2273 * search, but it always first looks in the directory
2274 * where the current process was started, which behavior
2275 * is undesirable for backward compatibility. So we
2276 * jump through our own hoops by picking out the path
2277 * we really want it to use. */
2279 fullcmd = qualified_path(cmdname);
2290 if (mode == P_NOWAIT) {
2291 /* asynchronous spawn -- store handle, return PID */
2292 w32_child_handles[w32_num_children] = ProcessInformation.hProcess;
2293 ret = w32_child_pids[w32_num_children] = ProcessInformation.dwProcessId;
2297 WaitForSingleObject(ProcessInformation.hProcess, INFINITE);
2298 GetExitCodeProcess(ProcessInformation.hProcess, &ret);
2299 CloseHandle(ProcessInformation.hProcess);
2302 CloseHandle(ProcessInformation.hThread);
2311 win32_execv(const char *cmdname, const char *const *argv)
2313 return execv(cmdname, (char *const *)argv);
2317 win32_execvp(const char *cmdname, const char *const *argv)
2319 return execvp(cmdname, (char *const *)argv);
2323 win32_perror(const char *str)
2329 win32_setbuf(FILE *pf, char *buf)
2335 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
2337 return setvbuf(pf, buf, type, size);
2341 win32_flushall(void)
2347 win32_fcloseall(void)
2353 win32_fgets(char *s, int n, FILE *pf)
2355 return fgets(s, n, pf);
2365 win32_fgetc(FILE *pf)
2371 win32_putc(int c, FILE *pf)
2377 win32_puts(const char *s)
2389 win32_putchar(int c)
2396 #ifndef USE_PERL_SBRK
2398 static char *committed = NULL;
2399 static char *base = NULL;
2400 static char *reserved = NULL;
2401 static char *brk = NULL;
2402 static DWORD pagesize = 0;
2403 static DWORD allocsize = 0;
2411 GetSystemInfo(&info);
2412 /* Pretend page size is larger so we don't perpetually
2413 * call the OS to commit just one page ...
2415 pagesize = info.dwPageSize << 3;
2416 allocsize = info.dwAllocationGranularity;
2418 /* This scheme fails eventually if request for contiguous
2419 * block is denied so reserve big blocks - this is only
2420 * address space not memory ...
2422 if (brk+need >= reserved)
2424 DWORD size = 64*1024*1024;
2426 if (committed && reserved && committed < reserved)
2428 /* Commit last of previous chunk cannot span allocations */
2429 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
2431 committed = reserved;
2433 /* Reserve some (more) space
2434 * Note this is a little sneaky, 1st call passes NULL as reserved
2435 * so lets system choose where we start, subsequent calls pass
2436 * the old end address so ask for a contiguous block
2438 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
2441 reserved = addr+size;
2456 if (brk > committed)
2458 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
2459 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
2474 win32_malloc(size_t size)
2476 return malloc(size);
2480 win32_calloc(size_t numitems, size_t size)
2482 return calloc(numitems,size);
2486 win32_realloc(void *block, size_t size)
2488 return realloc(block,size);
2492 win32_free(void *block)
2499 win32_open_osfhandle(long handle, int flags)
2501 return _open_osfhandle(handle, flags);
2505 win32_get_osfhandle(int fd)
2507 return _get_osfhandle(fd);
2518 SV *sv = sv_newmortal();
2519 /* Make one call with zero size - return value is required size */
2520 DWORD len = GetCurrentDirectory((DWORD)0,NULL);
2521 SvUPGRADE(sv,SVt_PV);
2523 SvCUR(sv) = GetCurrentDirectory((DWORD) SvLEN(sv), SvPVX(sv));
2526 * then it worked, set PV valid,
2527 * else leave it 'undef'
2543 croak("usage: Win32::SetCurrentDirectory($cwd)");
2544 if (SetCurrentDirectory(SvPV_nolen(ST(0))))
2551 XS(w32_GetNextAvailDrive)
2555 char root[] = "_:\\";
2560 if (GetDriveType(root) == 1) {
2569 XS(w32_GetLastError)
2573 XSRETURN_IV(GetLastError());
2577 XS(w32_SetLastError)
2581 croak("usage: Win32::SetLastError($error)");
2582 SetLastError(SvIV(ST(0)));
2590 char *name = getlogin_buffer;
2591 DWORD size = sizeof(getlogin_buffer);
2593 if (GetUserName(name,&size)) {
2594 /* size includes NULL */
2595 ST(0) = sv_2mortal(newSVpvn(name,size-1));
2605 char name[MAX_COMPUTERNAME_LENGTH+1];
2606 DWORD size = sizeof(name);
2608 if (GetComputerName(name,&size)) {
2609 /* size does NOT include NULL :-( */
2610 ST(0) = sv_2mortal(newSVpvn(name,size));
2621 #ifndef HAS_NETWKSTAGETINFO
2622 /* mingw32 (and Win95) don't have NetWksta*(), so do it the old way */
2624 DWORD size = sizeof(name);
2626 if (GetUserName(name,&size)) {
2628 DWORD sidlen = sizeof(sid);
2630 DWORD dnamelen = sizeof(dname);
2632 if (LookupAccountName(NULL, name, (PSID)&sid, &sidlen,
2633 dname, &dnamelen, &snu)) {
2634 XSRETURN_PV(dname); /* all that for this */
2638 /* this way is more reliable, in case user has a local account.
2639 * XXX need dynamic binding of netapi32.dll symbols or this will fail on
2640 * Win95. Probably makes more sense to move it into libwin32. */
2642 DWORD dnamelen = sizeof(dname);
2643 PWKSTA_INFO_100 pwi;
2645 if (NERR_Success == NetWkstaGetInfo(NULL, 100, (LPBYTE*)&pwi)) {
2646 if (pwi->wki100_langroup && *(pwi->wki100_langroup)) {
2647 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_langroup,
2648 -1, (LPSTR)dname, dnamelen, NULL, NULL);
2651 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_computername,
2652 -1, (LPSTR)dname, dnamelen, NULL, NULL);
2654 NetApiBufferFree(pwi);
2666 DWORD flags, filecomplen;
2667 if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
2668 &flags, fsname, sizeof(fsname))) {
2669 if (GIMME_V == G_ARRAY) {
2670 XPUSHs(sv_2mortal(newSVpvn(fsname,strlen(fsname))));
2671 XPUSHs(sv_2mortal(newSViv(flags)));
2672 XPUSHs(sv_2mortal(newSViv(filecomplen)));
2677 XSRETURN_PV(fsname);
2683 XS(w32_GetOSVersion)
2686 OSVERSIONINFO osver;
2688 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
2689 if (GetVersionEx(&osver)) {
2690 XPUSHs(newSVpvn(osver.szCSDVersion, strlen(osver.szCSDVersion)));
2691 XPUSHs(newSViv(osver.dwMajorVersion));
2692 XPUSHs(newSViv(osver.dwMinorVersion));
2693 XPUSHs(newSViv(osver.dwBuildNumber));
2694 XPUSHs(newSViv(osver.dwPlatformId));
2706 XSRETURN_IV(IsWinNT());
2714 XSRETURN_IV(IsWin95());
2718 XS(w32_FormatMessage)
2725 croak("usage: Win32::FormatMessage($errno)");
2727 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
2728 &source, SvIV(ST(0)), 0,
2729 msgbuf, sizeof(msgbuf)-1, NULL))
2730 XSRETURN_PV(msgbuf);
2740 PROCESS_INFORMATION stProcInfo;
2741 STARTUPINFO stStartInfo;
2742 BOOL bSuccess = FALSE;
2745 croak("usage: Win32::Spawn($cmdName, $args, $PID)");
2747 cmd = SvPV_nolen(ST(0));
2748 args = SvPV_nolen(ST(1));
2750 memset(&stStartInfo, 0, sizeof(stStartInfo)); /* Clear the block */
2751 stStartInfo.cb = sizeof(stStartInfo); /* Set the structure size */
2752 stStartInfo.dwFlags = STARTF_USESHOWWINDOW; /* Enable wShowWindow control */
2753 stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE; /* Start min (normal) */
2756 cmd, /* Image path */
2757 args, /* Arguments for command line */
2758 NULL, /* Default process security */
2759 NULL, /* Default thread security */
2760 FALSE, /* Must be TRUE to use std handles */
2761 NORMAL_PRIORITY_CLASS, /* No special scheduling */
2762 NULL, /* Inherit our environment block */
2763 NULL, /* Inherit our currrent directory */
2764 &stStartInfo, /* -> Startup info */
2765 &stProcInfo)) /* <- Process info (if OK) */
2767 CloseHandle(stProcInfo.hThread);/* library source code does this. */
2768 sv_setiv(ST(2), stProcInfo.dwProcessId);
2771 XSRETURN_IV(bSuccess);
2775 XS(w32_GetTickCount)
2779 DWORD msec = GetTickCount();
2786 XS(w32_GetShortPathName)
2793 croak("usage: Win32::GetShortPathName($longPathName)");
2795 shortpath = sv_mortalcopy(ST(0));
2796 SvUPGRADE(shortpath, SVt_PV);
2797 /* src == target is allowed */
2799 len = GetShortPathName(SvPVX(shortpath),
2802 } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
2804 SvCUR_set(shortpath,len);
2812 XS(w32_GetFullPathName)
2821 croak("usage: Win32::GetFullPathName($filename)");
2824 fullpath = sv_mortalcopy(filename);
2825 SvUPGRADE(fullpath, SVt_PV);
2827 len = GetFullPathName(SvPVX(filename),
2831 } while (len >= SvLEN(fullpath) && sv_grow(fullpath,len+1));
2833 if (GIMME_V == G_ARRAY) {
2835 XST_mPV(1,filepart);
2836 len = filepart - SvPVX(fullpath);
2839 SvCUR_set(fullpath,len);
2851 croak("usage: Win32::Sleep($milliseconds)");
2857 Perl_init_os_extras()
2859 char *file = __FILE__;
2862 w32_perlshell_tokens = Nullch;
2863 w32_perlshell_items = -1;
2864 w32_fdpid = newAV(); /* XXX needs to be in Perl_win32_init()? */
2865 New(1313, w32_children, 1, child_tab);
2866 w32_num_children = 0;
2868 /* these names are Activeware compatible */
2869 newXS("Win32::GetCwd", w32_GetCwd, file);
2870 newXS("Win32::SetCwd", w32_SetCwd, file);
2871 newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
2872 newXS("Win32::GetLastError", w32_GetLastError, file);
2873 newXS("Win32::SetLastError", w32_SetLastError, file);
2874 newXS("Win32::LoginName", w32_LoginName, file);
2875 newXS("Win32::NodeName", w32_NodeName, file);
2876 newXS("Win32::DomainName", w32_DomainName, file);
2877 newXS("Win32::FsType", w32_FsType, file);
2878 newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
2879 newXS("Win32::IsWinNT", w32_IsWinNT, file);
2880 newXS("Win32::IsWin95", w32_IsWin95, file);
2881 newXS("Win32::FormatMessage", w32_FormatMessage, file);
2882 newXS("Win32::Spawn", w32_Spawn, file);
2883 newXS("Win32::GetTickCount", w32_GetTickCount, file);
2884 newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
2885 newXS("Win32::GetFullPathName", w32_GetFullPathName, file);
2886 newXS("Win32::Sleep", w32_Sleep, file);
2888 /* XXX Bloat Alert! The following Activeware preloads really
2889 * ought to be part of Win32::Sys::*, so they're not included
2892 /* LookupAccountName
2894 * InitiateSystemShutdown
2895 * AbortSystemShutdown
2896 * ExpandEnvrironmentStrings
2901 Perl_win32_init(int *argcp, char ***argvp)
2903 /* Disable floating point errors, Perl will trap the ones we
2904 * care about. VC++ RTL defaults to switching these off
2905 * already, but the Borland RTL doesn't. Since we don't
2906 * want to be at the vendor's whim on the default, we set
2907 * it explicitly here.
2909 #if !defined(_ALPHA_) && !defined(__GNUC__)
2910 _control87(MCW_EM, MCW_EM);
2915 #ifdef USE_BINMODE_SCRIPTS
2918 win32_strip_return(SV *sv)
2920 char *s = SvPVX(sv);
2921 char *e = s+SvCUR(sv);
2925 if (*s == '\r' && s[1] == '\n')
2935 SvCUR_set(sv,d-SvPVX(sv));