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(pTHX_ 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];
132 return (os_id() == VER_PLATFORM_WIN32_WINDOWS);
138 return (os_id() == VER_PLATFORM_WIN32_NT);
141 /* *ptr is expected to point to valid allocated space (can't be NULL) */
143 GetRegStrFromKey(HKEY hkey, const char *lpszValueName, char** ptr, DWORD* lpDataLen)
145 /* Retrieve a REG_SZ or REG_EXPAND_SZ from the registry */
148 const char *subkey = "Software\\Perl";
152 retval = RegOpenKeyEx(hkey, subkey, 0, KEY_READ, &handle);
153 if (retval == ERROR_SUCCESS) {
154 retval = RegQueryValueEx(handle, lpszValueName, 0, &type, NULL, lpDataLen);
155 if (retval == ERROR_SUCCESS && type == REG_SZ) {
156 Renew(*ptr, *lpDataLen, char);
157 retval = RegQueryValueEx(handle, lpszValueName, 0, NULL,
158 (PBYTE)*ptr, lpDataLen);
159 if (retval == ERROR_SUCCESS)
167 /* *ptr is expected to point to valid allocated space (can't be NULL) */
169 GetRegStr(const char *lpszValueName, char** ptr, DWORD* lpDataLen)
171 char *str = GetRegStrFromKey(HKEY_CURRENT_USER, lpszValueName, ptr, lpDataLen);
173 str = GetRegStrFromKey(HKEY_LOCAL_MACHINE, lpszValueName, ptr, lpDataLen);
177 /* *prev_path is expected to point to valid allocated space (can't be NULL) */
179 get_emd_part(char **prev_path, char *trailing_path, ...)
183 char mod_name[MAX_PATH+1];
187 int oldsize, newsize;
189 va_start(ap, trailing_path);
190 strip = va_arg(ap, char *);
192 sprintf(base, "%5.3f",
193 (double)PERL_REVISION + ((double)PERL_VERSION / (double)1000));
195 if (!*w32_module_name) {
196 GetModuleFileName((HMODULE)((w32_perldll_handle == INVALID_HANDLE_VALUE)
197 ? GetModuleHandle(NULL)
198 : w32_perldll_handle),
199 w32_module_name, sizeof(w32_module_name));
201 /* try to get full path to binary (which may be mangled when perl is
202 * run from a 16-bit app) */
203 /*PerlIO_printf(PerlIO_stderr(), "Before %s\n", w32_module_name);*/
204 (void)win32_longpath(w32_module_name);
205 /*PerlIO_printf(PerlIO_stderr(), "After %s\n", w32_module_name);*/
207 /* normalize to forward slashes */
208 ptr = w32_module_name;
215 strcpy(mod_name, w32_module_name);
216 ptr = strrchr(mod_name, '/');
217 while (ptr && strip) {
218 /* look for directories to skip back */
221 ptr = strrchr(mod_name, '/');
222 /* avoid stripping component if there is no slash,
223 * or it doesn't match ... */
224 if (!ptr || stricmp(ptr+1, strip) != 0) {
225 /* ... but not if component matches 5.00X* */
226 if (!ptr || !(*strip == '5' && *(ptr+1) == '5'
227 && strncmp(strip, base, 5) == 0
228 && strncmp(ptr+1, base, 5) == 0))
234 strip = va_arg(ap, char *);
242 strcpy(++ptr, trailing_path);
244 /* only add directory if it exists */
245 if (GetFileAttributes(mod_name) != (DWORD) -1) {
246 /* directory exists */
247 newsize = strlen(mod_name) + 1;
248 oldsize = strlen(*prev_path) + 1;
249 newsize += oldsize; /* includes plus 1 for ';' */
250 Renew(*prev_path, newsize, char);
251 (*prev_path)[oldsize-1] = ';';
252 strcpy(&(*prev_path)[oldsize], mod_name);
260 win32_get_privlib(pTHX_ char *pl)
262 char *stdlib = "lib";
263 char buffer[MAX_PATH+1];
266 SV *sv = sv_2mortal(newSVpvn("",127));
268 /* $stdlib = $HKCU{"lib-$]"} || $HKLM{"lib-$]"} || $HKCU{"lib"} || $HKLM{"lib"} || ""; */
269 sprintf(buffer, "%s-%s", stdlib, pl);
271 if (!GetRegStr(buffer, path, &datalen))
272 (void)GetRegStr(stdlib, path, &datalen);
274 /* $stdlib .= ";$EMD/../../lib" */
275 (void)get_emd_part(path, stdlib, ARCHNAME, "bin", Nullch);
276 SvCUR_set(sv, strlen(*path));
277 SvLEN_set(sv, SvCUR(sv)+1);
282 win32_get_sitelib(pTHX_ char *pl)
284 char *sitelib = "sitelib";
286 char pathstr[MAX_PATH+1];
288 char **path1, *str1 = Nullch;
289 char **path2, *str2 = Nullch;
291 SV *sv1 = sv_2mortal(newSVpvn("",127));
292 SV *sv2 = sv_2mortal(newSVpvn("",127));
294 /* $HKCU{"sitelib-$]"} || $HKLM{"sitelib-$]"} . ---; */
295 sprintf(regstr, "%s-%s", sitelib, pl);
297 (void)GetRegStr(regstr, path1, &datalen);
300 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/site/$]/lib"; */
301 sprintf(pathstr, "site/%s/lib", pl);
302 str1 = get_emd_part(path1, pathstr, ARCHNAME, "bin", pl, Nullch);
303 if (!str1 && strlen(pl) == 7) {
304 /* pl may have been SUBVERSION-specific; try again without
306 sprintf(pathstr, "site/%.5s/lib", pl);
307 str1 = get_emd_part(path1, pathstr, ARCHNAME, "bin", pl, Nullch);
310 /* $HKCU{'sitelib'} || $HKLM{'sitelib'} . ---; */
312 (void)GetRegStr(sitelib, path2, &datalen);
315 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/site/lib"; */
316 str2 = get_emd_part(path2, "site/lib", ARCHNAME, "bin", pl, Nullch);
318 SvCUR_set(sv1, strlen(*path1));
319 SvLEN_set(sv1, SvCUR(sv1)+1);
320 SvCUR_set(sv2, strlen(*path2));
321 SvLEN_set(sv2, SvCUR(sv2)+1);
328 sv_catpvn(sv1, ";", 1);
336 has_shell_metachars(char *ptr)
342 * Scan string looking for redirection (< or >) or pipe
343 * characters (|) that are not in a quoted string.
344 * Shell variable interpolation (%VAR%) can also happen inside strings.
376 #if !defined(PERL_OBJECT)
377 /* since the current process environment is being updated in util.c
378 * the library functions will get the correct environment
381 Perl_my_popen(pTHX_ char *cmd, char *mode)
384 #define fixcmd(x) { \
385 char *pspace = strchr((x),' '); \
388 while (p < pspace) { \
399 PERL_FLUSHALL_FOR_CHILD;
400 return win32_popen(cmd, mode);
404 Perl_my_pclose(pTHX_ PerlIO *fp)
406 return win32_pclose(fp);
413 static OSVERSIONINFO osver;
415 if (osver.dwPlatformId != w32_platform) {
416 memset(&osver, 0, sizeof(OSVERSIONINFO));
417 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
418 GetVersionEx(&osver);
419 w32_platform = osver.dwPlatformId;
421 return (w32_platform);
424 /* Tokenize a string. Words are null-separated, and the list
425 * ends with a doubled null. Any character (except null and
426 * including backslash) may be escaped by preceding it with a
427 * backslash (the backslash will be stripped).
428 * Returns number of words in result buffer.
431 tokenize(char *str, char **dest, char ***destv)
433 char *retstart = Nullch;
434 char **retvstart = 0;
437 int slen = strlen(str);
439 register char **retv;
440 New(1307, ret, slen+2, char);
441 New(1308, retv, (slen+3)/2, char*);
449 if (*ret == '\\' && *str)
451 else if (*ret == ' ') {
467 retvstart[items] = Nullch;
479 if (!w32_perlshell_tokens) {
480 /* we don't use COMSPEC here for two reasons:
481 * 1. the same reason perl on UNIX doesn't use SHELL--rampant and
482 * uncontrolled unportability of the ensuing scripts.
483 * 2. PERL5SHELL could be set to a shell that may not be fit for
484 * interactive use (which is what most programs look in COMSPEC
487 char* defaultshell = (IsWinNT() ? "cmd.exe /x/c" : "command.com /c");
488 char *usershell = getenv("PERL5SHELL");
489 w32_perlshell_items = tokenize(usershell ? usershell : defaultshell,
490 &w32_perlshell_tokens,
496 do_aspawn(pTHX_ void *vreally, void **vmark, void **vsp)
498 SV *really = (SV*)vreally;
499 SV **mark = (SV**)vmark;
511 New(1306, argv, (sp - mark) + w32_perlshell_items + 2, char*);
513 if (SvNIOKp(*(mark+1)) && !SvPOKp(*(mark+1))) {
518 while (++mark <= sp) {
519 if (*mark && (str = SvPV_nolen(*mark)))
526 status = win32_spawnvp(flag,
527 (const char*)(really ? SvPV_nolen(really) : argv[0]),
528 (const char* const*)argv);
530 if (status < 0 && (errno == ENOEXEC || errno == ENOENT)) {
531 /* possible shell-builtin, invoke with shell */
533 sh_items = w32_perlshell_items;
535 argv[index+sh_items] = argv[index];
536 while (--sh_items >= 0)
537 argv[sh_items] = w32_perlshell_vec[sh_items];
539 status = win32_spawnvp(flag,
540 (const char*)(really ? SvPV_nolen(really) : argv[0]),
541 (const char* const*)argv);
544 if (flag != P_NOWAIT) {
547 Perl_warn(aTHX_ "Can't spawn \"%s\": %s", argv[0], strerror(errno));
552 PL_statusvalue = status;
559 do_spawn2(pTHX_ char *cmd, int exectype)
565 BOOL needToTry = TRUE;
568 /* Save an extra exec if possible. See if there are shell
569 * metacharacters in it */
570 if (!has_shell_metachars(cmd)) {
571 New(1301,argv, strlen(cmd) / 2 + 2, char*);
572 New(1302,cmd2, strlen(cmd) + 1, char);
575 for (s = cmd2; *s;) {
576 while (*s && isSPACE(*s))
580 while (*s && !isSPACE(*s))
589 status = win32_spawnvp(P_WAIT, argv[0],
590 (const char* const*)argv);
592 case EXECF_SPAWN_NOWAIT:
593 status = win32_spawnvp(P_NOWAIT, argv[0],
594 (const char* const*)argv);
597 status = win32_execvp(argv[0], (const char* const*)argv);
600 if (status != -1 || errno == 0)
610 New(1306, argv, w32_perlshell_items + 2, char*);
611 while (++i < w32_perlshell_items)
612 argv[i] = w32_perlshell_vec[i];
617 status = win32_spawnvp(P_WAIT, argv[0],
618 (const char* const*)argv);
620 case EXECF_SPAWN_NOWAIT:
621 status = win32_spawnvp(P_NOWAIT, argv[0],
622 (const char* const*)argv);
625 status = win32_execvp(argv[0], (const char* const*)argv);
631 if (exectype != EXECF_SPAWN_NOWAIT) {
634 Perl_warn(aTHX_ "Can't %s \"%s\": %s",
635 (exectype == EXECF_EXEC ? "exec" : "spawn"),
636 cmd, strerror(errno));
641 PL_statusvalue = status;
647 do_spawn(pTHX_ char *cmd)
649 return do_spawn2(aTHX_ cmd, EXECF_SPAWN);
653 do_spawn_nowait(pTHX_ char *cmd)
655 return do_spawn2(aTHX_ cmd, EXECF_SPAWN_NOWAIT);
659 Perl_do_exec(pTHX_ char *cmd)
661 do_spawn2(aTHX_ cmd, EXECF_EXEC);
665 /* The idea here is to read all the directory names into a string table
666 * (separated by nulls) and when one of the other dir functions is called
667 * return the pointer to the current file name.
670 win32_opendir(char *filename)
676 char scanname[MAX_PATH+3];
678 WIN32_FIND_DATAA aFindData;
679 WIN32_FIND_DATAW wFindData;
681 char buffer[MAX_PATH*2];
682 WCHAR wbuffer[MAX_PATH];
685 len = strlen(filename);
689 /* check to see if filename is a directory */
690 if (win32_stat(filename, &sbuf) < 0 || !S_ISDIR(sbuf.st_mode))
693 /* Get us a DIR structure */
694 Newz(1303, p, 1, DIR);
698 /* Create the search pattern */
699 strcpy(scanname, filename);
701 /* bare drive name means look in cwd for drive */
702 if (len == 2 && isALPHA(scanname[0]) && scanname[1] == ':') {
703 scanname[len++] = '.';
704 scanname[len++] = '/';
706 else if (scanname[len-1] != '/' && scanname[len-1] != '\\') {
707 scanname[len++] = '/';
709 scanname[len++] = '*';
710 scanname[len] = '\0';
712 /* do the FindFirstFile call */
714 A2WHELPER(scanname, wbuffer, sizeof(wbuffer), GETINTERPMODE());
715 fh = FindFirstFileW(wbuffer, &wFindData);
718 fh = FindFirstFileA(scanname, &aFindData);
720 if (fh == INVALID_HANDLE_VALUE) {
721 /* FindFirstFile() fails on empty drives! */
722 if (GetLastError() == ERROR_FILE_NOT_FOUND)
728 /* now allocate the first part of the string table for
729 * the filenames that we find.
732 W2AHELPER(wFindData.cFileName, buffer, sizeof(buffer), GETINTERPMODE());
736 ptr = aFindData.cFileName;
739 New(1304, p->start, idx, char);
740 if (p->start == NULL)
741 Perl_croak_nocontext("opendir: malloc failed!\n");
742 strcpy(p->start, ptr);
745 /* loop finding all the files that match the wildcard
746 * (which should be all of them in this directory!).
747 * the variable idx should point one past the null terminator
748 * of the previous string found.
751 ? FindNextFileW(fh, &wFindData)
752 : FindNextFileA(fh, &aFindData)) {
754 W2AHELPER(wFindData.cFileName, buffer, sizeof(buffer), GETINTERPMODE());
756 /* ptr is set above to the correct area */
758 /* bump the string table size by enough for the
759 * new name and it's null terminator
761 Renew(p->start, idx+len+1, char);
762 if (p->start == NULL)
763 Perl_croak_nocontext("opendir: malloc failed!\n");
764 strcpy(&p->start[idx], ptr);
775 /* Readdir just returns the current string pointer and bumps the
776 * string pointer to the nDllExport entry.
779 win32_readdir(DIR *dirp)
782 static int dummy = 0;
785 /* first set up the structure to return */
786 len = strlen(dirp->curr);
787 strcpy(dirp->dirstr.d_name, dirp->curr);
788 dirp->dirstr.d_namlen = len;
791 dirp->dirstr.d_ino = dummy++;
793 /* Now set up for the nDllExport call to readdir */
794 dirp->curr += len + 1;
795 if (dirp->curr >= (dirp->start + dirp->size)) {
799 return &(dirp->dirstr);
805 /* Telldir returns the current string pointer position */
807 win32_telldir(DIR *dirp)
809 return (long) dirp->curr;
813 /* Seekdir moves the string pointer to a previously saved position
817 win32_seekdir(DIR *dirp, long loc)
819 dirp->curr = (char *)loc;
822 /* Rewinddir resets the string pointer to the start */
824 win32_rewinddir(DIR *dirp)
826 dirp->curr = dirp->start;
829 /* free the memory allocated by opendir */
831 win32_closedir(DIR *dirp)
833 Safefree(dirp->start);
846 * Just pretend that everyone is a superuser. NT will let us know if
847 * we don\'t really have permission to do something.
850 #define ROOT_UID ((uid_t)0)
851 #define ROOT_GID ((gid_t)0)
880 return (auid == ROOT_UID ? 0 : -1);
886 return (agid == ROOT_GID ? 0 : -1);
893 char *buf = getlogin_buffer;
894 DWORD size = sizeof(getlogin_buffer);
895 if (GetUserName(buf,&size))
901 chown(const char *path, uid_t owner, gid_t group)
911 for (child = 0 ; child < w32_num_children ; ++child) {
912 if (w32_child_pids[child] == pid)
919 remove_dead_process(long child)
922 CloseHandle(w32_child_handles[child]);
923 Copy(&w32_child_handles[child+1], &w32_child_handles[child],
924 (w32_num_children-child-1), HANDLE);
925 Copy(&w32_child_pids[child+1], &w32_child_pids[child],
926 (w32_num_children-child-1), DWORD);
932 win32_kill(int pid, int sig)
935 hProcess = OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid);
936 if (hProcess && TerminateProcess(hProcess, sig))
937 CloseHandle(hProcess);
949 DllExport unsigned int
950 win32_sleep(unsigned int t)
957 win32_stat(const char *path, struct stat *buffer)
960 int l = strlen(path);
962 WCHAR wbuffer[MAX_PATH];
965 switch(path[l - 1]) {
966 /* FindFirstFile() and stat() are buggy with a trailing
967 * backslash, so change it to a forward slash :-( */
969 strncpy(t, path, l-1);
974 /* FindFirstFile() is buggy with "x:", so add a dot :-( */
976 if (l == 2 && isALPHA(path[0])) {
977 t[0] = path[0]; t[1] = ':'; t[2] = '.'; t[3] = '\0';
986 A2WHELPER(path, wbuffer, sizeof(wbuffer), GETINTERPMODE());
987 res = _wstat(wbuffer, (struct _stat *)buffer);
990 res = stat(path, buffer);
993 /* CRT is buggy on sharenames, so make sure it really isn't.
994 * XXX using GetFileAttributesEx() will enable us to set
995 * buffer->st_*time (but note that's not available on the
996 * Windows of 1995) */
999 r = GetFileAttributesW(wbuffer);
1002 r = GetFileAttributesA(path);
1004 if (r != 0xffffffff && (r & FILE_ATTRIBUTE_DIRECTORY)) {
1005 /* buffer may still contain old garbage since stat() failed */
1006 Zero(buffer, 1, struct stat);
1007 buffer->st_mode = S_IFDIR | S_IREAD;
1009 if (!(r & FILE_ATTRIBUTE_READONLY))
1010 buffer->st_mode |= S_IWRITE | S_IEXEC;
1015 if (l == 3 && isALPHA(path[0]) && path[1] == ':'
1016 && (path[2] == '\\' || path[2] == '/'))
1018 /* The drive can be inaccessible, some _stat()s are buggy */
1020 ? !GetVolumeInformationW(wbuffer,NULL,0,NULL,NULL,NULL,NULL,0)
1021 : !GetVolumeInformationA(path,NULL,0,NULL,NULL,NULL,NULL,0)) {
1027 if (S_ISDIR(buffer->st_mode))
1028 buffer->st_mode |= S_IWRITE | S_IEXEC;
1029 else if (S_ISREG(buffer->st_mode)) {
1030 if (l >= 4 && path[l-4] == '.') {
1031 const char *e = path + l - 3;
1032 if (strnicmp(e,"exe",3)
1033 && strnicmp(e,"bat",3)
1034 && strnicmp(e,"com",3)
1035 && (IsWin95() || strnicmp(e,"cmd",3)))
1036 buffer->st_mode &= ~S_IEXEC;
1038 buffer->st_mode |= S_IEXEC;
1041 buffer->st_mode &= ~S_IEXEC;
1048 /* Find the longname of a given path. path is destructively modified.
1049 * It should have space for at least MAX_PATH characters. */
1051 win32_longpath(char *path)
1053 WIN32_FIND_DATA fdata;
1055 char tmpbuf[MAX_PATH+1];
1056 char *tmpstart = tmpbuf;
1063 if (isALPHA(path[0]) && path[1] == ':' &&
1064 (path[2] == '/' || path[2] == '\\'))
1067 *tmpstart++ = path[0];
1071 else if ((path[0] == '/' || path[0] == '\\') &&
1072 (path[1] == '/' || path[1] == '\\'))
1075 *tmpstart++ = path[0];
1076 *tmpstart++ = path[1];
1077 /* copy machine name */
1078 while (*start && *start != '/' && *start != '\\')
1079 *tmpstart++ = *start++;
1081 *tmpstart++ = *start;
1083 /* copy share name */
1084 while (*start && *start != '/' && *start != '\\')
1085 *tmpstart++ = *start++;
1089 if (sep == '/' || sep == '\\')
1093 /* walk up to slash */
1094 while (*start && *start != '/' && *start != '\\')
1097 /* discard doubled slashes */
1098 while (*start && (start[1] == '/' || start[1] == '\\'))
1102 /* stop and find full name of component */
1104 fhand = FindFirstFile(path,&fdata);
1105 if (fhand != INVALID_HANDLE_VALUE) {
1106 strcpy(tmpstart, fdata.cFileName);
1107 tmpstart += strlen(fdata.cFileName);
1115 /* failed a step, just return without side effects */
1116 /*PerlIO_printf(PerlIO_stderr(), "Failed to find %s\n", path);*/
1121 strcpy(path,tmpbuf);
1125 #ifndef USE_WIN32_RTL_ENV
1128 win32_getenv(const char *name)
1131 static char *curitem = Nullch; /* XXX threadead */
1132 static WCHAR *wCuritem = (WCHAR*)Nullch; /* XXX threadead */
1133 static DWORD curlen = 0, wCurlen = 0;/* XXX threadead */
1134 WCHAR wBuffer[MAX_PATH];
1140 New(1306,wCuritem,wCurlen,WCHAR);
1145 New(1305,curitem,curlen,char);
1149 A2WHELPER(name, wBuffer, sizeof(wBuffer), GETINTERPMODE());
1150 needlen = GetEnvironmentVariableW(wBuffer,wCuritem,wCurlen);
1153 needlen = GetEnvironmentVariableA(name,curitem,curlen);
1156 while (needlen > wCurlen) {
1157 Renew(wCuritem,needlen,WCHAR);
1159 needlen = GetEnvironmentVariableW(wBuffer,wCuritem,wCurlen);
1161 if (needlen > curlen) {
1162 Renew(curitem,needlen,char);
1165 W2AHELPER(wCuritem, curitem, curlen, GETINTERPMODE());
1168 while (needlen > curlen) {
1169 Renew(curitem,needlen,char);
1171 needlen = GetEnvironmentVariableA(name,curitem,curlen);
1176 /* allow any environment variables that begin with 'PERL'
1177 to be stored in the registry */
1181 if (strncmp(name, "PERL", 4) == 0) {
1187 curitem = GetRegStr(name, &curitem, &curlen);
1190 if (curitem && *curitem == '\0')
1197 win32_putenv(const char *name)
1203 int length, relval = -1;
1207 length = strlen(name)+1;
1208 New(1309,wCuritem,length,WCHAR);
1209 A2WHELPER(name, wCuritem, length*2, GETINTERPMODE());
1210 wVal = wcschr(wCuritem, '=');
1213 if(SetEnvironmentVariableW(wCuritem, *wVal ? wVal : NULL))
1219 New(1309,curitem,strlen(name)+1,char);
1220 strcpy(curitem, name);
1221 val = strchr(curitem, '=');
1223 /* The sane way to deal with the environment.
1224 * Has these advantages over putenv() & co.:
1225 * * enables us to store a truly empty value in the
1226 * environment (like in UNIX).
1227 * * we don't have to deal with RTL globals, bugs and leaks.
1229 * Why you may want to enable USE_WIN32_RTL_ENV:
1230 * * environ[] and RTL functions will not reflect changes,
1231 * which might be an issue if extensions want to access
1232 * the env. via RTL. This cuts both ways, since RTL will
1233 * not see changes made by extensions that call the Win32
1234 * functions directly, either.
1238 if(SetEnvironmentVariableA(curitem, *val ? val : NULL))
1250 filetime_to_clock(PFILETIME ft)
1252 __int64 qw = ft->dwHighDateTime;
1254 qw |= ft->dwLowDateTime;
1255 qw /= 10000; /* File time ticks at 0.1uS, clock at 1mS */
1260 win32_times(struct tms *timebuf)
1265 if (GetProcessTimes(GetCurrentProcess(), &dummy, &dummy,
1267 timebuf->tms_utime = filetime_to_clock(&user);
1268 timebuf->tms_stime = filetime_to_clock(&kernel);
1269 timebuf->tms_cutime = 0;
1270 timebuf->tms_cstime = 0;
1273 /* That failed - e.g. Win95 fallback to clock() */
1274 clock_t t = clock();
1275 timebuf->tms_utime = t;
1276 timebuf->tms_stime = 0;
1277 timebuf->tms_cutime = 0;
1278 timebuf->tms_cstime = 0;
1283 /* fix utime() so it works on directories in NT
1284 * thanks to Jan Dubois <jan.dubois@ibm.net>
1287 filetime_from_time(PFILETIME pFileTime, time_t Time)
1289 struct tm *pTM = gmtime(&Time);
1290 SYSTEMTIME SystemTime;
1295 SystemTime.wYear = pTM->tm_year + 1900;
1296 SystemTime.wMonth = pTM->tm_mon + 1;
1297 SystemTime.wDay = pTM->tm_mday;
1298 SystemTime.wHour = pTM->tm_hour;
1299 SystemTime.wMinute = pTM->tm_min;
1300 SystemTime.wSecond = pTM->tm_sec;
1301 SystemTime.wMilliseconds = 0;
1303 return SystemTimeToFileTime(&SystemTime, pFileTime);
1307 win32_utime(const char *filename, struct utimbuf *times)
1313 struct utimbuf TimeBuffer;
1314 WCHAR wbuffer[MAX_PATH];
1319 A2WHELPER(filename, wbuffer, sizeof(wbuffer), GETINTERPMODE());
1320 rc = _wutime(wbuffer, (struct _utimbuf*)times);
1323 rc = utime(filename, times);
1325 /* EACCES: path specifies directory or readonly file */
1326 if (rc == 0 || errno != EACCES /* || !IsWinNT() */)
1329 if (times == NULL) {
1330 times = &TimeBuffer;
1331 time(×->actime);
1332 times->modtime = times->actime;
1335 /* This will (and should) still fail on readonly files */
1337 handle = CreateFileW(wbuffer, GENERIC_READ | GENERIC_WRITE,
1338 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1339 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1342 handle = CreateFileA(filename, GENERIC_READ | GENERIC_WRITE,
1343 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1344 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1346 if (handle == INVALID_HANDLE_VALUE)
1349 if (GetFileTime(handle, &ftCreate, &ftAccess, &ftWrite) &&
1350 filetime_from_time(&ftAccess, times->actime) &&
1351 filetime_from_time(&ftWrite, times->modtime) &&
1352 SetFileTime(handle, &ftCreate, &ftAccess, &ftWrite))
1357 CloseHandle(handle);
1362 win32_uname(struct utsname *name)
1364 struct hostent *hep;
1365 STRLEN nodemax = sizeof(name->nodename)-1;
1366 OSVERSIONINFO osver;
1368 memset(&osver, 0, sizeof(OSVERSIONINFO));
1369 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1370 if (GetVersionEx(&osver)) {
1372 switch (osver.dwPlatformId) {
1373 case VER_PLATFORM_WIN32_WINDOWS:
1374 strcpy(name->sysname, "Windows");
1376 case VER_PLATFORM_WIN32_NT:
1377 strcpy(name->sysname, "Windows NT");
1379 case VER_PLATFORM_WIN32s:
1380 strcpy(name->sysname, "Win32s");
1383 strcpy(name->sysname, "Win32 Unknown");
1388 sprintf(name->release, "%d.%d",
1389 osver.dwMajorVersion, osver.dwMinorVersion);
1392 sprintf(name->version, "Build %d",
1393 osver.dwPlatformId == VER_PLATFORM_WIN32_NT
1394 ? osver.dwBuildNumber : (osver.dwBuildNumber & 0xffff));
1395 if (osver.szCSDVersion[0]) {
1396 char *buf = name->version + strlen(name->version);
1397 sprintf(buf, " (%s)", osver.szCSDVersion);
1401 *name->sysname = '\0';
1402 *name->version = '\0';
1403 *name->release = '\0';
1407 hep = win32_gethostbyname("localhost");
1409 STRLEN len = strlen(hep->h_name);
1410 if (len <= nodemax) {
1411 strcpy(name->nodename, hep->h_name);
1414 strncpy(name->nodename, hep->h_name, nodemax);
1415 name->nodename[nodemax] = '\0';
1420 if (!GetComputerName(name->nodename, &sz))
1421 *name->nodename = '\0';
1424 /* machine (architecture) */
1428 GetSystemInfo(&info);
1431 switch (info.DUMMYUNIONNAME.DUMMYSTRUCTNAME.wProcessorArchitecture) {
1434 switch (info.u.s.wProcessorArchitecture) {
1436 switch (info.wProcessorArchitecture) {
1439 case PROCESSOR_ARCHITECTURE_INTEL:
1440 arch = "x86"; break;
1441 case PROCESSOR_ARCHITECTURE_MIPS:
1442 arch = "mips"; break;
1443 case PROCESSOR_ARCHITECTURE_ALPHA:
1444 arch = "alpha"; break;
1445 case PROCESSOR_ARCHITECTURE_PPC:
1446 arch = "ppc"; break;
1448 arch = "unknown"; break;
1450 strcpy(name->machine, arch);
1456 win32_waitpid(int pid, int *status, int flags)
1460 return win32_wait(status);
1462 long child = find_pid(pid);
1464 HANDLE hProcess = w32_child_handles[child];
1465 DWORD waitcode = WaitForSingleObject(hProcess, INFINITE);
1466 if (waitcode != WAIT_FAILED) {
1467 if (GetExitCodeProcess(hProcess, &waitcode)) {
1468 *status = (int)((waitcode & 0xff) << 8);
1469 retval = (int)w32_child_pids[child];
1470 remove_dead_process(child);
1478 retval = cwait(status, pid, WAIT_CHILD);
1479 /* cwait() returns "correctly" on Borland */
1480 #ifndef __BORLANDC__
1486 return retval >= 0 ? pid : retval;
1490 win32_wait(int *status)
1492 /* XXX this wait emulation only knows about processes
1493 * spawned via win32_spawnvp(P_NOWAIT, ...).
1496 DWORD exitcode, waitcode;
1498 if (!w32_num_children) {
1503 /* if a child exists, wait for it to die */
1504 waitcode = WaitForMultipleObjects(w32_num_children,
1508 if (waitcode != WAIT_FAILED) {
1509 if (waitcode >= WAIT_ABANDONED_0
1510 && waitcode < WAIT_ABANDONED_0 + w32_num_children)
1511 i = waitcode - WAIT_ABANDONED_0;
1513 i = waitcode - WAIT_OBJECT_0;
1514 if (GetExitCodeProcess(w32_child_handles[i], &exitcode) ) {
1515 *status = (int)((exitcode & 0xff) << 8);
1516 retval = (int)w32_child_pids[i];
1517 remove_dead_process(i);
1523 errno = GetLastError();
1527 static UINT timerid = 0;
1529 static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
1531 KillTimer(NULL,timerid);
1536 DllExport unsigned int
1537 win32_alarm(unsigned int sec)
1540 * the 'obvious' implentation is SetTimer() with a callback
1541 * which does whatever receiving SIGALRM would do
1542 * we cannot use SIGALRM even via raise() as it is not
1543 * one of the supported codes in <signal.h>
1545 * Snag is unless something is looking at the message queue
1546 * nothing happens :-(
1550 timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
1552 Perl_croak_nocontext("Cannot set timer");
1558 KillTimer(NULL,timerid);
1565 #if defined(HAVE_DES_FCRYPT) || defined(PERL_OBJECT)
1566 #ifdef HAVE_DES_FCRYPT
1567 extern char * des_fcrypt(const char *txt, const char *salt, char *cbuf);
1571 win32_crypt(const char *txt, const char *salt)
1573 #ifdef HAVE_DES_FCRYPT
1575 return des_fcrypt(txt, salt, crypt_buffer);
1577 die("The crypt() function is unimplemented due to excessive paranoia.");
1583 #ifdef USE_FIXED_OSFHANDLE
1585 EXTERN_C int __cdecl _alloc_osfhnd(void);
1586 EXTERN_C int __cdecl _set_osfhnd(int fh, long value);
1587 EXTERN_C void __cdecl _lock_fhandle(int);
1588 EXTERN_C void __cdecl _unlock_fhandle(int);
1589 EXTERN_C void __cdecl _unlock(int);
1591 #if (_MSC_VER >= 1000)
1593 long osfhnd; /* underlying OS file HANDLE */
1594 char osfile; /* attributes of file (e.g., open in text mode?) */
1595 char pipech; /* one char buffer for handles opened on pipes */
1596 #if defined (_MT) && !defined (DLL_FOR_WIN32S)
1598 CRITICAL_SECTION lock;
1599 #endif /* defined (_MT) && !defined (DLL_FOR_WIN32S) */
1602 EXTERN_C ioinfo * __pioinfo[];
1604 #define IOINFO_L2E 5
1605 #define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
1606 #define _pioinfo(i) (__pioinfo[i >> IOINFO_L2E] + (i & (IOINFO_ARRAY_ELTS - 1)))
1607 #define _osfile(i) (_pioinfo(i)->osfile)
1609 #else /* (_MSC_VER >= 1000) */
1610 extern char _osfile[];
1611 #endif /* (_MSC_VER >= 1000) */
1613 #define FOPEN 0x01 /* file handle open */
1614 #define FAPPEND 0x20 /* file handle opened O_APPEND */
1615 #define FDEV 0x40 /* file handle refers to device */
1616 #define FTEXT 0x80 /* file handle is in text mode */
1618 #define _STREAM_LOCKS 26 /* Table of stream locks */
1619 #define _LAST_STREAM_LOCK (_STREAM_LOCKS+_NSTREAM_-1) /* Last stream lock */
1620 #define _FH_LOCKS (_LAST_STREAM_LOCK+1) /* Table of fh locks */
1623 *int my_open_osfhandle(long osfhandle, int flags) - open C Runtime file handle
1626 * This function allocates a free C Runtime file handle and associates
1627 * it with the Win32 HANDLE specified by the first parameter. This is a
1628 * temperary fix for WIN95's brain damage GetFileType() error on socket
1629 * we just bypass that call for socket
1632 * long osfhandle - Win32 HANDLE to associate with C Runtime file handle.
1633 * int flags - flags to associate with C Runtime file handle.
1636 * returns index of entry in fh, if successful
1637 * return -1, if no free entry is found
1641 *******************************************************************************/
1644 my_open_osfhandle(long osfhandle, int flags)
1647 char fileflags; /* _osfile flags */
1649 /* copy relevant flags from second parameter */
1652 if (flags & O_APPEND)
1653 fileflags |= FAPPEND;
1658 /* attempt to allocate a C Runtime file handle */
1659 if ((fh = _alloc_osfhnd()) == -1) {
1660 errno = EMFILE; /* too many open files */
1661 _doserrno = 0L; /* not an OS error */
1662 return -1; /* return error to caller */
1665 /* the file is open. now, set the info in _osfhnd array */
1666 _set_osfhnd(fh, osfhandle);
1668 fileflags |= FOPEN; /* mark as open */
1670 #if (_MSC_VER >= 1000)
1671 _osfile(fh) = fileflags; /* set osfile entry */
1672 _unlock_fhandle(fh);
1674 _osfile[fh] = fileflags; /* set osfile entry */
1675 _unlock(fh+_FH_LOCKS); /* unlock handle */
1678 return fh; /* return handle */
1681 #define _open_osfhandle my_open_osfhandle
1682 #endif /* USE_FIXED_OSFHANDLE */
1684 /* simulate flock by locking a range on the file */
1686 #define LK_ERR(f,i) ((f) ? (i = 0) : (errno = GetLastError()))
1687 #define LK_LEN 0xffff0000
1690 win32_flock(int fd, int oper)
1697 Perl_croak_nocontext("flock() unimplemented on this platform");
1700 fh = (HANDLE)_get_osfhandle(fd);
1701 memset(&o, 0, sizeof(o));
1704 case LOCK_SH: /* shared lock */
1705 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
1707 case LOCK_EX: /* exclusive lock */
1708 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
1710 case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
1711 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
1713 case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
1714 LK_ERR(LockFileEx(fh,
1715 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
1716 0, LK_LEN, 0, &o),i);
1718 case LOCK_UN: /* unlock lock */
1719 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, 0, &o),i);
1721 default: /* unknown */
1732 * redirected io subsystem for all XS modules
1745 return (&(_environ));
1748 /* the rest are the remapped stdio routines */
1768 win32_ferror(FILE *fp)
1770 return (ferror(fp));
1775 win32_feof(FILE *fp)
1781 * Since the errors returned by the socket error function
1782 * WSAGetLastError() are not known by the library routine strerror
1783 * we have to roll our own.
1787 win32_strerror(int e)
1789 #ifndef __BORLANDC__ /* Borland intolerance */
1790 extern int sys_nerr;
1794 if (e < 0 || e > sys_nerr) {
1799 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
1800 strerror_buffer, sizeof(strerror_buffer), NULL) == 0)
1801 strcpy(strerror_buffer, "Unknown Error");
1803 return strerror_buffer;
1809 win32_str_os_error(pTHX_ void *sv, DWORD dwErr)
1813 dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
1814 |FORMAT_MESSAGE_IGNORE_INSERTS
1815 |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
1816 dwErr, 0, (char *)&sMsg, 1, NULL);
1818 while (0 < dwLen && isSPACE(sMsg[--dwLen]))
1820 if ('.' != sMsg[dwLen])
1825 sMsg = (char*)LocalAlloc(0, 64/**sizeof(TCHAR)*/);
1827 dwLen = sprintf(sMsg,
1828 "Unknown error #0x%lX (lookup 0x%lX)",
1829 dwErr, GetLastError());
1832 sv_setpvn((SV*)sv, sMsg, dwLen);
1839 win32_fprintf(FILE *fp, const char *format, ...)
1842 va_start(marker, format); /* Initialize variable arguments. */
1844 return (vfprintf(fp, format, marker));
1848 win32_printf(const char *format, ...)
1851 va_start(marker, format); /* Initialize variable arguments. */
1853 return (vprintf(format, marker));
1857 win32_vfprintf(FILE *fp, const char *format, va_list args)
1859 return (vfprintf(fp, format, args));
1863 win32_vprintf(const char *format, va_list args)
1865 return (vprintf(format, args));
1869 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
1871 return fread(buf, size, count, fp);
1875 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
1877 return fwrite(buf, size, count, fp);
1880 #define MODE_SIZE 10
1883 win32_fopen(const char *filename, const char *mode)
1885 WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH];
1886 if (stricmp(filename, "/dev/null")==0)
1891 A2WHELPER(mode, wMode, sizeof(wMode), GETINTERPMODE());
1892 A2WHELPER(filename, wBuffer, sizeof(wBuffer), GETINTERPMODE());
1893 return _wfopen(wBuffer, wMode);
1895 return fopen(filename, mode);
1898 #ifndef USE_SOCKETS_AS_HANDLES
1900 #define fdopen my_fdopen
1904 win32_fdopen(int handle, const char *mode)
1906 WCHAR wMode[MODE_SIZE];
1909 A2WHELPER(mode, wMode, sizeof(wMode), GETINTERPMODE());
1910 return _wfdopen(handle, wMode);
1912 return fdopen(handle, (char *) mode);
1916 win32_freopen(const char *path, const char *mode, FILE *stream)
1918 WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH];
1919 if (stricmp(path, "/dev/null")==0)
1924 A2WHELPER(mode, wMode, sizeof(wMode), GETINTERPMODE());
1925 A2WHELPER(path, wBuffer, sizeof(wBuffer), GETINTERPMODE());
1926 return _wfreopen(wBuffer, wMode, stream);
1928 return freopen(path, mode, stream);
1932 win32_fclose(FILE *pf)
1934 return my_fclose(pf); /* defined in win32sck.c */
1938 win32_fputs(const char *s,FILE *pf)
1940 return fputs(s, pf);
1944 win32_fputc(int c,FILE *pf)
1950 win32_ungetc(int c,FILE *pf)
1952 return ungetc(c,pf);
1956 win32_getc(FILE *pf)
1962 win32_fileno(FILE *pf)
1968 win32_clearerr(FILE *pf)
1975 win32_fflush(FILE *pf)
1981 win32_ftell(FILE *pf)
1987 win32_fseek(FILE *pf,long offset,int origin)
1989 return fseek(pf, offset, origin);
1993 win32_fgetpos(FILE *pf,fpos_t *p)
1995 return fgetpos(pf, p);
1999 win32_fsetpos(FILE *pf,const fpos_t *p)
2001 return fsetpos(pf, p);
2005 win32_rewind(FILE *pf)
2025 win32_fstat(int fd,struct stat *sbufptr)
2027 return fstat(fd,sbufptr);
2031 win32_pipe(int *pfd, unsigned int size, int mode)
2033 return _pipe(pfd, size, mode);
2037 * a popen() clone that respects PERL5SHELL
2041 win32_popen(const char *command, const char *mode)
2043 #ifdef USE_RTL_POPEN
2044 return _popen(command, mode);
2052 /* establish which ends read and write */
2053 if (strchr(mode,'w')) {
2054 stdfd = 0; /* stdin */
2058 else if (strchr(mode,'r')) {
2059 stdfd = 1; /* stdout */
2066 /* set the correct mode */
2067 if (strchr(mode,'b'))
2069 else if (strchr(mode,'t'))
2072 ourmode = _fmode & (O_TEXT | O_BINARY);
2074 /* the child doesn't inherit handles */
2075 ourmode |= O_NOINHERIT;
2077 if (win32_pipe( p, 512, ourmode) == -1)
2080 /* save current stdfd */
2081 if ((oldfd = win32_dup(stdfd)) == -1)
2084 /* make stdfd go to child end of pipe (implicitly closes stdfd) */
2085 /* stdfd will be inherited by the child */
2086 if (win32_dup2(p[child], stdfd) == -1)
2089 /* close the child end in parent */
2090 win32_close(p[child]);
2092 /* start the child */
2095 if ((childpid = do_spawn_nowait(aTHX_ (char*)command)) == -1)
2098 /* revert stdfd to whatever it was before */
2099 if (win32_dup2(oldfd, stdfd) == -1)
2102 /* close saved handle */
2105 sv_setiv(*av_fetch(w32_fdpid, p[parent], TRUE), childpid);
2108 /* we have an fd, return a file stream */
2109 return (win32_fdopen(p[parent], (char *)mode));
2112 /* we don't need to check for errors here */
2116 win32_dup2(oldfd, stdfd);
2121 #endif /* USE_RTL_POPEN */
2129 win32_pclose(FILE *pf)
2131 #ifdef USE_RTL_POPEN
2135 int childpid, status;
2138 sv = *av_fetch(w32_fdpid, win32_fileno(pf), TRUE);
2140 childpid = SvIVX(sv);
2152 if (win32_waitpid(childpid, &status, 0) == -1)
2157 #endif /* USE_RTL_POPEN */
2161 win32_rename(const char *oname, const char *newname)
2163 WCHAR wOldName[MAX_PATH];
2164 WCHAR wNewName[MAX_PATH];
2166 /* XXX despite what the documentation says about MoveFileEx(),
2167 * it doesn't work under Windows95!
2172 A2WHELPER(oname, wOldName, sizeof(wOldName), GETINTERPMODE());
2173 A2WHELPER(newname, wNewName, sizeof(wNewName), GETINTERPMODE());
2174 bResult = MoveFileExW(wOldName,wNewName,
2175 MOVEFILE_COPY_ALLOWED|MOVEFILE_REPLACE_EXISTING);
2178 bResult = MoveFileExA(oname,newname,
2179 MOVEFILE_COPY_ALLOWED|MOVEFILE_REPLACE_EXISTING);
2182 DWORD err = GetLastError();
2184 case ERROR_BAD_NET_NAME:
2185 case ERROR_BAD_NETPATH:
2186 case ERROR_BAD_PATHNAME:
2187 case ERROR_FILE_NOT_FOUND:
2188 case ERROR_FILENAME_EXCED_RANGE:
2189 case ERROR_INVALID_DRIVE:
2190 case ERROR_NO_MORE_FILES:
2191 case ERROR_PATH_NOT_FOUND:
2204 char tmpname[MAX_PATH+1];
2205 char dname[MAX_PATH+1];
2206 char *endname = Nullch;
2208 DWORD from_attr, to_attr;
2210 /* if oname doesn't exist, do nothing */
2211 from_attr = GetFileAttributes(oname);
2212 if (from_attr == 0xFFFFFFFF) {
2217 /* if newname exists, rename it to a temporary name so that we
2218 * don't delete it in case oname happens to be the same file
2219 * (but perhaps accessed via a different path)
2221 to_attr = GetFileAttributes(newname);
2222 if (to_attr != 0xFFFFFFFF) {
2223 /* if newname is a directory, we fail
2224 * XXX could overcome this with yet more convoluted logic */
2225 if (to_attr & FILE_ATTRIBUTE_DIRECTORY) {
2229 tmplen = strlen(newname);
2230 strcpy(tmpname,newname);
2231 endname = tmpname+tmplen;
2232 for (; endname > tmpname ; --endname) {
2233 if (*endname == '/' || *endname == '\\') {
2238 if (endname > tmpname)
2239 endname = strcpy(dname,tmpname);
2243 /* get a temporary filename in same directory
2244 * XXX is this really the best we can do? */
2245 if (!GetTempFileName((LPCTSTR)endname, "plr", 0, tmpname)) {
2249 DeleteFile(tmpname);
2251 retval = rename(newname, tmpname);
2258 /* rename oname to newname */
2259 retval = rename(oname, newname);
2261 /* if we created a temporary file before ... */
2262 if (endname != Nullch) {
2263 /* ...and rename succeeded, delete temporary file/directory */
2265 DeleteFile(tmpname);
2266 /* else restore it to what it was */
2268 (void)rename(tmpname, newname);
2275 win32_setmode(int fd, int mode)
2277 return setmode(fd, mode);
2281 win32_lseek(int fd, long offset, int origin)
2283 return lseek(fd, offset, origin);
2293 win32_open(const char *path, int flag, ...)
2297 WCHAR wBuffer[MAX_PATH];
2300 pmode = va_arg(ap, int);
2303 if (stricmp(path, "/dev/null")==0)
2308 A2WHELPER(path, wBuffer, sizeof(wBuffer), GETINTERPMODE());
2309 return _wopen(wBuffer, flag, pmode);
2311 return open(path,flag,pmode);
2333 win32_dup2(int fd1,int fd2)
2335 return dup2(fd1,fd2);
2339 win32_read(int fd, void *buf, unsigned int cnt)
2341 return read(fd, buf, cnt);
2345 win32_write(int fd, const void *buf, unsigned int cnt)
2347 return write(fd, buf, cnt);
2351 win32_mkdir(const char *dir, int mode)
2353 return mkdir(dir); /* just ignore mode */
2357 win32_rmdir(const char *dir)
2363 win32_chdir(const char *dir)
2369 create_command_line(const char* command, const char * const *args)
2372 char *cmd, *ptr, *arg;
2373 STRLEN len = strlen(command) + 1;
2375 for (index = 0; (ptr = (char*)args[index]) != NULL; ++index)
2376 len += strlen(ptr) + 1;
2378 New(1310, cmd, len, char);
2380 strcpy(ptr, command);
2382 for (index = 0; (arg = (char*)args[index]) != NULL; ++index) {
2392 qualified_path(const char *cmd)
2395 char *fullcmd, *curfullcmd;
2401 fullcmd = (char*)cmd;
2403 if (*fullcmd == '/' || *fullcmd == '\\')
2410 pathstr = win32_getenv("PATH");
2411 New(0, fullcmd, MAX_PATH+1, char);
2412 curfullcmd = fullcmd;
2417 /* start by appending the name to the current prefix */
2418 strcpy(curfullcmd, cmd);
2419 curfullcmd += cmdlen;
2421 /* if it doesn't end with '.', or has no extension, try adding
2422 * a trailing .exe first */
2423 if (cmd[cmdlen-1] != '.'
2424 && (cmdlen < 4 || cmd[cmdlen-4] != '.'))
2426 strcpy(curfullcmd, ".exe");
2427 res = GetFileAttributes(fullcmd);
2428 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
2433 /* that failed, try the bare name */
2434 res = GetFileAttributes(fullcmd);
2435 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
2438 /* quit if no other path exists, or if cmd already has path */
2439 if (!pathstr || !*pathstr || has_slash)
2442 /* skip leading semis */
2443 while (*pathstr == ';')
2446 /* build a new prefix from scratch */
2447 curfullcmd = fullcmd;
2448 while (*pathstr && *pathstr != ';') {
2449 if (*pathstr == '"') { /* foo;"baz;etc";bar */
2450 pathstr++; /* skip initial '"' */
2451 while (*pathstr && *pathstr != '"') {
2452 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
2453 *curfullcmd++ = *pathstr;
2457 pathstr++; /* skip trailing '"' */
2460 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
2461 *curfullcmd++ = *pathstr;
2466 pathstr++; /* skip trailing semi */
2467 if (curfullcmd > fullcmd /* append a dir separator */
2468 && curfullcmd[-1] != '/' && curfullcmd[-1] != '\\')
2470 *curfullcmd++ = '\\';
2478 /* XXX this needs to be made more compatible with the spawnvp()
2479 * provided by the various RTLs. In particular, searching for
2480 * *.{com,bat,cmd} files (as done by the RTLs) is unimplemented.
2481 * This doesn't significantly affect perl itself, because we
2482 * always invoke things using PERL5SHELL if a direct attempt to
2483 * spawn the executable fails.
2485 * XXX splitting and rejoining the commandline between do_aspawn()
2486 * and win32_spawnvp() could also be avoided.
2490 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
2492 #ifdef USE_RTL_SPAWNVP
2493 return spawnvp(mode, cmdname, (char * const *)argv);
2496 STARTUPINFO StartupInfo;
2497 PROCESS_INFORMATION ProcessInformation;
2500 char *cmd = create_command_line(cmdname, strcmp(cmdname, argv[0]) == 0
2502 char *fullcmd = Nullch;
2505 case P_NOWAIT: /* asynch + remember result */
2506 if (w32_num_children >= MAXIMUM_WAIT_OBJECTS) {
2512 case P_WAIT: /* synchronous execution */
2514 default: /* invalid mode */
2519 memset(&StartupInfo,0,sizeof(StartupInfo));
2520 StartupInfo.cb = sizeof(StartupInfo);
2521 StartupInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
2522 StartupInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
2523 StartupInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
2524 if (StartupInfo.hStdInput != INVALID_HANDLE_VALUE &&
2525 StartupInfo.hStdOutput != INVALID_HANDLE_VALUE &&
2526 StartupInfo.hStdError != INVALID_HANDLE_VALUE)
2528 StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
2531 create |= CREATE_NEW_CONSOLE;
2535 StartupInfo.dwFlags |= STARTF_USESHOWWINDOW;
2536 StartupInfo.wShowWindow = SW_HIDE;
2540 if (!CreateProcess(cmdname, /* search PATH to find executable */
2541 cmd, /* executable, and its arguments */
2542 NULL, /* process attributes */
2543 NULL, /* thread attributes */
2544 TRUE, /* inherit handles */
2545 create, /* creation flags */
2546 NULL, /* inherit environment */
2547 NULL, /* inherit cwd */
2549 &ProcessInformation))
2551 /* initial NULL argument to CreateProcess() does a PATH
2552 * search, but it always first looks in the directory
2553 * where the current process was started, which behavior
2554 * is undesirable for backward compatibility. So we
2555 * jump through our own hoops by picking out the path
2556 * we really want it to use. */
2558 fullcmd = qualified_path(cmdname);
2569 if (mode == P_NOWAIT) {
2570 /* asynchronous spawn -- store handle, return PID */
2571 w32_child_handles[w32_num_children] = ProcessInformation.hProcess;
2572 ret = w32_child_pids[w32_num_children] = ProcessInformation.dwProcessId;
2576 WaitForSingleObject(ProcessInformation.hProcess, INFINITE);
2577 GetExitCodeProcess(ProcessInformation.hProcess, &ret);
2578 CloseHandle(ProcessInformation.hProcess);
2581 CloseHandle(ProcessInformation.hThread);
2590 win32_execv(const char *cmdname, const char *const *argv)
2592 return execv(cmdname, (char *const *)argv);
2596 win32_execvp(const char *cmdname, const char *const *argv)
2598 return execvp(cmdname, (char *const *)argv);
2602 win32_perror(const char *str)
2608 win32_setbuf(FILE *pf, char *buf)
2614 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
2616 return setvbuf(pf, buf, type, size);
2620 win32_flushall(void)
2626 win32_fcloseall(void)
2632 win32_fgets(char *s, int n, FILE *pf)
2634 return fgets(s, n, pf);
2644 win32_fgetc(FILE *pf)
2650 win32_putc(int c, FILE *pf)
2656 win32_puts(const char *s)
2668 win32_putchar(int c)
2675 #ifndef USE_PERL_SBRK
2677 static char *committed = NULL;
2678 static char *base = NULL;
2679 static char *reserved = NULL;
2680 static char *brk = NULL;
2681 static DWORD pagesize = 0;
2682 static DWORD allocsize = 0;
2690 GetSystemInfo(&info);
2691 /* Pretend page size is larger so we don't perpetually
2692 * call the OS to commit just one page ...
2694 pagesize = info.dwPageSize << 3;
2695 allocsize = info.dwAllocationGranularity;
2697 /* This scheme fails eventually if request for contiguous
2698 * block is denied so reserve big blocks - this is only
2699 * address space not memory ...
2701 if (brk+need >= reserved)
2703 DWORD size = 64*1024*1024;
2705 if (committed && reserved && committed < reserved)
2707 /* Commit last of previous chunk cannot span allocations */
2708 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
2710 committed = reserved;
2712 /* Reserve some (more) space
2713 * Note this is a little sneaky, 1st call passes NULL as reserved
2714 * so lets system choose where we start, subsequent calls pass
2715 * the old end address so ask for a contiguous block
2717 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
2720 reserved = addr+size;
2735 if (brk > committed)
2737 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
2738 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
2753 win32_malloc(size_t size)
2755 return malloc(size);
2759 win32_calloc(size_t numitems, size_t size)
2761 return calloc(numitems,size);
2765 win32_realloc(void *block, size_t size)
2767 return realloc(block,size);
2771 win32_free(void *block)
2778 win32_open_osfhandle(long handle, int flags)
2780 return _open_osfhandle(handle, flags);
2784 win32_get_osfhandle(int fd)
2786 return _get_osfhandle(fd);
2797 SV *sv = sv_newmortal();
2798 /* Make one call with zero size - return value is required size */
2799 DWORD len = GetCurrentDirectory((DWORD)0,NULL);
2800 SvUPGRADE(sv,SVt_PV);
2802 SvCUR(sv) = GetCurrentDirectory((DWORD) SvLEN(sv), SvPVX(sv));
2805 * then it worked, set PV valid,
2806 * else leave it 'undef'
2822 Perl_croak(aTHX_ "usage: Win32::SetCurrentDirectory($cwd)");
2823 if (SetCurrentDirectory(SvPV_nolen(ST(0))))
2830 XS(w32_GetNextAvailDrive)
2834 char root[] = "_:\\";
2839 if (GetDriveType(root) == 1) {
2848 XS(w32_GetLastError)
2852 XSRETURN_IV(GetLastError());
2856 XS(w32_SetLastError)
2860 Perl_croak(aTHX_ "usage: Win32::SetLastError($error)");
2861 SetLastError(SvIV(ST(0)));
2869 char *name = getlogin_buffer;
2870 DWORD size = sizeof(getlogin_buffer);
2872 if (GetUserName(name,&size)) {
2873 /* size includes NULL */
2874 ST(0) = sv_2mortal(newSVpvn(name,size-1));
2884 char name[MAX_COMPUTERNAME_LENGTH+1];
2885 DWORD size = sizeof(name);
2887 if (GetComputerName(name,&size)) {
2888 /* size does NOT include NULL :-( */
2889 ST(0) = sv_2mortal(newSVpvn(name,size));
2900 #ifndef HAS_NETWKSTAGETINFO
2901 /* mingw32 (and Win95) don't have NetWksta*(), so do it the old way */
2903 DWORD size = sizeof(name);
2905 if (GetUserName(name,&size)) {
2907 DWORD sidlen = sizeof(sid);
2909 DWORD dnamelen = sizeof(dname);
2911 if (LookupAccountName(NULL, name, (PSID)&sid, &sidlen,
2912 dname, &dnamelen, &snu)) {
2913 XSRETURN_PV(dname); /* all that for this */
2917 /* this way is more reliable, in case user has a local account.
2918 * XXX need dynamic binding of netapi32.dll symbols or this will fail on
2919 * Win95. Probably makes more sense to move it into libwin32. */
2921 DWORD dnamelen = sizeof(dname);
2922 PWKSTA_INFO_100 pwi;
2924 if (NERR_Success == NetWkstaGetInfo(NULL, 100, (LPBYTE*)&pwi)) {
2925 if (pwi->wki100_langroup && *(pwi->wki100_langroup)) {
2926 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_langroup,
2927 -1, (LPSTR)dname, dnamelen, NULL, NULL);
2930 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_computername,
2931 -1, (LPSTR)dname, dnamelen, NULL, NULL);
2933 NetApiBufferFree(pwi);
2945 DWORD flags, filecomplen;
2946 if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
2947 &flags, fsname, sizeof(fsname))) {
2948 if (GIMME_V == G_ARRAY) {
2949 XPUSHs(sv_2mortal(newSVpvn(fsname,strlen(fsname))));
2950 XPUSHs(sv_2mortal(newSViv(flags)));
2951 XPUSHs(sv_2mortal(newSViv(filecomplen)));
2956 XSRETURN_PV(fsname);
2962 XS(w32_GetOSVersion)
2965 OSVERSIONINFO osver;
2967 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
2968 if (GetVersionEx(&osver)) {
2969 XPUSHs(newSVpvn(osver.szCSDVersion, strlen(osver.szCSDVersion)));
2970 XPUSHs(newSViv(osver.dwMajorVersion));
2971 XPUSHs(newSViv(osver.dwMinorVersion));
2972 XPUSHs(newSViv(osver.dwBuildNumber));
2973 XPUSHs(newSViv(osver.dwPlatformId));
2985 XSRETURN_IV(IsWinNT());
2993 XSRETURN_IV(IsWin95());
2997 XS(w32_FormatMessage)
3004 Perl_croak(aTHX_ "usage: Win32::FormatMessage($errno)");
3006 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
3007 &source, SvIV(ST(0)), 0,
3008 msgbuf, sizeof(msgbuf)-1, NULL))
3009 XSRETURN_PV(msgbuf);
3019 PROCESS_INFORMATION stProcInfo;
3020 STARTUPINFO stStartInfo;
3021 BOOL bSuccess = FALSE;
3024 Perl_croak(aTHX_ "usage: Win32::Spawn($cmdName, $args, $PID)");
3026 cmd = SvPV_nolen(ST(0));
3027 args = SvPV_nolen(ST(1));
3029 memset(&stStartInfo, 0, sizeof(stStartInfo)); /* Clear the block */
3030 stStartInfo.cb = sizeof(stStartInfo); /* Set the structure size */
3031 stStartInfo.dwFlags = STARTF_USESHOWWINDOW; /* Enable wShowWindow control */
3032 stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE; /* Start min (normal) */
3035 cmd, /* Image path */
3036 args, /* Arguments for command line */
3037 NULL, /* Default process security */
3038 NULL, /* Default thread security */
3039 FALSE, /* Must be TRUE to use std handles */
3040 NORMAL_PRIORITY_CLASS, /* No special scheduling */
3041 NULL, /* Inherit our environment block */
3042 NULL, /* Inherit our currrent directory */
3043 &stStartInfo, /* -> Startup info */
3044 &stProcInfo)) /* <- Process info (if OK) */
3046 CloseHandle(stProcInfo.hThread);/* library source code does this. */
3047 sv_setiv(ST(2), stProcInfo.dwProcessId);
3050 XSRETURN_IV(bSuccess);
3054 XS(w32_GetTickCount)
3057 DWORD msec = GetTickCount();
3065 XS(w32_GetShortPathName)
3072 Perl_croak(aTHX_ "usage: Win32::GetShortPathName($longPathName)");
3074 shortpath = sv_mortalcopy(ST(0));
3075 SvUPGRADE(shortpath, SVt_PV);
3076 /* src == target is allowed */
3078 len = GetShortPathName(SvPVX(shortpath),
3081 } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
3083 SvCUR_set(shortpath,len);
3091 XS(w32_GetFullPathName)
3100 Perl_croak(aTHX_ "usage: Win32::GetFullPathName($filename)");
3103 fullpath = sv_mortalcopy(filename);
3104 SvUPGRADE(fullpath, SVt_PV);
3106 len = GetFullPathName(SvPVX(filename),
3110 } while (len >= SvLEN(fullpath) && sv_grow(fullpath,len+1));
3112 if (GIMME_V == G_ARRAY) {
3114 XST_mPV(1,filepart);
3115 len = filepart - SvPVX(fullpath);
3118 SvCUR_set(fullpath,len);
3126 XS(w32_GetLongPathName)
3130 char tmpbuf[MAX_PATH+1];
3135 Perl_croak(aTHX_ "usage: Win32::GetLongPathName($pathname)");
3138 pathstr = SvPV(path,len);
3139 strcpy(tmpbuf, pathstr);
3140 pathstr = win32_longpath(tmpbuf);
3142 ST(0) = sv_2mortal(newSVpvn(pathstr, strlen(pathstr)));
3153 Perl_croak(aTHX_ "usage: Win32::Sleep($milliseconds)");
3163 Perl_croak(aTHX_ "usage: Win32::CopyFile($from, $to, $overwrite)");
3164 if (CopyFile(SvPV_nolen(ST(0)), SvPV_nolen(ST(1)), !SvTRUE(ST(2))))
3170 Perl_init_os_extras(pTHX)
3172 char *file = __FILE__;
3175 w32_perlshell_tokens = Nullch;
3176 w32_perlshell_items = -1;
3177 w32_fdpid = newAV(); /* XXX needs to be in Perl_win32_init()? */
3178 New(1313, w32_children, 1, child_tab);
3179 w32_num_children = 0;
3181 /* these names are Activeware compatible */
3182 newXS("Win32::GetCwd", w32_GetCwd, file);
3183 newXS("Win32::SetCwd", w32_SetCwd, file);
3184 newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
3185 newXS("Win32::GetLastError", w32_GetLastError, file);
3186 newXS("Win32::SetLastError", w32_SetLastError, file);
3187 newXS("Win32::LoginName", w32_LoginName, file);
3188 newXS("Win32::NodeName", w32_NodeName, file);
3189 newXS("Win32::DomainName", w32_DomainName, file);
3190 newXS("Win32::FsType", w32_FsType, file);
3191 newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
3192 newXS("Win32::IsWinNT", w32_IsWinNT, file);
3193 newXS("Win32::IsWin95", w32_IsWin95, file);
3194 newXS("Win32::FormatMessage", w32_FormatMessage, file);
3195 newXS("Win32::Spawn", w32_Spawn, file);
3196 newXS("Win32::GetTickCount", w32_GetTickCount, file);
3197 newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
3198 newXS("Win32::GetFullPathName", w32_GetFullPathName, file);
3199 newXS("Win32::GetLongPathName", w32_GetLongPathName, file);
3200 newXS("Win32::CopyFile", w32_CopyFile, file);
3201 newXS("Win32::Sleep", w32_Sleep, file);
3203 /* XXX Bloat Alert! The following Activeware preloads really
3204 * ought to be part of Win32::Sys::*, so they're not included
3207 /* LookupAccountName
3209 * InitiateSystemShutdown
3210 * AbortSystemShutdown
3211 * ExpandEnvrironmentStrings
3216 Perl_win32_init(int *argcp, char ***argvp)
3218 /* Disable floating point errors, Perl will trap the ones we
3219 * care about. VC++ RTL defaults to switching these off
3220 * already, but the Borland RTL doesn't. Since we don't
3221 * want to be at the vendor's whim on the default, we set
3222 * it explicitly here.
3224 #if !defined(_ALPHA_) && !defined(__GNUC__)
3225 _control87(MCW_EM, MCW_EM);
3230 #ifdef USE_BINMODE_SCRIPTS
3233 win32_strip_return(SV *sv)
3235 char *s = SvPVX(sv);
3236 char *e = s+SvCUR(sv);
3240 if (*s == '\r' && s[1] == '\n')
3250 SvCUR_set(sv,d-SvPVX(sv));