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
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 #define PERLIO_NOT_STDIO 0
29 #if !defined(PERLIO_IS_STDIO) && !defined(USE_SFIO)
38 #define PERL_NO_GET_CONTEXT
44 /* assert.h conflicts with #define of assert in perl.h */
51 #if defined(_MSC_VER) || defined(__MINGW32__)
52 #include <sys/utime.h>
57 /* Mingw32 defaults to globing command line
58 * So we turn it off like this:
63 #if defined(__MINGW32__)
64 /* Mingw32 is missing some prototypes */
65 FILE * _wfopen(LPCWSTR wszFileName, LPCWSTR wszMode);
66 FILE * _wfdopen(int nFd, LPCWSTR wszMode);
67 FILE * _freopen(LPCWSTR wszFileName, LPCWSTR wszMode, FILE * pOldStream);
72 #if defined(__BORLANDC__)
74 # define _utimbuf utimbuf
79 #define EXECF_SPAWN_NOWAIT 3
81 #if defined(PERL_IMPLICIT_SYS)
82 # undef win32_get_privlib
83 # define win32_get_privlib g_win32_get_privlib
84 # undef win32_get_sitelib
85 # define win32_get_sitelib g_win32_get_sitelib
86 # undef win32_get_vendorlib
87 # define win32_get_vendorlib g_win32_get_vendorlib
89 # define do_spawn g_do_spawn
91 # define getlogin g_getlogin
94 static void get_shell(void);
95 static long tokenize(const char *str, char **dest, char ***destv);
96 int do_spawn2(char *cmd, int exectype);
97 static BOOL has_shell_metachars(char *ptr);
98 static long filetime_to_clock(PFILETIME ft);
99 static BOOL filetime_from_time(PFILETIME ft, time_t t);
100 static char * get_emd_part(SV **leading, char *trailing, ...);
101 static void remove_dead_process(long deceased);
102 static long find_pid(int pid);
103 static char * qualified_path(const char *cmd);
104 static char * win32_get_xlib(const char *pl, const char *xlib,
105 const char *libname);
108 static void remove_dead_pseudo_process(long child);
109 static long find_pseudo_pid(int pid);
113 HANDLE w32_perldll_handle = INVALID_HANDLE_VALUE;
114 char w32_module_name[MAX_PATH+1];
117 static DWORD w32_platform = (DWORD)-1;
119 #define ONE_K_BUFSIZE 1024
124 return (win32_os_id() == VER_PLATFORM_WIN32_WINDOWS);
130 return (win32_os_id() == VER_PLATFORM_WIN32_NT);
134 set_w32_module_name(void)
137 GetModuleFileName((HMODULE)((w32_perldll_handle == INVALID_HANDLE_VALUE)
138 ? GetModuleHandle(NULL)
139 : w32_perldll_handle),
140 w32_module_name, sizeof(w32_module_name));
142 /* try to get full path to binary (which may be mangled when perl is
143 * run from a 16-bit app) */
144 /*PerlIO_printf(Perl_debug_log, "Before %s\n", w32_module_name);*/
145 (void)win32_longpath(w32_module_name);
146 /*PerlIO_printf(Perl_debug_log, "After %s\n", w32_module_name);*/
148 /* normalize to forward slashes */
149 ptr = w32_module_name;
157 /* *svp (if non-NULL) is expected to be POK (valid allocated SvPVX(*svp)) */
159 get_regstr_from(HKEY hkey, const char *valuename, SV **svp)
161 /* Retrieve a REG_SZ or REG_EXPAND_SZ from the registry */
164 const char *subkey = "Software\\Perl";
168 retval = RegOpenKeyEx(hkey, subkey, 0, KEY_READ, &handle);
169 if (retval == ERROR_SUCCESS) {
171 retval = RegQueryValueEx(handle, valuename, 0, &type, NULL, &datalen);
172 if (retval == ERROR_SUCCESS
173 && (type == REG_SZ || type == REG_EXPAND_SZ))
177 *svp = sv_2mortal(newSVpvn("",0));
178 SvGROW(*svp, datalen);
179 retval = RegQueryValueEx(handle, valuename, 0, NULL,
180 (PBYTE)SvPVX(*svp), &datalen);
181 if (retval == ERROR_SUCCESS) {
183 SvCUR_set(*svp,datalen-1);
191 /* *svp (if non-NULL) is expected to be POK (valid allocated SvPVX(*svp)) */
193 get_regstr(const char *valuename, SV **svp)
195 char *str = get_regstr_from(HKEY_CURRENT_USER, valuename, svp);
197 str = get_regstr_from(HKEY_LOCAL_MACHINE, valuename, svp);
201 /* *prev_pathp (if non-NULL) is expected to be POK (valid allocated SvPVX(sv)) */
203 get_emd_part(SV **prev_pathp, char *trailing_path, ...)
207 char mod_name[MAX_PATH+1];
211 int oldsize, newsize;
214 va_start(ap, trailing_path);
215 strip = va_arg(ap, char *);
217 sprintf(base, "%d.%d", (int)PERL_REVISION, (int)PERL_VERSION);
218 baselen = strlen(base);
220 if (!*w32_module_name) {
221 set_w32_module_name();
223 strcpy(mod_name, w32_module_name);
224 ptr = strrchr(mod_name, '/');
225 while (ptr && strip) {
226 /* look for directories to skip back */
229 ptr = strrchr(mod_name, '/');
230 /* avoid stripping component if there is no slash,
231 * or it doesn't match ... */
232 if (!ptr || stricmp(ptr+1, strip) != 0) {
233 /* ... but not if component matches m|5\.$patchlevel.*| */
234 if (!ptr || !(*strip == '5' && *(ptr+1) == '5'
235 && strncmp(strip, base, baselen) == 0
236 && strncmp(ptr+1, base, baselen) == 0))
242 strip = va_arg(ap, char *);
250 strcpy(++ptr, trailing_path);
252 /* only add directory if it exists */
253 if (GetFileAttributes(mod_name) != (DWORD) -1) {
254 /* directory exists */
257 *prev_pathp = sv_2mortal(newSVpvn("",0));
258 sv_catpvn(*prev_pathp, ";", 1);
259 sv_catpv(*prev_pathp, mod_name);
260 return SvPVX(*prev_pathp);
267 win32_get_privlib(const char *pl)
270 char *stdlib = "lib";
271 char buffer[MAX_PATH+1];
274 /* $stdlib = $HKCU{"lib-$]"} || $HKLM{"lib-$]"} || $HKCU{"lib"} || $HKLM{"lib"} || ""; */
275 sprintf(buffer, "%s-%s", stdlib, pl);
276 if (!get_regstr(buffer, &sv))
277 (void)get_regstr(stdlib, &sv);
279 /* $stdlib .= ";$EMD/../../lib" */
280 return get_emd_part(&sv, stdlib, ARCHNAME, "bin", Nullch);
284 win32_get_xlib(const char *pl, const char *xlib, const char *libname)
288 char pathstr[MAX_PATH+1];
294 /* $HKCU{"$xlib-$]"} || $HKLM{"$xlib-$]"} . ---; */
295 sprintf(regstr, "%s-%s", xlib, pl);
296 (void)get_regstr(regstr, &sv1);
299 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/$libname/$]/lib"; */
300 sprintf(pathstr, "%s/%s/lib", libname, pl);
301 (void)get_emd_part(&sv1, pathstr, ARCHNAME, "bin", pl, Nullch);
303 /* $HKCU{$xlib} || $HKLM{$xlib} . ---; */
304 (void)get_regstr(xlib, &sv2);
307 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/$libname/lib"; */
308 sprintf(pathstr, "%s/lib", libname);
309 (void)get_emd_part(&sv2, pathstr, ARCHNAME, "bin", pl, Nullch);
318 sv_catpvn(sv1, ";", 1);
325 win32_get_sitelib(const char *pl)
327 return win32_get_xlib(pl, "sitelib", "site");
330 #ifndef PERL_VENDORLIB_NAME
331 # define PERL_VENDORLIB_NAME "vendor"
335 win32_get_vendorlib(const char *pl)
337 return win32_get_xlib(pl, "vendorlib", PERL_VENDORLIB_NAME);
341 has_shell_metachars(char *ptr)
347 * Scan string looking for redirection (< or >) or pipe
348 * characters (|) that are not in a quoted string.
349 * Shell variable interpolation (%VAR%) can also happen inside strings.
381 #if !defined(PERL_IMPLICIT_SYS)
382 /* since the current process environment is being updated in util.c
383 * the library functions will get the correct environment
386 Perl_my_popen(pTHX_ char *cmd, char *mode)
389 #define fixcmd(x) { \
390 char *pspace = strchr((x),' '); \
393 while (p < pspace) { \
404 PERL_FLUSHALL_FOR_CHILD;
405 return win32_popen(cmd, mode);
409 Perl_my_pclose(pTHX_ PerlIO *fp)
411 return win32_pclose(fp);
415 DllExport unsigned long
418 static OSVERSIONINFO osver;
420 if (osver.dwPlatformId != w32_platform) {
421 memset(&osver, 0, sizeof(OSVERSIONINFO));
422 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
423 GetVersionEx(&osver);
424 w32_platform = osver.dwPlatformId;
426 return (unsigned long)w32_platform;
436 return -((int)w32_pseudo_id);
439 /* Windows 9x appears to always reports a pid for threads and processes
440 * that has the high bit set. So we treat the lower 31 bits as the
441 * "real" PID for Perl's purposes. */
442 if (IsWin95() && pid < 0)
447 /* Tokenize a string. Words are null-separated, and the list
448 * ends with a doubled null. Any character (except null and
449 * including backslash) may be escaped by preceding it with a
450 * backslash (the backslash will be stripped).
451 * Returns number of words in result buffer.
454 tokenize(const char *str, char **dest, char ***destv)
456 char *retstart = Nullch;
457 char **retvstart = 0;
461 int slen = strlen(str);
463 register char **retv;
464 New(1307, ret, slen+2, char);
465 New(1308, retv, (slen+3)/2, char*);
473 if (*ret == '\\' && *str)
475 else if (*ret == ' ') {
491 retvstart[items] = Nullch;
504 if (!w32_perlshell_tokens) {
505 /* we don't use COMSPEC here for two reasons:
506 * 1. the same reason perl on UNIX doesn't use SHELL--rampant and
507 * uncontrolled unportability of the ensuing scripts.
508 * 2. PERL5SHELL could be set to a shell that may not be fit for
509 * interactive use (which is what most programs look in COMSPEC
512 const char* defaultshell = (IsWinNT()
513 ? "cmd.exe /x/c" : "command.com /c");
514 const char *usershell = PerlEnv_getenv("PERL5SHELL");
515 w32_perlshell_items = tokenize(usershell ? usershell : defaultshell,
516 &w32_perlshell_tokens,
522 do_aspawn(void *vreally, void **vmark, void **vsp)
525 SV *really = (SV*)vreally;
526 SV **mark = (SV**)vmark;
538 New(1306, argv, (sp - mark) + w32_perlshell_items + 2, char*);
540 if (SvNIOKp(*(mark+1)) && !SvPOKp(*(mark+1))) {
545 while (++mark <= sp) {
546 if (*mark && (str = SvPV_nolen(*mark)))
553 status = win32_spawnvp(flag,
554 (const char*)(really ? SvPV_nolen(really) : argv[0]),
555 (const char* const*)argv);
557 if (status < 0 && (errno == ENOEXEC || errno == ENOENT)) {
558 /* possible shell-builtin, invoke with shell */
560 sh_items = w32_perlshell_items;
562 argv[index+sh_items] = argv[index];
563 while (--sh_items >= 0)
564 argv[sh_items] = w32_perlshell_vec[sh_items];
566 status = win32_spawnvp(flag,
567 (const char*)(really ? SvPV_nolen(really) : argv[0]),
568 (const char* const*)argv);
571 if (flag == P_NOWAIT) {
573 PL_statusvalue = -1; /* >16bits hint for pp_system() */
577 if (ckWARN(WARN_EXEC))
578 Perl_warner(aTHX_ WARN_EXEC, "Can't spawn \"%s\": %s", argv[0], strerror(errno));
583 PL_statusvalue = status;
590 do_spawn2(char *cmd, int exectype)
597 BOOL needToTry = TRUE;
600 /* Save an extra exec if possible. See if there are shell
601 * metacharacters in it */
602 if (!has_shell_metachars(cmd)) {
603 New(1301,argv, strlen(cmd) / 2 + 2, char*);
604 New(1302,cmd2, strlen(cmd) + 1, char);
607 for (s = cmd2; *s;) {
608 bool in_quotes = FALSE;
609 while (*s && isSPACE(*s))
614 /* ignore doubled backslashes, or backslash+quote */
615 if (*s == '\\' && (s[1] == '\\' || s[1] == '"')) {
618 /* keep track of when we're within quotes */
619 else if (*s == '"') {
621 in_quotes = !in_quotes;
623 /* break it up only at spaces that aren't in quotes */
624 else if (!in_quotes && isSPACE(*s))
636 status = win32_spawnvp(P_WAIT, argv[0],
637 (const char* const*)argv);
639 case EXECF_SPAWN_NOWAIT:
640 status = win32_spawnvp(P_NOWAIT, argv[0],
641 (const char* const*)argv);
644 status = win32_execvp(argv[0], (const char* const*)argv);
647 if (status != -1 || errno == 0)
657 New(1306, argv, w32_perlshell_items + 2, char*);
658 while (++i < w32_perlshell_items)
659 argv[i] = w32_perlshell_vec[i];
664 status = win32_spawnvp(P_WAIT, argv[0],
665 (const char* const*)argv);
667 case EXECF_SPAWN_NOWAIT:
668 status = win32_spawnvp(P_NOWAIT, argv[0],
669 (const char* const*)argv);
672 status = win32_execvp(argv[0], (const char* const*)argv);
678 if (exectype == EXECF_SPAWN_NOWAIT) {
680 PL_statusvalue = -1; /* >16bits hint for pp_system() */
684 if (ckWARN(WARN_EXEC))
685 Perl_warner(aTHX_ WARN_EXEC, "Can't %s \"%s\": %s",
686 (exectype == EXECF_EXEC ? "exec" : "spawn"),
687 cmd, strerror(errno));
692 PL_statusvalue = status;
700 return do_spawn2(cmd, EXECF_SPAWN);
704 do_spawn_nowait(char *cmd)
706 return do_spawn2(cmd, EXECF_SPAWN_NOWAIT);
710 Perl_do_exec(pTHX_ char *cmd)
712 do_spawn2(cmd, EXECF_EXEC);
716 /* The idea here is to read all the directory names into a string table
717 * (separated by nulls) and when one of the other dir functions is called
718 * return the pointer to the current file name.
721 win32_opendir(char *filename)
727 char scanname[MAX_PATH+3];
729 WIN32_FIND_DATAA aFindData;
730 WIN32_FIND_DATAW wFindData;
732 char buffer[MAX_PATH*2];
733 WCHAR wbuffer[MAX_PATH+1];
736 len = strlen(filename);
740 /* check to see if filename is a directory */
741 if (win32_stat(filename, &sbuf) < 0 || !S_ISDIR(sbuf.st_mode))
744 /* Get us a DIR structure */
745 Newz(1303, dirp, 1, DIR);
747 /* Create the search pattern */
748 strcpy(scanname, filename);
750 /* bare drive name means look in cwd for drive */
751 if (len == 2 && isALPHA(scanname[0]) && scanname[1] == ':') {
752 scanname[len++] = '.';
753 scanname[len++] = '/';
755 else if (scanname[len-1] != '/' && scanname[len-1] != '\\') {
756 scanname[len++] = '/';
758 scanname[len++] = '*';
759 scanname[len] = '\0';
761 /* do the FindFirstFile call */
763 A2WHELPER(scanname, wbuffer, sizeof(wbuffer));
764 fh = FindFirstFileW(PerlDir_mapW(wbuffer), &wFindData);
767 fh = FindFirstFileA(PerlDir_mapA(scanname), &aFindData);
770 if (fh == INVALID_HANDLE_VALUE) {
771 DWORD err = GetLastError();
772 /* FindFirstFile() fails on empty drives! */
774 case ERROR_FILE_NOT_FOUND:
776 case ERROR_NO_MORE_FILES:
777 case ERROR_PATH_NOT_FOUND:
780 case ERROR_NOT_ENOUGH_MEMORY:
791 /* now allocate the first part of the string table for
792 * the filenames that we find.
795 W2AHELPER(wFindData.cFileName, buffer, sizeof(buffer));
799 ptr = aFindData.cFileName;
806 New(1304, dirp->start, dirp->size, char);
807 strcpy(dirp->start, ptr);
809 dirp->end = dirp->curr = dirp->start;
815 /* Readdir just returns the current string pointer and bumps the
816 * string pointer to the nDllExport entry.
818 DllExport struct direct *
819 win32_readdir(DIR *dirp)
824 /* first set up the structure to return */
825 len = strlen(dirp->curr);
826 strcpy(dirp->dirstr.d_name, dirp->curr);
827 dirp->dirstr.d_namlen = len;
830 dirp->dirstr.d_ino = dirp->curr - dirp->start;
832 /* Now set up for the next call to readdir */
833 dirp->curr += len + 1;
834 if (dirp->curr >= dirp->end) {
838 WIN32_FIND_DATAW wFindData;
839 WIN32_FIND_DATAA aFindData;
840 char buffer[MAX_PATH*2];
842 /* finding the next file that matches the wildcard
843 * (which should be all of them in this directory!).
846 res = FindNextFileW(dirp->handle, &wFindData);
848 W2AHELPER(wFindData.cFileName, buffer, sizeof(buffer));
853 res = FindNextFileA(dirp->handle, &aFindData);
855 ptr = aFindData.cFileName;
858 long endpos = dirp->end - dirp->start;
859 long newsize = endpos + strlen(ptr) + 1;
860 /* bump the string table size by enough for the
861 * new name and its null terminator */
862 while (newsize > dirp->size) {
863 long curpos = dirp->curr - dirp->start;
865 Renew(dirp->start, dirp->size, char);
866 dirp->curr = dirp->start + curpos;
868 strcpy(dirp->start + endpos, ptr);
869 dirp->end = dirp->start + newsize;
875 return &(dirp->dirstr);
881 /* Telldir returns the current string pointer position */
883 win32_telldir(DIR *dirp)
885 return (dirp->curr - dirp->start);
889 /* Seekdir moves the string pointer to a previously saved position
890 * (returned by telldir).
893 win32_seekdir(DIR *dirp, long loc)
895 dirp->curr = dirp->start + loc;
898 /* Rewinddir resets the string pointer to the start */
900 win32_rewinddir(DIR *dirp)
902 dirp->curr = dirp->start;
905 /* free the memory allocated by opendir */
907 win32_closedir(DIR *dirp)
910 if (dirp->handle != INVALID_HANDLE_VALUE)
911 FindClose(dirp->handle);
912 Safefree(dirp->start);
925 * Just pretend that everyone is a superuser. NT will let us know if
926 * we don\'t really have permission to do something.
929 #define ROOT_UID ((uid_t)0)
930 #define ROOT_GID ((gid_t)0)
959 return (auid == ROOT_UID ? 0 : -1);
965 return (agid == ROOT_GID ? 0 : -1);
972 char *buf = w32_getlogin_buffer;
973 DWORD size = sizeof(w32_getlogin_buffer);
974 if (GetUserName(buf,&size))
980 chown(const char *path, uid_t owner, gid_t group)
987 * XXX this needs strengthening (for PerlIO)
990 int mkstemp(const char *path)
993 char buf[MAX_PATH+1];
997 if (i++ > 10) { /* give up */
1001 if (!GetTempFileNameA((LPCSTR)path, "plr", 1, buf)) {
1005 fd = PerlLIO_open3(buf, O_CREAT|O_RDWR|O_EXCL, 0600);
1015 long child = w32_num_children;
1016 while (--child >= 0) {
1017 if (w32_child_pids[child] == pid)
1024 remove_dead_process(long child)
1028 CloseHandle(w32_child_handles[child]);
1029 Move(&w32_child_handles[child+1], &w32_child_handles[child],
1030 (w32_num_children-child-1), HANDLE);
1031 Move(&w32_child_pids[child+1], &w32_child_pids[child],
1032 (w32_num_children-child-1), DWORD);
1039 find_pseudo_pid(int pid)
1042 long child = w32_num_pseudo_children;
1043 while (--child >= 0) {
1044 if (w32_pseudo_child_pids[child] == pid)
1051 remove_dead_pseudo_process(long child)
1055 CloseHandle(w32_pseudo_child_handles[child]);
1056 Move(&w32_pseudo_child_handles[child+1], &w32_pseudo_child_handles[child],
1057 (w32_num_pseudo_children-child-1), HANDLE);
1058 Move(&w32_pseudo_child_pids[child+1], &w32_pseudo_child_pids[child],
1059 (w32_num_pseudo_children-child-1), DWORD);
1060 w32_num_pseudo_children--;
1066 win32_kill(int pid, int sig)
1073 /* it is a pseudo-forked child */
1074 child = find_pseudo_pid(-pid);
1078 hProcess = w32_pseudo_child_handles[child];
1079 if (TerminateThread(hProcess, sig)) {
1080 remove_dead_pseudo_process(child);
1084 else if (IsWin95()) {
1092 child = find_pid(pid);
1096 hProcess = w32_child_handles[child];
1097 if (TerminateProcess(hProcess, sig)) {
1098 remove_dead_process(child);
1104 hProcess = OpenProcess(PROCESS_ALL_ACCESS, TRUE,
1105 (IsWin95() ? -pid : pid));
1109 if (TerminateProcess(hProcess, sig)) {
1110 CloseHandle(hProcess);
1124 DllExport unsigned int
1125 win32_sleep(unsigned int t)
1132 win32_stat(const char *path, struct stat *sbuf)
1135 char buffer[MAX_PATH+1];
1136 int l = strlen(path);
1138 WCHAR wbuffer[MAX_PATH+1];
1144 switch(path[l - 1]) {
1145 /* FindFirstFile() and stat() are buggy with a trailing
1146 * backslash, so change it to a forward slash :-( */
1148 strncpy(buffer, path, l-1);
1149 buffer[l - 1] = '/';
1153 /* FindFirstFile() is buggy with "x:", so add a dot :-( */
1155 if (l == 2 && isALPHA(path[0])) {
1156 buffer[0] = path[0];
1167 /* We *must* open & close the file once; otherwise file attribute changes */
1168 /* might not yet have propagated to "other" hard links of the same file. */
1169 /* This also gives us an opportunity to determine the number of links. */
1171 A2WHELPER(path, wbuffer, sizeof(wbuffer));
1172 pwbuffer = PerlDir_mapW(wbuffer);
1173 handle = CreateFileW(pwbuffer, 0, 0, NULL, OPEN_EXISTING, 0, NULL);
1176 path = PerlDir_mapA(path);
1178 handle = CreateFileA(path, 0, 0, NULL, OPEN_EXISTING, 0, NULL);
1180 if (handle != INVALID_HANDLE_VALUE) {
1181 BY_HANDLE_FILE_INFORMATION bhi;
1182 if (GetFileInformationByHandle(handle, &bhi))
1183 nlink = bhi.nNumberOfLinks;
1184 CloseHandle(handle);
1187 /* pwbuffer or path will be mapped correctly above */
1189 res = _wstat(pwbuffer, (struct _stat *)sbuf);
1192 res = stat(path, sbuf);
1194 sbuf->st_nlink = nlink;
1197 /* CRT is buggy on sharenames, so make sure it really isn't.
1198 * XXX using GetFileAttributesEx() will enable us to set
1199 * sbuf->st_*time (but note that's not available on the
1200 * Windows of 1995) */
1203 r = GetFileAttributesW(pwbuffer);
1206 r = GetFileAttributesA(path);
1208 if (r != 0xffffffff && (r & FILE_ATTRIBUTE_DIRECTORY)) {
1209 /* sbuf may still contain old garbage since stat() failed */
1210 Zero(sbuf, 1, struct stat);
1211 sbuf->st_mode = S_IFDIR | S_IREAD;
1213 if (!(r & FILE_ATTRIBUTE_READONLY))
1214 sbuf->st_mode |= S_IWRITE | S_IEXEC;
1219 if (l == 3 && isALPHA(path[0]) && path[1] == ':'
1220 && (path[2] == '\\' || path[2] == '/'))
1222 /* The drive can be inaccessible, some _stat()s are buggy */
1224 ? !GetVolumeInformationW(pwbuffer,NULL,0,NULL,NULL,NULL,NULL,0)
1225 : !GetVolumeInformationA(path,NULL,0,NULL,NULL,NULL,NULL,0)) {
1231 if (S_ISDIR(sbuf->st_mode))
1232 sbuf->st_mode |= S_IWRITE | S_IEXEC;
1233 else if (S_ISREG(sbuf->st_mode)) {
1235 if (l >= 4 && path[l-4] == '.') {
1236 const char *e = path + l - 3;
1237 if (strnicmp(e,"exe",3)
1238 && strnicmp(e,"bat",3)
1239 && strnicmp(e,"com",3)
1240 && (IsWin95() || strnicmp(e,"cmd",3)))
1241 sbuf->st_mode &= ~S_IEXEC;
1243 sbuf->st_mode |= S_IEXEC;
1246 sbuf->st_mode &= ~S_IEXEC;
1247 /* Propagate permissions to _group_ and _others_ */
1248 perms = sbuf->st_mode & (S_IREAD|S_IWRITE|S_IEXEC);
1249 sbuf->st_mode |= (perms>>3) | (perms>>6);
1256 /* Find the longname of a given path. path is destructively modified.
1257 * It should have space for at least MAX_PATH characters. */
1259 win32_longpath(char *path)
1261 WIN32_FIND_DATA fdata;
1263 char tmpbuf[MAX_PATH+1];
1264 char *tmpstart = tmpbuf;
1271 if (isALPHA(path[0]) && path[1] == ':' &&
1272 (path[2] == '/' || path[2] == '\\'))
1275 *tmpstart++ = path[0];
1279 else if ((path[0] == '/' || path[0] == '\\') &&
1280 (path[1] == '/' || path[1] == '\\'))
1283 *tmpstart++ = path[0];
1284 *tmpstart++ = path[1];
1285 /* copy machine name */
1286 while (*start && *start != '/' && *start != '\\')
1287 *tmpstart++ = *start++;
1289 *tmpstart++ = *start;
1291 /* copy share name */
1292 while (*start && *start != '/' && *start != '\\')
1293 *tmpstart++ = *start++;
1297 if (sep == '/' || sep == '\\')
1301 /* walk up to slash */
1302 while (*start && *start != '/' && *start != '\\')
1305 /* discard doubled slashes */
1306 while (*start && (start[1] == '/' || start[1] == '\\'))
1310 /* stop and find full name of component */
1312 fhand = FindFirstFile(path,&fdata);
1313 if (fhand != INVALID_HANDLE_VALUE) {
1314 strcpy(tmpstart, fdata.cFileName);
1315 tmpstart += strlen(fdata.cFileName);
1323 /* failed a step, just return without side effects */
1324 /*PerlIO_printf(Perl_debug_log, "Failed to find %s\n", path);*/
1329 strcpy(path,tmpbuf);
1334 win32_getenv(const char *name)
1337 WCHAR wBuffer[MAX_PATH+1];
1339 SV *curitem = Nullsv;
1342 A2WHELPER(name, wBuffer, sizeof(wBuffer));
1343 needlen = GetEnvironmentVariableW(wBuffer, NULL, 0);
1346 needlen = GetEnvironmentVariableA(name,NULL,0);
1348 curitem = sv_2mortal(newSVpvn("", 0));
1352 SvGROW(curitem, (needlen+1)*sizeof(WCHAR));
1353 needlen = GetEnvironmentVariableW(wBuffer,
1354 (WCHAR*)SvPVX(curitem),
1356 } while (needlen >= SvLEN(curitem)/sizeof(WCHAR));
1357 SvCUR_set(curitem, (needlen*sizeof(WCHAR))+1);
1358 acuritem = sv_2mortal(newSVsv(curitem));
1359 W2AHELPER((WCHAR*)SvPVX(acuritem), SvPVX(curitem), SvCUR(curitem));
1363 SvGROW(curitem, needlen+1);
1364 needlen = GetEnvironmentVariableA(name,SvPVX(curitem),
1366 } while (needlen >= SvLEN(curitem));
1367 SvCUR_set(curitem, needlen);
1371 /* allow any environment variables that begin with 'PERL'
1372 to be stored in the registry */
1373 if (strncmp(name, "PERL", 4) == 0)
1374 (void)get_regstr(name, &curitem);
1376 if (curitem && SvCUR(curitem))
1377 return SvPVX(curitem);
1383 win32_putenv(const char *name)
1390 int length, relval = -1;
1394 length = strlen(name)+1;
1395 New(1309,wCuritem,length,WCHAR);
1396 A2WHELPER(name, wCuritem, length*sizeof(WCHAR));
1397 wVal = wcschr(wCuritem, '=');
1400 if (SetEnvironmentVariableW(wCuritem, *wVal ? wVal : NULL))
1406 New(1309,curitem,strlen(name)+1,char);
1407 strcpy(curitem, name);
1408 val = strchr(curitem, '=');
1410 /* The sane way to deal with the environment.
1411 * Has these advantages over putenv() & co.:
1412 * * enables us to store a truly empty value in the
1413 * environment (like in UNIX).
1414 * * we don't have to deal with RTL globals, bugs and leaks.
1416 * Why you may want to enable USE_WIN32_RTL_ENV:
1417 * * environ[] and RTL functions will not reflect changes,
1418 * which might be an issue if extensions want to access
1419 * the env. via RTL. This cuts both ways, since RTL will
1420 * not see changes made by extensions that call the Win32
1421 * functions directly, either.
1425 if (SetEnvironmentVariableA(curitem, *val ? val : NULL))
1435 filetime_to_clock(PFILETIME ft)
1437 __int64 qw = ft->dwHighDateTime;
1439 qw |= ft->dwLowDateTime;
1440 qw /= 10000; /* File time ticks at 0.1uS, clock at 1mS */
1445 win32_times(struct tms *timebuf)
1450 if (GetProcessTimes(GetCurrentProcess(), &dummy, &dummy,
1452 timebuf->tms_utime = filetime_to_clock(&user);
1453 timebuf->tms_stime = filetime_to_clock(&kernel);
1454 timebuf->tms_cutime = 0;
1455 timebuf->tms_cstime = 0;
1458 /* That failed - e.g. Win95 fallback to clock() */
1459 clock_t t = clock();
1460 timebuf->tms_utime = t;
1461 timebuf->tms_stime = 0;
1462 timebuf->tms_cutime = 0;
1463 timebuf->tms_cstime = 0;
1468 /* fix utime() so it works on directories in NT */
1470 filetime_from_time(PFILETIME pFileTime, time_t Time)
1472 struct tm *pTM = localtime(&Time);
1473 SYSTEMTIME SystemTime;
1479 SystemTime.wYear = pTM->tm_year + 1900;
1480 SystemTime.wMonth = pTM->tm_mon + 1;
1481 SystemTime.wDay = pTM->tm_mday;
1482 SystemTime.wHour = pTM->tm_hour;
1483 SystemTime.wMinute = pTM->tm_min;
1484 SystemTime.wSecond = pTM->tm_sec;
1485 SystemTime.wMilliseconds = 0;
1487 return SystemTimeToFileTime(&SystemTime, &LocalTime) &&
1488 LocalFileTimeToFileTime(&LocalTime, pFileTime);
1492 win32_unlink(const char *filename)
1499 WCHAR wBuffer[MAX_PATH+1];
1502 A2WHELPER(filename, wBuffer, sizeof(wBuffer));
1503 pwBuffer = PerlDir_mapW(wBuffer);
1504 attrs = GetFileAttributesW(pwBuffer);
1505 if (attrs == 0xFFFFFFFF)
1507 if (attrs & FILE_ATTRIBUTE_READONLY) {
1508 (void)SetFileAttributesW(pwBuffer, attrs & ~FILE_ATTRIBUTE_READONLY);
1509 ret = _wunlink(pwBuffer);
1511 (void)SetFileAttributesW(pwBuffer, attrs);
1514 ret = _wunlink(pwBuffer);
1517 filename = PerlDir_mapA(filename);
1518 attrs = GetFileAttributesA(filename);
1519 if (attrs == 0xFFFFFFFF)
1521 if (attrs & FILE_ATTRIBUTE_READONLY) {
1522 (void)SetFileAttributesA(filename, attrs & ~FILE_ATTRIBUTE_READONLY);
1523 ret = unlink(filename);
1525 (void)SetFileAttributesA(filename, attrs);
1528 ret = unlink(filename);
1537 win32_utime(const char *filename, struct utimbuf *times)
1544 struct utimbuf TimeBuffer;
1545 WCHAR wbuffer[MAX_PATH+1];
1550 A2WHELPER(filename, wbuffer, sizeof(wbuffer));
1551 pwbuffer = PerlDir_mapW(wbuffer);
1552 rc = _wutime(pwbuffer, (struct _utimbuf*)times);
1555 filename = PerlDir_mapA(filename);
1556 rc = utime(filename, times);
1558 /* EACCES: path specifies directory or readonly file */
1559 if (rc == 0 || errno != EACCES /* || !IsWinNT() */)
1562 if (times == NULL) {
1563 times = &TimeBuffer;
1564 time(×->actime);
1565 times->modtime = times->actime;
1568 /* This will (and should) still fail on readonly files */
1570 handle = CreateFileW(pwbuffer, GENERIC_READ | GENERIC_WRITE,
1571 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1572 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1575 handle = CreateFileA(filename, GENERIC_READ | GENERIC_WRITE,
1576 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1577 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1579 if (handle == INVALID_HANDLE_VALUE)
1582 if (GetFileTime(handle, &ftCreate, &ftAccess, &ftWrite) &&
1583 filetime_from_time(&ftAccess, times->actime) &&
1584 filetime_from_time(&ftWrite, times->modtime) &&
1585 SetFileTime(handle, &ftCreate, &ftAccess, &ftWrite))
1590 CloseHandle(handle);
1595 win32_uname(struct utsname *name)
1597 struct hostent *hep;
1598 STRLEN nodemax = sizeof(name->nodename)-1;
1599 OSVERSIONINFO osver;
1601 memset(&osver, 0, sizeof(OSVERSIONINFO));
1602 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1603 if (GetVersionEx(&osver)) {
1605 switch (osver.dwPlatformId) {
1606 case VER_PLATFORM_WIN32_WINDOWS:
1607 strcpy(name->sysname, "Windows");
1609 case VER_PLATFORM_WIN32_NT:
1610 strcpy(name->sysname, "Windows NT");
1612 case VER_PLATFORM_WIN32s:
1613 strcpy(name->sysname, "Win32s");
1616 strcpy(name->sysname, "Win32 Unknown");
1621 sprintf(name->release, "%d.%d",
1622 osver.dwMajorVersion, osver.dwMinorVersion);
1625 sprintf(name->version, "Build %d",
1626 osver.dwPlatformId == VER_PLATFORM_WIN32_NT
1627 ? osver.dwBuildNumber : (osver.dwBuildNumber & 0xffff));
1628 if (osver.szCSDVersion[0]) {
1629 char *buf = name->version + strlen(name->version);
1630 sprintf(buf, " (%s)", osver.szCSDVersion);
1634 *name->sysname = '\0';
1635 *name->version = '\0';
1636 *name->release = '\0';
1640 hep = win32_gethostbyname("localhost");
1642 STRLEN len = strlen(hep->h_name);
1643 if (len <= nodemax) {
1644 strcpy(name->nodename, hep->h_name);
1647 strncpy(name->nodename, hep->h_name, nodemax);
1648 name->nodename[nodemax] = '\0';
1653 if (!GetComputerName(name->nodename, &sz))
1654 *name->nodename = '\0';
1657 /* machine (architecture) */
1661 GetSystemInfo(&info);
1663 #if (defined(__BORLANDC__)&&(__BORLANDC__<=0x520)) \
1664 || (defined(__MINGW32__) && !defined(_ANONYMOUS_UNION))
1665 switch (info.u.s.wProcessorArchitecture) {
1667 switch (info.wProcessorArchitecture) {
1669 case PROCESSOR_ARCHITECTURE_INTEL:
1670 arch = "x86"; break;
1671 case PROCESSOR_ARCHITECTURE_MIPS:
1672 arch = "mips"; break;
1673 case PROCESSOR_ARCHITECTURE_ALPHA:
1674 arch = "alpha"; break;
1675 case PROCESSOR_ARCHITECTURE_PPC:
1676 arch = "ppc"; break;
1678 arch = "unknown"; break;
1680 strcpy(name->machine, arch);
1686 win32_waitpid(int pid, int *status, int flags)
1689 DWORD timeout = (flags & WNOHANG) ? 0 : INFINITE;
1692 if (pid == -1) /* XXX threadid == 1 ? */
1693 return win32_wait(status);
1696 child = find_pseudo_pid(-pid);
1698 HANDLE hThread = w32_pseudo_child_handles[child];
1699 DWORD waitcode = WaitForSingleObject(hThread, timeout);
1700 if (waitcode == WAIT_TIMEOUT) {
1703 else if (waitcode != WAIT_FAILED) {
1704 if (GetExitCodeThread(hThread, &waitcode)) {
1705 *status = (int)((waitcode & 0xff) << 8);
1706 retval = (int)w32_pseudo_child_pids[child];
1707 remove_dead_pseudo_process(child);
1714 else if (IsWin95()) {
1723 child = find_pid(pid);
1725 hProcess = w32_child_handles[child];
1726 waitcode = WaitForSingleObject(hProcess, timeout);
1727 if (waitcode == WAIT_TIMEOUT) {
1730 else if (waitcode != WAIT_FAILED) {
1731 if (GetExitCodeProcess(hProcess, &waitcode)) {
1732 *status = (int)((waitcode & 0xff) << 8);
1733 retval = (int)w32_child_pids[child];
1734 remove_dead_process(child);
1743 hProcess = OpenProcess(PROCESS_ALL_ACCESS, TRUE,
1744 (IsWin95() ? -pid : pid));
1746 waitcode = WaitForSingleObject(hProcess, timeout);
1747 if (waitcode == WAIT_TIMEOUT) {
1750 else if (waitcode != WAIT_FAILED) {
1751 if (GetExitCodeProcess(hProcess, &waitcode)) {
1752 *status = (int)((waitcode & 0xff) << 8);
1753 CloseHandle(hProcess);
1757 CloseHandle(hProcess);
1763 return retval >= 0 ? pid : retval;
1767 win32_wait(int *status)
1769 /* XXX this wait emulation only knows about processes
1770 * spawned via win32_spawnvp(P_NOWAIT, ...).
1774 DWORD exitcode, waitcode;
1777 if (w32_num_pseudo_children) {
1778 waitcode = WaitForMultipleObjects(w32_num_pseudo_children,
1779 w32_pseudo_child_handles,
1782 if (waitcode != WAIT_FAILED) {
1783 if (waitcode >= WAIT_ABANDONED_0
1784 && waitcode < WAIT_ABANDONED_0 + w32_num_pseudo_children)
1785 i = waitcode - WAIT_ABANDONED_0;
1787 i = waitcode - WAIT_OBJECT_0;
1788 if (GetExitCodeThread(w32_pseudo_child_handles[i], &exitcode)) {
1789 *status = (int)((exitcode & 0xff) << 8);
1790 retval = (int)w32_pseudo_child_pids[i];
1791 remove_dead_pseudo_process(i);
1798 if (!w32_num_children) {
1803 /* if a child exists, wait for it to die */
1804 waitcode = WaitForMultipleObjects(w32_num_children,
1808 if (waitcode != WAIT_FAILED) {
1809 if (waitcode >= WAIT_ABANDONED_0
1810 && waitcode < WAIT_ABANDONED_0 + w32_num_children)
1811 i = waitcode - WAIT_ABANDONED_0;
1813 i = waitcode - WAIT_OBJECT_0;
1814 if (GetExitCodeProcess(w32_child_handles[i], &exitcode) ) {
1815 *status = (int)((exitcode & 0xff) << 8);
1816 retval = (int)w32_child_pids[i];
1817 remove_dead_process(i);
1823 errno = GetLastError();
1827 static UINT timerid = 0;
1829 static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
1832 KillTimer(NULL,timerid);
1834 CALL_FPTR(PL_sighandlerp)(14);
1837 DllExport unsigned int
1838 win32_alarm(unsigned int sec)
1841 * the 'obvious' implentation is SetTimer() with a callback
1842 * which does whatever receiving SIGALRM would do
1843 * we cannot use SIGALRM even via raise() as it is not
1844 * one of the supported codes in <signal.h>
1846 * Snag is unless something is looking at the message queue
1847 * nothing happens :-(
1852 timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
1854 Perl_croak_nocontext("Cannot set timer");
1860 KillTimer(NULL,timerid);
1867 #ifdef HAVE_DES_FCRYPT
1868 extern char * des_fcrypt(const char *txt, const char *salt, char *cbuf);
1872 win32_crypt(const char *txt, const char *salt)
1875 #ifdef HAVE_DES_FCRYPT
1876 return des_fcrypt(txt, salt, w32_crypt_buffer);
1878 Perl_croak(aTHX_ "The crypt() function is unimplemented due to excessive paranoia.");
1883 #ifdef USE_FIXED_OSFHANDLE
1885 #define FOPEN 0x01 /* file handle open */
1886 #define FNOINHERIT 0x10 /* file handle opened O_NOINHERIT */
1887 #define FAPPEND 0x20 /* file handle opened O_APPEND */
1888 #define FDEV 0x40 /* file handle refers to device */
1889 #define FTEXT 0x80 /* file handle is in text mode */
1892 *int my_open_osfhandle(long osfhandle, int flags) - open C Runtime file handle
1895 * This function allocates a free C Runtime file handle and associates
1896 * it with the Win32 HANDLE specified by the first parameter. This is a
1897 * temperary fix for WIN95's brain damage GetFileType() error on socket
1898 * we just bypass that call for socket
1900 * This works with MSVC++ 4.0+ or GCC/Mingw32
1903 * long osfhandle - Win32 HANDLE to associate with C Runtime file handle.
1904 * int flags - flags to associate with C Runtime file handle.
1907 * returns index of entry in fh, if successful
1908 * return -1, if no free entry is found
1912 *******************************************************************************/
1915 * we fake up some parts of the CRT that aren't exported by MSVCRT.dll
1916 * this lets sockets work on Win9X with GCC and should fix the problems
1921 /* create an ioinfo entry, kill its handle, and steal the entry */
1926 HANDLE hF = CreateFile("NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
1927 int fh = _open_osfhandle((long)hF, 0);
1931 EnterCriticalSection(&(_pioinfo(fh)->lock));
1936 my_open_osfhandle(long osfhandle, int flags)
1939 char fileflags; /* _osfile flags */
1941 /* copy relevant flags from second parameter */
1944 if (flags & O_APPEND)
1945 fileflags |= FAPPEND;
1950 if (flags & O_NOINHERIT)
1951 fileflags |= FNOINHERIT;
1953 /* attempt to allocate a C Runtime file handle */
1954 if ((fh = _alloc_osfhnd()) == -1) {
1955 errno = EMFILE; /* too many open files */
1956 _doserrno = 0L; /* not an OS error */
1957 return -1; /* return error to caller */
1960 /* the file is open. now, set the info in _osfhnd array */
1961 _set_osfhnd(fh, osfhandle);
1963 fileflags |= FOPEN; /* mark as open */
1965 _osfile(fh) = fileflags; /* set osfile entry */
1966 LeaveCriticalSection(&_pioinfo(fh)->lock);
1968 return fh; /* return handle */
1971 #endif /* USE_FIXED_OSFHANDLE */
1973 /* simulate flock by locking a range on the file */
1975 #define LK_ERR(f,i) ((f) ? (i = 0) : (errno = GetLastError()))
1976 #define LK_LEN 0xffff0000
1979 win32_flock(int fd, int oper)
1987 Perl_croak_nocontext("flock() unimplemented on this platform");
1990 fh = (HANDLE)_get_osfhandle(fd);
1991 memset(&o, 0, sizeof(o));
1994 case LOCK_SH: /* shared lock */
1995 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
1997 case LOCK_EX: /* exclusive lock */
1998 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
2000 case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
2001 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
2003 case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
2004 LK_ERR(LockFileEx(fh,
2005 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
2006 0, LK_LEN, 0, &o),i);
2008 case LOCK_UN: /* unlock lock */
2009 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, 0, &o),i);
2011 default: /* unknown */
2022 * redirected io subsystem for all XS modules
2035 return (&(_environ));
2038 /* the rest are the remapped stdio routines */
2058 win32_ferror(FILE *fp)
2060 return (ferror(fp));
2065 win32_feof(FILE *fp)
2071 * Since the errors returned by the socket error function
2072 * WSAGetLastError() are not known by the library routine strerror
2073 * we have to roll our own.
2077 win32_strerror(int e)
2079 #if !defined __BORLANDC__ && !defined __MINGW32__ /* compiler intolerance */
2080 extern int sys_nerr;
2084 if (e < 0 || e > sys_nerr) {
2089 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
2090 w32_strerror_buffer,
2091 sizeof(w32_strerror_buffer), NULL) == 0)
2092 strcpy(w32_strerror_buffer, "Unknown Error");
2094 return w32_strerror_buffer;
2100 win32_str_os_error(void *sv, DWORD dwErr)
2104 dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
2105 |FORMAT_MESSAGE_IGNORE_INSERTS
2106 |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
2107 dwErr, 0, (char *)&sMsg, 1, NULL);
2108 /* strip trailing whitespace and period */
2111 --dwLen; /* dwLen doesn't include trailing null */
2112 } while (0 < dwLen && isSPACE(sMsg[dwLen]));
2113 if ('.' != sMsg[dwLen])
2118 sMsg = (char*)LocalAlloc(0, 64/**sizeof(TCHAR)*/);
2120 dwLen = sprintf(sMsg,
2121 "Unknown error #0x%lX (lookup 0x%lX)",
2122 dwErr, GetLastError());
2126 sv_setpvn((SV*)sv, sMsg, dwLen);
2132 win32_fprintf(FILE *fp, const char *format, ...)
2135 va_start(marker, format); /* Initialize variable arguments. */
2137 return (vfprintf(fp, format, marker));
2141 win32_printf(const char *format, ...)
2144 va_start(marker, format); /* Initialize variable arguments. */
2146 return (vprintf(format, marker));
2150 win32_vfprintf(FILE *fp, const char *format, va_list args)
2152 return (vfprintf(fp, format, args));
2156 win32_vprintf(const char *format, va_list args)
2158 return (vprintf(format, args));
2162 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
2164 return fread(buf, size, count, fp);
2168 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
2170 return fwrite(buf, size, count, fp);
2173 #define MODE_SIZE 10
2176 win32_fopen(const char *filename, const char *mode)
2179 WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH+1];
2185 if (stricmp(filename, "/dev/null")==0)
2189 A2WHELPER(mode, wMode, sizeof(wMode));
2190 A2WHELPER(filename, wBuffer, sizeof(wBuffer));
2191 f = _wfopen(PerlDir_mapW(wBuffer), wMode);
2194 f = fopen(PerlDir_mapA(filename), mode);
2195 /* avoid buffering headaches for child processes */
2196 if (f && *mode == 'a')
2197 win32_fseek(f, 0, SEEK_END);
2201 #ifndef USE_SOCKETS_AS_HANDLES
2203 #define fdopen my_fdopen
2207 win32_fdopen(int handle, const char *mode)
2210 WCHAR wMode[MODE_SIZE];
2213 A2WHELPER(mode, wMode, sizeof(wMode));
2214 f = _wfdopen(handle, wMode);
2217 f = fdopen(handle, (char *) mode);
2218 /* avoid buffering headaches for child processes */
2219 if (f && *mode == 'a')
2220 win32_fseek(f, 0, SEEK_END);
2225 win32_freopen(const char *path, const char *mode, FILE *stream)
2228 WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH+1];
2229 if (stricmp(path, "/dev/null")==0)
2233 A2WHELPER(mode, wMode, sizeof(wMode));
2234 A2WHELPER(path, wBuffer, sizeof(wBuffer));
2235 return _wfreopen(PerlDir_mapW(wBuffer), wMode, stream);
2237 return freopen(PerlDir_mapA(path), mode, stream);
2241 win32_fclose(FILE *pf)
2243 return my_fclose(pf); /* defined in win32sck.c */
2247 win32_fputs(const char *s,FILE *pf)
2249 return fputs(s, pf);
2253 win32_fputc(int c,FILE *pf)
2259 win32_ungetc(int c,FILE *pf)
2261 return ungetc(c,pf);
2265 win32_getc(FILE *pf)
2271 win32_fileno(FILE *pf)
2277 win32_clearerr(FILE *pf)
2284 win32_fflush(FILE *pf)
2290 win32_ftell(FILE *pf)
2296 win32_fseek(FILE *pf,long offset,int origin)
2298 return fseek(pf, offset, origin);
2302 win32_fgetpos(FILE *pf,fpos_t *p)
2304 return fgetpos(pf, p);
2308 win32_fsetpos(FILE *pf,const fpos_t *p)
2310 return fsetpos(pf, p);
2314 win32_rewind(FILE *pf)
2334 win32_fstat(int fd,struct stat *sbufptr)
2337 /* A file designated by filehandle is not shown as accessible
2338 * for write operations, probably because it is opened for reading.
2341 int rc = fstat(fd,sbufptr);
2342 BY_HANDLE_FILE_INFORMATION bhfi;
2343 if (GetFileInformationByHandle((HANDLE)_get_osfhandle(fd), &bhfi)) {
2344 sbufptr->st_mode &= 0xFE00;
2345 if (bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
2346 sbufptr->st_mode |= (S_IREAD + (S_IREAD >> 3) + (S_IREAD >> 6));
2348 sbufptr->st_mode |= ((S_IREAD|S_IWRITE) + ((S_IREAD|S_IWRITE) >> 3)
2349 + ((S_IREAD|S_IWRITE) >> 6));
2353 return my_fstat(fd,sbufptr);
2358 win32_pipe(int *pfd, unsigned int size, int mode)
2360 return _pipe(pfd, size, mode);
2364 win32_popenlist(const char *mode, IV narg, SV **args)
2367 Perl_croak(aTHX_ "List form of pipe open not implemented");
2372 * a popen() clone that respects PERL5SHELL
2374 * changed to return PerlIO* rather than FILE * by BKS, 11-11-2000
2378 win32_popen(const char *command, const char *mode)
2380 #ifdef USE_RTL_POPEN
2381 return _popen(command, mode);
2389 /* establish which ends read and write */
2390 if (strchr(mode,'w')) {
2391 stdfd = 0; /* stdin */
2395 else if (strchr(mode,'r')) {
2396 stdfd = 1; /* stdout */
2403 /* set the correct mode */
2404 if (strchr(mode,'b'))
2406 else if (strchr(mode,'t'))
2409 ourmode = _fmode & (O_TEXT | O_BINARY);
2411 /* the child doesn't inherit handles */
2412 ourmode |= O_NOINHERIT;
2414 if (win32_pipe( p, 512, ourmode) == -1)
2417 /* save current stdfd */
2418 if ((oldfd = win32_dup(stdfd)) == -1)
2421 /* make stdfd go to child end of pipe (implicitly closes stdfd) */
2422 /* stdfd will be inherited by the child */
2423 if (win32_dup2(p[child], stdfd) == -1)
2426 /* close the child end in parent */
2427 win32_close(p[child]);
2429 /* start the child */
2432 if ((childpid = do_spawn_nowait((char*)command)) == -1)
2435 /* revert stdfd to whatever it was before */
2436 if (win32_dup2(oldfd, stdfd) == -1)
2439 /* close saved handle */
2443 sv_setiv(*av_fetch(w32_fdpid, p[parent], TRUE), childpid);
2446 /* set process id so that it can be returned by perl's open() */
2447 PL_forkprocess = childpid;
2450 /* we have an fd, return a file stream */
2451 return (PerlIO_fdopen(p[parent], (char *)mode));
2454 /* we don't need to check for errors here */
2458 win32_dup2(oldfd, stdfd);
2463 #endif /* USE_RTL_POPEN */
2471 win32_pclose(PerlIO *pf)
2473 #ifdef USE_RTL_POPEN
2477 int childpid, status;
2481 sv = *av_fetch(w32_fdpid, PerlIO_fileno(pf), TRUE);
2484 childpid = SvIVX(sv);
2501 if (win32_waitpid(childpid, &status, 0) == -1)
2506 #endif /* USE_RTL_POPEN */
2512 LPCWSTR lpExistingFileName,
2513 LPSECURITY_ATTRIBUTES lpSecurityAttributes)
2516 WCHAR wFullName[MAX_PATH+1];
2517 LPVOID lpContext = NULL;
2518 WIN32_STREAM_ID StreamId;
2519 DWORD dwSize = (char*)&StreamId.cStreamName - (char*)&StreamId;
2524 BOOL (__stdcall *pfnBackupWrite)(HANDLE, LPBYTE, DWORD, LPDWORD,
2525 BOOL, BOOL, LPVOID*) =
2526 (BOOL (__stdcall *)(HANDLE, LPBYTE, DWORD, LPDWORD,
2527 BOOL, BOOL, LPVOID*))
2528 GetProcAddress(GetModuleHandle("kernel32.dll"), "BackupWrite");
2529 if (pfnBackupWrite == NULL)
2532 dwLen = GetFullPathNameW(lpFileName, MAX_PATH, wFullName, NULL);
2535 dwLen = (dwLen+1)*sizeof(WCHAR);
2537 handle = CreateFileW(lpExistingFileName, FILE_WRITE_ATTRIBUTES,
2538 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
2539 NULL, OPEN_EXISTING, 0, NULL);
2540 if (handle == INVALID_HANDLE_VALUE)
2543 StreamId.dwStreamId = BACKUP_LINK;
2544 StreamId.dwStreamAttributes = 0;
2545 StreamId.dwStreamNameSize = 0;
2546 #if defined(__BORLANDC__) \
2547 ||(defined(__MINGW32__) && !defined(_ANONYMOUS_UNION))
2548 StreamId.Size.u.HighPart = 0;
2549 StreamId.Size.u.LowPart = dwLen;
2551 StreamId.Size.HighPart = 0;
2552 StreamId.Size.LowPart = dwLen;
2555 bSuccess = pfnBackupWrite(handle, (LPBYTE)&StreamId, dwSize, &dwWritten,
2556 FALSE, FALSE, &lpContext);
2558 bSuccess = pfnBackupWrite(handle, (LPBYTE)wFullName, dwLen, &dwWritten,
2559 FALSE, FALSE, &lpContext);
2560 pfnBackupWrite(handle, NULL, 0, &dwWritten, TRUE, FALSE, &lpContext);
2563 CloseHandle(handle);
2568 win32_link(const char *oldname, const char *newname)
2571 BOOL (__stdcall *pfnCreateHardLinkW)(LPCWSTR,LPCWSTR,LPSECURITY_ATTRIBUTES);
2572 WCHAR wOldName[MAX_PATH+1];
2573 WCHAR wNewName[MAX_PATH+1];
2576 Perl_croak(aTHX_ PL_no_func, "link");
2578 pfnCreateHardLinkW =
2579 (BOOL (__stdcall *)(LPCWSTR, LPCWSTR, LPSECURITY_ATTRIBUTES))
2580 GetProcAddress(GetModuleHandle("kernel32.dll"), "CreateHardLinkW");
2581 if (pfnCreateHardLinkW == NULL)
2582 pfnCreateHardLinkW = Nt4CreateHardLinkW;
2584 if ((A2WHELPER(oldname, wOldName, sizeof(wOldName))) &&
2585 (A2WHELPER(newname, wNewName, sizeof(wNewName))) &&
2586 (wcscpy(wOldName, PerlDir_mapW(wOldName)),
2587 pfnCreateHardLinkW(PerlDir_mapW(wNewName), wOldName, NULL)))
2591 errno = (GetLastError() == ERROR_FILE_NOT_FOUND) ? ENOENT : EINVAL;
2596 win32_rename(const char *oname, const char *newname)
2598 WCHAR wOldName[MAX_PATH+1];
2599 WCHAR wNewName[MAX_PATH+1];
2600 char szOldName[MAX_PATH+1];
2601 char szNewName[MAX_PATH+1];
2605 /* XXX despite what the documentation says about MoveFileEx(),
2606 * it doesn't work under Windows95!
2609 DWORD dwFlags = MOVEFILE_COPY_ALLOWED;
2611 A2WHELPER(oname, wOldName, sizeof(wOldName));
2612 A2WHELPER(newname, wNewName, sizeof(wNewName));
2613 if (wcsicmp(wNewName, wOldName))
2614 dwFlags |= MOVEFILE_REPLACE_EXISTING;
2615 wcscpy(wOldName, PerlDir_mapW(wOldName));
2616 bResult = MoveFileExW(wOldName,PerlDir_mapW(wNewName), dwFlags);
2619 if (stricmp(newname, oname))
2620 dwFlags |= MOVEFILE_REPLACE_EXISTING;
2621 strcpy(szOldName, PerlDir_mapA(oname));
2622 bResult = MoveFileExA(szOldName,PerlDir_mapA(newname), dwFlags);
2625 DWORD err = GetLastError();
2627 case ERROR_BAD_NET_NAME:
2628 case ERROR_BAD_NETPATH:
2629 case ERROR_BAD_PATHNAME:
2630 case ERROR_FILE_NOT_FOUND:
2631 case ERROR_FILENAME_EXCED_RANGE:
2632 case ERROR_INVALID_DRIVE:
2633 case ERROR_NO_MORE_FILES:
2634 case ERROR_PATH_NOT_FOUND:
2647 char szTmpName[MAX_PATH+1];
2648 char dname[MAX_PATH+1];
2649 char *endname = Nullch;
2651 DWORD from_attr, to_attr;
2653 strcpy(szOldName, PerlDir_mapA(oname));
2654 strcpy(szNewName, PerlDir_mapA(newname));
2656 /* if oname doesn't exist, do nothing */
2657 from_attr = GetFileAttributes(szOldName);
2658 if (from_attr == 0xFFFFFFFF) {
2663 /* if newname exists, rename it to a temporary name so that we
2664 * don't delete it in case oname happens to be the same file
2665 * (but perhaps accessed via a different path)
2667 to_attr = GetFileAttributes(szNewName);
2668 if (to_attr != 0xFFFFFFFF) {
2669 /* if newname is a directory, we fail
2670 * XXX could overcome this with yet more convoluted logic */
2671 if (to_attr & FILE_ATTRIBUTE_DIRECTORY) {
2675 tmplen = strlen(szNewName);
2676 strcpy(szTmpName,szNewName);
2677 endname = szTmpName+tmplen;
2678 for (; endname > szTmpName ; --endname) {
2679 if (*endname == '/' || *endname == '\\') {
2684 if (endname > szTmpName)
2685 endname = strcpy(dname,szTmpName);
2689 /* get a temporary filename in same directory
2690 * XXX is this really the best we can do? */
2691 if (!GetTempFileName((LPCTSTR)endname, "plr", 0, szTmpName)) {
2695 DeleteFile(szTmpName);
2697 retval = rename(szNewName, szTmpName);
2704 /* rename oname to newname */
2705 retval = rename(szOldName, szNewName);
2707 /* if we created a temporary file before ... */
2708 if (endname != Nullch) {
2709 /* ...and rename succeeded, delete temporary file/directory */
2711 DeleteFile(szTmpName);
2712 /* else restore it to what it was */
2714 (void)rename(szTmpName, szNewName);
2721 win32_setmode(int fd, int mode)
2723 return setmode(fd, mode);
2727 win32_lseek(int fd, long offset, int origin)
2729 return lseek(fd, offset, origin);
2739 win32_open(const char *path, int flag, ...)
2744 WCHAR wBuffer[MAX_PATH+1];
2747 pmode = va_arg(ap, int);
2750 if (stricmp(path, "/dev/null")==0)
2754 A2WHELPER(path, wBuffer, sizeof(wBuffer));
2755 return _wopen(PerlDir_mapW(wBuffer), flag, pmode);
2757 return open(PerlDir_mapA(path), flag, pmode);
2760 /* close() that understands socket */
2761 extern int my_close(int); /* in win32sck.c */
2766 return my_close(fd);
2782 win32_dup2(int fd1,int fd2)
2784 return dup2(fd1,fd2);
2787 #ifdef PERL_MSVCRT_READFIX
2789 #define LF 10 /* line feed */
2790 #define CR 13 /* carriage return */
2791 #define CTRLZ 26 /* ctrl-z means eof for text */
2792 #define FOPEN 0x01 /* file handle open */
2793 #define FEOFLAG 0x02 /* end of file has been encountered */
2794 #define FCRLF 0x04 /* CR-LF across read buffer (in text mode) */
2795 #define FPIPE 0x08 /* file handle refers to a pipe */
2796 #define FAPPEND 0x20 /* file handle opened O_APPEND */
2797 #define FDEV 0x40 /* file handle refers to device */
2798 #define FTEXT 0x80 /* file handle is in text mode */
2799 #define MAX_DESCRIPTOR_COUNT (64*32) /* this is the maximun that MSVCRT can handle */
2802 _fixed_read(int fh, void *buf, unsigned cnt)
2804 int bytes_read; /* number of bytes read */
2805 char *buffer; /* buffer to read to */
2806 int os_read; /* bytes read on OS call */
2807 char *p, *q; /* pointers into buffer */
2808 char peekchr; /* peek-ahead character */
2809 ULONG filepos; /* file position after seek */
2810 ULONG dosretval; /* o.s. return value */
2812 /* validate handle */
2813 if (((unsigned)fh >= (unsigned)MAX_DESCRIPTOR_COUNT) ||
2814 !(_osfile(fh) & FOPEN))
2816 /* out of range -- return error */
2818 _doserrno = 0; /* not o.s. error */
2823 * If lockinitflag is FALSE, assume fd is device
2824 * lockinitflag is set to TRUE by open.
2826 if (_pioinfo(fh)->lockinitflag)
2827 EnterCriticalSection(&(_pioinfo(fh)->lock)); /* lock file */
2829 bytes_read = 0; /* nothing read yet */
2830 buffer = (char*)buf;
2832 if (cnt == 0 || (_osfile(fh) & FEOFLAG)) {
2833 /* nothing to read or at EOF, so return 0 read */
2837 if ((_osfile(fh) & (FPIPE|FDEV)) && _pipech(fh) != LF) {
2838 /* a pipe/device and pipe lookahead non-empty: read the lookahead
2840 *buffer++ = _pipech(fh);
2843 _pipech(fh) = LF; /* mark as empty */
2848 if (!ReadFile((HANDLE)_osfhnd(fh), buffer, cnt, (LPDWORD)&os_read, NULL))
2850 /* ReadFile has reported an error. recognize two special cases.
2852 * 1. map ERROR_ACCESS_DENIED to EBADF
2854 * 2. just return 0 if ERROR_BROKEN_PIPE has occurred. it
2855 * means the handle is a read-handle on a pipe for which
2856 * all write-handles have been closed and all data has been
2859 if ((dosretval = GetLastError()) == ERROR_ACCESS_DENIED) {
2860 /* wrong read/write mode should return EBADF, not EACCES */
2862 _doserrno = dosretval;
2866 else if (dosretval == ERROR_BROKEN_PIPE) {
2876 bytes_read += os_read; /* update bytes read */
2878 if (_osfile(fh) & FTEXT) {
2879 /* now must translate CR-LFs to LFs in the buffer */
2881 /* set CRLF flag to indicate LF at beginning of buffer */
2882 /* if ((os_read != 0) && (*(char *)buf == LF)) */
2883 /* _osfile(fh) |= FCRLF; */
2885 /* _osfile(fh) &= ~FCRLF; */
2887 _osfile(fh) &= ~FCRLF;
2889 /* convert chars in the buffer: p is src, q is dest */
2891 while (p < (char *)buf + bytes_read) {
2893 /* if fh is not a device, set ctrl-z flag */
2894 if (!(_osfile(fh) & FDEV))
2895 _osfile(fh) |= FEOFLAG;
2896 break; /* stop translating */
2901 /* *p is CR, so must check next char for LF */
2902 if (p < (char *)buf + bytes_read - 1) {
2905 *q++ = LF; /* convert CR-LF to LF */
2908 *q++ = *p++; /* store char normally */
2911 /* This is the hard part. We found a CR at end of
2912 buffer. We must peek ahead to see if next char
2917 if (!ReadFile((HANDLE)_osfhnd(fh), &peekchr, 1,
2918 (LPDWORD)&os_read, NULL))
2919 dosretval = GetLastError();
2921 if (dosretval != 0 || os_read == 0) {
2922 /* couldn't read ahead, store CR */
2926 /* peekchr now has the extra character -- we now
2927 have several possibilities:
2928 1. disk file and char is not LF; just seek back
2930 2. disk file and char is LF; store LF, don't seek back
2931 3. pipe/device and char is LF; store LF.
2932 4. pipe/device and char isn't LF, store CR and
2933 put char in pipe lookahead buffer. */
2934 if (_osfile(fh) & (FDEV|FPIPE)) {
2935 /* non-seekable device */
2940 _pipech(fh) = peekchr;
2945 if (peekchr == LF) {
2946 /* nothing read yet; must make some
2949 /* turn on this flag for tell routine */
2950 _osfile(fh) |= FCRLF;
2953 HANDLE osHandle; /* o.s. handle value */
2955 if ((osHandle = (HANDLE)_get_osfhandle(fh)) != (HANDLE)-1)
2957 if ((filepos = SetFilePointer(osHandle, -1, NULL, FILE_CURRENT)) == -1)
2958 dosretval = GetLastError();
2969 /* we now change bytes_read to reflect the true number of chars
2971 bytes_read = q - (char *)buf;
2975 if (_pioinfo(fh)->lockinitflag)
2976 LeaveCriticalSection(&(_pioinfo(fh)->lock)); /* unlock file */
2981 #endif /* PERL_MSVCRT_READFIX */
2984 win32_read(int fd, void *buf, unsigned int cnt)
2986 #ifdef PERL_MSVCRT_READFIX
2987 return _fixed_read(fd, buf, cnt);
2989 return read(fd, buf, cnt);
2994 win32_write(int fd, const void *buf, unsigned int cnt)
2996 return write(fd, buf, cnt);
3000 win32_mkdir(const char *dir, int mode)
3004 WCHAR wBuffer[MAX_PATH+1];
3005 A2WHELPER(dir, wBuffer, sizeof(wBuffer));
3006 return _wmkdir(PerlDir_mapW(wBuffer));
3008 return mkdir(PerlDir_mapA(dir)); /* just ignore mode */
3012 win32_rmdir(const char *dir)
3016 WCHAR wBuffer[MAX_PATH+1];
3017 A2WHELPER(dir, wBuffer, sizeof(wBuffer));
3018 return _wrmdir(PerlDir_mapW(wBuffer));
3020 return rmdir(PerlDir_mapA(dir));
3024 win32_chdir(const char *dir)
3032 WCHAR wBuffer[MAX_PATH+1];
3033 A2WHELPER(dir, wBuffer, sizeof(wBuffer));
3034 return _wchdir(wBuffer);
3040 win32_access(const char *path, int mode)
3044 WCHAR wBuffer[MAX_PATH+1];
3045 A2WHELPER(path, wBuffer, sizeof(wBuffer));
3046 return _waccess(PerlDir_mapW(wBuffer), mode);
3048 return access(PerlDir_mapA(path), mode);
3052 win32_chmod(const char *path, int mode)
3056 WCHAR wBuffer[MAX_PATH+1];
3057 A2WHELPER(path, wBuffer, sizeof(wBuffer));
3058 return _wchmod(PerlDir_mapW(wBuffer), mode);
3060 return chmod(PerlDir_mapA(path), mode);
3065 create_command_line(const char * const *args)
3072 bool cmd_shell = FALSE;
3073 bool extra_quotes = FALSE;
3075 /* The NT cmd.exe shell has the following peculiarity that needs to be
3076 * worked around. It strips a leading and trailing dquote when any
3077 * of the following is true:
3078 * 1. the /S switch was used
3079 * 2. there are more than two dquotes
3080 * 3. there is a special character from this set: &<>()@^|
3081 * 4. no whitespace characters within the two dquotes
3082 * 5. string between two dquotes isn't an executable file
3083 * To work around this, we always add a leading and trailing dquote
3084 * to the string, if the first argument is either "cmd.exe" or "cmd",
3085 * and there were at least two or more arguments passed to cmd.exe
3086 * (not including switches).
3089 && (stricmp(args[0], "cmd.exe") == 0
3090 || stricmp(args[0], "cmd") == 0))
3096 DEBUG_p(PerlIO_printf(Perl_debug_log, "Args "));
3097 for (index = 0; (arg = (char*)args[index]) != NULL; ++index) {
3098 STRLEN curlen = strlen(arg);
3099 if (!(arg[0] == '"' && arg[curlen-1] == '"'))
3100 len += 2; /* assume quoting needed (worst case) */
3102 DEBUG_p(PerlIO_printf(Perl_debug_log, "[%s]",arg));
3104 DEBUG_p(PerlIO_printf(Perl_debug_log, "\n"));
3107 New(1310, cmd, len, char);
3110 for (index = 0; (arg = (char*)args[index]) != NULL; ++index) {
3112 STRLEN curlen = strlen(arg);
3114 /* we want to protect arguments with spaces with dquotes,
3115 * but only if they aren't already there */
3116 if (!(arg[0] == '"' && arg[curlen-1] == '"')) {
3118 while (i < curlen) {
3119 if (isSPACE(arg[i])) {
3139 if (cmd_shell && !extra_quotes
3140 && (stricmp(arg, "/x/c") == 0 || stricmp(arg, "/c") == 0)
3141 && (argc-1 > index+1)) /* two or more arguments to cmd.exe? */
3144 extra_quotes = TRUE;
3157 qualified_path(const char *cmd)
3161 char *fullcmd, *curfullcmd;
3167 fullcmd = (char*)cmd;
3169 if (*fullcmd == '/' || *fullcmd == '\\')
3176 pathstr = PerlEnv_getenv("PATH");
3177 New(0, fullcmd, MAX_PATH+1, char);
3178 curfullcmd = fullcmd;
3183 /* start by appending the name to the current prefix */
3184 strcpy(curfullcmd, cmd);
3185 curfullcmd += cmdlen;
3187 /* if it doesn't end with '.', or has no extension, try adding
3188 * a trailing .exe first */
3189 if (cmd[cmdlen-1] != '.'
3190 && (cmdlen < 4 || cmd[cmdlen-4] != '.'))
3192 strcpy(curfullcmd, ".exe");
3193 res = GetFileAttributes(fullcmd);
3194 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
3199 /* that failed, try the bare name */
3200 res = GetFileAttributes(fullcmd);
3201 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
3204 /* quit if no other path exists, or if cmd already has path */
3205 if (!pathstr || !*pathstr || has_slash)
3208 /* skip leading semis */
3209 while (*pathstr == ';')
3212 /* build a new prefix from scratch */
3213 curfullcmd = fullcmd;
3214 while (*pathstr && *pathstr != ';') {
3215 if (*pathstr == '"') { /* foo;"baz;etc";bar */
3216 pathstr++; /* skip initial '"' */
3217 while (*pathstr && *pathstr != '"') {
3218 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
3219 *curfullcmd++ = *pathstr;
3223 pathstr++; /* skip trailing '"' */
3226 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
3227 *curfullcmd++ = *pathstr;
3232 pathstr++; /* skip trailing semi */
3233 if (curfullcmd > fullcmd /* append a dir separator */
3234 && curfullcmd[-1] != '/' && curfullcmd[-1] != '\\')
3236 *curfullcmd++ = '\\';
3244 /* The following are just place holders.
3245 * Some hosts may provide and environment that the OS is
3246 * not tracking, therefore, these host must provide that
3247 * environment and the current directory to CreateProcess
3257 free_childenv(void* d)
3266 char szfilename[(MAX_PATH+1)*2];
3268 WCHAR wfilename[MAX_PATH+1];
3269 GetCurrentDirectoryW(MAX_PATH+1, wfilename);
3270 W2AHELPER(wfilename, szfilename, sizeof(szfilename));
3273 GetCurrentDirectoryA(MAX_PATH+1, szfilename);
3276 New(0, ptr, strlen(szfilename)+1, char);
3277 strcpy(ptr, szfilename);
3282 free_childdir(char* d)
3289 /* XXX this needs to be made more compatible with the spawnvp()
3290 * provided by the various RTLs. In particular, searching for
3291 * *.{com,bat,cmd} files (as done by the RTLs) is unimplemented.
3292 * This doesn't significantly affect perl itself, because we
3293 * always invoke things using PERL5SHELL if a direct attempt to
3294 * spawn the executable fails.
3296 * XXX splitting and rejoining the commandline between do_aspawn()
3297 * and win32_spawnvp() could also be avoided.
3301 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
3303 #ifdef USE_RTL_SPAWNVP
3304 return spawnvp(mode, cmdname, (char * const *)argv);
3311 STARTUPINFO StartupInfo;
3312 PROCESS_INFORMATION ProcessInformation;
3315 char *cmd = create_command_line(argv);
3316 char *fullcmd = Nullch;
3318 env = PerlEnv_get_childenv();
3319 dir = PerlEnv_get_childdir();
3322 case P_NOWAIT: /* asynch + remember result */
3323 if (w32_num_children >= MAXIMUM_WAIT_OBJECTS) {
3329 case P_WAIT: /* synchronous execution */
3331 default: /* invalid mode */
3336 memset(&StartupInfo,0,sizeof(StartupInfo));
3337 StartupInfo.cb = sizeof(StartupInfo);
3338 memset(&tbl,0,sizeof(tbl));
3339 PerlEnv_get_child_IO(&tbl);
3340 StartupInfo.dwFlags = tbl.dwFlags;
3341 StartupInfo.dwX = tbl.dwX;
3342 StartupInfo.dwY = tbl.dwY;
3343 StartupInfo.dwXSize = tbl.dwXSize;
3344 StartupInfo.dwYSize = tbl.dwYSize;
3345 StartupInfo.dwXCountChars = tbl.dwXCountChars;
3346 StartupInfo.dwYCountChars = tbl.dwYCountChars;
3347 StartupInfo.dwFillAttribute = tbl.dwFillAttribute;
3348 StartupInfo.wShowWindow = tbl.wShowWindow;
3349 StartupInfo.hStdInput = tbl.childStdIn;
3350 StartupInfo.hStdOutput = tbl.childStdOut;
3351 StartupInfo.hStdError = tbl.childStdErr;
3352 if (StartupInfo.hStdInput != INVALID_HANDLE_VALUE &&
3353 StartupInfo.hStdOutput != INVALID_HANDLE_VALUE &&
3354 StartupInfo.hStdError != INVALID_HANDLE_VALUE)
3356 StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
3359 create |= CREATE_NEW_CONSOLE;
3362 DEBUG_p(PerlIO_printf(Perl_debug_log, "Spawning [%s] with [%s]\n",
3365 if (!CreateProcess(cmdname, /* search PATH to find executable */
3366 cmd, /* executable, and its arguments */
3367 NULL, /* process attributes */
3368 NULL, /* thread attributes */
3369 TRUE, /* inherit handles */
3370 create, /* creation flags */
3371 (LPVOID)env, /* inherit environment */
3372 dir, /* inherit cwd */
3374 &ProcessInformation))
3376 /* initial NULL argument to CreateProcess() does a PATH
3377 * search, but it always first looks in the directory
3378 * where the current process was started, which behavior
3379 * is undesirable for backward compatibility. So we
3380 * jump through our own hoops by picking out the path
3381 * we really want it to use. */
3383 fullcmd = qualified_path(cmdname);
3386 DEBUG_p(PerlIO_printf(Perl_debug_log,
3387 "Retrying [%s] with same args\n",
3397 if (mode == P_NOWAIT) {
3398 /* asynchronous spawn -- store handle, return PID */
3399 ret = (int)ProcessInformation.dwProcessId;
3400 if (IsWin95() && ret < 0)
3403 w32_child_handles[w32_num_children] = ProcessInformation.hProcess;
3404 w32_child_pids[w32_num_children] = (DWORD)ret;
3409 WaitForSingleObject(ProcessInformation.hProcess, INFINITE);
3410 GetExitCodeProcess(ProcessInformation.hProcess, &status);
3412 CloseHandle(ProcessInformation.hProcess);
3415 CloseHandle(ProcessInformation.hThread);
3418 PerlEnv_free_childenv(env);
3419 PerlEnv_free_childdir(dir);
3427 win32_execv(const char *cmdname, const char *const *argv)
3431 /* if this is a pseudo-forked child, we just want to spawn
3432 * the new program, and return */
3434 return spawnv(P_WAIT, cmdname, (char *const *)argv);
3436 return execv(cmdname, (char *const *)argv);
3440 win32_execvp(const char *cmdname, const char *const *argv)
3444 /* if this is a pseudo-forked child, we just want to spawn
3445 * the new program, and return */
3446 if (w32_pseudo_id) {
3447 int status = win32_spawnvp(P_WAIT, cmdname, (char *const *)argv);
3456 return execvp(cmdname, (char *const *)argv);
3460 win32_perror(const char *str)
3466 win32_setbuf(FILE *pf, char *buf)
3472 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
3474 return setvbuf(pf, buf, type, size);
3478 win32_flushall(void)
3484 win32_fcloseall(void)
3490 win32_fgets(char *s, int n, FILE *pf)
3492 return fgets(s, n, pf);
3502 win32_fgetc(FILE *pf)
3508 win32_putc(int c, FILE *pf)
3514 win32_puts(const char *s)
3526 win32_putchar(int c)
3533 #ifndef USE_PERL_SBRK
3535 static char *committed = NULL;
3536 static char *base = NULL;
3537 static char *reserved = NULL;
3538 static char *brk = NULL;
3539 static DWORD pagesize = 0;
3540 static DWORD allocsize = 0;
3548 GetSystemInfo(&info);
3549 /* Pretend page size is larger so we don't perpetually
3550 * call the OS to commit just one page ...
3552 pagesize = info.dwPageSize << 3;
3553 allocsize = info.dwAllocationGranularity;
3555 /* This scheme fails eventually if request for contiguous
3556 * block is denied so reserve big blocks - this is only
3557 * address space not memory ...
3559 if (brk+need >= reserved)
3561 DWORD size = 64*1024*1024;
3563 if (committed && reserved && committed < reserved)
3565 /* Commit last of previous chunk cannot span allocations */
3566 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
3568 committed = reserved;
3570 /* Reserve some (more) space
3571 * Note this is a little sneaky, 1st call passes NULL as reserved
3572 * so lets system choose where we start, subsequent calls pass
3573 * the old end address so ask for a contiguous block
3575 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
3578 reserved = addr+size;
3593 if (brk > committed)
3595 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
3596 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
3611 win32_malloc(size_t size)
3613 return malloc(size);
3617 win32_calloc(size_t numitems, size_t size)
3619 return calloc(numitems,size);
3623 win32_realloc(void *block, size_t size)
3625 return realloc(block,size);
3629 win32_free(void *block)
3636 win32_open_osfhandle(long handle, int flags)
3638 #ifdef USE_FIXED_OSFHANDLE
3640 return my_open_osfhandle(handle, flags);
3642 return _open_osfhandle(handle, flags);
3646 win32_get_osfhandle(int fd)
3648 return _get_osfhandle(fd);
3652 win32_dynaload(const char* filename)
3656 char buf[MAX_PATH+1];
3659 /* LoadLibrary() doesn't recognize forward slashes correctly,
3660 * so turn 'em back. */
3661 first = strchr(filename, '/');
3663 STRLEN len = strlen(filename);
3664 if (len <= MAX_PATH) {
3665 strcpy(buf, filename);
3666 filename = &buf[first - filename];
3668 if (*filename == '/')
3669 *(char*)filename = '\\';
3676 WCHAR wfilename[MAX_PATH+1];
3677 A2WHELPER(filename, wfilename, sizeof(wfilename));
3678 hModule = LoadLibraryExW(PerlDir_mapW(wfilename), NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
3681 hModule = LoadLibraryExA(PerlDir_mapA(filename), NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
3694 /* Make the host for current directory */
3695 char* ptr = PerlEnv_get_childdir();
3698 * then it worked, set PV valid,
3699 * else return 'undef'
3702 SV *sv = sv_newmortal();
3704 PerlEnv_free_childdir(ptr);
3706 #ifndef INCOMPLETE_TAINTS
3723 Perl_croak(aTHX_ "usage: Win32::SetCurrentDirectory($cwd)");
3724 if (!PerlDir_chdir(SvPV_nolen(ST(0))))
3731 XS(w32_GetNextAvailDrive)
3735 char root[] = "_:\\";
3740 if (GetDriveType(root) == 1) {
3749 XS(w32_GetLastError)
3753 XSRETURN_IV(GetLastError());
3757 XS(w32_SetLastError)
3761 Perl_croak(aTHX_ "usage: Win32::SetLastError($error)");
3762 SetLastError(SvIV(ST(0)));
3770 char *name = w32_getlogin_buffer;
3771 DWORD size = sizeof(w32_getlogin_buffer);
3773 if (GetUserName(name,&size)) {
3774 /* size includes NULL */
3775 ST(0) = sv_2mortal(newSVpvn(name,size-1));
3785 char name[MAX_COMPUTERNAME_LENGTH+1];
3786 DWORD size = sizeof(name);
3788 if (GetComputerName(name,&size)) {
3789 /* size does NOT include NULL :-( */
3790 ST(0) = sv_2mortal(newSVpvn(name,size));
3801 HINSTANCE hNetApi32 = LoadLibrary("netapi32.dll");
3802 DWORD (__stdcall *pfnNetApiBufferFree)(LPVOID Buffer);
3803 DWORD (__stdcall *pfnNetWkstaGetInfo)(LPWSTR servername, DWORD level,
3807 pfnNetApiBufferFree = (DWORD (__stdcall *)(void *))
3808 GetProcAddress(hNetApi32, "NetApiBufferFree");
3809 pfnNetWkstaGetInfo = (DWORD (__stdcall *)(LPWSTR, DWORD, void *))
3810 GetProcAddress(hNetApi32, "NetWkstaGetInfo");
3813 if (hNetApi32 && pfnNetWkstaGetInfo && pfnNetApiBufferFree) {
3814 /* this way is more reliable, in case user has a local account. */
3816 DWORD dnamelen = sizeof(dname);
3818 DWORD wki100_platform_id;
3819 LPWSTR wki100_computername;
3820 LPWSTR wki100_langroup;
3821 DWORD wki100_ver_major;
3822 DWORD wki100_ver_minor;
3824 /* NERR_Success *is* 0*/
3825 if (0 == pfnNetWkstaGetInfo(NULL, 100, &pwi)) {
3826 if (pwi->wki100_langroup && *(pwi->wki100_langroup)) {
3827 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_langroup,
3828 -1, (LPSTR)dname, dnamelen, NULL, NULL);
3831 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_computername,
3832 -1, (LPSTR)dname, dnamelen, NULL, NULL);
3834 pfnNetApiBufferFree(pwi);
3835 FreeLibrary(hNetApi32);
3838 FreeLibrary(hNetApi32);
3841 /* Win95 doesn't have NetWksta*(), so do it the old way */
3843 DWORD size = sizeof(name);
3845 FreeLibrary(hNetApi32);
3846 if (GetUserName(name,&size)) {
3847 char sid[ONE_K_BUFSIZE];
3848 DWORD sidlen = sizeof(sid);
3850 DWORD dnamelen = sizeof(dname);
3852 if (LookupAccountName(NULL, name, (PSID)&sid, &sidlen,
3853 dname, &dnamelen, &snu)) {
3854 XSRETURN_PV(dname); /* all that for this */
3866 DWORD flags, filecomplen;
3867 if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
3868 &flags, fsname, sizeof(fsname))) {
3869 if (GIMME_V == G_ARRAY) {
3870 XPUSHs(sv_2mortal(newSVpvn(fsname,strlen(fsname))));
3871 XPUSHs(sv_2mortal(newSViv(flags)));
3872 XPUSHs(sv_2mortal(newSViv(filecomplen)));
3877 XSRETURN_PV(fsname);
3883 XS(w32_GetOSVersion)
3886 OSVERSIONINFOA osver;
3889 OSVERSIONINFOW osverw;
3890 char szCSDVersion[sizeof(osverw.szCSDVersion)];
3891 osverw.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
3892 if (!GetVersionExW(&osverw)) {
3895 W2AHELPER(osverw.szCSDVersion, szCSDVersion, sizeof(szCSDVersion));
3896 XPUSHs(newSVpvn(szCSDVersion, strlen(szCSDVersion)));
3897 osver.dwMajorVersion = osverw.dwMajorVersion;
3898 osver.dwMinorVersion = osverw.dwMinorVersion;
3899 osver.dwBuildNumber = osverw.dwBuildNumber;
3900 osver.dwPlatformId = osverw.dwPlatformId;
3903 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOA);
3904 if (!GetVersionExA(&osver)) {
3907 XPUSHs(newSVpvn(osver.szCSDVersion, strlen(osver.szCSDVersion)));
3909 XPUSHs(newSViv(osver.dwMajorVersion));
3910 XPUSHs(newSViv(osver.dwMinorVersion));
3911 XPUSHs(newSViv(osver.dwBuildNumber));
3912 XPUSHs(newSViv(osver.dwPlatformId));
3921 XSRETURN_IV(IsWinNT());
3929 XSRETURN_IV(IsWin95());
3933 XS(w32_FormatMessage)
3937 char msgbuf[ONE_K_BUFSIZE];
3940 Perl_croak(aTHX_ "usage: Win32::FormatMessage($errno)");
3943 WCHAR wmsgbuf[ONE_K_BUFSIZE];
3944 if (FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM,
3945 &source, SvIV(ST(0)), 0,
3946 wmsgbuf, ONE_K_BUFSIZE-1, NULL))
3948 W2AHELPER(wmsgbuf, msgbuf, sizeof(msgbuf));
3949 XSRETURN_PV(msgbuf);
3953 if (FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM,
3954 &source, SvIV(ST(0)), 0,
3955 msgbuf, sizeof(msgbuf)-1, NULL))
3956 XSRETURN_PV(msgbuf);
3969 PROCESS_INFORMATION stProcInfo;
3970 STARTUPINFO stStartInfo;
3971 BOOL bSuccess = FALSE;
3974 Perl_croak(aTHX_ "usage: Win32::Spawn($cmdName, $args, $PID)");
3976 cmd = SvPV_nolen(ST(0));
3977 args = SvPV_nolen(ST(1));
3979 env = PerlEnv_get_childenv();
3980 dir = PerlEnv_get_childdir();
3982 memset(&stStartInfo, 0, sizeof(stStartInfo)); /* Clear the block */
3983 stStartInfo.cb = sizeof(stStartInfo); /* Set the structure size */
3984 stStartInfo.dwFlags = STARTF_USESHOWWINDOW; /* Enable wShowWindow control */
3985 stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE; /* Start min (normal) */
3988 cmd, /* Image path */
3989 args, /* Arguments for command line */
3990 NULL, /* Default process security */
3991 NULL, /* Default thread security */
3992 FALSE, /* Must be TRUE to use std handles */
3993 NORMAL_PRIORITY_CLASS, /* No special scheduling */
3994 env, /* Inherit our environment block */
3995 dir, /* Inherit our currrent directory */
3996 &stStartInfo, /* -> Startup info */
3997 &stProcInfo)) /* <- Process info (if OK) */
3999 int pid = (int)stProcInfo.dwProcessId;
4000 if (IsWin95() && pid < 0)
4002 sv_setiv(ST(2), pid);
4003 CloseHandle(stProcInfo.hThread);/* library source code does this. */
4006 PerlEnv_free_childenv(env);
4007 PerlEnv_free_childdir(dir);
4008 XSRETURN_IV(bSuccess);
4012 XS(w32_GetTickCount)
4015 DWORD msec = GetTickCount();
4023 XS(w32_GetShortPathName)
4030 Perl_croak(aTHX_ "usage: Win32::GetShortPathName($longPathName)");
4032 shortpath = sv_mortalcopy(ST(0));
4033 SvUPGRADE(shortpath, SVt_PV);
4034 if (!SvPVX(shortpath) || !SvLEN(shortpath))
4037 /* src == target is allowed */
4039 len = GetShortPathName(SvPVX(shortpath),
4042 } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
4044 SvCUR_set(shortpath,len);
4052 XS(w32_GetFullPathName)
4061 Perl_croak(aTHX_ "usage: Win32::GetFullPathName($filename)");
4064 fullpath = sv_mortalcopy(filename);
4065 SvUPGRADE(fullpath, SVt_PV);
4066 if (!SvPVX(fullpath) || !SvLEN(fullpath))
4070 len = GetFullPathName(SvPVX(filename),
4074 } while (len >= SvLEN(fullpath) && sv_grow(fullpath,len+1));
4076 if (GIMME_V == G_ARRAY) {
4078 XST_mPV(1,filepart);
4079 len = filepart - SvPVX(fullpath);
4082 SvCUR_set(fullpath,len);
4090 XS(w32_GetLongPathName)
4094 char tmpbuf[MAX_PATH+1];
4099 Perl_croak(aTHX_ "usage: Win32::GetLongPathName($pathname)");
4102 pathstr = SvPV(path,len);
4103 strcpy(tmpbuf, pathstr);
4104 pathstr = win32_longpath(tmpbuf);
4106 ST(0) = sv_2mortal(newSVpvn(pathstr, strlen(pathstr)));
4117 Perl_croak(aTHX_ "usage: Win32::Sleep($milliseconds)");
4128 Perl_croak(aTHX_ "usage: Win32::CopyFile($from, $to, $overwrite)");
4130 WCHAR wSourceFile[MAX_PATH+1];
4131 WCHAR wDestFile[MAX_PATH+1];
4132 A2WHELPER(SvPV_nolen(ST(0)), wSourceFile, sizeof(wSourceFile));
4133 wcscpy(wSourceFile, PerlDir_mapW(wSourceFile));
4134 A2WHELPER(SvPV_nolen(ST(1)), wDestFile, sizeof(wDestFile));
4135 bResult = CopyFileW(wSourceFile, PerlDir_mapW(wDestFile), !SvTRUE(ST(2)));
4138 char szSourceFile[MAX_PATH+1];
4139 strcpy(szSourceFile, PerlDir_mapA(SvPV_nolen(ST(0))));
4140 bResult = CopyFileA(szSourceFile, PerlDir_mapA(SvPV_nolen(ST(1))), !SvTRUE(ST(2)));
4149 Perl_init_os_extras(void)
4152 char *file = __FILE__;
4155 /* these names are Activeware compatible */
4156 newXS("Win32::GetCwd", w32_GetCwd, file);
4157 newXS("Win32::SetCwd", w32_SetCwd, file);
4158 newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
4159 newXS("Win32::GetLastError", w32_GetLastError, file);
4160 newXS("Win32::SetLastError", w32_SetLastError, file);
4161 newXS("Win32::LoginName", w32_LoginName, file);
4162 newXS("Win32::NodeName", w32_NodeName, file);
4163 newXS("Win32::DomainName", w32_DomainName, file);
4164 newXS("Win32::FsType", w32_FsType, file);
4165 newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
4166 newXS("Win32::IsWinNT", w32_IsWinNT, file);
4167 newXS("Win32::IsWin95", w32_IsWin95, file);
4168 newXS("Win32::FormatMessage", w32_FormatMessage, file);
4169 newXS("Win32::Spawn", w32_Spawn, file);
4170 newXS("Win32::GetTickCount", w32_GetTickCount, file);
4171 newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
4172 newXS("Win32::GetFullPathName", w32_GetFullPathName, file);
4173 newXS("Win32::GetLongPathName", w32_GetLongPathName, file);
4174 newXS("Win32::CopyFile", w32_CopyFile, file);
4175 newXS("Win32::Sleep", w32_Sleep, file);
4177 /* XXX Bloat Alert! The following Activeware preloads really
4178 * ought to be part of Win32::Sys::*, so they're not included
4181 /* LookupAccountName
4183 * InitiateSystemShutdown
4184 * AbortSystemShutdown
4185 * ExpandEnvrironmentStrings
4190 Perl_win32_init(int *argcp, char ***argvp)
4192 /* Disable floating point errors, Perl will trap the ones we
4193 * care about. VC++ RTL defaults to switching these off
4194 * already, but the Borland RTL doesn't. Since we don't
4195 * want to be at the vendor's whim on the default, we set
4196 * it explicitly here.
4198 #if !defined(_ALPHA_) && !defined(__GNUC__)
4199 _control87(MCW_EM, MCW_EM);
4205 win32_get_child_IO(child_IO_table* ptbl)
4207 ptbl->childStdIn = GetStdHandle(STD_INPUT_HANDLE);
4208 ptbl->childStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
4209 ptbl->childStdErr = GetStdHandle(STD_ERROR_HANDLE);
4212 #ifdef HAVE_INTERP_INTERN
4215 Perl_sys_intern_init(pTHX)
4217 w32_perlshell_tokens = Nullch;
4218 w32_perlshell_vec = (char**)NULL;
4219 w32_perlshell_items = 0;
4220 w32_fdpid = newAV();
4221 New(1313, w32_children, 1, child_tab);
4222 w32_num_children = 0;
4223 # ifdef USE_ITHREADS
4225 New(1313, w32_pseudo_children, 1, child_tab);
4226 w32_num_pseudo_children = 0;
4228 w32_init_socktype = 0;
4232 Perl_sys_intern_clear(pTHX)
4234 Safefree(w32_perlshell_tokens);
4235 Safefree(w32_perlshell_vec);
4236 /* NOTE: w32_fdpid is freed by sv_clean_all() */
4237 Safefree(w32_children);
4238 # ifdef USE_ITHREADS
4239 Safefree(w32_pseudo_children);
4243 # ifdef USE_ITHREADS
4246 Perl_sys_intern_dup(pTHX_ struct interp_intern *src, struct interp_intern *dst)
4248 dst->perlshell_tokens = Nullch;
4249 dst->perlshell_vec = (char**)NULL;
4250 dst->perlshell_items = 0;
4251 dst->fdpid = newAV();
4252 Newz(1313, dst->children, 1, child_tab);
4254 Newz(1313, dst->pseudo_children, 1, child_tab);
4255 dst->thr_intern.Winit_socktype = 0;
4257 # endif /* USE_ITHREADS */
4258 #endif /* HAVE_INTERP_INTERN */
4261 win32_free_argvw(pTHX_ void *ptr)
4263 char** argv = (char**)ptr;
4271 win32_argv2utf8(int argc, char** argv)
4276 LPWSTR* lpwStr = CommandLineToArgvW(GetCommandLineW(), &wargc);
4277 if (lpwStr && argc) {
4279 length = WideCharToMultiByte(CP_UTF8, 0, lpwStr[--wargc], -1, NULL, 0, NULL, NULL);
4280 Newz(0, psz, length, char);
4281 WideCharToMultiByte(CP_UTF8, 0, lpwStr[wargc], -1, psz, length, NULL, NULL);
4284 call_atexit(win32_free_argvw, argv);
4286 GlobalFree((HGLOBAL)lpwStr);