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
19 /* #include "config.h" */
21 #define PERLIO_NOT_STDIO 0
22 #if !defined(PERLIO_IS_STDIO) && !defined(USE_SFIO)
31 #define PERL_NO_GET_CONTEXT
37 /* assert.h conflicts with #define of assert in perl.h */
44 #if defined(_MSC_VER) || defined(__MINGW32__)
45 #include <sys/utime.h>
51 /* Mingw32 defaults to globing command line
52 * So we turn it off like this:
57 #if defined(__MINGW32__)
61 #if defined(__BORLANDC__)
63 # define _utimbuf utimbuf
68 #define EXECF_SPAWN_NOWAIT 3
70 #if defined(PERL_IMPLICIT_SYS)
71 # undef win32_get_privlib
72 # define win32_get_privlib g_win32_get_privlib
73 # undef win32_get_sitelib
74 # define win32_get_sitelib g_win32_get_sitelib
76 # define do_spawn g_do_spawn
78 # define getlogin g_getlogin
81 #if defined(PERL_OBJECT)
83 # define do_aspawn g_do_aspawn
85 # define Perl_do_exec g_do_exec
88 static void get_shell(void);
89 static long tokenize(const char *str, char **dest, char ***destv);
90 int do_spawn2(char *cmd, int exectype);
91 static BOOL has_shell_metachars(char *ptr);
92 static long filetime_to_clock(PFILETIME ft);
93 static BOOL filetime_from_time(PFILETIME ft, time_t t);
94 static char * get_emd_part(SV **leading, char *trailing, ...);
95 static void remove_dead_process(long deceased);
96 static long find_pid(int pid);
97 static char * qualified_path(const char *cmd);
99 HANDLE w32_perldll_handle = INVALID_HANDLE_VALUE;
100 char w32_module_name[MAX_PATH+1];
101 static DWORD w32_platform = (DWORD)-1;
104 # ifdef USE_DECLSPEC_THREAD
105 __declspec(thread) char strerror_buffer[512];
106 __declspec(thread) char getlogin_buffer[128];
107 __declspec(thread) char w32_perllib_root[MAX_PATH+1];
108 # ifdef HAVE_DES_FCRYPT
109 __declspec(thread) char crypt_buffer[30];
112 # define strerror_buffer (thr->i.Wstrerror_buffer)
113 # define getlogin_buffer (thr->i.Wgetlogin_buffer)
114 # define w32_perllib_root (thr->i.Ww32_perllib_root)
115 # define crypt_buffer (thr->i.Wcrypt_buffer)
118 static char strerror_buffer[512];
119 static char getlogin_buffer[128];
120 static char w32_perllib_root[MAX_PATH+1];
121 # ifdef HAVE_DES_FCRYPT
122 static char crypt_buffer[30];
129 return (win32_os_id() == VER_PLATFORM_WIN32_WINDOWS);
135 return (win32_os_id() == VER_PLATFORM_WIN32_NT);
138 /* *svp (if non-NULL) is expected to be POK (valid allocated SvPVX(*svp)) */
140 get_regstr_from(HKEY hkey, const char *valuename, SV **svp)
142 /* Retrieve a REG_SZ or REG_EXPAND_SZ from the registry */
145 const char *subkey = "Software\\Perl";
149 retval = RegOpenKeyEx(hkey, subkey, 0, KEY_READ, &handle);
150 if (retval == ERROR_SUCCESS) {
152 retval = RegQueryValueEx(handle, valuename, 0, &type, NULL, &datalen);
153 if (retval == ERROR_SUCCESS && type == REG_SZ) {
156 *svp = sv_2mortal(newSVpvn("",0));
157 SvGROW(*svp, datalen);
158 retval = RegQueryValueEx(handle, valuename, 0, NULL,
159 (PBYTE)SvPVX(*svp), &datalen);
160 if (retval == ERROR_SUCCESS) {
162 SvCUR_set(*svp,datalen-1);
170 /* *svp (if non-NULL) is expected to be POK (valid allocated SvPVX(*svp)) */
172 get_regstr(const char *valuename, SV **svp)
174 char *str = get_regstr_from(HKEY_CURRENT_USER, valuename, svp);
176 str = get_regstr_from(HKEY_LOCAL_MACHINE, valuename, svp);
180 /* *prev_pathp (if non-NULL) is expected to be POK (valid allocated SvPVX(sv)) */
182 get_emd_part(SV **prev_pathp, char *trailing_path, ...)
186 char mod_name[MAX_PATH+1];
190 int oldsize, newsize;
192 va_start(ap, trailing_path);
193 strip = va_arg(ap, char *);
195 sprintf(base, "%5.3f",
196 (double)PERL_REVISION + ((double)PERL_VERSION / (double)1000));
198 if (!*w32_module_name) {
199 GetModuleFileName((HMODULE)((w32_perldll_handle == INVALID_HANDLE_VALUE)
200 ? GetModuleHandle(NULL)
201 : w32_perldll_handle),
202 w32_module_name, sizeof(w32_module_name));
204 /* try to get full path to binary (which may be mangled when perl is
205 * run from a 16-bit app) */
206 /*PerlIO_printf(Perl_debug_log, "Before %s\n", w32_module_name);*/
207 (void)win32_longpath(w32_module_name);
208 /*PerlIO_printf(Perl_debug_log, "After %s\n", w32_module_name);*/
210 /* normalize to forward slashes */
211 ptr = w32_module_name;
218 strcpy(mod_name, w32_module_name);
219 ptr = strrchr(mod_name, '/');
220 while (ptr && strip) {
221 /* look for directories to skip back */
224 ptr = strrchr(mod_name, '/');
225 /* avoid stripping component if there is no slash,
226 * or it doesn't match ... */
227 if (!ptr || stricmp(ptr+1, strip) != 0) {
228 /* ... but not if component matches 5.00X* */
229 if (!ptr || !(*strip == '5' && *(ptr+1) == '5'
230 && strncmp(strip, base, 5) == 0
231 && strncmp(ptr+1, base, 5) == 0))
237 strip = va_arg(ap, char *);
245 strcpy(++ptr, trailing_path);
247 /* only add directory if it exists */
248 if (GetFileAttributes(mod_name) != (DWORD) -1) {
249 /* directory exists */
252 *prev_pathp = sv_2mortal(newSVpvn("",0));
253 sv_catpvn(*prev_pathp, ";", 1);
254 sv_catpv(*prev_pathp, mod_name);
255 return SvPVX(*prev_pathp);
262 win32_get_privlib(char *pl)
265 char *stdlib = "lib";
266 char buffer[MAX_PATH+1];
269 /* $stdlib = $HKCU{"lib-$]"} || $HKLM{"lib-$]"} || $HKCU{"lib"} || $HKLM{"lib"} || ""; */
270 sprintf(buffer, "%s-%s", stdlib, pl);
271 if (!get_regstr(buffer, &sv))
272 (void)get_regstr(stdlib, &sv);
274 /* $stdlib .= ";$EMD/../../lib" */
275 return get_emd_part(&sv, stdlib, ARCHNAME, "bin", Nullch);
279 win32_get_sitelib(char *pl)
282 char *sitelib = "sitelib";
284 char pathstr[MAX_PATH+1];
290 /* $HKCU{"sitelib-$]"} || $HKLM{"sitelib-$]"} . ---; */
291 sprintf(regstr, "%s-%s", sitelib, pl);
292 (void)get_regstr(regstr, &sv1);
295 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/site/$]/lib"; */
296 sprintf(pathstr, "site/%s/lib", pl);
297 (void)get_emd_part(&sv1, pathstr, ARCHNAME, "bin", pl, Nullch);
298 if (!sv1 && strlen(pl) == 7) {
299 /* pl may have been SUBVERSION-specific; try again without
301 sprintf(pathstr, "site/%.5s/lib", pl);
302 (void)get_emd_part(&sv1, pathstr, ARCHNAME, "bin", pl, Nullch);
305 /* $HKCU{'sitelib'} || $HKLM{'sitelib'} . ---; */
306 (void)get_regstr(sitelib, &sv2);
309 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/site/lib"; */
310 (void)get_emd_part(&sv2, "site/lib", ARCHNAME, "bin", pl, Nullch);
319 sv_catpvn(sv1, ";", 1);
327 has_shell_metachars(char *ptr)
333 * Scan string looking for redirection (< or >) or pipe
334 * characters (|) that are not in a quoted string.
335 * Shell variable interpolation (%VAR%) can also happen inside strings.
367 #if !defined(PERL_IMPLICIT_SYS)
368 /* since the current process environment is being updated in util.c
369 * the library functions will get the correct environment
372 Perl_my_popen(pTHX_ char *cmd, char *mode)
375 #define fixcmd(x) { \
376 char *pspace = strchr((x),' '); \
379 while (p < pspace) { \
390 PERL_FLUSHALL_FOR_CHILD;
391 return win32_popen(cmd, mode);
395 Perl_my_pclose(pTHX_ PerlIO *fp)
397 return win32_pclose(fp);
401 DllExport unsigned long
404 static OSVERSIONINFO osver;
406 if (osver.dwPlatformId != w32_platform) {
407 memset(&osver, 0, sizeof(OSVERSIONINFO));
408 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
409 GetVersionEx(&osver);
410 w32_platform = osver.dwPlatformId;
412 return (unsigned long)w32_platform;
415 /* Tokenize a string. Words are null-separated, and the list
416 * ends with a doubled null. Any character (except null and
417 * including backslash) may be escaped by preceding it with a
418 * backslash (the backslash will be stripped).
419 * Returns number of words in result buffer.
422 tokenize(const char *str, char **dest, char ***destv)
424 char *retstart = Nullch;
425 char **retvstart = 0;
429 int slen = strlen(str);
431 register char **retv;
432 New(1307, ret, slen+2, char);
433 New(1308, retv, (slen+3)/2, char*);
441 if (*ret == '\\' && *str)
443 else if (*ret == ' ') {
459 retvstart[items] = Nullch;
472 if (!w32_perlshell_tokens) {
473 /* we don't use COMSPEC here for two reasons:
474 * 1. the same reason perl on UNIX doesn't use SHELL--rampant and
475 * uncontrolled unportability of the ensuing scripts.
476 * 2. PERL5SHELL could be set to a shell that may not be fit for
477 * interactive use (which is what most programs look in COMSPEC
480 const char* defaultshell = (IsWinNT()
481 ? "cmd.exe /x/c" : "command.com /c");
482 const char *usershell = getenv("PERL5SHELL");
483 w32_perlshell_items = tokenize(usershell ? usershell : defaultshell,
484 &w32_perlshell_tokens,
490 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 if (ckWARN(WARN_EXEC))
543 Perl_warner(aTHX_ WARN_EXEC, "Can't spawn \"%s\": %s", argv[0], strerror(errno));
548 PL_statusvalue = status;
555 do_spawn2(char *cmd, int exectype)
562 BOOL needToTry = TRUE;
565 /* Save an extra exec if possible. See if there are shell
566 * metacharacters in it */
567 if (!has_shell_metachars(cmd)) {
568 New(1301,argv, strlen(cmd) / 2 + 2, char*);
569 New(1302,cmd2, strlen(cmd) + 1, char);
572 for (s = cmd2; *s;) {
573 while (*s && isSPACE(*s))
577 while (*s && !isSPACE(*s))
586 status = win32_spawnvp(P_WAIT, argv[0],
587 (const char* const*)argv);
589 case EXECF_SPAWN_NOWAIT:
590 status = win32_spawnvp(P_NOWAIT, argv[0],
591 (const char* const*)argv);
594 status = win32_execvp(argv[0], (const char* const*)argv);
597 if (status != -1 || errno == 0)
607 New(1306, argv, w32_perlshell_items + 2, char*);
608 while (++i < w32_perlshell_items)
609 argv[i] = w32_perlshell_vec[i];
614 status = win32_spawnvp(P_WAIT, argv[0],
615 (const char* const*)argv);
617 case EXECF_SPAWN_NOWAIT:
618 status = win32_spawnvp(P_NOWAIT, argv[0],
619 (const char* const*)argv);
622 status = win32_execvp(argv[0], (const char* const*)argv);
628 if (exectype != EXECF_SPAWN_NOWAIT) {
631 if (ckWARN(WARN_EXEC))
632 Perl_warner(aTHX_ WARN_EXEC, "Can't %s \"%s\": %s",
633 (exectype == EXECF_EXEC ? "exec" : "spawn"),
634 cmd, strerror(errno));
639 PL_statusvalue = status;
647 return do_spawn2(cmd, EXECF_SPAWN);
651 do_spawn_nowait(char *cmd)
653 return do_spawn2(cmd, EXECF_SPAWN_NOWAIT);
657 Perl_do_exec(pTHX_ char *cmd)
659 do_spawn2(cmd, EXECF_EXEC);
663 /* The idea here is to read all the directory names into a string table
664 * (separated by nulls) and when one of the other dir functions is called
665 * return the pointer to the current file name.
668 win32_opendir(char *filename)
674 char scanname[MAX_PATH+3];
676 WIN32_FIND_DATAA aFindData;
677 WIN32_FIND_DATAW wFindData;
679 char buffer[MAX_PATH*2];
680 WCHAR wbuffer[MAX_PATH];
683 len = strlen(filename);
687 /* check to see if filename is a directory */
688 if (win32_stat(filename, &sbuf) < 0 || !S_ISDIR(sbuf.st_mode))
691 /* Get us a DIR structure */
692 Newz(1303, dirp, 1, DIR);
694 /* Create the search pattern */
695 strcpy(scanname, filename);
697 /* bare drive name means look in cwd for drive */
698 if (len == 2 && isALPHA(scanname[0]) && scanname[1] == ':') {
699 scanname[len++] = '.';
700 scanname[len++] = '/';
702 else if (scanname[len-1] != '/' && scanname[len-1] != '\\') {
703 scanname[len++] = '/';
705 scanname[len++] = '*';
706 scanname[len] = '\0';
708 /* do the FindFirstFile call */
710 A2WHELPER(scanname, wbuffer, sizeof(wbuffer));
711 fh = FindFirstFileW(wbuffer, &wFindData);
714 fh = FindFirstFileA(scanname, &aFindData);
717 if (fh == INVALID_HANDLE_VALUE) {
718 DWORD err = GetLastError();
719 /* FindFirstFile() fails on empty drives! */
721 case ERROR_FILE_NOT_FOUND:
723 case ERROR_NO_MORE_FILES:
724 case ERROR_PATH_NOT_FOUND:
727 case ERROR_NOT_ENOUGH_MEMORY:
738 /* now allocate the first part of the string table for
739 * the filenames that we find.
742 W2AHELPER(wFindData.cFileName, buffer, sizeof(buffer));
746 ptr = aFindData.cFileName;
753 New(1304, dirp->start, dirp->size, char);
754 strcpy(dirp->start, ptr);
756 dirp->end = dirp->curr = dirp->start;
762 /* Readdir just returns the current string pointer and bumps the
763 * string pointer to the nDllExport entry.
765 DllExport struct direct *
766 win32_readdir(DIR *dirp)
771 /* first set up the structure to return */
772 len = strlen(dirp->curr);
773 strcpy(dirp->dirstr.d_name, dirp->curr);
774 dirp->dirstr.d_namlen = len;
777 dirp->dirstr.d_ino = dirp->curr - dirp->start;
779 /* Now set up for the next call to readdir */
780 dirp->curr += len + 1;
781 if (dirp->curr >= dirp->end) {
785 WIN32_FIND_DATAW wFindData;
786 WIN32_FIND_DATAA aFindData;
787 char buffer[MAX_PATH*2];
789 /* finding the next file that matches the wildcard
790 * (which should be all of them in this directory!).
793 res = FindNextFileW(dirp->handle, &wFindData);
795 W2AHELPER(wFindData.cFileName, buffer, sizeof(buffer));
800 res = FindNextFileA(dirp->handle, &aFindData);
802 ptr = aFindData.cFileName;
805 long endpos = dirp->end - dirp->start;
806 long newsize = endpos + strlen(ptr) + 1;
807 /* bump the string table size by enough for the
808 * new name and it's null terminator */
809 while (newsize > dirp->size) {
810 long curpos = dirp->curr - dirp->start;
812 Renew(dirp->start, dirp->size, char);
813 dirp->curr = dirp->start + curpos;
815 strcpy(dirp->start + endpos, ptr);
816 dirp->end = dirp->start + newsize;
822 return &(dirp->dirstr);
828 /* Telldir returns the current string pointer position */
830 win32_telldir(DIR *dirp)
832 return (dirp->curr - dirp->start);
836 /* Seekdir moves the string pointer to a previously saved position
837 * (returned by telldir).
840 win32_seekdir(DIR *dirp, long loc)
842 dirp->curr = dirp->start + loc;
845 /* Rewinddir resets the string pointer to the start */
847 win32_rewinddir(DIR *dirp)
849 dirp->curr = dirp->start;
852 /* free the memory allocated by opendir */
854 win32_closedir(DIR *dirp)
857 if (dirp->handle != INVALID_HANDLE_VALUE)
858 FindClose(dirp->handle);
859 Safefree(dirp->start);
872 * Just pretend that everyone is a superuser. NT will let us know if
873 * we don\'t really have permission to do something.
876 #define ROOT_UID ((uid_t)0)
877 #define ROOT_GID ((gid_t)0)
906 return (auid == ROOT_UID ? 0 : -1);
912 return (agid == ROOT_GID ? 0 : -1);
919 char *buf = getlogin_buffer;
920 DWORD size = sizeof(getlogin_buffer);
921 if (GetUserName(buf,&size))
927 chown(const char *path, uid_t owner, gid_t group)
938 for (child = 0 ; child < w32_num_children ; ++child) {
939 if (w32_child_pids[child] == pid)
946 remove_dead_process(long child)
950 CloseHandle(w32_child_handles[child]);
951 Copy(&w32_child_handles[child+1], &w32_child_handles[child],
952 (w32_num_children-child-1), HANDLE);
953 Copy(&w32_child_pids[child+1], &w32_child_pids[child],
954 (w32_num_children-child-1), DWORD);
960 win32_kill(int pid, int sig)
963 hProcess = OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid);
964 if (hProcess && TerminateProcess(hProcess, sig))
965 CloseHandle(hProcess);
977 DllExport unsigned int
978 win32_sleep(unsigned int t)
985 win32_stat(const char *path, struct stat *buffer)
989 int l = strlen(path);
991 WCHAR wbuffer[MAX_PATH];
994 switch(path[l - 1]) {
995 /* FindFirstFile() and stat() are buggy with a trailing
996 * backslash, so change it to a forward slash :-( */
998 strncpy(t, path, l-1);
1003 /* FindFirstFile() is buggy with "x:", so add a dot :-( */
1005 if (l == 2 && isALPHA(path[0])) {
1006 t[0] = path[0]; t[1] = ':'; t[2] = '.'; t[3] = '\0';
1014 A2WHELPER(path, wbuffer, sizeof(wbuffer));
1015 res = _wstat(wbuffer, (struct _stat *)buffer);
1018 res = stat(path, buffer);
1021 /* CRT is buggy on sharenames, so make sure it really isn't.
1022 * XXX using GetFileAttributesEx() will enable us to set
1023 * buffer->st_*time (but note that's not available on the
1024 * Windows of 1995) */
1027 r = GetFileAttributesW(wbuffer);
1030 r = GetFileAttributesA(path);
1032 if (r != 0xffffffff && (r & FILE_ATTRIBUTE_DIRECTORY)) {
1033 /* buffer may still contain old garbage since stat() failed */
1034 Zero(buffer, 1, struct stat);
1035 buffer->st_mode = S_IFDIR | S_IREAD;
1037 if (!(r & FILE_ATTRIBUTE_READONLY))
1038 buffer->st_mode |= S_IWRITE | S_IEXEC;
1043 if (l == 3 && isALPHA(path[0]) && path[1] == ':'
1044 && (path[2] == '\\' || path[2] == '/'))
1046 /* The drive can be inaccessible, some _stat()s are buggy */
1048 ? !GetVolumeInformationW(wbuffer,NULL,0,NULL,NULL,NULL,NULL,0)
1049 : !GetVolumeInformationA(path,NULL,0,NULL,NULL,NULL,NULL,0)) {
1055 if (S_ISDIR(buffer->st_mode))
1056 buffer->st_mode |= S_IWRITE | S_IEXEC;
1057 else if (S_ISREG(buffer->st_mode)) {
1058 if (l >= 4 && path[l-4] == '.') {
1059 const char *e = path + l - 3;
1060 if (strnicmp(e,"exe",3)
1061 && strnicmp(e,"bat",3)
1062 && strnicmp(e,"com",3)
1063 && (IsWin95() || strnicmp(e,"cmd",3)))
1064 buffer->st_mode &= ~S_IEXEC;
1066 buffer->st_mode |= S_IEXEC;
1069 buffer->st_mode &= ~S_IEXEC;
1076 /* Find the longname of a given path. path is destructively modified.
1077 * It should have space for at least MAX_PATH characters. */
1079 win32_longpath(char *path)
1081 WIN32_FIND_DATA fdata;
1083 char tmpbuf[MAX_PATH+1];
1084 char *tmpstart = tmpbuf;
1091 if (isALPHA(path[0]) && path[1] == ':' &&
1092 (path[2] == '/' || path[2] == '\\'))
1095 *tmpstart++ = path[0];
1099 else if ((path[0] == '/' || path[0] == '\\') &&
1100 (path[1] == '/' || path[1] == '\\'))
1103 *tmpstart++ = path[0];
1104 *tmpstart++ = path[1];
1105 /* copy machine name */
1106 while (*start && *start != '/' && *start != '\\')
1107 *tmpstart++ = *start++;
1109 *tmpstart++ = *start;
1111 /* copy share name */
1112 while (*start && *start != '/' && *start != '\\')
1113 *tmpstart++ = *start++;
1117 if (sep == '/' || sep == '\\')
1121 /* walk up to slash */
1122 while (*start && *start != '/' && *start != '\\')
1125 /* discard doubled slashes */
1126 while (*start && (start[1] == '/' || start[1] == '\\'))
1130 /* stop and find full name of component */
1132 fhand = FindFirstFile(path,&fdata);
1133 if (fhand != INVALID_HANDLE_VALUE) {
1134 strcpy(tmpstart, fdata.cFileName);
1135 tmpstart += strlen(fdata.cFileName);
1143 /* failed a step, just return without side effects */
1144 /*PerlIO_printf(Perl_debug_log, "Failed to find %s\n", path);*/
1149 strcpy(path,tmpbuf);
1153 #ifndef USE_WIN32_RTL_ENV
1156 win32_getenv(const char *name)
1159 WCHAR wBuffer[MAX_PATH];
1161 SV *curitem = Nullsv;
1164 A2WHELPER(name, wBuffer, sizeof(wBuffer));
1165 needlen = GetEnvironmentVariableW(wBuffer, NULL, 0);
1168 needlen = GetEnvironmentVariableA(name,NULL,0);
1170 curitem = sv_2mortal(newSVpvn("", 0));
1174 SvGROW(curitem, (needlen+1)*sizeof(WCHAR));
1175 needlen = GetEnvironmentVariableW(wBuffer,
1176 (WCHAR*)SvPVX(curitem),
1178 } while (needlen >= SvLEN(curitem)/sizeof(WCHAR));
1179 SvCUR_set(curitem, (needlen*sizeof(WCHAR))+1);
1180 acuritem = sv_2mortal(newSVsv(curitem));
1181 W2AHELPER((WCHAR*)SvPVX(acuritem), SvPVX(curitem), SvCUR(curitem));
1185 SvGROW(curitem, needlen+1);
1186 needlen = GetEnvironmentVariableA(name,SvPVX(curitem),
1188 } while (needlen >= SvLEN(curitem));
1189 SvCUR_set(curitem, needlen);
1193 /* allow any environment variables that begin with 'PERL'
1194 to be stored in the registry */
1195 if (strncmp(name, "PERL", 4) == 0)
1196 (void)get_regstr(name, &curitem);
1198 if (curitem && SvCUR(curitem))
1199 return SvPVX(curitem);
1205 win32_putenv(const char *name)
1212 int length, relval = -1;
1216 length = strlen(name)+1;
1217 New(1309,wCuritem,length,WCHAR);
1218 A2WHELPER(name, wCuritem, length*sizeof(WCHAR));
1219 wVal = wcschr(wCuritem, '=');
1222 if(SetEnvironmentVariableW(wCuritem, *wVal ? wVal : NULL))
1228 New(1309,curitem,strlen(name)+1,char);
1229 strcpy(curitem, name);
1230 val = strchr(curitem, '=');
1232 /* The sane way to deal with the environment.
1233 * Has these advantages over putenv() & co.:
1234 * * enables us to store a truly empty value in the
1235 * environment (like in UNIX).
1236 * * we don't have to deal with RTL globals, bugs and leaks.
1238 * Why you may want to enable USE_WIN32_RTL_ENV:
1239 * * environ[] and RTL functions will not reflect changes,
1240 * which might be an issue if extensions want to access
1241 * the env. via RTL. This cuts both ways, since RTL will
1242 * not see changes made by extensions that call the Win32
1243 * functions directly, either.
1247 if(SetEnvironmentVariableA(curitem, *val ? val : NULL))
1259 filetime_to_clock(PFILETIME ft)
1261 __int64 qw = ft->dwHighDateTime;
1263 qw |= ft->dwLowDateTime;
1264 qw /= 10000; /* File time ticks at 0.1uS, clock at 1mS */
1269 win32_times(struct tms *timebuf)
1274 if (GetProcessTimes(GetCurrentProcess(), &dummy, &dummy,
1276 timebuf->tms_utime = filetime_to_clock(&user);
1277 timebuf->tms_stime = filetime_to_clock(&kernel);
1278 timebuf->tms_cutime = 0;
1279 timebuf->tms_cstime = 0;
1282 /* That failed - e.g. Win95 fallback to clock() */
1283 clock_t t = clock();
1284 timebuf->tms_utime = t;
1285 timebuf->tms_stime = 0;
1286 timebuf->tms_cutime = 0;
1287 timebuf->tms_cstime = 0;
1292 /* fix utime() so it works on directories in NT */
1294 filetime_from_time(PFILETIME pFileTime, time_t Time)
1296 struct tm *pTM = localtime(&Time);
1297 SYSTEMTIME SystemTime;
1303 SystemTime.wYear = pTM->tm_year + 1900;
1304 SystemTime.wMonth = pTM->tm_mon + 1;
1305 SystemTime.wDay = pTM->tm_mday;
1306 SystemTime.wHour = pTM->tm_hour;
1307 SystemTime.wMinute = pTM->tm_min;
1308 SystemTime.wSecond = pTM->tm_sec;
1309 SystemTime.wMilliseconds = 0;
1311 return SystemTimeToFileTime(&SystemTime, &LocalTime) &&
1312 LocalFileTimeToFileTime(&LocalTime, pFileTime);
1316 win32_utime(const char *filename, struct utimbuf *times)
1323 struct utimbuf TimeBuffer;
1324 WCHAR wbuffer[MAX_PATH];
1328 A2WHELPER(filename, wbuffer, sizeof(wbuffer));
1329 rc = _wutime(wbuffer, (struct _utimbuf*)times);
1332 rc = utime(filename, times);
1334 /* EACCES: path specifies directory or readonly file */
1335 if (rc == 0 || errno != EACCES /* || !IsWinNT() */)
1338 if (times == NULL) {
1339 times = &TimeBuffer;
1340 time(×->actime);
1341 times->modtime = times->actime;
1344 /* This will (and should) still fail on readonly files */
1346 handle = CreateFileW(wbuffer, GENERIC_READ | GENERIC_WRITE,
1347 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1348 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1351 handle = CreateFileA(filename, GENERIC_READ | GENERIC_WRITE,
1352 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1353 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1355 if (handle == INVALID_HANDLE_VALUE)
1358 if (GetFileTime(handle, &ftCreate, &ftAccess, &ftWrite) &&
1359 filetime_from_time(&ftAccess, times->actime) &&
1360 filetime_from_time(&ftWrite, times->modtime) &&
1361 SetFileTime(handle, &ftCreate, &ftAccess, &ftWrite))
1366 CloseHandle(handle);
1371 win32_uname(struct utsname *name)
1373 struct hostent *hep;
1374 STRLEN nodemax = sizeof(name->nodename)-1;
1375 OSVERSIONINFO osver;
1377 memset(&osver, 0, sizeof(OSVERSIONINFO));
1378 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1379 if (GetVersionEx(&osver)) {
1381 switch (osver.dwPlatformId) {
1382 case VER_PLATFORM_WIN32_WINDOWS:
1383 strcpy(name->sysname, "Windows");
1385 case VER_PLATFORM_WIN32_NT:
1386 strcpy(name->sysname, "Windows NT");
1388 case VER_PLATFORM_WIN32s:
1389 strcpy(name->sysname, "Win32s");
1392 strcpy(name->sysname, "Win32 Unknown");
1397 sprintf(name->release, "%d.%d",
1398 osver.dwMajorVersion, osver.dwMinorVersion);
1401 sprintf(name->version, "Build %d",
1402 osver.dwPlatformId == VER_PLATFORM_WIN32_NT
1403 ? osver.dwBuildNumber : (osver.dwBuildNumber & 0xffff));
1404 if (osver.szCSDVersion[0]) {
1405 char *buf = name->version + strlen(name->version);
1406 sprintf(buf, " (%s)", osver.szCSDVersion);
1410 *name->sysname = '\0';
1411 *name->version = '\0';
1412 *name->release = '\0';
1416 hep = win32_gethostbyname("localhost");
1418 STRLEN len = strlen(hep->h_name);
1419 if (len <= nodemax) {
1420 strcpy(name->nodename, hep->h_name);
1423 strncpy(name->nodename, hep->h_name, nodemax);
1424 name->nodename[nodemax] = '\0';
1429 if (!GetComputerName(name->nodename, &sz))
1430 *name->nodename = '\0';
1433 /* machine (architecture) */
1437 GetSystemInfo(&info);
1439 #if defined(__BORLANDC__) || defined(__MINGW32__)
1440 switch (info.u.s.wProcessorArchitecture) {
1442 switch (info.wProcessorArchitecture) {
1444 case PROCESSOR_ARCHITECTURE_INTEL:
1445 arch = "x86"; break;
1446 case PROCESSOR_ARCHITECTURE_MIPS:
1447 arch = "mips"; break;
1448 case PROCESSOR_ARCHITECTURE_ALPHA:
1449 arch = "alpha"; break;
1450 case PROCESSOR_ARCHITECTURE_PPC:
1451 arch = "ppc"; break;
1453 arch = "unknown"; break;
1455 strcpy(name->machine, arch);
1461 win32_waitpid(int pid, int *status, int flags)
1466 return win32_wait(status);
1468 long child = find_pid(pid);
1470 HANDLE hProcess = w32_child_handles[child];
1471 DWORD waitcode = WaitForSingleObject(hProcess, INFINITE);
1472 if (waitcode != WAIT_FAILED) {
1473 if (GetExitCodeProcess(hProcess, &waitcode)) {
1474 *status = (int)((waitcode & 0xff) << 8);
1475 retval = (int)w32_child_pids[child];
1476 remove_dead_process(child);
1484 retval = cwait(status, pid, WAIT_CHILD);
1485 /* cwait() returns "correctly" on Borland */
1486 #ifndef __BORLANDC__
1492 return retval >= 0 ? pid : retval;
1496 win32_wait(int *status)
1498 /* XXX this wait emulation only knows about processes
1499 * spawned via win32_spawnvp(P_NOWAIT, ...).
1503 DWORD exitcode, waitcode;
1505 if (!w32_num_children) {
1510 /* if a child exists, wait for it to die */
1511 waitcode = WaitForMultipleObjects(w32_num_children,
1515 if (waitcode != WAIT_FAILED) {
1516 if (waitcode >= WAIT_ABANDONED_0
1517 && waitcode < WAIT_ABANDONED_0 + w32_num_children)
1518 i = waitcode - WAIT_ABANDONED_0;
1520 i = waitcode - WAIT_OBJECT_0;
1521 if (GetExitCodeProcess(w32_child_handles[i], &exitcode) ) {
1522 *status = (int)((exitcode & 0xff) << 8);
1523 retval = (int)w32_child_pids[i];
1524 remove_dead_process(i);
1530 errno = GetLastError();
1534 static UINT timerid = 0;
1536 static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
1539 KillTimer(NULL,timerid);
1544 DllExport unsigned int
1545 win32_alarm(unsigned int sec)
1548 * the 'obvious' implentation is SetTimer() with a callback
1549 * which does whatever receiving SIGALRM would do
1550 * we cannot use SIGALRM even via raise() as it is not
1551 * one of the supported codes in <signal.h>
1553 * Snag is unless something is looking at the message queue
1554 * nothing happens :-(
1559 timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
1561 Perl_croak_nocontext("Cannot set timer");
1567 KillTimer(NULL,timerid);
1574 #if defined(HAVE_DES_FCRYPT) || defined(PERL_OBJECT)
1575 #ifdef HAVE_DES_FCRYPT
1576 extern char * des_fcrypt(const char *txt, const char *salt, char *cbuf);
1580 win32_crypt(const char *txt, const char *salt)
1583 #ifdef HAVE_DES_FCRYPT
1585 return des_fcrypt(txt, salt, crypt_buffer);
1587 die("The crypt() function is unimplemented due to excessive paranoia.");
1593 #ifdef USE_FIXED_OSFHANDLE
1595 EXTERN_C int __cdecl _alloc_osfhnd(void);
1596 EXTERN_C int __cdecl _set_osfhnd(int fh, long value);
1597 EXTERN_C void __cdecl _lock_fhandle(int);
1598 EXTERN_C void __cdecl _unlock_fhandle(int);
1599 EXTERN_C void __cdecl _unlock(int);
1601 #if (_MSC_VER >= 1000)
1603 long osfhnd; /* underlying OS file HANDLE */
1604 char osfile; /* attributes of file (e.g., open in text mode?) */
1605 char pipech; /* one char buffer for handles opened on pipes */
1606 #if defined (_MT) && !defined (DLL_FOR_WIN32S)
1608 CRITICAL_SECTION lock;
1609 #endif /* defined (_MT) && !defined (DLL_FOR_WIN32S) */
1612 EXTERN_C ioinfo * __pioinfo[];
1614 #define IOINFO_L2E 5
1615 #define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
1616 #define _pioinfo(i) (__pioinfo[i >> IOINFO_L2E] + (i & (IOINFO_ARRAY_ELTS - 1)))
1617 #define _osfile(i) (_pioinfo(i)->osfile)
1619 #else /* (_MSC_VER >= 1000) */
1620 extern char _osfile[];
1621 #endif /* (_MSC_VER >= 1000) */
1623 #define FOPEN 0x01 /* file handle open */
1624 #define FAPPEND 0x20 /* file handle opened O_APPEND */
1625 #define FDEV 0x40 /* file handle refers to device */
1626 #define FTEXT 0x80 /* file handle is in text mode */
1628 #define _STREAM_LOCKS 26 /* Table of stream locks */
1629 #define _LAST_STREAM_LOCK (_STREAM_LOCKS+_NSTREAM_-1) /* Last stream lock */
1630 #define _FH_LOCKS (_LAST_STREAM_LOCK+1) /* Table of fh locks */
1633 *int my_open_osfhandle(long osfhandle, int flags) - open C Runtime file handle
1636 * This function allocates a free C Runtime file handle and associates
1637 * it with the Win32 HANDLE specified by the first parameter. This is a
1638 * temperary fix for WIN95's brain damage GetFileType() error on socket
1639 * we just bypass that call for socket
1642 * long osfhandle - Win32 HANDLE to associate with C Runtime file handle.
1643 * int flags - flags to associate with C Runtime file handle.
1646 * returns index of entry in fh, if successful
1647 * return -1, if no free entry is found
1651 *******************************************************************************/
1654 my_open_osfhandle(long osfhandle, int flags)
1657 char fileflags; /* _osfile flags */
1659 /* copy relevant flags from second parameter */
1662 if (flags & O_APPEND)
1663 fileflags |= FAPPEND;
1668 /* attempt to allocate a C Runtime file handle */
1669 if ((fh = _alloc_osfhnd()) == -1) {
1670 errno = EMFILE; /* too many open files */
1671 _doserrno = 0L; /* not an OS error */
1672 return -1; /* return error to caller */
1675 /* the file is open. now, set the info in _osfhnd array */
1676 _set_osfhnd(fh, osfhandle);
1678 fileflags |= FOPEN; /* mark as open */
1680 #if (_MSC_VER >= 1000)
1681 _osfile(fh) = fileflags; /* set osfile entry */
1682 _unlock_fhandle(fh);
1684 _osfile[fh] = fileflags; /* set osfile entry */
1685 _unlock(fh+_FH_LOCKS); /* unlock handle */
1688 return fh; /* return handle */
1691 #define _open_osfhandle my_open_osfhandle
1692 #endif /* USE_FIXED_OSFHANDLE */
1694 /* simulate flock by locking a range on the file */
1696 #define LK_ERR(f,i) ((f) ? (i = 0) : (errno = GetLastError()))
1697 #define LK_LEN 0xffff0000
1700 win32_flock(int fd, int oper)
1708 Perl_croak_nocontext("flock() unimplemented on this platform");
1711 fh = (HANDLE)_get_osfhandle(fd);
1712 memset(&o, 0, sizeof(o));
1715 case LOCK_SH: /* shared lock */
1716 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
1718 case LOCK_EX: /* exclusive lock */
1719 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
1721 case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
1722 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
1724 case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
1725 LK_ERR(LockFileEx(fh,
1726 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
1727 0, LK_LEN, 0, &o),i);
1729 case LOCK_UN: /* unlock lock */
1730 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, 0, &o),i);
1732 default: /* unknown */
1743 * redirected io subsystem for all XS modules
1756 return (&(_environ));
1759 /* the rest are the remapped stdio routines */
1779 win32_ferror(FILE *fp)
1781 return (ferror(fp));
1786 win32_feof(FILE *fp)
1792 * Since the errors returned by the socket error function
1793 * WSAGetLastError() are not known by the library routine strerror
1794 * we have to roll our own.
1798 win32_strerror(int e)
1800 #ifndef __BORLANDC__ /* Borland intolerance */
1801 extern int sys_nerr;
1805 if (e < 0 || e > sys_nerr) {
1810 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
1811 strerror_buffer, sizeof(strerror_buffer), NULL) == 0)
1812 strcpy(strerror_buffer, "Unknown Error");
1814 return strerror_buffer;
1820 win32_str_os_error(void *sv, DWORD dwErr)
1824 dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
1825 |FORMAT_MESSAGE_IGNORE_INSERTS
1826 |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
1827 dwErr, 0, (char *)&sMsg, 1, NULL);
1828 /* strip trailing whitespace and period */
1831 --dwLen; /* dwLen doesn't include trailing null */
1832 } while (0 < dwLen && isSPACE(sMsg[dwLen]));
1833 if ('.' != sMsg[dwLen])
1838 sMsg = (char*)LocalAlloc(0, 64/**sizeof(TCHAR)*/);
1840 dwLen = sprintf(sMsg,
1841 "Unknown error #0x%lX (lookup 0x%lX)",
1842 dwErr, GetLastError());
1846 sv_setpvn((SV*)sv, sMsg, dwLen);
1853 win32_fprintf(FILE *fp, const char *format, ...)
1856 va_start(marker, format); /* Initialize variable arguments. */
1858 return (vfprintf(fp, format, marker));
1862 win32_printf(const char *format, ...)
1865 va_start(marker, format); /* Initialize variable arguments. */
1867 return (vprintf(format, marker));
1871 win32_vfprintf(FILE *fp, const char *format, va_list args)
1873 return (vfprintf(fp, format, args));
1877 win32_vprintf(const char *format, va_list args)
1879 return (vprintf(format, args));
1883 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
1885 return fread(buf, size, count, fp);
1889 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
1891 return fwrite(buf, size, count, fp);
1894 #define MODE_SIZE 10
1897 win32_fopen(const char *filename, const char *mode)
1900 WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH];
1905 if (stricmp(filename, "/dev/null")==0)
1909 A2WHELPER(mode, wMode, sizeof(wMode));
1910 A2WHELPER(filename, wBuffer, sizeof(wBuffer));
1911 return _wfopen(wBuffer, wMode);
1913 return fopen(filename, mode);
1916 #ifndef USE_SOCKETS_AS_HANDLES
1918 #define fdopen my_fdopen
1922 win32_fdopen(int handle, const char *mode)
1925 WCHAR wMode[MODE_SIZE];
1927 A2WHELPER(mode, wMode, sizeof(wMode));
1928 return _wfdopen(handle, wMode);
1930 return fdopen(handle, (char *) mode);
1934 win32_freopen(const char *path, const char *mode, FILE *stream)
1937 WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH];
1938 if (stricmp(path, "/dev/null")==0)
1942 A2WHELPER(mode, wMode, sizeof(wMode));
1943 A2WHELPER(path, wBuffer, sizeof(wBuffer));
1944 return _wfreopen(wBuffer, wMode, stream);
1946 return freopen(path, mode, stream);
1950 win32_fclose(FILE *pf)
1952 return my_fclose(pf); /* defined in win32sck.c */
1956 win32_fputs(const char *s,FILE *pf)
1958 return fputs(s, pf);
1962 win32_fputc(int c,FILE *pf)
1968 win32_ungetc(int c,FILE *pf)
1970 return ungetc(c,pf);
1974 win32_getc(FILE *pf)
1980 win32_fileno(FILE *pf)
1986 win32_clearerr(FILE *pf)
1993 win32_fflush(FILE *pf)
1999 win32_ftell(FILE *pf)
2005 win32_fseek(FILE *pf,long offset,int origin)
2007 return fseek(pf, offset, origin);
2011 win32_fgetpos(FILE *pf,fpos_t *p)
2013 return fgetpos(pf, p);
2017 win32_fsetpos(FILE *pf,const fpos_t *p)
2019 return fsetpos(pf, p);
2023 win32_rewind(FILE *pf)
2043 win32_fstat(int fd,struct stat *sbufptr)
2045 return fstat(fd,sbufptr);
2049 win32_pipe(int *pfd, unsigned int size, int mode)
2051 return _pipe(pfd, size, mode);
2055 * a popen() clone that respects PERL5SHELL
2059 win32_popen(const char *command, const char *mode)
2061 #ifdef USE_RTL_POPEN
2062 return _popen(command, mode);
2070 /* establish which ends read and write */
2071 if (strchr(mode,'w')) {
2072 stdfd = 0; /* stdin */
2076 else if (strchr(mode,'r')) {
2077 stdfd = 1; /* stdout */
2084 /* set the correct mode */
2085 if (strchr(mode,'b'))
2087 else if (strchr(mode,'t'))
2090 ourmode = _fmode & (O_TEXT | O_BINARY);
2092 /* the child doesn't inherit handles */
2093 ourmode |= O_NOINHERIT;
2095 if (win32_pipe( p, 512, ourmode) == -1)
2098 /* save current stdfd */
2099 if ((oldfd = win32_dup(stdfd)) == -1)
2102 /* make stdfd go to child end of pipe (implicitly closes stdfd) */
2103 /* stdfd will be inherited by the child */
2104 if (win32_dup2(p[child], stdfd) == -1)
2107 /* close the child end in parent */
2108 win32_close(p[child]);
2110 /* start the child */
2113 if ((childpid = do_spawn_nowait((char*)command)) == -1)
2116 /* revert stdfd to whatever it was before */
2117 if (win32_dup2(oldfd, stdfd) == -1)
2120 /* close saved handle */
2123 sv_setiv(*av_fetch(w32_fdpid, p[parent], TRUE), childpid);
2125 /* set process id so that it can be returned by perl's open() */
2126 PL_forkprocess = childpid;
2129 /* we have an fd, return a file stream */
2130 return (win32_fdopen(p[parent], (char *)mode));
2133 /* we don't need to check for errors here */
2137 win32_dup2(oldfd, stdfd);
2142 #endif /* USE_RTL_POPEN */
2150 win32_pclose(FILE *pf)
2152 #ifdef USE_RTL_POPEN
2156 int childpid, status;
2159 sv = *av_fetch(w32_fdpid, win32_fileno(pf), TRUE);
2161 childpid = SvIVX(sv);
2173 if (win32_waitpid(childpid, &status, 0) == -1)
2178 #endif /* USE_RTL_POPEN */
2182 win32_rename(const char *oname, const char *newname)
2184 WCHAR wOldName[MAX_PATH];
2185 WCHAR wNewName[MAX_PATH];
2187 /* XXX despite what the documentation says about MoveFileEx(),
2188 * it doesn't work under Windows95!
2193 A2WHELPER(oname, wOldName, sizeof(wOldName));
2194 A2WHELPER(newname, wNewName, sizeof(wNewName));
2195 bResult = MoveFileExW(wOldName,wNewName,
2196 MOVEFILE_COPY_ALLOWED|MOVEFILE_REPLACE_EXISTING);
2199 bResult = MoveFileExA(oname,newname,
2200 MOVEFILE_COPY_ALLOWED|MOVEFILE_REPLACE_EXISTING);
2203 DWORD err = GetLastError();
2205 case ERROR_BAD_NET_NAME:
2206 case ERROR_BAD_NETPATH:
2207 case ERROR_BAD_PATHNAME:
2208 case ERROR_FILE_NOT_FOUND:
2209 case ERROR_FILENAME_EXCED_RANGE:
2210 case ERROR_INVALID_DRIVE:
2211 case ERROR_NO_MORE_FILES:
2212 case ERROR_PATH_NOT_FOUND:
2225 char tmpname[MAX_PATH+1];
2226 char dname[MAX_PATH+1];
2227 char *endname = Nullch;
2229 DWORD from_attr, to_attr;
2231 /* if oname doesn't exist, do nothing */
2232 from_attr = GetFileAttributes(oname);
2233 if (from_attr == 0xFFFFFFFF) {
2238 /* if newname exists, rename it to a temporary name so that we
2239 * don't delete it in case oname happens to be the same file
2240 * (but perhaps accessed via a different path)
2242 to_attr = GetFileAttributes(newname);
2243 if (to_attr != 0xFFFFFFFF) {
2244 /* if newname is a directory, we fail
2245 * XXX could overcome this with yet more convoluted logic */
2246 if (to_attr & FILE_ATTRIBUTE_DIRECTORY) {
2250 tmplen = strlen(newname);
2251 strcpy(tmpname,newname);
2252 endname = tmpname+tmplen;
2253 for (; endname > tmpname ; --endname) {
2254 if (*endname == '/' || *endname == '\\') {
2259 if (endname > tmpname)
2260 endname = strcpy(dname,tmpname);
2264 /* get a temporary filename in same directory
2265 * XXX is this really the best we can do? */
2266 if (!GetTempFileName((LPCTSTR)endname, "plr", 0, tmpname)) {
2270 DeleteFile(tmpname);
2272 retval = rename(newname, tmpname);
2279 /* rename oname to newname */
2280 retval = rename(oname, newname);
2282 /* if we created a temporary file before ... */
2283 if (endname != Nullch) {
2284 /* ...and rename succeeded, delete temporary file/directory */
2286 DeleteFile(tmpname);
2287 /* else restore it to what it was */
2289 (void)rename(tmpname, newname);
2296 win32_setmode(int fd, int mode)
2298 return setmode(fd, mode);
2302 win32_lseek(int fd, long offset, int origin)
2304 return lseek(fd, offset, origin);
2314 win32_open(const char *path, int flag, ...)
2319 WCHAR wBuffer[MAX_PATH];
2322 pmode = va_arg(ap, int);
2325 if (stricmp(path, "/dev/null")==0)
2329 A2WHELPER(path, wBuffer, sizeof(wBuffer));
2330 return _wopen(wBuffer, flag, pmode);
2332 return open(path,flag,pmode);
2354 win32_dup2(int fd1,int fd2)
2356 return dup2(fd1,fd2);
2360 win32_read(int fd, void *buf, unsigned int cnt)
2362 return read(fd, buf, cnt);
2366 win32_write(int fd, const void *buf, unsigned int cnt)
2368 return write(fd, buf, cnt);
2372 win32_mkdir(const char *dir, int mode)
2374 return mkdir(dir); /* just ignore mode */
2378 win32_rmdir(const char *dir)
2384 win32_chdir(const char *dir)
2390 create_command_line(const char* command, const char * const *args)
2394 char *cmd, *ptr, *arg;
2395 STRLEN len = strlen(command) + 1;
2397 for (index = 0; (ptr = (char*)args[index]) != NULL; ++index)
2398 len += strlen(ptr) + 1;
2400 New(1310, cmd, len, char);
2402 strcpy(ptr, command);
2404 for (index = 0; (arg = (char*)args[index]) != NULL; ++index) {
2414 qualified_path(const char *cmd)
2418 char *fullcmd, *curfullcmd;
2424 fullcmd = (char*)cmd;
2426 if (*fullcmd == '/' || *fullcmd == '\\')
2433 pathstr = win32_getenv("PATH");
2434 New(0, fullcmd, MAX_PATH+1, char);
2435 curfullcmd = fullcmd;
2440 /* start by appending the name to the current prefix */
2441 strcpy(curfullcmd, cmd);
2442 curfullcmd += cmdlen;
2444 /* if it doesn't end with '.', or has no extension, try adding
2445 * a trailing .exe first */
2446 if (cmd[cmdlen-1] != '.'
2447 && (cmdlen < 4 || cmd[cmdlen-4] != '.'))
2449 strcpy(curfullcmd, ".exe");
2450 res = GetFileAttributes(fullcmd);
2451 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
2456 /* that failed, try the bare name */
2457 res = GetFileAttributes(fullcmd);
2458 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
2461 /* quit if no other path exists, or if cmd already has path */
2462 if (!pathstr || !*pathstr || has_slash)
2465 /* skip leading semis */
2466 while (*pathstr == ';')
2469 /* build a new prefix from scratch */
2470 curfullcmd = fullcmd;
2471 while (*pathstr && *pathstr != ';') {
2472 if (*pathstr == '"') { /* foo;"baz;etc";bar */
2473 pathstr++; /* skip initial '"' */
2474 while (*pathstr && *pathstr != '"') {
2475 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
2476 *curfullcmd++ = *pathstr;
2480 pathstr++; /* skip trailing '"' */
2483 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
2484 *curfullcmd++ = *pathstr;
2489 pathstr++; /* skip trailing semi */
2490 if (curfullcmd > fullcmd /* append a dir separator */
2491 && curfullcmd[-1] != '/' && curfullcmd[-1] != '\\')
2493 *curfullcmd++ = '\\';
2501 /* The following are just place holders.
2502 * Some hosts may provide and environment that the OS is
2503 * not tracking, therefore, these host must provide that
2504 * environment and the current directory to CreateProcess
2514 free_childenv(void* d)
2525 free_childdir(char* d)
2530 /* XXX this needs to be made more compatible with the spawnvp()
2531 * provided by the various RTLs. In particular, searching for
2532 * *.{com,bat,cmd} files (as done by the RTLs) is unimplemented.
2533 * This doesn't significantly affect perl itself, because we
2534 * always invoke things using PERL5SHELL if a direct attempt to
2535 * spawn the executable fails.
2537 * XXX splitting and rejoining the commandline between do_aspawn()
2538 * and win32_spawnvp() could also be avoided.
2542 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
2544 #ifdef USE_RTL_SPAWNVP
2545 return spawnvp(mode, cmdname, (char * const *)argv);
2551 STARTUPINFO StartupInfo;
2552 PROCESS_INFORMATION ProcessInformation;
2555 char *cmd = create_command_line(cmdname, strcmp(cmdname, argv[0]) == 0
2557 char *fullcmd = Nullch;
2559 env = PerlEnv_get_childenv();
2560 dir = PerlEnv_get_childdir();
2563 case P_NOWAIT: /* asynch + remember result */
2564 if (w32_num_children >= MAXIMUM_WAIT_OBJECTS) {
2570 case P_WAIT: /* synchronous execution */
2572 default: /* invalid mode */
2577 memset(&StartupInfo,0,sizeof(StartupInfo));
2578 StartupInfo.cb = sizeof(StartupInfo);
2579 StartupInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
2580 StartupInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
2581 StartupInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
2582 if (StartupInfo.hStdInput != INVALID_HANDLE_VALUE &&
2583 StartupInfo.hStdOutput != INVALID_HANDLE_VALUE &&
2584 StartupInfo.hStdError != INVALID_HANDLE_VALUE)
2586 StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
2589 create |= CREATE_NEW_CONSOLE;
2593 if (!CreateProcess(cmdname, /* search PATH to find executable */
2594 cmd, /* executable, and its arguments */
2595 NULL, /* process attributes */
2596 NULL, /* thread attributes */
2597 TRUE, /* inherit handles */
2598 create, /* creation flags */
2599 (LPVOID)env, /* inherit environment */
2600 dir, /* inherit cwd */
2602 &ProcessInformation))
2604 /* initial NULL argument to CreateProcess() does a PATH
2605 * search, but it always first looks in the directory
2606 * where the current process was started, which behavior
2607 * is undesirable for backward compatibility. So we
2608 * jump through our own hoops by picking out the path
2609 * we really want it to use. */
2611 fullcmd = qualified_path(cmdname);
2622 if (mode == P_NOWAIT) {
2623 /* asynchronous spawn -- store handle, return PID */
2624 w32_child_handles[w32_num_children] = ProcessInformation.hProcess;
2625 w32_child_pids[w32_num_children] = ProcessInformation.dwProcessId;
2626 ret = (int)ProcessInformation.dwProcessId;
2631 WaitForSingleObject(ProcessInformation.hProcess, INFINITE);
2632 GetExitCodeProcess(ProcessInformation.hProcess, &status);
2634 CloseHandle(ProcessInformation.hProcess);
2637 CloseHandle(ProcessInformation.hThread);
2640 PerlEnv_free_childenv(env);
2641 PerlEnv_free_childdir(dir);
2649 win32_execv(const char *cmdname, const char *const *argv)
2651 return execv(cmdname, (char *const *)argv);
2655 win32_execvp(const char *cmdname, const char *const *argv)
2657 return execvp(cmdname, (char *const *)argv);
2661 win32_perror(const char *str)
2667 win32_setbuf(FILE *pf, char *buf)
2673 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
2675 return setvbuf(pf, buf, type, size);
2679 win32_flushall(void)
2685 win32_fcloseall(void)
2691 win32_fgets(char *s, int n, FILE *pf)
2693 return fgets(s, n, pf);
2703 win32_fgetc(FILE *pf)
2709 win32_putc(int c, FILE *pf)
2715 win32_puts(const char *s)
2727 win32_putchar(int c)
2734 #ifndef USE_PERL_SBRK
2736 static char *committed = NULL;
2737 static char *base = NULL;
2738 static char *reserved = NULL;
2739 static char *brk = NULL;
2740 static DWORD pagesize = 0;
2741 static DWORD allocsize = 0;
2749 GetSystemInfo(&info);
2750 /* Pretend page size is larger so we don't perpetually
2751 * call the OS to commit just one page ...
2753 pagesize = info.dwPageSize << 3;
2754 allocsize = info.dwAllocationGranularity;
2756 /* This scheme fails eventually if request for contiguous
2757 * block is denied so reserve big blocks - this is only
2758 * address space not memory ...
2760 if (brk+need >= reserved)
2762 DWORD size = 64*1024*1024;
2764 if (committed && reserved && committed < reserved)
2766 /* Commit last of previous chunk cannot span allocations */
2767 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
2769 committed = reserved;
2771 /* Reserve some (more) space
2772 * Note this is a little sneaky, 1st call passes NULL as reserved
2773 * so lets system choose where we start, subsequent calls pass
2774 * the old end address so ask for a contiguous block
2776 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
2779 reserved = addr+size;
2794 if (brk > committed)
2796 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
2797 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
2812 win32_malloc(size_t size)
2814 return malloc(size);
2818 win32_calloc(size_t numitems, size_t size)
2820 return calloc(numitems,size);
2824 win32_realloc(void *block, size_t size)
2826 return realloc(block,size);
2830 win32_free(void *block)
2837 win32_open_osfhandle(long handle, int flags)
2839 return _open_osfhandle(handle, flags);
2843 win32_get_osfhandle(int fd)
2845 return _get_osfhandle(fd);
2849 win32_dynaload(const char* filename)
2854 WCHAR wfilename[MAX_PATH];
2855 A2WHELPER(filename, wfilename, sizeof(wfilename));
2856 hModule = LoadLibraryExW(wfilename, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
2859 hModule = LoadLibraryExA(filename, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
2865 win32_add_host(char *nameId, void *data)
2868 * This must be called before the script is parsed,
2869 * therefore no locking of threads is needed
2872 struct host_link *link;
2873 New(1314, link, 1, struct host_link);
2874 link->host_data = data;
2875 link->nameId = nameId;
2876 link->next = w32_host_link;
2877 w32_host_link = link;
2882 win32_get_host_data(char *nameId)
2885 struct host_link *link = w32_host_link;
2887 if(strEQ(link->nameId, nameId))
2888 return link->host_data;
2902 SV *sv = sv_newmortal();
2903 /* Make one call with zero size - return value is required size */
2904 DWORD len = GetCurrentDirectory((DWORD)0,NULL);
2905 SvUPGRADE(sv,SVt_PV);
2907 SvCUR(sv) = GetCurrentDirectory((DWORD) SvLEN(sv), SvPVX(sv));
2910 * then it worked, set PV valid,
2911 * else leave it 'undef'
2927 Perl_croak(aTHX_ "usage: Win32::SetCurrentDirectory($cwd)");
2928 if (SetCurrentDirectory(SvPV_nolen(ST(0))))
2935 XS(w32_GetNextAvailDrive)
2939 char root[] = "_:\\";
2944 if (GetDriveType(root) == 1) {
2953 XS(w32_GetLastError)
2957 XSRETURN_IV(GetLastError());
2961 XS(w32_SetLastError)
2965 Perl_croak(aTHX_ "usage: Win32::SetLastError($error)");
2966 SetLastError(SvIV(ST(0)));
2974 char *name = getlogin_buffer;
2975 DWORD size = sizeof(getlogin_buffer);
2977 if (GetUserName(name,&size)) {
2978 /* size includes NULL */
2979 ST(0) = sv_2mortal(newSVpvn(name,size-1));
2989 char name[MAX_COMPUTERNAME_LENGTH+1];
2990 DWORD size = sizeof(name);
2992 if (GetComputerName(name,&size)) {
2993 /* size does NOT include NULL :-( */
2994 ST(0) = sv_2mortal(newSVpvn(name,size));
3005 HINSTANCE hNetApi32 = LoadLibrary("netapi32.dll");
3006 DWORD (__stdcall *pfnNetApiBufferFree)(LPVOID Buffer);
3007 DWORD (__stdcall *pfnNetWkstaGetInfo)(LPWSTR servername, DWORD level,
3011 pfnNetApiBufferFree = (DWORD (__stdcall *)(void *))
3012 GetProcAddress(hNetApi32, "NetApiBufferFree");
3013 pfnNetWkstaGetInfo = (DWORD (__stdcall *)(LPWSTR, DWORD, void *))
3014 GetProcAddress(hNetApi32, "NetWkstaGetInfo");
3017 if (hNetApi32 && pfnNetWkstaGetInfo && pfnNetApiBufferFree) {
3018 /* this way is more reliable, in case user has a local account. */
3020 DWORD dnamelen = sizeof(dname);
3022 DWORD wki100_platform_id;
3023 LPWSTR wki100_computername;
3024 LPWSTR wki100_langroup;
3025 DWORD wki100_ver_major;
3026 DWORD wki100_ver_minor;
3028 /* NERR_Success *is* 0*/
3029 if (0 == pfnNetWkstaGetInfo(NULL, 100, &pwi)) {
3030 if (pwi->wki100_langroup && *(pwi->wki100_langroup)) {
3031 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_langroup,
3032 -1, (LPSTR)dname, dnamelen, NULL, NULL);
3035 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_computername,
3036 -1, (LPSTR)dname, dnamelen, NULL, NULL);
3038 pfnNetApiBufferFree(pwi);
3039 FreeLibrary(hNetApi32);
3042 FreeLibrary(hNetApi32);
3045 /* Win95 doesn't have NetWksta*(), so do it the old way */
3047 DWORD size = sizeof(name);
3049 FreeLibrary(hNetApi32);
3050 if (GetUserName(name,&size)) {
3052 DWORD sidlen = sizeof(sid);
3054 DWORD dnamelen = sizeof(dname);
3056 if (LookupAccountName(NULL, name, (PSID)&sid, &sidlen,
3057 dname, &dnamelen, &snu)) {
3058 XSRETURN_PV(dname); /* all that for this */
3070 DWORD flags, filecomplen;
3071 if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
3072 &flags, fsname, sizeof(fsname))) {
3073 if (GIMME_V == G_ARRAY) {
3074 XPUSHs(sv_2mortal(newSVpvn(fsname,strlen(fsname))));
3075 XPUSHs(sv_2mortal(newSViv(flags)));
3076 XPUSHs(sv_2mortal(newSViv(filecomplen)));
3081 XSRETURN_PV(fsname);
3087 XS(w32_GetOSVersion)
3090 OSVERSIONINFO osver;
3092 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
3093 if (GetVersionEx(&osver)) {
3094 XPUSHs(newSVpvn(osver.szCSDVersion, strlen(osver.szCSDVersion)));
3095 XPUSHs(newSViv(osver.dwMajorVersion));
3096 XPUSHs(newSViv(osver.dwMinorVersion));
3097 XPUSHs(newSViv(osver.dwBuildNumber));
3098 XPUSHs(newSViv(osver.dwPlatformId));
3110 XSRETURN_IV(IsWinNT());
3118 XSRETURN_IV(IsWin95());
3122 XS(w32_FormatMessage)
3129 Perl_croak(aTHX_ "usage: Win32::FormatMessage($errno)");
3131 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
3132 &source, SvIV(ST(0)), 0,
3133 msgbuf, sizeof(msgbuf)-1, NULL))
3134 XSRETURN_PV(msgbuf);
3144 PROCESS_INFORMATION stProcInfo;
3145 STARTUPINFO stStartInfo;
3146 BOOL bSuccess = FALSE;
3149 Perl_croak(aTHX_ "usage: Win32::Spawn($cmdName, $args, $PID)");
3151 cmd = SvPV_nolen(ST(0));
3152 args = SvPV_nolen(ST(1));
3154 memset(&stStartInfo, 0, sizeof(stStartInfo)); /* Clear the block */
3155 stStartInfo.cb = sizeof(stStartInfo); /* Set the structure size */
3156 stStartInfo.dwFlags = STARTF_USESHOWWINDOW; /* Enable wShowWindow control */
3157 stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE; /* Start min (normal) */
3160 cmd, /* Image path */
3161 args, /* Arguments for command line */
3162 NULL, /* Default process security */
3163 NULL, /* Default thread security */
3164 FALSE, /* Must be TRUE to use std handles */
3165 NORMAL_PRIORITY_CLASS, /* No special scheduling */
3166 NULL, /* Inherit our environment block */
3167 NULL, /* Inherit our currrent directory */
3168 &stStartInfo, /* -> Startup info */
3169 &stProcInfo)) /* <- Process info (if OK) */
3171 CloseHandle(stProcInfo.hThread);/* library source code does this. */
3172 sv_setiv(ST(2), stProcInfo.dwProcessId);
3175 XSRETURN_IV(bSuccess);
3179 XS(w32_GetTickCount)
3182 DWORD msec = GetTickCount();
3190 XS(w32_GetShortPathName)
3197 Perl_croak(aTHX_ "usage: Win32::GetShortPathName($longPathName)");
3199 shortpath = sv_mortalcopy(ST(0));
3200 SvUPGRADE(shortpath, SVt_PV);
3201 /* src == target is allowed */
3203 len = GetShortPathName(SvPVX(shortpath),
3206 } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
3208 SvCUR_set(shortpath,len);
3216 XS(w32_GetFullPathName)
3225 Perl_croak(aTHX_ "usage: Win32::GetFullPathName($filename)");
3228 fullpath = sv_mortalcopy(filename);
3229 SvUPGRADE(fullpath, SVt_PV);
3231 len = GetFullPathName(SvPVX(filename),
3235 } while (len >= SvLEN(fullpath) && sv_grow(fullpath,len+1));
3237 if (GIMME_V == G_ARRAY) {
3239 XST_mPV(1,filepart);
3240 len = filepart - SvPVX(fullpath);
3243 SvCUR_set(fullpath,len);
3251 XS(w32_GetLongPathName)
3255 char tmpbuf[MAX_PATH+1];
3260 Perl_croak(aTHX_ "usage: Win32::GetLongPathName($pathname)");
3263 pathstr = SvPV(path,len);
3264 strcpy(tmpbuf, pathstr);
3265 pathstr = win32_longpath(tmpbuf);
3267 ST(0) = sv_2mortal(newSVpvn(pathstr, strlen(pathstr)));
3278 Perl_croak(aTHX_ "usage: Win32::Sleep($milliseconds)");
3288 Perl_croak(aTHX_ "usage: Win32::CopyFile($from, $to, $overwrite)");
3289 if (CopyFile(SvPV_nolen(ST(0)), SvPV_nolen(ST(1)), !SvTRUE(ST(2))))
3295 Perl_init_os_extras(void)
3298 char *file = __FILE__;
3301 w32_perlshell_tokens = Nullch;
3302 w32_perlshell_items = -1;
3303 w32_fdpid = newAV(); /* XXX needs to be in Perl_win32_init()? */
3304 New(1313, w32_children, 1, child_tab);
3305 w32_num_children = 0;
3307 /* these names are Activeware compatible */
3308 newXS("Win32::GetCwd", w32_GetCwd, file);
3309 newXS("Win32::SetCwd", w32_SetCwd, file);
3310 newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
3311 newXS("Win32::GetLastError", w32_GetLastError, file);
3312 newXS("Win32::SetLastError", w32_SetLastError, file);
3313 newXS("Win32::LoginName", w32_LoginName, file);
3314 newXS("Win32::NodeName", w32_NodeName, file);
3315 newXS("Win32::DomainName", w32_DomainName, file);
3316 newXS("Win32::FsType", w32_FsType, file);
3317 newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
3318 newXS("Win32::IsWinNT", w32_IsWinNT, file);
3319 newXS("Win32::IsWin95", w32_IsWin95, file);
3320 newXS("Win32::FormatMessage", w32_FormatMessage, file);
3321 newXS("Win32::Spawn", w32_Spawn, file);
3322 newXS("Win32::GetTickCount", w32_GetTickCount, file);
3323 newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
3324 newXS("Win32::GetFullPathName", w32_GetFullPathName, file);
3325 newXS("Win32::GetLongPathName", w32_GetLongPathName, file);
3326 newXS("Win32::CopyFile", w32_CopyFile, file);
3327 newXS("Win32::Sleep", w32_Sleep, file);
3329 /* XXX Bloat Alert! The following Activeware preloads really
3330 * ought to be part of Win32::Sys::*, so they're not included
3333 /* LookupAccountName
3335 * InitiateSystemShutdown
3336 * AbortSystemShutdown
3337 * ExpandEnvrironmentStrings
3342 Perl_win32_init(int *argcp, char ***argvp)
3344 /* Disable floating point errors, Perl will trap the ones we
3345 * care about. VC++ RTL defaults to switching these off
3346 * already, but the Borland RTL doesn't. Since we don't
3347 * want to be at the vendor's whim on the default, we set
3348 * it explicitly here.
3350 #if !defined(_ALPHA_) && !defined(__GNUC__)
3351 _control87(MCW_EM, MCW_EM);
3356 #ifdef USE_BINMODE_SCRIPTS
3359 win32_strip_return(SV *sv)
3361 char *s = SvPVX(sv);
3362 char *e = s+SvCUR(sv);
3366 if (*s == '\r' && s[1] == '\n')
3376 SvCUR_set(sv,d-SvPVX(sv));