This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Integrate mainline
[perl5.git] / win32 / win32.c
1 /* WIN32.C
2  *
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.
6  *
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.
9  */
10
11 #define WIN32_LEAN_AND_MEAN
12 #define WIN32IO_IS_STDIO
13 #include <tchar.h>
14 #ifdef __GNUC__
15 #define Win32_Winsock
16 #endif
17 #include <windows.h>
18 #ifndef __MINGW32__     /* GCC/Mingw32-2.95.2 forgot the WINAPI on CommandLineToArgvW() */
19 #  include <shellapi.h>
20 #else
21    LPWSTR* WINAPI CommandLineToArgvW(LPCWSTR lpCommandLine, int * pNumArgs);
22 #endif
23 #include <winnt.h>
24 #include <io.h>
25
26 /* #include "config.h" */
27
28 #define PERLIO_NOT_STDIO 0 
29 #if !defined(PERLIO_IS_STDIO) && !defined(USE_SFIO)
30 #define PerlIO FILE
31 #endif
32
33 #include <sys/stat.h>
34 #include "EXTERN.h"
35 #include "perl.h"
36
37 #define NO_XSLOCKS
38 #define PERL_NO_GET_CONTEXT
39 #include "XSUB.h"
40
41 #include "Win32iop.h"
42 #include <fcntl.h>
43 #ifndef __GNUC__
44 /* assert.h conflicts with #define of assert in perl.h */
45 #include <assert.h>
46 #endif
47 #include <string.h>
48 #include <stdarg.h>
49 #include <float.h>
50 #include <time.h>
51 #if defined(_MSC_VER) || defined(__MINGW32__)
52 #include <sys/utime.h>
53 #else
54 #include <utime.h>
55 #endif
56 #ifdef __GNUC__
57 /* Mingw32 defaults to globing command line 
58  * So we turn it off like this:
59  */
60 int _CRT_glob = 0;
61 #endif
62
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);
68 int _flushall();
69 int _fcloseall();
70 #endif
71
72 #if defined(__BORLANDC__)
73 #  define _stat stat
74 #  define _utimbuf utimbuf
75 #endif
76
77 #define EXECF_EXEC 1
78 #define EXECF_SPAWN 2
79 #define EXECF_SPAWN_NOWAIT 3
80
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
88 #  undef do_spawn
89 #  define do_spawn g_do_spawn
90 #  undef getlogin
91 #  define getlogin g_getlogin
92 #endif
93
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);
106
107 #ifdef USE_ITHREADS
108 static void             remove_dead_pseudo_process(long child);
109 static long             find_pseudo_pid(int pid);
110 #endif
111
112 START_EXTERN_C
113 HANDLE  w32_perldll_handle = INVALID_HANDLE_VALUE;
114 char    w32_module_name[MAX_PATH+1];
115 END_EXTERN_C
116
117 static DWORD    w32_platform = (DWORD)-1;
118
119 #define ONE_K_BUFSIZE   1024
120
121 int 
122 IsWin95(void)
123 {
124     return (win32_os_id() == VER_PLATFORM_WIN32_WINDOWS);
125 }
126
127 int
128 IsWinNT(void)
129 {
130     return (win32_os_id() == VER_PLATFORM_WIN32_NT);
131 }
132
133 EXTERN_C void
134 set_w32_module_name(void)
135 {
136     char* ptr;
137     GetModuleFileName((HMODULE)((w32_perldll_handle == INVALID_HANDLE_VALUE)
138                                 ? GetModuleHandle(NULL)
139                                 : w32_perldll_handle),
140                       w32_module_name, sizeof(w32_module_name));
141
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);*/
147
148     /* normalize to forward slashes */
149     ptr = w32_module_name;
150     while (*ptr) {
151         if (*ptr == '\\')
152             *ptr = '/';
153         ++ptr;
154     }
155 }
156
157 /* *svp (if non-NULL) is expected to be POK (valid allocated SvPVX(*svp)) */
158 static char*
159 get_regstr_from(HKEY hkey, const char *valuename, SV **svp)
160 {
161     /* Retrieve a REG_SZ or REG_EXPAND_SZ from the registry */
162     HKEY handle;
163     DWORD type;
164     const char *subkey = "Software\\Perl";
165     char *str = Nullch;
166     long retval;
167
168     retval = RegOpenKeyEx(hkey, subkey, 0, KEY_READ, &handle);
169     if (retval == ERROR_SUCCESS) {
170         DWORD datalen;
171         retval = RegQueryValueEx(handle, valuename, 0, &type, NULL, &datalen);
172         if (retval == ERROR_SUCCESS
173             && (type == REG_SZ || type == REG_EXPAND_SZ))
174         {
175             dTHX;
176             if (!*svp)
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) {
182                 str = SvPVX(*svp);
183                 SvCUR_set(*svp,datalen-1);
184             }
185         }
186         RegCloseKey(handle);
187     }
188     return str;
189 }
190
191 /* *svp (if non-NULL) is expected to be POK (valid allocated SvPVX(*svp)) */
192 static char*
193 get_regstr(const char *valuename, SV **svp)
194 {
195     char *str = get_regstr_from(HKEY_CURRENT_USER, valuename, svp);
196     if (!str)
197         str = get_regstr_from(HKEY_LOCAL_MACHINE, valuename, svp);
198     return str;
199 }
200
201 /* *prev_pathp (if non-NULL) is expected to be POK (valid allocated SvPVX(sv)) */
202 static char *
203 get_emd_part(SV **prev_pathp, char *trailing_path, ...)
204 {
205     char base[10];
206     va_list ap;
207     char mod_name[MAX_PATH+1];
208     char *ptr;
209     char *optr;
210     char *strip;
211     int oldsize, newsize;
212     STRLEN baselen;
213
214     va_start(ap, trailing_path);
215     strip = va_arg(ap, char *);
216
217     sprintf(base, "%d.%d", (int)PERL_REVISION, (int)PERL_VERSION);
218     baselen = strlen(base);
219
220     if (!*w32_module_name) {
221         set_w32_module_name();
222     }
223     strcpy(mod_name, w32_module_name);
224     ptr = strrchr(mod_name, '/');
225     while (ptr && strip) {
226         /* look for directories to skip back */
227         optr = ptr;
228         *ptr = '\0';
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))
237             {
238                 *optr = '/';
239                 ptr = optr;
240             }
241         }
242         strip = va_arg(ap, char *);
243     }
244     if (!ptr) {
245         ptr = mod_name;
246         *ptr++ = '.';
247         *ptr = '/';
248     }
249     va_end(ap);
250     strcpy(++ptr, trailing_path);
251
252     /* only add directory if it exists */
253     if (GetFileAttributes(mod_name) != (DWORD) -1) {
254         /* directory exists */
255         dTHX;
256         if (!*prev_pathp)
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);
261     }
262
263     return Nullch;
264 }
265
266 char *
267 win32_get_privlib(const char *pl)
268 {
269     dTHX;
270     char *stdlib = "lib";
271     char buffer[MAX_PATH+1];
272     SV *sv = Nullsv;
273
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);
278
279     /* $stdlib .= ";$EMD/../../lib" */
280     return get_emd_part(&sv, stdlib, ARCHNAME, "bin", Nullch);
281 }
282
283 static char *
284 win32_get_xlib(const char *pl, const char *xlib, const char *libname)
285 {
286     dTHX;
287     char regstr[40];
288     char pathstr[MAX_PATH+1];
289     DWORD datalen;
290     int len, newsize;
291     SV *sv1 = Nullsv;
292     SV *sv2 = Nullsv;
293
294     /* $HKCU{"$xlib-$]"} || $HKLM{"$xlib-$]"} . ---; */
295     sprintf(regstr, "%s-%s", xlib, pl);
296     (void)get_regstr(regstr, &sv1);
297
298     /* $xlib .=
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);
302
303     /* $HKCU{$xlib} || $HKLM{$xlib} . ---; */
304     (void)get_regstr(xlib, &sv2);
305
306     /* $xlib .=
307      * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/$libname/lib";  */
308     sprintf(pathstr, "%s/lib", libname);
309     (void)get_emd_part(&sv2, pathstr, ARCHNAME, "bin", pl, Nullch);
310
311     if (!sv1 && !sv2)
312         return Nullch;
313     if (!sv1)
314         return SvPVX(sv2);
315     if (!sv2)
316         return SvPVX(sv1);
317
318     sv_catpvn(sv1, ";", 1);
319     sv_catsv(sv1, sv2);
320
321     return SvPVX(sv1);
322 }
323
324 char *
325 win32_get_sitelib(const char *pl)
326 {
327     return win32_get_xlib(pl, "sitelib", "site");
328 }
329
330 #ifndef PERL_VENDORLIB_NAME
331 #  define PERL_VENDORLIB_NAME   "vendor"
332 #endif
333
334 char *
335 win32_get_vendorlib(const char *pl)
336 {
337     return win32_get_xlib(pl, "vendorlib", PERL_VENDORLIB_NAME);
338 }
339
340 static BOOL
341 has_shell_metachars(char *ptr)
342 {
343     int inquote = 0;
344     char quote = '\0';
345
346     /*
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.
350      */
351     while (*ptr) {
352         switch(*ptr) {
353         case '%':
354             return TRUE;
355         case '\'':
356         case '\"':
357             if (inquote) {
358                 if (quote == *ptr) {
359                     inquote = 0;
360                     quote = '\0';
361                 }
362             }
363             else {
364                 quote = *ptr;
365                 inquote++;
366             }
367             break;
368         case '>':
369         case '<':
370         case '|':
371             if (!inquote)
372                 return TRUE;
373         default:
374             break;
375         }
376         ++ptr;
377     }
378     return FALSE;
379 }
380
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
384  */
385 PerlIO *
386 Perl_my_popen(pTHX_ char *cmd, char *mode)
387 {
388 #ifdef FIXCMD
389 #define fixcmd(x)   {                                   \
390                         char *pspace = strchr((x),' '); \
391                         if (pspace) {                   \
392                             char *p = (x);              \
393                             while (p < pspace) {        \
394                                 if (*p == '/')          \
395                                     *p = '\\';          \
396                                 p++;                    \
397                             }                           \
398                         }                               \
399                     }
400 #else
401 #define fixcmd(x)
402 #endif
403     fixcmd(cmd);
404     PERL_FLUSHALL_FOR_CHILD;
405     return win32_popen(cmd, mode);
406 }
407
408 long
409 Perl_my_pclose(pTHX_ PerlIO *fp)
410 {
411     return win32_pclose(fp);
412 }
413 #endif
414
415 DllExport unsigned long
416 win32_os_id(void)
417 {
418     static OSVERSIONINFO osver;
419
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;
425     }
426     return (unsigned long)w32_platform;
427 }
428
429 DllExport int
430 win32_getpid(void)
431 {
432     int pid;
433 #ifdef USE_ITHREADS
434     dTHX;
435     if (w32_pseudo_id)
436         return -((int)w32_pseudo_id);
437 #endif
438     pid = _getpid();
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)
443         pid = -pid;
444     return pid;
445 }
446
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.
452  */
453 static long
454 tokenize(const char *str, char **dest, char ***destv)
455 {
456     char *retstart = Nullch;
457     char **retvstart = 0;
458     int items = -1;
459     if (str) {
460         dTHX;
461         int slen = strlen(str);
462         register char *ret;
463         register char **retv;
464         New(1307, ret, slen+2, char);
465         New(1308, retv, (slen+3)/2, char*);
466
467         retstart = ret;
468         retvstart = retv;
469         *retv = ret;
470         items = 0;
471         while (*str) {
472             *ret = *str++;
473             if (*ret == '\\' && *str)
474                 *ret = *str++;
475             else if (*ret == ' ') {
476                 while (*str == ' ')
477                     str++;
478                 if (ret == retstart)
479                     ret--;
480                 else {
481                     *ret = '\0';
482                     ++items;
483                     if (*str)
484                         *++retv = ret+1;
485                 }
486             }
487             else if (!*str)
488                 ++items;
489             ret++;
490         }
491         retvstart[items] = Nullch;
492         *ret++ = '\0';
493         *ret = '\0';
494     }
495     *dest = retstart;
496     *destv = retvstart;
497     return items;
498 }
499
500 static void
501 get_shell(void)
502 {
503     dTHX;
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
510          *     for).
511          */
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,
517                                        &w32_perlshell_vec);
518     }
519 }
520
521 int
522 do_aspawn(void *vreally, void **vmark, void **vsp)
523 {
524     dTHX;
525     SV *really = (SV*)vreally;
526     SV **mark = (SV**)vmark;
527     SV **sp = (SV**)vsp;
528     char **argv;
529     char *str;
530     int status;
531     int flag = P_WAIT;
532     int index = 0;
533
534     if (sp <= mark)
535         return -1;
536
537     get_shell();
538     New(1306, argv, (sp - mark) + w32_perlshell_items + 2, char*);
539
540     if (SvNIOKp(*(mark+1)) && !SvPOKp(*(mark+1))) {
541         ++mark;
542         flag = SvIVx(*mark);
543     }
544
545     while (++mark <= sp) {
546         if (*mark && (str = SvPV_nolen(*mark)))
547             argv[index++] = str;
548         else
549             argv[index++] = "";
550     }
551     argv[index++] = 0;
552    
553     status = win32_spawnvp(flag,
554                            (const char*)(really ? SvPV_nolen(really) : argv[0]),
555                            (const char* const*)argv);
556
557     if (status < 0 && (errno == ENOEXEC || errno == ENOENT)) {
558         /* possible shell-builtin, invoke with shell */
559         int sh_items;
560         sh_items = w32_perlshell_items;
561         while (--index >= 0)
562             argv[index+sh_items] = argv[index];
563         while (--sh_items >= 0)
564             argv[sh_items] = w32_perlshell_vec[sh_items];
565    
566         status = win32_spawnvp(flag,
567                                (const char*)(really ? SvPV_nolen(really) : argv[0]),
568                                (const char* const*)argv);
569     }
570
571     if (flag == P_NOWAIT) {
572         if (IsWin95())
573             PL_statusvalue = -1;        /* >16bits hint for pp_system() */
574     }
575     else {
576         if (status < 0) {
577             if (ckWARN(WARN_EXEC))
578                 Perl_warner(aTHX_ WARN_EXEC, "Can't spawn \"%s\": %s", argv[0], strerror(errno));
579             status = 255 * 256;
580         }
581         else
582             status *= 256;
583         PL_statusvalue = status;
584     }
585     Safefree(argv);
586     return (status);
587 }
588
589 int
590 do_spawn2(char *cmd, int exectype)
591 {
592     dTHX;
593     char **a;
594     char *s;
595     char **argv;
596     int status = -1;
597     BOOL needToTry = TRUE;
598     char *cmd2;
599
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);
605         strcpy(cmd2, cmd);
606         a = argv;
607         for (s = cmd2; *s;) {
608             bool in_quotes = FALSE;
609             while (*s && isSPACE(*s))
610                 s++;
611             if (*s)
612                 *(a++) = s;
613             while (*s) {
614                 /* ignore doubled backslashes, or backslash+quote */
615                 if (*s == '\\' && (s[1] == '\\' || s[1] == '"')) {
616                     s += 2;
617                 }
618                 /* keep track of when we're within quotes */
619                 else if (*s == '"') {
620                     s++;
621                     in_quotes = !in_quotes;
622                 }
623                 /* break it up only at spaces that aren't in quotes */
624                 else if (!in_quotes && isSPACE(*s))
625                     break;
626                 else
627                     s++;
628             }
629             if (*s)
630                 *s++ = '\0';
631         }
632         *a = Nullch;
633         if (argv[0]) {
634             switch (exectype) {
635             case EXECF_SPAWN:
636                 status = win32_spawnvp(P_WAIT, argv[0],
637                                        (const char* const*)argv);
638                 break;
639             case EXECF_SPAWN_NOWAIT:
640                 status = win32_spawnvp(P_NOWAIT, argv[0],
641                                        (const char* const*)argv);
642                 break;
643             case EXECF_EXEC:
644                 status = win32_execvp(argv[0], (const char* const*)argv);
645                 break;
646             }
647             if (status != -1 || errno == 0)
648                 needToTry = FALSE;
649         }
650         Safefree(argv);
651         Safefree(cmd2);
652     }
653     if (needToTry) {
654         char **argv;
655         int i = -1;
656         get_shell();
657         New(1306, argv, w32_perlshell_items + 2, char*);
658         while (++i < w32_perlshell_items)
659             argv[i] = w32_perlshell_vec[i];
660         argv[i++] = cmd;
661         argv[i] = Nullch;
662         switch (exectype) {
663         case EXECF_SPAWN:
664             status = win32_spawnvp(P_WAIT, argv[0],
665                                    (const char* const*)argv);
666             break;
667         case EXECF_SPAWN_NOWAIT:
668             status = win32_spawnvp(P_NOWAIT, argv[0],
669                                    (const char* const*)argv);
670             break;
671         case EXECF_EXEC:
672             status = win32_execvp(argv[0], (const char* const*)argv);
673             break;
674         }
675         cmd = argv[0];
676         Safefree(argv);
677     }
678     if (exectype == EXECF_SPAWN_NOWAIT) {
679         if (IsWin95())
680             PL_statusvalue = -1;        /* >16bits hint for pp_system() */
681     }
682     else {
683         if (status < 0) {
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));
688             status = 255 * 256;
689         }
690         else
691             status *= 256;
692         PL_statusvalue = status;
693     }
694     return (status);
695 }
696
697 int
698 do_spawn(char *cmd)
699 {
700     return do_spawn2(cmd, EXECF_SPAWN);
701 }
702
703 int
704 do_spawn_nowait(char *cmd)
705 {
706     return do_spawn2(cmd, EXECF_SPAWN_NOWAIT);
707 }
708
709 bool
710 Perl_do_exec(pTHX_ char *cmd)
711 {
712     do_spawn2(cmd, EXECF_EXEC);
713     return FALSE;
714 }
715
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.
719  */
720 DllExport DIR *
721 win32_opendir(char *filename)
722 {
723     dTHX;
724     DIR                 *dirp;
725     long                len;
726     long                idx;
727     char                scanname[MAX_PATH+3];
728     struct stat         sbuf;
729     WIN32_FIND_DATAA    aFindData;
730     WIN32_FIND_DATAW    wFindData;
731     HANDLE              fh;
732     char                buffer[MAX_PATH*2];
733     WCHAR               wbuffer[MAX_PATH+1];
734     char*               ptr;
735
736     len = strlen(filename);
737     if (len > MAX_PATH)
738         return NULL;
739
740     /* check to see if filename is a directory */
741     if (win32_stat(filename, &sbuf) < 0 || !S_ISDIR(sbuf.st_mode))
742         return NULL;
743
744     /* Get us a DIR structure */
745     Newz(1303, dirp, 1, DIR);
746
747     /* Create the search pattern */
748     strcpy(scanname, filename);
749
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++] = '/';
754     }
755     else if (scanname[len-1] != '/' && scanname[len-1] != '\\') {
756         scanname[len++] = '/';
757     }
758     scanname[len++] = '*';
759     scanname[len] = '\0';
760
761     /* do the FindFirstFile call */
762     if (USING_WIDE()) {
763         A2WHELPER(scanname, wbuffer, sizeof(wbuffer));
764         fh = FindFirstFileW(PerlDir_mapW(wbuffer), &wFindData);
765     }
766     else {
767         fh = FindFirstFileA(PerlDir_mapA(scanname), &aFindData);
768     }
769     dirp->handle = fh;
770     if (fh == INVALID_HANDLE_VALUE) {
771         DWORD err = GetLastError();
772         /* FindFirstFile() fails on empty drives! */
773         switch (err) {
774         case ERROR_FILE_NOT_FOUND:
775             return dirp;
776         case ERROR_NO_MORE_FILES:
777         case ERROR_PATH_NOT_FOUND:
778             errno = ENOENT;
779             break;
780         case ERROR_NOT_ENOUGH_MEMORY:
781             errno = ENOMEM;
782             break;
783         default:
784             errno = EINVAL;
785             break;
786         }
787         Safefree(dirp);
788         return NULL;
789     }
790
791     /* now allocate the first part of the string table for
792      * the filenames that we find.
793      */
794     if (USING_WIDE()) {
795         W2AHELPER(wFindData.cFileName, buffer, sizeof(buffer));
796         ptr = buffer;
797     }
798     else {
799         ptr = aFindData.cFileName;
800     }
801     idx = strlen(ptr)+1;
802     if (idx < 256)
803         dirp->size = 128;
804     else
805         dirp->size = idx;
806     New(1304, dirp->start, dirp->size, char);
807     strcpy(dirp->start, ptr);
808     dirp->nfiles++;
809     dirp->end = dirp->curr = dirp->start;
810     dirp->end += idx;
811     return dirp;
812 }
813
814
815 /* Readdir just returns the current string pointer and bumps the
816  * string pointer to the nDllExport entry.
817  */
818 DllExport struct direct *
819 win32_readdir(DIR *dirp)
820 {
821     long         len;
822
823     if (dirp->curr) {
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;
828
829         /* Fake an inode */
830         dirp->dirstr.d_ino = dirp->curr - dirp->start;
831
832         /* Now set up for the next call to readdir */
833         dirp->curr += len + 1;
834         if (dirp->curr >= dirp->end) {
835             dTHX;
836             char*               ptr;
837             BOOL                res;
838             WIN32_FIND_DATAW    wFindData;
839             WIN32_FIND_DATAA    aFindData;
840             char                buffer[MAX_PATH*2];
841
842             /* finding the next file that matches the wildcard
843              * (which should be all of them in this directory!).
844              */
845             if (USING_WIDE()) {
846                 res = FindNextFileW(dirp->handle, &wFindData);
847                 if (res) {
848                     W2AHELPER(wFindData.cFileName, buffer, sizeof(buffer));
849                     ptr = buffer;
850                 }
851             }
852             else {
853                 res = FindNextFileA(dirp->handle, &aFindData);
854                 if (res)
855                     ptr = aFindData.cFileName;
856             }
857             if (res) {
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;
864                     dirp->size *= 2;
865                     Renew(dirp->start, dirp->size, char);
866                     dirp->curr = dirp->start + curpos;
867                 }
868                 strcpy(dirp->start + endpos, ptr);
869                 dirp->end = dirp->start + newsize;
870                 dirp->nfiles++;
871             }
872             else
873                 dirp->curr = NULL;
874         }
875         return &(dirp->dirstr);
876     } 
877     else
878         return NULL;
879 }
880
881 /* Telldir returns the current string pointer position */
882 DllExport long
883 win32_telldir(DIR *dirp)
884 {
885     return (dirp->curr - dirp->start);
886 }
887
888
889 /* Seekdir moves the string pointer to a previously saved position
890  * (returned by telldir).
891  */
892 DllExport void
893 win32_seekdir(DIR *dirp, long loc)
894 {
895     dirp->curr = dirp->start + loc;
896 }
897
898 /* Rewinddir resets the string pointer to the start */
899 DllExport void
900 win32_rewinddir(DIR *dirp)
901 {
902     dirp->curr = dirp->start;
903 }
904
905 /* free the memory allocated by opendir */
906 DllExport int
907 win32_closedir(DIR *dirp)
908 {
909     dTHX;
910     if (dirp->handle != INVALID_HANDLE_VALUE)
911         FindClose(dirp->handle);
912     Safefree(dirp->start);
913     Safefree(dirp);
914     return 1;
915 }
916
917
918 /*
919  * various stubs
920  */
921
922
923 /* Ownership
924  *
925  * Just pretend that everyone is a superuser. NT will let us know if
926  * we don\'t really have permission to do something.
927  */
928
929 #define ROOT_UID    ((uid_t)0)
930 #define ROOT_GID    ((gid_t)0)
931
932 uid_t
933 getuid(void)
934 {
935     return ROOT_UID;
936 }
937
938 uid_t
939 geteuid(void)
940 {
941     return ROOT_UID;
942 }
943
944 gid_t
945 getgid(void)
946 {
947     return ROOT_GID;
948 }
949
950 gid_t
951 getegid(void)
952 {
953     return ROOT_GID;
954 }
955
956 int
957 setuid(uid_t auid)
958
959     return (auid == ROOT_UID ? 0 : -1);
960 }
961
962 int
963 setgid(gid_t agid)
964 {
965     return (agid == ROOT_GID ? 0 : -1);
966 }
967
968 char *
969 getlogin(void)
970 {
971     dTHX;
972     char *buf = w32_getlogin_buffer;
973     DWORD size = sizeof(w32_getlogin_buffer);
974     if (GetUserName(buf,&size))
975         return buf;
976     return (char*)NULL;
977 }
978
979 int
980 chown(const char *path, uid_t owner, gid_t group)
981 {
982     /* XXX noop */
983     return 0;
984 }
985
986 /*
987  * XXX this needs strengthening  (for PerlIO)
988  *   -- BKS, 11-11-200
989 */
990 int mkstemp(const char *path)
991 {
992     dTHX;
993     char buf[MAX_PATH+1];
994     int i = 0, fd = -1;
995
996 retry:
997     if (i++ > 10) { /* give up */
998         errno = ENOENT;
999         return -1;
1000     }
1001     if (!GetTempFileNameA((LPCSTR)path, "plr", 1, buf)) {
1002         errno = ENOENT;
1003         return -1;
1004     }
1005     fd = PerlLIO_open3(buf, O_CREAT|O_RDWR|O_EXCL, 0600);
1006     if (fd == -1)
1007         goto retry;
1008     return fd;
1009 }
1010
1011 static long
1012 find_pid(int pid)
1013 {
1014     dTHX;
1015     long child = w32_num_children;
1016     while (--child >= 0) {
1017         if (w32_child_pids[child] == pid)
1018             return child;
1019     }
1020     return -1;
1021 }
1022
1023 static void
1024 remove_dead_process(long child)
1025 {
1026     if (child >= 0) {
1027         dTHX;
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);
1033         w32_num_children--;
1034     }
1035 }
1036
1037 #ifdef USE_ITHREADS
1038 static long
1039 find_pseudo_pid(int pid)
1040 {
1041     dTHX;
1042     long child = w32_num_pseudo_children;
1043     while (--child >= 0) {
1044         if (w32_pseudo_child_pids[child] == pid)
1045             return child;
1046     }
1047     return -1;
1048 }
1049
1050 static void
1051 remove_dead_pseudo_process(long child)
1052 {
1053     if (child >= 0) {
1054         dTHX;
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--;
1061     }
1062 }
1063 #endif
1064
1065 DllExport int
1066 win32_kill(int pid, int sig)
1067 {
1068     dTHX;
1069     HANDLE hProcess;
1070     long child;
1071 #ifdef USE_ITHREADS
1072     if (pid < 0) {
1073         /* it is a pseudo-forked child */
1074         child = find_pseudo_pid(-pid);
1075         if (child >= 0) {
1076             if (!sig)
1077                 return 0;
1078             hProcess = w32_pseudo_child_handles[child];
1079             if (TerminateThread(hProcess, sig)) {
1080                 remove_dead_pseudo_process(child);
1081                 return 0;
1082             }
1083         }
1084         else if (IsWin95()) {
1085             pid = -pid;
1086             goto alien_process;
1087         }
1088     }
1089     else
1090 #endif
1091     {
1092         child = find_pid(pid);
1093         if (child >= 0) {
1094             if (!sig)
1095                 return 0;
1096             hProcess = w32_child_handles[child];
1097             if (TerminateProcess(hProcess, sig)) {
1098                 remove_dead_process(child);
1099                 return 0;
1100             }
1101         }
1102         else {
1103 alien_process:
1104             hProcess = OpenProcess(PROCESS_ALL_ACCESS, TRUE,
1105                                    (IsWin95() ? -pid : pid));
1106             if (hProcess) {
1107                 if (!sig)
1108                     return 0;
1109                 if (TerminateProcess(hProcess, sig)) {
1110                     CloseHandle(hProcess);
1111                     return 0;
1112                 }
1113             }
1114         }
1115     }
1116     errno = EINVAL;
1117     return -1;
1118 }
1119
1120 /*
1121  * File system stuff
1122  */
1123
1124 DllExport unsigned int
1125 win32_sleep(unsigned int t)
1126 {
1127     Sleep(t*1000);
1128     return 0;
1129 }
1130
1131 DllExport int
1132 win32_stat(const char *path, struct stat *sbuf)
1133 {
1134     dTHX;
1135     char        buffer[MAX_PATH+1]; 
1136     int         l = strlen(path);
1137     int         res;
1138     WCHAR       wbuffer[MAX_PATH+1];
1139     WCHAR*      pwbuffer;
1140     HANDLE      handle;
1141     int         nlink = 1;
1142
1143     if (l > 1) {
1144         switch(path[l - 1]) {
1145         /* FindFirstFile() and stat() are buggy with a trailing
1146          * backslash, so change it to a forward slash :-( */
1147         case '\\':
1148             strncpy(buffer, path, l-1);
1149             buffer[l - 1] = '/';
1150             buffer[l] = '\0';
1151             path = buffer;
1152             break;
1153         /* FindFirstFile() is buggy with "x:", so add a dot :-( */
1154         case ':':
1155             if (l == 2 && isALPHA(path[0])) {
1156                 buffer[0] = path[0];
1157                 buffer[1] = ':';
1158                 buffer[2] = '.';
1159                 buffer[3] = '\0';
1160                 l = 3;
1161                 path = buffer;
1162             }
1163             break;
1164         }
1165     }
1166
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.    */
1170     if (USING_WIDE()) {
1171         A2WHELPER(path, wbuffer, sizeof(wbuffer));
1172         pwbuffer = PerlDir_mapW(wbuffer);
1173         handle = CreateFileW(pwbuffer, 0, 0, NULL, OPEN_EXISTING, 0, NULL);
1174     }
1175     else {
1176         path = PerlDir_mapA(path);
1177         l = strlen(path);
1178         handle = CreateFileA(path, 0, 0, NULL, OPEN_EXISTING, 0, NULL);
1179     }
1180     if (handle != INVALID_HANDLE_VALUE) {
1181         BY_HANDLE_FILE_INFORMATION bhi;
1182         if (GetFileInformationByHandle(handle, &bhi))
1183             nlink = bhi.nNumberOfLinks;
1184         CloseHandle(handle);
1185     }
1186
1187     /* pwbuffer or path will be mapped correctly above */
1188     if (USING_WIDE()) {
1189         res = _wstat(pwbuffer, (struct _stat *)sbuf);
1190     }
1191     else {
1192         res = stat(path, sbuf);
1193     }
1194     sbuf->st_nlink = nlink;
1195
1196     if (res < 0) {
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) */
1201         DWORD r;
1202         if (USING_WIDE()) {
1203             r = GetFileAttributesW(pwbuffer);
1204         }
1205         else {
1206             r = GetFileAttributesA(path);
1207         }
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;
1212             errno = 0;
1213             if (!(r & FILE_ATTRIBUTE_READONLY))
1214                 sbuf->st_mode |= S_IWRITE | S_IEXEC;
1215             return 0;
1216         }
1217     }
1218     else {
1219         if (l == 3 && isALPHA(path[0]) && path[1] == ':'
1220             && (path[2] == '\\' || path[2] == '/'))
1221         {
1222             /* The drive can be inaccessible, some _stat()s are buggy */
1223             if (USING_WIDE()
1224                 ? !GetVolumeInformationW(pwbuffer,NULL,0,NULL,NULL,NULL,NULL,0)
1225                 : !GetVolumeInformationA(path,NULL,0,NULL,NULL,NULL,NULL,0)) {
1226                 errno = ENOENT;
1227                 return -1;
1228             }
1229         }
1230 #ifdef __BORLANDC__
1231         if (S_ISDIR(sbuf->st_mode))
1232             sbuf->st_mode |= S_IWRITE | S_IEXEC;
1233         else if (S_ISREG(sbuf->st_mode)) {
1234             int perms;
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;
1242                 else
1243                     sbuf->st_mode |= S_IEXEC;
1244             }
1245             else
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);
1250         }
1251 #endif
1252     }
1253     return res;
1254 }
1255
1256 /* Find the longname of a given path.  path is destructively modified.
1257  * It should have space for at least MAX_PATH characters. */
1258 DllExport char *
1259 win32_longpath(char *path)
1260 {
1261     WIN32_FIND_DATA fdata;
1262     HANDLE fhand;
1263     char tmpbuf[MAX_PATH+1];
1264     char *tmpstart = tmpbuf;
1265     char *start = path;
1266     char sep;
1267     if (!path)
1268         return Nullch;
1269
1270     /* drive prefix */
1271     if (isALPHA(path[0]) && path[1] == ':' &&
1272         (path[2] == '/' || path[2] == '\\'))
1273     {
1274         start = path + 2;
1275         *tmpstart++ = path[0];
1276         *tmpstart++ = ':';
1277     }
1278     /* UNC prefix */
1279     else if ((path[0] == '/' || path[0] == '\\') &&
1280              (path[1] == '/' || path[1] == '\\'))
1281     {
1282         start = path + 2;
1283         *tmpstart++ = path[0];
1284         *tmpstart++ = path[1];
1285         /* copy machine name */
1286         while (*start && *start != '/' && *start != '\\')
1287             *tmpstart++ = *start++;
1288         if (*start) {
1289             *tmpstart++ = *start;
1290             start++;
1291             /* copy share name */
1292             while (*start && *start != '/' && *start != '\\')
1293                 *tmpstart++ = *start++;
1294         }
1295     }
1296     sep = *start++;
1297     if (sep == '/' || sep == '\\')
1298         *tmpstart++ = sep;
1299     *tmpstart = '\0';
1300     while (sep) {
1301         /* walk up to slash */
1302         while (*start && *start != '/' && *start != '\\')
1303             ++start;
1304
1305         /* discard doubled slashes */
1306         while (*start && (start[1] == '/' || start[1] == '\\'))
1307             ++start;
1308         sep = *start;
1309
1310         /* stop and find full name of component */
1311         *start = '\0';
1312         fhand = FindFirstFile(path,&fdata);
1313         if (fhand != INVALID_HANDLE_VALUE) {
1314             strcpy(tmpstart, fdata.cFileName);
1315             tmpstart += strlen(fdata.cFileName);
1316             if (sep)
1317                 *tmpstart++ = sep;
1318             *tmpstart = '\0';
1319             *start++ = sep;
1320             FindClose(fhand);
1321         }
1322         else {
1323             /* failed a step, just return without side effects */
1324             /*PerlIO_printf(Perl_debug_log, "Failed to find %s\n", path);*/
1325             *start = sep;
1326             return Nullch;
1327         }
1328     }
1329     strcpy(path,tmpbuf);
1330     return path;
1331 }
1332
1333 DllExport char *
1334 win32_getenv(const char *name)
1335 {
1336     dTHX;
1337     WCHAR wBuffer[MAX_PATH+1];
1338     DWORD needlen;
1339     SV *curitem = Nullsv;
1340
1341     if (USING_WIDE()) {
1342         A2WHELPER(name, wBuffer, sizeof(wBuffer));
1343         needlen = GetEnvironmentVariableW(wBuffer, NULL, 0);
1344     }
1345     else
1346         needlen = GetEnvironmentVariableA(name,NULL,0);
1347     if (needlen != 0) {
1348         curitem = sv_2mortal(newSVpvn("", 0));
1349         if (USING_WIDE()) {
1350             SV *acuritem;
1351             do {
1352                 SvGROW(curitem, (needlen+1)*sizeof(WCHAR));
1353                 needlen = GetEnvironmentVariableW(wBuffer,
1354                                                   (WCHAR*)SvPVX(curitem),
1355                                                   needlen);
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));
1360         }
1361         else {
1362             do {
1363                 SvGROW(curitem, needlen+1);
1364                 needlen = GetEnvironmentVariableA(name,SvPVX(curitem),
1365                                                   needlen);
1366             } while (needlen >= SvLEN(curitem));
1367             SvCUR_set(curitem, needlen);
1368         }
1369     }
1370     else {
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);
1375     }
1376     if (curitem && SvCUR(curitem))
1377         return SvPVX(curitem);
1378
1379     return Nullch;
1380 }
1381
1382 DllExport int
1383 win32_putenv(const char *name)
1384 {
1385     dTHX;
1386     char* curitem;
1387     char* val;
1388     WCHAR* wCuritem;
1389     WCHAR* wVal;
1390     int length, relval = -1;
1391
1392     if (name) {
1393         if (USING_WIDE()) {
1394             length = strlen(name)+1;
1395             New(1309,wCuritem,length,WCHAR);
1396             A2WHELPER(name, wCuritem, length*sizeof(WCHAR));
1397             wVal = wcschr(wCuritem, '=');
1398             if (wVal) {
1399                 *wVal++ = '\0';
1400                 if (SetEnvironmentVariableW(wCuritem, *wVal ? wVal : NULL))
1401                     relval = 0;
1402             }
1403             Safefree(wCuritem);
1404         }
1405         else {
1406             New(1309,curitem,strlen(name)+1,char);
1407             strcpy(curitem, name);
1408             val = strchr(curitem, '=');
1409             if (val) {
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.
1415                  *  * Much faster.
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.
1422                  * GSAR 97-06-07
1423                  */
1424                 *val++ = '\0';
1425                 if (SetEnvironmentVariableA(curitem, *val ? val : NULL))
1426                     relval = 0;
1427             }
1428             Safefree(curitem);
1429         }
1430     }
1431     return relval;
1432 }
1433
1434 static long
1435 filetime_to_clock(PFILETIME ft)
1436 {
1437     __int64 qw = ft->dwHighDateTime;
1438     qw <<= 32;
1439     qw |= ft->dwLowDateTime;
1440     qw /= 10000;  /* File time ticks at 0.1uS, clock at 1mS */
1441     return (long) qw;
1442 }
1443
1444 DllExport int
1445 win32_times(struct tms *timebuf)
1446 {
1447     FILETIME user;
1448     FILETIME kernel;
1449     FILETIME dummy;
1450     if (GetProcessTimes(GetCurrentProcess(), &dummy, &dummy, 
1451                         &kernel,&user)) {
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;
1456         
1457     } else { 
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;
1464     }
1465     return 0;
1466 }
1467
1468 /* fix utime() so it works on directories in NT */
1469 static BOOL
1470 filetime_from_time(PFILETIME pFileTime, time_t Time)
1471 {
1472     struct tm *pTM = localtime(&Time);
1473     SYSTEMTIME SystemTime;
1474     FILETIME LocalTime;
1475
1476     if (pTM == NULL)
1477         return FALSE;
1478
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;
1486
1487     return SystemTimeToFileTime(&SystemTime, &LocalTime) &&
1488            LocalFileTimeToFileTime(&LocalTime, pFileTime);
1489 }
1490
1491 DllExport int
1492 win32_unlink(const char *filename)
1493 {
1494     dTHX;
1495     int ret;
1496     DWORD attrs;
1497
1498     if (USING_WIDE()) {
1499         WCHAR wBuffer[MAX_PATH+1];
1500         WCHAR* pwBuffer;
1501
1502         A2WHELPER(filename, wBuffer, sizeof(wBuffer));
1503         pwBuffer = PerlDir_mapW(wBuffer);
1504         attrs = GetFileAttributesW(pwBuffer);
1505         if (attrs == 0xFFFFFFFF)
1506             goto fail;
1507         if (attrs & FILE_ATTRIBUTE_READONLY) {
1508             (void)SetFileAttributesW(pwBuffer, attrs & ~FILE_ATTRIBUTE_READONLY);
1509             ret = _wunlink(pwBuffer);
1510             if (ret == -1)
1511                 (void)SetFileAttributesW(pwBuffer, attrs);
1512         }
1513         else
1514             ret = _wunlink(pwBuffer);
1515     }
1516     else {
1517         filename = PerlDir_mapA(filename);
1518         attrs = GetFileAttributesA(filename);
1519         if (attrs == 0xFFFFFFFF)
1520             goto fail;
1521         if (attrs & FILE_ATTRIBUTE_READONLY) {
1522             (void)SetFileAttributesA(filename, attrs & ~FILE_ATTRIBUTE_READONLY);
1523             ret = unlink(filename);
1524             if (ret == -1)
1525                 (void)SetFileAttributesA(filename, attrs);
1526         }
1527         else
1528             ret = unlink(filename);
1529     }
1530     return ret;
1531 fail:
1532     errno = ENOENT;
1533     return -1;
1534 }
1535
1536 DllExport int
1537 win32_utime(const char *filename, struct utimbuf *times)
1538 {
1539     dTHX;
1540     HANDLE handle;
1541     FILETIME ftCreate;
1542     FILETIME ftAccess;
1543     FILETIME ftWrite;
1544     struct utimbuf TimeBuffer;
1545     WCHAR wbuffer[MAX_PATH+1];
1546     WCHAR* pwbuffer;
1547
1548     int rc;
1549     if (USING_WIDE()) {
1550         A2WHELPER(filename, wbuffer, sizeof(wbuffer));
1551         pwbuffer = PerlDir_mapW(wbuffer);
1552         rc = _wutime(pwbuffer, (struct _utimbuf*)times);
1553     }
1554     else {
1555         filename = PerlDir_mapA(filename);
1556         rc = utime(filename, times);
1557     }
1558     /* EACCES: path specifies directory or readonly file */
1559     if (rc == 0 || errno != EACCES /* || !IsWinNT() */)
1560         return rc;
1561
1562     if (times == NULL) {
1563         times = &TimeBuffer;
1564         time(&times->actime);
1565         times->modtime = times->actime;
1566     }
1567
1568     /* This will (and should) still fail on readonly files */
1569     if (USING_WIDE()) {
1570         handle = CreateFileW(pwbuffer, GENERIC_READ | GENERIC_WRITE,
1571                             FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1572                             OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1573     }
1574     else {
1575         handle = CreateFileA(filename, GENERIC_READ | GENERIC_WRITE,
1576                             FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1577                             OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1578     }
1579     if (handle == INVALID_HANDLE_VALUE)
1580         return rc;
1581
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))
1586     {
1587         rc = 0;
1588     }
1589
1590     CloseHandle(handle);
1591     return rc;
1592 }
1593
1594 DllExport int
1595 win32_uname(struct utsname *name)
1596 {
1597     struct hostent *hep;
1598     STRLEN nodemax = sizeof(name->nodename)-1;
1599     OSVERSIONINFO osver;
1600
1601     memset(&osver, 0, sizeof(OSVERSIONINFO));
1602     osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1603     if (GetVersionEx(&osver)) {
1604         /* sysname */
1605         switch (osver.dwPlatformId) {
1606         case VER_PLATFORM_WIN32_WINDOWS:
1607             strcpy(name->sysname, "Windows");
1608             break;
1609         case VER_PLATFORM_WIN32_NT:
1610             strcpy(name->sysname, "Windows NT");
1611             break;
1612         case VER_PLATFORM_WIN32s:
1613             strcpy(name->sysname, "Win32s");
1614             break;
1615         default:
1616             strcpy(name->sysname, "Win32 Unknown");
1617             break;
1618         }
1619
1620         /* release */
1621         sprintf(name->release, "%d.%d",
1622                 osver.dwMajorVersion, osver.dwMinorVersion);
1623
1624         /* version */
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);
1631         }
1632     }
1633     else {
1634         *name->sysname = '\0';
1635         *name->version = '\0';
1636         *name->release = '\0';
1637     }
1638
1639     /* nodename */
1640     hep = win32_gethostbyname("localhost");
1641     if (hep) {
1642         STRLEN len = strlen(hep->h_name);
1643         if (len <= nodemax) {
1644             strcpy(name->nodename, hep->h_name);
1645         }
1646         else {
1647             strncpy(name->nodename, hep->h_name, nodemax);
1648             name->nodename[nodemax] = '\0';
1649         }
1650     }
1651     else {
1652         DWORD sz = nodemax;
1653         if (!GetComputerName(name->nodename, &sz))
1654             *name->nodename = '\0';
1655     }
1656
1657     /* machine (architecture) */
1658     {
1659         SYSTEM_INFO info;
1660         char *arch;
1661         GetSystemInfo(&info);
1662
1663 #if (defined(__BORLANDC__)&&(__BORLANDC__<=0x520)) \
1664  || (defined(__MINGW32__) && !defined(_ANONYMOUS_UNION))
1665         switch (info.u.s.wProcessorArchitecture) {
1666 #else
1667         switch (info.wProcessorArchitecture) {
1668 #endif
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;
1677         default:
1678             arch = "unknown"; break;
1679         }
1680         strcpy(name->machine, arch);
1681     }
1682     return 0;
1683 }
1684
1685 DllExport int
1686 win32_waitpid(int pid, int *status, int flags)
1687 {
1688     dTHX;
1689     DWORD timeout = (flags & WNOHANG) ? 0 : INFINITE;
1690     int retval = -1;
1691     long child;
1692     if (pid == -1)                              /* XXX threadid == 1 ? */
1693         return win32_wait(status);
1694 #ifdef USE_ITHREADS
1695     else if (pid < 0) {
1696         child = find_pseudo_pid(-pid);
1697         if (child >= 0) {
1698             HANDLE hThread = w32_pseudo_child_handles[child];
1699             DWORD waitcode = WaitForSingleObject(hThread, timeout);
1700             if (waitcode == WAIT_TIMEOUT) {
1701                 return 0;
1702             }
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);
1708                     return -retval;
1709                 }
1710             }
1711             else
1712                 errno = ECHILD;
1713         }
1714         else if (IsWin95()) {
1715             pid = -pid;
1716             goto alien_process;
1717         }
1718     }
1719 #endif
1720     else {
1721         HANDLE hProcess;
1722         DWORD waitcode;
1723         child = find_pid(pid);
1724         if (child >= 0) {
1725             hProcess = w32_child_handles[child];
1726             waitcode = WaitForSingleObject(hProcess, timeout);
1727             if (waitcode == WAIT_TIMEOUT) {
1728                 return 0;
1729             }
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);
1735                     return retval;
1736                 }
1737             }
1738             else
1739                 errno = ECHILD;
1740         }
1741         else {
1742 alien_process:
1743             hProcess = OpenProcess(PROCESS_ALL_ACCESS, TRUE,
1744                                    (IsWin95() ? -pid : pid));
1745             if (hProcess) {
1746                 waitcode = WaitForSingleObject(hProcess, timeout);
1747                 if (waitcode == WAIT_TIMEOUT) {
1748                     return 0;
1749                 }
1750                 else if (waitcode != WAIT_FAILED) {
1751                     if (GetExitCodeProcess(hProcess, &waitcode)) {
1752                         *status = (int)((waitcode & 0xff) << 8);
1753                         CloseHandle(hProcess);
1754                         return pid;
1755                     }
1756                 }
1757                 CloseHandle(hProcess);
1758             }
1759             else
1760                 errno = ECHILD;
1761         }
1762     }
1763     return retval >= 0 ? pid : retval;                
1764 }
1765
1766 DllExport int
1767 win32_wait(int *status)
1768 {
1769     /* XXX this wait emulation only knows about processes
1770      * spawned via win32_spawnvp(P_NOWAIT, ...).
1771      */
1772     dTHX;
1773     int i, retval;
1774     DWORD exitcode, waitcode;
1775
1776 #ifdef USE_ITHREADS
1777     if (w32_num_pseudo_children) {
1778         waitcode = WaitForMultipleObjects(w32_num_pseudo_children,
1779                                           w32_pseudo_child_handles,
1780                                           FALSE,
1781                                           INFINITE);
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;
1786             else
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);
1792                 return -retval;
1793             }
1794         }
1795     }
1796 #endif
1797
1798     if (!w32_num_children) {
1799         errno = ECHILD;
1800         return -1;
1801     }
1802
1803     /* if a child exists, wait for it to die */
1804     waitcode = WaitForMultipleObjects(w32_num_children,
1805                                       w32_child_handles,
1806                                       FALSE,
1807                                       INFINITE);
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;
1812         else
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);
1818             return retval;
1819         }
1820     }
1821
1822 FAILED:
1823     errno = GetLastError();
1824     return -1;
1825 }
1826
1827 #ifndef PERL_IMPLICIT_CONTEXT
1828
1829 static UINT timerid = 0;
1830
1831 static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
1832 {
1833     dTHX;
1834     KillTimer(NULL,timerid);
1835     timerid=0;  
1836     CALL_FPTR(PL_sighandlerp)(14);
1837 }
1838
1839 #endif /* !PERL_IMPLICIT_CONTEXT */
1840
1841 DllExport unsigned int
1842 win32_alarm(unsigned int sec)
1843 {
1844 #ifndef PERL_IMPLICIT_CONTEXT
1845     /* 
1846      * the 'obvious' implentation is SetTimer() with a callback
1847      * which does whatever receiving SIGALRM would do 
1848      * we cannot use SIGALRM even via raise() as it is not 
1849      * one of the supported codes in <signal.h>
1850      *
1851      * Snag is unless something is looking at the message queue
1852      * nothing happens :-(
1853      */ 
1854     dTHX;
1855     if (sec)
1856      {
1857       timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
1858       if (!timerid)
1859        Perl_croak_nocontext("Cannot set timer");
1860      } 
1861     else
1862      {
1863       if (timerid)
1864        {
1865         KillTimer(NULL,timerid);
1866         timerid=0;  
1867        }
1868      }
1869 #endif /* !PERL_IMPLICIT_CONTEXT */
1870     return 0;
1871 }
1872
1873 #ifdef HAVE_DES_FCRYPT
1874 extern char *   des_fcrypt(const char *txt, const char *salt, char *cbuf);
1875 #endif
1876
1877 DllExport char *
1878 win32_crypt(const char *txt, const char *salt)
1879 {
1880     dTHX;
1881 #ifdef HAVE_DES_FCRYPT
1882     return des_fcrypt(txt, salt, w32_crypt_buffer);
1883 #else
1884     Perl_croak(aTHX_ "The crypt() function is unimplemented due to excessive paranoia.");
1885     return Nullch;
1886 #endif
1887 }
1888
1889 #ifdef USE_FIXED_OSFHANDLE
1890
1891 #define FOPEN                   0x01    /* file handle open */
1892 #define FNOINHERIT              0x10    /* file handle opened O_NOINHERIT */
1893 #define FAPPEND                 0x20    /* file handle opened O_APPEND */
1894 #define FDEV                    0x40    /* file handle refers to device */
1895 #define FTEXT                   0x80    /* file handle is in text mode */
1896
1897 /***
1898 *int my_open_osfhandle(long osfhandle, int flags) - open C Runtime file handle
1899 *
1900 *Purpose:
1901 *       This function allocates a free C Runtime file handle and associates
1902 *       it with the Win32 HANDLE specified by the first parameter. This is a
1903 *       temperary fix for WIN95's brain damage GetFileType() error on socket
1904 *       we just bypass that call for socket
1905 *
1906 *       This works with MSVC++ 4.0+ or GCC/Mingw32
1907 *
1908 *Entry:
1909 *       long osfhandle - Win32 HANDLE to associate with C Runtime file handle.
1910 *       int flags      - flags to associate with C Runtime file handle.
1911 *
1912 *Exit:
1913 *       returns index of entry in fh, if successful
1914 *       return -1, if no free entry is found
1915 *
1916 *Exceptions:
1917 *
1918 *******************************************************************************/
1919
1920 /*
1921  * we fake up some parts of the CRT that aren't exported by MSVCRT.dll
1922  * this lets sockets work on Win9X with GCC and should fix the problems
1923  * with perl95.exe
1924  *      -- BKS, 1-23-2000
1925 */
1926
1927 /* create an ioinfo entry, kill its handle, and steal the entry */
1928
1929 static int
1930 _alloc_osfhnd(void)
1931 {
1932     HANDLE hF = CreateFile("NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
1933     int fh = _open_osfhandle((long)hF, 0);
1934     CloseHandle(hF);
1935     if (fh == -1)
1936         return fh;
1937     EnterCriticalSection(&(_pioinfo(fh)->lock));
1938     return fh;
1939 }
1940
1941 static int
1942 my_open_osfhandle(long osfhandle, int flags)
1943 {
1944     int fh;
1945     char fileflags;             /* _osfile flags */
1946
1947     /* copy relevant flags from second parameter */
1948     fileflags = FDEV;
1949
1950     if (flags & O_APPEND)
1951         fileflags |= FAPPEND;
1952
1953     if (flags & O_TEXT)
1954         fileflags |= FTEXT;
1955
1956     if (flags & O_NOINHERIT)
1957         fileflags |= FNOINHERIT;
1958
1959     /* attempt to allocate a C Runtime file handle */
1960     if ((fh = _alloc_osfhnd()) == -1) {
1961         errno = EMFILE;         /* too many open files */
1962         _doserrno = 0L;         /* not an OS error */
1963         return -1;              /* return error to caller */
1964     }
1965
1966     /* the file is open. now, set the info in _osfhnd array */
1967     _set_osfhnd(fh, osfhandle);
1968
1969     fileflags |= FOPEN;         /* mark as open */
1970
1971     _osfile(fh) = fileflags;    /* set osfile entry */
1972     LeaveCriticalSection(&_pioinfo(fh)->lock);
1973
1974     return fh;                  /* return handle */
1975 }
1976
1977 #endif  /* USE_FIXED_OSFHANDLE */
1978
1979 /* simulate flock by locking a range on the file */
1980
1981 #define LK_ERR(f,i)     ((f) ? (i = 0) : (errno = GetLastError()))
1982 #define LK_LEN          0xffff0000
1983
1984 DllExport int
1985 win32_flock(int fd, int oper)
1986 {
1987     OVERLAPPED o;
1988     int i = -1;
1989     HANDLE fh;
1990
1991     if (!IsWinNT()) {
1992         dTHX;
1993         Perl_croak_nocontext("flock() unimplemented on this platform");
1994         return -1;
1995     }
1996     fh = (HANDLE)_get_osfhandle(fd);
1997     memset(&o, 0, sizeof(o));
1998
1999     switch(oper) {
2000     case LOCK_SH:               /* shared lock */
2001         LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
2002         break;
2003     case LOCK_EX:               /* exclusive lock */
2004         LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
2005         break;
2006     case LOCK_SH|LOCK_NB:       /* non-blocking shared lock */
2007         LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
2008         break;
2009     case LOCK_EX|LOCK_NB:       /* non-blocking exclusive lock */
2010         LK_ERR(LockFileEx(fh,
2011                        LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
2012                        0, LK_LEN, 0, &o),i);
2013         break;
2014     case LOCK_UN:               /* unlock lock */
2015         LK_ERR(UnlockFileEx(fh, 0, LK_LEN, 0, &o),i);
2016         break;
2017     default:                    /* unknown */
2018         errno = EINVAL;
2019         break;
2020     }
2021     return i;
2022 }
2023
2024 #undef LK_ERR
2025 #undef LK_LEN
2026
2027 /*
2028  *  redirected io subsystem for all XS modules
2029  *
2030  */
2031
2032 DllExport int *
2033 win32_errno(void)
2034 {
2035     return (&errno);
2036 }
2037
2038 DllExport char ***
2039 win32_environ(void)
2040 {
2041     return (&(_environ));
2042 }
2043
2044 /* the rest are the remapped stdio routines */
2045 DllExport FILE *
2046 win32_stderr(void)
2047 {
2048     return (stderr);
2049 }
2050
2051 DllExport FILE *
2052 win32_stdin(void)
2053 {
2054     return (stdin);
2055 }
2056
2057 DllExport FILE *
2058 win32_stdout()
2059 {
2060     return (stdout);
2061 }
2062
2063 DllExport int
2064 win32_ferror(FILE *fp)
2065 {
2066     return (ferror(fp));
2067 }
2068
2069
2070 DllExport int
2071 win32_feof(FILE *fp)
2072 {
2073     return (feof(fp));
2074 }
2075
2076 /*
2077  * Since the errors returned by the socket error function 
2078  * WSAGetLastError() are not known by the library routine strerror
2079  * we have to roll our own.
2080  */
2081
2082 DllExport char *
2083 win32_strerror(int e) 
2084 {
2085 #if !defined __BORLANDC__ && !defined __MINGW32__      /* compiler intolerance */
2086     extern int sys_nerr;
2087 #endif
2088     DWORD source = 0;
2089
2090     if (e < 0 || e > sys_nerr) {
2091         dTHX;
2092         if (e < 0)
2093             e = GetLastError();
2094
2095         if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
2096                           w32_strerror_buffer,
2097                           sizeof(w32_strerror_buffer), NULL) == 0) 
2098             strcpy(w32_strerror_buffer, "Unknown Error");
2099
2100         return w32_strerror_buffer;
2101     }
2102     return strerror(e);
2103 }
2104
2105 DllExport void
2106 win32_str_os_error(void *sv, DWORD dwErr)
2107 {
2108     DWORD dwLen;
2109     char *sMsg;
2110     dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
2111                           |FORMAT_MESSAGE_IGNORE_INSERTS
2112                           |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
2113                            dwErr, 0, (char *)&sMsg, 1, NULL);
2114     /* strip trailing whitespace and period */
2115     if (0 < dwLen) {
2116         do {
2117             --dwLen;    /* dwLen doesn't include trailing null */
2118         } while (0 < dwLen && isSPACE(sMsg[dwLen]));
2119         if ('.' != sMsg[dwLen])
2120             dwLen++;
2121         sMsg[dwLen] = '\0';
2122     }
2123     if (0 == dwLen) {
2124         sMsg = (char*)LocalAlloc(0, 64/**sizeof(TCHAR)*/);
2125         if (sMsg)
2126             dwLen = sprintf(sMsg,
2127                             "Unknown error #0x%lX (lookup 0x%lX)",
2128                             dwErr, GetLastError());
2129     }
2130     if (sMsg) {
2131         dTHX;
2132         sv_setpvn((SV*)sv, sMsg, dwLen);
2133         LocalFree(sMsg);
2134     }
2135 }
2136
2137 DllExport int
2138 win32_fprintf(FILE *fp, const char *format, ...)
2139 {
2140     va_list marker;
2141     va_start(marker, format);     /* Initialize variable arguments. */
2142
2143     return (vfprintf(fp, format, marker));
2144 }
2145
2146 DllExport int
2147 win32_printf(const char *format, ...)
2148 {
2149     va_list marker;
2150     va_start(marker, format);     /* Initialize variable arguments. */
2151
2152     return (vprintf(format, marker));
2153 }
2154
2155 DllExport int
2156 win32_vfprintf(FILE *fp, const char *format, va_list args)
2157 {
2158     return (vfprintf(fp, format, args));
2159 }
2160
2161 DllExport int
2162 win32_vprintf(const char *format, va_list args)
2163 {
2164     return (vprintf(format, args));
2165 }
2166
2167 DllExport size_t
2168 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
2169 {
2170     return fread(buf, size, count, fp);
2171 }
2172
2173 DllExport size_t
2174 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
2175 {
2176     return fwrite(buf, size, count, fp);
2177 }
2178
2179 #define MODE_SIZE 10
2180
2181 DllExport FILE *
2182 win32_fopen(const char *filename, const char *mode)
2183 {
2184     dTHX;
2185     WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH+1];
2186     FILE *f;
2187     
2188     if (!*filename)
2189         return NULL;
2190
2191     if (stricmp(filename, "/dev/null")==0)
2192         filename = "NUL";
2193
2194     if (USING_WIDE()) {
2195         A2WHELPER(mode, wMode, sizeof(wMode));
2196         A2WHELPER(filename, wBuffer, sizeof(wBuffer));
2197         f = _wfopen(PerlDir_mapW(wBuffer), wMode);
2198     }
2199     else
2200         f = fopen(PerlDir_mapA(filename), mode);
2201     /* avoid buffering headaches for child processes */
2202     if (f && *mode == 'a')
2203         win32_fseek(f, 0, SEEK_END);
2204     return f;
2205 }
2206
2207 #ifndef USE_SOCKETS_AS_HANDLES
2208 #undef fdopen
2209 #define fdopen my_fdopen
2210 #endif
2211
2212 DllExport FILE *
2213 win32_fdopen(int handle, const char *mode)
2214 {
2215     dTHX;
2216     WCHAR wMode[MODE_SIZE];
2217     FILE *f;
2218     if (USING_WIDE()) {
2219         A2WHELPER(mode, wMode, sizeof(wMode));
2220         f = _wfdopen(handle, wMode);
2221     }
2222     else
2223         f = fdopen(handle, (char *) mode);
2224     /* avoid buffering headaches for child processes */
2225     if (f && *mode == 'a')
2226         win32_fseek(f, 0, SEEK_END);
2227     return f;
2228 }
2229
2230 DllExport FILE *
2231 win32_freopen(const char *path, const char *mode, FILE *stream)
2232 {
2233     dTHX;
2234     WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH+1];
2235     if (stricmp(path, "/dev/null")==0)
2236         path = "NUL";
2237
2238     if (USING_WIDE()) {
2239         A2WHELPER(mode, wMode, sizeof(wMode));
2240         A2WHELPER(path, wBuffer, sizeof(wBuffer));
2241         return _wfreopen(PerlDir_mapW(wBuffer), wMode, stream);
2242     }
2243     return freopen(PerlDir_mapA(path), mode, stream);
2244 }
2245
2246 DllExport int
2247 win32_fclose(FILE *pf)
2248 {
2249     return my_fclose(pf);       /* defined in win32sck.c */
2250 }
2251
2252 DllExport int
2253 win32_fputs(const char *s,FILE *pf)
2254 {
2255     return fputs(s, pf);
2256 }
2257
2258 DllExport int
2259 win32_fputc(int c,FILE *pf)
2260 {
2261     return fputc(c,pf);
2262 }
2263
2264 DllExport int
2265 win32_ungetc(int c,FILE *pf)
2266 {
2267     return ungetc(c,pf);
2268 }
2269
2270 DllExport int
2271 win32_getc(FILE *pf)
2272 {
2273     return getc(pf);
2274 }
2275
2276 DllExport int
2277 win32_fileno(FILE *pf)
2278 {
2279     return fileno(pf);
2280 }
2281
2282 DllExport void
2283 win32_clearerr(FILE *pf)
2284 {
2285     clearerr(pf);
2286     return;
2287 }
2288
2289 DllExport int
2290 win32_fflush(FILE *pf)
2291 {
2292     return fflush(pf);
2293 }
2294
2295 DllExport long
2296 win32_ftell(FILE *pf)
2297 {
2298     return ftell(pf);
2299 }
2300
2301 DllExport int
2302 win32_fseek(FILE *pf,long offset,int origin)
2303 {
2304     return fseek(pf, offset, origin);
2305 }
2306
2307 DllExport int
2308 win32_fgetpos(FILE *pf,fpos_t *p)
2309 {
2310     return fgetpos(pf, p);
2311 }
2312
2313 DllExport int
2314 win32_fsetpos(FILE *pf,const fpos_t *p)
2315 {
2316     return fsetpos(pf, p);
2317 }
2318
2319 DllExport void
2320 win32_rewind(FILE *pf)
2321 {
2322     rewind(pf);
2323     return;
2324 }
2325
2326 DllExport FILE*
2327 win32_tmpfile(void)
2328 {
2329     dTHX;
2330     char prefix[MAX_PATH+1];
2331     char filename[MAX_PATH+1];
2332     DWORD len = GetTempPath(MAX_PATH, prefix);
2333     if (len && len < MAX_PATH) {
2334         if (GetTempFileName(prefix, "plx", 0, filename)) {
2335             HANDLE fh = CreateFile(filename,
2336                                    DELETE | GENERIC_READ | GENERIC_WRITE,
2337                                    0,
2338                                    NULL,
2339                                    CREATE_ALWAYS,
2340                                    FILE_ATTRIBUTE_NORMAL
2341                                    | FILE_FLAG_DELETE_ON_CLOSE,
2342                                    NULL);
2343             if (fh != INVALID_HANDLE_VALUE) {
2344                 int fd = win32_open_osfhandle((long)fh, 0);
2345                 if (fd >= 0) {
2346                     DEBUG_p(PerlIO_printf(Perl_debug_log,
2347                                           "Created tmpfile=%s\n",filename));
2348                     return fdopen(fd, "w+b");
2349                 }
2350             }
2351         }
2352     }
2353     return NULL;
2354 }
2355
2356 DllExport void
2357 win32_abort(void)
2358 {
2359     abort();
2360     return;
2361 }
2362
2363 DllExport int
2364 win32_fstat(int fd,struct stat *sbufptr)
2365 {
2366 #ifdef __BORLANDC__
2367     /* A file designated by filehandle is not shown as accessible
2368      * for write operations, probably because it is opened for reading.
2369      * --Vadim Konovalov
2370      */ 
2371     int rc = fstat(fd,sbufptr);
2372     BY_HANDLE_FILE_INFORMATION bhfi;
2373     if (GetFileInformationByHandle((HANDLE)_get_osfhandle(fd), &bhfi)) {
2374         sbufptr->st_mode &= 0xFE00;
2375         if (bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
2376             sbufptr->st_mode |= (S_IREAD + (S_IREAD >> 3) + (S_IREAD >> 6));
2377         else
2378             sbufptr->st_mode |= ((S_IREAD|S_IWRITE) + ((S_IREAD|S_IWRITE) >> 3)
2379               + ((S_IREAD|S_IWRITE) >> 6));
2380     }
2381     return rc;
2382 #else
2383     return my_fstat(fd,sbufptr);
2384 #endif
2385 }
2386
2387 DllExport int
2388 win32_pipe(int *pfd, unsigned int size, int mode)
2389 {
2390     return _pipe(pfd, size, mode);
2391 }
2392
2393 DllExport PerlIO*
2394 win32_popenlist(const char *mode, IV narg, SV **args)
2395 {
2396  dTHX;
2397  Perl_croak(aTHX_ "List form of pipe open not implemented");
2398  return NULL;
2399 }
2400
2401 /*
2402  * a popen() clone that respects PERL5SHELL
2403  *
2404  * changed to return PerlIO* rather than FILE * by BKS, 11-11-2000
2405  */
2406
2407 DllExport PerlIO*
2408 win32_popen(const char *command, const char *mode)
2409 {
2410 #ifdef USE_RTL_POPEN
2411     return _popen(command, mode);
2412 #else
2413     int p[2];
2414     int parent, child;
2415     int stdfd, oldfd;
2416     int ourmode;
2417     int childpid;
2418
2419     /* establish which ends read and write */
2420     if (strchr(mode,'w')) {
2421         stdfd = 0;              /* stdin */
2422         parent = 1;
2423         child = 0;
2424     }
2425     else if (strchr(mode,'r')) {
2426         stdfd = 1;              /* stdout */
2427         parent = 0;
2428         child = 1;
2429     }
2430     else
2431         return NULL;
2432
2433     /* set the correct mode */
2434     if (strchr(mode,'b'))
2435         ourmode = O_BINARY;
2436     else if (strchr(mode,'t'))
2437         ourmode = O_TEXT;
2438     else
2439         ourmode = _fmode & (O_TEXT | O_BINARY);
2440
2441     /* the child doesn't inherit handles */
2442     ourmode |= O_NOINHERIT;
2443
2444     if (win32_pipe( p, 512, ourmode) == -1)
2445         return NULL;
2446
2447     /* save current stdfd */
2448     if ((oldfd = win32_dup(stdfd)) == -1)
2449         goto cleanup;
2450
2451     /* make stdfd go to child end of pipe (implicitly closes stdfd) */
2452     /* stdfd will be inherited by the child */
2453     if (win32_dup2(p[child], stdfd) == -1)
2454         goto cleanup;
2455
2456     /* close the child end in parent */
2457     win32_close(p[child]);
2458
2459     /* start the child */
2460     {
2461         dTHX;
2462         if ((childpid = do_spawn_nowait((char*)command)) == -1)
2463             goto cleanup;
2464
2465         /* revert stdfd to whatever it was before */
2466         if (win32_dup2(oldfd, stdfd) == -1)
2467             goto cleanup;
2468
2469         /* close saved handle */
2470         win32_close(oldfd);
2471
2472         LOCK_FDPID_MUTEX;
2473         sv_setiv(*av_fetch(w32_fdpid, p[parent], TRUE), childpid);
2474         UNLOCK_FDPID_MUTEX;
2475
2476         /* set process id so that it can be returned by perl's open() */
2477         PL_forkprocess = childpid;
2478     }
2479
2480     /* we have an fd, return a file stream */
2481     return (PerlIO_fdopen(p[parent], (char *)mode));
2482
2483 cleanup:
2484     /* we don't need to check for errors here */
2485     win32_close(p[0]);
2486     win32_close(p[1]);
2487     if (oldfd != -1) {
2488         win32_dup2(oldfd, stdfd);
2489         win32_close(oldfd);
2490     }
2491     return (NULL);
2492
2493 #endif /* USE_RTL_POPEN */
2494 }
2495
2496 /*
2497  * pclose() clone
2498  */
2499
2500 DllExport int
2501 win32_pclose(PerlIO *pf)
2502 {
2503 #ifdef USE_RTL_POPEN
2504     return _pclose(pf);
2505 #else
2506     dTHX;
2507     int childpid, status;
2508     SV *sv;
2509
2510     LOCK_FDPID_MUTEX;
2511     sv = *av_fetch(w32_fdpid, PerlIO_fileno(pf), TRUE);
2512
2513     if (SvIOK(sv))
2514         childpid = SvIVX(sv);
2515     else
2516         childpid = 0;
2517
2518     if (!childpid) {
2519         errno = EBADF;
2520         return -1;
2521     }
2522
2523 #ifdef USE_PERLIO
2524     PerlIO_close(pf);
2525 #else
2526     fclose(pf);
2527 #endif
2528     SvIVX(sv) = 0;
2529     UNLOCK_FDPID_MUTEX;
2530
2531     if (win32_waitpid(childpid, &status, 0) == -1)
2532         return -1;
2533
2534     return status;
2535
2536 #endif /* USE_RTL_POPEN */
2537 }
2538
2539 static BOOL WINAPI
2540 Nt4CreateHardLinkW(
2541     LPCWSTR lpFileName,
2542     LPCWSTR lpExistingFileName,
2543     LPSECURITY_ATTRIBUTES lpSecurityAttributes)
2544 {
2545     HANDLE handle;
2546     WCHAR wFullName[MAX_PATH+1];
2547     LPVOID lpContext = NULL;
2548     WIN32_STREAM_ID StreamId;
2549     DWORD dwSize = (char*)&StreamId.cStreamName - (char*)&StreamId;
2550     DWORD dwWritten;
2551     DWORD dwLen;
2552     BOOL bSuccess;
2553
2554     BOOL (__stdcall *pfnBackupWrite)(HANDLE, LPBYTE, DWORD, LPDWORD,
2555                                      BOOL, BOOL, LPVOID*) =
2556         (BOOL (__stdcall *)(HANDLE, LPBYTE, DWORD, LPDWORD,
2557                             BOOL, BOOL, LPVOID*))
2558         GetProcAddress(GetModuleHandle("kernel32.dll"), "BackupWrite");
2559     if (pfnBackupWrite == NULL)
2560         return 0;
2561
2562     dwLen = GetFullPathNameW(lpFileName, MAX_PATH, wFullName, NULL);
2563     if (dwLen == 0)
2564         return 0;
2565     dwLen = (dwLen+1)*sizeof(WCHAR);
2566
2567     handle = CreateFileW(lpExistingFileName, FILE_WRITE_ATTRIBUTES,
2568                          FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
2569                          NULL, OPEN_EXISTING, 0, NULL);
2570     if (handle == INVALID_HANDLE_VALUE)
2571         return 0;
2572
2573     StreamId.dwStreamId = BACKUP_LINK;
2574     StreamId.dwStreamAttributes = 0;
2575     StreamId.dwStreamNameSize = 0;
2576 #if defined(__BORLANDC__) \
2577  ||(defined(__MINGW32__) && !defined(_ANONYMOUS_UNION))
2578     StreamId.Size.u.HighPart = 0;
2579     StreamId.Size.u.LowPart = dwLen;
2580 #else
2581     StreamId.Size.HighPart = 0;
2582     StreamId.Size.LowPart = dwLen;
2583 #endif
2584
2585     bSuccess = pfnBackupWrite(handle, (LPBYTE)&StreamId, dwSize, &dwWritten,
2586                               FALSE, FALSE, &lpContext);
2587     if (bSuccess) {
2588         bSuccess = pfnBackupWrite(handle, (LPBYTE)wFullName, dwLen, &dwWritten,
2589                                   FALSE, FALSE, &lpContext);
2590         pfnBackupWrite(handle, NULL, 0, &dwWritten, TRUE, FALSE, &lpContext);
2591     }
2592
2593     CloseHandle(handle);
2594     return bSuccess;
2595 }
2596
2597 DllExport int
2598 win32_link(const char *oldname, const char *newname)
2599 {
2600     dTHX;
2601     BOOL (__stdcall *pfnCreateHardLinkW)(LPCWSTR,LPCWSTR,LPSECURITY_ATTRIBUTES);
2602     WCHAR wOldName[MAX_PATH+1];
2603     WCHAR wNewName[MAX_PATH+1];
2604
2605     if (IsWin95())
2606         Perl_croak(aTHX_ PL_no_func, "link");
2607
2608     pfnCreateHardLinkW =
2609         (BOOL (__stdcall *)(LPCWSTR, LPCWSTR, LPSECURITY_ATTRIBUTES))
2610         GetProcAddress(GetModuleHandle("kernel32.dll"), "CreateHardLinkW");
2611     if (pfnCreateHardLinkW == NULL)
2612         pfnCreateHardLinkW = Nt4CreateHardLinkW;
2613
2614     if ((A2WHELPER(oldname, wOldName, sizeof(wOldName))) &&
2615         (A2WHELPER(newname, wNewName, sizeof(wNewName))) &&
2616         (wcscpy(wOldName, PerlDir_mapW(wOldName)),
2617         pfnCreateHardLinkW(PerlDir_mapW(wNewName), wOldName, NULL)))
2618     {
2619         return 0;
2620     }
2621     errno = (GetLastError() == ERROR_FILE_NOT_FOUND) ? ENOENT : EINVAL;
2622     return -1;
2623 }
2624
2625 DllExport int
2626 win32_rename(const char *oname, const char *newname)
2627 {
2628     WCHAR wOldName[MAX_PATH+1];
2629     WCHAR wNewName[MAX_PATH+1];
2630     char szOldName[MAX_PATH+1];
2631     char szNewName[MAX_PATH+1];
2632     BOOL bResult;
2633     dTHX;
2634
2635     /* XXX despite what the documentation says about MoveFileEx(),
2636      * it doesn't work under Windows95!
2637      */
2638     if (IsWinNT()) {
2639         DWORD dwFlags = MOVEFILE_COPY_ALLOWED;
2640         if (USING_WIDE()) {
2641             A2WHELPER(oname, wOldName, sizeof(wOldName));
2642             A2WHELPER(newname, wNewName, sizeof(wNewName));
2643             if (wcsicmp(wNewName, wOldName))
2644                 dwFlags |= MOVEFILE_REPLACE_EXISTING;
2645             wcscpy(wOldName, PerlDir_mapW(wOldName));
2646             bResult = MoveFileExW(wOldName,PerlDir_mapW(wNewName), dwFlags);
2647         }
2648         else {
2649             if (stricmp(newname, oname))
2650                 dwFlags |= MOVEFILE_REPLACE_EXISTING;
2651             strcpy(szOldName, PerlDir_mapA(oname));
2652             bResult = MoveFileExA(szOldName,PerlDir_mapA(newname), dwFlags);
2653         }
2654         if (!bResult) {
2655             DWORD err = GetLastError();
2656             switch (err) {
2657             case ERROR_BAD_NET_NAME:
2658             case ERROR_BAD_NETPATH:
2659             case ERROR_BAD_PATHNAME:
2660             case ERROR_FILE_NOT_FOUND:
2661             case ERROR_FILENAME_EXCED_RANGE:
2662             case ERROR_INVALID_DRIVE:
2663             case ERROR_NO_MORE_FILES:
2664             case ERROR_PATH_NOT_FOUND:
2665                 errno = ENOENT;
2666                 break;
2667             default:
2668                 errno = EACCES;
2669                 break;
2670             }
2671             return -1;
2672         }
2673         return 0;
2674     }
2675     else {
2676         int retval = 0;
2677         char szTmpName[MAX_PATH+1];
2678         char dname[MAX_PATH+1];
2679         char *endname = Nullch;
2680         STRLEN tmplen = 0;
2681         DWORD from_attr, to_attr;
2682
2683         strcpy(szOldName, PerlDir_mapA(oname));
2684         strcpy(szNewName, PerlDir_mapA(newname));
2685
2686         /* if oname doesn't exist, do nothing */
2687         from_attr = GetFileAttributes(szOldName);
2688         if (from_attr == 0xFFFFFFFF) {
2689             errno = ENOENT;
2690             return -1;
2691         }
2692
2693         /* if newname exists, rename it to a temporary name so that we
2694          * don't delete it in case oname happens to be the same file
2695          * (but perhaps accessed via a different path)
2696          */
2697         to_attr = GetFileAttributes(szNewName);
2698         if (to_attr != 0xFFFFFFFF) {
2699             /* if newname is a directory, we fail
2700              * XXX could overcome this with yet more convoluted logic */
2701             if (to_attr & FILE_ATTRIBUTE_DIRECTORY) {
2702                 errno = EACCES;
2703                 return -1;
2704             }
2705             tmplen = strlen(szNewName);
2706             strcpy(szTmpName,szNewName);
2707             endname = szTmpName+tmplen;
2708             for (; endname > szTmpName ; --endname) {
2709                 if (*endname == '/' || *endname == '\\') {
2710                     *endname = '\0';
2711                     break;
2712                 }
2713             }
2714             if (endname > szTmpName)
2715                 endname = strcpy(dname,szTmpName);
2716             else
2717                 endname = ".";
2718
2719             /* get a temporary filename in same directory
2720              * XXX is this really the best we can do? */
2721             if (!GetTempFileName((LPCTSTR)endname, "plr", 0, szTmpName)) {
2722                 errno = ENOENT;
2723                 return -1;
2724             }
2725             DeleteFile(szTmpName);
2726
2727             retval = rename(szNewName, szTmpName);
2728             if (retval != 0) {
2729                 errno = EACCES;
2730                 return retval;
2731             }
2732         }
2733
2734         /* rename oname to newname */
2735         retval = rename(szOldName, szNewName);
2736
2737         /* if we created a temporary file before ... */
2738         if (endname != Nullch) {
2739             /* ...and rename succeeded, delete temporary file/directory */
2740             if (retval == 0)
2741                 DeleteFile(szTmpName);
2742             /* else restore it to what it was */
2743             else
2744                 (void)rename(szTmpName, szNewName);
2745         }
2746         return retval;
2747     }
2748 }
2749
2750 DllExport int
2751 win32_setmode(int fd, int mode)
2752 {
2753     return setmode(fd, mode);
2754 }
2755
2756 DllExport long
2757 win32_lseek(int fd, long offset, int origin)
2758 {
2759     return lseek(fd, offset, origin);
2760 }
2761
2762 DllExport long
2763 win32_tell(int fd)
2764 {
2765     return tell(fd);
2766 }
2767
2768 DllExport int
2769 win32_open(const char *path, int flag, ...)
2770 {
2771     dTHX;
2772     va_list ap;
2773     int pmode;
2774     WCHAR wBuffer[MAX_PATH+1];
2775
2776     va_start(ap, flag);
2777     pmode = va_arg(ap, int);
2778     va_end(ap);
2779
2780     if (stricmp(path, "/dev/null")==0)
2781         path = "NUL";
2782
2783     if (USING_WIDE()) {
2784         A2WHELPER(path, wBuffer, sizeof(wBuffer));
2785         return _wopen(PerlDir_mapW(wBuffer), flag, pmode);
2786     }
2787     return open(PerlDir_mapA(path), flag, pmode);
2788 }
2789
2790 /* close() that understands socket */
2791 extern int my_close(int);       /* in win32sck.c */
2792
2793 DllExport int
2794 win32_close(int fd)
2795 {
2796     return my_close(fd);
2797 }
2798
2799 DllExport int
2800 win32_eof(int fd)
2801 {
2802     return eof(fd);
2803 }
2804
2805 DllExport int
2806 win32_dup(int fd)
2807 {
2808     return dup(fd);
2809 }
2810
2811 DllExport int
2812 win32_dup2(int fd1,int fd2)
2813 {
2814     return dup2(fd1,fd2);
2815 }
2816
2817 #ifdef PERL_MSVCRT_READFIX
2818
2819 #define LF              10      /* line feed */
2820 #define CR              13      /* carriage return */
2821 #define CTRLZ           26      /* ctrl-z means eof for text */
2822 #define FOPEN           0x01    /* file handle open */
2823 #define FEOFLAG         0x02    /* end of file has been encountered */
2824 #define FCRLF           0x04    /* CR-LF across read buffer (in text mode) */
2825 #define FPIPE           0x08    /* file handle refers to a pipe */
2826 #define FAPPEND         0x20    /* file handle opened O_APPEND */
2827 #define FDEV            0x40    /* file handle refers to device */
2828 #define FTEXT           0x80    /* file handle is in text mode */
2829 #define MAX_DESCRIPTOR_COUNT    (64*32) /* this is the maximun that MSVCRT can handle */
2830
2831 int __cdecl
2832 _fixed_read(int fh, void *buf, unsigned cnt)
2833 {
2834     int bytes_read;                 /* number of bytes read */
2835     char *buffer;                   /* buffer to read to */
2836     int os_read;                    /* bytes read on OS call */
2837     char *p, *q;                    /* pointers into buffer */
2838     char peekchr;                   /* peek-ahead character */
2839     ULONG filepos;                  /* file position after seek */
2840     ULONG dosretval;                /* o.s. return value */
2841
2842     /* validate handle */
2843     if (((unsigned)fh >= (unsigned)MAX_DESCRIPTOR_COUNT) ||
2844          !(_osfile(fh) & FOPEN))
2845     {
2846         /* out of range -- return error */
2847         errno = EBADF;
2848         _doserrno = 0;  /* not o.s. error */
2849         return -1;
2850     }
2851
2852     /*
2853      * If lockinitflag is FALSE, assume fd is device
2854      * lockinitflag is set to TRUE by open.
2855      */
2856     if (_pioinfo(fh)->lockinitflag)
2857         EnterCriticalSection(&(_pioinfo(fh)->lock));  /* lock file */
2858
2859     bytes_read = 0;                 /* nothing read yet */
2860     buffer = (char*)buf;
2861
2862     if (cnt == 0 || (_osfile(fh) & FEOFLAG)) {
2863         /* nothing to read or at EOF, so return 0 read */
2864         goto functionexit;
2865     }
2866
2867     if ((_osfile(fh) & (FPIPE|FDEV)) && _pipech(fh) != LF) {
2868         /* a pipe/device and pipe lookahead non-empty: read the lookahead
2869          * char */
2870         *buffer++ = _pipech(fh);
2871         ++bytes_read;
2872         --cnt;
2873         _pipech(fh) = LF;           /* mark as empty */
2874     }
2875
2876     /* read the data */
2877
2878     if (!ReadFile((HANDLE)_osfhnd(fh), buffer, cnt, (LPDWORD)&os_read, NULL))
2879     {
2880         /* ReadFile has reported an error. recognize two special cases.
2881          *
2882          *      1. map ERROR_ACCESS_DENIED to EBADF
2883          *
2884          *      2. just return 0 if ERROR_BROKEN_PIPE has occurred. it
2885          *         means the handle is a read-handle on a pipe for which
2886          *         all write-handles have been closed and all data has been
2887          *         read. */
2888
2889         if ((dosretval = GetLastError()) == ERROR_ACCESS_DENIED) {
2890             /* wrong read/write mode should return EBADF, not EACCES */
2891             errno = EBADF;
2892             _doserrno = dosretval;
2893             bytes_read = -1;
2894             goto functionexit;
2895         }
2896         else if (dosretval == ERROR_BROKEN_PIPE) {
2897             bytes_read = 0;
2898             goto functionexit;
2899         }
2900         else {
2901             bytes_read = -1;
2902             goto functionexit;
2903         }
2904     }
2905
2906     bytes_read += os_read;          /* update bytes read */
2907
2908     if (_osfile(fh) & FTEXT) {
2909         /* now must translate CR-LFs to LFs in the buffer */
2910
2911         /* set CRLF flag to indicate LF at beginning of buffer */
2912         /* if ((os_read != 0) && (*(char *)buf == LF))   */
2913         /*    _osfile(fh) |= FCRLF;                      */
2914         /* else                                          */
2915         /*    _osfile(fh) &= ~FCRLF;                     */
2916
2917         _osfile(fh) &= ~FCRLF;
2918
2919         /* convert chars in the buffer: p is src, q is dest */
2920         p = q = (char*)buf;
2921         while (p < (char *)buf + bytes_read) {
2922             if (*p == CTRLZ) {
2923                 /* if fh is not a device, set ctrl-z flag */
2924                 if (!(_osfile(fh) & FDEV))
2925                     _osfile(fh) |= FEOFLAG;
2926                 break;              /* stop translating */
2927             }
2928             else if (*p != CR)
2929                 *q++ = *p++;
2930             else {
2931                 /* *p is CR, so must check next char for LF */
2932                 if (p < (char *)buf + bytes_read - 1) {
2933                     if (*(p+1) == LF) {
2934                         p += 2;
2935                         *q++ = LF;  /* convert CR-LF to LF */
2936                     }
2937                     else
2938                         *q++ = *p++;    /* store char normally */
2939                 }
2940                 else {
2941                     /* This is the hard part.  We found a CR at end of
2942                        buffer.  We must peek ahead to see if next char
2943                        is an LF. */
2944                     ++p;
2945
2946                     dosretval = 0;
2947                     if (!ReadFile((HANDLE)_osfhnd(fh), &peekchr, 1,
2948                                     (LPDWORD)&os_read, NULL))
2949                         dosretval = GetLastError();
2950
2951                     if (dosretval != 0 || os_read == 0) {
2952                         /* couldn't read ahead, store CR */
2953                         *q++ = CR;
2954                     }
2955                     else {
2956                         /* peekchr now has the extra character -- we now
2957                            have several possibilities:
2958                            1. disk file and char is not LF; just seek back
2959                               and copy CR
2960                            2. disk file and char is LF; store LF, don't seek back
2961                            3. pipe/device and char is LF; store LF.
2962                            4. pipe/device and char isn't LF, store CR and
2963                               put char in pipe lookahead buffer. */
2964                         if (_osfile(fh) & (FDEV|FPIPE)) {
2965                             /* non-seekable device */
2966                             if (peekchr == LF)
2967                                 *q++ = LF;
2968                             else {
2969                                 *q++ = CR;
2970                                 _pipech(fh) = peekchr;
2971                             }
2972                         }
2973                         else {
2974                             /* disk file */
2975                             if (peekchr == LF) {
2976                                 /* nothing read yet; must make some
2977                                    progress */
2978                                 *q++ = LF;
2979                                 /* turn on this flag for tell routine */
2980                                 _osfile(fh) |= FCRLF;
2981                             }
2982                             else {
2983                                 HANDLE osHandle;        /* o.s. handle value */
2984                                 /* seek back */
2985                                 if ((osHandle = (HANDLE)_get_osfhandle(fh)) != (HANDLE)-1)
2986                                 {
2987                                     if ((filepos = SetFilePointer(osHandle, -1, NULL, FILE_CURRENT)) == -1)
2988                                         dosretval = GetLastError();
2989                                 }
2990                                 if (peekchr != LF)
2991                                     *q++ = CR;
2992                             }
2993                         }
2994                     }
2995                 }
2996             }
2997         }
2998
2999         /* we now change bytes_read to reflect the true number of chars
3000            in the buffer */
3001         bytes_read = q - (char *)buf;
3002     }
3003
3004 functionexit:   
3005     if (_pioinfo(fh)->lockinitflag)
3006         LeaveCriticalSection(&(_pioinfo(fh)->lock));    /* unlock file */
3007
3008     return bytes_read;
3009 }
3010
3011 #endif  /* PERL_MSVCRT_READFIX */
3012
3013 DllExport int
3014 win32_read(int fd, void *buf, unsigned int cnt)
3015 {
3016 #ifdef PERL_MSVCRT_READFIX
3017     return _fixed_read(fd, buf, cnt);
3018 #else
3019     return read(fd, buf, cnt);
3020 #endif
3021 }
3022
3023 DllExport int
3024 win32_write(int fd, const void *buf, unsigned int cnt)
3025 {
3026     return write(fd, buf, cnt);
3027 }
3028
3029 DllExport int
3030 win32_mkdir(const char *dir, int mode)
3031 {
3032     dTHX;
3033     if (USING_WIDE()) {
3034         WCHAR wBuffer[MAX_PATH+1];
3035         A2WHELPER(dir, wBuffer, sizeof(wBuffer));
3036         return _wmkdir(PerlDir_mapW(wBuffer));
3037     }
3038     return mkdir(PerlDir_mapA(dir)); /* just ignore mode */
3039 }
3040
3041 DllExport int
3042 win32_rmdir(const char *dir)
3043 {
3044     dTHX;
3045     if (USING_WIDE()) {
3046         WCHAR wBuffer[MAX_PATH+1];
3047         A2WHELPER(dir, wBuffer, sizeof(wBuffer));
3048         return _wrmdir(PerlDir_mapW(wBuffer));
3049     }
3050     return rmdir(PerlDir_mapA(dir));
3051 }
3052
3053 DllExport int
3054 win32_chdir(const char *dir)
3055 {
3056     dTHX;
3057     if (!dir) {
3058         errno = ENOENT;
3059         return -1;
3060     }
3061     if (USING_WIDE()) {
3062         WCHAR wBuffer[MAX_PATH+1];
3063         A2WHELPER(dir, wBuffer, sizeof(wBuffer));
3064         return _wchdir(wBuffer);
3065     }
3066     return chdir(dir);
3067 }
3068
3069 DllExport  int
3070 win32_access(const char *path, int mode)
3071 {
3072     dTHX;
3073     if (USING_WIDE()) {
3074         WCHAR wBuffer[MAX_PATH+1];
3075         A2WHELPER(path, wBuffer, sizeof(wBuffer));
3076         return _waccess(PerlDir_mapW(wBuffer), mode);
3077     }
3078     return access(PerlDir_mapA(path), mode);
3079 }
3080
3081 DllExport  int
3082 win32_chmod(const char *path, int mode)
3083 {
3084     dTHX;
3085     if (USING_WIDE()) {
3086         WCHAR wBuffer[MAX_PATH+1];
3087         A2WHELPER(path, wBuffer, sizeof(wBuffer));
3088         return _wchmod(PerlDir_mapW(wBuffer), mode);
3089     }
3090     return chmod(PerlDir_mapA(path), mode);
3091 }
3092
3093
3094 static char *
3095 create_command_line(const char *cmdname, const char * const *args)
3096 {
3097     dTHX;
3098     int index, argc;
3099     char *cmd, *ptr;
3100     const char *arg;
3101     STRLEN len = 0;
3102     bool bat_file = FALSE;
3103     bool cmd_shell = FALSE;
3104     bool extra_quotes = FALSE;
3105     char *cname = (char*)cmdname;
3106
3107     if (!cname)
3108         cname = (char*)args[0];
3109
3110     /* The NT cmd.exe shell has the following peculiarity that needs to be
3111      * worked around.  It strips a leading and trailing dquote when any
3112      * of the following is true:
3113      *    1. the /S switch was used
3114      *    2. there are more than two dquotes
3115      *    3. there is a special character from this set: &<>()@^|
3116      *    4. no whitespace characters within the two dquotes
3117      *    5. string between two dquotes isn't an executable file
3118      * To work around this, we always add a leading and trailing dquote
3119      * to the string, if the first argument is either "cmd.exe" or "cmd",
3120      * and there were at least two or more arguments passed to cmd.exe
3121      * (not including switches).
3122      */
3123     if (cname) {
3124         STRLEN clen = strlen(cname);
3125         if (clen > 4
3126             && (stricmp(&cname[clen-4], ".bat") == 0
3127                 || (IsWinNT() && stricmp(&cname[clen-4], ".cmd") == 0)))
3128         {
3129             bat_file = TRUE;
3130             len += 3;
3131         }
3132         else if (stricmp(cname, "cmd.exe") == 0
3133                  || stricmp(cname, "cmd") == 0)
3134         {
3135             cmd_shell = TRUE;
3136             len += 3;
3137         }
3138     }
3139
3140     DEBUG_p(PerlIO_printf(Perl_debug_log, "Args "));
3141     for (index = 0; (arg = (char*)args[index]) != NULL; ++index) {
3142         STRLEN curlen = strlen(arg);
3143         if (!(arg[0] == '"' && arg[curlen-1] == '"'))
3144             len += 2;   /* assume quoting needed (worst case) */
3145         len += curlen + 1;
3146         DEBUG_p(PerlIO_printf(Perl_debug_log, "[%s]",arg));
3147     }
3148     DEBUG_p(PerlIO_printf(Perl_debug_log, "\n"));
3149
3150     argc = index;
3151     New(1310, cmd, len, char);
3152     ptr = cmd;
3153
3154     if (bat_file) {
3155         *ptr++ = '"';
3156         extra_quotes = TRUE;
3157     }
3158
3159     for (index = 0; (arg = (char*)args[index]) != NULL; ++index) {
3160         bool do_quote = 0;
3161         STRLEN curlen = strlen(arg);
3162
3163         /* we want to protect empty arguments and ones with spaces with
3164          * dquotes, but only if they aren't already there */
3165         if (!curlen) {
3166             do_quote = 1;
3167         }
3168         else if (!(arg[0] == '"' && curlen > 1 && arg[curlen-1] == '"')) {
3169             STRLEN i = 0;
3170             while (i < curlen) {
3171                 if (isSPACE(arg[i])) {
3172                     do_quote = 1;
3173                     break;
3174                 }
3175                 i++;
3176             }
3177         }
3178
3179         if (do_quote)
3180             *ptr++ = '"';
3181
3182         strcpy(ptr, arg);
3183         ptr += curlen;
3184
3185         if (do_quote)
3186             *ptr++ = '"';
3187
3188         if (args[index+1])
3189             *ptr++ = ' ';
3190
3191         if (!extra_quotes
3192             && cmd_shell
3193             && (stricmp(arg, "/x/c") == 0 || stricmp(arg, "/c") == 0)
3194             && (argc-1 > index+1))   /* two or more arguments to cmd.exe? */
3195         {
3196             *ptr++ = '"';
3197             extra_quotes = TRUE;
3198         }
3199     }
3200
3201     if (extra_quotes)
3202         *ptr++ = '"';
3203
3204     *ptr = '\0';
3205
3206     return cmd;
3207 }
3208
3209 static char *
3210 qualified_path(const char *cmd)
3211 {
3212     dTHX;
3213     char *pathstr;
3214     char *fullcmd, *curfullcmd;
3215     STRLEN cmdlen = 0;
3216     int has_slash = 0;
3217
3218     if (!cmd)
3219         return Nullch;
3220     fullcmd = (char*)cmd;
3221     while (*fullcmd) {
3222         if (*fullcmd == '/' || *fullcmd == '\\')
3223             has_slash++;
3224         fullcmd++;
3225         cmdlen++;
3226     }
3227
3228     /* look in PATH */
3229     pathstr = PerlEnv_getenv("PATH");
3230     New(0, fullcmd, MAX_PATH+1, char);
3231     curfullcmd = fullcmd;
3232
3233     while (1) {
3234         DWORD res;
3235
3236         /* start by appending the name to the current prefix */
3237         strcpy(curfullcmd, cmd);
3238         curfullcmd += cmdlen;
3239
3240         /* if it doesn't end with '.', or has no extension, try adding
3241          * a trailing .exe first */
3242         if (cmd[cmdlen-1] != '.'
3243             && (cmdlen < 4 || cmd[cmdlen-4] != '.'))
3244         {
3245             strcpy(curfullcmd, ".exe");
3246             res = GetFileAttributes(fullcmd);
3247             if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
3248                 return fullcmd;
3249             *curfullcmd = '\0';
3250         }
3251
3252         /* that failed, try the bare name */
3253         res = GetFileAttributes(fullcmd);
3254         if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
3255             return fullcmd;
3256
3257         /* quit if no other path exists, or if cmd already has path */
3258         if (!pathstr || !*pathstr || has_slash)
3259             break;
3260
3261         /* skip leading semis */
3262         while (*pathstr == ';')
3263             pathstr++;
3264
3265         /* build a new prefix from scratch */
3266         curfullcmd = fullcmd;
3267         while (*pathstr && *pathstr != ';') {
3268             if (*pathstr == '"') {      /* foo;"baz;etc";bar */
3269                 pathstr++;              /* skip initial '"' */
3270                 while (*pathstr && *pathstr != '"') {
3271                     if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
3272                         *curfullcmd++ = *pathstr;
3273                     pathstr++;
3274                 }
3275                 if (*pathstr)
3276                     pathstr++;          /* skip trailing '"' */
3277             }
3278             else {
3279                 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
3280                     *curfullcmd++ = *pathstr;
3281                 pathstr++;
3282             }
3283         }
3284         if (*pathstr)
3285             pathstr++;                  /* skip trailing semi */
3286         if (curfullcmd > fullcmd        /* append a dir separator */
3287             && curfullcmd[-1] != '/' && curfullcmd[-1] != '\\')
3288         {
3289             *curfullcmd++ = '\\';
3290         }
3291     }
3292 GIVE_UP:
3293     Safefree(fullcmd);
3294     return Nullch;
3295 }
3296
3297 /* The following are just place holders.
3298  * Some hosts may provide and environment that the OS is
3299  * not tracking, therefore, these host must provide that
3300  * environment and the current directory to CreateProcess
3301  */
3302
3303 DllExport void*
3304 win32_get_childenv(void)
3305 {
3306     return NULL;
3307 }
3308
3309 DllExport void
3310 win32_free_childenv(void* d)
3311 {
3312 }
3313
3314 DllExport void
3315 win32_clearenv(void)
3316 {
3317     char *envv = GetEnvironmentStrings();
3318     char *cur = envv;
3319     STRLEN len;
3320     while (*cur) {
3321         char *end = strchr(cur,'=');
3322         if (end && end != cur) {
3323             *end = '\0';
3324             SetEnvironmentVariable(cur, NULL);
3325             *end = '=';
3326             cur = end + strlen(end+1)+2;
3327         }
3328         else if ((len = strlen(cur)))
3329             cur += len+1;
3330     }
3331     FreeEnvironmentStrings(envv);
3332 }
3333
3334 DllExport char*
3335 win32_get_childdir(void)
3336 {
3337     dTHX;
3338     char* ptr;
3339     char szfilename[(MAX_PATH+1)*2];
3340     if (USING_WIDE()) {
3341         WCHAR wfilename[MAX_PATH+1];
3342         GetCurrentDirectoryW(MAX_PATH+1, wfilename);
3343         W2AHELPER(wfilename, szfilename, sizeof(szfilename));
3344     }
3345     else {
3346         GetCurrentDirectoryA(MAX_PATH+1, szfilename);
3347     }
3348
3349     New(0, ptr, strlen(szfilename)+1, char);
3350     strcpy(ptr, szfilename);
3351     return ptr;
3352 }
3353
3354 DllExport void
3355 win32_free_childdir(char* d)
3356 {
3357     dTHX;
3358     Safefree(d);
3359 }
3360
3361
3362 /* XXX this needs to be made more compatible with the spawnvp()
3363  * provided by the various RTLs.  In particular, searching for
3364  * *.{com,bat,cmd} files (as done by the RTLs) is unimplemented.
3365  * This doesn't significantly affect perl itself, because we
3366  * always invoke things using PERL5SHELL if a direct attempt to
3367  * spawn the executable fails.
3368  * 
3369  * XXX splitting and rejoining the commandline between do_aspawn()
3370  * and win32_spawnvp() could also be avoided.
3371  */
3372
3373 DllExport int
3374 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
3375 {
3376 #ifdef USE_RTL_SPAWNVP
3377     return spawnvp(mode, cmdname, (char * const *)argv);
3378 #else
3379     dTHX;
3380     int ret;
3381     void* env;
3382     char* dir;
3383     child_IO_table tbl;
3384     STARTUPINFO StartupInfo;
3385     PROCESS_INFORMATION ProcessInformation;
3386     DWORD create = 0;
3387
3388     char *cmd = create_command_line(cmdname, argv);
3389     char *fullcmd = Nullch;
3390
3391     env = PerlEnv_get_childenv();
3392     dir = PerlEnv_get_childdir();
3393
3394     switch(mode) {
3395     case P_NOWAIT:      /* asynch + remember result */
3396         if (w32_num_children >= MAXIMUM_WAIT_OBJECTS) {
3397             errno = EAGAIN;
3398             ret = -1;
3399             goto RETVAL;
3400         }
3401         /* FALL THROUGH */
3402     case P_WAIT:        /* synchronous execution */
3403         break;
3404     default:            /* invalid mode */
3405         errno = EINVAL;
3406         ret = -1;
3407         goto RETVAL;
3408     }
3409     memset(&StartupInfo,0,sizeof(StartupInfo));
3410     StartupInfo.cb = sizeof(StartupInfo);
3411     memset(&tbl,0,sizeof(tbl));
3412     PerlEnv_get_child_IO(&tbl);
3413     StartupInfo.dwFlags         = tbl.dwFlags;
3414     StartupInfo.dwX             = tbl.dwX; 
3415     StartupInfo.dwY             = tbl.dwY; 
3416     StartupInfo.dwXSize         = tbl.dwXSize; 
3417     StartupInfo.dwYSize         = tbl.dwYSize; 
3418     StartupInfo.dwXCountChars   = tbl.dwXCountChars; 
3419     StartupInfo.dwYCountChars   = tbl.dwYCountChars; 
3420     StartupInfo.dwFillAttribute = tbl.dwFillAttribute; 
3421     StartupInfo.wShowWindow     = tbl.wShowWindow; 
3422     StartupInfo.hStdInput       = tbl.childStdIn;
3423     StartupInfo.hStdOutput      = tbl.childStdOut;
3424     StartupInfo.hStdError       = tbl.childStdErr;
3425     if (StartupInfo.hStdInput != INVALID_HANDLE_VALUE &&
3426         StartupInfo.hStdOutput != INVALID_HANDLE_VALUE &&
3427         StartupInfo.hStdError != INVALID_HANDLE_VALUE)
3428     {
3429         StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
3430     }
3431     else {
3432         create |= CREATE_NEW_CONSOLE;
3433     }
3434
3435     DEBUG_p(PerlIO_printf(Perl_debug_log, "Spawning [%s] with [%s]\n",
3436                           cmdname,cmd));
3437 RETRY:
3438     if (!CreateProcess(cmdname,         /* search PATH to find executable */
3439                        cmd,             /* executable, and its arguments */
3440                        NULL,            /* process attributes */
3441                        NULL,            /* thread attributes */
3442                        TRUE,            /* inherit handles */
3443                        create,          /* creation flags */
3444                        (LPVOID)env,     /* inherit environment */
3445                        dir,             /* inherit cwd */
3446                        &StartupInfo,
3447                        &ProcessInformation))
3448     {
3449         /* initial NULL argument to CreateProcess() does a PATH
3450          * search, but it always first looks in the directory
3451          * where the current process was started, which behavior
3452          * is undesirable for backward compatibility.  So we
3453          * jump through our own hoops by picking out the path
3454          * we really want it to use. */
3455         if (!fullcmd) {
3456             fullcmd = qualified_path(cmdname);
3457             if (fullcmd) {
3458                 cmdname = fullcmd;
3459                 DEBUG_p(PerlIO_printf(Perl_debug_log,
3460                                       "Retrying [%s] with same args\n",
3461                                       cmdname));
3462                 goto RETRY;
3463             }
3464         }
3465         errno = ENOENT;
3466         ret = -1;
3467         goto RETVAL;
3468     }
3469
3470     if (mode == P_NOWAIT) {
3471         /* asynchronous spawn -- store handle, return PID */
3472         ret = (int)ProcessInformation.dwProcessId;
3473         if (IsWin95() && ret < 0)
3474             ret = -ret;
3475
3476         w32_child_handles[w32_num_children] = ProcessInformation.hProcess;
3477         w32_child_pids[w32_num_children] = (DWORD)ret;
3478         ++w32_num_children;
3479     }
3480     else  {
3481         DWORD status;
3482         WaitForSingleObject(ProcessInformation.hProcess, INFINITE);
3483         GetExitCodeProcess(ProcessInformation.hProcess, &status);
3484         ret = (int)status;
3485         CloseHandle(ProcessInformation.hProcess);
3486     }
3487
3488     CloseHandle(ProcessInformation.hThread);
3489
3490 RETVAL:
3491     PerlEnv_free_childenv(env);
3492     PerlEnv_free_childdir(dir);
3493     Safefree(cmd);
3494     Safefree(fullcmd);
3495     return ret;
3496 #endif
3497 }
3498
3499 DllExport int
3500 win32_execv(const char *cmdname, const char *const *argv)
3501 {
3502 #ifdef USE_ITHREADS
3503     dTHX;
3504     /* if this is a pseudo-forked child, we just want to spawn
3505      * the new program, and return */
3506     if (w32_pseudo_id)
3507         return spawnv(P_WAIT, cmdname, (char *const *)argv);
3508 #endif
3509     return execv(cmdname, (char *const *)argv);
3510 }
3511
3512 DllExport int
3513 win32_execvp(const char *cmdname, const char *const *argv)
3514 {
3515 #ifdef USE_ITHREADS
3516     dTHX;
3517     /* if this is a pseudo-forked child, we just want to spawn
3518      * the new program, and return */
3519     if (w32_pseudo_id) {
3520         int status = win32_spawnvp(P_WAIT, cmdname, (char *const *)argv);
3521         if (status != -1) {
3522             my_exit(status);
3523             return 0;
3524         }
3525         else
3526             return status;
3527     }
3528 #endif
3529     return execvp(cmdname, (char *const *)argv);
3530 }
3531
3532 DllExport void
3533 win32_perror(const char *str)
3534 {
3535     perror(str);
3536 }
3537
3538 DllExport void
3539 win32_setbuf(FILE *pf, char *buf)
3540 {
3541     setbuf(pf, buf);
3542 }
3543
3544 DllExport int
3545 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
3546 {
3547     return setvbuf(pf, buf, type, size);
3548 }
3549
3550 DllExport int
3551 win32_flushall(void)
3552 {
3553     return flushall();
3554 }
3555
3556 DllExport int
3557 win32_fcloseall(void)
3558 {
3559     return fcloseall();
3560 }
3561
3562 DllExport char*
3563 win32_fgets(char *s, int n, FILE *pf)
3564 {
3565     return fgets(s, n, pf);
3566 }
3567
3568 DllExport char*
3569 win32_gets(char *s)
3570 {
3571     return gets(s);
3572 }
3573
3574 DllExport int
3575 win32_fgetc(FILE *pf)
3576 {
3577     return fgetc(pf);
3578 }
3579
3580 DllExport int
3581 win32_putc(int c, FILE *pf)
3582 {
3583     return putc(c,pf);
3584 }
3585
3586 DllExport int
3587 win32_puts(const char *s)
3588 {
3589     return puts(s);
3590 }
3591
3592 DllExport int
3593 win32_getchar(void)
3594 {
3595     return getchar();
3596 }
3597
3598 DllExport int
3599 win32_putchar(int c)
3600 {
3601     return putchar(c);
3602 }
3603
3604 #ifdef MYMALLOC
3605
3606 #ifndef USE_PERL_SBRK
3607
3608 static char *committed = NULL;          /* XXX threadead */
3609 static char *base      = NULL;          /* XXX threadead */
3610 static char *reserved  = NULL;          /* XXX threadead */
3611 static char *brk       = NULL;          /* XXX threadead */
3612 static DWORD pagesize  = 0;             /* XXX threadead */
3613 static DWORD allocsize = 0;             /* XXX threadead */
3614
3615 void *
3616 sbrk(int need)
3617 {
3618  void *result;
3619  if (!pagesize)
3620   {SYSTEM_INFO info;
3621    GetSystemInfo(&info);
3622    /* Pretend page size is larger so we don't perpetually
3623     * call the OS to commit just one page ...
3624     */
3625    pagesize = info.dwPageSize << 3;
3626    allocsize = info.dwAllocationGranularity;
3627   }
3628  /* This scheme fails eventually if request for contiguous
3629   * block is denied so reserve big blocks - this is only 
3630   * address space not memory ...
3631   */
3632  if (brk+need >= reserved)
3633   {
3634    DWORD size = 64*1024*1024;
3635    char *addr;
3636    if (committed && reserved && committed < reserved)
3637     {
3638      /* Commit last of previous chunk cannot span allocations */
3639      addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
3640      if (addr)
3641       committed = reserved;
3642     }
3643    /* Reserve some (more) space 
3644     * Note this is a little sneaky, 1st call passes NULL as reserved
3645     * so lets system choose where we start, subsequent calls pass
3646     * the old end address so ask for a contiguous block
3647     */
3648    addr  = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
3649    if (addr)
3650     {
3651      reserved = addr+size;
3652      if (!base)
3653       base = addr;
3654      if (!committed)
3655       committed = base;
3656      if (!brk)
3657       brk = committed;
3658     }
3659    else
3660     {
3661      return (void *) -1;
3662     }
3663   }
3664  result = brk;
3665  brk += need;
3666  if (brk > committed)
3667   {
3668    DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
3669    char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
3670    if (addr)
3671     {
3672      committed += size;
3673     }
3674    else
3675     return (void *) -1;
3676   }
3677  return result;
3678 }
3679
3680 #endif
3681 #endif
3682
3683 DllExport void*
3684 win32_malloc(size_t size)
3685 {
3686     return malloc(size);
3687 }
3688
3689 DllExport void*
3690 win32_calloc(size_t numitems, size_t size)
3691 {
3692     return calloc(numitems,size);
3693 }
3694
3695 DllExport void*
3696 win32_realloc(void *block, size_t size)
3697 {
3698     return realloc(block,size);
3699 }
3700
3701 DllExport void
3702 win32_free(void *block)
3703 {
3704     free(block);
3705 }
3706
3707
3708 int
3709 win32_open_osfhandle(long handle, int flags)
3710 {
3711 #ifdef USE_FIXED_OSFHANDLE
3712     if (IsWin95())
3713         return my_open_osfhandle(handle, flags);
3714 #endif
3715     return _open_osfhandle(handle, flags);
3716 }
3717
3718 long
3719 win32_get_osfhandle(int fd)
3720 {
3721     return _get_osfhandle(fd);
3722 }
3723
3724 DllExport void*
3725 win32_dynaload(const char* filename)
3726 {
3727     dTHX;
3728     HMODULE hModule;
3729     char buf[MAX_PATH+1];
3730     char *first;
3731
3732     /* LoadLibrary() doesn't recognize forward slashes correctly,
3733      * so turn 'em back. */
3734     first = strchr(filename, '/');
3735     if (first) {
3736         STRLEN len = strlen(filename);
3737         if (len <= MAX_PATH) {
3738             strcpy(buf, filename);
3739             filename = &buf[first - filename];
3740             while (*filename) {
3741                 if (*filename == '/')
3742                     *(char*)filename = '\\';
3743                 ++filename;
3744             }
3745             filename = buf;
3746         }
3747     }
3748     if (USING_WIDE()) {
3749         WCHAR wfilename[MAX_PATH+1];
3750         A2WHELPER(filename, wfilename, sizeof(wfilename));
3751         hModule = LoadLibraryExW(PerlDir_mapW(wfilename), NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
3752     }
3753     else {
3754         hModule = LoadLibraryExA(PerlDir_mapA(filename), NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
3755     }
3756     return hModule;
3757 }
3758
3759 /*
3760  * Extras.
3761  */
3762
3763 static
3764 XS(w32_GetCwd)
3765 {
3766     dXSARGS;
3767     /* Make the host for current directory */
3768     char* ptr = PerlEnv_get_childdir();
3769     /* 
3770      * If ptr != Nullch 
3771      *   then it worked, set PV valid, 
3772      *   else return 'undef' 
3773      */
3774     if (ptr) {
3775         SV *sv = sv_newmortal();
3776         sv_setpv(sv, ptr);
3777         PerlEnv_free_childdir(ptr);
3778
3779 #ifndef INCOMPLETE_TAINTS
3780         SvTAINTED_on(sv);
3781 #endif
3782
3783         EXTEND(SP,1);
3784         SvPOK_on(sv);
3785         ST(0) = sv;
3786         XSRETURN(1);
3787     }
3788     XSRETURN_UNDEF;
3789 }
3790
3791 static
3792 XS(w32_SetCwd)
3793 {
3794     dXSARGS;
3795     if (items != 1)
3796         Perl_croak(aTHX_ "usage: Win32::SetCurrentDirectory($cwd)");
3797     if (!PerlDir_chdir(SvPV_nolen(ST(0))))
3798         XSRETURN_YES;
3799
3800     XSRETURN_NO;
3801 }
3802
3803 static
3804 XS(w32_GetNextAvailDrive)
3805 {
3806     dXSARGS;
3807     char ix = 'C';
3808     char root[] = "_:\\";
3809
3810     EXTEND(SP,1);
3811     while (ix <= 'Z') {
3812         root[0] = ix++;
3813         if (GetDriveType(root) == 1) {
3814             root[2] = '\0';
3815             XSRETURN_PV(root);
3816         }
3817     }
3818     XSRETURN_UNDEF;
3819 }
3820
3821 static
3822 XS(w32_GetLastError)
3823 {
3824     dXSARGS;
3825     EXTEND(SP,1);
3826     XSRETURN_IV(GetLastError());
3827 }
3828
3829 static
3830 XS(w32_SetLastError)
3831 {
3832     dXSARGS;
3833     if (items != 1)
3834         Perl_croak(aTHX_ "usage: Win32::SetLastError($error)");
3835     SetLastError(SvIV(ST(0)));
3836     XSRETURN_EMPTY;
3837 }
3838
3839 static
3840 XS(w32_LoginName)
3841 {
3842     dXSARGS;
3843     char *name = w32_getlogin_buffer;
3844     DWORD size = sizeof(w32_getlogin_buffer);
3845     EXTEND(SP,1);
3846     if (GetUserName(name,&size)) {
3847         /* size includes NULL */
3848         ST(0) = sv_2mortal(newSVpvn(name,size-1));
3849         XSRETURN(1);
3850     }
3851     XSRETURN_UNDEF;
3852 }
3853
3854 static
3855 XS(w32_NodeName)
3856 {
3857     dXSARGS;
3858     char name[MAX_COMPUTERNAME_LENGTH+1];
3859     DWORD size = sizeof(name);
3860     EXTEND(SP,1);
3861     if (GetComputerName(name,&size)) {
3862         /* size does NOT include NULL :-( */
3863         ST(0) = sv_2mortal(newSVpvn(name,size));
3864         XSRETURN(1);
3865     }
3866     XSRETURN_UNDEF;
3867 }
3868
3869
3870 static
3871 XS(w32_DomainName)
3872 {
3873     dXSARGS;
3874     HINSTANCE hNetApi32 = LoadLibrary("netapi32.dll");
3875     DWORD (__stdcall *pfnNetApiBufferFree)(LPVOID Buffer);
3876     DWORD (__stdcall *pfnNetWkstaGetInfo)(LPWSTR servername, DWORD level,
3877                                           void *bufptr);
3878
3879     if (hNetApi32) {
3880         pfnNetApiBufferFree = (DWORD (__stdcall *)(void *))
3881             GetProcAddress(hNetApi32, "NetApiBufferFree");
3882         pfnNetWkstaGetInfo = (DWORD (__stdcall *)(LPWSTR, DWORD, void *))
3883             GetProcAddress(hNetApi32, "NetWkstaGetInfo");
3884     }
3885     EXTEND(SP,1);
3886     if (hNetApi32 && pfnNetWkstaGetInfo && pfnNetApiBufferFree) {
3887         /* this way is more reliable, in case user has a local account. */
3888         char dname[256];
3889         DWORD dnamelen = sizeof(dname);
3890         struct {
3891             DWORD   wki100_platform_id;
3892             LPWSTR  wki100_computername;
3893             LPWSTR  wki100_langroup;
3894             DWORD   wki100_ver_major;
3895             DWORD   wki100_ver_minor;
3896         } *pwi;
3897         /* NERR_Success *is* 0*/
3898         if (0 == pfnNetWkstaGetInfo(NULL, 100, &pwi)) {
3899             if (pwi->wki100_langroup && *(pwi->wki100_langroup)) {
3900                 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_langroup,
3901                                     -1, (LPSTR)dname, dnamelen, NULL, NULL);
3902             }
3903             else {
3904                 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_computername,
3905                                     -1, (LPSTR)dname, dnamelen, NULL, NULL);
3906             }
3907             pfnNetApiBufferFree(pwi);
3908             FreeLibrary(hNetApi32);
3909             XSRETURN_PV(dname);
3910         }
3911         FreeLibrary(hNetApi32);
3912     }
3913     else {
3914         /* Win95 doesn't have NetWksta*(), so do it the old way */
3915         char name[256];
3916         DWORD size = sizeof(name);
3917         if (hNetApi32)
3918             FreeLibrary(hNetApi32);
3919         if (GetUserName(name,&size)) {
3920             char sid[ONE_K_BUFSIZE];
3921             DWORD sidlen = sizeof(sid);
3922             char dname[256];
3923             DWORD dnamelen = sizeof(dname);
3924             SID_NAME_USE snu;
3925             if (LookupAccountName(NULL, name, (PSID)&sid, &sidlen,
3926                                   dname, &dnamelen, &snu)) {
3927                 XSRETURN_PV(dname);             /* all that for this */
3928             }
3929         }
3930     }
3931     XSRETURN_UNDEF;
3932 }
3933
3934 static
3935 XS(w32_FsType)
3936 {
3937     dXSARGS;
3938     char fsname[256];
3939     DWORD flags, filecomplen;
3940     if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
3941                          &flags, fsname, sizeof(fsname))) {
3942         if (GIMME_V == G_ARRAY) {
3943             XPUSHs(sv_2mortal(newSVpvn(fsname,strlen(fsname))));
3944             XPUSHs(sv_2mortal(newSViv(flags)));
3945             XPUSHs(sv_2mortal(newSViv(filecomplen)));
3946             PUTBACK;
3947             return;
3948         }
3949         EXTEND(SP,1);
3950         XSRETURN_PV(fsname);
3951     }
3952     XSRETURN_EMPTY;
3953 }
3954
3955 static
3956 XS(w32_GetOSVersion)
3957 {
3958     dXSARGS;
3959     OSVERSIONINFOA osver;
3960
3961     if (USING_WIDE()) {
3962         OSVERSIONINFOW osverw;
3963         char szCSDVersion[sizeof(osverw.szCSDVersion)];
3964         osverw.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
3965         if (!GetVersionExW(&osverw)) {
3966             XSRETURN_EMPTY;
3967         }
3968         W2AHELPER(osverw.szCSDVersion, szCSDVersion, sizeof(szCSDVersion));
3969         XPUSHs(newSVpvn(szCSDVersion, strlen(szCSDVersion)));
3970         osver.dwMajorVersion = osverw.dwMajorVersion;
3971         osver.dwMinorVersion = osverw.dwMinorVersion;
3972         osver.dwBuildNumber = osverw.dwBuildNumber;
3973         osver.dwPlatformId = osverw.dwPlatformId;
3974     }
3975     else {
3976         osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOA);
3977         if (!GetVersionExA(&osver)) {
3978             XSRETURN_EMPTY;
3979         }
3980         XPUSHs(newSVpvn(osver.szCSDVersion, strlen(osver.szCSDVersion)));
3981     }
3982     XPUSHs(newSViv(osver.dwMajorVersion));
3983     XPUSHs(newSViv(osver.dwMinorVersion));
3984     XPUSHs(newSViv(osver.dwBuildNumber));
3985     XPUSHs(newSViv(osver.dwPlatformId));
3986     PUTBACK;
3987 }
3988
3989 static
3990 XS(w32_IsWinNT)
3991 {
3992     dXSARGS;
3993     EXTEND(SP,1);
3994     XSRETURN_IV(IsWinNT());
3995 }
3996
3997 static
3998 XS(w32_IsWin95)
3999 {
4000     dXSARGS;
4001     EXTEND(SP,1);
4002     XSRETURN_IV(IsWin95());
4003 }
4004
4005 static
4006 XS(w32_FormatMessage)
4007 {
4008     dXSARGS;
4009     DWORD source = 0;
4010     char msgbuf[ONE_K_BUFSIZE];
4011
4012     if (items != 1)
4013         Perl_croak(aTHX_ "usage: Win32::FormatMessage($errno)");
4014
4015     if (USING_WIDE()) {
4016         WCHAR wmsgbuf[ONE_K_BUFSIZE];
4017         if (FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM,
4018                           &source, SvIV(ST(0)), 0,
4019                           wmsgbuf, ONE_K_BUFSIZE-1, NULL))
4020         {
4021             W2AHELPER(wmsgbuf, msgbuf, sizeof(msgbuf));
4022             XSRETURN_PV(msgbuf);
4023         }
4024     }
4025     else {
4026         if (FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM,
4027                           &source, SvIV(ST(0)), 0,
4028                           msgbuf, sizeof(msgbuf)-1, NULL))
4029             XSRETURN_PV(msgbuf);
4030     }
4031
4032     XSRETURN_UNDEF;
4033 }
4034
4035 static
4036 XS(w32_Spawn)
4037 {
4038     dXSARGS;
4039     char *cmd, *args;
4040     void *env;
4041     char *dir;
4042     PROCESS_INFORMATION stProcInfo;
4043     STARTUPINFO stStartInfo;
4044     BOOL bSuccess = FALSE;
4045
4046     if (items != 3)
4047         Perl_croak(aTHX_ "usage: Win32::Spawn($cmdName, $args, $PID)");
4048
4049     cmd = SvPV_nolen(ST(0));
4050     args = SvPV_nolen(ST(1));
4051
4052     env = PerlEnv_get_childenv();
4053     dir = PerlEnv_get_childdir();
4054
4055     memset(&stStartInfo, 0, sizeof(stStartInfo));   /* Clear the block */
4056     stStartInfo.cb = sizeof(stStartInfo);           /* Set the structure size */
4057     stStartInfo.dwFlags = STARTF_USESHOWWINDOW;     /* Enable wShowWindow control */
4058     stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE;   /* Start min (normal) */
4059
4060     if (CreateProcess(
4061                 cmd,                    /* Image path */
4062                 args,                   /* Arguments for command line */
4063                 NULL,                   /* Default process security */
4064                 NULL,                   /* Default thread security */
4065                 FALSE,                  /* Must be TRUE to use std handles */
4066                 NORMAL_PRIORITY_CLASS,  /* No special scheduling */
4067                 env,                    /* Inherit our environment block */
4068                 dir,                    /* Inherit our currrent directory */
4069                 &stStartInfo,           /* -> Startup info */
4070                 &stProcInfo))           /* <- Process info (if OK) */
4071     {
4072         int pid = (int)stProcInfo.dwProcessId;
4073         if (IsWin95() && pid < 0)
4074             pid = -pid;
4075         sv_setiv(ST(2), pid);
4076         CloseHandle(stProcInfo.hThread);/* library source code does this. */
4077         bSuccess = TRUE;
4078     }
4079     PerlEnv_free_childenv(env);
4080     PerlEnv_free_childdir(dir);
4081     XSRETURN_IV(bSuccess);
4082 }
4083
4084 static
4085 XS(w32_GetTickCount)
4086 {
4087     dXSARGS;
4088     DWORD msec = GetTickCount();
4089     EXTEND(SP,1);
4090     if ((IV)msec > 0)
4091         XSRETURN_IV(msec);
4092     XSRETURN_NV(msec);
4093 }
4094
4095 static
4096 XS(w32_GetShortPathName)
4097 {
4098     dXSARGS;
4099     SV *shortpath;
4100     DWORD len;
4101
4102     if (items != 1)
4103         Perl_croak(aTHX_ "usage: Win32::GetShortPathName($longPathName)");
4104
4105     shortpath = sv_mortalcopy(ST(0));
4106     SvUPGRADE(shortpath, SVt_PV);
4107     if (!SvPVX(shortpath) || !SvLEN(shortpath))
4108         XSRETURN_UNDEF;
4109
4110     /* src == target is allowed */
4111     do {
4112         len = GetShortPathName(SvPVX(shortpath),
4113                                SvPVX(shortpath),
4114                                SvLEN(shortpath));
4115     } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
4116     if (len) {
4117         SvCUR_set(shortpath,len);
4118         ST(0) = shortpath;
4119         XSRETURN(1);
4120     }
4121     XSRETURN_UNDEF;
4122 }
4123
4124 static
4125 XS(w32_GetFullPathName)
4126 {
4127     dXSARGS;
4128     SV *filename;
4129     SV *fullpath;
4130     char *filepart;
4131     DWORD len;
4132
4133     if (items != 1)
4134         Perl_croak(aTHX_ "usage: Win32::GetFullPathName($filename)");
4135
4136     filename = ST(0);
4137     fullpath = sv_mortalcopy(filename);
4138     SvUPGRADE(fullpath, SVt_PV);
4139     if (!SvPVX(fullpath) || !SvLEN(fullpath))
4140         XSRETURN_UNDEF;
4141
4142     do {
4143         len = GetFullPathName(SvPVX(filename),
4144                               SvLEN(fullpath),
4145                               SvPVX(fullpath),
4146                               &filepart);
4147     } while (len >= SvLEN(fullpath) && sv_grow(fullpath,len+1));
4148     if (len) {
4149         if (GIMME_V == G_ARRAY) {
4150             EXTEND(SP,1);
4151             XST_mPV(1,filepart);
4152             len = filepart - SvPVX(fullpath);
4153             items = 2;
4154         }
4155         SvCUR_set(fullpath,len);
4156         ST(0) = fullpath;
4157         XSRETURN(items);
4158     }
4159     XSRETURN_EMPTY;
4160 }
4161
4162 static
4163 XS(w32_GetLongPathName)
4164 {
4165     dXSARGS;
4166     SV *path;
4167     char tmpbuf[MAX_PATH+1];
4168     char *pathstr;
4169     STRLEN len;
4170
4171     if (items != 1)
4172         Perl_croak(aTHX_ "usage: Win32::GetLongPathName($pathname)");
4173
4174     path = ST(0);
4175     pathstr = SvPV(path,len);
4176     strcpy(tmpbuf, pathstr);
4177     pathstr = win32_longpath(tmpbuf);
4178     if (pathstr) {
4179         ST(0) = sv_2mortal(newSVpvn(pathstr, strlen(pathstr)));
4180         XSRETURN(1);
4181     }
4182     XSRETURN_EMPTY;
4183 }
4184
4185 static
4186 XS(w32_Sleep)
4187 {
4188     dXSARGS;
4189     if (items != 1)
4190         Perl_croak(aTHX_ "usage: Win32::Sleep($milliseconds)");
4191     Sleep(SvIV(ST(0)));
4192     XSRETURN_YES;
4193 }
4194
4195 static
4196 XS(w32_CopyFile)
4197 {
4198     dXSARGS;
4199     BOOL bResult;
4200     if (items != 3)
4201         Perl_croak(aTHX_ "usage: Win32::CopyFile($from, $to, $overwrite)");
4202     if (USING_WIDE()) {
4203         WCHAR wSourceFile[MAX_PATH+1];
4204         WCHAR wDestFile[MAX_PATH+1];
4205         A2WHELPER(SvPV_nolen(ST(0)), wSourceFile, sizeof(wSourceFile));
4206         wcscpy(wSourceFile, PerlDir_mapW(wSourceFile));
4207         A2WHELPER(SvPV_nolen(ST(1)), wDestFile, sizeof(wDestFile));
4208         bResult = CopyFileW(wSourceFile, PerlDir_mapW(wDestFile), !SvTRUE(ST(2)));
4209     }
4210     else {
4211         char szSourceFile[MAX_PATH+1];
4212         strcpy(szSourceFile, PerlDir_mapA(SvPV_nolen(ST(0))));
4213         bResult = CopyFileA(szSourceFile, PerlDir_mapA(SvPV_nolen(ST(1))), !SvTRUE(ST(2)));
4214     }
4215
4216     if (bResult)
4217         XSRETURN_YES;
4218     XSRETURN_NO;
4219 }
4220
4221 void
4222 Perl_init_os_extras(void)
4223 {
4224     dTHX;
4225     char *file = __FILE__;
4226     dXSUB_SYS;
4227
4228     /* these names are Activeware compatible */
4229     newXS("Win32::GetCwd", w32_GetCwd, file);
4230     newXS("Win32::SetCwd", w32_SetCwd, file);
4231     newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
4232     newXS("Win32::GetLastError", w32_GetLastError, file);
4233     newXS("Win32::SetLastError", w32_SetLastError, file);
4234     newXS("Win32::LoginName", w32_LoginName, file);
4235     newXS("Win32::NodeName", w32_NodeName, file);
4236     newXS("Win32::DomainName", w32_DomainName, file);
4237     newXS("Win32::FsType", w32_FsType, file);
4238     newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
4239     newXS("Win32::IsWinNT", w32_IsWinNT, file);
4240     newXS("Win32::IsWin95", w32_IsWin95, file);
4241     newXS("Win32::FormatMessage", w32_FormatMessage, file);
4242     newXS("Win32::Spawn", w32_Spawn, file);
4243     newXS("Win32::GetTickCount", w32_GetTickCount, file);
4244     newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
4245     newXS("Win32::GetFullPathName", w32_GetFullPathName, file);
4246     newXS("Win32::GetLongPathName", w32_GetLongPathName, file);
4247     newXS("Win32::CopyFile", w32_CopyFile, file);
4248     newXS("Win32::Sleep", w32_Sleep, file);
4249
4250     /* XXX Bloat Alert! The following Activeware preloads really
4251      * ought to be part of Win32::Sys::*, so they're not included
4252      * here.
4253      */
4254     /* LookupAccountName
4255      * LookupAccountSID
4256      * InitiateSystemShutdown
4257      * AbortSystemShutdown
4258      * ExpandEnvrironmentStrings
4259      */
4260 }
4261
4262 void
4263 Perl_win32_init(int *argcp, char ***argvp)
4264 {
4265     /* Disable floating point errors, Perl will trap the ones we
4266      * care about.  VC++ RTL defaults to switching these off
4267      * already, but the Borland RTL doesn't.  Since we don't
4268      * want to be at the vendor's whim on the default, we set
4269      * it explicitly here.
4270      */
4271 #if !defined(_ALPHA_) && !defined(__GNUC__)
4272     _control87(MCW_EM, MCW_EM);
4273 #endif
4274     MALLOC_INIT;
4275 }
4276
4277 void
4278 win32_get_child_IO(child_IO_table* ptbl)
4279 {
4280     ptbl->childStdIn    = GetStdHandle(STD_INPUT_HANDLE);
4281     ptbl->childStdOut   = GetStdHandle(STD_OUTPUT_HANDLE);
4282     ptbl->childStdErr   = GetStdHandle(STD_ERROR_HANDLE);
4283 }
4284
4285 #ifdef HAVE_INTERP_INTERN
4286
4287 void
4288 Perl_sys_intern_init(pTHX)
4289 {
4290     w32_perlshell_tokens        = Nullch;
4291     w32_perlshell_vec           = (char**)NULL;
4292     w32_perlshell_items         = 0;
4293     w32_fdpid                   = newAV();
4294     New(1313, w32_children, 1, child_tab);
4295     w32_num_children            = 0;
4296 #  ifdef USE_ITHREADS
4297     w32_pseudo_id               = 0;
4298     New(1313, w32_pseudo_children, 1, child_tab);
4299     w32_num_pseudo_children     = 0;
4300 #  endif
4301     w32_init_socktype           = 0;
4302 }
4303
4304 void
4305 Perl_sys_intern_clear(pTHX)
4306 {
4307     Safefree(w32_perlshell_tokens);
4308     Safefree(w32_perlshell_vec);
4309     /* NOTE: w32_fdpid is freed by sv_clean_all() */
4310     Safefree(w32_children);
4311 #  ifdef USE_ITHREADS
4312     Safefree(w32_pseudo_children);
4313 #  endif
4314 }
4315
4316 #  ifdef USE_ITHREADS
4317
4318 void
4319 Perl_sys_intern_dup(pTHX_ struct interp_intern *src, struct interp_intern *dst)
4320 {
4321     dst->perlshell_tokens       = Nullch;
4322     dst->perlshell_vec          = (char**)NULL;
4323     dst->perlshell_items        = 0;
4324     dst->fdpid                  = newAV();
4325     Newz(1313, dst->children, 1, child_tab);
4326     dst->pseudo_id              = 0;
4327     Newz(1313, dst->pseudo_children, 1, child_tab);
4328     dst->thr_intern.Winit_socktype = 0;
4329 }
4330 #  endif /* USE_ITHREADS */
4331 #endif /* HAVE_INTERP_INTERN */
4332
4333 static void
4334 win32_free_argvw(pTHX_ void *ptr)
4335 {
4336     char** argv = (char**)ptr;
4337     while(*argv) {
4338         Safefree(*argv);
4339         *argv++ = Nullch;
4340     }
4341 }
4342
4343 void
4344 win32_argv2utf8(int argc, char** argv)
4345 {
4346     dTHX;
4347     char* psz;
4348     int length, wargc;
4349     LPWSTR* lpwStr = CommandLineToArgvW(GetCommandLineW(), &wargc);
4350     if (lpwStr && argc) {
4351         while (argc--) {
4352             length = WideCharToMultiByte(CP_UTF8, 0, lpwStr[--wargc], -1, NULL, 0, NULL, NULL);
4353             Newz(0, psz, length, char);
4354             WideCharToMultiByte(CP_UTF8, 0, lpwStr[wargc], -1, psz, length, NULL, NULL);
4355             argv[argc] = psz;
4356         }
4357         call_atexit(win32_free_argvw, argv);
4358     }
4359     GlobalFree((HGLOBAL)lpwStr);
4360 }
4361