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.
10 #define PERLIO_NOT_STDIO 0
11 #define WIN32_LEAN_AND_MEAN
12 #define WIN32IO_IS_STDIO
18 #ifndef __MINGW32__ /* GCC/Mingw32-2.95.2 forgot the WINAPI on CommandLineToArgvW() */
19 # include <shellapi.h>
21 LPWSTR* WINAPI CommandLineToArgvW(LPCWSTR lpCommandLine, int * pNumArgs);
26 /* #include "config.h" */
28 #if !defined(PERLIO_IS_STDIO) && !defined(USE_SFIO)
37 #define PERL_NO_GET_CONTEXT
43 /* assert.h conflicts with #define of assert in perl.h */
50 #if defined(_MSC_VER) || defined(__MINGW32__)
51 #include <sys/utime.h>
56 /* Mingw32 defaults to globing command line
57 * So we turn it off like this:
62 #if defined(__MINGW32__)
63 /* Mingw32 is missing some prototypes */
64 FILE * _wfopen(LPCWSTR wszFileName, LPCWSTR wszMode);
65 FILE * _wfdopen(int nFd, LPCWSTR wszMode);
66 FILE * _freopen(LPCWSTR wszFileName, LPCWSTR wszMode, FILE * pOldStream);
71 #if defined(__BORLANDC__)
73 # define _utimbuf utimbuf
78 #define EXECF_SPAWN_NOWAIT 3
80 #if defined(PERL_IMPLICIT_SYS)
81 # undef win32_get_privlib
82 # define win32_get_privlib g_win32_get_privlib
83 # undef win32_get_sitelib
84 # define win32_get_sitelib g_win32_get_sitelib
85 # undef win32_get_vendorlib
86 # define win32_get_vendorlib g_win32_get_vendorlib
88 # define do_spawn g_do_spawn
90 # define getlogin g_getlogin
93 static void get_shell(void);
94 static long tokenize(const char *str, char **dest, char ***destv);
95 int do_spawn2(char *cmd, int exectype);
96 static BOOL has_shell_metachars(char *ptr);
97 static long filetime_to_clock(PFILETIME ft);
98 static BOOL filetime_from_time(PFILETIME ft, time_t t);
99 static char * get_emd_part(SV **leading, char *trailing, ...);
100 static void remove_dead_process(long deceased);
101 static long find_pid(int pid);
102 static char * qualified_path(const char *cmd);
103 static char * win32_get_xlib(const char *pl, const char *xlib,
104 const char *libname);
107 static void remove_dead_pseudo_process(long child);
108 static long find_pseudo_pid(int pid);
112 HANDLE w32_perldll_handle = INVALID_HANDLE_VALUE;
113 char w32_module_name[MAX_PATH+1];
116 static DWORD w32_platform = (DWORD)-1;
118 #define ONE_K_BUFSIZE 1024
123 return (win32_os_id() == VER_PLATFORM_WIN32_WINDOWS);
129 return (win32_os_id() == VER_PLATFORM_WIN32_NT);
133 set_w32_module_name(void)
136 GetModuleFileName((HMODULE)((w32_perldll_handle == INVALID_HANDLE_VALUE)
137 ? GetModuleHandle(NULL)
138 : w32_perldll_handle),
139 w32_module_name, sizeof(w32_module_name));
141 /* try to get full path to binary (which may be mangled when perl is
142 * run from a 16-bit app) */
143 /*PerlIO_printf(Perl_debug_log, "Before %s\n", w32_module_name);*/
144 (void)win32_longpath(w32_module_name);
145 /*PerlIO_printf(Perl_debug_log, "After %s\n", w32_module_name);*/
147 /* normalize to forward slashes */
148 ptr = w32_module_name;
156 /* *svp (if non-NULL) is expected to be POK (valid allocated SvPVX(*svp)) */
158 get_regstr_from(HKEY hkey, const char *valuename, SV **svp)
160 /* Retrieve a REG_SZ or REG_EXPAND_SZ from the registry */
163 const char *subkey = "Software\\Perl";
167 retval = RegOpenKeyEx(hkey, subkey, 0, KEY_READ, &handle);
168 if (retval == ERROR_SUCCESS) {
170 retval = RegQueryValueEx(handle, valuename, 0, &type, NULL, &datalen);
171 if (retval == ERROR_SUCCESS
172 && (type == REG_SZ || type == REG_EXPAND_SZ))
176 *svp = sv_2mortal(newSVpvn("",0));
177 SvGROW(*svp, datalen);
178 retval = RegQueryValueEx(handle, valuename, 0, NULL,
179 (PBYTE)SvPVX(*svp), &datalen);
180 if (retval == ERROR_SUCCESS) {
182 SvCUR_set(*svp,datalen-1);
190 /* *svp (if non-NULL) is expected to be POK (valid allocated SvPVX(*svp)) */
192 get_regstr(const char *valuename, SV **svp)
194 char *str = get_regstr_from(HKEY_CURRENT_USER, valuename, svp);
196 str = get_regstr_from(HKEY_LOCAL_MACHINE, valuename, svp);
200 /* *prev_pathp (if non-NULL) is expected to be POK (valid allocated SvPVX(sv)) */
202 get_emd_part(SV **prev_pathp, char *trailing_path, ...)
206 char mod_name[MAX_PATH+1];
210 int oldsize, newsize;
213 va_start(ap, trailing_path);
214 strip = va_arg(ap, char *);
216 sprintf(base, "%d.%d", (int)PERL_REVISION, (int)PERL_VERSION);
217 baselen = strlen(base);
219 if (!*w32_module_name) {
220 set_w32_module_name();
222 strcpy(mod_name, w32_module_name);
223 ptr = strrchr(mod_name, '/');
224 while (ptr && strip) {
225 /* look for directories to skip back */
228 ptr = strrchr(mod_name, '/');
229 /* avoid stripping component if there is no slash,
230 * or it doesn't match ... */
231 if (!ptr || stricmp(ptr+1, strip) != 0) {
232 /* ... but not if component matches m|5\.$patchlevel.*| */
233 if (!ptr || !(*strip == '5' && *(ptr+1) == '5'
234 && strncmp(strip, base, baselen) == 0
235 && strncmp(ptr+1, base, baselen) == 0))
241 strip = va_arg(ap, char *);
249 strcpy(++ptr, trailing_path);
251 /* only add directory if it exists */
252 if (GetFileAttributes(mod_name) != (DWORD) -1) {
253 /* directory exists */
256 *prev_pathp = sv_2mortal(newSVpvn("",0));
257 sv_catpvn(*prev_pathp, ";", 1);
258 sv_catpv(*prev_pathp, mod_name);
259 return SvPVX(*prev_pathp);
266 win32_get_privlib(const char *pl)
269 char *stdlib = "lib";
270 char buffer[MAX_PATH+1];
273 /* $stdlib = $HKCU{"lib-$]"} || $HKLM{"lib-$]"} || $HKCU{"lib"} || $HKLM{"lib"} || ""; */
274 sprintf(buffer, "%s-%s", stdlib, pl);
275 if (!get_regstr(buffer, &sv))
276 (void)get_regstr(stdlib, &sv);
278 /* $stdlib .= ";$EMD/../../lib" */
279 return get_emd_part(&sv, stdlib, ARCHNAME, "bin", Nullch);
283 win32_get_xlib(const char *pl, const char *xlib, const char *libname)
287 char pathstr[MAX_PATH+1];
293 /* $HKCU{"$xlib-$]"} || $HKLM{"$xlib-$]"} . ---; */
294 sprintf(regstr, "%s-%s", xlib, pl);
295 (void)get_regstr(regstr, &sv1);
298 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/$libname/$]/lib"; */
299 sprintf(pathstr, "%s/%s/lib", libname, pl);
300 (void)get_emd_part(&sv1, pathstr, ARCHNAME, "bin", pl, Nullch);
302 /* $HKCU{$xlib} || $HKLM{$xlib} . ---; */
303 (void)get_regstr(xlib, &sv2);
306 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/$libname/lib"; */
307 sprintf(pathstr, "%s/lib", libname);
308 (void)get_emd_part(&sv2, pathstr, ARCHNAME, "bin", pl, Nullch);
317 sv_catpvn(sv1, ";", 1);
324 win32_get_sitelib(const char *pl)
326 return win32_get_xlib(pl, "sitelib", "site");
329 #ifndef PERL_VENDORLIB_NAME
330 # define PERL_VENDORLIB_NAME "vendor"
334 win32_get_vendorlib(const char *pl)
336 return win32_get_xlib(pl, "vendorlib", PERL_VENDORLIB_NAME);
340 has_shell_metachars(char *ptr)
346 * Scan string looking for redirection (< or >) or pipe
347 * characters (|) that are not in a quoted string.
348 * Shell variable interpolation (%VAR%) can also happen inside strings.
380 #if !defined(PERL_IMPLICIT_SYS)
381 /* since the current process environment is being updated in util.c
382 * the library functions will get the correct environment
385 Perl_my_popen(pTHX_ char *cmd, char *mode)
388 #define fixcmd(x) { \
389 char *pspace = strchr((x),' '); \
392 while (p < pspace) { \
403 PERL_FLUSHALL_FOR_CHILD;
404 return win32_popen(cmd, mode);
408 Perl_my_pclose(pTHX_ PerlIO *fp)
410 return win32_pclose(fp);
414 DllExport unsigned long
417 static OSVERSIONINFO osver;
419 if (osver.dwPlatformId != w32_platform) {
420 memset(&osver, 0, sizeof(OSVERSIONINFO));
421 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
422 GetVersionEx(&osver);
423 w32_platform = osver.dwPlatformId;
425 return (unsigned long)w32_platform;
435 return -((int)w32_pseudo_id);
438 /* Windows 9x appears to always reports a pid for threads and processes
439 * that has the high bit set. So we treat the lower 31 bits as the
440 * "real" PID for Perl's purposes. */
441 if (IsWin95() && pid < 0)
446 /* Tokenize a string. Words are null-separated, and the list
447 * ends with a doubled null. Any character (except null and
448 * including backslash) may be escaped by preceding it with a
449 * backslash (the backslash will be stripped).
450 * Returns number of words in result buffer.
453 tokenize(const char *str, char **dest, char ***destv)
455 char *retstart = Nullch;
456 char **retvstart = 0;
460 int slen = strlen(str);
462 register char **retv;
463 New(1307, ret, slen+2, char);
464 New(1308, retv, (slen+3)/2, char*);
472 if (*ret == '\\' && *str)
474 else if (*ret == ' ') {
490 retvstart[items] = Nullch;
503 if (!w32_perlshell_tokens) {
504 /* we don't use COMSPEC here for two reasons:
505 * 1. the same reason perl on UNIX doesn't use SHELL--rampant and
506 * uncontrolled unportability of the ensuing scripts.
507 * 2. PERL5SHELL could be set to a shell that may not be fit for
508 * interactive use (which is what most programs look in COMSPEC
511 const char* defaultshell = (IsWinNT()
512 ? "cmd.exe /x/c" : "command.com /c");
513 const char *usershell = PerlEnv_getenv("PERL5SHELL");
514 w32_perlshell_items = tokenize(usershell ? usershell : defaultshell,
515 &w32_perlshell_tokens,
521 do_aspawn(void *vreally, void **vmark, void **vsp)
524 SV *really = (SV*)vreally;
525 SV **mark = (SV**)vmark;
537 New(1306, argv, (sp - mark) + w32_perlshell_items + 2, char*);
539 if (SvNIOKp(*(mark+1)) && !SvPOKp(*(mark+1))) {
544 while (++mark <= sp) {
545 if (*mark && (str = SvPV_nolen(*mark)))
552 status = win32_spawnvp(flag,
553 (const char*)(really ? SvPV_nolen(really) : argv[0]),
554 (const char* const*)argv);
556 if (status < 0 && (errno == ENOEXEC || errno == ENOENT)) {
557 /* possible shell-builtin, invoke with shell */
559 sh_items = w32_perlshell_items;
561 argv[index+sh_items] = argv[index];
562 while (--sh_items >= 0)
563 argv[sh_items] = w32_perlshell_vec[sh_items];
565 status = win32_spawnvp(flag,
566 (const char*)(really ? SvPV_nolen(really) : argv[0]),
567 (const char* const*)argv);
570 if (flag == P_NOWAIT) {
572 PL_statusvalue = -1; /* >16bits hint for pp_system() */
576 if (ckWARN(WARN_EXEC))
577 Perl_warner(aTHX_ WARN_EXEC, "Can't spawn \"%s\": %s", argv[0], strerror(errno));
582 PL_statusvalue = status;
588 /* returns pointer to the next unquoted space or the end of the string */
590 find_next_space(const char *s)
592 bool in_quotes = FALSE;
594 /* ignore doubled backslashes, or backslash+quote */
595 if (*s == '\\' && (s[1] == '\\' || s[1] == '"')) {
598 /* keep track of when we're within quotes */
599 else if (*s == '"') {
601 in_quotes = !in_quotes;
603 /* break it up only at spaces that aren't in quotes */
604 else if (!in_quotes && isSPACE(*s))
613 do_spawn2(char *cmd, int exectype)
620 BOOL needToTry = TRUE;
623 /* Save an extra exec if possible. See if there are shell
624 * metacharacters in it */
625 if (!has_shell_metachars(cmd)) {
626 New(1301,argv, strlen(cmd) / 2 + 2, char*);
627 New(1302,cmd2, strlen(cmd) + 1, char);
630 for (s = cmd2; *s;) {
631 while (*s && isSPACE(*s))
635 s = find_next_space(s);
643 status = win32_spawnvp(P_WAIT, argv[0],
644 (const char* const*)argv);
646 case EXECF_SPAWN_NOWAIT:
647 status = win32_spawnvp(P_NOWAIT, argv[0],
648 (const char* const*)argv);
651 status = win32_execvp(argv[0], (const char* const*)argv);
654 if (status != -1 || errno == 0)
664 New(1306, argv, w32_perlshell_items + 2, char*);
665 while (++i < w32_perlshell_items)
666 argv[i] = w32_perlshell_vec[i];
671 status = win32_spawnvp(P_WAIT, argv[0],
672 (const char* const*)argv);
674 case EXECF_SPAWN_NOWAIT:
675 status = win32_spawnvp(P_NOWAIT, argv[0],
676 (const char* const*)argv);
679 status = win32_execvp(argv[0], (const char* const*)argv);
685 if (exectype == EXECF_SPAWN_NOWAIT) {
687 PL_statusvalue = -1; /* >16bits hint for pp_system() */
691 if (ckWARN(WARN_EXEC))
692 Perl_warner(aTHX_ WARN_EXEC, "Can't %s \"%s\": %s",
693 (exectype == EXECF_EXEC ? "exec" : "spawn"),
694 cmd, strerror(errno));
699 PL_statusvalue = status;
707 return do_spawn2(cmd, EXECF_SPAWN);
711 do_spawn_nowait(char *cmd)
713 return do_spawn2(cmd, EXECF_SPAWN_NOWAIT);
717 Perl_do_exec(pTHX_ char *cmd)
719 do_spawn2(cmd, EXECF_EXEC);
723 /* The idea here is to read all the directory names into a string table
724 * (separated by nulls) and when one of the other dir functions is called
725 * return the pointer to the current file name.
728 win32_opendir(char *filename)
734 char scanname[MAX_PATH+3];
736 WIN32_FIND_DATAA aFindData;
737 WIN32_FIND_DATAW wFindData;
739 char buffer[MAX_PATH*2];
740 WCHAR wbuffer[MAX_PATH+1];
743 len = strlen(filename);
747 /* check to see if filename is a directory */
748 if (win32_stat(filename, &sbuf) < 0 || !S_ISDIR(sbuf.st_mode))
751 /* Get us a DIR structure */
752 Newz(1303, dirp, 1, DIR);
754 /* Create the search pattern */
755 strcpy(scanname, filename);
757 /* bare drive name means look in cwd for drive */
758 if (len == 2 && isALPHA(scanname[0]) && scanname[1] == ':') {
759 scanname[len++] = '.';
760 scanname[len++] = '/';
762 else if (scanname[len-1] != '/' && scanname[len-1] != '\\') {
763 scanname[len++] = '/';
765 scanname[len++] = '*';
766 scanname[len] = '\0';
768 /* do the FindFirstFile call */
770 A2WHELPER(scanname, wbuffer, sizeof(wbuffer));
771 fh = FindFirstFileW(PerlDir_mapW(wbuffer), &wFindData);
774 fh = FindFirstFileA(PerlDir_mapA(scanname), &aFindData);
777 if (fh == INVALID_HANDLE_VALUE) {
778 DWORD err = GetLastError();
779 /* FindFirstFile() fails on empty drives! */
781 case ERROR_FILE_NOT_FOUND:
783 case ERROR_NO_MORE_FILES:
784 case ERROR_PATH_NOT_FOUND:
787 case ERROR_NOT_ENOUGH_MEMORY:
798 /* now allocate the first part of the string table for
799 * the filenames that we find.
802 W2AHELPER(wFindData.cFileName, buffer, sizeof(buffer));
806 ptr = aFindData.cFileName;
813 New(1304, dirp->start, dirp->size, char);
814 strcpy(dirp->start, ptr);
816 dirp->end = dirp->curr = dirp->start;
822 /* Readdir just returns the current string pointer and bumps the
823 * string pointer to the nDllExport entry.
825 DllExport struct direct *
826 win32_readdir(DIR *dirp)
831 /* first set up the structure to return */
832 len = strlen(dirp->curr);
833 strcpy(dirp->dirstr.d_name, dirp->curr);
834 dirp->dirstr.d_namlen = len;
837 dirp->dirstr.d_ino = dirp->curr - dirp->start;
839 /* Now set up for the next call to readdir */
840 dirp->curr += len + 1;
841 if (dirp->curr >= dirp->end) {
845 WIN32_FIND_DATAW wFindData;
846 WIN32_FIND_DATAA aFindData;
847 char buffer[MAX_PATH*2];
849 /* finding the next file that matches the wildcard
850 * (which should be all of them in this directory!).
853 res = FindNextFileW(dirp->handle, &wFindData);
855 W2AHELPER(wFindData.cFileName, buffer, sizeof(buffer));
860 res = FindNextFileA(dirp->handle, &aFindData);
862 ptr = aFindData.cFileName;
865 long endpos = dirp->end - dirp->start;
866 long newsize = endpos + strlen(ptr) + 1;
867 /* bump the string table size by enough for the
868 * new name and its null terminator */
869 while (newsize > dirp->size) {
870 long curpos = dirp->curr - dirp->start;
872 Renew(dirp->start, dirp->size, char);
873 dirp->curr = dirp->start + curpos;
875 strcpy(dirp->start + endpos, ptr);
876 dirp->end = dirp->start + newsize;
882 return &(dirp->dirstr);
888 /* Telldir returns the current string pointer position */
890 win32_telldir(DIR *dirp)
892 return (dirp->curr - dirp->start);
896 /* Seekdir moves the string pointer to a previously saved position
897 * (returned by telldir).
900 win32_seekdir(DIR *dirp, long loc)
902 dirp->curr = dirp->start + loc;
905 /* Rewinddir resets the string pointer to the start */
907 win32_rewinddir(DIR *dirp)
909 dirp->curr = dirp->start;
912 /* free the memory allocated by opendir */
914 win32_closedir(DIR *dirp)
917 if (dirp->handle != INVALID_HANDLE_VALUE)
918 FindClose(dirp->handle);
919 Safefree(dirp->start);
932 * Just pretend that everyone is a superuser. NT will let us know if
933 * we don\'t really have permission to do something.
936 #define ROOT_UID ((uid_t)0)
937 #define ROOT_GID ((gid_t)0)
966 return (auid == ROOT_UID ? 0 : -1);
972 return (agid == ROOT_GID ? 0 : -1);
979 char *buf = w32_getlogin_buffer;
980 DWORD size = sizeof(w32_getlogin_buffer);
981 if (GetUserName(buf,&size))
987 chown(const char *path, uid_t owner, gid_t group)
994 * XXX this needs strengthening (for PerlIO)
997 int mkstemp(const char *path)
1000 char buf[MAX_PATH+1];
1004 if (i++ > 10) { /* give up */
1008 if (!GetTempFileNameA((LPCSTR)path, "plr", 1, buf)) {
1012 fd = PerlLIO_open3(buf, O_CREAT|O_RDWR|O_EXCL, 0600);
1022 long child = w32_num_children;
1023 while (--child >= 0) {
1024 if (w32_child_pids[child] == pid)
1031 remove_dead_process(long child)
1035 CloseHandle(w32_child_handles[child]);
1036 Move(&w32_child_handles[child+1], &w32_child_handles[child],
1037 (w32_num_children-child-1), HANDLE);
1038 Move(&w32_child_pids[child+1], &w32_child_pids[child],
1039 (w32_num_children-child-1), DWORD);
1046 find_pseudo_pid(int pid)
1049 long child = w32_num_pseudo_children;
1050 while (--child >= 0) {
1051 if (w32_pseudo_child_pids[child] == pid)
1058 remove_dead_pseudo_process(long child)
1062 CloseHandle(w32_pseudo_child_handles[child]);
1063 Move(&w32_pseudo_child_handles[child+1], &w32_pseudo_child_handles[child],
1064 (w32_num_pseudo_children-child-1), HANDLE);
1065 Move(&w32_pseudo_child_pids[child+1], &w32_pseudo_child_pids[child],
1066 (w32_num_pseudo_children-child-1), DWORD);
1067 w32_num_pseudo_children--;
1073 win32_kill(int pid, int sig)
1080 /* it is a pseudo-forked child */
1081 child = find_pseudo_pid(-pid);
1085 hProcess = w32_pseudo_child_handles[child];
1086 if (TerminateThread(hProcess, sig)) {
1087 remove_dead_pseudo_process(child);
1091 else if (IsWin95()) {
1099 child = find_pid(pid);
1103 hProcess = w32_child_handles[child];
1104 if (TerminateProcess(hProcess, sig)) {
1105 remove_dead_process(child);
1111 hProcess = OpenProcess(PROCESS_ALL_ACCESS, TRUE,
1112 (IsWin95() ? -pid : pid));
1116 if (TerminateProcess(hProcess, sig)) {
1117 CloseHandle(hProcess);
1131 DllExport unsigned int
1132 win32_sleep(unsigned int t)
1139 win32_stat(const char *path, struct stat *sbuf)
1142 char buffer[MAX_PATH+1];
1143 int l = strlen(path);
1145 WCHAR wbuffer[MAX_PATH+1];
1151 switch(path[l - 1]) {
1152 /* FindFirstFile() and stat() are buggy with a trailing
1153 * backslash, so change it to a forward slash :-( */
1155 strncpy(buffer, path, l-1);
1156 buffer[l - 1] = '/';
1160 /* FindFirstFile() is buggy with "x:", so add a dot :-( */
1162 if (l == 2 && isALPHA(path[0])) {
1163 buffer[0] = path[0];
1174 /* We *must* open & close the file once; otherwise file attribute changes */
1175 /* might not yet have propagated to "other" hard links of the same file. */
1176 /* This also gives us an opportunity to determine the number of links. */
1178 A2WHELPER(path, wbuffer, sizeof(wbuffer));
1179 pwbuffer = PerlDir_mapW(wbuffer);
1180 handle = CreateFileW(pwbuffer, 0, 0, NULL, OPEN_EXISTING, 0, NULL);
1183 path = PerlDir_mapA(path);
1185 handle = CreateFileA(path, 0, 0, NULL, OPEN_EXISTING, 0, NULL);
1187 if (handle != INVALID_HANDLE_VALUE) {
1188 BY_HANDLE_FILE_INFORMATION bhi;
1189 if (GetFileInformationByHandle(handle, &bhi))
1190 nlink = bhi.nNumberOfLinks;
1191 CloseHandle(handle);
1194 /* pwbuffer or path will be mapped correctly above */
1196 res = _wstat(pwbuffer, (struct _stat *)sbuf);
1199 res = stat(path, sbuf);
1201 sbuf->st_nlink = nlink;
1204 /* CRT is buggy on sharenames, so make sure it really isn't.
1205 * XXX using GetFileAttributesEx() will enable us to set
1206 * sbuf->st_*time (but note that's not available on the
1207 * Windows of 1995) */
1210 r = GetFileAttributesW(pwbuffer);
1213 r = GetFileAttributesA(path);
1215 if (r != 0xffffffff && (r & FILE_ATTRIBUTE_DIRECTORY)) {
1216 /* sbuf may still contain old garbage since stat() failed */
1217 Zero(sbuf, 1, struct stat);
1218 sbuf->st_mode = S_IFDIR | S_IREAD;
1220 if (!(r & FILE_ATTRIBUTE_READONLY))
1221 sbuf->st_mode |= S_IWRITE | S_IEXEC;
1226 if (l == 3 && isALPHA(path[0]) && path[1] == ':'
1227 && (path[2] == '\\' || path[2] == '/'))
1229 /* The drive can be inaccessible, some _stat()s are buggy */
1231 ? !GetVolumeInformationW(pwbuffer,NULL,0,NULL,NULL,NULL,NULL,0)
1232 : !GetVolumeInformationA(path,NULL,0,NULL,NULL,NULL,NULL,0)) {
1238 if (S_ISDIR(sbuf->st_mode))
1239 sbuf->st_mode |= S_IWRITE | S_IEXEC;
1240 else if (S_ISREG(sbuf->st_mode)) {
1242 if (l >= 4 && path[l-4] == '.') {
1243 const char *e = path + l - 3;
1244 if (strnicmp(e,"exe",3)
1245 && strnicmp(e,"bat",3)
1246 && strnicmp(e,"com",3)
1247 && (IsWin95() || strnicmp(e,"cmd",3)))
1248 sbuf->st_mode &= ~S_IEXEC;
1250 sbuf->st_mode |= S_IEXEC;
1253 sbuf->st_mode &= ~S_IEXEC;
1254 /* Propagate permissions to _group_ and _others_ */
1255 perms = sbuf->st_mode & (S_IREAD|S_IWRITE|S_IEXEC);
1256 sbuf->st_mode |= (perms>>3) | (perms>>6);
1263 /* Find the longname of a given path. path is destructively modified.
1264 * It should have space for at least MAX_PATH characters. */
1266 win32_longpath(char *path)
1268 WIN32_FIND_DATA fdata;
1270 char tmpbuf[MAX_PATH+1];
1271 char *tmpstart = tmpbuf;
1278 if (isALPHA(path[0]) && path[1] == ':' &&
1279 (path[2] == '/' || path[2] == '\\'))
1282 *tmpstart++ = path[0];
1286 else if ((path[0] == '/' || path[0] == '\\') &&
1287 (path[1] == '/' || path[1] == '\\'))
1290 *tmpstart++ = path[0];
1291 *tmpstart++ = path[1];
1292 /* copy machine name */
1293 while (*start && *start != '/' && *start != '\\')
1294 *tmpstart++ = *start++;
1296 *tmpstart++ = *start;
1298 /* copy share name */
1299 while (*start && *start != '/' && *start != '\\')
1300 *tmpstart++ = *start++;
1304 if (sep == '/' || sep == '\\')
1308 /* walk up to slash */
1309 while (*start && *start != '/' && *start != '\\')
1312 /* discard doubled slashes */
1313 while (*start && (start[1] == '/' || start[1] == '\\'))
1317 /* stop and find full name of component */
1319 fhand = FindFirstFile(path,&fdata);
1320 if (fhand != INVALID_HANDLE_VALUE) {
1321 strcpy(tmpstart, fdata.cFileName);
1322 tmpstart += strlen(fdata.cFileName);
1330 /* failed a step, just return without side effects */
1331 /*PerlIO_printf(Perl_debug_log, "Failed to find %s\n", path);*/
1336 strcpy(path,tmpbuf);
1341 win32_getenv(const char *name)
1344 WCHAR wBuffer[MAX_PATH+1];
1346 SV *curitem = Nullsv;
1349 A2WHELPER(name, wBuffer, sizeof(wBuffer));
1350 needlen = GetEnvironmentVariableW(wBuffer, NULL, 0);
1353 needlen = GetEnvironmentVariableA(name,NULL,0);
1355 curitem = sv_2mortal(newSVpvn("", 0));
1359 SvGROW(curitem, (needlen+1)*sizeof(WCHAR));
1360 needlen = GetEnvironmentVariableW(wBuffer,
1361 (WCHAR*)SvPVX(curitem),
1363 } while (needlen >= SvLEN(curitem)/sizeof(WCHAR));
1364 SvCUR_set(curitem, (needlen*sizeof(WCHAR))+1);
1365 acuritem = sv_2mortal(newSVsv(curitem));
1366 W2AHELPER((WCHAR*)SvPVX(acuritem), SvPVX(curitem), SvCUR(curitem));
1370 SvGROW(curitem, needlen+1);
1371 needlen = GetEnvironmentVariableA(name,SvPVX(curitem),
1373 } while (needlen >= SvLEN(curitem));
1374 SvCUR_set(curitem, needlen);
1378 /* allow any environment variables that begin with 'PERL'
1379 to be stored in the registry */
1380 if (strncmp(name, "PERL", 4) == 0)
1381 (void)get_regstr(name, &curitem);
1383 if (curitem && SvCUR(curitem))
1384 return SvPVX(curitem);
1390 win32_putenv(const char *name)
1397 int length, relval = -1;
1401 length = strlen(name)+1;
1402 New(1309,wCuritem,length,WCHAR);
1403 A2WHELPER(name, wCuritem, length*sizeof(WCHAR));
1404 wVal = wcschr(wCuritem, '=');
1407 if (SetEnvironmentVariableW(wCuritem, *wVal ? wVal : NULL))
1413 New(1309,curitem,strlen(name)+1,char);
1414 strcpy(curitem, name);
1415 val = strchr(curitem, '=');
1417 /* The sane way to deal with the environment.
1418 * Has these advantages over putenv() & co.:
1419 * * enables us to store a truly empty value in the
1420 * environment (like in UNIX).
1421 * * we don't have to deal with RTL globals, bugs and leaks.
1423 * Why you may want to enable USE_WIN32_RTL_ENV:
1424 * * environ[] and RTL functions will not reflect changes,
1425 * which might be an issue if extensions want to access
1426 * the env. via RTL. This cuts both ways, since RTL will
1427 * not see changes made by extensions that call the Win32
1428 * functions directly, either.
1432 if (SetEnvironmentVariableA(curitem, *val ? val : NULL))
1442 filetime_to_clock(PFILETIME ft)
1444 __int64 qw = ft->dwHighDateTime;
1446 qw |= ft->dwLowDateTime;
1447 qw /= 10000; /* File time ticks at 0.1uS, clock at 1mS */
1452 win32_times(struct tms *timebuf)
1457 if (GetProcessTimes(GetCurrentProcess(), &dummy, &dummy,
1459 timebuf->tms_utime = filetime_to_clock(&user);
1460 timebuf->tms_stime = filetime_to_clock(&kernel);
1461 timebuf->tms_cutime = 0;
1462 timebuf->tms_cstime = 0;
1465 /* That failed - e.g. Win95 fallback to clock() */
1466 clock_t t = clock();
1467 timebuf->tms_utime = t;
1468 timebuf->tms_stime = 0;
1469 timebuf->tms_cutime = 0;
1470 timebuf->tms_cstime = 0;
1475 /* fix utime() so it works on directories in NT */
1477 filetime_from_time(PFILETIME pFileTime, time_t Time)
1479 struct tm *pTM = localtime(&Time);
1480 SYSTEMTIME SystemTime;
1486 SystemTime.wYear = pTM->tm_year + 1900;
1487 SystemTime.wMonth = pTM->tm_mon + 1;
1488 SystemTime.wDay = pTM->tm_mday;
1489 SystemTime.wHour = pTM->tm_hour;
1490 SystemTime.wMinute = pTM->tm_min;
1491 SystemTime.wSecond = pTM->tm_sec;
1492 SystemTime.wMilliseconds = 0;
1494 return SystemTimeToFileTime(&SystemTime, &LocalTime) &&
1495 LocalFileTimeToFileTime(&LocalTime, pFileTime);
1499 win32_unlink(const char *filename)
1506 WCHAR wBuffer[MAX_PATH+1];
1509 A2WHELPER(filename, wBuffer, sizeof(wBuffer));
1510 pwBuffer = PerlDir_mapW(wBuffer);
1511 attrs = GetFileAttributesW(pwBuffer);
1512 if (attrs == 0xFFFFFFFF)
1514 if (attrs & FILE_ATTRIBUTE_READONLY) {
1515 (void)SetFileAttributesW(pwBuffer, attrs & ~FILE_ATTRIBUTE_READONLY);
1516 ret = _wunlink(pwBuffer);
1518 (void)SetFileAttributesW(pwBuffer, attrs);
1521 ret = _wunlink(pwBuffer);
1524 filename = PerlDir_mapA(filename);
1525 attrs = GetFileAttributesA(filename);
1526 if (attrs == 0xFFFFFFFF)
1528 if (attrs & FILE_ATTRIBUTE_READONLY) {
1529 (void)SetFileAttributesA(filename, attrs & ~FILE_ATTRIBUTE_READONLY);
1530 ret = unlink(filename);
1532 (void)SetFileAttributesA(filename, attrs);
1535 ret = unlink(filename);
1544 win32_utime(const char *filename, struct utimbuf *times)
1551 struct utimbuf TimeBuffer;
1552 WCHAR wbuffer[MAX_PATH+1];
1557 A2WHELPER(filename, wbuffer, sizeof(wbuffer));
1558 pwbuffer = PerlDir_mapW(wbuffer);
1559 rc = _wutime(pwbuffer, (struct _utimbuf*)times);
1562 filename = PerlDir_mapA(filename);
1563 rc = utime(filename, times);
1565 /* EACCES: path specifies directory or readonly file */
1566 if (rc == 0 || errno != EACCES /* || !IsWinNT() */)
1569 if (times == NULL) {
1570 times = &TimeBuffer;
1571 time(×->actime);
1572 times->modtime = times->actime;
1575 /* This will (and should) still fail on readonly files */
1577 handle = CreateFileW(pwbuffer, GENERIC_READ | GENERIC_WRITE,
1578 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1579 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1582 handle = CreateFileA(filename, GENERIC_READ | GENERIC_WRITE,
1583 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1584 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1586 if (handle == INVALID_HANDLE_VALUE)
1589 if (GetFileTime(handle, &ftCreate, &ftAccess, &ftWrite) &&
1590 filetime_from_time(&ftAccess, times->actime) &&
1591 filetime_from_time(&ftWrite, times->modtime) &&
1592 SetFileTime(handle, &ftCreate, &ftAccess, &ftWrite))
1597 CloseHandle(handle);
1602 win32_uname(struct utsname *name)
1604 struct hostent *hep;
1605 STRLEN nodemax = sizeof(name->nodename)-1;
1606 OSVERSIONINFO osver;
1608 memset(&osver, 0, sizeof(OSVERSIONINFO));
1609 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1610 if (GetVersionEx(&osver)) {
1612 switch (osver.dwPlatformId) {
1613 case VER_PLATFORM_WIN32_WINDOWS:
1614 strcpy(name->sysname, "Windows");
1616 case VER_PLATFORM_WIN32_NT:
1617 strcpy(name->sysname, "Windows NT");
1619 case VER_PLATFORM_WIN32s:
1620 strcpy(name->sysname, "Win32s");
1623 strcpy(name->sysname, "Win32 Unknown");
1628 sprintf(name->release, "%d.%d",
1629 osver.dwMajorVersion, osver.dwMinorVersion);
1632 sprintf(name->version, "Build %d",
1633 osver.dwPlatformId == VER_PLATFORM_WIN32_NT
1634 ? osver.dwBuildNumber : (osver.dwBuildNumber & 0xffff));
1635 if (osver.szCSDVersion[0]) {
1636 char *buf = name->version + strlen(name->version);
1637 sprintf(buf, " (%s)", osver.szCSDVersion);
1641 *name->sysname = '\0';
1642 *name->version = '\0';
1643 *name->release = '\0';
1647 hep = win32_gethostbyname("localhost");
1649 STRLEN len = strlen(hep->h_name);
1650 if (len <= nodemax) {
1651 strcpy(name->nodename, hep->h_name);
1654 strncpy(name->nodename, hep->h_name, nodemax);
1655 name->nodename[nodemax] = '\0';
1660 if (!GetComputerName(name->nodename, &sz))
1661 *name->nodename = '\0';
1664 /* machine (architecture) */
1668 GetSystemInfo(&info);
1670 #if (defined(__BORLANDC__)&&(__BORLANDC__<=0x520)) \
1671 || (defined(__MINGW32__) && !defined(_ANONYMOUS_UNION))
1672 switch (info.u.s.wProcessorArchitecture) {
1674 switch (info.wProcessorArchitecture) {
1676 case PROCESSOR_ARCHITECTURE_INTEL:
1677 arch = "x86"; break;
1678 case PROCESSOR_ARCHITECTURE_MIPS:
1679 arch = "mips"; break;
1680 case PROCESSOR_ARCHITECTURE_ALPHA:
1681 arch = "alpha"; break;
1682 case PROCESSOR_ARCHITECTURE_PPC:
1683 arch = "ppc"; break;
1685 arch = "unknown"; break;
1687 strcpy(name->machine, arch);
1693 win32_internal_wait(int *status, DWORD timeout)
1695 /* XXX this wait emulation only knows about processes
1696 * spawned via win32_spawnvp(P_NOWAIT, ...).
1700 DWORD exitcode, waitcode;
1703 if (w32_num_pseudo_children) {
1704 waitcode = WaitForMultipleObjects(w32_num_pseudo_children,
1705 w32_pseudo_child_handles,
1708 /* Time out here if there are no other children to wait for. */
1709 if (waitcode == WAIT_TIMEOUT) {
1710 if (!w32_num_children) {
1714 else if (waitcode != WAIT_FAILED) {
1715 if (waitcode >= WAIT_ABANDONED_0
1716 && waitcode < WAIT_ABANDONED_0 + w32_num_pseudo_children)
1717 i = waitcode - WAIT_ABANDONED_0;
1719 i = waitcode - WAIT_OBJECT_0;
1720 if (GetExitCodeThread(w32_pseudo_child_handles[i], &exitcode)) {
1721 *status = (int)((exitcode & 0xff) << 8);
1722 retval = (int)w32_pseudo_child_pids[i];
1723 remove_dead_pseudo_process(i);
1730 if (!w32_num_children) {
1735 /* if a child exists, wait for it to die */
1736 waitcode = WaitForMultipleObjects(w32_num_children,
1740 if (waitcode == WAIT_TIMEOUT) {
1743 if (waitcode != WAIT_FAILED) {
1744 if (waitcode >= WAIT_ABANDONED_0
1745 && waitcode < WAIT_ABANDONED_0 + w32_num_children)
1746 i = waitcode - WAIT_ABANDONED_0;
1748 i = waitcode - WAIT_OBJECT_0;
1749 if (GetExitCodeProcess(w32_child_handles[i], &exitcode) ) {
1750 *status = (int)((exitcode & 0xff) << 8);
1751 retval = (int)w32_child_pids[i];
1752 remove_dead_process(i);
1758 errno = GetLastError();
1763 win32_waitpid(int pid, int *status, int flags)
1766 DWORD timeout = (flags & WNOHANG) ? 0 : INFINITE;
1769 if (pid == -1) /* XXX threadid == 1 ? */
1770 return win32_internal_wait(status, timeout);
1773 child = find_pseudo_pid(-pid);
1775 HANDLE hThread = w32_pseudo_child_handles[child];
1776 DWORD waitcode = WaitForSingleObject(hThread, timeout);
1777 if (waitcode == WAIT_TIMEOUT) {
1780 else if (waitcode != WAIT_FAILED) {
1781 if (GetExitCodeThread(hThread, &waitcode)) {
1782 *status = (int)((waitcode & 0xff) << 8);
1783 retval = (int)w32_pseudo_child_pids[child];
1784 remove_dead_pseudo_process(child);
1791 else if (IsWin95()) {
1800 child = find_pid(pid);
1802 hProcess = w32_child_handles[child];
1803 waitcode = WaitForSingleObject(hProcess, timeout);
1804 if (waitcode == WAIT_TIMEOUT) {
1807 else if (waitcode != WAIT_FAILED) {
1808 if (GetExitCodeProcess(hProcess, &waitcode)) {
1809 *status = (int)((waitcode & 0xff) << 8);
1810 retval = (int)w32_child_pids[child];
1811 remove_dead_process(child);
1820 hProcess = OpenProcess(PROCESS_ALL_ACCESS, TRUE,
1821 (IsWin95() ? -pid : pid));
1823 waitcode = WaitForSingleObject(hProcess, timeout);
1824 if (waitcode == WAIT_TIMEOUT) {
1827 else if (waitcode != WAIT_FAILED) {
1828 if (GetExitCodeProcess(hProcess, &waitcode)) {
1829 *status = (int)((waitcode & 0xff) << 8);
1830 CloseHandle(hProcess);
1834 CloseHandle(hProcess);
1840 return retval >= 0 ? pid : retval;
1844 win32_wait(int *status)
1846 return win32_internal_wait(status, INFINITE);
1849 #ifndef PERL_IMPLICIT_CONTEXT
1851 static UINT timerid = 0;
1853 static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
1856 KillTimer(NULL,timerid);
1858 CALL_FPTR(PL_sighandlerp)(14);
1861 #endif /* !PERL_IMPLICIT_CONTEXT */
1863 DllExport unsigned int
1864 win32_alarm(unsigned int sec)
1866 #ifndef PERL_IMPLICIT_CONTEXT
1868 * the 'obvious' implentation is SetTimer() with a callback
1869 * which does whatever receiving SIGALRM would do
1870 * we cannot use SIGALRM even via raise() as it is not
1871 * one of the supported codes in <signal.h>
1873 * Snag is unless something is looking at the message queue
1874 * nothing happens :-(
1879 timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
1881 Perl_croak_nocontext("Cannot set timer");
1887 KillTimer(NULL,timerid);
1891 #endif /* !PERL_IMPLICIT_CONTEXT */
1895 #ifdef HAVE_DES_FCRYPT
1896 extern char * des_fcrypt(const char *txt, const char *salt, char *cbuf);
1900 win32_crypt(const char *txt, const char *salt)
1903 #ifdef HAVE_DES_FCRYPT
1904 return des_fcrypt(txt, salt, w32_crypt_buffer);
1906 Perl_croak(aTHX_ "The crypt() function is unimplemented due to excessive paranoia.");
1911 #ifdef USE_FIXED_OSFHANDLE
1913 #define FOPEN 0x01 /* file handle open */
1914 #define FNOINHERIT 0x10 /* file handle opened O_NOINHERIT */
1915 #define FAPPEND 0x20 /* file handle opened O_APPEND */
1916 #define FDEV 0x40 /* file handle refers to device */
1917 #define FTEXT 0x80 /* file handle is in text mode */
1920 *int my_open_osfhandle(long osfhandle, int flags) - open C Runtime file handle
1923 * This function allocates a free C Runtime file handle and associates
1924 * it with the Win32 HANDLE specified by the first parameter. This is a
1925 * temperary fix for WIN95's brain damage GetFileType() error on socket
1926 * we just bypass that call for socket
1928 * This works with MSVC++ 4.0+ or GCC/Mingw32
1931 * long osfhandle - Win32 HANDLE to associate with C Runtime file handle.
1932 * int flags - flags to associate with C Runtime file handle.
1935 * returns index of entry in fh, if successful
1936 * return -1, if no free entry is found
1940 *******************************************************************************/
1943 * we fake up some parts of the CRT that aren't exported by MSVCRT.dll
1944 * this lets sockets work on Win9X with GCC and should fix the problems
1949 /* create an ioinfo entry, kill its handle, and steal the entry */
1954 HANDLE hF = CreateFile("NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
1955 int fh = _open_osfhandle((long)hF, 0);
1959 EnterCriticalSection(&(_pioinfo(fh)->lock));
1964 my_open_osfhandle(long osfhandle, int flags)
1967 char fileflags; /* _osfile flags */
1969 /* copy relevant flags from second parameter */
1972 if (flags & O_APPEND)
1973 fileflags |= FAPPEND;
1978 if (flags & O_NOINHERIT)
1979 fileflags |= FNOINHERIT;
1981 /* attempt to allocate a C Runtime file handle */
1982 if ((fh = _alloc_osfhnd()) == -1) {
1983 errno = EMFILE; /* too many open files */
1984 _doserrno = 0L; /* not an OS error */
1985 return -1; /* return error to caller */
1988 /* the file is open. now, set the info in _osfhnd array */
1989 _set_osfhnd(fh, osfhandle);
1991 fileflags |= FOPEN; /* mark as open */
1993 _osfile(fh) = fileflags; /* set osfile entry */
1994 LeaveCriticalSection(&_pioinfo(fh)->lock);
1996 return fh; /* return handle */
1999 #endif /* USE_FIXED_OSFHANDLE */
2001 /* simulate flock by locking a range on the file */
2003 #define LK_ERR(f,i) ((f) ? (i = 0) : (errno = GetLastError()))
2004 #define LK_LEN 0xffff0000
2007 win32_flock(int fd, int oper)
2015 Perl_croak_nocontext("flock() unimplemented on this platform");
2018 fh = (HANDLE)_get_osfhandle(fd);
2019 memset(&o, 0, sizeof(o));
2022 case LOCK_SH: /* shared lock */
2023 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
2025 case LOCK_EX: /* exclusive lock */
2026 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
2028 case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
2029 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
2031 case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
2032 LK_ERR(LockFileEx(fh,
2033 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
2034 0, LK_LEN, 0, &o),i);
2036 case LOCK_UN: /* unlock lock */
2037 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, 0, &o),i);
2039 default: /* unknown */
2050 * redirected io subsystem for all XS modules
2063 return (&(_environ));
2066 /* the rest are the remapped stdio routines */
2086 win32_ferror(FILE *fp)
2088 return (ferror(fp));
2093 win32_feof(FILE *fp)
2099 * Since the errors returned by the socket error function
2100 * WSAGetLastError() are not known by the library routine strerror
2101 * we have to roll our own.
2105 win32_strerror(int e)
2107 #if !defined __BORLANDC__ && !defined __MINGW32__ /* compiler intolerance */
2108 extern int sys_nerr;
2112 if (e < 0 || e > sys_nerr) {
2117 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
2118 w32_strerror_buffer,
2119 sizeof(w32_strerror_buffer), NULL) == 0)
2120 strcpy(w32_strerror_buffer, "Unknown Error");
2122 return w32_strerror_buffer;
2128 win32_str_os_error(void *sv, DWORD dwErr)
2132 dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
2133 |FORMAT_MESSAGE_IGNORE_INSERTS
2134 |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
2135 dwErr, 0, (char *)&sMsg, 1, NULL);
2136 /* strip trailing whitespace and period */
2139 --dwLen; /* dwLen doesn't include trailing null */
2140 } while (0 < dwLen && isSPACE(sMsg[dwLen]));
2141 if ('.' != sMsg[dwLen])
2146 sMsg = (char*)LocalAlloc(0, 64/**sizeof(TCHAR)*/);
2148 dwLen = sprintf(sMsg,
2149 "Unknown error #0x%lX (lookup 0x%lX)",
2150 dwErr, GetLastError());
2154 sv_setpvn((SV*)sv, sMsg, dwLen);
2160 win32_fprintf(FILE *fp, const char *format, ...)
2163 va_start(marker, format); /* Initialize variable arguments. */
2165 return (vfprintf(fp, format, marker));
2169 win32_printf(const char *format, ...)
2172 va_start(marker, format); /* Initialize variable arguments. */
2174 return (vprintf(format, marker));
2178 win32_vfprintf(FILE *fp, const char *format, va_list args)
2180 return (vfprintf(fp, format, args));
2184 win32_vprintf(const char *format, va_list args)
2186 return (vprintf(format, args));
2190 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
2192 return fread(buf, size, count, fp);
2196 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
2198 return fwrite(buf, size, count, fp);
2201 #define MODE_SIZE 10
2204 win32_fopen(const char *filename, const char *mode)
2207 WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH+1];
2213 if (stricmp(filename, "/dev/null")==0)
2217 A2WHELPER(mode, wMode, sizeof(wMode));
2218 A2WHELPER(filename, wBuffer, sizeof(wBuffer));
2219 f = _wfopen(PerlDir_mapW(wBuffer), wMode);
2222 f = fopen(PerlDir_mapA(filename), mode);
2223 /* avoid buffering headaches for child processes */
2224 if (f && *mode == 'a')
2225 win32_fseek(f, 0, SEEK_END);
2229 #ifndef USE_SOCKETS_AS_HANDLES
2231 #define fdopen my_fdopen
2235 win32_fdopen(int handle, const char *mode)
2238 WCHAR wMode[MODE_SIZE];
2241 A2WHELPER(mode, wMode, sizeof(wMode));
2242 f = _wfdopen(handle, wMode);
2245 f = fdopen(handle, (char *) mode);
2246 /* avoid buffering headaches for child processes */
2247 if (f && *mode == 'a')
2248 win32_fseek(f, 0, SEEK_END);
2253 win32_freopen(const char *path, const char *mode, FILE *stream)
2256 WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH+1];
2257 if (stricmp(path, "/dev/null")==0)
2261 A2WHELPER(mode, wMode, sizeof(wMode));
2262 A2WHELPER(path, wBuffer, sizeof(wBuffer));
2263 return _wfreopen(PerlDir_mapW(wBuffer), wMode, stream);
2265 return freopen(PerlDir_mapA(path), mode, stream);
2269 win32_fclose(FILE *pf)
2271 return my_fclose(pf); /* defined in win32sck.c */
2275 win32_fputs(const char *s,FILE *pf)
2277 return fputs(s, pf);
2281 win32_fputc(int c,FILE *pf)
2287 win32_ungetc(int c,FILE *pf)
2289 return ungetc(c,pf);
2293 win32_getc(FILE *pf)
2299 win32_fileno(FILE *pf)
2305 win32_clearerr(FILE *pf)
2312 win32_fflush(FILE *pf)
2318 win32_ftell(FILE *pf)
2324 win32_fseek(FILE *pf,long offset,int origin)
2326 return fseek(pf, offset, origin);
2330 win32_fgetpos(FILE *pf,fpos_t *p)
2332 return fgetpos(pf, p);
2336 win32_fsetpos(FILE *pf,const fpos_t *p)
2338 return fsetpos(pf, p);
2342 win32_rewind(FILE *pf)
2352 char prefix[MAX_PATH+1];
2353 char filename[MAX_PATH+1];
2354 DWORD len = GetTempPath(MAX_PATH, prefix);
2355 if (len && len < MAX_PATH) {
2356 if (GetTempFileName(prefix, "plx", 0, filename)) {
2357 HANDLE fh = CreateFile(filename,
2358 DELETE | GENERIC_READ | GENERIC_WRITE,
2362 FILE_ATTRIBUTE_NORMAL
2363 | FILE_FLAG_DELETE_ON_CLOSE,
2365 if (fh != INVALID_HANDLE_VALUE) {
2366 int fd = win32_open_osfhandle((long)fh, 0);
2368 DEBUG_p(PerlIO_printf(Perl_debug_log,
2369 "Created tmpfile=%s\n",filename));
2370 return fdopen(fd, "w+b");
2386 win32_fstat(int fd,struct stat *sbufptr)
2389 /* A file designated by filehandle is not shown as accessible
2390 * for write operations, probably because it is opened for reading.
2393 int rc = fstat(fd,sbufptr);
2394 BY_HANDLE_FILE_INFORMATION bhfi;
2395 if (GetFileInformationByHandle((HANDLE)_get_osfhandle(fd), &bhfi)) {
2396 sbufptr->st_mode &= 0xFE00;
2397 if (bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
2398 sbufptr->st_mode |= (S_IREAD + (S_IREAD >> 3) + (S_IREAD >> 6));
2400 sbufptr->st_mode |= ((S_IREAD|S_IWRITE) + ((S_IREAD|S_IWRITE) >> 3)
2401 + ((S_IREAD|S_IWRITE) >> 6));
2405 return my_fstat(fd,sbufptr);
2410 win32_pipe(int *pfd, unsigned int size, int mode)
2412 return _pipe(pfd, size, mode);
2416 win32_popenlist(const char *mode, IV narg, SV **args)
2419 Perl_croak(aTHX_ "List form of pipe open not implemented");
2424 * a popen() clone that respects PERL5SHELL
2426 * changed to return PerlIO* rather than FILE * by BKS, 11-11-2000
2430 win32_popen(const char *command, const char *mode)
2432 #ifdef USE_RTL_POPEN
2433 return _popen(command, mode);
2441 /* establish which ends read and write */
2442 if (strchr(mode,'w')) {
2443 stdfd = 0; /* stdin */
2447 else if (strchr(mode,'r')) {
2448 stdfd = 1; /* stdout */
2455 /* set the correct mode */
2456 if (strchr(mode,'b'))
2458 else if (strchr(mode,'t'))
2461 ourmode = _fmode & (O_TEXT | O_BINARY);
2463 /* the child doesn't inherit handles */
2464 ourmode |= O_NOINHERIT;
2466 if (win32_pipe( p, 512, ourmode) == -1)
2469 /* save current stdfd */
2470 if ((oldfd = win32_dup(stdfd)) == -1)
2473 /* make stdfd go to child end of pipe (implicitly closes stdfd) */
2474 /* stdfd will be inherited by the child */
2475 if (win32_dup2(p[child], stdfd) == -1)
2478 /* close the child end in parent */
2479 win32_close(p[child]);
2481 /* start the child */
2484 if ((childpid = do_spawn_nowait((char*)command)) == -1)
2487 /* revert stdfd to whatever it was before */
2488 if (win32_dup2(oldfd, stdfd) == -1)
2491 /* close saved handle */
2495 sv_setiv(*av_fetch(w32_fdpid, p[parent], TRUE), childpid);
2498 /* set process id so that it can be returned by perl's open() */
2499 PL_forkprocess = childpid;
2502 /* we have an fd, return a file stream */
2503 return (PerlIO_fdopen(p[parent], (char *)mode));
2506 /* we don't need to check for errors here */
2510 win32_dup2(oldfd, stdfd);
2515 #endif /* USE_RTL_POPEN */
2523 win32_pclose(PerlIO *pf)
2525 #ifdef USE_RTL_POPEN
2529 int childpid, status;
2533 sv = *av_fetch(w32_fdpid, PerlIO_fileno(pf), TRUE);
2536 childpid = SvIVX(sv);
2553 if (win32_waitpid(childpid, &status, 0) == -1)
2558 #endif /* USE_RTL_POPEN */
2564 LPCWSTR lpExistingFileName,
2565 LPSECURITY_ATTRIBUTES lpSecurityAttributes)
2568 WCHAR wFullName[MAX_PATH+1];
2569 LPVOID lpContext = NULL;
2570 WIN32_STREAM_ID StreamId;
2571 DWORD dwSize = (char*)&StreamId.cStreamName - (char*)&StreamId;
2576 BOOL (__stdcall *pfnBackupWrite)(HANDLE, LPBYTE, DWORD, LPDWORD,
2577 BOOL, BOOL, LPVOID*) =
2578 (BOOL (__stdcall *)(HANDLE, LPBYTE, DWORD, LPDWORD,
2579 BOOL, BOOL, LPVOID*))
2580 GetProcAddress(GetModuleHandle("kernel32.dll"), "BackupWrite");
2581 if (pfnBackupWrite == NULL)
2584 dwLen = GetFullPathNameW(lpFileName, MAX_PATH, wFullName, NULL);
2587 dwLen = (dwLen+1)*sizeof(WCHAR);
2589 handle = CreateFileW(lpExistingFileName, FILE_WRITE_ATTRIBUTES,
2590 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
2591 NULL, OPEN_EXISTING, 0, NULL);
2592 if (handle == INVALID_HANDLE_VALUE)
2595 StreamId.dwStreamId = BACKUP_LINK;
2596 StreamId.dwStreamAttributes = 0;
2597 StreamId.dwStreamNameSize = 0;
2598 #if defined(__BORLANDC__) \
2599 ||(defined(__MINGW32__) && !defined(_ANONYMOUS_UNION))
2600 StreamId.Size.u.HighPart = 0;
2601 StreamId.Size.u.LowPart = dwLen;
2603 StreamId.Size.HighPart = 0;
2604 StreamId.Size.LowPart = dwLen;
2607 bSuccess = pfnBackupWrite(handle, (LPBYTE)&StreamId, dwSize, &dwWritten,
2608 FALSE, FALSE, &lpContext);
2610 bSuccess = pfnBackupWrite(handle, (LPBYTE)wFullName, dwLen, &dwWritten,
2611 FALSE, FALSE, &lpContext);
2612 pfnBackupWrite(handle, NULL, 0, &dwWritten, TRUE, FALSE, &lpContext);
2615 CloseHandle(handle);
2620 win32_link(const char *oldname, const char *newname)
2623 BOOL (__stdcall *pfnCreateHardLinkW)(LPCWSTR,LPCWSTR,LPSECURITY_ATTRIBUTES);
2624 WCHAR wOldName[MAX_PATH+1];
2625 WCHAR wNewName[MAX_PATH+1];
2628 Perl_croak(aTHX_ PL_no_func, "link");
2630 pfnCreateHardLinkW =
2631 (BOOL (__stdcall *)(LPCWSTR, LPCWSTR, LPSECURITY_ATTRIBUTES))
2632 GetProcAddress(GetModuleHandle("kernel32.dll"), "CreateHardLinkW");
2633 if (pfnCreateHardLinkW == NULL)
2634 pfnCreateHardLinkW = Nt4CreateHardLinkW;
2636 if ((A2WHELPER(oldname, wOldName, sizeof(wOldName))) &&
2637 (A2WHELPER(newname, wNewName, sizeof(wNewName))) &&
2638 (wcscpy(wOldName, PerlDir_mapW(wOldName)),
2639 pfnCreateHardLinkW(PerlDir_mapW(wNewName), wOldName, NULL)))
2643 errno = (GetLastError() == ERROR_FILE_NOT_FOUND) ? ENOENT : EINVAL;
2648 win32_rename(const char *oname, const char *newname)
2650 WCHAR wOldName[MAX_PATH+1];
2651 WCHAR wNewName[MAX_PATH+1];
2652 char szOldName[MAX_PATH+1];
2653 char szNewName[MAX_PATH+1];
2657 /* XXX despite what the documentation says about MoveFileEx(),
2658 * it doesn't work under Windows95!
2661 DWORD dwFlags = MOVEFILE_COPY_ALLOWED;
2663 A2WHELPER(oname, wOldName, sizeof(wOldName));
2664 A2WHELPER(newname, wNewName, sizeof(wNewName));
2665 if (wcsicmp(wNewName, wOldName))
2666 dwFlags |= MOVEFILE_REPLACE_EXISTING;
2667 wcscpy(wOldName, PerlDir_mapW(wOldName));
2668 bResult = MoveFileExW(wOldName,PerlDir_mapW(wNewName), dwFlags);
2671 if (stricmp(newname, oname))
2672 dwFlags |= MOVEFILE_REPLACE_EXISTING;
2673 strcpy(szOldName, PerlDir_mapA(oname));
2674 bResult = MoveFileExA(szOldName,PerlDir_mapA(newname), dwFlags);
2677 DWORD err = GetLastError();
2679 case ERROR_BAD_NET_NAME:
2680 case ERROR_BAD_NETPATH:
2681 case ERROR_BAD_PATHNAME:
2682 case ERROR_FILE_NOT_FOUND:
2683 case ERROR_FILENAME_EXCED_RANGE:
2684 case ERROR_INVALID_DRIVE:
2685 case ERROR_NO_MORE_FILES:
2686 case ERROR_PATH_NOT_FOUND:
2699 char szTmpName[MAX_PATH+1];
2700 char dname[MAX_PATH+1];
2701 char *endname = Nullch;
2703 DWORD from_attr, to_attr;
2705 strcpy(szOldName, PerlDir_mapA(oname));
2706 strcpy(szNewName, PerlDir_mapA(newname));
2708 /* if oname doesn't exist, do nothing */
2709 from_attr = GetFileAttributes(szOldName);
2710 if (from_attr == 0xFFFFFFFF) {
2715 /* if newname exists, rename it to a temporary name so that we
2716 * don't delete it in case oname happens to be the same file
2717 * (but perhaps accessed via a different path)
2719 to_attr = GetFileAttributes(szNewName);
2720 if (to_attr != 0xFFFFFFFF) {
2721 /* if newname is a directory, we fail
2722 * XXX could overcome this with yet more convoluted logic */
2723 if (to_attr & FILE_ATTRIBUTE_DIRECTORY) {
2727 tmplen = strlen(szNewName);
2728 strcpy(szTmpName,szNewName);
2729 endname = szTmpName+tmplen;
2730 for (; endname > szTmpName ; --endname) {
2731 if (*endname == '/' || *endname == '\\') {
2736 if (endname > szTmpName)
2737 endname = strcpy(dname,szTmpName);
2741 /* get a temporary filename in same directory
2742 * XXX is this really the best we can do? */
2743 if (!GetTempFileName((LPCTSTR)endname, "plr", 0, szTmpName)) {
2747 DeleteFile(szTmpName);
2749 retval = rename(szNewName, szTmpName);
2756 /* rename oname to newname */
2757 retval = rename(szOldName, szNewName);
2759 /* if we created a temporary file before ... */
2760 if (endname != Nullch) {
2761 /* ...and rename succeeded, delete temporary file/directory */
2763 DeleteFile(szTmpName);
2764 /* else restore it to what it was */
2766 (void)rename(szTmpName, szNewName);
2773 win32_setmode(int fd, int mode)
2775 return setmode(fd, mode);
2779 win32_lseek(int fd, long offset, int origin)
2781 return lseek(fd, offset, origin);
2791 win32_open(const char *path, int flag, ...)
2796 WCHAR wBuffer[MAX_PATH+1];
2799 pmode = va_arg(ap, int);
2802 if (stricmp(path, "/dev/null")==0)
2806 A2WHELPER(path, wBuffer, sizeof(wBuffer));
2807 return _wopen(PerlDir_mapW(wBuffer), flag, pmode);
2809 return open(PerlDir_mapA(path), flag, pmode);
2812 /* close() that understands socket */
2813 extern int my_close(int); /* in win32sck.c */
2818 return my_close(fd);
2834 win32_dup2(int fd1,int fd2)
2836 return dup2(fd1,fd2);
2839 #ifdef PERL_MSVCRT_READFIX
2841 #define LF 10 /* line feed */
2842 #define CR 13 /* carriage return */
2843 #define CTRLZ 26 /* ctrl-z means eof for text */
2844 #define FOPEN 0x01 /* file handle open */
2845 #define FEOFLAG 0x02 /* end of file has been encountered */
2846 #define FCRLF 0x04 /* CR-LF across read buffer (in text mode) */
2847 #define FPIPE 0x08 /* file handle refers to a pipe */
2848 #define FAPPEND 0x20 /* file handle opened O_APPEND */
2849 #define FDEV 0x40 /* file handle refers to device */
2850 #define FTEXT 0x80 /* file handle is in text mode */
2851 #define MAX_DESCRIPTOR_COUNT (64*32) /* this is the maximun that MSVCRT can handle */
2854 _fixed_read(int fh, void *buf, unsigned cnt)
2856 int bytes_read; /* number of bytes read */
2857 char *buffer; /* buffer to read to */
2858 int os_read; /* bytes read on OS call */
2859 char *p, *q; /* pointers into buffer */
2860 char peekchr; /* peek-ahead character */
2861 ULONG filepos; /* file position after seek */
2862 ULONG dosretval; /* o.s. return value */
2864 /* validate handle */
2865 if (((unsigned)fh >= (unsigned)MAX_DESCRIPTOR_COUNT) ||
2866 !(_osfile(fh) & FOPEN))
2868 /* out of range -- return error */
2870 _doserrno = 0; /* not o.s. error */
2875 * If lockinitflag is FALSE, assume fd is device
2876 * lockinitflag is set to TRUE by open.
2878 if (_pioinfo(fh)->lockinitflag)
2879 EnterCriticalSection(&(_pioinfo(fh)->lock)); /* lock file */
2881 bytes_read = 0; /* nothing read yet */
2882 buffer = (char*)buf;
2884 if (cnt == 0 || (_osfile(fh) & FEOFLAG)) {
2885 /* nothing to read or at EOF, so return 0 read */
2889 if ((_osfile(fh) & (FPIPE|FDEV)) && _pipech(fh) != LF) {
2890 /* a pipe/device and pipe lookahead non-empty: read the lookahead
2892 *buffer++ = _pipech(fh);
2895 _pipech(fh) = LF; /* mark as empty */
2900 if (!ReadFile((HANDLE)_osfhnd(fh), buffer, cnt, (LPDWORD)&os_read, NULL))
2902 /* ReadFile has reported an error. recognize two special cases.
2904 * 1. map ERROR_ACCESS_DENIED to EBADF
2906 * 2. just return 0 if ERROR_BROKEN_PIPE has occurred. it
2907 * means the handle is a read-handle on a pipe for which
2908 * all write-handles have been closed and all data has been
2911 if ((dosretval = GetLastError()) == ERROR_ACCESS_DENIED) {
2912 /* wrong read/write mode should return EBADF, not EACCES */
2914 _doserrno = dosretval;
2918 else if (dosretval == ERROR_BROKEN_PIPE) {
2928 bytes_read += os_read; /* update bytes read */
2930 if (_osfile(fh) & FTEXT) {
2931 /* now must translate CR-LFs to LFs in the buffer */
2933 /* set CRLF flag to indicate LF at beginning of buffer */
2934 /* if ((os_read != 0) && (*(char *)buf == LF)) */
2935 /* _osfile(fh) |= FCRLF; */
2937 /* _osfile(fh) &= ~FCRLF; */
2939 _osfile(fh) &= ~FCRLF;
2941 /* convert chars in the buffer: p is src, q is dest */
2943 while (p < (char *)buf + bytes_read) {
2945 /* if fh is not a device, set ctrl-z flag */
2946 if (!(_osfile(fh) & FDEV))
2947 _osfile(fh) |= FEOFLAG;
2948 break; /* stop translating */
2953 /* *p is CR, so must check next char for LF */
2954 if (p < (char *)buf + bytes_read - 1) {
2957 *q++ = LF; /* convert CR-LF to LF */
2960 *q++ = *p++; /* store char normally */
2963 /* This is the hard part. We found a CR at end of
2964 buffer. We must peek ahead to see if next char
2969 if (!ReadFile((HANDLE)_osfhnd(fh), &peekchr, 1,
2970 (LPDWORD)&os_read, NULL))
2971 dosretval = GetLastError();
2973 if (dosretval != 0 || os_read == 0) {
2974 /* couldn't read ahead, store CR */
2978 /* peekchr now has the extra character -- we now
2979 have several possibilities:
2980 1. disk file and char is not LF; just seek back
2982 2. disk file and char is LF; store LF, don't seek back
2983 3. pipe/device and char is LF; store LF.
2984 4. pipe/device and char isn't LF, store CR and
2985 put char in pipe lookahead buffer. */
2986 if (_osfile(fh) & (FDEV|FPIPE)) {
2987 /* non-seekable device */
2992 _pipech(fh) = peekchr;
2997 if (peekchr == LF) {
2998 /* nothing read yet; must make some
3001 /* turn on this flag for tell routine */
3002 _osfile(fh) |= FCRLF;
3005 HANDLE osHandle; /* o.s. handle value */
3007 if ((osHandle = (HANDLE)_get_osfhandle(fh)) != (HANDLE)-1)
3009 if ((filepos = SetFilePointer(osHandle, -1, NULL, FILE_CURRENT)) == -1)
3010 dosretval = GetLastError();
3021 /* we now change bytes_read to reflect the true number of chars
3023 bytes_read = q - (char *)buf;
3027 if (_pioinfo(fh)->lockinitflag)
3028 LeaveCriticalSection(&(_pioinfo(fh)->lock)); /* unlock file */
3033 #endif /* PERL_MSVCRT_READFIX */
3036 win32_read(int fd, void *buf, unsigned int cnt)
3038 #ifdef PERL_MSVCRT_READFIX
3039 return _fixed_read(fd, buf, cnt);
3041 return read(fd, buf, cnt);
3046 win32_write(int fd, const void *buf, unsigned int cnt)
3048 return write(fd, buf, cnt);
3052 win32_mkdir(const char *dir, int mode)
3056 WCHAR wBuffer[MAX_PATH+1];
3057 A2WHELPER(dir, wBuffer, sizeof(wBuffer));
3058 return _wmkdir(PerlDir_mapW(wBuffer));
3060 return mkdir(PerlDir_mapA(dir)); /* just ignore mode */
3064 win32_rmdir(const char *dir)
3068 WCHAR wBuffer[MAX_PATH+1];
3069 A2WHELPER(dir, wBuffer, sizeof(wBuffer));
3070 return _wrmdir(PerlDir_mapW(wBuffer));
3072 return rmdir(PerlDir_mapA(dir));
3076 win32_chdir(const char *dir)
3084 WCHAR wBuffer[MAX_PATH+1];
3085 A2WHELPER(dir, wBuffer, sizeof(wBuffer));
3086 return _wchdir(wBuffer);
3092 win32_access(const char *path, int mode)
3096 WCHAR wBuffer[MAX_PATH+1];
3097 A2WHELPER(path, wBuffer, sizeof(wBuffer));
3098 return _waccess(PerlDir_mapW(wBuffer), mode);
3100 return access(PerlDir_mapA(path), mode);
3104 win32_chmod(const char *path, int mode)
3108 WCHAR wBuffer[MAX_PATH+1];
3109 A2WHELPER(path, wBuffer, sizeof(wBuffer));
3110 return _wchmod(PerlDir_mapW(wBuffer), mode);
3112 return chmod(PerlDir_mapA(path), mode);
3117 create_command_line(char *cname, STRLEN clen, const char * const *args)
3124 bool bat_file = FALSE;
3125 bool cmd_shell = FALSE;
3126 bool dumb_shell = FALSE;
3127 bool extra_quotes = FALSE;
3128 bool quote_next = FALSE;
3131 cname = (char*)args[0];
3133 /* The NT cmd.exe shell has the following peculiarity that needs to be
3134 * worked around. It strips a leading and trailing dquote when any
3135 * of the following is true:
3136 * 1. the /S switch was used
3137 * 2. there are more than two dquotes
3138 * 3. there is a special character from this set: &<>()@^|
3139 * 4. no whitespace characters within the two dquotes
3140 * 5. string between two dquotes isn't an executable file
3141 * To work around this, we always add a leading and trailing dquote
3142 * to the string, if the first argument is either "cmd.exe" or "cmd",
3143 * and there were at least two or more arguments passed to cmd.exe
3144 * (not including switches).
3145 * XXX the above rules (from "cmd /?") don't seem to be applied
3146 * always, making for the convolutions below :-(
3150 clen = strlen(cname);
3153 && (stricmp(&cname[clen-4], ".bat") == 0
3154 || (IsWinNT() && stricmp(&cname[clen-4], ".cmd") == 0)))
3160 char *exe = strrchr(cname, '/');
3161 char *exe2 = strrchr(cname, '\\');
3168 if (stricmp(exe, "cmd.exe") == 0 || stricmp(exe, "cmd") == 0) {
3172 else if (stricmp(exe, "command.com") == 0
3173 || stricmp(exe, "command") == 0)
3180 DEBUG_p(PerlIO_printf(Perl_debug_log, "Args "));
3181 for (index = 0; (arg = (char*)args[index]) != NULL; ++index) {
3182 STRLEN curlen = strlen(arg);
3183 if (!(arg[0] == '"' && arg[curlen-1] == '"'))
3184 len += 2; /* assume quoting needed (worst case) */
3186 DEBUG_p(PerlIO_printf(Perl_debug_log, "[%s]",arg));
3188 DEBUG_p(PerlIO_printf(Perl_debug_log, "\n"));
3191 New(1310, cmd, len, char);
3196 extra_quotes = TRUE;
3199 for (index = 0; (arg = (char*)args[index]) != NULL; ++index) {
3201 STRLEN curlen = strlen(arg);
3203 /* we want to protect empty arguments and ones with spaces with
3204 * dquotes, but only if they aren't already there */
3209 else if (quote_next) {
3210 /* see if it really is multiple arguments pretending to
3211 * be one and force a set of quotes around it */
3212 if (*find_next_space(arg))
3215 else if (!(arg[0] == '"' && curlen > 1 && arg[curlen-1] == '"')) {
3217 while (i < curlen) {
3218 if (isSPACE(arg[i])) {
3221 else if (arg[i] == '"') {
3244 && (stricmp(arg, "/x/c") == 0 || stricmp(arg, "/c") == 0))
3246 /* is there a next argument? */
3247 if (args[index+1]) {
3248 /* are there two or more next arguments? */
3249 if (args[index+2]) {
3251 extra_quotes = TRUE;
3254 /* single argument, force quoting if it has spaces */
3270 qualified_path(const char *cmd)
3274 char *fullcmd, *curfullcmd;
3280 fullcmd = (char*)cmd;
3282 if (*fullcmd == '/' || *fullcmd == '\\')
3289 pathstr = PerlEnv_getenv("PATH");
3290 New(0, fullcmd, MAX_PATH+1, char);
3291 curfullcmd = fullcmd;
3296 /* start by appending the name to the current prefix */
3297 strcpy(curfullcmd, cmd);
3298 curfullcmd += cmdlen;
3300 /* if it doesn't end with '.', or has no extension, try adding
3301 * a trailing .exe first */
3302 if (cmd[cmdlen-1] != '.'
3303 && (cmdlen < 4 || cmd[cmdlen-4] != '.'))
3305 strcpy(curfullcmd, ".exe");
3306 res = GetFileAttributes(fullcmd);
3307 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
3312 /* that failed, try the bare name */
3313 res = GetFileAttributes(fullcmd);
3314 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
3317 /* quit if no other path exists, or if cmd already has path */
3318 if (!pathstr || !*pathstr || has_slash)
3321 /* skip leading semis */
3322 while (*pathstr == ';')
3325 /* build a new prefix from scratch */
3326 curfullcmd = fullcmd;
3327 while (*pathstr && *pathstr != ';') {
3328 if (*pathstr == '"') { /* foo;"baz;etc";bar */
3329 pathstr++; /* skip initial '"' */
3330 while (*pathstr && *pathstr != '"') {
3331 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
3332 *curfullcmd++ = *pathstr;
3336 pathstr++; /* skip trailing '"' */
3339 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
3340 *curfullcmd++ = *pathstr;
3345 pathstr++; /* skip trailing semi */
3346 if (curfullcmd > fullcmd /* append a dir separator */
3347 && curfullcmd[-1] != '/' && curfullcmd[-1] != '\\')
3349 *curfullcmd++ = '\\';
3357 /* The following are just place holders.
3358 * Some hosts may provide and environment that the OS is
3359 * not tracking, therefore, these host must provide that
3360 * environment and the current directory to CreateProcess
3364 win32_get_childenv(void)
3370 win32_free_childenv(void* d)
3375 win32_clearenv(void)
3377 char *envv = GetEnvironmentStrings();
3381 char *end = strchr(cur,'=');
3382 if (end && end != cur) {
3384 SetEnvironmentVariable(cur, NULL);
3386 cur = end + strlen(end+1)+2;
3388 else if ((len = strlen(cur)))
3391 FreeEnvironmentStrings(envv);
3395 win32_get_childdir(void)
3399 char szfilename[(MAX_PATH+1)*2];
3401 WCHAR wfilename[MAX_PATH+1];
3402 GetCurrentDirectoryW(MAX_PATH+1, wfilename);
3403 W2AHELPER(wfilename, szfilename, sizeof(szfilename));
3406 GetCurrentDirectoryA(MAX_PATH+1, szfilename);
3409 New(0, ptr, strlen(szfilename)+1, char);
3410 strcpy(ptr, szfilename);
3415 win32_free_childdir(char* d)
3422 /* XXX this needs to be made more compatible with the spawnvp()
3423 * provided by the various RTLs. In particular, searching for
3424 * *.{com,bat,cmd} files (as done by the RTLs) is unimplemented.
3425 * This doesn't significantly affect perl itself, because we
3426 * always invoke things using PERL5SHELL if a direct attempt to
3427 * spawn the executable fails.
3429 * XXX splitting and rejoining the commandline between do_aspawn()
3430 * and win32_spawnvp() could also be avoided.
3434 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
3436 #ifdef USE_RTL_SPAWNVP
3437 return spawnvp(mode, cmdname, (char * const *)argv);
3444 STARTUPINFO StartupInfo;
3445 PROCESS_INFORMATION ProcessInformation;
3448 char *fullcmd = Nullch;
3449 char *cname = (char *)cmdname;
3453 clen = strlen(cname);
3454 /* if command name contains dquotes, must remove them */
3455 if (strchr(cname, '"')) {
3457 New(0,cname,clen+1,char);
3470 cmd = create_command_line(cname, clen, argv);
3472 env = PerlEnv_get_childenv();
3473 dir = PerlEnv_get_childdir();
3476 case P_NOWAIT: /* asynch + remember result */
3477 if (w32_num_children >= MAXIMUM_WAIT_OBJECTS) {
3483 case P_WAIT: /* synchronous execution */
3485 default: /* invalid mode */
3490 memset(&StartupInfo,0,sizeof(StartupInfo));
3491 StartupInfo.cb = sizeof(StartupInfo);
3492 memset(&tbl,0,sizeof(tbl));
3493 PerlEnv_get_child_IO(&tbl);
3494 StartupInfo.dwFlags = tbl.dwFlags;
3495 StartupInfo.dwX = tbl.dwX;
3496 StartupInfo.dwY = tbl.dwY;
3497 StartupInfo.dwXSize = tbl.dwXSize;
3498 StartupInfo.dwYSize = tbl.dwYSize;
3499 StartupInfo.dwXCountChars = tbl.dwXCountChars;
3500 StartupInfo.dwYCountChars = tbl.dwYCountChars;
3501 StartupInfo.dwFillAttribute = tbl.dwFillAttribute;
3502 StartupInfo.wShowWindow = tbl.wShowWindow;
3503 StartupInfo.hStdInput = tbl.childStdIn;
3504 StartupInfo.hStdOutput = tbl.childStdOut;
3505 StartupInfo.hStdError = tbl.childStdErr;
3506 if (StartupInfo.hStdInput != INVALID_HANDLE_VALUE &&
3507 StartupInfo.hStdOutput != INVALID_HANDLE_VALUE &&
3508 StartupInfo.hStdError != INVALID_HANDLE_VALUE)
3510 StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
3513 create |= CREATE_NEW_CONSOLE;
3516 DEBUG_p(PerlIO_printf(Perl_debug_log, "Spawning [%s] with [%s]\n",
3519 if (!CreateProcess(cname, /* search PATH to find executable */
3520 cmd, /* executable, and its arguments */
3521 NULL, /* process attributes */
3522 NULL, /* thread attributes */
3523 TRUE, /* inherit handles */
3524 create, /* creation flags */
3525 (LPVOID)env, /* inherit environment */
3526 dir, /* inherit cwd */
3528 &ProcessInformation))
3530 /* initial NULL argument to CreateProcess() does a PATH
3531 * search, but it always first looks in the directory
3532 * where the current process was started, which behavior
3533 * is undesirable for backward compatibility. So we
3534 * jump through our own hoops by picking out the path
3535 * we really want it to use. */
3537 fullcmd = qualified_path(cname);
3539 if (cname != cmdname)
3542 DEBUG_p(PerlIO_printf(Perl_debug_log,
3543 "Retrying [%s] with same args\n",
3553 if (mode == P_NOWAIT) {
3554 /* asynchronous spawn -- store handle, return PID */
3555 ret = (int)ProcessInformation.dwProcessId;
3556 if (IsWin95() && ret < 0)
3559 w32_child_handles[w32_num_children] = ProcessInformation.hProcess;
3560 w32_child_pids[w32_num_children] = (DWORD)ret;
3565 WaitForSingleObject(ProcessInformation.hProcess, INFINITE);
3566 GetExitCodeProcess(ProcessInformation.hProcess, &status);
3568 CloseHandle(ProcessInformation.hProcess);
3571 CloseHandle(ProcessInformation.hThread);
3574 PerlEnv_free_childenv(env);
3575 PerlEnv_free_childdir(dir);
3577 if (cname != cmdname)
3584 win32_execv(const char *cmdname, const char *const *argv)
3588 /* if this is a pseudo-forked child, we just want to spawn
3589 * the new program, and return */
3591 return spawnv(P_WAIT, cmdname, (char *const *)argv);
3593 return execv(cmdname, (char *const *)argv);
3597 win32_execvp(const char *cmdname, const char *const *argv)
3601 /* if this is a pseudo-forked child, we just want to spawn
3602 * the new program, and return */
3603 if (w32_pseudo_id) {
3604 int status = win32_spawnvp(P_WAIT, cmdname, (char *const *)argv);
3613 return execvp(cmdname, (char *const *)argv);
3617 win32_perror(const char *str)
3623 win32_setbuf(FILE *pf, char *buf)
3629 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
3631 return setvbuf(pf, buf, type, size);
3635 win32_flushall(void)
3641 win32_fcloseall(void)
3647 win32_fgets(char *s, int n, FILE *pf)
3649 return fgets(s, n, pf);
3659 win32_fgetc(FILE *pf)
3665 win32_putc(int c, FILE *pf)
3671 win32_puts(const char *s)
3683 win32_putchar(int c)
3690 #ifndef USE_PERL_SBRK
3692 static char *committed = NULL; /* XXX threadead */
3693 static char *base = NULL; /* XXX threadead */
3694 static char *reserved = NULL; /* XXX threadead */
3695 static char *brk = NULL; /* XXX threadead */
3696 static DWORD pagesize = 0; /* XXX threadead */
3697 static DWORD allocsize = 0; /* XXX threadead */
3705 GetSystemInfo(&info);
3706 /* Pretend page size is larger so we don't perpetually
3707 * call the OS to commit just one page ...
3709 pagesize = info.dwPageSize << 3;
3710 allocsize = info.dwAllocationGranularity;
3712 /* This scheme fails eventually if request for contiguous
3713 * block is denied so reserve big blocks - this is only
3714 * address space not memory ...
3716 if (brk+need >= reserved)
3718 DWORD size = 64*1024*1024;
3720 if (committed && reserved && committed < reserved)
3722 /* Commit last of previous chunk cannot span allocations */
3723 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
3725 committed = reserved;
3727 /* Reserve some (more) space
3728 * Note this is a little sneaky, 1st call passes NULL as reserved
3729 * so lets system choose where we start, subsequent calls pass
3730 * the old end address so ask for a contiguous block
3732 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
3735 reserved = addr+size;
3750 if (brk > committed)
3752 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
3753 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
3768 win32_malloc(size_t size)
3770 return malloc(size);
3774 win32_calloc(size_t numitems, size_t size)
3776 return calloc(numitems,size);
3780 win32_realloc(void *block, size_t size)
3782 return realloc(block,size);
3786 win32_free(void *block)
3793 win32_open_osfhandle(long handle, int flags)
3795 #ifdef USE_FIXED_OSFHANDLE
3797 return my_open_osfhandle(handle, flags);
3799 return _open_osfhandle(handle, flags);
3803 win32_get_osfhandle(int fd)
3805 return _get_osfhandle(fd);
3809 win32_dynaload(const char* filename)
3813 char buf[MAX_PATH+1];
3816 /* LoadLibrary() doesn't recognize forward slashes correctly,
3817 * so turn 'em back. */
3818 first = strchr(filename, '/');
3820 STRLEN len = strlen(filename);
3821 if (len <= MAX_PATH) {
3822 strcpy(buf, filename);
3823 filename = &buf[first - filename];
3825 if (*filename == '/')
3826 *(char*)filename = '\\';
3833 WCHAR wfilename[MAX_PATH+1];
3834 A2WHELPER(filename, wfilename, sizeof(wfilename));
3835 hModule = LoadLibraryExW(PerlDir_mapW(wfilename), NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
3838 hModule = LoadLibraryExA(PerlDir_mapA(filename), NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
3851 /* Make the host for current directory */
3852 char* ptr = PerlEnv_get_childdir();
3855 * then it worked, set PV valid,
3856 * else return 'undef'
3859 SV *sv = sv_newmortal();
3861 PerlEnv_free_childdir(ptr);
3863 #ifndef INCOMPLETE_TAINTS
3880 Perl_croak(aTHX_ "usage: Win32::SetCurrentDirectory($cwd)");
3881 if (!PerlDir_chdir(SvPV_nolen(ST(0))))
3888 XS(w32_GetNextAvailDrive)
3892 char root[] = "_:\\";
3897 if (GetDriveType(root) == 1) {
3906 XS(w32_GetLastError)
3910 XSRETURN_IV(GetLastError());
3914 XS(w32_SetLastError)
3918 Perl_croak(aTHX_ "usage: Win32::SetLastError($error)");
3919 SetLastError(SvIV(ST(0)));
3927 char *name = w32_getlogin_buffer;
3928 DWORD size = sizeof(w32_getlogin_buffer);
3930 if (GetUserName(name,&size)) {
3931 /* size includes NULL */
3932 ST(0) = sv_2mortal(newSVpvn(name,size-1));
3942 char name[MAX_COMPUTERNAME_LENGTH+1];
3943 DWORD size = sizeof(name);
3945 if (GetComputerName(name,&size)) {
3946 /* size does NOT include NULL :-( */
3947 ST(0) = sv_2mortal(newSVpvn(name,size));
3958 HINSTANCE hNetApi32 = LoadLibrary("netapi32.dll");
3959 DWORD (__stdcall *pfnNetApiBufferFree)(LPVOID Buffer);
3960 DWORD (__stdcall *pfnNetWkstaGetInfo)(LPWSTR servername, DWORD level,
3964 pfnNetApiBufferFree = (DWORD (__stdcall *)(void *))
3965 GetProcAddress(hNetApi32, "NetApiBufferFree");
3966 pfnNetWkstaGetInfo = (DWORD (__stdcall *)(LPWSTR, DWORD, void *))
3967 GetProcAddress(hNetApi32, "NetWkstaGetInfo");
3970 if (hNetApi32 && pfnNetWkstaGetInfo && pfnNetApiBufferFree) {
3971 /* this way is more reliable, in case user has a local account. */
3973 DWORD dnamelen = sizeof(dname);
3975 DWORD wki100_platform_id;
3976 LPWSTR wki100_computername;
3977 LPWSTR wki100_langroup;
3978 DWORD wki100_ver_major;
3979 DWORD wki100_ver_minor;
3981 /* NERR_Success *is* 0*/
3982 if (0 == pfnNetWkstaGetInfo(NULL, 100, &pwi)) {
3983 if (pwi->wki100_langroup && *(pwi->wki100_langroup)) {
3984 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_langroup,
3985 -1, (LPSTR)dname, dnamelen, NULL, NULL);
3988 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_computername,
3989 -1, (LPSTR)dname, dnamelen, NULL, NULL);
3991 pfnNetApiBufferFree(pwi);
3992 FreeLibrary(hNetApi32);
3995 FreeLibrary(hNetApi32);
3998 /* Win95 doesn't have NetWksta*(), so do it the old way */
4000 DWORD size = sizeof(name);
4002 FreeLibrary(hNetApi32);
4003 if (GetUserName(name,&size)) {
4004 char sid[ONE_K_BUFSIZE];
4005 DWORD sidlen = sizeof(sid);
4007 DWORD dnamelen = sizeof(dname);
4009 if (LookupAccountName(NULL, name, (PSID)&sid, &sidlen,
4010 dname, &dnamelen, &snu)) {
4011 XSRETURN_PV(dname); /* all that for this */
4023 DWORD flags, filecomplen;
4024 if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
4025 &flags, fsname, sizeof(fsname))) {
4026 if (GIMME_V == G_ARRAY) {
4027 XPUSHs(sv_2mortal(newSVpvn(fsname,strlen(fsname))));
4028 XPUSHs(sv_2mortal(newSViv(flags)));
4029 XPUSHs(sv_2mortal(newSViv(filecomplen)));
4034 XSRETURN_PV(fsname);
4040 XS(w32_GetOSVersion)
4043 OSVERSIONINFOA osver;
4046 OSVERSIONINFOW osverw;
4047 char szCSDVersion[sizeof(osverw.szCSDVersion)];
4048 osverw.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
4049 if (!GetVersionExW(&osverw)) {
4052 W2AHELPER(osverw.szCSDVersion, szCSDVersion, sizeof(szCSDVersion));
4053 XPUSHs(newSVpvn(szCSDVersion, strlen(szCSDVersion)));
4054 osver.dwMajorVersion = osverw.dwMajorVersion;
4055 osver.dwMinorVersion = osverw.dwMinorVersion;
4056 osver.dwBuildNumber = osverw.dwBuildNumber;
4057 osver.dwPlatformId = osverw.dwPlatformId;
4060 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOA);
4061 if (!GetVersionExA(&osver)) {
4064 XPUSHs(newSVpvn(osver.szCSDVersion, strlen(osver.szCSDVersion)));
4066 XPUSHs(newSViv(osver.dwMajorVersion));
4067 XPUSHs(newSViv(osver.dwMinorVersion));
4068 XPUSHs(newSViv(osver.dwBuildNumber));
4069 XPUSHs(newSViv(osver.dwPlatformId));
4078 XSRETURN_IV(IsWinNT());
4086 XSRETURN_IV(IsWin95());
4090 XS(w32_FormatMessage)
4094 char msgbuf[ONE_K_BUFSIZE];
4097 Perl_croak(aTHX_ "usage: Win32::FormatMessage($errno)");
4100 WCHAR wmsgbuf[ONE_K_BUFSIZE];
4101 if (FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM,
4102 &source, SvIV(ST(0)), 0,
4103 wmsgbuf, ONE_K_BUFSIZE-1, NULL))
4105 W2AHELPER(wmsgbuf, msgbuf, sizeof(msgbuf));
4106 XSRETURN_PV(msgbuf);
4110 if (FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM,
4111 &source, SvIV(ST(0)), 0,
4112 msgbuf, sizeof(msgbuf)-1, NULL))
4113 XSRETURN_PV(msgbuf);
4126 PROCESS_INFORMATION stProcInfo;
4127 STARTUPINFO stStartInfo;
4128 BOOL bSuccess = FALSE;
4131 Perl_croak(aTHX_ "usage: Win32::Spawn($cmdName, $args, $PID)");
4133 cmd = SvPV_nolen(ST(0));
4134 args = SvPV_nolen(ST(1));
4136 env = PerlEnv_get_childenv();
4137 dir = PerlEnv_get_childdir();
4139 memset(&stStartInfo, 0, sizeof(stStartInfo)); /* Clear the block */
4140 stStartInfo.cb = sizeof(stStartInfo); /* Set the structure size */
4141 stStartInfo.dwFlags = STARTF_USESHOWWINDOW; /* Enable wShowWindow control */
4142 stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE; /* Start min (normal) */
4145 cmd, /* Image path */
4146 args, /* Arguments for command line */
4147 NULL, /* Default process security */
4148 NULL, /* Default thread security */
4149 FALSE, /* Must be TRUE to use std handles */
4150 NORMAL_PRIORITY_CLASS, /* No special scheduling */
4151 env, /* Inherit our environment block */
4152 dir, /* Inherit our currrent directory */
4153 &stStartInfo, /* -> Startup info */
4154 &stProcInfo)) /* <- Process info (if OK) */
4156 int pid = (int)stProcInfo.dwProcessId;
4157 if (IsWin95() && pid < 0)
4159 sv_setiv(ST(2), pid);
4160 CloseHandle(stProcInfo.hThread);/* library source code does this. */
4163 PerlEnv_free_childenv(env);
4164 PerlEnv_free_childdir(dir);
4165 XSRETURN_IV(bSuccess);
4169 XS(w32_GetTickCount)
4172 DWORD msec = GetTickCount();
4180 XS(w32_GetShortPathName)
4187 Perl_croak(aTHX_ "usage: Win32::GetShortPathName($longPathName)");
4189 shortpath = sv_mortalcopy(ST(0));
4190 SvUPGRADE(shortpath, SVt_PV);
4191 if (!SvPVX(shortpath) || !SvLEN(shortpath))
4194 /* src == target is allowed */
4196 len = GetShortPathName(SvPVX(shortpath),
4199 } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
4201 SvCUR_set(shortpath,len);
4209 XS(w32_GetFullPathName)
4218 Perl_croak(aTHX_ "usage: Win32::GetFullPathName($filename)");
4221 fullpath = sv_mortalcopy(filename);
4222 SvUPGRADE(fullpath, SVt_PV);
4223 if (!SvPVX(fullpath) || !SvLEN(fullpath))
4227 len = GetFullPathName(SvPVX(filename),
4231 } while (len >= SvLEN(fullpath) && sv_grow(fullpath,len+1));
4233 if (GIMME_V == G_ARRAY) {
4235 XST_mPV(1,filepart);
4236 len = filepart - SvPVX(fullpath);
4239 SvCUR_set(fullpath,len);
4247 XS(w32_GetLongPathName)
4251 char tmpbuf[MAX_PATH+1];
4256 Perl_croak(aTHX_ "usage: Win32::GetLongPathName($pathname)");
4259 pathstr = SvPV(path,len);
4260 strcpy(tmpbuf, pathstr);
4261 pathstr = win32_longpath(tmpbuf);
4263 ST(0) = sv_2mortal(newSVpvn(pathstr, strlen(pathstr)));
4274 Perl_croak(aTHX_ "usage: Win32::Sleep($milliseconds)");
4285 Perl_croak(aTHX_ "usage: Win32::CopyFile($from, $to, $overwrite)");
4287 WCHAR wSourceFile[MAX_PATH+1];
4288 WCHAR wDestFile[MAX_PATH+1];
4289 A2WHELPER(SvPV_nolen(ST(0)), wSourceFile, sizeof(wSourceFile));
4290 wcscpy(wSourceFile, PerlDir_mapW(wSourceFile));
4291 A2WHELPER(SvPV_nolen(ST(1)), wDestFile, sizeof(wDestFile));
4292 bResult = CopyFileW(wSourceFile, PerlDir_mapW(wDestFile), !SvTRUE(ST(2)));
4295 char szSourceFile[MAX_PATH+1];
4296 strcpy(szSourceFile, PerlDir_mapA(SvPV_nolen(ST(0))));
4297 bResult = CopyFileA(szSourceFile, PerlDir_mapA(SvPV_nolen(ST(1))), !SvTRUE(ST(2)));
4306 Perl_init_os_extras(void)
4309 char *file = __FILE__;
4312 /* these names are Activeware compatible */
4313 newXS("Win32::GetCwd", w32_GetCwd, file);
4314 newXS("Win32::SetCwd", w32_SetCwd, file);
4315 newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
4316 newXS("Win32::GetLastError", w32_GetLastError, file);
4317 newXS("Win32::SetLastError", w32_SetLastError, file);
4318 newXS("Win32::LoginName", w32_LoginName, file);
4319 newXS("Win32::NodeName", w32_NodeName, file);
4320 newXS("Win32::DomainName", w32_DomainName, file);
4321 newXS("Win32::FsType", w32_FsType, file);
4322 newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
4323 newXS("Win32::IsWinNT", w32_IsWinNT, file);
4324 newXS("Win32::IsWin95", w32_IsWin95, file);
4325 newXS("Win32::FormatMessage", w32_FormatMessage, file);
4326 newXS("Win32::Spawn", w32_Spawn, file);
4327 newXS("Win32::GetTickCount", w32_GetTickCount, file);
4328 newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
4329 newXS("Win32::GetFullPathName", w32_GetFullPathName, file);
4330 newXS("Win32::GetLongPathName", w32_GetLongPathName, file);
4331 newXS("Win32::CopyFile", w32_CopyFile, file);
4332 newXS("Win32::Sleep", w32_Sleep, file);
4334 /* XXX Bloat Alert! The following Activeware preloads really
4335 * ought to be part of Win32::Sys::*, so they're not included
4338 /* LookupAccountName
4340 * InitiateSystemShutdown
4341 * AbortSystemShutdown
4342 * ExpandEnvrironmentStrings
4347 Perl_win32_init(int *argcp, char ***argvp)
4349 /* Disable floating point errors, Perl will trap the ones we
4350 * care about. VC++ RTL defaults to switching these off
4351 * already, but the Borland RTL doesn't. Since we don't
4352 * want to be at the vendor's whim on the default, we set
4353 * it explicitly here.
4355 #if !defined(_ALPHA_) && !defined(__GNUC__)
4356 _control87(MCW_EM, MCW_EM);
4362 win32_get_child_IO(child_IO_table* ptbl)
4364 ptbl->childStdIn = GetStdHandle(STD_INPUT_HANDLE);
4365 ptbl->childStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
4366 ptbl->childStdErr = GetStdHandle(STD_ERROR_HANDLE);
4369 #ifdef HAVE_INTERP_INTERN
4372 Perl_sys_intern_init(pTHX)
4374 w32_perlshell_tokens = Nullch;
4375 w32_perlshell_vec = (char**)NULL;
4376 w32_perlshell_items = 0;
4377 w32_fdpid = newAV();
4378 New(1313, w32_children, 1, child_tab);
4379 w32_num_children = 0;
4380 # ifdef USE_ITHREADS
4382 New(1313, w32_pseudo_children, 1, child_tab);
4383 w32_num_pseudo_children = 0;
4385 w32_init_socktype = 0;
4389 Perl_sys_intern_clear(pTHX)
4391 Safefree(w32_perlshell_tokens);
4392 Safefree(w32_perlshell_vec);
4393 /* NOTE: w32_fdpid is freed by sv_clean_all() */
4394 Safefree(w32_children);
4395 # ifdef USE_ITHREADS
4396 Safefree(w32_pseudo_children);
4400 # ifdef USE_ITHREADS
4403 Perl_sys_intern_dup(pTHX_ struct interp_intern *src, struct interp_intern *dst)
4405 dst->perlshell_tokens = Nullch;
4406 dst->perlshell_vec = (char**)NULL;
4407 dst->perlshell_items = 0;
4408 dst->fdpid = newAV();
4409 Newz(1313, dst->children, 1, child_tab);
4411 Newz(1313, dst->pseudo_children, 1, child_tab);
4412 dst->thr_intern.Winit_socktype = 0;
4414 # endif /* USE_ITHREADS */
4415 #endif /* HAVE_INTERP_INTERN */
4418 win32_free_argvw(pTHX_ void *ptr)
4420 char** argv = (char**)ptr;
4428 win32_argv2utf8(int argc, char** argv)
4433 LPWSTR* lpwStr = CommandLineToArgvW(GetCommandLineW(), &wargc);
4434 if (lpwStr && argc) {
4436 length = WideCharToMultiByte(CP_UTF8, 0, lpwStr[--wargc], -1, NULL, 0, NULL, NULL);
4437 Newz(0, psz, length, char);
4438 WideCharToMultiByte(CP_UTF8, 0, lpwStr[wargc], -1, psz, length, NULL, NULL);
4441 call_atexit(win32_free_argvw, argv);
4443 GlobalFree((HGLOBAL)lpwStr);