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)
41 #include "patchlevel.h"
45 extern CPerlObj* pPerl;
53 /* assert.h conflicts with #define of assert in perl.h */
60 #if defined(_MSC_VER) || defined(__MINGW32__)
61 #include <sys/utime.h>
67 /* Mingw32 defaults to globing command line
68 * So we turn it off like this:
75 #define EXECF_SPAWN_NOWAIT 3
77 #if defined(PERL_OBJECT)
78 #undef win32_get_privlib
79 #define win32_get_privlib g_win32_get_privlib
80 #undef win32_get_sitelib
81 #define win32_get_sitelib g_win32_get_sitelib
83 #define do_aspawn g_do_aspawn
85 #define do_spawn g_do_spawn
87 #define do_exec g_do_exec
89 #define getlogin g_getlogin
92 static DWORD os_id(void);
93 static void get_shell(void);
94 static long tokenize(char *str, char **dest, char ***destv);
95 int do_spawn2(char *cmd, int exectype);
96 static BOOL has_shell_metachars(char *ptr);
97 static long filetime_to_clock(PFILETIME ft);
98 static BOOL filetime_from_time(PFILETIME ft, time_t t);
99 static char * get_emd_part(char *leading, char *trailing, ...);
100 static void remove_dead_process(HANDLE deceased);
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", (double) 5 + ((double) PATCHLEVEL / (double) 1000));
194 GetModuleFileName((HMODULE)((w32_perldll_handle == INVALID_HANDLE_VALUE)
195 ? GetModuleHandle(NULL) : w32_perldll_handle),
196 mod_name, sizeof(mod_name));
197 ptr = strrchr(mod_name, '\\');
198 while (ptr && strip) {
199 /* look for directories to skip back */
202 ptr = strrchr(mod_name, '\\');
203 if (!ptr || stricmp(ptr+1, strip) != 0) {
204 if(!(*strip == '5' && *(ptr+1) == '5' && strncmp(strip, base, 5) == 0
205 && strncmp(ptr+1, base, 5) == 0)) {
210 strip = va_arg(ap, char *);
218 strcpy(++ptr, trailing_path);
220 /* only add directory if it exists */
221 if(GetFileAttributes(mod_name) != (DWORD) -1) {
222 /* directory exists */
223 newsize = strlen(mod_name) + 1;
225 oldsize = strlen(prev_path) + 1;
226 newsize += oldsize; /* includes plus 1 for ';' */
227 Renew(prev_path, newsize, char);
228 prev_path[oldsize-1] = ';';
229 strcpy(&prev_path[oldsize], mod_name);
232 New(1311, prev_path, newsize, char);
233 strcpy(prev_path, mod_name);
241 win32_get_privlib(char *pl)
243 char *stdlib = "lib";
244 char buffer[MAX_PATH+1];
248 /* $stdlib = $HKCU{"lib-$]"} || $HKLM{"lib-$]"} || $HKCU{"lib"} || $HKLM{"lib"} || ""; */
249 sprintf(buffer, "%s-%s", stdlib, pl);
250 path = GetRegStr(buffer, &path, &datalen);
252 path = GetRegStr(stdlib, &path, &datalen);
254 /* $stdlib .= ";$EMD/../../lib" */
255 return get_emd_part(path, stdlib, ARCHNAME, "bin", Nullch);
259 win32_get_sitelib(char *pl)
261 char *sitelib = "sitelib";
263 char pathstr[MAX_PATH+1];
265 char *path1 = Nullch;
266 char *path2 = Nullch;
269 /* $HKCU{"sitelib-$]"} || $HKLM{"sitelib-$]"} . ---; */
270 sprintf(regstr, "%s-%s", sitelib, pl);
271 path1 = GetRegStr(regstr, &path1, &datalen);
274 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/site/$]/lib"; */
275 sprintf(pathstr, "site\\%s\\lib", pl);
276 path1 = get_emd_part(path1, pathstr, ARCHNAME, "bin", pl, Nullch);
278 /* $HKCU{'sitelib'} || $HKLM{'sitelib'} . ---; */
279 path2 = GetRegStr(sitelib, &path2, &datalen);
282 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/site/lib"; */
283 path2 = get_emd_part(path2, "site\\lib", ARCHNAME, "bin", pl, Nullch);
292 newsize = len + strlen(path2) + 2; /* plus one for ';' */
294 Renew(path1, newsize, char);
296 strcpy(&path1[len], path2);
304 has_shell_metachars(char *ptr)
310 * Scan string looking for redirection (< or >) or pipe
311 * characters (|) that are not in a quoted string.
312 * Shell variable interpolation (%VAR%) can also happen inside strings.
344 #if !defined(PERL_OBJECT)
345 /* since the current process environment is being updated in util.c
346 * the library functions will get the correct environment
349 my_popen(char *cmd, char *mode)
352 #define fixcmd(x) { \
353 char *pspace = strchr((x),' '); \
356 while (p < pspace) { \
367 win32_fflush(stdout);
368 win32_fflush(stderr);
369 return win32_popen(cmd, mode);
373 my_pclose(PerlIO *fp)
375 return win32_pclose(fp);
382 static OSVERSIONINFO osver;
384 if (osver.dwPlatformId != w32_platform) {
385 memset(&osver, 0, sizeof(OSVERSIONINFO));
386 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
387 GetVersionEx(&osver);
388 w32_platform = osver.dwPlatformId;
390 return (w32_platform);
393 /* Tokenize a string. Words are null-separated, and the list
394 * ends with a doubled null. Any character (except null and
395 * including backslash) may be escaped by preceding it with a
396 * backslash (the backslash will be stripped).
397 * Returns number of words in result buffer.
400 tokenize(char *str, char **dest, char ***destv)
402 char *retstart = Nullch;
403 char **retvstart = 0;
406 int slen = strlen(str);
408 register char **retv;
409 New(1307, ret, slen+2, char);
410 New(1308, retv, (slen+3)/2, char*);
418 if (*ret == '\\' && *str)
420 else if (*ret == ' ') {
436 retvstart[items] = Nullch;
448 if (!w32_perlshell_tokens) {
449 /* we don't use COMSPEC here for two reasons:
450 * 1. the same reason perl on UNIX doesn't use SHELL--rampant and
451 * uncontrolled unportability of the ensuing scripts.
452 * 2. PERL5SHELL could be set to a shell that may not be fit for
453 * interactive use (which is what most programs look in COMSPEC
456 char* defaultshell = (IsWinNT() ? "cmd.exe /x/c" : "command.com /c");
457 char *usershell = getenv("PERL5SHELL");
458 w32_perlshell_items = tokenize(usershell ? usershell : defaultshell,
459 &w32_perlshell_tokens,
465 do_aspawn(void *vreally, void **vmark, void **vsp)
467 SV *really = (SV*)vreally;
468 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(*mark, n_a)))
496 status = win32_spawnvp(flag,
497 (const char*)(really ? SvPV(really,n_a) : 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(really,n_a) : 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)
847 remove_dead_process(HANDLE deceased)
851 for (child = 0 ; child < w32_num_children ; ++child) {
852 if (w32_child_pids[child] == deceased) {
853 Copy(&w32_child_pids[child+1], &w32_child_pids[child],
854 (w32_num_children-child-1), HANDLE);
863 win32_kill(int pid, int sig)
866 HANDLE hProcess= OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid);
868 HANDLE hProcess = (HANDLE) pid;
871 if (hProcess == NULL) {
872 croak("kill process failed!\n");
875 if (!TerminateProcess(hProcess, sig))
876 croak("kill process failed!\n");
877 CloseHandle(hProcess);
879 /* WaitForMultipleObjects() on a pid that was killed returns error
880 * so if we know the pid is gone we remove it from process list */
881 remove_dead_process(hProcess);
890 DllExport unsigned int
891 win32_sleep(unsigned int t)
898 win32_stat(const char *path, struct stat *buffer)
901 const char *p = path;
902 int l = strlen(path);
906 switch(path[l - 1]) {
909 if (path[l - 2] != ':') {
910 strncpy(t, path, l - 1);
916 res = stat(p,buffer);
918 /* CRT is buggy on sharenames, so make sure it really isn't.
919 * XXX using GetFileAttributesEx() will enable us to set
920 * buffer->st_*time (but note that's not available on the
921 * Windows of 1995) */
922 DWORD r = GetFileAttributes(p);
923 if (r != 0xffffffff && (r & FILE_ATTRIBUTE_DIRECTORY)) {
924 buffer->st_mode |= S_IFDIR | S_IREAD;
926 if (!(r & FILE_ATTRIBUTE_READONLY))
927 buffer->st_mode |= S_IWRITE | S_IEXEC;
932 if (l == 3 && path[l-2] == ':'
933 && (path[l-1] == '\\' || path[l-1] == '/'))
935 /* The drive can be inaccessible, some _stat()s are buggy */
936 if (!GetVolumeInformation(path,NULL,0,NULL,NULL,NULL,NULL,0)) {
942 if (S_ISDIR(buffer->st_mode))
943 buffer->st_mode |= S_IWRITE | S_IEXEC;
944 else if (S_ISREG(buffer->st_mode)) {
945 if (l >= 4 && path[l-4] == '.') {
946 const char *e = path + l - 3;
947 if (strnicmp(e,"exe",3)
948 && strnicmp(e,"bat",3)
949 && strnicmp(e,"com",3)
950 && (IsWin95() || strnicmp(e,"cmd",3)))
951 buffer->st_mode &= ~S_IEXEC;
953 buffer->st_mode |= S_IEXEC;
956 buffer->st_mode &= ~S_IEXEC;
963 #ifndef USE_WIN32_RTL_ENV
966 win32_getenv(const char *name)
968 static char *curitem = Nullch; /* XXX threadead */
969 static DWORD curlen = 0; /* XXX threadead */
973 New(1305,curitem,curlen,char);
976 needlen = GetEnvironmentVariable(name,curitem,curlen);
978 while (needlen > curlen) {
979 Renew(curitem,needlen,char);
981 needlen = GetEnvironmentVariable(name,curitem,curlen);
985 /* allow any environment variables that begin with 'PERL'
986 to be stored in the registry */
990 if (strncmp(name, "PERL", 4) == 0) {
996 curitem = GetRegStr(name, &curitem, &curlen);
999 if (curitem && *curitem == '\0')
1006 win32_putenv(const char *name)
1012 New(1309,curitem,strlen(name)+1,char);
1013 strcpy(curitem, name);
1014 val = strchr(curitem, '=');
1016 /* The sane way to deal with the environment.
1017 * Has these advantages over putenv() & co.:
1018 * * enables us to store a truly empty value in the
1019 * environment (like in UNIX).
1020 * * we don't have to deal with RTL globals, bugs and leaks.
1022 * Why you may want to enable USE_WIN32_RTL_ENV:
1023 * * environ[] and RTL functions will not reflect changes,
1024 * which might be an issue if extensions want to access
1025 * the env. via RTL. This cuts both ways, since RTL will
1026 * not see changes made by extensions that call the Win32
1027 * functions directly, either.
1031 if(SetEnvironmentVariable(curitem, *val ? val : NULL))
1042 filetime_to_clock(PFILETIME ft)
1044 __int64 qw = ft->dwHighDateTime;
1046 qw |= ft->dwLowDateTime;
1047 qw /= 10000; /* File time ticks at 0.1uS, clock at 1mS */
1052 win32_times(struct tms *timebuf)
1057 if (GetProcessTimes(GetCurrentProcess(), &dummy, &dummy,
1059 timebuf->tms_utime = filetime_to_clock(&user);
1060 timebuf->tms_stime = filetime_to_clock(&kernel);
1061 timebuf->tms_cutime = 0;
1062 timebuf->tms_cstime = 0;
1065 /* That failed - e.g. Win95 fallback to clock() */
1066 clock_t t = clock();
1067 timebuf->tms_utime = t;
1068 timebuf->tms_stime = 0;
1069 timebuf->tms_cutime = 0;
1070 timebuf->tms_cstime = 0;
1075 /* fix utime() so it works on directories in NT
1076 * thanks to Jan Dubois <jan.dubois@ibm.net>
1079 filetime_from_time(PFILETIME pFileTime, time_t Time)
1081 struct tm *pTM = gmtime(&Time);
1082 SYSTEMTIME SystemTime;
1087 SystemTime.wYear = pTM->tm_year + 1900;
1088 SystemTime.wMonth = pTM->tm_mon + 1;
1089 SystemTime.wDay = pTM->tm_mday;
1090 SystemTime.wHour = pTM->tm_hour;
1091 SystemTime.wMinute = pTM->tm_min;
1092 SystemTime.wSecond = pTM->tm_sec;
1093 SystemTime.wMilliseconds = 0;
1095 return SystemTimeToFileTime(&SystemTime, pFileTime);
1099 win32_utime(const char *filename, struct utimbuf *times)
1105 struct utimbuf TimeBuffer;
1107 int rc = utime(filename,times);
1108 /* EACCES: path specifies directory or readonly file */
1109 if (rc == 0 || errno != EACCES /* || !IsWinNT() */)
1112 if (times == NULL) {
1113 times = &TimeBuffer;
1114 time(×->actime);
1115 times->modtime = times->actime;
1118 /* This will (and should) still fail on readonly files */
1119 handle = CreateFile(filename, GENERIC_READ | GENERIC_WRITE,
1120 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1121 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1122 if (handle == INVALID_HANDLE_VALUE)
1125 if (GetFileTime(handle, &ftCreate, &ftAccess, &ftWrite) &&
1126 filetime_from_time(&ftAccess, times->actime) &&
1127 filetime_from_time(&ftWrite, times->modtime) &&
1128 SetFileTime(handle, &ftCreate, &ftAccess, &ftWrite))
1133 CloseHandle(handle);
1138 win32_waitpid(int pid, int *status, int flags)
1142 return win32_wait(status);
1144 rc = cwait(status, pid, WAIT_CHILD);
1145 /* cwait() returns "correctly" on Borland */
1146 #ifndef __BORLANDC__
1150 remove_dead_process((HANDLE)pid);
1152 return rc >= 0 ? pid : rc;
1156 win32_wait(int *status)
1159 return wait(status);
1161 /* XXX this wait emulation only knows about processes
1162 * spawned via win32_spawnvp(P_NOWAIT, ...).
1165 DWORD exitcode, waitcode;
1167 if (!w32_num_children) {
1172 /* if a child exists, wait for it to die */
1173 waitcode = WaitForMultipleObjects(w32_num_children,
1177 if (waitcode != WAIT_FAILED) {
1178 if (waitcode >= WAIT_ABANDONED_0
1179 && waitcode < WAIT_ABANDONED_0 + w32_num_children)
1180 i = waitcode - WAIT_ABANDONED_0;
1182 i = waitcode - WAIT_OBJECT_0;
1183 if (GetExitCodeProcess(w32_child_pids[i], &exitcode) ) {
1184 CloseHandle(w32_child_pids[i]);
1185 *status = (int)((exitcode & 0xff) << 8);
1186 retval = (int)w32_child_pids[i];
1187 Copy(&w32_child_pids[i+1], &w32_child_pids[i],
1188 (w32_num_children-i-1), HANDLE);
1195 errno = GetLastError();
1201 static UINT timerid = 0;
1203 static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
1205 KillTimer(NULL,timerid);
1210 DllExport unsigned int
1211 win32_alarm(unsigned int sec)
1214 * the 'obvious' implentation is SetTimer() with a callback
1215 * which does whatever receiving SIGALRM would do
1216 * we cannot use SIGALRM even via raise() as it is not
1217 * one of the supported codes in <signal.h>
1219 * Snag is unless something is looking at the message queue
1220 * nothing happens :-(
1224 timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
1226 croak("Cannot set timer");
1232 KillTimer(NULL,timerid);
1239 #if defined(HAVE_DES_FCRYPT) || defined(PERL_OBJECT)
1240 #ifdef HAVE_DES_FCRYPT
1241 extern char * des_fcrypt(const char *txt, const char *salt, char *cbuf);
1245 win32_crypt(const char *txt, const char *salt)
1247 #ifdef HAVE_DES_FCRYPT
1249 return des_fcrypt(txt, salt, crypt_buffer);
1251 die("The crypt() function is unimplemented due to excessive paranoia.");
1257 #ifdef USE_FIXED_OSFHANDLE
1259 EXTERN_C int __cdecl _alloc_osfhnd(void);
1260 EXTERN_C int __cdecl _set_osfhnd(int fh, long value);
1261 EXTERN_C void __cdecl _lock_fhandle(int);
1262 EXTERN_C void __cdecl _unlock_fhandle(int);
1263 EXTERN_C void __cdecl _unlock(int);
1265 #if (_MSC_VER >= 1000)
1267 long osfhnd; /* underlying OS file HANDLE */
1268 char osfile; /* attributes of file (e.g., open in text mode?) */
1269 char pipech; /* one char buffer for handles opened on pipes */
1270 #if defined (_MT) && !defined (DLL_FOR_WIN32S)
1272 CRITICAL_SECTION lock;
1273 #endif /* defined (_MT) && !defined (DLL_FOR_WIN32S) */
1276 EXTERN_C ioinfo * __pioinfo[];
1278 #define IOINFO_L2E 5
1279 #define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
1280 #define _pioinfo(i) (__pioinfo[i >> IOINFO_L2E] + (i & (IOINFO_ARRAY_ELTS - 1)))
1281 #define _osfile(i) (_pioinfo(i)->osfile)
1283 #else /* (_MSC_VER >= 1000) */
1284 extern char _osfile[];
1285 #endif /* (_MSC_VER >= 1000) */
1287 #define FOPEN 0x01 /* file handle open */
1288 #define FAPPEND 0x20 /* file handle opened O_APPEND */
1289 #define FDEV 0x40 /* file handle refers to device */
1290 #define FTEXT 0x80 /* file handle is in text mode */
1292 #define _STREAM_LOCKS 26 /* Table of stream locks */
1293 #define _LAST_STREAM_LOCK (_STREAM_LOCKS+_NSTREAM_-1) /* Last stream lock */
1294 #define _FH_LOCKS (_LAST_STREAM_LOCK+1) /* Table of fh locks */
1297 *int my_open_osfhandle(long osfhandle, int flags) - open C Runtime file handle
1300 * This function allocates a free C Runtime file handle and associates
1301 * it with the Win32 HANDLE specified by the first parameter. This is a
1302 * temperary fix for WIN95's brain damage GetFileType() error on socket
1303 * we just bypass that call for socket
1306 * long osfhandle - Win32 HANDLE to associate with C Runtime file handle.
1307 * int flags - flags to associate with C Runtime file handle.
1310 * returns index of entry in fh, if successful
1311 * return -1, if no free entry is found
1315 *******************************************************************************/
1318 my_open_osfhandle(long osfhandle, int flags)
1321 char fileflags; /* _osfile flags */
1323 /* copy relevant flags from second parameter */
1326 if (flags & O_APPEND)
1327 fileflags |= FAPPEND;
1332 /* attempt to allocate a C Runtime file handle */
1333 if ((fh = _alloc_osfhnd()) == -1) {
1334 errno = EMFILE; /* too many open files */
1335 _doserrno = 0L; /* not an OS error */
1336 return -1; /* return error to caller */
1339 /* the file is open. now, set the info in _osfhnd array */
1340 _set_osfhnd(fh, osfhandle);
1342 fileflags |= FOPEN; /* mark as open */
1344 #if (_MSC_VER >= 1000)
1345 _osfile(fh) = fileflags; /* set osfile entry */
1346 _unlock_fhandle(fh);
1348 _osfile[fh] = fileflags; /* set osfile entry */
1349 _unlock(fh+_FH_LOCKS); /* unlock handle */
1352 return fh; /* return handle */
1355 #define _open_osfhandle my_open_osfhandle
1356 #endif /* USE_FIXED_OSFHANDLE */
1358 /* simulate flock by locking a range on the file */
1360 #define LK_ERR(f,i) ((f) ? (i = 0) : (errno = GetLastError()))
1361 #define LK_LEN 0xffff0000
1364 win32_flock(int fd, int oper)
1371 croak("flock() unimplemented on this platform");
1374 fh = (HANDLE)_get_osfhandle(fd);
1375 memset(&o, 0, sizeof(o));
1378 case LOCK_SH: /* shared lock */
1379 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
1381 case LOCK_EX: /* exclusive lock */
1382 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
1384 case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
1385 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
1387 case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
1388 LK_ERR(LockFileEx(fh,
1389 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
1390 0, LK_LEN, 0, &o),i);
1392 case LOCK_UN: /* unlock lock */
1393 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, 0, &o),i);
1395 default: /* unknown */
1406 * redirected io subsystem for all XS modules
1419 return (&(_environ));
1422 /* the rest are the remapped stdio routines */
1442 win32_ferror(FILE *fp)
1444 return (ferror(fp));
1449 win32_feof(FILE *fp)
1455 * Since the errors returned by the socket error function
1456 * WSAGetLastError() are not known by the library routine strerror
1457 * we have to roll our own.
1461 win32_strerror(int e)
1463 #ifndef __BORLANDC__ /* Borland intolerance */
1464 extern int sys_nerr;
1468 if (e < 0 || e > sys_nerr) {
1473 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
1474 strerror_buffer, sizeof(strerror_buffer), NULL) == 0)
1475 strcpy(strerror_buffer, "Unknown Error");
1477 return strerror_buffer;
1483 win32_str_os_error(void *sv, DWORD dwErr)
1487 dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
1488 |FORMAT_MESSAGE_IGNORE_INSERTS
1489 |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
1490 dwErr, 0, (char *)&sMsg, 1, NULL);
1492 while (0 < dwLen && isspace(sMsg[--dwLen]))
1494 if ('.' != sMsg[dwLen])
1499 sMsg = (char*)LocalAlloc(0, 64/**sizeof(TCHAR)*/);
1500 dwLen = sprintf(sMsg,
1501 "Unknown error #0x%lX (lookup 0x%lX)",
1502 dwErr, GetLastError());
1504 sv_setpvn((SV*)sv, sMsg, dwLen);
1510 win32_fprintf(FILE *fp, const char *format, ...)
1513 va_start(marker, format); /* Initialize variable arguments. */
1515 return (vfprintf(fp, format, marker));
1519 win32_printf(const char *format, ...)
1522 va_start(marker, format); /* Initialize variable arguments. */
1524 return (vprintf(format, marker));
1528 win32_vfprintf(FILE *fp, const char *format, va_list args)
1530 return (vfprintf(fp, format, args));
1534 win32_vprintf(const char *format, va_list args)
1536 return (vprintf(format, args));
1540 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
1542 return fread(buf, size, count, fp);
1546 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
1548 return fwrite(buf, size, count, fp);
1552 win32_fopen(const char *filename, const char *mode)
1554 if (stricmp(filename, "/dev/null")==0)
1555 return fopen("NUL", mode);
1556 return fopen(filename, mode);
1559 #ifndef USE_SOCKETS_AS_HANDLES
1561 #define fdopen my_fdopen
1565 win32_fdopen( int handle, const char *mode)
1567 return fdopen(handle, (char *) mode);
1571 win32_freopen( const char *path, const char *mode, FILE *stream)
1573 if (stricmp(path, "/dev/null")==0)
1574 return freopen("NUL", mode, stream);
1575 return freopen(path, mode, stream);
1579 win32_fclose(FILE *pf)
1581 return my_fclose(pf); /* defined in win32sck.c */
1585 win32_fputs(const char *s,FILE *pf)
1587 return fputs(s, pf);
1591 win32_fputc(int c,FILE *pf)
1597 win32_ungetc(int c,FILE *pf)
1599 return ungetc(c,pf);
1603 win32_getc(FILE *pf)
1609 win32_fileno(FILE *pf)
1615 win32_clearerr(FILE *pf)
1622 win32_fflush(FILE *pf)
1628 win32_ftell(FILE *pf)
1634 win32_fseek(FILE *pf,long offset,int origin)
1636 return fseek(pf, offset, origin);
1640 win32_fgetpos(FILE *pf,fpos_t *p)
1642 return fgetpos(pf, p);
1646 win32_fsetpos(FILE *pf,const fpos_t *p)
1648 return fsetpos(pf, p);
1652 win32_rewind(FILE *pf)
1672 win32_fstat(int fd,struct stat *sbufptr)
1674 return fstat(fd,sbufptr);
1678 win32_pipe(int *pfd, unsigned int size, int mode)
1680 return _pipe(pfd, size, mode);
1684 * a popen() clone that respects PERL5SHELL
1688 win32_popen(const char *command, const char *mode)
1690 #ifdef USE_RTL_POPEN
1691 return _popen(command, mode);
1699 /* establish which ends read and write */
1700 if (strchr(mode,'w')) {
1701 stdfd = 0; /* stdin */
1705 else if (strchr(mode,'r')) {
1706 stdfd = 1; /* stdout */
1713 /* set the correct mode */
1714 if (strchr(mode,'b'))
1716 else if (strchr(mode,'t'))
1719 ourmode = _fmode & (O_TEXT | O_BINARY);
1721 /* the child doesn't inherit handles */
1722 ourmode |= O_NOINHERIT;
1724 if (win32_pipe( p, 512, ourmode) == -1)
1727 /* save current stdfd */
1728 if ((oldfd = win32_dup(stdfd)) == -1)
1731 /* make stdfd go to child end of pipe (implicitly closes stdfd) */
1732 /* stdfd will be inherited by the child */
1733 if (win32_dup2(p[child], stdfd) == -1)
1736 /* close the child end in parent */
1737 win32_close(p[child]);
1739 /* start the child */
1740 if ((childpid = do_spawn_nowait((char*)command)) == -1)
1743 /* revert stdfd to whatever it was before */
1744 if (win32_dup2(oldfd, stdfd) == -1)
1747 /* close saved handle */
1750 sv_setiv(*av_fetch(w32_fdpid, p[parent], TRUE), childpid);
1752 /* we have an fd, return a file stream */
1753 return (win32_fdopen(p[parent], (char *)mode));
1756 /* we don't need to check for errors here */
1760 win32_dup2(oldfd, stdfd);
1765 #endif /* USE_RTL_POPEN */
1773 win32_pclose(FILE *pf)
1775 #ifdef USE_RTL_POPEN
1779 int childpid, status;
1782 sv = *av_fetch(w32_fdpid, win32_fileno(pf), TRUE);
1784 childpid = SvIVX(sv);
1796 remove_dead_process((HANDLE)childpid);
1798 /* wait for the child */
1799 if (cwait(&status, childpid, WAIT_CHILD) == -1)
1801 /* cwait() returns "correctly" on Borland */
1802 #ifndef __BORLANDC__
1807 #endif /* USE_RTL_POPEN */
1811 win32_rename(const char *oname, const char *newname)
1813 /* XXX despite what the documentation says about MoveFileEx(),
1814 * it doesn't work under Windows95!
1817 if (!MoveFileEx(oname,newname,
1818 MOVEFILE_COPY_ALLOWED|MOVEFILE_REPLACE_EXISTING)) {
1819 DWORD err = GetLastError();
1821 case ERROR_BAD_NET_NAME:
1822 case ERROR_BAD_NETPATH:
1823 case ERROR_BAD_PATHNAME:
1824 case ERROR_FILE_NOT_FOUND:
1825 case ERROR_FILENAME_EXCED_RANGE:
1826 case ERROR_INVALID_DRIVE:
1827 case ERROR_NO_MORE_FILES:
1828 case ERROR_PATH_NOT_FOUND:
1841 char tmpname[MAX_PATH+1];
1842 char dname[MAX_PATH+1];
1843 char *endname = Nullch;
1845 DWORD from_attr, to_attr;
1847 /* if oname doesn't exist, do nothing */
1848 from_attr = GetFileAttributes(oname);
1849 if (from_attr == 0xFFFFFFFF) {
1854 /* if newname exists, rename it to a temporary name so that we
1855 * don't delete it in case oname happens to be the same file
1856 * (but perhaps accessed via a different path)
1858 to_attr = GetFileAttributes(newname);
1859 if (to_attr != 0xFFFFFFFF) {
1860 /* if newname is a directory, we fail
1861 * XXX could overcome this with yet more convoluted logic */
1862 if (to_attr & FILE_ATTRIBUTE_DIRECTORY) {
1866 tmplen = strlen(newname);
1867 strcpy(tmpname,newname);
1868 endname = tmpname+tmplen;
1869 for (; endname > tmpname ; --endname) {
1870 if (*endname == '/' || *endname == '\\') {
1875 if (endname > tmpname)
1876 endname = strcpy(dname,tmpname);
1880 /* get a temporary filename in same directory
1881 * XXX is this really the best we can do? */
1882 if (!GetTempFileName((LPCTSTR)endname, "plr", 0, tmpname)) {
1886 DeleteFile(tmpname);
1888 retval = rename(newname, tmpname);
1895 /* rename oname to newname */
1896 retval = rename(oname, newname);
1898 /* if we created a temporary file before ... */
1899 if (endname != Nullch) {
1900 /* ...and rename succeeded, delete temporary file/directory */
1902 DeleteFile(tmpname);
1903 /* else restore it to what it was */
1905 (void)rename(tmpname, newname);
1912 win32_setmode(int fd, int mode)
1914 return setmode(fd, mode);
1918 win32_lseek(int fd, long offset, int origin)
1920 return lseek(fd, offset, origin);
1930 win32_open(const char *path, int flag, ...)
1936 pmode = va_arg(ap, int);
1939 if (stricmp(path, "/dev/null")==0)
1940 return open("NUL", flag, pmode);
1941 return open(path,flag,pmode);
1963 win32_dup2(int fd1,int fd2)
1965 return dup2(fd1,fd2);
1969 win32_read(int fd, void *buf, unsigned int cnt)
1971 return read(fd, buf, cnt);
1975 win32_write(int fd, const void *buf, unsigned int cnt)
1977 return write(fd, buf, cnt);
1981 win32_mkdir(const char *dir, int mode)
1983 return mkdir(dir); /* just ignore mode */
1987 win32_rmdir(const char *dir)
1993 win32_chdir(const char *dir)
1999 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
2003 #ifndef USE_RTL_WAIT
2004 if (mode == P_NOWAIT && w32_num_children >= MAXIMUM_WAIT_OBJECTS)
2008 status = spawnvp(mode, cmdname, (char * const *) argv);
2009 #ifndef USE_RTL_WAIT
2010 /* XXX For the P_NOWAIT case, Borland RTL returns pinfo.dwProcessId
2011 * while VC RTL returns pinfo.hProcess. For purposes of the custom
2012 * implementation of win32_wait(), we assume the latter.
2014 if (mode == P_NOWAIT && status >= 0)
2015 w32_child_pids[w32_num_children++] = (HANDLE)status;
2021 win32_execv(const char *cmdname, const char *const *argv)
2023 return execv(cmdname, (char *const *)argv);
2027 win32_execvp(const char *cmdname, const char *const *argv)
2029 return execvp(cmdname, (char *const *)argv);
2033 win32_perror(const char *str)
2039 win32_setbuf(FILE *pf, char *buf)
2045 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
2047 return setvbuf(pf, buf, type, size);
2051 win32_flushall(void)
2057 win32_fcloseall(void)
2063 win32_fgets(char *s, int n, FILE *pf)
2065 return fgets(s, n, pf);
2075 win32_fgetc(FILE *pf)
2081 win32_putc(int c, FILE *pf)
2087 win32_puts(const char *s)
2099 win32_putchar(int c)
2106 #ifndef USE_PERL_SBRK
2108 static char *committed = NULL;
2109 static char *base = NULL;
2110 static char *reserved = NULL;
2111 static char *brk = NULL;
2112 static DWORD pagesize = 0;
2113 static DWORD allocsize = 0;
2121 GetSystemInfo(&info);
2122 /* Pretend page size is larger so we don't perpetually
2123 * call the OS to commit just one page ...
2125 pagesize = info.dwPageSize << 3;
2126 allocsize = info.dwAllocationGranularity;
2128 /* This scheme fails eventually if request for contiguous
2129 * block is denied so reserve big blocks - this is only
2130 * address space not memory ...
2132 if (brk+need >= reserved)
2134 DWORD size = 64*1024*1024;
2136 if (committed && reserved && committed < reserved)
2138 /* Commit last of previous chunk cannot span allocations */
2139 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
2141 committed = reserved;
2143 /* Reserve some (more) space
2144 * Note this is a little sneaky, 1st call passes NULL as reserved
2145 * so lets system choose where we start, subsequent calls pass
2146 * the old end address so ask for a contiguous block
2148 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
2151 reserved = addr+size;
2166 if (brk > committed)
2168 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
2169 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
2184 win32_malloc(size_t size)
2186 return malloc(size);
2190 win32_calloc(size_t numitems, size_t size)
2192 return calloc(numitems,size);
2196 win32_realloc(void *block, size_t size)
2198 return realloc(block,size);
2202 win32_free(void *block)
2209 win32_open_osfhandle(long handle, int flags)
2211 return _open_osfhandle(handle, flags);
2215 win32_get_osfhandle(int fd)
2217 return _get_osfhandle(fd);
2228 SV *sv = sv_newmortal();
2229 /* Make one call with zero size - return value is required size */
2230 DWORD len = GetCurrentDirectory((DWORD)0,NULL);
2231 SvUPGRADE(sv,SVt_PV);
2233 SvCUR(sv) = GetCurrentDirectory((DWORD) SvLEN(sv), SvPVX(sv));
2236 * then it worked, set PV valid,
2237 * else leave it 'undef'
2252 croak("usage: Win32::SetCurrentDirectory($cwd)");
2253 if (SetCurrentDirectory(SvPV(ST(0),n_a)))
2260 XS(w32_GetNextAvailDrive)
2264 char root[] = "_:\\";
2267 if (GetDriveType(root) == 1) {
2276 XS(w32_GetLastError)
2279 XSRETURN_IV(GetLastError());
2286 char *name = getlogin_buffer;
2287 DWORD size = sizeof(getlogin_buffer);
2288 if (GetUserName(name,&size)) {
2289 /* size includes NULL */
2290 ST(0) = sv_2mortal(newSVpv(name,size-1));
2300 char name[MAX_COMPUTERNAME_LENGTH+1];
2301 DWORD size = sizeof(name);
2302 if (GetComputerName(name,&size)) {
2303 /* size does NOT include NULL :-( */
2304 ST(0) = sv_2mortal(newSVpv(name,size));
2315 #ifndef HAS_NETWKSTAGETINFO
2316 /* mingw32 (and Win95) don't have NetWksta*(), so do it the old way */
2318 DWORD size = sizeof(name);
2319 if (GetUserName(name,&size)) {
2321 DWORD sidlen = sizeof(sid);
2323 DWORD dnamelen = sizeof(dname);
2325 if (LookupAccountName(NULL, name, (PSID)&sid, &sidlen,
2326 dname, &dnamelen, &snu)) {
2327 XSRETURN_PV(dname); /* all that for this */
2331 /* this way is more reliable, in case user has a local account.
2332 * XXX need dynamic binding of netapi32.dll symbols or this will fail on
2333 * Win95. Probably makes more sense to move it into libwin32. */
2335 DWORD dnamelen = sizeof(dname);
2336 PWKSTA_INFO_100 pwi;
2337 if (NERR_Success == NetWkstaGetInfo(NULL, 100, (LPBYTE*)&pwi)) {
2338 if (pwi->wki100_langroup && *(pwi->wki100_langroup)) {
2339 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_langroup,
2340 -1, (LPSTR)dname, dnamelen, NULL, NULL);
2343 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_computername,
2344 -1, (LPSTR)dname, dnamelen, NULL, NULL);
2346 NetApiBufferFree(pwi);
2358 DWORD flags, filecomplen;
2359 if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
2360 &flags, fsname, sizeof(fsname))) {
2361 if (GIMME == G_ARRAY) {
2362 XPUSHs(sv_2mortal(newSVpv(fsname,0)));
2363 XPUSHs(sv_2mortal(newSViv(flags)));
2364 XPUSHs(sv_2mortal(newSViv(filecomplen)));
2368 XSRETURN_PV(fsname);
2374 XS(w32_GetOSVersion)
2377 OSVERSIONINFO osver;
2379 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
2380 if (GetVersionEx(&osver)) {
2381 XPUSHs(newSVpv(osver.szCSDVersion, 0));
2382 XPUSHs(newSViv(osver.dwMajorVersion));
2383 XPUSHs(newSViv(osver.dwMinorVersion));
2384 XPUSHs(newSViv(osver.dwBuildNumber));
2385 XPUSHs(newSViv(osver.dwPlatformId));
2396 XSRETURN_IV(IsWinNT());
2403 XSRETURN_IV(IsWin95());
2407 XS(w32_FormatMessage)
2414 croak("usage: Win32::FormatMessage($errno)");
2416 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
2417 &source, SvIV(ST(0)), 0,
2418 msgbuf, sizeof(msgbuf)-1, NULL))
2419 XSRETURN_PV(msgbuf);
2429 PROCESS_INFORMATION stProcInfo;
2430 STARTUPINFO stStartInfo;
2431 BOOL bSuccess = FALSE;
2435 croak("usage: Win32::Spawn($cmdName, $args, $PID)");
2437 cmd = SvPV(ST(0),n_a);
2438 args = SvPV(ST(1), n_a);
2440 memset(&stStartInfo, 0, sizeof(stStartInfo)); /* Clear the block */
2441 stStartInfo.cb = sizeof(stStartInfo); /* Set the structure size */
2442 stStartInfo.dwFlags = STARTF_USESHOWWINDOW; /* Enable wShowWindow control */
2443 stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE; /* Start min (normal) */
2446 cmd, /* Image path */
2447 args, /* Arguments for command line */
2448 NULL, /* Default process security */
2449 NULL, /* Default thread security */
2450 FALSE, /* Must be TRUE to use std handles */
2451 NORMAL_PRIORITY_CLASS, /* No special scheduling */
2452 NULL, /* Inherit our environment block */
2453 NULL, /* Inherit our currrent directory */
2454 &stStartInfo, /* -> Startup info */
2455 &stProcInfo)) /* <- Process info (if OK) */
2457 CloseHandle(stProcInfo.hThread);/* library source code does this. */
2458 sv_setiv(ST(2), stProcInfo.dwProcessId);
2461 XSRETURN_IV(bSuccess);
2465 XS(w32_GetTickCount)
2468 XSRETURN_IV(GetTickCount());
2472 XS(w32_GetShortPathName)
2479 croak("usage: Win32::GetShortPathName($longPathName)");
2481 shortpath = sv_mortalcopy(ST(0));
2482 SvUPGRADE(shortpath, SVt_PV);
2483 /* src == target is allowed */
2485 len = GetShortPathName(SvPVX(shortpath),
2488 } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
2490 SvCUR_set(shortpath,len);
2494 ST(0) = &PL_sv_undef;
2503 croak("usage: Win32::Sleep($milliseconds)");
2509 Perl_init_os_extras()
2511 char *file = __FILE__;
2514 w32_perlshell_tokens = Nullch;
2515 w32_perlshell_items = -1;
2516 w32_fdpid = newAV(); /* XXX needs to be in Perl_win32_init()? */
2517 #ifndef USE_RTL_WAIT
2518 w32_num_children = 0;
2521 /* these names are Activeware compatible */
2522 newXS("Win32::GetCwd", w32_GetCwd, file);
2523 newXS("Win32::SetCwd", w32_SetCwd, file);
2524 newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
2525 newXS("Win32::GetLastError", w32_GetLastError, file);
2526 newXS("Win32::LoginName", w32_LoginName, file);
2527 newXS("Win32::NodeName", w32_NodeName, file);
2528 newXS("Win32::DomainName", w32_DomainName, file);
2529 newXS("Win32::FsType", w32_FsType, file);
2530 newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
2531 newXS("Win32::IsWinNT", w32_IsWinNT, file);
2532 newXS("Win32::IsWin95", w32_IsWin95, file);
2533 newXS("Win32::FormatMessage", w32_FormatMessage, file);
2534 newXS("Win32::Spawn", w32_Spawn, file);
2535 newXS("Win32::GetTickCount", w32_GetTickCount, file);
2536 newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
2537 newXS("Win32::Sleep", w32_Sleep, file);
2539 /* XXX Bloat Alert! The following Activeware preloads really
2540 * ought to be part of Win32::Sys::*, so they're not included
2543 /* LookupAccountName
2545 * InitiateSystemShutdown
2546 * AbortSystemShutdown
2547 * ExpandEnvrironmentStrings
2552 Perl_win32_init(int *argcp, char ***argvp)
2554 /* Disable floating point errors, Perl will trap the ones we
2555 * care about. VC++ RTL defaults to switching these off
2556 * already, but the Borland RTL doesn't. Since we don't
2557 * want to be at the vendor's whim on the default, we set
2558 * it explicitly here.
2560 #if !defined(_ALPHA_) && !defined(__GNUC__)
2561 _control87(MCW_EM, MCW_EM);
2566 #ifdef USE_BINMODE_SCRIPTS
2569 win32_strip_return(SV *sv)
2571 char *s = SvPVX(sv);
2572 char *e = s+SvCUR(sv);
2576 if (*s == '\r' && s[1] == '\n')
2586 SvCUR_set(sv,d-SvPVX(sv));