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 ptr = strrchr(mod_name, '\\');
199 while (ptr && strip) {
200 /* look for directories to skip back */
203 ptr = strrchr(mod_name, '\\');
204 if (!ptr || stricmp(ptr+1, strip) != 0) {
205 if(!(*strip == '5' && *(ptr+1) == '5' && strncmp(strip, base, 5) == 0
206 && strncmp(ptr+1, base, 5) == 0)) {
211 strip = va_arg(ap, char *);
219 strcpy(++ptr, trailing_path);
221 /* only add directory if it exists */
222 if(GetFileAttributes(mod_name) != (DWORD) -1) {
223 /* directory exists */
224 newsize = strlen(mod_name) + 1;
226 oldsize = strlen(prev_path) + 1;
227 newsize += oldsize; /* includes plus 1 for ';' */
228 Renew(prev_path, newsize, char);
229 prev_path[oldsize-1] = ';';
230 strcpy(&prev_path[oldsize], mod_name);
233 New(1311, prev_path, newsize, char);
234 strcpy(prev_path, mod_name);
242 win32_get_privlib(char *pl)
244 char *stdlib = "lib";
245 char buffer[MAX_PATH+1];
249 /* $stdlib = $HKCU{"lib-$]"} || $HKLM{"lib-$]"} || $HKCU{"lib"} || $HKLM{"lib"} || ""; */
250 sprintf(buffer, "%s-%s", stdlib, pl);
251 path = GetRegStr(buffer, &path, &datalen);
253 path = GetRegStr(stdlib, &path, &datalen);
255 /* $stdlib .= ";$EMD/../../lib" */
256 return get_emd_part(path, stdlib, ARCHNAME, "bin", Nullch);
260 win32_get_sitelib(char *pl)
262 char *sitelib = "sitelib";
264 char pathstr[MAX_PATH+1];
266 char *path1 = Nullch;
267 char *path2 = Nullch;
270 /* $HKCU{"sitelib-$]"} || $HKLM{"sitelib-$]"} . ---; */
271 sprintf(regstr, "%s-%s", sitelib, pl);
272 path1 = GetRegStr(regstr, &path1, &datalen);
275 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/site/$]/lib"; */
276 sprintf(pathstr, "site\\%s\\lib", pl);
277 path1 = get_emd_part(path1, pathstr, ARCHNAME, "bin", pl, Nullch);
279 /* $HKCU{'sitelib'} || $HKLM{'sitelib'} . ---; */
280 path2 = GetRegStr(sitelib, &path2, &datalen);
283 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/site/lib"; */
284 path2 = get_emd_part(path2, "site\\lib", ARCHNAME, "bin", pl, Nullch);
293 newsize = len + strlen(path2) + 2; /* plus one for ';' */
295 Renew(path1, newsize, char);
297 strcpy(&path1[len], path2);
305 has_shell_metachars(char *ptr)
311 * Scan string looking for redirection (< or >) or pipe
312 * characters (|) that are not in a quoted string.
313 * Shell variable interpolation (%VAR%) can also happen inside strings.
345 #if !defined(PERL_OBJECT)
346 /* since the current process environment is being updated in util.c
347 * the library functions will get the correct environment
350 my_popen(char *cmd, char *mode)
353 #define fixcmd(x) { \
354 char *pspace = strchr((x),' '); \
357 while (p < pspace) { \
368 win32_fflush(stdout);
369 win32_fflush(stderr);
370 return win32_popen(cmd, mode);
374 my_pclose(PerlIO *fp)
376 return win32_pclose(fp);
383 static OSVERSIONINFO osver;
385 if (osver.dwPlatformId != w32_platform) {
386 memset(&osver, 0, sizeof(OSVERSIONINFO));
387 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
388 GetVersionEx(&osver);
389 w32_platform = osver.dwPlatformId;
391 return (w32_platform);
394 /* Tokenize a string. Words are null-separated, and the list
395 * ends with a doubled null. Any character (except null and
396 * including backslash) may be escaped by preceding it with a
397 * backslash (the backslash will be stripped).
398 * Returns number of words in result buffer.
401 tokenize(char *str, char **dest, char ***destv)
403 char *retstart = Nullch;
404 char **retvstart = 0;
407 int slen = strlen(str);
409 register char **retv;
410 New(1307, ret, slen+2, char);
411 New(1308, retv, (slen+3)/2, char*);
419 if (*ret == '\\' && *str)
421 else if (*ret == ' ') {
437 retvstart[items] = Nullch;
449 if (!w32_perlshell_tokens) {
450 /* we don't use COMSPEC here for two reasons:
451 * 1. the same reason perl on UNIX doesn't use SHELL--rampant and
452 * uncontrolled unportability of the ensuing scripts.
453 * 2. PERL5SHELL could be set to a shell that may not be fit for
454 * interactive use (which is what most programs look in COMSPEC
457 char* defaultshell = (IsWinNT() ? "cmd.exe /x/c" : "command.com /c");
458 char *usershell = getenv("PERL5SHELL");
459 w32_perlshell_items = tokenize(usershell ? usershell : defaultshell,
460 &w32_perlshell_tokens,
466 do_aspawn(void *vreally, void **vmark, void **vsp)
468 SV *really = (SV*)vreally;
469 SV **mark = (SV**)vmark;
481 New(1306, argv, (sp - mark) + w32_perlshell_items + 2, char*);
483 if (SvNIOKp(*(mark+1)) && !SvPOKp(*(mark+1))) {
488 while (++mark <= sp) {
489 if (*mark && (str = SvPV_nolen(*mark)))
496 status = win32_spawnvp(flag,
497 (const char*)(really ? SvPV_nolen(really) : argv[0]),
498 (const char* const*)argv);
500 if (status < 0 && (errno == ENOEXEC || errno == ENOENT)) {
501 /* possible shell-builtin, invoke with shell */
503 sh_items = w32_perlshell_items;
505 argv[index+sh_items] = argv[index];
506 while (--sh_items >= 0)
507 argv[sh_items] = w32_perlshell_vec[sh_items];
509 status = win32_spawnvp(flag,
510 (const char*)(really ? SvPV_nolen(really) : argv[0]),
511 (const char* const*)argv);
514 if (flag != P_NOWAIT) {
517 warn("Can't spawn \"%s\": %s", argv[0], strerror(errno));
522 PL_statusvalue = status;
529 do_spawn2(char *cmd, int exectype)
535 BOOL needToTry = TRUE;
538 /* Save an extra exec if possible. See if there are shell
539 * metacharacters in it */
540 if (!has_shell_metachars(cmd)) {
541 New(1301,argv, strlen(cmd) / 2 + 2, char*);
542 New(1302,cmd2, strlen(cmd) + 1, char);
545 for (s = cmd2; *s;) {
546 while (*s && isspace(*s))
550 while (*s && !isspace(*s))
559 status = win32_spawnvp(P_WAIT, argv[0],
560 (const char* const*)argv);
562 case EXECF_SPAWN_NOWAIT:
563 status = win32_spawnvp(P_NOWAIT, argv[0],
564 (const char* const*)argv);
567 status = win32_execvp(argv[0], (const char* const*)argv);
570 if (status != -1 || errno == 0)
580 New(1306, argv, w32_perlshell_items + 2, char*);
581 while (++i < w32_perlshell_items)
582 argv[i] = w32_perlshell_vec[i];
587 status = win32_spawnvp(P_WAIT, argv[0],
588 (const char* const*)argv);
590 case EXECF_SPAWN_NOWAIT:
591 status = win32_spawnvp(P_NOWAIT, argv[0],
592 (const char* const*)argv);
595 status = win32_execvp(argv[0], (const char* const*)argv);
601 if (exectype != EXECF_SPAWN_NOWAIT) {
604 warn("Can't %s \"%s\": %s",
605 (exectype == EXECF_EXEC ? "exec" : "spawn"),
606 cmd, strerror(errno));
611 PL_statusvalue = status;
619 return do_spawn2(cmd, EXECF_SPAWN);
623 do_spawn_nowait(char *cmd)
625 return do_spawn2(cmd, EXECF_SPAWN_NOWAIT);
631 do_spawn2(cmd, EXECF_EXEC);
635 /* The idea here is to read all the directory names into a string table
636 * (separated by nulls) and when one of the other dir functions is called
637 * return the pointer to the current file name.
640 win32_opendir(char *filename)
645 char scanname[MAX_PATH+3];
647 WIN32_FIND_DATA FindData;
650 len = strlen(filename);
654 /* check to see if filename is a directory */
655 if (win32_stat(filename, &sbuf) < 0 || !S_ISDIR(sbuf.st_mode))
658 /* Get us a DIR structure */
659 Newz(1303, p, 1, DIR);
663 /* Create the search pattern */
664 strcpy(scanname, filename);
665 if (scanname[len-1] != '/' && scanname[len-1] != '\\')
666 scanname[len++] = '/';
667 scanname[len++] = '*';
668 scanname[len] = '\0';
670 /* do the FindFirstFile call */
671 fh = FindFirstFile(scanname, &FindData);
672 if (fh == INVALID_HANDLE_VALUE) {
673 /* FindFirstFile() fails on empty drives! */
674 if (GetLastError() == ERROR_FILE_NOT_FOUND)
680 /* now allocate the first part of the string table for
681 * the filenames that we find.
683 idx = strlen(FindData.cFileName)+1;
684 New(1304, p->start, idx, char);
685 if (p->start == NULL)
686 croak("opendir: malloc failed!\n");
687 strcpy(p->start, FindData.cFileName);
690 /* loop finding all the files that match the wildcard
691 * (which should be all of them in this directory!).
692 * the variable idx should point one past the null terminator
693 * of the previous string found.
695 while (FindNextFile(fh, &FindData)) {
696 len = strlen(FindData.cFileName);
697 /* bump the string table size by enough for the
698 * new name and it's null terminator
700 Renew(p->start, idx+len+1, char);
701 if (p->start == NULL)
702 croak("opendir: malloc failed!\n");
703 strcpy(&p->start[idx], FindData.cFileName);
714 /* Readdir just returns the current string pointer and bumps the
715 * string pointer to the nDllExport entry.
718 win32_readdir(DIR *dirp)
721 static int dummy = 0;
724 /* first set up the structure to return */
725 len = strlen(dirp->curr);
726 strcpy(dirp->dirstr.d_name, dirp->curr);
727 dirp->dirstr.d_namlen = len;
730 dirp->dirstr.d_ino = dummy++;
732 /* Now set up for the nDllExport call to readdir */
733 dirp->curr += len + 1;
734 if (dirp->curr >= (dirp->start + dirp->size)) {
738 return &(dirp->dirstr);
744 /* Telldir returns the current string pointer position */
746 win32_telldir(DIR *dirp)
748 return (long) dirp->curr;
752 /* Seekdir moves the string pointer to a previously saved position
756 win32_seekdir(DIR *dirp, long loc)
758 dirp->curr = (char *)loc;
761 /* Rewinddir resets the string pointer to the start */
763 win32_rewinddir(DIR *dirp)
765 dirp->curr = dirp->start;
768 /* free the memory allocated by opendir */
770 win32_closedir(DIR *dirp)
772 Safefree(dirp->start);
785 * Just pretend that everyone is a superuser. NT will let us know if
786 * we don\'t really have permission to do something.
789 #define ROOT_UID ((uid_t)0)
790 #define ROOT_GID ((gid_t)0)
819 return (auid == ROOT_UID ? 0 : -1);
825 return (agid == ROOT_GID ? 0 : -1);
832 char *buf = getlogin_buffer;
833 DWORD size = sizeof(getlogin_buffer);
834 if (GetUserName(buf,&size))
840 chown(const char *path, uid_t owner, gid_t group)
850 for (child = 0 ; child < w32_num_children ; ++child) {
851 if (w32_child_pids[child] == pid)
858 remove_dead_process(long child)
861 CloseHandle(w32_child_handles[child]);
862 Copy(&w32_child_handles[child+1], &w32_child_handles[child],
863 (w32_num_children-child-1), HANDLE);
864 Copy(&w32_child_pids[child+1], &w32_child_pids[child],
865 (w32_num_children-child-1), DWORD);
871 win32_kill(int pid, int sig)
874 hProcess = OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid);
875 if (hProcess && TerminateProcess(hProcess, sig))
876 CloseHandle(hProcess);
888 DllExport unsigned int
889 win32_sleep(unsigned int t)
896 win32_stat(const char *path, struct stat *buffer)
899 const char *p = path;
900 int l = strlen(path);
904 switch(path[l - 1]) {
907 if (path[l - 2] != ':') {
908 strncpy(t, path, l - 1);
914 res = stat(p,buffer);
916 /* CRT is buggy on sharenames, so make sure it really isn't.
917 * XXX using GetFileAttributesEx() will enable us to set
918 * buffer->st_*time (but note that's not available on the
919 * Windows of 1995) */
920 DWORD r = GetFileAttributes(p);
921 if (r != 0xffffffff && (r & FILE_ATTRIBUTE_DIRECTORY)) {
922 buffer->st_mode |= S_IFDIR | S_IREAD;
924 if (!(r & FILE_ATTRIBUTE_READONLY))
925 buffer->st_mode |= S_IWRITE | S_IEXEC;
930 if (l == 3 && path[l-2] == ':'
931 && (path[l-1] == '\\' || path[l-1] == '/'))
933 /* The drive can be inaccessible, some _stat()s are buggy */
934 if (!GetVolumeInformation(path,NULL,0,NULL,NULL,NULL,NULL,0)) {
940 if (S_ISDIR(buffer->st_mode))
941 buffer->st_mode |= S_IWRITE | S_IEXEC;
942 else if (S_ISREG(buffer->st_mode)) {
943 if (l >= 4 && path[l-4] == '.') {
944 const char *e = path + l - 3;
945 if (strnicmp(e,"exe",3)
946 && strnicmp(e,"bat",3)
947 && strnicmp(e,"com",3)
948 && (IsWin95() || strnicmp(e,"cmd",3)))
949 buffer->st_mode &= ~S_IEXEC;
951 buffer->st_mode |= S_IEXEC;
954 buffer->st_mode &= ~S_IEXEC;
961 #ifndef USE_WIN32_RTL_ENV
964 win32_getenv(const char *name)
966 static char *curitem = Nullch; /* XXX threadead */
967 static DWORD curlen = 0; /* XXX threadead */
971 New(1305,curitem,curlen,char);
974 needlen = GetEnvironmentVariable(name,curitem,curlen);
976 while (needlen > curlen) {
977 Renew(curitem,needlen,char);
979 needlen = GetEnvironmentVariable(name,curitem,curlen);
983 /* allow any environment variables that begin with 'PERL'
984 to be stored in the registry */
988 if (strncmp(name, "PERL", 4) == 0) {
994 curitem = GetRegStr(name, &curitem, &curlen);
997 if (curitem && *curitem == '\0')
1004 win32_putenv(const char *name)
1010 New(1309,curitem,strlen(name)+1,char);
1011 strcpy(curitem, name);
1012 val = strchr(curitem, '=');
1014 /* The sane way to deal with the environment.
1015 * Has these advantages over putenv() & co.:
1016 * * enables us to store a truly empty value in the
1017 * environment (like in UNIX).
1018 * * we don't have to deal with RTL globals, bugs and leaks.
1020 * Why you may want to enable USE_WIN32_RTL_ENV:
1021 * * environ[] and RTL functions will not reflect changes,
1022 * which might be an issue if extensions want to access
1023 * the env. via RTL. This cuts both ways, since RTL will
1024 * not see changes made by extensions that call the Win32
1025 * functions directly, either.
1029 if(SetEnvironmentVariable(curitem, *val ? val : NULL))
1040 filetime_to_clock(PFILETIME ft)
1042 __int64 qw = ft->dwHighDateTime;
1044 qw |= ft->dwLowDateTime;
1045 qw /= 10000; /* File time ticks at 0.1uS, clock at 1mS */
1050 win32_times(struct tms *timebuf)
1055 if (GetProcessTimes(GetCurrentProcess(), &dummy, &dummy,
1057 timebuf->tms_utime = filetime_to_clock(&user);
1058 timebuf->tms_stime = filetime_to_clock(&kernel);
1059 timebuf->tms_cutime = 0;
1060 timebuf->tms_cstime = 0;
1063 /* That failed - e.g. Win95 fallback to clock() */
1064 clock_t t = clock();
1065 timebuf->tms_utime = t;
1066 timebuf->tms_stime = 0;
1067 timebuf->tms_cutime = 0;
1068 timebuf->tms_cstime = 0;
1073 /* fix utime() so it works on directories in NT
1074 * thanks to Jan Dubois <jan.dubois@ibm.net>
1077 filetime_from_time(PFILETIME pFileTime, time_t Time)
1079 struct tm *pTM = gmtime(&Time);
1080 SYSTEMTIME SystemTime;
1085 SystemTime.wYear = pTM->tm_year + 1900;
1086 SystemTime.wMonth = pTM->tm_mon + 1;
1087 SystemTime.wDay = pTM->tm_mday;
1088 SystemTime.wHour = pTM->tm_hour;
1089 SystemTime.wMinute = pTM->tm_min;
1090 SystemTime.wSecond = pTM->tm_sec;
1091 SystemTime.wMilliseconds = 0;
1093 return SystemTimeToFileTime(&SystemTime, pFileTime);
1097 win32_utime(const char *filename, struct utimbuf *times)
1103 struct utimbuf TimeBuffer;
1105 int rc = utime(filename,times);
1106 /* EACCES: path specifies directory or readonly file */
1107 if (rc == 0 || errno != EACCES /* || !IsWinNT() */)
1110 if (times == NULL) {
1111 times = &TimeBuffer;
1112 time(×->actime);
1113 times->modtime = times->actime;
1116 /* This will (and should) still fail on readonly files */
1117 handle = CreateFile(filename, GENERIC_READ | GENERIC_WRITE,
1118 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1119 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1120 if (handle == INVALID_HANDLE_VALUE)
1123 if (GetFileTime(handle, &ftCreate, &ftAccess, &ftWrite) &&
1124 filetime_from_time(&ftAccess, times->actime) &&
1125 filetime_from_time(&ftWrite, times->modtime) &&
1126 SetFileTime(handle, &ftCreate, &ftAccess, &ftWrite))
1131 CloseHandle(handle);
1136 win32_uname(struct utsname *name)
1138 struct hostent *hep;
1139 STRLEN nodemax = sizeof(name->nodename)-1;
1140 OSVERSIONINFO osver;
1142 memset(&osver, 0, sizeof(OSVERSIONINFO));
1143 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1144 if (GetVersionEx(&osver)) {
1146 switch (osver.dwPlatformId) {
1147 case VER_PLATFORM_WIN32_WINDOWS:
1148 strcpy(name->sysname, "Windows");
1150 case VER_PLATFORM_WIN32_NT:
1151 strcpy(name->sysname, "Windows NT");
1153 case VER_PLATFORM_WIN32s:
1154 strcpy(name->sysname, "Win32s");
1157 strcpy(name->sysname, "Win32 Unknown");
1162 sprintf(name->release, "%d.%d",
1163 osver.dwMajorVersion, osver.dwMinorVersion);
1166 sprintf(name->version, "Build %d",
1167 osver.dwPlatformId == VER_PLATFORM_WIN32_NT
1168 ? osver.dwBuildNumber : (osver.dwBuildNumber & 0xffff));
1169 if (osver.szCSDVersion[0]) {
1170 char *buf = name->version + strlen(name->version);
1171 sprintf(buf, " (%s)", osver.szCSDVersion);
1175 *name->sysname = '\0';
1176 *name->version = '\0';
1177 *name->release = '\0';
1181 hep = win32_gethostbyname("localhost");
1183 STRLEN len = strlen(hep->h_name);
1184 if (len <= nodemax) {
1185 strcpy(name->nodename, hep->h_name);
1188 strncpy(name->nodename, hep->h_name, nodemax);
1189 name->nodename[nodemax] = '\0';
1194 if (!GetComputerName(name->nodename, &sz))
1195 *name->nodename = '\0';
1198 /* machine (architecture) */
1202 GetSystemInfo(&info);
1203 switch (info.wProcessorArchitecture) {
1204 case PROCESSOR_ARCHITECTURE_INTEL:
1205 arch = "x86"; break;
1206 case PROCESSOR_ARCHITECTURE_MIPS:
1207 arch = "mips"; break;
1208 case PROCESSOR_ARCHITECTURE_ALPHA:
1209 arch = "alpha"; break;
1210 case PROCESSOR_ARCHITECTURE_PPC:
1211 arch = "ppc"; break;
1213 arch = "unknown"; break;
1215 strcpy(name->machine, arch);
1221 win32_waitpid(int pid, int *status, int flags)
1225 return win32_wait(status);
1227 long child = find_pid(pid);
1229 HANDLE hProcess = w32_child_handles[child];
1230 DWORD waitcode = WaitForSingleObject(hProcess, INFINITE);
1231 if (waitcode != WAIT_FAILED) {
1232 if (GetExitCodeProcess(hProcess, &waitcode)) {
1233 *status = (int)((waitcode & 0xff) << 8);
1234 retval = (int)w32_child_pids[child];
1235 remove_dead_process(child);
1243 retval = cwait(status, pid, WAIT_CHILD);
1244 /* cwait() returns "correctly" on Borland */
1245 #ifndef __BORLANDC__
1251 return retval >= 0 ? pid : retval;
1255 win32_wait(int *status)
1257 /* XXX this wait emulation only knows about processes
1258 * spawned via win32_spawnvp(P_NOWAIT, ...).
1261 DWORD exitcode, waitcode;
1263 if (!w32_num_children) {
1268 /* if a child exists, wait for it to die */
1269 waitcode = WaitForMultipleObjects(w32_num_children,
1273 if (waitcode != WAIT_FAILED) {
1274 if (waitcode >= WAIT_ABANDONED_0
1275 && waitcode < WAIT_ABANDONED_0 + w32_num_children)
1276 i = waitcode - WAIT_ABANDONED_0;
1278 i = waitcode - WAIT_OBJECT_0;
1279 if (GetExitCodeProcess(w32_child_handles[i], &exitcode) ) {
1280 *status = (int)((exitcode & 0xff) << 8);
1281 retval = (int)w32_child_pids[i];
1282 remove_dead_process(i);
1288 errno = GetLastError();
1292 static UINT timerid = 0;
1294 static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
1296 KillTimer(NULL,timerid);
1301 DllExport unsigned int
1302 win32_alarm(unsigned int sec)
1305 * the 'obvious' implentation is SetTimer() with a callback
1306 * which does whatever receiving SIGALRM would do
1307 * we cannot use SIGALRM even via raise() as it is not
1308 * one of the supported codes in <signal.h>
1310 * Snag is unless something is looking at the message queue
1311 * nothing happens :-(
1315 timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
1317 croak("Cannot set timer");
1323 KillTimer(NULL,timerid);
1330 #if defined(HAVE_DES_FCRYPT) || defined(PERL_OBJECT)
1331 #ifdef HAVE_DES_FCRYPT
1332 extern char * des_fcrypt(const char *txt, const char *salt, char *cbuf);
1336 win32_crypt(const char *txt, const char *salt)
1338 #ifdef HAVE_DES_FCRYPT
1340 return des_fcrypt(txt, salt, crypt_buffer);
1342 die("The crypt() function is unimplemented due to excessive paranoia.");
1348 #ifdef USE_FIXED_OSFHANDLE
1350 EXTERN_C int __cdecl _alloc_osfhnd(void);
1351 EXTERN_C int __cdecl _set_osfhnd(int fh, long value);
1352 EXTERN_C void __cdecl _lock_fhandle(int);
1353 EXTERN_C void __cdecl _unlock_fhandle(int);
1354 EXTERN_C void __cdecl _unlock(int);
1356 #if (_MSC_VER >= 1000)
1358 long osfhnd; /* underlying OS file HANDLE */
1359 char osfile; /* attributes of file (e.g., open in text mode?) */
1360 char pipech; /* one char buffer for handles opened on pipes */
1361 #if defined (_MT) && !defined (DLL_FOR_WIN32S)
1363 CRITICAL_SECTION lock;
1364 #endif /* defined (_MT) && !defined (DLL_FOR_WIN32S) */
1367 EXTERN_C ioinfo * __pioinfo[];
1369 #define IOINFO_L2E 5
1370 #define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
1371 #define _pioinfo(i) (__pioinfo[i >> IOINFO_L2E] + (i & (IOINFO_ARRAY_ELTS - 1)))
1372 #define _osfile(i) (_pioinfo(i)->osfile)
1374 #else /* (_MSC_VER >= 1000) */
1375 extern char _osfile[];
1376 #endif /* (_MSC_VER >= 1000) */
1378 #define FOPEN 0x01 /* file handle open */
1379 #define FAPPEND 0x20 /* file handle opened O_APPEND */
1380 #define FDEV 0x40 /* file handle refers to device */
1381 #define FTEXT 0x80 /* file handle is in text mode */
1383 #define _STREAM_LOCKS 26 /* Table of stream locks */
1384 #define _LAST_STREAM_LOCK (_STREAM_LOCKS+_NSTREAM_-1) /* Last stream lock */
1385 #define _FH_LOCKS (_LAST_STREAM_LOCK+1) /* Table of fh locks */
1388 *int my_open_osfhandle(long osfhandle, int flags) - open C Runtime file handle
1391 * This function allocates a free C Runtime file handle and associates
1392 * it with the Win32 HANDLE specified by the first parameter. This is a
1393 * temperary fix for WIN95's brain damage GetFileType() error on socket
1394 * we just bypass that call for socket
1397 * long osfhandle - Win32 HANDLE to associate with C Runtime file handle.
1398 * int flags - flags to associate with C Runtime file handle.
1401 * returns index of entry in fh, if successful
1402 * return -1, if no free entry is found
1406 *******************************************************************************/
1409 my_open_osfhandle(long osfhandle, int flags)
1412 char fileflags; /* _osfile flags */
1414 /* copy relevant flags from second parameter */
1417 if (flags & O_APPEND)
1418 fileflags |= FAPPEND;
1423 /* attempt to allocate a C Runtime file handle */
1424 if ((fh = _alloc_osfhnd()) == -1) {
1425 errno = EMFILE; /* too many open files */
1426 _doserrno = 0L; /* not an OS error */
1427 return -1; /* return error to caller */
1430 /* the file is open. now, set the info in _osfhnd array */
1431 _set_osfhnd(fh, osfhandle);
1433 fileflags |= FOPEN; /* mark as open */
1435 #if (_MSC_VER >= 1000)
1436 _osfile(fh) = fileflags; /* set osfile entry */
1437 _unlock_fhandle(fh);
1439 _osfile[fh] = fileflags; /* set osfile entry */
1440 _unlock(fh+_FH_LOCKS); /* unlock handle */
1443 return fh; /* return handle */
1446 #define _open_osfhandle my_open_osfhandle
1447 #endif /* USE_FIXED_OSFHANDLE */
1449 /* simulate flock by locking a range on the file */
1451 #define LK_ERR(f,i) ((f) ? (i = 0) : (errno = GetLastError()))
1452 #define LK_LEN 0xffff0000
1455 win32_flock(int fd, int oper)
1462 croak("flock() unimplemented on this platform");
1465 fh = (HANDLE)_get_osfhandle(fd);
1466 memset(&o, 0, sizeof(o));
1469 case LOCK_SH: /* shared lock */
1470 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
1472 case LOCK_EX: /* exclusive lock */
1473 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
1475 case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
1476 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
1478 case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
1479 LK_ERR(LockFileEx(fh,
1480 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
1481 0, LK_LEN, 0, &o),i);
1483 case LOCK_UN: /* unlock lock */
1484 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, 0, &o),i);
1486 default: /* unknown */
1497 * redirected io subsystem for all XS modules
1510 return (&(_environ));
1513 /* the rest are the remapped stdio routines */
1533 win32_ferror(FILE *fp)
1535 return (ferror(fp));
1540 win32_feof(FILE *fp)
1546 * Since the errors returned by the socket error function
1547 * WSAGetLastError() are not known by the library routine strerror
1548 * we have to roll our own.
1552 win32_strerror(int e)
1554 #ifndef __BORLANDC__ /* Borland intolerance */
1555 extern int sys_nerr;
1559 if (e < 0 || e > sys_nerr) {
1564 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
1565 strerror_buffer, sizeof(strerror_buffer), NULL) == 0)
1566 strcpy(strerror_buffer, "Unknown Error");
1568 return strerror_buffer;
1574 win32_str_os_error(void *sv, DWORD dwErr)
1578 dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
1579 |FORMAT_MESSAGE_IGNORE_INSERTS
1580 |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
1581 dwErr, 0, (char *)&sMsg, 1, NULL);
1583 while (0 < dwLen && isspace(sMsg[--dwLen]))
1585 if ('.' != sMsg[dwLen])
1590 sMsg = (char*)LocalAlloc(0, 64/**sizeof(TCHAR)*/);
1591 dwLen = sprintf(sMsg,
1592 "Unknown error #0x%lX (lookup 0x%lX)",
1593 dwErr, GetLastError());
1595 sv_setpvn((SV*)sv, sMsg, dwLen);
1601 win32_fprintf(FILE *fp, const char *format, ...)
1604 va_start(marker, format); /* Initialize variable arguments. */
1606 return (vfprintf(fp, format, marker));
1610 win32_printf(const char *format, ...)
1613 va_start(marker, format); /* Initialize variable arguments. */
1615 return (vprintf(format, marker));
1619 win32_vfprintf(FILE *fp, const char *format, va_list args)
1621 return (vfprintf(fp, format, args));
1625 win32_vprintf(const char *format, va_list args)
1627 return (vprintf(format, args));
1631 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
1633 return fread(buf, size, count, fp);
1637 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
1639 return fwrite(buf, size, count, fp);
1643 win32_fopen(const char *filename, const char *mode)
1645 if (stricmp(filename, "/dev/null")==0)
1646 return fopen("NUL", mode);
1647 return fopen(filename, mode);
1650 #ifndef USE_SOCKETS_AS_HANDLES
1652 #define fdopen my_fdopen
1656 win32_fdopen( int handle, const char *mode)
1658 return fdopen(handle, (char *) mode);
1662 win32_freopen( const char *path, const char *mode, FILE *stream)
1664 if (stricmp(path, "/dev/null")==0)
1665 return freopen("NUL", mode, stream);
1666 return freopen(path, mode, stream);
1670 win32_fclose(FILE *pf)
1672 return my_fclose(pf); /* defined in win32sck.c */
1676 win32_fputs(const char *s,FILE *pf)
1678 return fputs(s, pf);
1682 win32_fputc(int c,FILE *pf)
1688 win32_ungetc(int c,FILE *pf)
1690 return ungetc(c,pf);
1694 win32_getc(FILE *pf)
1700 win32_fileno(FILE *pf)
1706 win32_clearerr(FILE *pf)
1713 win32_fflush(FILE *pf)
1719 win32_ftell(FILE *pf)
1725 win32_fseek(FILE *pf,long offset,int origin)
1727 return fseek(pf, offset, origin);
1731 win32_fgetpos(FILE *pf,fpos_t *p)
1733 return fgetpos(pf, p);
1737 win32_fsetpos(FILE *pf,const fpos_t *p)
1739 return fsetpos(pf, p);
1743 win32_rewind(FILE *pf)
1763 win32_fstat(int fd,struct stat *sbufptr)
1765 return fstat(fd,sbufptr);
1769 win32_pipe(int *pfd, unsigned int size, int mode)
1771 return _pipe(pfd, size, mode);
1775 * a popen() clone that respects PERL5SHELL
1779 win32_popen(const char *command, const char *mode)
1781 #ifdef USE_RTL_POPEN
1782 return _popen(command, mode);
1790 /* establish which ends read and write */
1791 if (strchr(mode,'w')) {
1792 stdfd = 0; /* stdin */
1796 else if (strchr(mode,'r')) {
1797 stdfd = 1; /* stdout */
1804 /* set the correct mode */
1805 if (strchr(mode,'b'))
1807 else if (strchr(mode,'t'))
1810 ourmode = _fmode & (O_TEXT | O_BINARY);
1812 /* the child doesn't inherit handles */
1813 ourmode |= O_NOINHERIT;
1815 if (win32_pipe( p, 512, ourmode) == -1)
1818 /* save current stdfd */
1819 if ((oldfd = win32_dup(stdfd)) == -1)
1822 /* make stdfd go to child end of pipe (implicitly closes stdfd) */
1823 /* stdfd will be inherited by the child */
1824 if (win32_dup2(p[child], stdfd) == -1)
1827 /* close the child end in parent */
1828 win32_close(p[child]);
1830 /* start the child */
1831 if ((childpid = do_spawn_nowait((char*)command)) == -1)
1834 /* revert stdfd to whatever it was before */
1835 if (win32_dup2(oldfd, stdfd) == -1)
1838 /* close saved handle */
1841 sv_setiv(*av_fetch(w32_fdpid, p[parent], TRUE), childpid);
1843 /* we have an fd, return a file stream */
1844 return (win32_fdopen(p[parent], (char *)mode));
1847 /* we don't need to check for errors here */
1851 win32_dup2(oldfd, stdfd);
1856 #endif /* USE_RTL_POPEN */
1864 win32_pclose(FILE *pf)
1866 #ifdef USE_RTL_POPEN
1870 int childpid, status;
1873 sv = *av_fetch(w32_fdpid, win32_fileno(pf), TRUE);
1875 childpid = SvIVX(sv);
1887 if (win32_waitpid(childpid, &status, 0) == -1)
1892 #endif /* USE_RTL_POPEN */
1896 win32_rename(const char *oname, const char *newname)
1898 /* XXX despite what the documentation says about MoveFileEx(),
1899 * it doesn't work under Windows95!
1902 if (!MoveFileEx(oname,newname,
1903 MOVEFILE_COPY_ALLOWED|MOVEFILE_REPLACE_EXISTING)) {
1904 DWORD err = GetLastError();
1906 case ERROR_BAD_NET_NAME:
1907 case ERROR_BAD_NETPATH:
1908 case ERROR_BAD_PATHNAME:
1909 case ERROR_FILE_NOT_FOUND:
1910 case ERROR_FILENAME_EXCED_RANGE:
1911 case ERROR_INVALID_DRIVE:
1912 case ERROR_NO_MORE_FILES:
1913 case ERROR_PATH_NOT_FOUND:
1926 char tmpname[MAX_PATH+1];
1927 char dname[MAX_PATH+1];
1928 char *endname = Nullch;
1930 DWORD from_attr, to_attr;
1932 /* if oname doesn't exist, do nothing */
1933 from_attr = GetFileAttributes(oname);
1934 if (from_attr == 0xFFFFFFFF) {
1939 /* if newname exists, rename it to a temporary name so that we
1940 * don't delete it in case oname happens to be the same file
1941 * (but perhaps accessed via a different path)
1943 to_attr = GetFileAttributes(newname);
1944 if (to_attr != 0xFFFFFFFF) {
1945 /* if newname is a directory, we fail
1946 * XXX could overcome this with yet more convoluted logic */
1947 if (to_attr & FILE_ATTRIBUTE_DIRECTORY) {
1951 tmplen = strlen(newname);
1952 strcpy(tmpname,newname);
1953 endname = tmpname+tmplen;
1954 for (; endname > tmpname ; --endname) {
1955 if (*endname == '/' || *endname == '\\') {
1960 if (endname > tmpname)
1961 endname = strcpy(dname,tmpname);
1965 /* get a temporary filename in same directory
1966 * XXX is this really the best we can do? */
1967 if (!GetTempFileName((LPCTSTR)endname, "plr", 0, tmpname)) {
1971 DeleteFile(tmpname);
1973 retval = rename(newname, tmpname);
1980 /* rename oname to newname */
1981 retval = rename(oname, newname);
1983 /* if we created a temporary file before ... */
1984 if (endname != Nullch) {
1985 /* ...and rename succeeded, delete temporary file/directory */
1987 DeleteFile(tmpname);
1988 /* else restore it to what it was */
1990 (void)rename(tmpname, newname);
1997 win32_setmode(int fd, int mode)
1999 return setmode(fd, mode);
2003 win32_lseek(int fd, long offset, int origin)
2005 return lseek(fd, offset, origin);
2015 win32_open(const char *path, int flag, ...)
2021 pmode = va_arg(ap, int);
2024 if (stricmp(path, "/dev/null")==0)
2025 return open("NUL", flag, pmode);
2026 return open(path,flag,pmode);
2048 win32_dup2(int fd1,int fd2)
2050 return dup2(fd1,fd2);
2054 win32_read(int fd, void *buf, unsigned int cnt)
2056 return read(fd, buf, cnt);
2060 win32_write(int fd, const void *buf, unsigned int cnt)
2062 return write(fd, buf, cnt);
2066 win32_mkdir(const char *dir, int mode)
2068 return mkdir(dir); /* just ignore mode */
2072 win32_rmdir(const char *dir)
2078 win32_chdir(const char *dir)
2084 create_command_line(const char* command, const char * const *args)
2087 char *cmd, *ptr, *arg;
2088 STRLEN len = strlen(command) + 1;
2090 for (index = 0; (ptr = (char*)args[index]) != NULL; ++index)
2091 len += strlen(ptr) + 1;
2093 New(1310, cmd, len, char);
2095 strcpy(ptr, command);
2099 for (index = 0; (arg = (char*)args[index]) != NULL; ++index) {
2102 if ((char*)args[index+1] != NULL)
2110 qualified_path(const char *cmd)
2113 char *fullcmd, *curfullcmd;
2119 fullcmd = (char*)cmd;
2121 if (*fullcmd == '/' || *fullcmd == '\\')
2128 pathstr = win32_getenv("PATH");
2129 New(0, fullcmd, MAX_PATH+1, char);
2130 curfullcmd = fullcmd;
2135 /* start by appending the name to the current prefix */
2136 strcpy(curfullcmd, cmd);
2137 curfullcmd += cmdlen;
2139 /* if it doesn't end with '.', or has no extension, try adding
2140 * a trailing .exe first */
2141 if (cmd[cmdlen-1] != '.'
2142 && (cmdlen < 4 || cmd[cmdlen-4] != '.'))
2144 strcpy(curfullcmd, ".exe");
2145 res = GetFileAttributes(fullcmd);
2146 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
2151 /* that failed, try the bare name */
2152 res = GetFileAttributes(fullcmd);
2153 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
2156 /* quit if no other path exists, or if cmd already has path */
2157 if (!pathstr || !*pathstr || has_slash)
2160 /* skip leading semis */
2161 while (*pathstr == ';')
2164 /* build a new prefix from scratch */
2165 curfullcmd = fullcmd;
2166 while (*pathstr && *pathstr != ';') {
2167 if (*pathstr == '"') { /* foo;"baz;etc";bar */
2168 pathstr++; /* skip initial '"' */
2169 while (*pathstr && *pathstr != '"') {
2170 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
2171 *curfullcmd++ = *pathstr;
2175 pathstr++; /* skip trailing '"' */
2178 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
2179 *curfullcmd++ = *pathstr;
2184 pathstr++; /* skip trailing semi */
2185 if (curfullcmd > fullcmd /* append a dir separator */
2186 && curfullcmd[-1] != '/' && curfullcmd[-1] != '\\')
2188 *curfullcmd++ = '\\';
2196 /* XXX this needs to be made more compatible with the spawnvp()
2197 * provided by the various RTLs. In particular, searching for
2198 * *.{com,bat,cmd} files (as done by the RTLs) is unimplemented.
2199 * This doesn't significantly affect perl itself, because we
2200 * always invoke things using PERL5SHELL if a direct attempt to
2201 * spawn the executable fails.
2203 * XXX splitting and rejoining the commandline between do_aspawn()
2204 * and win32_spawnvp() could also be avoided.
2208 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
2210 #ifdef USE_RTL_SPAWNVP
2211 return spawnvp(mode, cmdname, (char * const *)argv);
2214 STARTUPINFO StartupInfo;
2215 PROCESS_INFORMATION ProcessInformation;
2218 char *cmd = create_command_line(cmdname, strcmp(cmdname, argv[0]) == 0
2220 char *fullcmd = Nullch;
2223 case P_NOWAIT: /* asynch + remember result */
2224 if (w32_num_children >= MAXIMUM_WAIT_OBJECTS) {
2230 case P_WAIT: /* synchronous execution */
2232 default: /* invalid mode */
2237 memset(&StartupInfo,0,sizeof(StartupInfo));
2238 StartupInfo.cb = sizeof(StartupInfo);
2239 StartupInfo.wShowWindow = SW_SHOWDEFAULT;
2242 if (!CreateProcess(cmdname, /* search PATH to find executable */
2243 cmd, /* executable, and its arguments */
2244 NULL, /* process attributes */
2245 NULL, /* thread attributes */
2246 TRUE, /* inherit handles */
2247 create, /* creation flags */
2248 NULL, /* inherit environment */
2249 NULL, /* inherit cwd */
2251 &ProcessInformation))
2253 /* initial NULL argument to CreateProcess() does a PATH
2254 * search, but it always first looks in the directory
2255 * where the current process was started, which behavior
2256 * is undesirable for backward compatibility. So we
2257 * jump through our own hoops by picking out the path
2258 * we really want it to use. */
2260 fullcmd = qualified_path(cmdname);
2271 if (mode == P_NOWAIT) {
2272 /* asynchronous spawn -- store handle, return PID */
2273 w32_child_handles[w32_num_children] = ProcessInformation.hProcess;
2274 ret = w32_child_pids[w32_num_children] = ProcessInformation.dwProcessId;
2278 WaitForSingleObject(ProcessInformation.hProcess, INFINITE);
2279 GetExitCodeProcess(ProcessInformation.hProcess, &ret);
2280 CloseHandle(ProcessInformation.hProcess);
2283 CloseHandle(ProcessInformation.hThread);
2292 win32_execv(const char *cmdname, const char *const *argv)
2294 return execv(cmdname, (char *const *)argv);
2298 win32_execvp(const char *cmdname, const char *const *argv)
2300 return execvp(cmdname, (char *const *)argv);
2304 win32_perror(const char *str)
2310 win32_setbuf(FILE *pf, char *buf)
2316 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
2318 return setvbuf(pf, buf, type, size);
2322 win32_flushall(void)
2328 win32_fcloseall(void)
2334 win32_fgets(char *s, int n, FILE *pf)
2336 return fgets(s, n, pf);
2346 win32_fgetc(FILE *pf)
2352 win32_putc(int c, FILE *pf)
2358 win32_puts(const char *s)
2370 win32_putchar(int c)
2377 #ifndef USE_PERL_SBRK
2379 static char *committed = NULL;
2380 static char *base = NULL;
2381 static char *reserved = NULL;
2382 static char *brk = NULL;
2383 static DWORD pagesize = 0;
2384 static DWORD allocsize = 0;
2392 GetSystemInfo(&info);
2393 /* Pretend page size is larger so we don't perpetually
2394 * call the OS to commit just one page ...
2396 pagesize = info.dwPageSize << 3;
2397 allocsize = info.dwAllocationGranularity;
2399 /* This scheme fails eventually if request for contiguous
2400 * block is denied so reserve big blocks - this is only
2401 * address space not memory ...
2403 if (brk+need >= reserved)
2405 DWORD size = 64*1024*1024;
2407 if (committed && reserved && committed < reserved)
2409 /* Commit last of previous chunk cannot span allocations */
2410 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
2412 committed = reserved;
2414 /* Reserve some (more) space
2415 * Note this is a little sneaky, 1st call passes NULL as reserved
2416 * so lets system choose where we start, subsequent calls pass
2417 * the old end address so ask for a contiguous block
2419 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
2422 reserved = addr+size;
2437 if (brk > committed)
2439 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
2440 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
2455 win32_malloc(size_t size)
2457 return malloc(size);
2461 win32_calloc(size_t numitems, size_t size)
2463 return calloc(numitems,size);
2467 win32_realloc(void *block, size_t size)
2469 return realloc(block,size);
2473 win32_free(void *block)
2480 win32_open_osfhandle(long handle, int flags)
2482 return _open_osfhandle(handle, flags);
2486 win32_get_osfhandle(int fd)
2488 return _get_osfhandle(fd);
2499 SV *sv = sv_newmortal();
2500 /* Make one call with zero size - return value is required size */
2501 DWORD len = GetCurrentDirectory((DWORD)0,NULL);
2502 SvUPGRADE(sv,SVt_PV);
2504 SvCUR(sv) = GetCurrentDirectory((DWORD) SvLEN(sv), SvPVX(sv));
2507 * then it worked, set PV valid,
2508 * else leave it 'undef'
2524 croak("usage: Win32::SetCurrentDirectory($cwd)");
2525 if (SetCurrentDirectory(SvPV_nolen(ST(0))))
2532 XS(w32_GetNextAvailDrive)
2536 char root[] = "_:\\";
2541 if (GetDriveType(root) == 1) {
2550 XS(w32_GetLastError)
2554 XSRETURN_IV(GetLastError());
2558 XS(w32_SetLastError)
2562 croak("usage: Win32::SetLastError($error)");
2563 SetLastError(SvIV(ST(0)));
2571 char *name = getlogin_buffer;
2572 DWORD size = sizeof(getlogin_buffer);
2574 if (GetUserName(name,&size)) {
2575 /* size includes NULL */
2576 ST(0) = sv_2mortal(newSVpvn(name,size-1));
2586 char name[MAX_COMPUTERNAME_LENGTH+1];
2587 DWORD size = sizeof(name);
2589 if (GetComputerName(name,&size)) {
2590 /* size does NOT include NULL :-( */
2591 ST(0) = sv_2mortal(newSVpvn(name,size));
2602 #ifndef HAS_NETWKSTAGETINFO
2603 /* mingw32 (and Win95) don't have NetWksta*(), so do it the old way */
2605 DWORD size = sizeof(name);
2607 if (GetUserName(name,&size)) {
2609 DWORD sidlen = sizeof(sid);
2611 DWORD dnamelen = sizeof(dname);
2613 if (LookupAccountName(NULL, name, (PSID)&sid, &sidlen,
2614 dname, &dnamelen, &snu)) {
2615 XSRETURN_PV(dname); /* all that for this */
2619 /* this way is more reliable, in case user has a local account.
2620 * XXX need dynamic binding of netapi32.dll symbols or this will fail on
2621 * Win95. Probably makes more sense to move it into libwin32. */
2623 DWORD dnamelen = sizeof(dname);
2624 PWKSTA_INFO_100 pwi;
2626 if (NERR_Success == NetWkstaGetInfo(NULL, 100, (LPBYTE*)&pwi)) {
2627 if (pwi->wki100_langroup && *(pwi->wki100_langroup)) {
2628 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_langroup,
2629 -1, (LPSTR)dname, dnamelen, NULL, NULL);
2632 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_computername,
2633 -1, (LPSTR)dname, dnamelen, NULL, NULL);
2635 NetApiBufferFree(pwi);
2647 DWORD flags, filecomplen;
2648 if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
2649 &flags, fsname, sizeof(fsname))) {
2650 if (GIMME_V == G_ARRAY) {
2651 XPUSHs(sv_2mortal(newSVpvn(fsname,strlen(fsname))));
2652 XPUSHs(sv_2mortal(newSViv(flags)));
2653 XPUSHs(sv_2mortal(newSViv(filecomplen)));
2658 XSRETURN_PV(fsname);
2664 XS(w32_GetOSVersion)
2667 OSVERSIONINFO osver;
2669 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
2670 if (GetVersionEx(&osver)) {
2671 XPUSHs(newSVpvn(osver.szCSDVersion, strlen(osver.szCSDVersion)));
2672 XPUSHs(newSViv(osver.dwMajorVersion));
2673 XPUSHs(newSViv(osver.dwMinorVersion));
2674 XPUSHs(newSViv(osver.dwBuildNumber));
2675 XPUSHs(newSViv(osver.dwPlatformId));
2687 XSRETURN_IV(IsWinNT());
2695 XSRETURN_IV(IsWin95());
2699 XS(w32_FormatMessage)
2706 croak("usage: Win32::FormatMessage($errno)");
2708 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
2709 &source, SvIV(ST(0)), 0,
2710 msgbuf, sizeof(msgbuf)-1, NULL))
2711 XSRETURN_PV(msgbuf);
2721 PROCESS_INFORMATION stProcInfo;
2722 STARTUPINFO stStartInfo;
2723 BOOL bSuccess = FALSE;
2726 croak("usage: Win32::Spawn($cmdName, $args, $PID)");
2728 cmd = SvPV_nolen(ST(0));
2729 args = SvPV_nolen(ST(1));
2731 memset(&stStartInfo, 0, sizeof(stStartInfo)); /* Clear the block */
2732 stStartInfo.cb = sizeof(stStartInfo); /* Set the structure size */
2733 stStartInfo.dwFlags = STARTF_USESHOWWINDOW; /* Enable wShowWindow control */
2734 stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE; /* Start min (normal) */
2737 cmd, /* Image path */
2738 args, /* Arguments for command line */
2739 NULL, /* Default process security */
2740 NULL, /* Default thread security */
2741 FALSE, /* Must be TRUE to use std handles */
2742 NORMAL_PRIORITY_CLASS, /* No special scheduling */
2743 NULL, /* Inherit our environment block */
2744 NULL, /* Inherit our currrent directory */
2745 &stStartInfo, /* -> Startup info */
2746 &stProcInfo)) /* <- Process info (if OK) */
2748 CloseHandle(stProcInfo.hThread);/* library source code does this. */
2749 sv_setiv(ST(2), stProcInfo.dwProcessId);
2752 XSRETURN_IV(bSuccess);
2756 XS(w32_GetTickCount)
2760 XSRETURN_IV(GetTickCount());
2764 XS(w32_GetShortPathName)
2771 croak("usage: Win32::GetShortPathName($longPathName)");
2773 shortpath = sv_mortalcopy(ST(0));
2774 SvUPGRADE(shortpath, SVt_PV);
2775 /* src == target is allowed */
2777 len = GetShortPathName(SvPVX(shortpath),
2780 } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
2782 SvCUR_set(shortpath,len);
2790 XS(w32_GetFullPathName)
2799 croak("usage: Win32::GetFullPathName($filename)");
2802 fullpath = sv_mortalcopy(filename);
2803 SvUPGRADE(fullpath, SVt_PV);
2805 len = GetFullPathName(SvPVX(filename),
2809 } while (len >= SvLEN(fullpath) && sv_grow(fullpath,len+1));
2811 if (GIMME_V == G_ARRAY) {
2813 XST_mPV(1,filepart);
2814 len = filepart - SvPVX(fullpath);
2817 SvCUR_set(fullpath,len);
2829 croak("usage: Win32::Sleep($milliseconds)");
2835 Perl_init_os_extras()
2837 char *file = __FILE__;
2840 w32_perlshell_tokens = Nullch;
2841 w32_perlshell_items = -1;
2842 w32_fdpid = newAV(); /* XXX needs to be in Perl_win32_init()? */
2843 New(1313, w32_children, 1, child_tab);
2844 w32_num_children = 0;
2846 /* these names are Activeware compatible */
2847 newXS("Win32::GetCwd", w32_GetCwd, file);
2848 newXS("Win32::SetCwd", w32_SetCwd, file);
2849 newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
2850 newXS("Win32::GetLastError", w32_GetLastError, file);
2851 newXS("Win32::SetLastError", w32_SetLastError, file);
2852 newXS("Win32::LoginName", w32_LoginName, file);
2853 newXS("Win32::NodeName", w32_NodeName, file);
2854 newXS("Win32::DomainName", w32_DomainName, file);
2855 newXS("Win32::FsType", w32_FsType, file);
2856 newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
2857 newXS("Win32::IsWinNT", w32_IsWinNT, file);
2858 newXS("Win32::IsWin95", w32_IsWin95, file);
2859 newXS("Win32::FormatMessage", w32_FormatMessage, file);
2860 newXS("Win32::Spawn", w32_Spawn, file);
2861 newXS("Win32::GetTickCount", w32_GetTickCount, file);
2862 newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
2863 newXS("Win32::GetFullPathName", w32_GetFullPathName, file);
2864 newXS("Win32::Sleep", w32_Sleep, file);
2866 /* XXX Bloat Alert! The following Activeware preloads really
2867 * ought to be part of Win32::Sys::*, so they're not included
2870 /* LookupAccountName
2872 * InitiateSystemShutdown
2873 * AbortSystemShutdown
2874 * ExpandEnvrironmentStrings
2879 Perl_win32_init(int *argcp, char ***argvp)
2881 /* Disable floating point errors, Perl will trap the ones we
2882 * care about. VC++ RTL defaults to switching these off
2883 * already, but the Borland RTL doesn't. Since we don't
2884 * want to be at the vendor's whim on the default, we set
2885 * it explicitly here.
2887 #if !defined(_ALPHA_) && !defined(__GNUC__)
2888 _control87(MCW_EM, MCW_EM);
2893 #ifdef USE_BINMODE_SCRIPTS
2896 win32_strip_return(SV *sv)
2898 char *s = SvPVX(sv);
2899 char *e = s+SvCUR(sv);
2903 if (*s == '\r' && s[1] == '\n')
2913 SvCUR_set(sv,d-SvPVX(sv));