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