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)
44 extern CPerlObj* pPerl;
51 /* assert.h conflicts with #define of assert in perl.h */
58 #if defined(_MSC_VER) || defined(__MINGW32__)
59 #include <sys/utime.h>
65 /* Mingw32 defaults to globing command line
66 * So we turn it off like this:
73 #define EXECF_SPAWN_NOWAIT 3
75 #if defined(PERL_OBJECT)
76 #undef win32_get_privlib
77 #define win32_get_privlib g_win32_get_privlib
78 #undef win32_get_sitelib
79 #define win32_get_sitelib g_win32_get_sitelib
81 #define do_aspawn g_do_aspawn
83 #define do_spawn g_do_spawn
85 #define do_exec g_do_exec
87 #define getlogin g_getlogin
90 static DWORD os_id(void);
91 static void get_shell(void);
92 static long tokenize(char *str, char **dest, char ***destv);
93 int do_spawn2(char *cmd, int exectype);
94 static BOOL has_shell_metachars(char *ptr);
95 static long filetime_to_clock(PFILETIME ft);
96 static BOOL filetime_from_time(PFILETIME ft, time_t t);
97 static char * get_emd_part(char **leading, char *trailing, ...);
98 static void remove_dead_process(long deceased);
99 static long find_pid(int pid);
100 static char * qualified_path(const char *cmd);
102 HANDLE w32_perldll_handle = INVALID_HANDLE_VALUE;
103 char w32_module_name[MAX_PATH+1];
104 static DWORD w32_platform = (DWORD)-1;
107 # ifdef USE_DECLSPEC_THREAD
108 __declspec(thread) char strerror_buffer[512];
109 __declspec(thread) char getlogin_buffer[128];
110 __declspec(thread) char w32_perllib_root[MAX_PATH+1];
111 # ifdef HAVE_DES_FCRYPT
112 __declspec(thread) char crypt_buffer[30];
115 # define strerror_buffer (thr->i.Wstrerror_buffer)
116 # define getlogin_buffer (thr->i.Wgetlogin_buffer)
117 # define w32_perllib_root (thr->i.Ww32_perllib_root)
118 # define crypt_buffer (thr->i.Wcrypt_buffer)
121 static char strerror_buffer[512];
122 static char getlogin_buffer[128];
123 static char w32_perllib_root[MAX_PATH+1];
124 # ifdef HAVE_DES_FCRYPT
125 static char crypt_buffer[30];
131 return (os_id() == VER_PLATFORM_WIN32_WINDOWS);
136 return (os_id() == VER_PLATFORM_WIN32_NT);
139 /* *ptr is expected to point to valid allocated space (can't be NULL) */
141 GetRegStrFromKey(HKEY hkey, const char *lpszValueName, char** ptr, DWORD* lpDataLen)
143 /* Retrieve a REG_SZ or REG_EXPAND_SZ from the registry */
146 const char *subkey = "Software\\Perl";
150 retval = RegOpenKeyEx(hkey, subkey, 0, KEY_READ, &handle);
151 if (retval == ERROR_SUCCESS) {
152 retval = RegQueryValueEx(handle, lpszValueName, 0, &type, NULL, lpDataLen);
153 if (retval == ERROR_SUCCESS && type == REG_SZ) {
154 Renew(*ptr, *lpDataLen, char);
155 retval = RegQueryValueEx(handle, lpszValueName, 0, NULL,
156 (PBYTE)*ptr, lpDataLen);
157 if (retval == ERROR_SUCCESS)
165 /* *ptr is expected to point to valid allocated space (can't be NULL) */
167 GetRegStr(const char *lpszValueName, char** ptr, DWORD* lpDataLen)
169 char *str = GetRegStrFromKey(HKEY_CURRENT_USER, lpszValueName, ptr, lpDataLen);
171 str = GetRegStrFromKey(HKEY_LOCAL_MACHINE, lpszValueName, ptr, lpDataLen);
175 /* *prev_path is expected to point to valid allocated space (can't be NULL) */
177 get_emd_part(char **prev_path, char *trailing_path, ...)
181 char mod_name[MAX_PATH+1];
185 int oldsize, newsize;
187 va_start(ap, trailing_path);
188 strip = va_arg(ap, char *);
190 sprintf(base, "%5.3f",
191 (double)PERL_REVISION + ((double)PERL_VERSION / (double)1000));
193 if (!*w32_module_name) {
194 GetModuleFileName((HMODULE)((w32_perldll_handle == INVALID_HANDLE_VALUE)
195 ? GetModuleHandle(NULL)
196 : w32_perldll_handle),
197 w32_module_name, sizeof(w32_module_name));
199 /* try to get full path to binary (which may be mangled when perl is
200 * run from a 16-bit app) */
201 /*PerlIO_printf(PerlIO_stderr(), "Before %s\n", w32_module_name);*/
202 (void)win32_longpath(w32_module_name);
203 /*PerlIO_printf(PerlIO_stderr(), "After %s\n", w32_module_name);*/
205 /* normalize to forward slashes */
206 ptr = w32_module_name;
213 strcpy(mod_name, w32_module_name);
214 ptr = strrchr(mod_name, '/');
215 while (ptr && strip) {
216 /* look for directories to skip back */
219 ptr = strrchr(mod_name, '/');
220 if (!ptr || stricmp(ptr+1, strip) != 0) {
221 if(!(*strip == '5' && *(ptr+1) == '5'
222 && strncmp(strip, base, 5) == 0
223 && strncmp(ptr+1, base, 5) == 0))
229 strip = va_arg(ap, char *);
237 strcpy(++ptr, trailing_path);
239 /* only add directory if it exists */
240 if (GetFileAttributes(mod_name) != (DWORD) -1) {
241 /* directory exists */
242 newsize = strlen(mod_name) + 1;
243 oldsize = strlen(*prev_path) + 1;
244 newsize += oldsize; /* includes plus 1 for ';' */
245 Renew(*prev_path, newsize, char);
246 (*prev_path)[oldsize-1] = ';';
247 strcpy(&(*prev_path)[oldsize], mod_name);
255 win32_get_privlib(char *pl)
257 char *stdlib = "lib";
258 char buffer[MAX_PATH+1];
261 SV *sv = sv_2mortal(newSVpvn("",127));
263 /* $stdlib = $HKCU{"lib-$]"} || $HKLM{"lib-$]"} || $HKCU{"lib"} || $HKLM{"lib"} || ""; */
264 sprintf(buffer, "%s-%s", stdlib, pl);
266 if (!GetRegStr(buffer, path, &datalen))
267 (void)GetRegStr(stdlib, path, &datalen);
269 /* $stdlib .= ";$EMD/../../lib" */
270 (void)get_emd_part(path, stdlib, ARCHNAME, "bin", Nullch);
271 SvCUR_set(sv, strlen(*path));
272 SvLEN_set(sv, SvCUR(sv)+1);
277 win32_get_sitelib(char *pl)
279 char *sitelib = "sitelib";
281 char pathstr[MAX_PATH+1];
283 char **path1, *str1 = Nullch;
284 char **path2, *str2 = Nullch;
286 SV *sv1 = sv_2mortal(newSVpvn("",127));
287 SV *sv2 = sv_2mortal(newSVpvn("",127));
289 /* $HKCU{"sitelib-$]"} || $HKLM{"sitelib-$]"} . ---; */
290 sprintf(regstr, "%s-%s", sitelib, pl);
292 (void)GetRegStr(regstr, path1, &datalen);
295 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/site/$]/lib"; */
296 sprintf(pathstr, "site/%s/lib", pl);
297 str1 = get_emd_part(path1, pathstr, ARCHNAME, "bin", pl, Nullch);
298 if (!str1 && strlen(pl) == 7) {
299 /* pl may have been SUBVERSION-specific; try again without
301 sprintf(pathstr, "site/%.5s/lib", pl);
302 str1 = get_emd_part(path1, pathstr, ARCHNAME, "bin", pl, Nullch);
305 /* $HKCU{'sitelib'} || $HKLM{'sitelib'} . ---; */
307 (void)GetRegStr(sitelib, path2, &datalen);
310 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/site/lib"; */
311 str2 = get_emd_part(path2, "site/lib", ARCHNAME, "bin", pl, Nullch);
313 SvCUR_set(sv1, strlen(*path1));
314 SvLEN_set(sv1, SvCUR(sv1)+1);
315 SvCUR_set(sv2, strlen(*path2));
316 SvLEN_set(sv2, SvCUR(sv2)+1);
323 sv_catpvn(sv1, ";", 1);
331 has_shell_metachars(char *ptr)
337 * Scan string looking for redirection (< or >) or pipe
338 * characters (|) that are not in a quoted string.
339 * Shell variable interpolation (%VAR%) can also happen inside strings.
371 #if !defined(PERL_OBJECT)
372 /* since the current process environment is being updated in util.c
373 * the library functions will get the correct environment
376 my_popen(char *cmd, char *mode)
379 #define fixcmd(x) { \
380 char *pspace = strchr((x),' '); \
383 while (p < pspace) { \
394 PERL_FLUSHALL_FOR_CHILD;
395 return win32_popen(cmd, mode);
399 my_pclose(PerlIO *fp)
401 return win32_pclose(fp);
408 static OSVERSIONINFO osver;
410 if (osver.dwPlatformId != w32_platform) {
411 memset(&osver, 0, sizeof(OSVERSIONINFO));
412 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
413 GetVersionEx(&osver);
414 w32_platform = osver.dwPlatformId;
416 return (w32_platform);
419 /* Tokenize a string. Words are null-separated, and the list
420 * ends with a doubled null. Any character (except null and
421 * including backslash) may be escaped by preceding it with a
422 * backslash (the backslash will be stripped).
423 * Returns number of words in result buffer.
426 tokenize(char *str, char **dest, char ***destv)
428 char *retstart = Nullch;
429 char **retvstart = 0;
432 int slen = strlen(str);
434 register char **retv;
435 New(1307, ret, slen+2, char);
436 New(1308, retv, (slen+3)/2, char*);
444 if (*ret == '\\' && *str)
446 else if (*ret == ' ') {
462 retvstart[items] = Nullch;
474 if (!w32_perlshell_tokens) {
475 /* we don't use COMSPEC here for two reasons:
476 * 1. the same reason perl on UNIX doesn't use SHELL--rampant and
477 * uncontrolled unportability of the ensuing scripts.
478 * 2. PERL5SHELL could be set to a shell that may not be fit for
479 * interactive use (which is what most programs look in COMSPEC
482 char* defaultshell = (IsWinNT() ? "cmd.exe /x/c" : "command.com /c");
483 char *usershell = getenv("PERL5SHELL");
484 w32_perlshell_items = tokenize(usershell ? usershell : defaultshell,
485 &w32_perlshell_tokens,
491 do_aspawn(void *vreally, void **vmark, void **vsp)
493 SV *really = (SV*)vreally;
494 SV **mark = (SV**)vmark;
506 New(1306, argv, (sp - mark) + w32_perlshell_items + 2, char*);
508 if (SvNIOKp(*(mark+1)) && !SvPOKp(*(mark+1))) {
513 while (++mark <= sp) {
514 if (*mark && (str = SvPV_nolen(*mark)))
521 status = win32_spawnvp(flag,
522 (const char*)(really ? SvPV_nolen(really) : argv[0]),
523 (const char* const*)argv);
525 if (status < 0 && (errno == ENOEXEC || errno == ENOENT)) {
526 /* possible shell-builtin, invoke with shell */
528 sh_items = w32_perlshell_items;
530 argv[index+sh_items] = argv[index];
531 while (--sh_items >= 0)
532 argv[sh_items] = w32_perlshell_vec[sh_items];
534 status = win32_spawnvp(flag,
535 (const char*)(really ? SvPV_nolen(really) : argv[0]),
536 (const char* const*)argv);
539 if (flag != P_NOWAIT) {
542 warn("Can't spawn \"%s\": %s", argv[0], strerror(errno));
547 PL_statusvalue = status;
554 do_spawn2(char *cmd, int exectype)
560 BOOL needToTry = TRUE;
563 /* Save an extra exec if possible. See if there are shell
564 * metacharacters in it */
565 if (!has_shell_metachars(cmd)) {
566 New(1301,argv, strlen(cmd) / 2 + 2, char*);
567 New(1302,cmd2, strlen(cmd) + 1, char);
570 for (s = cmd2; *s;) {
571 while (*s && isSPACE(*s))
575 while (*s && !isSPACE(*s))
584 status = win32_spawnvp(P_WAIT, argv[0],
585 (const char* const*)argv);
587 case EXECF_SPAWN_NOWAIT:
588 status = win32_spawnvp(P_NOWAIT, argv[0],
589 (const char* const*)argv);
592 status = win32_execvp(argv[0], (const char* const*)argv);
595 if (status != -1 || errno == 0)
605 New(1306, argv, w32_perlshell_items + 2, char*);
606 while (++i < w32_perlshell_items)
607 argv[i] = w32_perlshell_vec[i];
612 status = win32_spawnvp(P_WAIT, argv[0],
613 (const char* const*)argv);
615 case EXECF_SPAWN_NOWAIT:
616 status = win32_spawnvp(P_NOWAIT, argv[0],
617 (const char* const*)argv);
620 status = win32_execvp(argv[0], (const char* const*)argv);
626 if (exectype != EXECF_SPAWN_NOWAIT) {
629 warn("Can't %s \"%s\": %s",
630 (exectype == EXECF_EXEC ? "exec" : "spawn"),
631 cmd, strerror(errno));
636 PL_statusvalue = status;
644 return do_spawn2(cmd, EXECF_SPAWN);
648 do_spawn_nowait(char *cmd)
650 return do_spawn2(cmd, EXECF_SPAWN_NOWAIT);
656 do_spawn2(cmd, EXECF_EXEC);
660 /* The idea here is to read all the directory names into a string table
661 * (separated by nulls) and when one of the other dir functions is called
662 * return the pointer to the current file name.
665 win32_opendir(char *filename)
670 char scanname[MAX_PATH+3];
672 WIN32_FIND_DATAA aFindData;
673 WIN32_FIND_DATAW wFindData;
675 char buffer[MAX_PATH*2];
676 WCHAR wbuffer[MAX_PATH];
679 len = strlen(filename);
683 /* check to see if filename is a directory */
684 if (win32_stat(filename, &sbuf) < 0 || !S_ISDIR(sbuf.st_mode))
687 /* Get us a DIR structure */
688 Newz(1303, p, 1, DIR);
692 /* Create the search pattern */
693 strcpy(scanname, filename);
695 /* bare drive name means look in cwd for drive */
696 if (len == 2 && isALPHA(scanname[0]) && scanname[1] == ':') {
697 scanname[len++] = '.';
698 scanname[len++] = '/';
700 else if (scanname[len-1] != '/' && scanname[len-1] != '\\') {
701 scanname[len++] = '/';
703 scanname[len++] = '*';
704 scanname[len] = '\0';
706 /* do the FindFirstFile call */
708 A2WHELPER(scanname, wbuffer, sizeof(wbuffer), GETINTERPMODE());
709 fh = FindFirstFileW(wbuffer, &wFindData);
712 fh = FindFirstFileA(scanname, &aFindData);
714 if (fh == INVALID_HANDLE_VALUE) {
715 /* FindFirstFile() fails on empty drives! */
716 if (GetLastError() == ERROR_FILE_NOT_FOUND)
722 /* now allocate the first part of the string table for
723 * the filenames that we find.
726 W2AHELPER(wFindData.cFileName, buffer, sizeof(buffer), GETINTERPMODE());
730 ptr = aFindData.cFileName;
733 New(1304, p->start, idx, char);
734 if (p->start == NULL)
735 croak("opendir: malloc failed!\n");
736 strcpy(p->start, ptr);
739 /* loop finding all the files that match the wildcard
740 * (which should be all of them in this directory!).
741 * the variable idx should point one past the null terminator
742 * of the previous string found.
745 ? FindNextFileW(fh, &wFindData)
746 : FindNextFileA(fh, &aFindData)) {
748 W2AHELPER(wFindData.cFileName, buffer, sizeof(buffer), GETINTERPMODE());
750 /* ptr is set above to the correct area */
752 /* bump the string table size by enough for the
753 * new name and it's null terminator
755 Renew(p->start, idx+len+1, char);
756 if (p->start == NULL)
757 croak("opendir: malloc failed!\n");
758 strcpy(&p->start[idx], ptr);
769 /* Readdir just returns the current string pointer and bumps the
770 * string pointer to the nDllExport entry.
773 win32_readdir(DIR *dirp)
776 static int dummy = 0;
779 /* first set up the structure to return */
780 len = strlen(dirp->curr);
781 strcpy(dirp->dirstr.d_name, dirp->curr);
782 dirp->dirstr.d_namlen = len;
785 dirp->dirstr.d_ino = dummy++;
787 /* Now set up for the nDllExport call to readdir */
788 dirp->curr += len + 1;
789 if (dirp->curr >= (dirp->start + dirp->size)) {
793 return &(dirp->dirstr);
799 /* Telldir returns the current string pointer position */
801 win32_telldir(DIR *dirp)
803 return (long) dirp->curr;
807 /* Seekdir moves the string pointer to a previously saved position
811 win32_seekdir(DIR *dirp, long loc)
813 dirp->curr = (char *)loc;
816 /* Rewinddir resets the string pointer to the start */
818 win32_rewinddir(DIR *dirp)
820 dirp->curr = dirp->start;
823 /* free the memory allocated by opendir */
825 win32_closedir(DIR *dirp)
827 Safefree(dirp->start);
840 * Just pretend that everyone is a superuser. NT will let us know if
841 * we don\'t really have permission to do something.
844 #define ROOT_UID ((uid_t)0)
845 #define ROOT_GID ((gid_t)0)
874 return (auid == ROOT_UID ? 0 : -1);
880 return (agid == ROOT_GID ? 0 : -1);
887 char *buf = getlogin_buffer;
888 DWORD size = sizeof(getlogin_buffer);
889 if (GetUserName(buf,&size))
895 chown(const char *path, uid_t owner, gid_t group)
905 for (child = 0 ; child < w32_num_children ; ++child) {
906 if (w32_child_pids[child] == pid)
913 remove_dead_process(long child)
916 CloseHandle(w32_child_handles[child]);
917 Copy(&w32_child_handles[child+1], &w32_child_handles[child],
918 (w32_num_children-child-1), HANDLE);
919 Copy(&w32_child_pids[child+1], &w32_child_pids[child],
920 (w32_num_children-child-1), DWORD);
926 win32_kill(int pid, int sig)
929 hProcess = OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid);
930 if (hProcess && TerminateProcess(hProcess, sig))
931 CloseHandle(hProcess);
943 DllExport unsigned int
944 win32_sleep(unsigned int t)
951 win32_stat(const char *path, struct stat *buffer)
954 int l = strlen(path);
956 WCHAR wbuffer[MAX_PATH];
959 switch(path[l - 1]) {
960 /* FindFirstFile() and stat() are buggy with a trailing
961 * backslash, so change it to a forward slash :-( */
963 strncpy(t, path, l-1);
968 /* FindFirstFile() is buggy with "x:", so add a dot :-( */
970 if (l == 2 && isALPHA(path[0])) {
971 t[0] = path[0]; t[1] = ':'; t[2] = '.'; t[3] = '\0';
979 A2WHELPER(path, wbuffer, sizeof(wbuffer), GETINTERPMODE());
980 res = _wstat(wbuffer, (struct _stat *)buffer);
983 res = stat(path, buffer);
986 /* CRT is buggy on sharenames, so make sure it really isn't.
987 * XXX using GetFileAttributesEx() will enable us to set
988 * buffer->st_*time (but note that's not available on the
989 * Windows of 1995) */
992 r = GetFileAttributesW(wbuffer);
995 r = GetFileAttributesA(path);
997 if (r != 0xffffffff && (r & FILE_ATTRIBUTE_DIRECTORY)) {
998 /* buffer may still contain old garbage since stat() failed */
999 Zero(buffer, 1, struct stat);
1000 buffer->st_mode = S_IFDIR | S_IREAD;
1002 if (!(r & FILE_ATTRIBUTE_READONLY))
1003 buffer->st_mode |= S_IWRITE | S_IEXEC;
1008 if (l == 3 && isALPHA(path[0]) && path[1] == ':'
1009 && (path[2] == '\\' || path[2] == '/'))
1011 /* The drive can be inaccessible, some _stat()s are buggy */
1013 ? !GetVolumeInformationW(wbuffer,NULL,0,NULL,NULL,NULL,NULL,0)
1014 : !GetVolumeInformationA(path,NULL,0,NULL,NULL,NULL,NULL,0)) {
1020 if (S_ISDIR(buffer->st_mode))
1021 buffer->st_mode |= S_IWRITE | S_IEXEC;
1022 else if (S_ISREG(buffer->st_mode)) {
1023 if (l >= 4 && path[l-4] == '.') {
1024 const char *e = path + l - 3;
1025 if (strnicmp(e,"exe",3)
1026 && strnicmp(e,"bat",3)
1027 && strnicmp(e,"com",3)
1028 && (IsWin95() || strnicmp(e,"cmd",3)))
1029 buffer->st_mode &= ~S_IEXEC;
1031 buffer->st_mode |= S_IEXEC;
1034 buffer->st_mode &= ~S_IEXEC;
1041 /* Find the longname of a given path. path is destructively modified.
1042 * It should have space for at least MAX_PATH characters. */
1044 win32_longpath(char *path)
1046 WIN32_FIND_DATA fdata;
1048 char tmpbuf[MAX_PATH+1];
1049 char *tmpstart = tmpbuf;
1056 if (isALPHA(path[0]) && path[1] == ':' &&
1057 (path[2] == '/' || path[2] == '\\'))
1060 *tmpstart++ = path[0];
1064 else if ((path[0] == '/' || path[0] == '\\') &&
1065 (path[1] == '/' || path[1] == '\\'))
1068 *tmpstart++ = path[0];
1069 *tmpstart++ = path[1];
1070 /* copy machine name */
1071 while (*start && *start != '/' && *start != '\\')
1072 *tmpstart++ = *start++;
1074 *tmpstart++ = *start;
1076 /* copy share name */
1077 while (*start && *start != '/' && *start != '\\')
1078 *tmpstart++ = *start++;
1082 if (sep == '/' || sep == '\\')
1086 /* walk up to slash */
1087 while (*start && *start != '/' && *start != '\\')
1090 /* discard doubled slashes */
1091 while (*start && (start[1] == '/' || start[1] == '\\'))
1095 /* stop and find full name of component */
1097 fhand = FindFirstFile(path,&fdata);
1098 if (fhand != INVALID_HANDLE_VALUE) {
1099 strcpy(tmpstart, fdata.cFileName);
1100 tmpstart += strlen(fdata.cFileName);
1108 /* failed a step, just return without side effects */
1109 /*PerlIO_printf(PerlIO_stderr(), "Failed to find %s\n", path);*/
1114 strcpy(path,tmpbuf);
1118 #ifndef USE_WIN32_RTL_ENV
1121 win32_getenv(const char *name)
1123 static char *curitem = Nullch; /* XXX threadead */
1124 static WCHAR *wCuritem = (WCHAR*)Nullch; /* XXX threadead */
1125 static DWORD curlen = 0, wCurlen = 0;/* XXX threadead */
1126 WCHAR wBuffer[MAX_PATH];
1131 New(1306,wCuritem,wCurlen,WCHAR);
1136 New(1305,curitem,curlen,char);
1140 A2WHELPER(name, wBuffer, sizeof(wBuffer), GETINTERPMODE());
1141 needlen = GetEnvironmentVariableW(wBuffer,wCuritem,wCurlen);
1144 needlen = GetEnvironmentVariableA(name,curitem,curlen);
1147 while (needlen > wCurlen) {
1148 Renew(wCuritem,needlen,WCHAR);
1150 needlen = GetEnvironmentVariableW(wBuffer,wCuritem,wCurlen);
1152 if (needlen > curlen) {
1153 Renew(curitem,needlen,char);
1156 W2AHELPER(wCuritem, curitem, curlen, GETINTERPMODE());
1159 while (needlen > curlen) {
1160 Renew(curitem,needlen,char);
1162 needlen = GetEnvironmentVariableA(name,curitem,curlen);
1167 /* allow any environment variables that begin with 'PERL'
1168 to be stored in the registry */
1172 if (strncmp(name, "PERL", 4) == 0) {
1178 curitem = GetRegStr(name, &curitem, &curlen);
1181 if (curitem && *curitem == '\0')
1188 win32_putenv(const char *name)
1194 int length, relval = -1;
1197 length = strlen(name)+1;
1198 New(1309,wCuritem,length,WCHAR);
1199 A2WHELPER(name, wCuritem, length*2, GETINTERPMODE());
1200 wVal = wcschr(wCuritem, '=');
1203 if(SetEnvironmentVariableW(wCuritem, *wVal ? wVal : NULL))
1209 New(1309,curitem,strlen(name)+1,char);
1210 strcpy(curitem, name);
1211 val = strchr(curitem, '=');
1213 /* The sane way to deal with the environment.
1214 * Has these advantages over putenv() & co.:
1215 * * enables us to store a truly empty value in the
1216 * environment (like in UNIX).
1217 * * we don't have to deal with RTL globals, bugs and leaks.
1219 * Why you may want to enable USE_WIN32_RTL_ENV:
1220 * * environ[] and RTL functions will not reflect changes,
1221 * which might be an issue if extensions want to access
1222 * the env. via RTL. This cuts both ways, since RTL will
1223 * not see changes made by extensions that call the Win32
1224 * functions directly, either.
1228 if(SetEnvironmentVariableA(curitem, *val ? val : NULL))
1240 filetime_to_clock(PFILETIME ft)
1242 __int64 qw = ft->dwHighDateTime;
1244 qw |= ft->dwLowDateTime;
1245 qw /= 10000; /* File time ticks at 0.1uS, clock at 1mS */
1250 win32_times(struct tms *timebuf)
1255 if (GetProcessTimes(GetCurrentProcess(), &dummy, &dummy,
1257 timebuf->tms_utime = filetime_to_clock(&user);
1258 timebuf->tms_stime = filetime_to_clock(&kernel);
1259 timebuf->tms_cutime = 0;
1260 timebuf->tms_cstime = 0;
1263 /* That failed - e.g. Win95 fallback to clock() */
1264 clock_t t = clock();
1265 timebuf->tms_utime = t;
1266 timebuf->tms_stime = 0;
1267 timebuf->tms_cutime = 0;
1268 timebuf->tms_cstime = 0;
1273 /* fix utime() so it works on directories in NT
1274 * thanks to Jan Dubois <jan.dubois@ibm.net>
1277 filetime_from_time(PFILETIME pFileTime, time_t Time)
1279 struct tm *pTM = gmtime(&Time);
1280 SYSTEMTIME SystemTime;
1285 SystemTime.wYear = pTM->tm_year + 1900;
1286 SystemTime.wMonth = pTM->tm_mon + 1;
1287 SystemTime.wDay = pTM->tm_mday;
1288 SystemTime.wHour = pTM->tm_hour;
1289 SystemTime.wMinute = pTM->tm_min;
1290 SystemTime.wSecond = pTM->tm_sec;
1291 SystemTime.wMilliseconds = 0;
1293 return SystemTimeToFileTime(&SystemTime, pFileTime);
1297 win32_utime(const char *filename, struct utimbuf *times)
1303 struct utimbuf TimeBuffer;
1304 WCHAR wbuffer[MAX_PATH];
1308 A2WHELPER(filename, wbuffer, sizeof(wbuffer), GETINTERPMODE());
1309 rc = _wutime(wbuffer, (struct _utimbuf*)times);
1312 rc = utime(filename, times);
1314 /* EACCES: path specifies directory or readonly file */
1315 if (rc == 0 || errno != EACCES /* || !IsWinNT() */)
1318 if (times == NULL) {
1319 times = &TimeBuffer;
1320 time(×->actime);
1321 times->modtime = times->actime;
1324 /* This will (and should) still fail on readonly files */
1326 handle = CreateFileW(wbuffer, GENERIC_READ | GENERIC_WRITE,
1327 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1328 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1331 handle = CreateFileA(filename, GENERIC_READ | GENERIC_WRITE,
1332 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1333 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1335 if (handle == INVALID_HANDLE_VALUE)
1338 if (GetFileTime(handle, &ftCreate, &ftAccess, &ftWrite) &&
1339 filetime_from_time(&ftAccess, times->actime) &&
1340 filetime_from_time(&ftWrite, times->modtime) &&
1341 SetFileTime(handle, &ftCreate, &ftAccess, &ftWrite))
1346 CloseHandle(handle);
1351 win32_uname(struct utsname *name)
1353 struct hostent *hep;
1354 STRLEN nodemax = sizeof(name->nodename)-1;
1355 OSVERSIONINFO osver;
1357 memset(&osver, 0, sizeof(OSVERSIONINFO));
1358 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1359 if (GetVersionEx(&osver)) {
1361 switch (osver.dwPlatformId) {
1362 case VER_PLATFORM_WIN32_WINDOWS:
1363 strcpy(name->sysname, "Windows");
1365 case VER_PLATFORM_WIN32_NT:
1366 strcpy(name->sysname, "Windows NT");
1368 case VER_PLATFORM_WIN32s:
1369 strcpy(name->sysname, "Win32s");
1372 strcpy(name->sysname, "Win32 Unknown");
1377 sprintf(name->release, "%d.%d",
1378 osver.dwMajorVersion, osver.dwMinorVersion);
1381 sprintf(name->version, "Build %d",
1382 osver.dwPlatformId == VER_PLATFORM_WIN32_NT
1383 ? osver.dwBuildNumber : (osver.dwBuildNumber & 0xffff));
1384 if (osver.szCSDVersion[0]) {
1385 char *buf = name->version + strlen(name->version);
1386 sprintf(buf, " (%s)", osver.szCSDVersion);
1390 *name->sysname = '\0';
1391 *name->version = '\0';
1392 *name->release = '\0';
1396 hep = win32_gethostbyname("localhost");
1398 STRLEN len = strlen(hep->h_name);
1399 if (len <= nodemax) {
1400 strcpy(name->nodename, hep->h_name);
1403 strncpy(name->nodename, hep->h_name, nodemax);
1404 name->nodename[nodemax] = '\0';
1409 if (!GetComputerName(name->nodename, &sz))
1410 *name->nodename = '\0';
1413 /* machine (architecture) */
1417 GetSystemInfo(&info);
1420 switch (info.DUMMYUNIONNAME.DUMMYSTRUCTNAME.wProcessorArchitecture) {
1423 switch (info.u.s.wProcessorArchitecture) {
1425 switch (info.wProcessorArchitecture) {
1428 case PROCESSOR_ARCHITECTURE_INTEL:
1429 arch = "x86"; break;
1430 case PROCESSOR_ARCHITECTURE_MIPS:
1431 arch = "mips"; break;
1432 case PROCESSOR_ARCHITECTURE_ALPHA:
1433 arch = "alpha"; break;
1434 case PROCESSOR_ARCHITECTURE_PPC:
1435 arch = "ppc"; break;
1437 arch = "unknown"; break;
1439 strcpy(name->machine, arch);
1445 win32_waitpid(int pid, int *status, int flags)
1449 return win32_wait(status);
1451 long child = find_pid(pid);
1453 HANDLE hProcess = w32_child_handles[child];
1454 DWORD waitcode = WaitForSingleObject(hProcess, INFINITE);
1455 if (waitcode != WAIT_FAILED) {
1456 if (GetExitCodeProcess(hProcess, &waitcode)) {
1457 *status = (int)((waitcode & 0xff) << 8);
1458 retval = (int)w32_child_pids[child];
1459 remove_dead_process(child);
1467 retval = cwait(status, pid, WAIT_CHILD);
1468 /* cwait() returns "correctly" on Borland */
1469 #ifndef __BORLANDC__
1475 return retval >= 0 ? pid : retval;
1479 win32_wait(int *status)
1481 /* XXX this wait emulation only knows about processes
1482 * spawned via win32_spawnvp(P_NOWAIT, ...).
1485 DWORD exitcode, waitcode;
1487 if (!w32_num_children) {
1492 /* if a child exists, wait for it to die */
1493 waitcode = WaitForMultipleObjects(w32_num_children,
1497 if (waitcode != WAIT_FAILED) {
1498 if (waitcode >= WAIT_ABANDONED_0
1499 && waitcode < WAIT_ABANDONED_0 + w32_num_children)
1500 i = waitcode - WAIT_ABANDONED_0;
1502 i = waitcode - WAIT_OBJECT_0;
1503 if (GetExitCodeProcess(w32_child_handles[i], &exitcode) ) {
1504 *status = (int)((exitcode & 0xff) << 8);
1505 retval = (int)w32_child_pids[i];
1506 remove_dead_process(i);
1512 errno = GetLastError();
1516 static UINT timerid = 0;
1518 static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
1520 KillTimer(NULL,timerid);
1525 DllExport unsigned int
1526 win32_alarm(unsigned int sec)
1529 * the 'obvious' implentation is SetTimer() with a callback
1530 * which does whatever receiving SIGALRM would do
1531 * we cannot use SIGALRM even via raise() as it is not
1532 * one of the supported codes in <signal.h>
1534 * Snag is unless something is looking at the message queue
1535 * nothing happens :-(
1539 timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
1541 croak("Cannot set timer");
1547 KillTimer(NULL,timerid);
1554 #if defined(HAVE_DES_FCRYPT) || defined(PERL_OBJECT)
1555 #ifdef HAVE_DES_FCRYPT
1556 extern char * des_fcrypt(const char *txt, const char *salt, char *cbuf);
1560 win32_crypt(const char *txt, const char *salt)
1562 #ifdef HAVE_DES_FCRYPT
1564 return des_fcrypt(txt, salt, crypt_buffer);
1566 die("The crypt() function is unimplemented due to excessive paranoia.");
1572 #ifdef USE_FIXED_OSFHANDLE
1574 EXTERN_C int __cdecl _alloc_osfhnd(void);
1575 EXTERN_C int __cdecl _set_osfhnd(int fh, long value);
1576 EXTERN_C void __cdecl _lock_fhandle(int);
1577 EXTERN_C void __cdecl _unlock_fhandle(int);
1578 EXTERN_C void __cdecl _unlock(int);
1580 #if (_MSC_VER >= 1000)
1582 long osfhnd; /* underlying OS file HANDLE */
1583 char osfile; /* attributes of file (e.g., open in text mode?) */
1584 char pipech; /* one char buffer for handles opened on pipes */
1585 #if defined (_MT) && !defined (DLL_FOR_WIN32S)
1587 CRITICAL_SECTION lock;
1588 #endif /* defined (_MT) && !defined (DLL_FOR_WIN32S) */
1591 EXTERN_C ioinfo * __pioinfo[];
1593 #define IOINFO_L2E 5
1594 #define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
1595 #define _pioinfo(i) (__pioinfo[i >> IOINFO_L2E] + (i & (IOINFO_ARRAY_ELTS - 1)))
1596 #define _osfile(i) (_pioinfo(i)->osfile)
1598 #else /* (_MSC_VER >= 1000) */
1599 extern char _osfile[];
1600 #endif /* (_MSC_VER >= 1000) */
1602 #define FOPEN 0x01 /* file handle open */
1603 #define FAPPEND 0x20 /* file handle opened O_APPEND */
1604 #define FDEV 0x40 /* file handle refers to device */
1605 #define FTEXT 0x80 /* file handle is in text mode */
1607 #define _STREAM_LOCKS 26 /* Table of stream locks */
1608 #define _LAST_STREAM_LOCK (_STREAM_LOCKS+_NSTREAM_-1) /* Last stream lock */
1609 #define _FH_LOCKS (_LAST_STREAM_LOCK+1) /* Table of fh locks */
1612 *int my_open_osfhandle(long osfhandle, int flags) - open C Runtime file handle
1615 * This function allocates a free C Runtime file handle and associates
1616 * it with the Win32 HANDLE specified by the first parameter. This is a
1617 * temperary fix for WIN95's brain damage GetFileType() error on socket
1618 * we just bypass that call for socket
1621 * long osfhandle - Win32 HANDLE to associate with C Runtime file handle.
1622 * int flags - flags to associate with C Runtime file handle.
1625 * returns index of entry in fh, if successful
1626 * return -1, if no free entry is found
1630 *******************************************************************************/
1633 my_open_osfhandle(long osfhandle, int flags)
1636 char fileflags; /* _osfile flags */
1638 /* copy relevant flags from second parameter */
1641 if (flags & O_APPEND)
1642 fileflags |= FAPPEND;
1647 /* attempt to allocate a C Runtime file handle */
1648 if ((fh = _alloc_osfhnd()) == -1) {
1649 errno = EMFILE; /* too many open files */
1650 _doserrno = 0L; /* not an OS error */
1651 return -1; /* return error to caller */
1654 /* the file is open. now, set the info in _osfhnd array */
1655 _set_osfhnd(fh, osfhandle);
1657 fileflags |= FOPEN; /* mark as open */
1659 #if (_MSC_VER >= 1000)
1660 _osfile(fh) = fileflags; /* set osfile entry */
1661 _unlock_fhandle(fh);
1663 _osfile[fh] = fileflags; /* set osfile entry */
1664 _unlock(fh+_FH_LOCKS); /* unlock handle */
1667 return fh; /* return handle */
1670 #define _open_osfhandle my_open_osfhandle
1671 #endif /* USE_FIXED_OSFHANDLE */
1673 /* simulate flock by locking a range on the file */
1675 #define LK_ERR(f,i) ((f) ? (i = 0) : (errno = GetLastError()))
1676 #define LK_LEN 0xffff0000
1679 win32_flock(int fd, int oper)
1686 croak("flock() unimplemented on this platform");
1689 fh = (HANDLE)_get_osfhandle(fd);
1690 memset(&o, 0, sizeof(o));
1693 case LOCK_SH: /* shared lock */
1694 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
1696 case LOCK_EX: /* exclusive lock */
1697 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
1699 case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
1700 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
1702 case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
1703 LK_ERR(LockFileEx(fh,
1704 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
1705 0, LK_LEN, 0, &o),i);
1707 case LOCK_UN: /* unlock lock */
1708 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, 0, &o),i);
1710 default: /* unknown */
1721 * redirected io subsystem for all XS modules
1734 return (&(_environ));
1737 /* the rest are the remapped stdio routines */
1757 win32_ferror(FILE *fp)
1759 return (ferror(fp));
1764 win32_feof(FILE *fp)
1770 * Since the errors returned by the socket error function
1771 * WSAGetLastError() are not known by the library routine strerror
1772 * we have to roll our own.
1776 win32_strerror(int e)
1778 #ifndef __BORLANDC__ /* Borland intolerance */
1779 extern int sys_nerr;
1783 if (e < 0 || e > sys_nerr) {
1788 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
1789 strerror_buffer, sizeof(strerror_buffer), NULL) == 0)
1790 strcpy(strerror_buffer, "Unknown Error");
1792 return strerror_buffer;
1798 win32_str_os_error(void *sv, DWORD dwErr)
1802 dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
1803 |FORMAT_MESSAGE_IGNORE_INSERTS
1804 |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
1805 dwErr, 0, (char *)&sMsg, 1, NULL);
1807 while (0 < dwLen && isSPACE(sMsg[--dwLen]))
1809 if ('.' != sMsg[dwLen])
1814 sMsg = (char*)LocalAlloc(0, 64/**sizeof(TCHAR)*/);
1816 dwLen = sprintf(sMsg,
1817 "Unknown error #0x%lX (lookup 0x%lX)",
1818 dwErr, GetLastError());
1821 sv_setpvn((SV*)sv, sMsg, dwLen);
1828 win32_fprintf(FILE *fp, const char *format, ...)
1831 va_start(marker, format); /* Initialize variable arguments. */
1833 return (vfprintf(fp, format, marker));
1837 win32_printf(const char *format, ...)
1840 va_start(marker, format); /* Initialize variable arguments. */
1842 return (vprintf(format, marker));
1846 win32_vfprintf(FILE *fp, const char *format, va_list args)
1848 return (vfprintf(fp, format, args));
1852 win32_vprintf(const char *format, va_list args)
1854 return (vprintf(format, args));
1858 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
1860 return fread(buf, size, count, fp);
1864 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
1866 return fwrite(buf, size, count, fp);
1869 #define MODE_SIZE 10
1872 win32_fopen(const char *filename, const char *mode)
1874 WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH];
1875 if (stricmp(filename, "/dev/null")==0)
1879 A2WHELPER(mode, wMode, sizeof(wMode), GETINTERPMODE());
1880 A2WHELPER(filename, wBuffer, sizeof(wBuffer), GETINTERPMODE());
1881 return _wfopen(wBuffer, wMode);
1883 return fopen(filename, mode);
1886 #ifndef USE_SOCKETS_AS_HANDLES
1888 #define fdopen my_fdopen
1892 win32_fdopen(int handle, const char *mode)
1894 WCHAR wMode[MODE_SIZE];
1896 A2WHELPER(mode, wMode, sizeof(wMode), GETINTERPMODE());
1897 return _wfdopen(handle, wMode);
1899 return fdopen(handle, (char *) mode);
1903 win32_freopen(const char *path, const char *mode, FILE *stream)
1905 WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH];
1906 if (stricmp(path, "/dev/null")==0)
1910 A2WHELPER(mode, wMode, sizeof(wMode), GETINTERPMODE());
1911 A2WHELPER(path, wBuffer, sizeof(wBuffer), GETINTERPMODE());
1912 return _wfreopen(wBuffer, wMode, stream);
1914 return freopen(path, mode, stream);
1918 win32_fclose(FILE *pf)
1920 return my_fclose(pf); /* defined in win32sck.c */
1924 win32_fputs(const char *s,FILE *pf)
1926 return fputs(s, pf);
1930 win32_fputc(int c,FILE *pf)
1936 win32_ungetc(int c,FILE *pf)
1938 return ungetc(c,pf);
1942 win32_getc(FILE *pf)
1948 win32_fileno(FILE *pf)
1954 win32_clearerr(FILE *pf)
1961 win32_fflush(FILE *pf)
1967 win32_ftell(FILE *pf)
1973 win32_fseek(FILE *pf,long offset,int origin)
1975 return fseek(pf, offset, origin);
1979 win32_fgetpos(FILE *pf,fpos_t *p)
1981 return fgetpos(pf, p);
1985 win32_fsetpos(FILE *pf,const fpos_t *p)
1987 return fsetpos(pf, p);
1991 win32_rewind(FILE *pf)
2011 win32_fstat(int fd,struct stat *sbufptr)
2013 return fstat(fd,sbufptr);
2017 win32_pipe(int *pfd, unsigned int size, int mode)
2019 return _pipe(pfd, size, mode);
2023 * a popen() clone that respects PERL5SHELL
2027 win32_popen(const char *command, const char *mode)
2029 #ifdef USE_RTL_POPEN
2030 return _popen(command, mode);
2038 /* establish which ends read and write */
2039 if (strchr(mode,'w')) {
2040 stdfd = 0; /* stdin */
2044 else if (strchr(mode,'r')) {
2045 stdfd = 1; /* stdout */
2052 /* set the correct mode */
2053 if (strchr(mode,'b'))
2055 else if (strchr(mode,'t'))
2058 ourmode = _fmode & (O_TEXT | O_BINARY);
2060 /* the child doesn't inherit handles */
2061 ourmode |= O_NOINHERIT;
2063 if (win32_pipe( p, 512, ourmode) == -1)
2066 /* save current stdfd */
2067 if ((oldfd = win32_dup(stdfd)) == -1)
2070 /* make stdfd go to child end of pipe (implicitly closes stdfd) */
2071 /* stdfd will be inherited by the child */
2072 if (win32_dup2(p[child], stdfd) == -1)
2075 /* close the child end in parent */
2076 win32_close(p[child]);
2078 /* start the child */
2079 if ((childpid = do_spawn_nowait((char*)command)) == -1)
2082 /* revert stdfd to whatever it was before */
2083 if (win32_dup2(oldfd, stdfd) == -1)
2086 /* close saved handle */
2089 sv_setiv(*av_fetch(w32_fdpid, p[parent], TRUE), childpid);
2091 /* we have an fd, return a file stream */
2092 return (win32_fdopen(p[parent], (char *)mode));
2095 /* we don't need to check for errors here */
2099 win32_dup2(oldfd, stdfd);
2104 #endif /* USE_RTL_POPEN */
2112 win32_pclose(FILE *pf)
2114 #ifdef USE_RTL_POPEN
2118 int childpid, status;
2121 sv = *av_fetch(w32_fdpid, win32_fileno(pf), TRUE);
2123 childpid = SvIVX(sv);
2135 if (win32_waitpid(childpid, &status, 0) == -1)
2140 #endif /* USE_RTL_POPEN */
2144 win32_rename(const char *oname, const char *newname)
2146 WCHAR wOldName[MAX_PATH];
2147 WCHAR wNewName[MAX_PATH];
2149 /* XXX despite what the documentation says about MoveFileEx(),
2150 * it doesn't work under Windows95!
2154 A2WHELPER(oname, wOldName, sizeof(wOldName), GETINTERPMODE());
2155 A2WHELPER(newname, wNewName, sizeof(wNewName), GETINTERPMODE());
2156 bResult = MoveFileExW(wOldName,wNewName,
2157 MOVEFILE_COPY_ALLOWED|MOVEFILE_REPLACE_EXISTING);
2160 bResult = MoveFileExA(oname,newname,
2161 MOVEFILE_COPY_ALLOWED|MOVEFILE_REPLACE_EXISTING);
2164 DWORD err = GetLastError();
2166 case ERROR_BAD_NET_NAME:
2167 case ERROR_BAD_NETPATH:
2168 case ERROR_BAD_PATHNAME:
2169 case ERROR_FILE_NOT_FOUND:
2170 case ERROR_FILENAME_EXCED_RANGE:
2171 case ERROR_INVALID_DRIVE:
2172 case ERROR_NO_MORE_FILES:
2173 case ERROR_PATH_NOT_FOUND:
2186 char tmpname[MAX_PATH+1];
2187 char dname[MAX_PATH+1];
2188 char *endname = Nullch;
2190 DWORD from_attr, to_attr;
2192 /* if oname doesn't exist, do nothing */
2193 from_attr = GetFileAttributes(oname);
2194 if (from_attr == 0xFFFFFFFF) {
2199 /* if newname exists, rename it to a temporary name so that we
2200 * don't delete it in case oname happens to be the same file
2201 * (but perhaps accessed via a different path)
2203 to_attr = GetFileAttributes(newname);
2204 if (to_attr != 0xFFFFFFFF) {
2205 /* if newname is a directory, we fail
2206 * XXX could overcome this with yet more convoluted logic */
2207 if (to_attr & FILE_ATTRIBUTE_DIRECTORY) {
2211 tmplen = strlen(newname);
2212 strcpy(tmpname,newname);
2213 endname = tmpname+tmplen;
2214 for (; endname > tmpname ; --endname) {
2215 if (*endname == '/' || *endname == '\\') {
2220 if (endname > tmpname)
2221 endname = strcpy(dname,tmpname);
2225 /* get a temporary filename in same directory
2226 * XXX is this really the best we can do? */
2227 if (!GetTempFileName((LPCTSTR)endname, "plr", 0, tmpname)) {
2231 DeleteFile(tmpname);
2233 retval = rename(newname, tmpname);
2240 /* rename oname to newname */
2241 retval = rename(oname, newname);
2243 /* if we created a temporary file before ... */
2244 if (endname != Nullch) {
2245 /* ...and rename succeeded, delete temporary file/directory */
2247 DeleteFile(tmpname);
2248 /* else restore it to what it was */
2250 (void)rename(tmpname, newname);
2257 win32_setmode(int fd, int mode)
2259 return setmode(fd, mode);
2263 win32_lseek(int fd, long offset, int origin)
2265 return lseek(fd, offset, origin);
2275 win32_open(const char *path, int flag, ...)
2281 pmode = va_arg(ap, int);
2284 WCHAR wBuffer[MAX_PATH];
2285 if (stricmp(path, "/dev/null")==0)
2289 A2WHELPER(path, wBuffer, sizeof(wBuffer), GETINTERPMODE());
2290 return _wopen(wBuffer, flag, pmode);
2292 return open(path,flag,pmode);
2314 win32_dup2(int fd1,int fd2)
2316 return dup2(fd1,fd2);
2320 win32_read(int fd, void *buf, unsigned int cnt)
2322 return read(fd, buf, cnt);
2326 win32_write(int fd, const void *buf, unsigned int cnt)
2328 return write(fd, buf, cnt);
2332 win32_mkdir(const char *dir, int mode)
2334 return mkdir(dir); /* just ignore mode */
2338 win32_rmdir(const char *dir)
2344 win32_chdir(const char *dir)
2350 create_command_line(const char* command, const char * const *args)
2353 char *cmd, *ptr, *arg;
2354 STRLEN len = strlen(command) + 1;
2356 for (index = 0; (ptr = (char*)args[index]) != NULL; ++index)
2357 len += strlen(ptr) + 1;
2359 New(1310, cmd, len, char);
2361 strcpy(ptr, command);
2363 for (index = 0; (arg = (char*)args[index]) != NULL; ++index) {
2373 qualified_path(const char *cmd)
2376 char *fullcmd, *curfullcmd;
2382 fullcmd = (char*)cmd;
2384 if (*fullcmd == '/' || *fullcmd == '\\')
2391 pathstr = win32_getenv("PATH");
2392 New(0, fullcmd, MAX_PATH+1, char);
2393 curfullcmd = fullcmd;
2398 /* start by appending the name to the current prefix */
2399 strcpy(curfullcmd, cmd);
2400 curfullcmd += cmdlen;
2402 /* if it doesn't end with '.', or has no extension, try adding
2403 * a trailing .exe first */
2404 if (cmd[cmdlen-1] != '.'
2405 && (cmdlen < 4 || cmd[cmdlen-4] != '.'))
2407 strcpy(curfullcmd, ".exe");
2408 res = GetFileAttributes(fullcmd);
2409 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
2414 /* that failed, try the bare name */
2415 res = GetFileAttributes(fullcmd);
2416 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
2419 /* quit if no other path exists, or if cmd already has path */
2420 if (!pathstr || !*pathstr || has_slash)
2423 /* skip leading semis */
2424 while (*pathstr == ';')
2427 /* build a new prefix from scratch */
2428 curfullcmd = fullcmd;
2429 while (*pathstr && *pathstr != ';') {
2430 if (*pathstr == '"') { /* foo;"baz;etc";bar */
2431 pathstr++; /* skip initial '"' */
2432 while (*pathstr && *pathstr != '"') {
2433 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
2434 *curfullcmd++ = *pathstr;
2438 pathstr++; /* skip trailing '"' */
2441 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
2442 *curfullcmd++ = *pathstr;
2447 pathstr++; /* skip trailing semi */
2448 if (curfullcmd > fullcmd /* append a dir separator */
2449 && curfullcmd[-1] != '/' && curfullcmd[-1] != '\\')
2451 *curfullcmd++ = '\\';
2459 /* XXX this needs to be made more compatible with the spawnvp()
2460 * provided by the various RTLs. In particular, searching for
2461 * *.{com,bat,cmd} files (as done by the RTLs) is unimplemented.
2462 * This doesn't significantly affect perl itself, because we
2463 * always invoke things using PERL5SHELL if a direct attempt to
2464 * spawn the executable fails.
2466 * XXX splitting and rejoining the commandline between do_aspawn()
2467 * and win32_spawnvp() could also be avoided.
2471 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
2473 #ifdef USE_RTL_SPAWNVP
2474 return spawnvp(mode, cmdname, (char * const *)argv);
2477 STARTUPINFO StartupInfo;
2478 PROCESS_INFORMATION ProcessInformation;
2481 char *cmd = create_command_line(cmdname, strcmp(cmdname, argv[0]) == 0
2483 char *fullcmd = Nullch;
2486 case P_NOWAIT: /* asynch + remember result */
2487 if (w32_num_children >= MAXIMUM_WAIT_OBJECTS) {
2493 case P_WAIT: /* synchronous execution */
2495 default: /* invalid mode */
2500 memset(&StartupInfo,0,sizeof(StartupInfo));
2501 StartupInfo.cb = sizeof(StartupInfo);
2502 StartupInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
2503 StartupInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
2504 StartupInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
2505 if (StartupInfo.hStdInput != INVALID_HANDLE_VALUE &&
2506 StartupInfo.hStdOutput != INVALID_HANDLE_VALUE &&
2507 StartupInfo.hStdError != INVALID_HANDLE_VALUE)
2509 StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
2512 create |= CREATE_NEW_CONSOLE;
2516 StartupInfo.dwFlags |= STARTF_USESHOWWINDOW;
2517 StartupInfo.wShowWindow = SW_HIDE;
2521 if (!CreateProcess(cmdname, /* search PATH to find executable */
2522 cmd, /* executable, and its arguments */
2523 NULL, /* process attributes */
2524 NULL, /* thread attributes */
2525 TRUE, /* inherit handles */
2526 create, /* creation flags */
2527 NULL, /* inherit environment */
2528 NULL, /* inherit cwd */
2530 &ProcessInformation))
2532 /* initial NULL argument to CreateProcess() does a PATH
2533 * search, but it always first looks in the directory
2534 * where the current process was started, which behavior
2535 * is undesirable for backward compatibility. So we
2536 * jump through our own hoops by picking out the path
2537 * we really want it to use. */
2539 fullcmd = qualified_path(cmdname);
2550 if (mode == P_NOWAIT) {
2551 /* asynchronous spawn -- store handle, return PID */
2552 w32_child_handles[w32_num_children] = ProcessInformation.hProcess;
2553 ret = w32_child_pids[w32_num_children] = ProcessInformation.dwProcessId;
2557 WaitForSingleObject(ProcessInformation.hProcess, INFINITE);
2558 GetExitCodeProcess(ProcessInformation.hProcess, &ret);
2559 CloseHandle(ProcessInformation.hProcess);
2562 CloseHandle(ProcessInformation.hThread);
2571 win32_execv(const char *cmdname, const char *const *argv)
2573 return execv(cmdname, (char *const *)argv);
2577 win32_execvp(const char *cmdname, const char *const *argv)
2579 return execvp(cmdname, (char *const *)argv);
2583 win32_perror(const char *str)
2589 win32_setbuf(FILE *pf, char *buf)
2595 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
2597 return setvbuf(pf, buf, type, size);
2601 win32_flushall(void)
2607 win32_fcloseall(void)
2613 win32_fgets(char *s, int n, FILE *pf)
2615 return fgets(s, n, pf);
2625 win32_fgetc(FILE *pf)
2631 win32_putc(int c, FILE *pf)
2637 win32_puts(const char *s)
2649 win32_putchar(int c)
2656 #ifndef USE_PERL_SBRK
2658 static char *committed = NULL;
2659 static char *base = NULL;
2660 static char *reserved = NULL;
2661 static char *brk = NULL;
2662 static DWORD pagesize = 0;
2663 static DWORD allocsize = 0;
2671 GetSystemInfo(&info);
2672 /* Pretend page size is larger so we don't perpetually
2673 * call the OS to commit just one page ...
2675 pagesize = info.dwPageSize << 3;
2676 allocsize = info.dwAllocationGranularity;
2678 /* This scheme fails eventually if request for contiguous
2679 * block is denied so reserve big blocks - this is only
2680 * address space not memory ...
2682 if (brk+need >= reserved)
2684 DWORD size = 64*1024*1024;
2686 if (committed && reserved && committed < reserved)
2688 /* Commit last of previous chunk cannot span allocations */
2689 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
2691 committed = reserved;
2693 /* Reserve some (more) space
2694 * Note this is a little sneaky, 1st call passes NULL as reserved
2695 * so lets system choose where we start, subsequent calls pass
2696 * the old end address so ask for a contiguous block
2698 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
2701 reserved = addr+size;
2716 if (brk > committed)
2718 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
2719 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
2734 win32_malloc(size_t size)
2736 return malloc(size);
2740 win32_calloc(size_t numitems, size_t size)
2742 return calloc(numitems,size);
2746 win32_realloc(void *block, size_t size)
2748 return realloc(block,size);
2752 win32_free(void *block)
2759 win32_open_osfhandle(long handle, int flags)
2761 return _open_osfhandle(handle, flags);
2765 win32_get_osfhandle(int fd)
2767 return _get_osfhandle(fd);
2778 SV *sv = sv_newmortal();
2779 /* Make one call with zero size - return value is required size */
2780 DWORD len = GetCurrentDirectory((DWORD)0,NULL);
2781 SvUPGRADE(sv,SVt_PV);
2783 SvCUR(sv) = GetCurrentDirectory((DWORD) SvLEN(sv), SvPVX(sv));
2786 * then it worked, set PV valid,
2787 * else leave it 'undef'
2803 croak("usage: Win32::SetCurrentDirectory($cwd)");
2804 if (SetCurrentDirectory(SvPV_nolen(ST(0))))
2811 XS(w32_GetNextAvailDrive)
2815 char root[] = "_:\\";
2820 if (GetDriveType(root) == 1) {
2829 XS(w32_GetLastError)
2833 XSRETURN_IV(GetLastError());
2837 XS(w32_SetLastError)
2841 croak("usage: Win32::SetLastError($error)");
2842 SetLastError(SvIV(ST(0)));
2850 char *name = getlogin_buffer;
2851 DWORD size = sizeof(getlogin_buffer);
2853 if (GetUserName(name,&size)) {
2854 /* size includes NULL */
2855 ST(0) = sv_2mortal(newSVpvn(name,size-1));
2865 char name[MAX_COMPUTERNAME_LENGTH+1];
2866 DWORD size = sizeof(name);
2868 if (GetComputerName(name,&size)) {
2869 /* size does NOT include NULL :-( */
2870 ST(0) = sv_2mortal(newSVpvn(name,size));
2881 #ifndef HAS_NETWKSTAGETINFO
2882 /* mingw32 (and Win95) don't have NetWksta*(), so do it the old way */
2884 DWORD size = sizeof(name);
2886 if (GetUserName(name,&size)) {
2888 DWORD sidlen = sizeof(sid);
2890 DWORD dnamelen = sizeof(dname);
2892 if (LookupAccountName(NULL, name, (PSID)&sid, &sidlen,
2893 dname, &dnamelen, &snu)) {
2894 XSRETURN_PV(dname); /* all that for this */
2898 /* this way is more reliable, in case user has a local account.
2899 * XXX need dynamic binding of netapi32.dll symbols or this will fail on
2900 * Win95. Probably makes more sense to move it into libwin32. */
2902 DWORD dnamelen = sizeof(dname);
2903 PWKSTA_INFO_100 pwi;
2905 if (NERR_Success == NetWkstaGetInfo(NULL, 100, (LPBYTE*)&pwi)) {
2906 if (pwi->wki100_langroup && *(pwi->wki100_langroup)) {
2907 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_langroup,
2908 -1, (LPSTR)dname, dnamelen, NULL, NULL);
2911 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_computername,
2912 -1, (LPSTR)dname, dnamelen, NULL, NULL);
2914 NetApiBufferFree(pwi);
2926 DWORD flags, filecomplen;
2927 if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
2928 &flags, fsname, sizeof(fsname))) {
2929 if (GIMME_V == G_ARRAY) {
2930 XPUSHs(sv_2mortal(newSVpvn(fsname,strlen(fsname))));
2931 XPUSHs(sv_2mortal(newSViv(flags)));
2932 XPUSHs(sv_2mortal(newSViv(filecomplen)));
2937 XSRETURN_PV(fsname);
2943 XS(w32_GetOSVersion)
2946 OSVERSIONINFO osver;
2948 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
2949 if (GetVersionEx(&osver)) {
2950 XPUSHs(newSVpvn(osver.szCSDVersion, strlen(osver.szCSDVersion)));
2951 XPUSHs(newSViv(osver.dwMajorVersion));
2952 XPUSHs(newSViv(osver.dwMinorVersion));
2953 XPUSHs(newSViv(osver.dwBuildNumber));
2954 XPUSHs(newSViv(osver.dwPlatformId));
2966 XSRETURN_IV(IsWinNT());
2974 XSRETURN_IV(IsWin95());
2978 XS(w32_FormatMessage)
2985 croak("usage: Win32::FormatMessage($errno)");
2987 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
2988 &source, SvIV(ST(0)), 0,
2989 msgbuf, sizeof(msgbuf)-1, NULL))
2990 XSRETURN_PV(msgbuf);
3000 PROCESS_INFORMATION stProcInfo;
3001 STARTUPINFO stStartInfo;
3002 BOOL bSuccess = FALSE;
3005 croak("usage: Win32::Spawn($cmdName, $args, $PID)");
3007 cmd = SvPV_nolen(ST(0));
3008 args = SvPV_nolen(ST(1));
3010 memset(&stStartInfo, 0, sizeof(stStartInfo)); /* Clear the block */
3011 stStartInfo.cb = sizeof(stStartInfo); /* Set the structure size */
3012 stStartInfo.dwFlags = STARTF_USESHOWWINDOW; /* Enable wShowWindow control */
3013 stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE; /* Start min (normal) */
3016 cmd, /* Image path */
3017 args, /* Arguments for command line */
3018 NULL, /* Default process security */
3019 NULL, /* Default thread security */
3020 FALSE, /* Must be TRUE to use std handles */
3021 NORMAL_PRIORITY_CLASS, /* No special scheduling */
3022 NULL, /* Inherit our environment block */
3023 NULL, /* Inherit our currrent directory */
3024 &stStartInfo, /* -> Startup info */
3025 &stProcInfo)) /* <- Process info (if OK) */
3027 CloseHandle(stProcInfo.hThread);/* library source code does this. */
3028 sv_setiv(ST(2), stProcInfo.dwProcessId);
3031 XSRETURN_IV(bSuccess);
3035 XS(w32_GetTickCount)
3038 DWORD msec = GetTickCount();
3046 XS(w32_GetShortPathName)
3053 croak("usage: Win32::GetShortPathName($longPathName)");
3055 shortpath = sv_mortalcopy(ST(0));
3056 SvUPGRADE(shortpath, SVt_PV);
3057 /* src == target is allowed */
3059 len = GetShortPathName(SvPVX(shortpath),
3062 } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
3064 SvCUR_set(shortpath,len);
3072 XS(w32_GetFullPathName)
3081 croak("usage: Win32::GetFullPathName($filename)");
3084 fullpath = sv_mortalcopy(filename);
3085 SvUPGRADE(fullpath, SVt_PV);
3087 len = GetFullPathName(SvPVX(filename),
3091 } while (len >= SvLEN(fullpath) && sv_grow(fullpath,len+1));
3093 if (GIMME_V == G_ARRAY) {
3095 XST_mPV(1,filepart);
3096 len = filepart - SvPVX(fullpath);
3099 SvCUR_set(fullpath,len);
3107 XS(w32_GetLongPathName)
3111 char tmpbuf[MAX_PATH+1];
3116 croak("usage: Win32::GetLongPathName($pathname)");
3119 pathstr = SvPV(path,len);
3120 strcpy(tmpbuf, pathstr);
3121 pathstr = win32_longpath(tmpbuf);
3123 ST(0) = sv_2mortal(newSVpvn(pathstr, strlen(pathstr)));
3134 croak("usage: Win32::Sleep($milliseconds)");
3144 croak("usage: Win32::CopyFile($from, $to, $overwrite)");
3145 if (CopyFile(SvPV_nolen(ST(0)), SvPV_nolen(ST(1)), !SvTRUE(ST(2))))
3151 Perl_init_os_extras()
3153 char *file = __FILE__;
3156 w32_perlshell_tokens = Nullch;
3157 w32_perlshell_items = -1;
3158 w32_fdpid = newAV(); /* XXX needs to be in Perl_win32_init()? */
3159 New(1313, w32_children, 1, child_tab);
3160 w32_num_children = 0;
3162 /* these names are Activeware compatible */
3163 newXS("Win32::GetCwd", w32_GetCwd, file);
3164 newXS("Win32::SetCwd", w32_SetCwd, file);
3165 newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
3166 newXS("Win32::GetLastError", w32_GetLastError, file);
3167 newXS("Win32::SetLastError", w32_SetLastError, file);
3168 newXS("Win32::LoginName", w32_LoginName, file);
3169 newXS("Win32::NodeName", w32_NodeName, file);
3170 newXS("Win32::DomainName", w32_DomainName, file);
3171 newXS("Win32::FsType", w32_FsType, file);
3172 newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
3173 newXS("Win32::IsWinNT", w32_IsWinNT, file);
3174 newXS("Win32::IsWin95", w32_IsWin95, file);
3175 newXS("Win32::FormatMessage", w32_FormatMessage, file);
3176 newXS("Win32::Spawn", w32_Spawn, file);
3177 newXS("Win32::GetTickCount", w32_GetTickCount, file);
3178 newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
3179 newXS("Win32::GetFullPathName", w32_GetFullPathName, file);
3180 newXS("Win32::GetLongPathName", w32_GetLongPathName, file);
3181 newXS("Win32::CopyFile", w32_CopyFile, file);
3182 newXS("Win32::Sleep", w32_Sleep, file);
3184 /* XXX Bloat Alert! The following Activeware preloads really
3185 * ought to be part of Win32::Sys::*, so they're not included
3188 /* LookupAccountName
3190 * InitiateSystemShutdown
3191 * AbortSystemShutdown
3192 * ExpandEnvrironmentStrings
3197 Perl_win32_init(int *argcp, char ***argvp)
3199 /* Disable floating point errors, Perl will trap the ones we
3200 * care about. VC++ RTL defaults to switching these off
3201 * already, but the Borland RTL doesn't. Since we don't
3202 * want to be at the vendor's whim on the default, we set
3203 * it explicitly here.
3205 #if !defined(_ALPHA_) && !defined(__GNUC__)
3206 _control87(MCW_EM, MCW_EM);
3211 #ifdef USE_BINMODE_SCRIPTS
3214 win32_strip_return(SV *sv)
3216 char *s = SvPVX(sv);
3217 char *e = s+SvCUR(sv);
3221 if (*s == '\r' && s[1] == '\n')
3231 SvCUR_set(sv,d-SvPVX(sv));