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 PERL_FLUSHALL_FOR_CHILD;
381 return win32_popen(cmd, mode);
385 my_pclose(PerlIO *fp)
387 return win32_pclose(fp);
394 static OSVERSIONINFO osver;
396 if (osver.dwPlatformId != w32_platform) {
397 memset(&osver, 0, sizeof(OSVERSIONINFO));
398 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
399 GetVersionEx(&osver);
400 w32_platform = osver.dwPlatformId;
402 return (w32_platform);
405 /* Tokenize a string. Words are null-separated, and the list
406 * ends with a doubled null. Any character (except null and
407 * including backslash) may be escaped by preceding it with a
408 * backslash (the backslash will be stripped).
409 * Returns number of words in result buffer.
412 tokenize(char *str, char **dest, char ***destv)
414 char *retstart = Nullch;
415 char **retvstart = 0;
418 int slen = strlen(str);
420 register char **retv;
421 New(1307, ret, slen+2, char);
422 New(1308, retv, (slen+3)/2, char*);
430 if (*ret == '\\' && *str)
432 else if (*ret == ' ') {
448 retvstart[items] = Nullch;
460 if (!w32_perlshell_tokens) {
461 /* we don't use COMSPEC here for two reasons:
462 * 1. the same reason perl on UNIX doesn't use SHELL--rampant and
463 * uncontrolled unportability of the ensuing scripts.
464 * 2. PERL5SHELL could be set to a shell that may not be fit for
465 * interactive use (which is what most programs look in COMSPEC
468 char* defaultshell = (IsWinNT() ? "cmd.exe /x/c" : "command.com /c");
469 char *usershell = getenv("PERL5SHELL");
470 w32_perlshell_items = tokenize(usershell ? usershell : defaultshell,
471 &w32_perlshell_tokens,
477 do_aspawn(void *vreally, void **vmark, void **vsp)
479 SV *really = (SV*)vreally;
480 SV **mark = (SV**)vmark;
492 New(1306, argv, (sp - mark) + w32_perlshell_items + 2, char*);
494 if (SvNIOKp(*(mark+1)) && !SvPOKp(*(mark+1))) {
499 while (++mark <= sp) {
500 if (*mark && (str = SvPV_nolen(*mark)))
507 status = win32_spawnvp(flag,
508 (const char*)(really ? SvPV_nolen(really) : argv[0]),
509 (const char* const*)argv);
511 if (status < 0 && (errno == ENOEXEC || errno == ENOENT)) {
512 /* possible shell-builtin, invoke with shell */
514 sh_items = w32_perlshell_items;
516 argv[index+sh_items] = argv[index];
517 while (--sh_items >= 0)
518 argv[sh_items] = w32_perlshell_vec[sh_items];
520 status = win32_spawnvp(flag,
521 (const char*)(really ? SvPV_nolen(really) : argv[0]),
522 (const char* const*)argv);
525 if (flag != P_NOWAIT) {
528 warn("Can't spawn \"%s\": %s", argv[0], strerror(errno));
533 PL_statusvalue = status;
540 do_spawn2(char *cmd, int exectype)
546 BOOL needToTry = TRUE;
549 /* Save an extra exec if possible. See if there are shell
550 * metacharacters in it */
551 if (!has_shell_metachars(cmd)) {
552 New(1301,argv, strlen(cmd) / 2 + 2, char*);
553 New(1302,cmd2, strlen(cmd) + 1, char);
556 for (s = cmd2; *s;) {
557 while (*s && isspace(*s))
561 while (*s && !isspace(*s))
570 status = win32_spawnvp(P_WAIT, argv[0],
571 (const char* const*)argv);
573 case EXECF_SPAWN_NOWAIT:
574 status = win32_spawnvp(P_NOWAIT, argv[0],
575 (const char* const*)argv);
578 status = win32_execvp(argv[0], (const char* const*)argv);
581 if (status != -1 || errno == 0)
591 New(1306, argv, w32_perlshell_items + 2, char*);
592 while (++i < w32_perlshell_items)
593 argv[i] = w32_perlshell_vec[i];
598 status = win32_spawnvp(P_WAIT, argv[0],
599 (const char* const*)argv);
601 case EXECF_SPAWN_NOWAIT:
602 status = win32_spawnvp(P_NOWAIT, argv[0],
603 (const char* const*)argv);
606 status = win32_execvp(argv[0], (const char* const*)argv);
612 if (exectype != EXECF_SPAWN_NOWAIT) {
615 warn("Can't %s \"%s\": %s",
616 (exectype == EXECF_EXEC ? "exec" : "spawn"),
617 cmd, strerror(errno));
622 PL_statusvalue = status;
630 return do_spawn2(cmd, EXECF_SPAWN);
634 do_spawn_nowait(char *cmd)
636 return do_spawn2(cmd, EXECF_SPAWN_NOWAIT);
642 do_spawn2(cmd, EXECF_EXEC);
646 /* The idea here is to read all the directory names into a string table
647 * (separated by nulls) and when one of the other dir functions is called
648 * return the pointer to the current file name.
651 win32_opendir(char *filename)
656 char scanname[MAX_PATH+3];
658 WIN32_FIND_DATA FindData;
661 len = strlen(filename);
665 /* check to see if filename is a directory */
666 if (win32_stat(filename, &sbuf) < 0 || !S_ISDIR(sbuf.st_mode))
669 /* Get us a DIR structure */
670 Newz(1303, p, 1, DIR);
674 /* Create the search pattern */
675 strcpy(scanname, filename);
676 if (scanname[len-1] != '/' && scanname[len-1] != '\\')
677 scanname[len++] = '/';
678 scanname[len++] = '*';
679 scanname[len] = '\0';
681 /* do the FindFirstFile call */
682 fh = FindFirstFile(scanname, &FindData);
683 if (fh == INVALID_HANDLE_VALUE) {
684 /* FindFirstFile() fails on empty drives! */
685 if (GetLastError() == ERROR_FILE_NOT_FOUND)
691 /* now allocate the first part of the string table for
692 * the filenames that we find.
694 idx = strlen(FindData.cFileName)+1;
695 New(1304, p->start, idx, char);
696 if (p->start == NULL)
697 croak("opendir: malloc failed!\n");
698 strcpy(p->start, FindData.cFileName);
701 /* loop finding all the files that match the wildcard
702 * (which should be all of them in this directory!).
703 * the variable idx should point one past the null terminator
704 * of the previous string found.
706 while (FindNextFile(fh, &FindData)) {
707 len = strlen(FindData.cFileName);
708 /* bump the string table size by enough for the
709 * new name and it's null terminator
711 Renew(p->start, idx+len+1, char);
712 if (p->start == NULL)
713 croak("opendir: malloc failed!\n");
714 strcpy(&p->start[idx], FindData.cFileName);
725 /* Readdir just returns the current string pointer and bumps the
726 * string pointer to the nDllExport entry.
729 win32_readdir(DIR *dirp)
732 static int dummy = 0;
735 /* first set up the structure to return */
736 len = strlen(dirp->curr);
737 strcpy(dirp->dirstr.d_name, dirp->curr);
738 dirp->dirstr.d_namlen = len;
741 dirp->dirstr.d_ino = dummy++;
743 /* Now set up for the nDllExport call to readdir */
744 dirp->curr += len + 1;
745 if (dirp->curr >= (dirp->start + dirp->size)) {
749 return &(dirp->dirstr);
755 /* Telldir returns the current string pointer position */
757 win32_telldir(DIR *dirp)
759 return (long) dirp->curr;
763 /* Seekdir moves the string pointer to a previously saved position
767 win32_seekdir(DIR *dirp, long loc)
769 dirp->curr = (char *)loc;
772 /* Rewinddir resets the string pointer to the start */
774 win32_rewinddir(DIR *dirp)
776 dirp->curr = dirp->start;
779 /* free the memory allocated by opendir */
781 win32_closedir(DIR *dirp)
783 Safefree(dirp->start);
796 * Just pretend that everyone is a superuser. NT will let us know if
797 * we don\'t really have permission to do something.
800 #define ROOT_UID ((uid_t)0)
801 #define ROOT_GID ((gid_t)0)
830 return (auid == ROOT_UID ? 0 : -1);
836 return (agid == ROOT_GID ? 0 : -1);
843 char *buf = getlogin_buffer;
844 DWORD size = sizeof(getlogin_buffer);
845 if (GetUserName(buf,&size))
851 chown(const char *path, uid_t owner, gid_t group)
861 for (child = 0 ; child < w32_num_children ; ++child) {
862 if (w32_child_pids[child] == pid)
869 remove_dead_process(long child)
872 CloseHandle(w32_child_handles[child]);
873 Copy(&w32_child_handles[child+1], &w32_child_handles[child],
874 (w32_num_children-child-1), HANDLE);
875 Copy(&w32_child_pids[child+1], &w32_child_pids[child],
876 (w32_num_children-child-1), DWORD);
882 win32_kill(int pid, int sig)
885 hProcess = OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid);
886 if (hProcess && TerminateProcess(hProcess, sig))
887 CloseHandle(hProcess);
899 DllExport unsigned int
900 win32_sleep(unsigned int t)
907 win32_stat(const char *path, struct stat *buffer)
910 int l = strlen(path);
914 switch(path[l - 1]) {
915 /* FindFirstFile() and stat() are buggy with a trailing
916 * backslash, so change it to a forward slash :-( */
918 strncpy(t, path, l-1);
923 /* FindFirstFile() is buggy with "x:", so add a slash :-( */
925 if (l == 2 && isALPHA(path[0])) {
926 t[0] = path[0]; t[1] = ':'; t[2] = '/'; t[3] = '\0';
933 res = stat(path,buffer);
935 /* CRT is buggy on sharenames, so make sure it really isn't.
936 * XXX using GetFileAttributesEx() will enable us to set
937 * buffer->st_*time (but note that's not available on the
938 * Windows of 1995) */
939 DWORD r = GetFileAttributes(path);
940 if (r != 0xffffffff && (r & FILE_ATTRIBUTE_DIRECTORY)) {
941 /* buffer may still contain old garbage since stat() failed */
942 Zero(buffer, 1, struct stat);
943 buffer->st_mode = S_IFDIR | S_IREAD;
945 if (!(r & FILE_ATTRIBUTE_READONLY))
946 buffer->st_mode |= S_IWRITE | S_IEXEC;
951 if (l == 3 && isALPHA(path[0]) && path[1] == ':'
952 && (path[2] == '\\' || path[2] == '/'))
954 /* The drive can be inaccessible, some _stat()s are buggy */
955 if (!GetVolumeInformation(path,NULL,0,NULL,NULL,NULL,NULL,0)) {
961 if (S_ISDIR(buffer->st_mode))
962 buffer->st_mode |= S_IWRITE | S_IEXEC;
963 else if (S_ISREG(buffer->st_mode)) {
964 if (l >= 4 && path[l-4] == '.') {
965 const char *e = path + l - 3;
966 if (strnicmp(e,"exe",3)
967 && strnicmp(e,"bat",3)
968 && strnicmp(e,"com",3)
969 && (IsWin95() || strnicmp(e,"cmd",3)))
970 buffer->st_mode &= ~S_IEXEC;
972 buffer->st_mode |= S_IEXEC;
975 buffer->st_mode &= ~S_IEXEC;
982 #ifndef USE_WIN32_RTL_ENV
985 win32_getenv(const char *name)
987 static char *curitem = Nullch; /* XXX threadead */
988 static DWORD curlen = 0; /* XXX threadead */
992 New(1305,curitem,curlen,char);
995 needlen = GetEnvironmentVariable(name,curitem,curlen);
997 while (needlen > curlen) {
998 Renew(curitem,needlen,char);
1000 needlen = GetEnvironmentVariable(name,curitem,curlen);
1004 /* allow any environment variables that begin with 'PERL'
1005 to be stored in the registry */
1009 if (strncmp(name, "PERL", 4) == 0) {
1015 curitem = GetRegStr(name, &curitem, &curlen);
1018 if (curitem && *curitem == '\0')
1025 win32_putenv(const char *name)
1031 New(1309,curitem,strlen(name)+1,char);
1032 strcpy(curitem, name);
1033 val = strchr(curitem, '=');
1035 /* The sane way to deal with the environment.
1036 * Has these advantages over putenv() & co.:
1037 * * enables us to store a truly empty value in the
1038 * environment (like in UNIX).
1039 * * we don't have to deal with RTL globals, bugs and leaks.
1041 * Why you may want to enable USE_WIN32_RTL_ENV:
1042 * * environ[] and RTL functions will not reflect changes,
1043 * which might be an issue if extensions want to access
1044 * the env. via RTL. This cuts both ways, since RTL will
1045 * not see changes made by extensions that call the Win32
1046 * functions directly, either.
1050 if(SetEnvironmentVariable(curitem, *val ? val : NULL))
1061 filetime_to_clock(PFILETIME ft)
1063 __int64 qw = ft->dwHighDateTime;
1065 qw |= ft->dwLowDateTime;
1066 qw /= 10000; /* File time ticks at 0.1uS, clock at 1mS */
1071 win32_times(struct tms *timebuf)
1076 if (GetProcessTimes(GetCurrentProcess(), &dummy, &dummy,
1078 timebuf->tms_utime = filetime_to_clock(&user);
1079 timebuf->tms_stime = filetime_to_clock(&kernel);
1080 timebuf->tms_cutime = 0;
1081 timebuf->tms_cstime = 0;
1084 /* That failed - e.g. Win95 fallback to clock() */
1085 clock_t t = clock();
1086 timebuf->tms_utime = t;
1087 timebuf->tms_stime = 0;
1088 timebuf->tms_cutime = 0;
1089 timebuf->tms_cstime = 0;
1094 /* fix utime() so it works on directories in NT
1095 * thanks to Jan Dubois <jan.dubois@ibm.net>
1098 filetime_from_time(PFILETIME pFileTime, time_t Time)
1100 struct tm *pTM = gmtime(&Time);
1101 SYSTEMTIME SystemTime;
1106 SystemTime.wYear = pTM->tm_year + 1900;
1107 SystemTime.wMonth = pTM->tm_mon + 1;
1108 SystemTime.wDay = pTM->tm_mday;
1109 SystemTime.wHour = pTM->tm_hour;
1110 SystemTime.wMinute = pTM->tm_min;
1111 SystemTime.wSecond = pTM->tm_sec;
1112 SystemTime.wMilliseconds = 0;
1114 return SystemTimeToFileTime(&SystemTime, pFileTime);
1118 win32_utime(const char *filename, struct utimbuf *times)
1124 struct utimbuf TimeBuffer;
1126 int rc = utime(filename,times);
1127 /* EACCES: path specifies directory or readonly file */
1128 if (rc == 0 || errno != EACCES /* || !IsWinNT() */)
1131 if (times == NULL) {
1132 times = &TimeBuffer;
1133 time(×->actime);
1134 times->modtime = times->actime;
1137 /* This will (and should) still fail on readonly files */
1138 handle = CreateFile(filename, GENERIC_READ | GENERIC_WRITE,
1139 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1140 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1141 if (handle == INVALID_HANDLE_VALUE)
1144 if (GetFileTime(handle, &ftCreate, &ftAccess, &ftWrite) &&
1145 filetime_from_time(&ftAccess, times->actime) &&
1146 filetime_from_time(&ftWrite, times->modtime) &&
1147 SetFileTime(handle, &ftCreate, &ftAccess, &ftWrite))
1152 CloseHandle(handle);
1157 win32_uname(struct utsname *name)
1159 struct hostent *hep;
1160 STRLEN nodemax = sizeof(name->nodename)-1;
1161 OSVERSIONINFO osver;
1163 memset(&osver, 0, sizeof(OSVERSIONINFO));
1164 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1165 if (GetVersionEx(&osver)) {
1167 switch (osver.dwPlatformId) {
1168 case VER_PLATFORM_WIN32_WINDOWS:
1169 strcpy(name->sysname, "Windows");
1171 case VER_PLATFORM_WIN32_NT:
1172 strcpy(name->sysname, "Windows NT");
1174 case VER_PLATFORM_WIN32s:
1175 strcpy(name->sysname, "Win32s");
1178 strcpy(name->sysname, "Win32 Unknown");
1183 sprintf(name->release, "%d.%d",
1184 osver.dwMajorVersion, osver.dwMinorVersion);
1187 sprintf(name->version, "Build %d",
1188 osver.dwPlatformId == VER_PLATFORM_WIN32_NT
1189 ? osver.dwBuildNumber : (osver.dwBuildNumber & 0xffff));
1190 if (osver.szCSDVersion[0]) {
1191 char *buf = name->version + strlen(name->version);
1192 sprintf(buf, " (%s)", osver.szCSDVersion);
1196 *name->sysname = '\0';
1197 *name->version = '\0';
1198 *name->release = '\0';
1202 hep = win32_gethostbyname("localhost");
1204 STRLEN len = strlen(hep->h_name);
1205 if (len <= nodemax) {
1206 strcpy(name->nodename, hep->h_name);
1209 strncpy(name->nodename, hep->h_name, nodemax);
1210 name->nodename[nodemax] = '\0';
1215 if (!GetComputerName(name->nodename, &sz))
1216 *name->nodename = '\0';
1219 /* machine (architecture) */
1223 GetSystemInfo(&info);
1224 switch (info.wProcessorArchitecture) {
1225 case PROCESSOR_ARCHITECTURE_INTEL:
1226 arch = "x86"; break;
1227 case PROCESSOR_ARCHITECTURE_MIPS:
1228 arch = "mips"; break;
1229 case PROCESSOR_ARCHITECTURE_ALPHA:
1230 arch = "alpha"; break;
1231 case PROCESSOR_ARCHITECTURE_PPC:
1232 arch = "ppc"; break;
1234 arch = "unknown"; break;
1236 strcpy(name->machine, arch);
1242 win32_waitpid(int pid, int *status, int flags)
1246 return win32_wait(status);
1248 long child = find_pid(pid);
1250 HANDLE hProcess = w32_child_handles[child];
1251 DWORD waitcode = WaitForSingleObject(hProcess, INFINITE);
1252 if (waitcode != WAIT_FAILED) {
1253 if (GetExitCodeProcess(hProcess, &waitcode)) {
1254 *status = (int)((waitcode & 0xff) << 8);
1255 retval = (int)w32_child_pids[child];
1256 remove_dead_process(child);
1264 retval = cwait(status, pid, WAIT_CHILD);
1265 /* cwait() returns "correctly" on Borland */
1266 #ifndef __BORLANDC__
1272 return retval >= 0 ? pid : retval;
1276 win32_wait(int *status)
1278 /* XXX this wait emulation only knows about processes
1279 * spawned via win32_spawnvp(P_NOWAIT, ...).
1282 DWORD exitcode, waitcode;
1284 if (!w32_num_children) {
1289 /* if a child exists, wait for it to die */
1290 waitcode = WaitForMultipleObjects(w32_num_children,
1294 if (waitcode != WAIT_FAILED) {
1295 if (waitcode >= WAIT_ABANDONED_0
1296 && waitcode < WAIT_ABANDONED_0 + w32_num_children)
1297 i = waitcode - WAIT_ABANDONED_0;
1299 i = waitcode - WAIT_OBJECT_0;
1300 if (GetExitCodeProcess(w32_child_handles[i], &exitcode) ) {
1301 *status = (int)((exitcode & 0xff) << 8);
1302 retval = (int)w32_child_pids[i];
1303 remove_dead_process(i);
1309 errno = GetLastError();
1313 static UINT timerid = 0;
1315 static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
1317 KillTimer(NULL,timerid);
1322 DllExport unsigned int
1323 win32_alarm(unsigned int sec)
1326 * the 'obvious' implentation is SetTimer() with a callback
1327 * which does whatever receiving SIGALRM would do
1328 * we cannot use SIGALRM even via raise() as it is not
1329 * one of the supported codes in <signal.h>
1331 * Snag is unless something is looking at the message queue
1332 * nothing happens :-(
1336 timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
1338 croak("Cannot set timer");
1344 KillTimer(NULL,timerid);
1351 #if defined(HAVE_DES_FCRYPT) || defined(PERL_OBJECT)
1352 #ifdef HAVE_DES_FCRYPT
1353 extern char * des_fcrypt(const char *txt, const char *salt, char *cbuf);
1357 win32_crypt(const char *txt, const char *salt)
1359 #ifdef HAVE_DES_FCRYPT
1361 return des_fcrypt(txt, salt, crypt_buffer);
1363 die("The crypt() function is unimplemented due to excessive paranoia.");
1369 #ifdef USE_FIXED_OSFHANDLE
1371 EXTERN_C int __cdecl _alloc_osfhnd(void);
1372 EXTERN_C int __cdecl _set_osfhnd(int fh, long value);
1373 EXTERN_C void __cdecl _lock_fhandle(int);
1374 EXTERN_C void __cdecl _unlock_fhandle(int);
1375 EXTERN_C void __cdecl _unlock(int);
1377 #if (_MSC_VER >= 1000)
1379 long osfhnd; /* underlying OS file HANDLE */
1380 char osfile; /* attributes of file (e.g., open in text mode?) */
1381 char pipech; /* one char buffer for handles opened on pipes */
1382 #if defined (_MT) && !defined (DLL_FOR_WIN32S)
1384 CRITICAL_SECTION lock;
1385 #endif /* defined (_MT) && !defined (DLL_FOR_WIN32S) */
1388 EXTERN_C ioinfo * __pioinfo[];
1390 #define IOINFO_L2E 5
1391 #define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
1392 #define _pioinfo(i) (__pioinfo[i >> IOINFO_L2E] + (i & (IOINFO_ARRAY_ELTS - 1)))
1393 #define _osfile(i) (_pioinfo(i)->osfile)
1395 #else /* (_MSC_VER >= 1000) */
1396 extern char _osfile[];
1397 #endif /* (_MSC_VER >= 1000) */
1399 #define FOPEN 0x01 /* file handle open */
1400 #define FAPPEND 0x20 /* file handle opened O_APPEND */
1401 #define FDEV 0x40 /* file handle refers to device */
1402 #define FTEXT 0x80 /* file handle is in text mode */
1404 #define _STREAM_LOCKS 26 /* Table of stream locks */
1405 #define _LAST_STREAM_LOCK (_STREAM_LOCKS+_NSTREAM_-1) /* Last stream lock */
1406 #define _FH_LOCKS (_LAST_STREAM_LOCK+1) /* Table of fh locks */
1409 *int my_open_osfhandle(long osfhandle, int flags) - open C Runtime file handle
1412 * This function allocates a free C Runtime file handle and associates
1413 * it with the Win32 HANDLE specified by the first parameter. This is a
1414 * temperary fix for WIN95's brain damage GetFileType() error on socket
1415 * we just bypass that call for socket
1418 * long osfhandle - Win32 HANDLE to associate with C Runtime file handle.
1419 * int flags - flags to associate with C Runtime file handle.
1422 * returns index of entry in fh, if successful
1423 * return -1, if no free entry is found
1427 *******************************************************************************/
1430 my_open_osfhandle(long osfhandle, int flags)
1433 char fileflags; /* _osfile flags */
1435 /* copy relevant flags from second parameter */
1438 if (flags & O_APPEND)
1439 fileflags |= FAPPEND;
1444 /* attempt to allocate a C Runtime file handle */
1445 if ((fh = _alloc_osfhnd()) == -1) {
1446 errno = EMFILE; /* too many open files */
1447 _doserrno = 0L; /* not an OS error */
1448 return -1; /* return error to caller */
1451 /* the file is open. now, set the info in _osfhnd array */
1452 _set_osfhnd(fh, osfhandle);
1454 fileflags |= FOPEN; /* mark as open */
1456 #if (_MSC_VER >= 1000)
1457 _osfile(fh) = fileflags; /* set osfile entry */
1458 _unlock_fhandle(fh);
1460 _osfile[fh] = fileflags; /* set osfile entry */
1461 _unlock(fh+_FH_LOCKS); /* unlock handle */
1464 return fh; /* return handle */
1467 #define _open_osfhandle my_open_osfhandle
1468 #endif /* USE_FIXED_OSFHANDLE */
1470 /* simulate flock by locking a range on the file */
1472 #define LK_ERR(f,i) ((f) ? (i = 0) : (errno = GetLastError()))
1473 #define LK_LEN 0xffff0000
1476 win32_flock(int fd, int oper)
1483 croak("flock() unimplemented on this platform");
1486 fh = (HANDLE)_get_osfhandle(fd);
1487 memset(&o, 0, sizeof(o));
1490 case LOCK_SH: /* shared lock */
1491 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
1493 case LOCK_EX: /* exclusive lock */
1494 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
1496 case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
1497 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
1499 case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
1500 LK_ERR(LockFileEx(fh,
1501 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
1502 0, LK_LEN, 0, &o),i);
1504 case LOCK_UN: /* unlock lock */
1505 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, 0, &o),i);
1507 default: /* unknown */
1518 * redirected io subsystem for all XS modules
1531 return (&(_environ));
1534 /* the rest are the remapped stdio routines */
1554 win32_ferror(FILE *fp)
1556 return (ferror(fp));
1561 win32_feof(FILE *fp)
1567 * Since the errors returned by the socket error function
1568 * WSAGetLastError() are not known by the library routine strerror
1569 * we have to roll our own.
1573 win32_strerror(int e)
1575 #ifndef __BORLANDC__ /* Borland intolerance */
1576 extern int sys_nerr;
1580 if (e < 0 || e > sys_nerr) {
1585 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
1586 strerror_buffer, sizeof(strerror_buffer), NULL) == 0)
1587 strcpy(strerror_buffer, "Unknown Error");
1589 return strerror_buffer;
1595 win32_str_os_error(void *sv, DWORD dwErr)
1599 dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
1600 |FORMAT_MESSAGE_IGNORE_INSERTS
1601 |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
1602 dwErr, 0, (char *)&sMsg, 1, NULL);
1604 while (0 < dwLen && isspace(sMsg[--dwLen]))
1606 if ('.' != sMsg[dwLen])
1611 sMsg = (char*)LocalAlloc(0, 64/**sizeof(TCHAR)*/);
1612 dwLen = sprintf(sMsg,
1613 "Unknown error #0x%lX (lookup 0x%lX)",
1614 dwErr, GetLastError());
1616 sv_setpvn((SV*)sv, sMsg, dwLen);
1622 win32_fprintf(FILE *fp, const char *format, ...)
1625 va_start(marker, format); /* Initialize variable arguments. */
1627 return (vfprintf(fp, format, marker));
1631 win32_printf(const char *format, ...)
1634 va_start(marker, format); /* Initialize variable arguments. */
1636 return (vprintf(format, marker));
1640 win32_vfprintf(FILE *fp, const char *format, va_list args)
1642 return (vfprintf(fp, format, args));
1646 win32_vprintf(const char *format, va_list args)
1648 return (vprintf(format, args));
1652 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
1654 return fread(buf, size, count, fp);
1658 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
1660 return fwrite(buf, size, count, fp);
1664 win32_fopen(const char *filename, const char *mode)
1666 if (stricmp(filename, "/dev/null")==0)
1667 return fopen("NUL", mode);
1668 return fopen(filename, mode);
1671 #ifndef USE_SOCKETS_AS_HANDLES
1673 #define fdopen my_fdopen
1677 win32_fdopen( int handle, const char *mode)
1679 return fdopen(handle, (char *) mode);
1683 win32_freopen( const char *path, const char *mode, FILE *stream)
1685 if (stricmp(path, "/dev/null")==0)
1686 return freopen("NUL", mode, stream);
1687 return freopen(path, mode, stream);
1691 win32_fclose(FILE *pf)
1693 return my_fclose(pf); /* defined in win32sck.c */
1697 win32_fputs(const char *s,FILE *pf)
1699 return fputs(s, pf);
1703 win32_fputc(int c,FILE *pf)
1709 win32_ungetc(int c,FILE *pf)
1711 return ungetc(c,pf);
1715 win32_getc(FILE *pf)
1721 win32_fileno(FILE *pf)
1727 win32_clearerr(FILE *pf)
1734 win32_fflush(FILE *pf)
1740 win32_ftell(FILE *pf)
1746 win32_fseek(FILE *pf,long offset,int origin)
1748 return fseek(pf, offset, origin);
1752 win32_fgetpos(FILE *pf,fpos_t *p)
1754 return fgetpos(pf, p);
1758 win32_fsetpos(FILE *pf,const fpos_t *p)
1760 return fsetpos(pf, p);
1764 win32_rewind(FILE *pf)
1784 win32_fstat(int fd,struct stat *sbufptr)
1786 return fstat(fd,sbufptr);
1790 win32_pipe(int *pfd, unsigned int size, int mode)
1792 return _pipe(pfd, size, mode);
1796 * a popen() clone that respects PERL5SHELL
1800 win32_popen(const char *command, const char *mode)
1802 #ifdef USE_RTL_POPEN
1803 return _popen(command, mode);
1811 /* establish which ends read and write */
1812 if (strchr(mode,'w')) {
1813 stdfd = 0; /* stdin */
1817 else if (strchr(mode,'r')) {
1818 stdfd = 1; /* stdout */
1825 /* set the correct mode */
1826 if (strchr(mode,'b'))
1828 else if (strchr(mode,'t'))
1831 ourmode = _fmode & (O_TEXT | O_BINARY);
1833 /* the child doesn't inherit handles */
1834 ourmode |= O_NOINHERIT;
1836 if (win32_pipe( p, 512, ourmode) == -1)
1839 /* save current stdfd */
1840 if ((oldfd = win32_dup(stdfd)) == -1)
1843 /* make stdfd go to child end of pipe (implicitly closes stdfd) */
1844 /* stdfd will be inherited by the child */
1845 if (win32_dup2(p[child], stdfd) == -1)
1848 /* close the child end in parent */
1849 win32_close(p[child]);
1851 /* start the child */
1852 if ((childpid = do_spawn_nowait((char*)command)) == -1)
1855 /* revert stdfd to whatever it was before */
1856 if (win32_dup2(oldfd, stdfd) == -1)
1859 /* close saved handle */
1862 sv_setiv(*av_fetch(w32_fdpid, p[parent], TRUE), childpid);
1864 /* we have an fd, return a file stream */
1865 return (win32_fdopen(p[parent], (char *)mode));
1868 /* we don't need to check for errors here */
1872 win32_dup2(oldfd, stdfd);
1877 #endif /* USE_RTL_POPEN */
1885 win32_pclose(FILE *pf)
1887 #ifdef USE_RTL_POPEN
1891 int childpid, status;
1894 sv = *av_fetch(w32_fdpid, win32_fileno(pf), TRUE);
1896 childpid = SvIVX(sv);
1908 if (win32_waitpid(childpid, &status, 0) == -1)
1913 #endif /* USE_RTL_POPEN */
1917 win32_rename(const char *oname, const char *newname)
1919 /* XXX despite what the documentation says about MoveFileEx(),
1920 * it doesn't work under Windows95!
1923 if (!MoveFileEx(oname,newname,
1924 MOVEFILE_COPY_ALLOWED|MOVEFILE_REPLACE_EXISTING)) {
1925 DWORD err = GetLastError();
1927 case ERROR_BAD_NET_NAME:
1928 case ERROR_BAD_NETPATH:
1929 case ERROR_BAD_PATHNAME:
1930 case ERROR_FILE_NOT_FOUND:
1931 case ERROR_FILENAME_EXCED_RANGE:
1932 case ERROR_INVALID_DRIVE:
1933 case ERROR_NO_MORE_FILES:
1934 case ERROR_PATH_NOT_FOUND:
1947 char tmpname[MAX_PATH+1];
1948 char dname[MAX_PATH+1];
1949 char *endname = Nullch;
1951 DWORD from_attr, to_attr;
1953 /* if oname doesn't exist, do nothing */
1954 from_attr = GetFileAttributes(oname);
1955 if (from_attr == 0xFFFFFFFF) {
1960 /* if newname exists, rename it to a temporary name so that we
1961 * don't delete it in case oname happens to be the same file
1962 * (but perhaps accessed via a different path)
1964 to_attr = GetFileAttributes(newname);
1965 if (to_attr != 0xFFFFFFFF) {
1966 /* if newname is a directory, we fail
1967 * XXX could overcome this with yet more convoluted logic */
1968 if (to_attr & FILE_ATTRIBUTE_DIRECTORY) {
1972 tmplen = strlen(newname);
1973 strcpy(tmpname,newname);
1974 endname = tmpname+tmplen;
1975 for (; endname > tmpname ; --endname) {
1976 if (*endname == '/' || *endname == '\\') {
1981 if (endname > tmpname)
1982 endname = strcpy(dname,tmpname);
1986 /* get a temporary filename in same directory
1987 * XXX is this really the best we can do? */
1988 if (!GetTempFileName((LPCTSTR)endname, "plr", 0, tmpname)) {
1992 DeleteFile(tmpname);
1994 retval = rename(newname, tmpname);
2001 /* rename oname to newname */
2002 retval = rename(oname, newname);
2004 /* if we created a temporary file before ... */
2005 if (endname != Nullch) {
2006 /* ...and rename succeeded, delete temporary file/directory */
2008 DeleteFile(tmpname);
2009 /* else restore it to what it was */
2011 (void)rename(tmpname, newname);
2018 win32_setmode(int fd, int mode)
2020 return setmode(fd, mode);
2024 win32_lseek(int fd, long offset, int origin)
2026 return lseek(fd, offset, origin);
2036 win32_open(const char *path, int flag, ...)
2042 pmode = va_arg(ap, int);
2045 if (stricmp(path, "/dev/null")==0)
2046 return open("NUL", flag, pmode);
2047 return open(path,flag,pmode);
2069 win32_dup2(int fd1,int fd2)
2071 return dup2(fd1,fd2);
2075 win32_read(int fd, void *buf, unsigned int cnt)
2077 return read(fd, buf, cnt);
2081 win32_write(int fd, const void *buf, unsigned int cnt)
2083 return write(fd, buf, cnt);
2087 win32_mkdir(const char *dir, int mode)
2089 return mkdir(dir); /* just ignore mode */
2093 win32_rmdir(const char *dir)
2099 win32_chdir(const char *dir)
2105 create_command_line(const char* command, const char * const *args)
2108 char *cmd, *ptr, *arg;
2109 STRLEN len = strlen(command) + 1;
2111 for (index = 0; (ptr = (char*)args[index]) != NULL; ++index)
2112 len += strlen(ptr) + 1;
2114 New(1310, cmd, len, char);
2116 strcpy(ptr, command);
2118 for (index = 0; (arg = (char*)args[index]) != NULL; ++index) {
2128 qualified_path(const char *cmd)
2131 char *fullcmd, *curfullcmd;
2137 fullcmd = (char*)cmd;
2139 if (*fullcmd == '/' || *fullcmd == '\\')
2146 pathstr = win32_getenv("PATH");
2147 New(0, fullcmd, MAX_PATH+1, char);
2148 curfullcmd = fullcmd;
2153 /* start by appending the name to the current prefix */
2154 strcpy(curfullcmd, cmd);
2155 curfullcmd += cmdlen;
2157 /* if it doesn't end with '.', or has no extension, try adding
2158 * a trailing .exe first */
2159 if (cmd[cmdlen-1] != '.'
2160 && (cmdlen < 4 || cmd[cmdlen-4] != '.'))
2162 strcpy(curfullcmd, ".exe");
2163 res = GetFileAttributes(fullcmd);
2164 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
2169 /* that failed, try the bare name */
2170 res = GetFileAttributes(fullcmd);
2171 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
2174 /* quit if no other path exists, or if cmd already has path */
2175 if (!pathstr || !*pathstr || has_slash)
2178 /* skip leading semis */
2179 while (*pathstr == ';')
2182 /* build a new prefix from scratch */
2183 curfullcmd = fullcmd;
2184 while (*pathstr && *pathstr != ';') {
2185 if (*pathstr == '"') { /* foo;"baz;etc";bar */
2186 pathstr++; /* skip initial '"' */
2187 while (*pathstr && *pathstr != '"') {
2188 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
2189 *curfullcmd++ = *pathstr;
2193 pathstr++; /* skip trailing '"' */
2196 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
2197 *curfullcmd++ = *pathstr;
2202 pathstr++; /* skip trailing semi */
2203 if (curfullcmd > fullcmd /* append a dir separator */
2204 && curfullcmd[-1] != '/' && curfullcmd[-1] != '\\')
2206 *curfullcmd++ = '\\';
2214 /* XXX this needs to be made more compatible with the spawnvp()
2215 * provided by the various RTLs. In particular, searching for
2216 * *.{com,bat,cmd} files (as done by the RTLs) is unimplemented.
2217 * This doesn't significantly affect perl itself, because we
2218 * always invoke things using PERL5SHELL if a direct attempt to
2219 * spawn the executable fails.
2221 * XXX splitting and rejoining the commandline between do_aspawn()
2222 * and win32_spawnvp() could also be avoided.
2226 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
2228 #ifdef USE_RTL_SPAWNVP
2229 return spawnvp(mode, cmdname, (char * const *)argv);
2232 STARTUPINFO StartupInfo;
2233 PROCESS_INFORMATION ProcessInformation;
2236 char *cmd = create_command_line(cmdname, strcmp(cmdname, argv[0]) == 0
2238 char *fullcmd = Nullch;
2241 case P_NOWAIT: /* asynch + remember result */
2242 if (w32_num_children >= MAXIMUM_WAIT_OBJECTS) {
2248 case P_WAIT: /* synchronous execution */
2250 default: /* invalid mode */
2255 memset(&StartupInfo,0,sizeof(StartupInfo));
2256 StartupInfo.cb = sizeof(StartupInfo);
2257 StartupInfo.wShowWindow = SW_SHOWDEFAULT;
2260 if (!CreateProcess(cmdname, /* search PATH to find executable */
2261 cmd, /* executable, and its arguments */
2262 NULL, /* process attributes */
2263 NULL, /* thread attributes */
2264 TRUE, /* inherit handles */
2265 create, /* creation flags */
2266 NULL, /* inherit environment */
2267 NULL, /* inherit cwd */
2269 &ProcessInformation))
2271 /* initial NULL argument to CreateProcess() does a PATH
2272 * search, but it always first looks in the directory
2273 * where the current process was started, which behavior
2274 * is undesirable for backward compatibility. So we
2275 * jump through our own hoops by picking out the path
2276 * we really want it to use. */
2278 fullcmd = qualified_path(cmdname);
2289 if (mode == P_NOWAIT) {
2290 /* asynchronous spawn -- store handle, return PID */
2291 w32_child_handles[w32_num_children] = ProcessInformation.hProcess;
2292 ret = w32_child_pids[w32_num_children] = ProcessInformation.dwProcessId;
2296 WaitForSingleObject(ProcessInformation.hProcess, INFINITE);
2297 GetExitCodeProcess(ProcessInformation.hProcess, &ret);
2298 CloseHandle(ProcessInformation.hProcess);
2301 CloseHandle(ProcessInformation.hThread);
2310 win32_execv(const char *cmdname, const char *const *argv)
2312 return execv(cmdname, (char *const *)argv);
2316 win32_execvp(const char *cmdname, const char *const *argv)
2318 return execvp(cmdname, (char *const *)argv);
2322 win32_perror(const char *str)
2328 win32_setbuf(FILE *pf, char *buf)
2334 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
2336 return setvbuf(pf, buf, type, size);
2340 win32_flushall(void)
2346 win32_fcloseall(void)
2352 win32_fgets(char *s, int n, FILE *pf)
2354 return fgets(s, n, pf);
2364 win32_fgetc(FILE *pf)
2370 win32_putc(int c, FILE *pf)
2376 win32_puts(const char *s)
2388 win32_putchar(int c)
2395 #ifndef USE_PERL_SBRK
2397 static char *committed = NULL;
2398 static char *base = NULL;
2399 static char *reserved = NULL;
2400 static char *brk = NULL;
2401 static DWORD pagesize = 0;
2402 static DWORD allocsize = 0;
2410 GetSystemInfo(&info);
2411 /* Pretend page size is larger so we don't perpetually
2412 * call the OS to commit just one page ...
2414 pagesize = info.dwPageSize << 3;
2415 allocsize = info.dwAllocationGranularity;
2417 /* This scheme fails eventually if request for contiguous
2418 * block is denied so reserve big blocks - this is only
2419 * address space not memory ...
2421 if (brk+need >= reserved)
2423 DWORD size = 64*1024*1024;
2425 if (committed && reserved && committed < reserved)
2427 /* Commit last of previous chunk cannot span allocations */
2428 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
2430 committed = reserved;
2432 /* Reserve some (more) space
2433 * Note this is a little sneaky, 1st call passes NULL as reserved
2434 * so lets system choose where we start, subsequent calls pass
2435 * the old end address so ask for a contiguous block
2437 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
2440 reserved = addr+size;
2455 if (brk > committed)
2457 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
2458 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
2473 win32_malloc(size_t size)
2475 return malloc(size);
2479 win32_calloc(size_t numitems, size_t size)
2481 return calloc(numitems,size);
2485 win32_realloc(void *block, size_t size)
2487 return realloc(block,size);
2491 win32_free(void *block)
2498 win32_open_osfhandle(long handle, int flags)
2500 return _open_osfhandle(handle, flags);
2504 win32_get_osfhandle(int fd)
2506 return _get_osfhandle(fd);
2517 SV *sv = sv_newmortal();
2518 /* Make one call with zero size - return value is required size */
2519 DWORD len = GetCurrentDirectory((DWORD)0,NULL);
2520 SvUPGRADE(sv,SVt_PV);
2522 SvCUR(sv) = GetCurrentDirectory((DWORD) SvLEN(sv), SvPVX(sv));
2525 * then it worked, set PV valid,
2526 * else leave it 'undef'
2542 croak("usage: Win32::SetCurrentDirectory($cwd)");
2543 if (SetCurrentDirectory(SvPV_nolen(ST(0))))
2550 XS(w32_GetNextAvailDrive)
2554 char root[] = "_:\\";
2559 if (GetDriveType(root) == 1) {
2568 XS(w32_GetLastError)
2572 XSRETURN_IV(GetLastError());
2576 XS(w32_SetLastError)
2580 croak("usage: Win32::SetLastError($error)");
2581 SetLastError(SvIV(ST(0)));
2589 char *name = getlogin_buffer;
2590 DWORD size = sizeof(getlogin_buffer);
2592 if (GetUserName(name,&size)) {
2593 /* size includes NULL */
2594 ST(0) = sv_2mortal(newSVpvn(name,size-1));
2604 char name[MAX_COMPUTERNAME_LENGTH+1];
2605 DWORD size = sizeof(name);
2607 if (GetComputerName(name,&size)) {
2608 /* size does NOT include NULL :-( */
2609 ST(0) = sv_2mortal(newSVpvn(name,size));
2620 #ifndef HAS_NETWKSTAGETINFO
2621 /* mingw32 (and Win95) don't have NetWksta*(), so do it the old way */
2623 DWORD size = sizeof(name);
2625 if (GetUserName(name,&size)) {
2627 DWORD sidlen = sizeof(sid);
2629 DWORD dnamelen = sizeof(dname);
2631 if (LookupAccountName(NULL, name, (PSID)&sid, &sidlen,
2632 dname, &dnamelen, &snu)) {
2633 XSRETURN_PV(dname); /* all that for this */
2637 /* this way is more reliable, in case user has a local account.
2638 * XXX need dynamic binding of netapi32.dll symbols or this will fail on
2639 * Win95. Probably makes more sense to move it into libwin32. */
2641 DWORD dnamelen = sizeof(dname);
2642 PWKSTA_INFO_100 pwi;
2644 if (NERR_Success == NetWkstaGetInfo(NULL, 100, (LPBYTE*)&pwi)) {
2645 if (pwi->wki100_langroup && *(pwi->wki100_langroup)) {
2646 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_langroup,
2647 -1, (LPSTR)dname, dnamelen, NULL, NULL);
2650 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_computername,
2651 -1, (LPSTR)dname, dnamelen, NULL, NULL);
2653 NetApiBufferFree(pwi);
2665 DWORD flags, filecomplen;
2666 if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
2667 &flags, fsname, sizeof(fsname))) {
2668 if (GIMME_V == G_ARRAY) {
2669 XPUSHs(sv_2mortal(newSVpvn(fsname,strlen(fsname))));
2670 XPUSHs(sv_2mortal(newSViv(flags)));
2671 XPUSHs(sv_2mortal(newSViv(filecomplen)));
2676 XSRETURN_PV(fsname);
2682 XS(w32_GetOSVersion)
2685 OSVERSIONINFO osver;
2687 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
2688 if (GetVersionEx(&osver)) {
2689 XPUSHs(newSVpvn(osver.szCSDVersion, strlen(osver.szCSDVersion)));
2690 XPUSHs(newSViv(osver.dwMajorVersion));
2691 XPUSHs(newSViv(osver.dwMinorVersion));
2692 XPUSHs(newSViv(osver.dwBuildNumber));
2693 XPUSHs(newSViv(osver.dwPlatformId));
2705 XSRETURN_IV(IsWinNT());
2713 XSRETURN_IV(IsWin95());
2717 XS(w32_FormatMessage)
2724 croak("usage: Win32::FormatMessage($errno)");
2726 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
2727 &source, SvIV(ST(0)), 0,
2728 msgbuf, sizeof(msgbuf)-1, NULL))
2729 XSRETURN_PV(msgbuf);
2739 PROCESS_INFORMATION stProcInfo;
2740 STARTUPINFO stStartInfo;
2741 BOOL bSuccess = FALSE;
2744 croak("usage: Win32::Spawn($cmdName, $args, $PID)");
2746 cmd = SvPV_nolen(ST(0));
2747 args = SvPV_nolen(ST(1));
2749 memset(&stStartInfo, 0, sizeof(stStartInfo)); /* Clear the block */
2750 stStartInfo.cb = sizeof(stStartInfo); /* Set the structure size */
2751 stStartInfo.dwFlags = STARTF_USESHOWWINDOW; /* Enable wShowWindow control */
2752 stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE; /* Start min (normal) */
2755 cmd, /* Image path */
2756 args, /* Arguments for command line */
2757 NULL, /* Default process security */
2758 NULL, /* Default thread security */
2759 FALSE, /* Must be TRUE to use std handles */
2760 NORMAL_PRIORITY_CLASS, /* No special scheduling */
2761 NULL, /* Inherit our environment block */
2762 NULL, /* Inherit our currrent directory */
2763 &stStartInfo, /* -> Startup info */
2764 &stProcInfo)) /* <- Process info (if OK) */
2766 CloseHandle(stProcInfo.hThread);/* library source code does this. */
2767 sv_setiv(ST(2), stProcInfo.dwProcessId);
2770 XSRETURN_IV(bSuccess);
2774 XS(w32_GetTickCount)
2778 DWORD msec = GetTickCount();
2785 XS(w32_GetShortPathName)
2792 croak("usage: Win32::GetShortPathName($longPathName)");
2794 shortpath = sv_mortalcopy(ST(0));
2795 SvUPGRADE(shortpath, SVt_PV);
2796 /* src == target is allowed */
2798 len = GetShortPathName(SvPVX(shortpath),
2801 } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
2803 SvCUR_set(shortpath,len);
2811 XS(w32_GetFullPathName)
2820 croak("usage: Win32::GetFullPathName($filename)");
2823 fullpath = sv_mortalcopy(filename);
2824 SvUPGRADE(fullpath, SVt_PV);
2826 len = GetFullPathName(SvPVX(filename),
2830 } while (len >= SvLEN(fullpath) && sv_grow(fullpath,len+1));
2832 if (GIMME_V == G_ARRAY) {
2834 XST_mPV(1,filepart);
2835 len = filepart - SvPVX(fullpath);
2838 SvCUR_set(fullpath,len);
2850 croak("usage: Win32::Sleep($milliseconds)");
2856 Perl_init_os_extras()
2858 char *file = __FILE__;
2861 w32_perlshell_tokens = Nullch;
2862 w32_perlshell_items = -1;
2863 w32_fdpid = newAV(); /* XXX needs to be in Perl_win32_init()? */
2864 New(1313, w32_children, 1, child_tab);
2865 w32_num_children = 0;
2867 /* these names are Activeware compatible */
2868 newXS("Win32::GetCwd", w32_GetCwd, file);
2869 newXS("Win32::SetCwd", w32_SetCwd, file);
2870 newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
2871 newXS("Win32::GetLastError", w32_GetLastError, file);
2872 newXS("Win32::SetLastError", w32_SetLastError, file);
2873 newXS("Win32::LoginName", w32_LoginName, file);
2874 newXS("Win32::NodeName", w32_NodeName, file);
2875 newXS("Win32::DomainName", w32_DomainName, file);
2876 newXS("Win32::FsType", w32_FsType, file);
2877 newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
2878 newXS("Win32::IsWinNT", w32_IsWinNT, file);
2879 newXS("Win32::IsWin95", w32_IsWin95, file);
2880 newXS("Win32::FormatMessage", w32_FormatMessage, file);
2881 newXS("Win32::Spawn", w32_Spawn, file);
2882 newXS("Win32::GetTickCount", w32_GetTickCount, file);
2883 newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
2884 newXS("Win32::GetFullPathName", w32_GetFullPathName, file);
2885 newXS("Win32::Sleep", w32_Sleep, file);
2887 /* XXX Bloat Alert! The following Activeware preloads really
2888 * ought to be part of Win32::Sys::*, so they're not included
2891 /* LookupAccountName
2893 * InitiateSystemShutdown
2894 * AbortSystemShutdown
2895 * ExpandEnvrironmentStrings
2900 Perl_win32_init(int *argcp, char ***argvp)
2902 /* Disable floating point errors, Perl will trap the ones we
2903 * care about. VC++ RTL defaults to switching these off
2904 * already, but the Borland RTL doesn't. Since we don't
2905 * want to be at the vendor's whim on the default, we set
2906 * it explicitly here.
2908 #if !defined(_ALPHA_) && !defined(__GNUC__)
2909 _control87(MCW_EM, MCW_EM);
2914 #ifdef USE_BINMODE_SCRIPTS
2917 win32_strip_return(SV *sv)
2919 char *s = SvPVX(sv);
2920 char *e = s+SvCUR(sv);
2924 if (*s == '\r' && s[1] == '\n')
2934 SvCUR_set(sv,d-SvPVX(sv));