OS/390 cleanable gunk.
[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 DllExport int
1694 win32_waitpid(int pid, int *status, int flags)
1695 {
1696     dTHX;
1697     DWORD timeout = (flags & WNOHANG) ? 0 : INFINITE;
1698     int retval = -1;
1699     long child;
1700     if (pid == -1)                              /* XXX threadid == 1 ? */
1701         return win32_wait(status);
1702 #ifdef USE_ITHREADS
1703     else if (pid < 0) {
1704         child = find_pseudo_pid(-pid);
1705         if (child >= 0) {
1706             HANDLE hThread = w32_pseudo_child_handles[child];
1707             DWORD waitcode = WaitForSingleObject(hThread, timeout);
1708             if (waitcode == WAIT_TIMEOUT) {
1709                 return 0;
1710             }
1711             else if (waitcode != WAIT_FAILED) {
1712                 if (GetExitCodeThread(hThread, &waitcode)) {
1713                     *status = (int)((waitcode & 0xff) << 8);
1714                     retval = (int)w32_pseudo_child_pids[child];
1715                     remove_dead_pseudo_process(child);
1716                     return -retval;
1717                 }
1718             }
1719             else
1720                 errno = ECHILD;
1721         }
1722         else if (IsWin95()) {
1723             pid = -pid;
1724             goto alien_process;
1725         }
1726     }
1727 #endif
1728     else {
1729         HANDLE hProcess;
1730         DWORD waitcode;
1731         child = find_pid(pid);
1732         if (child >= 0) {
1733             hProcess = w32_child_handles[child];
1734             waitcode = WaitForSingleObject(hProcess, timeout);
1735             if (waitcode == WAIT_TIMEOUT) {
1736                 return 0;
1737             }
1738             else if (waitcode != WAIT_FAILED) {
1739                 if (GetExitCodeProcess(hProcess, &waitcode)) {
1740                     *status = (int)((waitcode & 0xff) << 8);
1741                     retval = (int)w32_child_pids[child];
1742                     remove_dead_process(child);
1743                     return retval;
1744                 }
1745             }
1746             else
1747                 errno = ECHILD;
1748         }
1749         else {
1750 alien_process:
1751             hProcess = OpenProcess(PROCESS_ALL_ACCESS, TRUE,
1752                                    (IsWin95() ? -pid : pid));
1753             if (hProcess) {
1754                 waitcode = WaitForSingleObject(hProcess, timeout);
1755                 if (waitcode == WAIT_TIMEOUT) {
1756                     return 0;
1757                 }
1758                 else if (waitcode != WAIT_FAILED) {
1759                     if (GetExitCodeProcess(hProcess, &waitcode)) {
1760                         *status = (int)((waitcode & 0xff) << 8);
1761                         CloseHandle(hProcess);
1762                         return pid;
1763                     }
1764                 }
1765                 CloseHandle(hProcess);
1766             }
1767             else
1768                 errno = ECHILD;
1769         }
1770     }
1771     return retval >= 0 ? pid : retval;                
1772 }
1773
1774 DllExport int
1775 win32_wait(int *status)
1776 {
1777     /* XXX this wait emulation only knows about processes
1778      * spawned via win32_spawnvp(P_NOWAIT, ...).
1779      */
1780     dTHX;
1781     int i, retval;
1782     DWORD exitcode, waitcode;
1783
1784 #ifdef USE_ITHREADS
1785     if (w32_num_pseudo_children) {
1786         waitcode = WaitForMultipleObjects(w32_num_pseudo_children,
1787                                           w32_pseudo_child_handles,
1788                                           FALSE,
1789                                           INFINITE);
1790         if (waitcode != WAIT_FAILED) {
1791             if (waitcode >= WAIT_ABANDONED_0
1792                 && waitcode < WAIT_ABANDONED_0 + w32_num_pseudo_children)
1793                 i = waitcode - WAIT_ABANDONED_0;
1794             else
1795                 i = waitcode - WAIT_OBJECT_0;
1796             if (GetExitCodeThread(w32_pseudo_child_handles[i], &exitcode)) {
1797                 *status = (int)((exitcode & 0xff) << 8);
1798                 retval = (int)w32_pseudo_child_pids[i];
1799                 remove_dead_pseudo_process(i);
1800                 return -retval;
1801             }
1802         }
1803     }
1804 #endif
1805
1806     if (!w32_num_children) {
1807         errno = ECHILD;
1808         return -1;
1809     }
1810
1811     /* if a child exists, wait for it to die */
1812     waitcode = WaitForMultipleObjects(w32_num_children,
1813                                       w32_child_handles,
1814                                       FALSE,
1815                                       INFINITE);
1816     if (waitcode != WAIT_FAILED) {
1817         if (waitcode >= WAIT_ABANDONED_0
1818             && waitcode < WAIT_ABANDONED_0 + w32_num_children)
1819             i = waitcode - WAIT_ABANDONED_0;
1820         else
1821             i = waitcode - WAIT_OBJECT_0;
1822         if (GetExitCodeProcess(w32_child_handles[i], &exitcode) ) {
1823             *status = (int)((exitcode & 0xff) << 8);
1824             retval = (int)w32_child_pids[i];
1825             remove_dead_process(i);
1826             return retval;
1827         }
1828     }
1829
1830 FAILED:
1831     errno = GetLastError();
1832     return -1;
1833 }
1834
1835 #ifndef PERL_IMPLICIT_CONTEXT
1836
1837 static UINT timerid = 0;
1838
1839 static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
1840 {
1841     dTHX;
1842     KillTimer(NULL,timerid);
1843     timerid=0;  
1844     CALL_FPTR(PL_sighandlerp)(14);
1845 }
1846
1847 #endif /* !PERL_IMPLICIT_CONTEXT */
1848
1849 DllExport unsigned int
1850 win32_alarm(unsigned int sec)
1851 {
1852 #ifndef PERL_IMPLICIT_CONTEXT
1853     /* 
1854      * the 'obvious' implentation is SetTimer() with a callback
1855      * which does whatever receiving SIGALRM would do 
1856      * we cannot use SIGALRM even via raise() as it is not 
1857      * one of the supported codes in <signal.h>
1858      *
1859      * Snag is unless something is looking at the message queue
1860      * nothing happens :-(
1861      */ 
1862     dTHX;
1863     if (sec)
1864      {
1865       timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
1866       if (!timerid)
1867        Perl_croak_nocontext("Cannot set timer");
1868      } 
1869     else
1870      {
1871       if (timerid)
1872        {
1873         KillTimer(NULL,timerid);
1874         timerid=0;  
1875        }
1876      }
1877 #endif /* !PERL_IMPLICIT_CONTEXT */
1878     return 0;
1879 }
1880
1881 #ifdef HAVE_DES_FCRYPT
1882 extern char *   des_fcrypt(const char *txt, const char *salt, char *cbuf);
1883 #endif
1884
1885 DllExport char *
1886 win32_crypt(const char *txt, const char *salt)
1887 {
1888     dTHX;
1889 #ifdef HAVE_DES_FCRYPT
1890     return des_fcrypt(txt, salt, w32_crypt_buffer);
1891 #else
1892     Perl_croak(aTHX_ "The crypt() function is unimplemented due to excessive paranoia.");
1893     return Nullch;
1894 #endif
1895 }
1896
1897 #ifdef USE_FIXED_OSFHANDLE
1898
1899 #define FOPEN                   0x01    /* file handle open */
1900 #define FNOINHERIT              0x10    /* file handle opened O_NOINHERIT */
1901 #define FAPPEND                 0x20    /* file handle opened O_APPEND */
1902 #define FDEV                    0x40    /* file handle refers to device */
1903 #define FTEXT                   0x80    /* file handle is in text mode */
1904
1905 /***
1906 *int my_open_osfhandle(long osfhandle, int flags) - open C Runtime file handle
1907 *
1908 *Purpose:
1909 *       This function allocates a free C Runtime file handle and associates
1910 *       it with the Win32 HANDLE specified by the first parameter. This is a
1911 *       temperary fix for WIN95's brain damage GetFileType() error on socket
1912 *       we just bypass that call for socket
1913 *
1914 *       This works with MSVC++ 4.0+ or GCC/Mingw32
1915 *
1916 *Entry:
1917 *       long osfhandle - Win32 HANDLE to associate with C Runtime file handle.
1918 *       int flags      - flags to associate with C Runtime file handle.
1919 *
1920 *Exit:
1921 *       returns index of entry in fh, if successful
1922 *       return -1, if no free entry is found
1923 *
1924 *Exceptions:
1925 *
1926 *******************************************************************************/
1927
1928 /*
1929  * we fake up some parts of the CRT that aren't exported by MSVCRT.dll
1930  * this lets sockets work on Win9X with GCC and should fix the problems
1931  * with perl95.exe
1932  *      -- BKS, 1-23-2000
1933 */
1934
1935 /* create an ioinfo entry, kill its handle, and steal the entry */
1936
1937 static int
1938 _alloc_osfhnd(void)
1939 {
1940     HANDLE hF = CreateFile("NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
1941     int fh = _open_osfhandle((long)hF, 0);
1942     CloseHandle(hF);
1943     if (fh == -1)
1944         return fh;
1945     EnterCriticalSection(&(_pioinfo(fh)->lock));
1946     return fh;
1947 }
1948
1949 static int
1950 my_open_osfhandle(long osfhandle, int flags)
1951 {
1952     int fh;
1953     char fileflags;             /* _osfile flags */
1954
1955     /* copy relevant flags from second parameter */
1956     fileflags = FDEV;
1957
1958     if (flags & O_APPEND)
1959         fileflags |= FAPPEND;
1960
1961     if (flags & O_TEXT)
1962         fileflags |= FTEXT;
1963
1964     if (flags & O_NOINHERIT)
1965         fileflags |= FNOINHERIT;
1966
1967     /* attempt to allocate a C Runtime file handle */
1968     if ((fh = _alloc_osfhnd()) == -1) {
1969         errno = EMFILE;         /* too many open files */
1970         _doserrno = 0L;         /* not an OS error */
1971         return -1;              /* return error to caller */
1972     }
1973
1974     /* the file is open. now, set the info in _osfhnd array */
1975     _set_osfhnd(fh, osfhandle);
1976
1977     fileflags |= FOPEN;         /* mark as open */
1978
1979     _osfile(fh) = fileflags;    /* set osfile entry */
1980     LeaveCriticalSection(&_pioinfo(fh)->lock);
1981
1982     return fh;                  /* return handle */
1983 }
1984
1985 #endif  /* USE_FIXED_OSFHANDLE */
1986
1987 /* simulate flock by locking a range on the file */
1988
1989 #define LK_ERR(f,i)     ((f) ? (i = 0) : (errno = GetLastError()))
1990 #define LK_LEN          0xffff0000
1991
1992 DllExport int
1993 win32_flock(int fd, int oper)
1994 {
1995     OVERLAPPED o;
1996     int i = -1;
1997     HANDLE fh;
1998
1999     if (!IsWinNT()) {
2000         dTHX;
2001         Perl_croak_nocontext("flock() unimplemented on this platform");
2002         return -1;
2003     }
2004     fh = (HANDLE)_get_osfhandle(fd);
2005     memset(&o, 0, sizeof(o));
2006
2007     switch(oper) {
2008     case LOCK_SH:               /* shared lock */
2009         LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
2010         break;
2011     case LOCK_EX:               /* exclusive lock */
2012         LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
2013         break;
2014     case LOCK_SH|LOCK_NB:       /* non-blocking shared lock */
2015         LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
2016         break;
2017     case LOCK_EX|LOCK_NB:       /* non-blocking exclusive lock */
2018         LK_ERR(LockFileEx(fh,
2019                        LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
2020                        0, LK_LEN, 0, &o),i);
2021         break;
2022     case LOCK_UN:               /* unlock lock */
2023         LK_ERR(UnlockFileEx(fh, 0, LK_LEN, 0, &o),i);
2024         break;
2025     default:                    /* unknown */
2026         errno = EINVAL;
2027         break;
2028     }
2029     return i;
2030 }
2031
2032 #undef LK_ERR
2033 #undef LK_LEN
2034
2035 /*
2036  *  redirected io subsystem for all XS modules
2037  *
2038  */
2039
2040 DllExport int *
2041 win32_errno(void)
2042 {
2043     return (&errno);
2044 }
2045
2046 DllExport char ***
2047 win32_environ(void)
2048 {
2049     return (&(_environ));
2050 }
2051
2052 /* the rest are the remapped stdio routines */
2053 DllExport FILE *
2054 win32_stderr(void)
2055 {
2056     return (stderr);
2057 }
2058
2059 DllExport FILE *
2060 win32_stdin(void)
2061 {
2062     return (stdin);
2063 }
2064
2065 DllExport FILE *
2066 win32_stdout()
2067 {
2068     return (stdout);
2069 }
2070
2071 DllExport int
2072 win32_ferror(FILE *fp)
2073 {
2074     return (ferror(fp));
2075 }
2076
2077
2078 DllExport int
2079 win32_feof(FILE *fp)
2080 {
2081     return (feof(fp));
2082 }
2083
2084 /*
2085  * Since the errors returned by the socket error function 
2086  * WSAGetLastError() are not known by the library routine strerror
2087  * we have to roll our own.
2088  */
2089
2090 DllExport char *
2091 win32_strerror(int e) 
2092 {
2093 #if !defined __BORLANDC__ && !defined __MINGW32__      /* compiler intolerance */
2094     extern int sys_nerr;
2095 #endif
2096     DWORD source = 0;
2097
2098     if (e < 0 || e > sys_nerr) {
2099         dTHX;
2100         if (e < 0)
2101             e = GetLastError();
2102
2103         if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
2104                           w32_strerror_buffer,
2105                           sizeof(w32_strerror_buffer), NULL) == 0) 
2106             strcpy(w32_strerror_buffer, "Unknown Error");
2107
2108         return w32_strerror_buffer;
2109     }
2110     return strerror(e);
2111 }
2112
2113 DllExport void
2114 win32_str_os_error(void *sv, DWORD dwErr)
2115 {
2116     DWORD dwLen;
2117     char *sMsg;
2118     dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
2119                           |FORMAT_MESSAGE_IGNORE_INSERTS
2120                           |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
2121                            dwErr, 0, (char *)&sMsg, 1, NULL);
2122     /* strip trailing whitespace and period */
2123     if (0 < dwLen) {
2124         do {
2125             --dwLen;    /* dwLen doesn't include trailing null */
2126         } while (0 < dwLen && isSPACE(sMsg[dwLen]));
2127         if ('.' != sMsg[dwLen])
2128             dwLen++;
2129         sMsg[dwLen] = '\0';
2130     }
2131     if (0 == dwLen) {
2132         sMsg = (char*)LocalAlloc(0, 64/**sizeof(TCHAR)*/);
2133         if (sMsg)
2134             dwLen = sprintf(sMsg,
2135                             "Unknown error #0x%lX (lookup 0x%lX)",
2136                             dwErr, GetLastError());
2137     }
2138     if (sMsg) {
2139         dTHX;
2140         sv_setpvn((SV*)sv, sMsg, dwLen);
2141         LocalFree(sMsg);
2142     }
2143 }
2144
2145 DllExport int
2146 win32_fprintf(FILE *fp, const char *format, ...)
2147 {
2148     va_list marker;
2149     va_start(marker, format);     /* Initialize variable arguments. */
2150
2151     return (vfprintf(fp, format, marker));
2152 }
2153
2154 DllExport int
2155 win32_printf(const char *format, ...)
2156 {
2157     va_list marker;
2158     va_start(marker, format);     /* Initialize variable arguments. */
2159
2160     return (vprintf(format, marker));
2161 }
2162
2163 DllExport int
2164 win32_vfprintf(FILE *fp, const char *format, va_list args)
2165 {
2166     return (vfprintf(fp, format, args));
2167 }
2168
2169 DllExport int
2170 win32_vprintf(const char *format, va_list args)
2171 {
2172     return (vprintf(format, args));
2173 }
2174
2175 DllExport size_t
2176 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
2177 {
2178     return fread(buf, size, count, fp);
2179 }
2180
2181 DllExport size_t
2182 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
2183 {
2184     return fwrite(buf, size, count, fp);
2185 }
2186
2187 #define MODE_SIZE 10
2188
2189 DllExport FILE *
2190 win32_fopen(const char *filename, const char *mode)
2191 {
2192     dTHX;
2193     WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH+1];
2194     FILE *f;
2195     
2196     if (!*filename)
2197         return NULL;
2198
2199     if (stricmp(filename, "/dev/null")==0)
2200         filename = "NUL";
2201
2202     if (USING_WIDE()) {
2203         A2WHELPER(mode, wMode, sizeof(wMode));
2204         A2WHELPER(filename, wBuffer, sizeof(wBuffer));
2205         f = _wfopen(PerlDir_mapW(wBuffer), wMode);
2206     }
2207     else
2208         f = fopen(PerlDir_mapA(filename), mode);
2209     /* avoid buffering headaches for child processes */
2210     if (f && *mode == 'a')
2211         win32_fseek(f, 0, SEEK_END);
2212     return f;
2213 }
2214
2215 #ifndef USE_SOCKETS_AS_HANDLES
2216 #undef fdopen
2217 #define fdopen my_fdopen
2218 #endif
2219
2220 DllExport FILE *
2221 win32_fdopen(int handle, const char *mode)
2222 {
2223     dTHX;
2224     WCHAR wMode[MODE_SIZE];
2225     FILE *f;
2226     if (USING_WIDE()) {
2227         A2WHELPER(mode, wMode, sizeof(wMode));
2228         f = _wfdopen(handle, wMode);
2229     }
2230     else
2231         f = fdopen(handle, (char *) mode);
2232     /* avoid buffering headaches for child processes */
2233     if (f && *mode == 'a')
2234         win32_fseek(f, 0, SEEK_END);
2235     return f;
2236 }
2237
2238 DllExport FILE *
2239 win32_freopen(const char *path, const char *mode, FILE *stream)
2240 {
2241     dTHX;
2242     WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH+1];
2243     if (stricmp(path, "/dev/null")==0)
2244         path = "NUL";
2245
2246     if (USING_WIDE()) {
2247         A2WHELPER(mode, wMode, sizeof(wMode));
2248         A2WHELPER(path, wBuffer, sizeof(wBuffer));
2249         return _wfreopen(PerlDir_mapW(wBuffer), wMode, stream);
2250     }
2251     return freopen(PerlDir_mapA(path), mode, stream);
2252 }
2253
2254 DllExport int
2255 win32_fclose(FILE *pf)
2256 {
2257     return my_fclose(pf);       /* defined in win32sck.c */
2258 }
2259
2260 DllExport int
2261 win32_fputs(const char *s,FILE *pf)
2262 {
2263     return fputs(s, pf);
2264 }
2265
2266 DllExport int
2267 win32_fputc(int c,FILE *pf)
2268 {
2269     return fputc(c,pf);
2270 }
2271
2272 DllExport int
2273 win32_ungetc(int c,FILE *pf)
2274 {
2275     return ungetc(c,pf);
2276 }
2277
2278 DllExport int
2279 win32_getc(FILE *pf)
2280 {
2281     return getc(pf);
2282 }
2283
2284 DllExport int
2285 win32_fileno(FILE *pf)
2286 {
2287     return fileno(pf);
2288 }
2289
2290 DllExport void
2291 win32_clearerr(FILE *pf)
2292 {
2293     clearerr(pf);
2294     return;
2295 }
2296
2297 DllExport int
2298 win32_fflush(FILE *pf)
2299 {
2300     return fflush(pf);
2301 }
2302
2303 DllExport long
2304 win32_ftell(FILE *pf)
2305 {
2306     return ftell(pf);
2307 }
2308
2309 DllExport int
2310 win32_fseek(FILE *pf,long offset,int origin)
2311 {
2312     return fseek(pf, offset, origin);
2313 }
2314
2315 DllExport int
2316 win32_fgetpos(FILE *pf,fpos_t *p)
2317 {
2318     return fgetpos(pf, p);
2319 }
2320
2321 DllExport int
2322 win32_fsetpos(FILE *pf,const fpos_t *p)
2323 {
2324     return fsetpos(pf, p);
2325 }
2326
2327 DllExport void
2328 win32_rewind(FILE *pf)
2329 {
2330     rewind(pf);
2331     return;
2332 }
2333
2334 DllExport FILE*
2335 win32_tmpfile(void)
2336 {
2337     dTHX;
2338     char prefix[MAX_PATH+1];
2339     char filename[MAX_PATH+1];
2340     DWORD len = GetTempPath(MAX_PATH, prefix);
2341     if (len && len < MAX_PATH) {
2342         if (GetTempFileName(prefix, "plx", 0, filename)) {
2343             HANDLE fh = CreateFile(filename,
2344                                    DELETE | GENERIC_READ | GENERIC_WRITE,
2345                                    0,
2346                                    NULL,
2347                                    CREATE_ALWAYS,
2348                                    FILE_ATTRIBUTE_NORMAL
2349                                    | FILE_FLAG_DELETE_ON_CLOSE,
2350                                    NULL);
2351             if (fh != INVALID_HANDLE_VALUE) {
2352                 int fd = win32_open_osfhandle((long)fh, 0);
2353                 if (fd >= 0) {
2354                     DEBUG_p(PerlIO_printf(Perl_debug_log,
2355                                           "Created tmpfile=%s\n",filename));
2356                     return fdopen(fd, "w+b");
2357                 }
2358             }
2359         }
2360     }
2361     return NULL;
2362 }
2363
2364 DllExport void
2365 win32_abort(void)
2366 {
2367     abort();
2368     return;
2369 }
2370
2371 DllExport int
2372 win32_fstat(int fd,struct stat *sbufptr)
2373 {
2374 #ifdef __BORLANDC__
2375     /* A file designated by filehandle is not shown as accessible
2376      * for write operations, probably because it is opened for reading.
2377      * --Vadim Konovalov
2378      */ 
2379     int rc = fstat(fd,sbufptr);
2380     BY_HANDLE_FILE_INFORMATION bhfi;
2381     if (GetFileInformationByHandle((HANDLE)_get_osfhandle(fd), &bhfi)) {
2382         sbufptr->st_mode &= 0xFE00;
2383         if (bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
2384             sbufptr->st_mode |= (S_IREAD + (S_IREAD >> 3) + (S_IREAD >> 6));
2385         else
2386             sbufptr->st_mode |= ((S_IREAD|S_IWRITE) + ((S_IREAD|S_IWRITE) >> 3)
2387               + ((S_IREAD|S_IWRITE) >> 6));
2388     }
2389     return rc;
2390 #else
2391     return my_fstat(fd,sbufptr);
2392 #endif
2393 }
2394
2395 DllExport int
2396 win32_pipe(int *pfd, unsigned int size, int mode)
2397 {
2398     return _pipe(pfd, size, mode);
2399 }
2400
2401 DllExport PerlIO*
2402 win32_popenlist(const char *mode, IV narg, SV **args)
2403 {
2404  dTHX;
2405  Perl_croak(aTHX_ "List form of pipe open not implemented");
2406  return NULL;
2407 }
2408
2409 /*
2410  * a popen() clone that respects PERL5SHELL
2411  *
2412  * changed to return PerlIO* rather than FILE * by BKS, 11-11-2000
2413  */
2414
2415 DllExport PerlIO*
2416 win32_popen(const char *command, const char *mode)
2417 {
2418 #ifdef USE_RTL_POPEN
2419     return _popen(command, mode);
2420 #else
2421     int p[2];
2422     int parent, child;
2423     int stdfd, oldfd;
2424     int ourmode;
2425     int childpid;
2426
2427     /* establish which ends read and write */
2428     if (strchr(mode,'w')) {
2429         stdfd = 0;              /* stdin */
2430         parent = 1;
2431         child = 0;
2432     }
2433     else if (strchr(mode,'r')) {
2434         stdfd = 1;              /* stdout */
2435         parent = 0;
2436         child = 1;
2437     }
2438     else
2439         return NULL;
2440
2441     /* set the correct mode */
2442     if (strchr(mode,'b'))
2443         ourmode = O_BINARY;
2444     else if (strchr(mode,'t'))
2445         ourmode = O_TEXT;
2446     else
2447         ourmode = _fmode & (O_TEXT | O_BINARY);
2448
2449     /* the child doesn't inherit handles */
2450     ourmode |= O_NOINHERIT;
2451
2452     if (win32_pipe( p, 512, ourmode) == -1)
2453         return NULL;
2454
2455     /* save current stdfd */
2456     if ((oldfd = win32_dup(stdfd)) == -1)
2457         goto cleanup;
2458
2459     /* make stdfd go to child end of pipe (implicitly closes stdfd) */
2460     /* stdfd will be inherited by the child */
2461     if (win32_dup2(p[child], stdfd) == -1)
2462         goto cleanup;
2463
2464     /* close the child end in parent */
2465     win32_close(p[child]);
2466
2467     /* start the child */
2468     {
2469         dTHX;
2470         if ((childpid = do_spawn_nowait((char*)command)) == -1)
2471             goto cleanup;
2472
2473         /* revert stdfd to whatever it was before */
2474         if (win32_dup2(oldfd, stdfd) == -1)
2475             goto cleanup;
2476
2477         /* close saved handle */
2478         win32_close(oldfd);
2479
2480         LOCK_FDPID_MUTEX;
2481         sv_setiv(*av_fetch(w32_fdpid, p[parent], TRUE), childpid);
2482         UNLOCK_FDPID_MUTEX;
2483
2484         /* set process id so that it can be returned by perl's open() */
2485         PL_forkprocess = childpid;
2486     }
2487
2488     /* we have an fd, return a file stream */
2489     return (PerlIO_fdopen(p[parent], (char *)mode));
2490
2491 cleanup:
2492     /* we don't need to check for errors here */
2493     win32_close(p[0]);
2494     win32_close(p[1]);
2495     if (oldfd != -1) {
2496         win32_dup2(oldfd, stdfd);
2497         win32_close(oldfd);
2498     }
2499     return (NULL);
2500
2501 #endif /* USE_RTL_POPEN */
2502 }
2503
2504 /*
2505  * pclose() clone
2506  */
2507
2508 DllExport int
2509 win32_pclose(PerlIO *pf)
2510 {
2511 #ifdef USE_RTL_POPEN
2512     return _pclose(pf);
2513 #else
2514     dTHX;
2515     int childpid, status;
2516     SV *sv;
2517
2518     LOCK_FDPID_MUTEX;
2519     sv = *av_fetch(w32_fdpid, PerlIO_fileno(pf), TRUE);
2520
2521     if (SvIOK(sv))
2522         childpid = SvIVX(sv);
2523     else
2524         childpid = 0;
2525
2526     if (!childpid) {
2527         errno = EBADF;
2528         return -1;
2529     }
2530
2531 #ifdef USE_PERLIO
2532     PerlIO_close(pf);
2533 #else
2534     fclose(pf);
2535 #endif
2536     SvIVX(sv) = 0;
2537     UNLOCK_FDPID_MUTEX;
2538
2539     if (win32_waitpid(childpid, &status, 0) == -1)
2540         return -1;
2541
2542     return status;
2543
2544 #endif /* USE_RTL_POPEN */
2545 }
2546
2547 static BOOL WINAPI
2548 Nt4CreateHardLinkW(
2549     LPCWSTR lpFileName,
2550     LPCWSTR lpExistingFileName,
2551     LPSECURITY_ATTRIBUTES lpSecurityAttributes)
2552 {
2553     HANDLE handle;
2554     WCHAR wFullName[MAX_PATH+1];
2555     LPVOID lpContext = NULL;
2556     WIN32_STREAM_ID StreamId;
2557     DWORD dwSize = (char*)&StreamId.cStreamName - (char*)&StreamId;
2558     DWORD dwWritten;
2559     DWORD dwLen;
2560     BOOL bSuccess;
2561
2562     BOOL (__stdcall *pfnBackupWrite)(HANDLE, LPBYTE, DWORD, LPDWORD,
2563                                      BOOL, BOOL, LPVOID*) =
2564         (BOOL (__stdcall *)(HANDLE, LPBYTE, DWORD, LPDWORD,
2565                             BOOL, BOOL, LPVOID*))
2566         GetProcAddress(GetModuleHandle("kernel32.dll"), "BackupWrite");
2567     if (pfnBackupWrite == NULL)
2568         return 0;
2569
2570     dwLen = GetFullPathNameW(lpFileName, MAX_PATH, wFullName, NULL);
2571     if (dwLen == 0)
2572         return 0;
2573     dwLen = (dwLen+1)*sizeof(WCHAR);
2574
2575     handle = CreateFileW(lpExistingFileName, FILE_WRITE_ATTRIBUTES,
2576                          FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
2577                          NULL, OPEN_EXISTING, 0, NULL);
2578     if (handle == INVALID_HANDLE_VALUE)
2579         return 0;
2580
2581     StreamId.dwStreamId = BACKUP_LINK;
2582     StreamId.dwStreamAttributes = 0;
2583     StreamId.dwStreamNameSize = 0;
2584 #if defined(__BORLANDC__) \
2585  ||(defined(__MINGW32__) && !defined(_ANONYMOUS_UNION))
2586     StreamId.Size.u.HighPart = 0;
2587     StreamId.Size.u.LowPart = dwLen;
2588 #else
2589     StreamId.Size.HighPart = 0;
2590     StreamId.Size.LowPart = dwLen;
2591 #endif
2592
2593     bSuccess = pfnBackupWrite(handle, (LPBYTE)&StreamId, dwSize, &dwWritten,
2594                               FALSE, FALSE, &lpContext);
2595     if (bSuccess) {
2596         bSuccess = pfnBackupWrite(handle, (LPBYTE)wFullName, dwLen, &dwWritten,
2597                                   FALSE, FALSE, &lpContext);
2598         pfnBackupWrite(handle, NULL, 0, &dwWritten, TRUE, FALSE, &lpContext);
2599     }
2600
2601     CloseHandle(handle);
2602     return bSuccess;
2603 }
2604
2605 DllExport int
2606 win32_link(const char *oldname, const char *newname)
2607 {
2608     dTHX;
2609     BOOL (__stdcall *pfnCreateHardLinkW)(LPCWSTR,LPCWSTR,LPSECURITY_ATTRIBUTES);
2610     WCHAR wOldName[MAX_PATH+1];
2611     WCHAR wNewName[MAX_PATH+1];
2612
2613     if (IsWin95())
2614         Perl_croak(aTHX_ PL_no_func, "link");
2615
2616     pfnCreateHardLinkW =
2617         (BOOL (__stdcall *)(LPCWSTR, LPCWSTR, LPSECURITY_ATTRIBUTES))
2618         GetProcAddress(GetModuleHandle("kernel32.dll"), "CreateHardLinkW");
2619     if (pfnCreateHardLinkW == NULL)
2620         pfnCreateHardLinkW = Nt4CreateHardLinkW;
2621
2622     if ((A2WHELPER(oldname, wOldName, sizeof(wOldName))) &&
2623         (A2WHELPER(newname, wNewName, sizeof(wNewName))) &&
2624         (wcscpy(wOldName, PerlDir_mapW(wOldName)),
2625         pfnCreateHardLinkW(PerlDir_mapW(wNewName), wOldName, NULL)))
2626     {
2627         return 0;
2628     }
2629     errno = (GetLastError() == ERROR_FILE_NOT_FOUND) ? ENOENT : EINVAL;
2630     return -1;
2631 }
2632
2633 DllExport int
2634 win32_rename(const char *oname, const char *newname)
2635 {
2636     WCHAR wOldName[MAX_PATH+1];
2637     WCHAR wNewName[MAX_PATH+1];
2638     char szOldName[MAX_PATH+1];
2639     char szNewName[MAX_PATH+1];
2640     BOOL bResult;
2641     dTHX;
2642
2643     /* XXX despite what the documentation says about MoveFileEx(),
2644      * it doesn't work under Windows95!
2645      */
2646     if (IsWinNT()) {
2647         DWORD dwFlags = MOVEFILE_COPY_ALLOWED;
2648         if (USING_WIDE()) {
2649             A2WHELPER(oname, wOldName, sizeof(wOldName));
2650             A2WHELPER(newname, wNewName, sizeof(wNewName));
2651             if (wcsicmp(wNewName, wOldName))
2652                 dwFlags |= MOVEFILE_REPLACE_EXISTING;
2653             wcscpy(wOldName, PerlDir_mapW(wOldName));
2654             bResult = MoveFileExW(wOldName,PerlDir_mapW(wNewName), dwFlags);
2655         }
2656         else {
2657             if (stricmp(newname, oname))
2658                 dwFlags |= MOVEFILE_REPLACE_EXISTING;
2659             strcpy(szOldName, PerlDir_mapA(oname));
2660             bResult = MoveFileExA(szOldName,PerlDir_mapA(newname), dwFlags);
2661         }
2662         if (!bResult) {
2663             DWORD err = GetLastError();
2664             switch (err) {
2665             case ERROR_BAD_NET_NAME:
2666             case ERROR_BAD_NETPATH:
2667             case ERROR_BAD_PATHNAME:
2668             case ERROR_FILE_NOT_FOUND:
2669             case ERROR_FILENAME_EXCED_RANGE:
2670             case ERROR_INVALID_DRIVE:
2671             case ERROR_NO_MORE_FILES:
2672             case ERROR_PATH_NOT_FOUND:
2673                 errno = ENOENT;
2674                 break;
2675             default:
2676                 errno = EACCES;
2677                 break;
2678             }
2679             return -1;
2680         }
2681         return 0;
2682     }
2683     else {
2684         int retval = 0;
2685         char szTmpName[MAX_PATH+1];
2686         char dname[MAX_PATH+1];
2687         char *endname = Nullch;
2688         STRLEN tmplen = 0;
2689         DWORD from_attr, to_attr;
2690
2691         strcpy(szOldName, PerlDir_mapA(oname));
2692         strcpy(szNewName, PerlDir_mapA(newname));
2693
2694         /* if oname doesn't exist, do nothing */
2695         from_attr = GetFileAttributes(szOldName);
2696         if (from_attr == 0xFFFFFFFF) {
2697             errno = ENOENT;
2698             return -1;
2699         }
2700
2701         /* if newname exists, rename it to a temporary name so that we
2702          * don't delete it in case oname happens to be the same file
2703          * (but perhaps accessed via a different path)
2704          */
2705         to_attr = GetFileAttributes(szNewName);
2706         if (to_attr != 0xFFFFFFFF) {
2707             /* if newname is a directory, we fail
2708              * XXX could overcome this with yet more convoluted logic */
2709             if (to_attr & FILE_ATTRIBUTE_DIRECTORY) {
2710                 errno = EACCES;
2711                 return -1;
2712             }
2713             tmplen = strlen(szNewName);
2714             strcpy(szTmpName,szNewName);
2715             endname = szTmpName+tmplen;
2716             for (; endname > szTmpName ; --endname) {
2717                 if (*endname == '/' || *endname == '\\') {
2718                     *endname = '\0';
2719                     break;
2720                 }
2721             }
2722             if (endname > szTmpName)
2723                 endname = strcpy(dname,szTmpName);
2724             else
2725                 endname = ".";
2726
2727             /* get a temporary filename in same directory
2728              * XXX is this really the best we can do? */
2729             if (!GetTempFileName((LPCTSTR)endname, "plr", 0, szTmpName)) {
2730                 errno = ENOENT;
2731                 return -1;
2732             }
2733             DeleteFile(szTmpName);
2734
2735             retval = rename(szNewName, szTmpName);
2736             if (retval != 0) {
2737                 errno = EACCES;
2738                 return retval;
2739             }
2740         }
2741
2742         /* rename oname to newname */
2743         retval = rename(szOldName, szNewName);
2744
2745         /* if we created a temporary file before ... */
2746         if (endname != Nullch) {
2747             /* ...and rename succeeded, delete temporary file/directory */
2748             if (retval == 0)
2749                 DeleteFile(szTmpName);
2750             /* else restore it to what it was */
2751             else
2752                 (void)rename(szTmpName, szNewName);
2753         }
2754         return retval;
2755     }
2756 }
2757
2758 DllExport int
2759 win32_setmode(int fd, int mode)
2760 {
2761     return setmode(fd, mode);
2762 }
2763
2764 DllExport long
2765 win32_lseek(int fd, long offset, int origin)
2766 {
2767     return lseek(fd, offset, origin);
2768 }
2769
2770 DllExport long
2771 win32_tell(int fd)
2772 {
2773     return tell(fd);
2774 }
2775
2776 DllExport int
2777 win32_open(const char *path, int flag, ...)
2778 {
2779     dTHX;
2780     va_list ap;
2781     int pmode;
2782     WCHAR wBuffer[MAX_PATH+1];
2783
2784     va_start(ap, flag);
2785     pmode = va_arg(ap, int);
2786     va_end(ap);
2787
2788     if (stricmp(path, "/dev/null")==0)
2789         path = "NUL";
2790
2791     if (USING_WIDE()) {
2792         A2WHELPER(path, wBuffer, sizeof(wBuffer));
2793         return _wopen(PerlDir_mapW(wBuffer), flag, pmode);
2794     }
2795     return open(PerlDir_mapA(path), flag, pmode);
2796 }
2797
2798 /* close() that understands socket */
2799 extern int my_close(int);       /* in win32sck.c */
2800
2801 DllExport int
2802 win32_close(int fd)
2803 {
2804     return my_close(fd);
2805 }
2806
2807 DllExport int
2808 win32_eof(int fd)
2809 {
2810     return eof(fd);
2811 }
2812
2813 DllExport int
2814 win32_dup(int fd)
2815 {
2816     return dup(fd);
2817 }
2818
2819 DllExport int
2820 win32_dup2(int fd1,int fd2)
2821 {
2822     return dup2(fd1,fd2);
2823 }
2824
2825 #ifdef PERL_MSVCRT_READFIX
2826
2827 #define LF              10      /* line feed */
2828 #define CR              13      /* carriage return */
2829 #define CTRLZ           26      /* ctrl-z means eof for text */
2830 #define FOPEN           0x01    /* file handle open */
2831 #define FEOFLAG         0x02    /* end of file has been encountered */
2832 #define FCRLF           0x04    /* CR-LF across read buffer (in text mode) */
2833 #define FPIPE           0x08    /* file handle refers to a pipe */
2834 #define FAPPEND         0x20    /* file handle opened O_APPEND */
2835 #define FDEV            0x40    /* file handle refers to device */
2836 #define FTEXT           0x80    /* file handle is in text mode */
2837 #define MAX_DESCRIPTOR_COUNT    (64*32) /* this is the maximun that MSVCRT can handle */
2838
2839 int __cdecl
2840 _fixed_read(int fh, void *buf, unsigned cnt)
2841 {
2842     int bytes_read;                 /* number of bytes read */
2843     char *buffer;                   /* buffer to read to */
2844     int os_read;                    /* bytes read on OS call */
2845     char *p, *q;                    /* pointers into buffer */
2846     char peekchr;                   /* peek-ahead character */
2847     ULONG filepos;                  /* file position after seek */
2848     ULONG dosretval;                /* o.s. return value */
2849
2850     /* validate handle */
2851     if (((unsigned)fh >= (unsigned)MAX_DESCRIPTOR_COUNT) ||
2852          !(_osfile(fh) & FOPEN))
2853     {
2854         /* out of range -- return error */
2855         errno = EBADF;
2856         _doserrno = 0;  /* not o.s. error */
2857         return -1;
2858     }
2859
2860     /*
2861      * If lockinitflag is FALSE, assume fd is device
2862      * lockinitflag is set to TRUE by open.
2863      */
2864     if (_pioinfo(fh)->lockinitflag)
2865         EnterCriticalSection(&(_pioinfo(fh)->lock));  /* lock file */
2866
2867     bytes_read = 0;                 /* nothing read yet */
2868     buffer = (char*)buf;
2869
2870     if (cnt == 0 || (_osfile(fh) & FEOFLAG)) {
2871         /* nothing to read or at EOF, so return 0 read */
2872         goto functionexit;
2873     }
2874
2875     if ((_osfile(fh) & (FPIPE|FDEV)) && _pipech(fh) != LF) {
2876         /* a pipe/device and pipe lookahead non-empty: read the lookahead
2877          * char */
2878         *buffer++ = _pipech(fh);
2879         ++bytes_read;
2880         --cnt;
2881         _pipech(fh) = LF;           /* mark as empty */
2882     }
2883
2884     /* read the data */
2885
2886     if (!ReadFile((HANDLE)_osfhnd(fh), buffer, cnt, (LPDWORD)&os_read, NULL))
2887     {
2888         /* ReadFile has reported an error. recognize two special cases.
2889          *
2890          *      1. map ERROR_ACCESS_DENIED to EBADF
2891          *
2892          *      2. just return 0 if ERROR_BROKEN_PIPE has occurred. it
2893          *         means the handle is a read-handle on a pipe for which
2894          *         all write-handles have been closed and all data has been
2895          *         read. */
2896
2897         if ((dosretval = GetLastError()) == ERROR_ACCESS_DENIED) {
2898             /* wrong read/write mode should return EBADF, not EACCES */
2899             errno = EBADF;
2900             _doserrno = dosretval;
2901             bytes_read = -1;
2902             goto functionexit;
2903         }
2904         else if (dosretval == ERROR_BROKEN_PIPE) {
2905             bytes_read = 0;
2906             goto functionexit;
2907         }
2908         else {
2909             bytes_read = -1;
2910             goto functionexit;
2911         }
2912     }
2913
2914     bytes_read += os_read;          /* update bytes read */
2915
2916     if (_osfile(fh) & FTEXT) {
2917         /* now must translate CR-LFs to LFs in the buffer */
2918
2919         /* set CRLF flag to indicate LF at beginning of buffer */
2920         /* if ((os_read != 0) && (*(char *)buf == LF))   */
2921         /*    _osfile(fh) |= FCRLF;                      */
2922         /* else                                          */
2923         /*    _osfile(fh) &= ~FCRLF;                     */
2924
2925         _osfile(fh) &= ~FCRLF;
2926
2927         /* convert chars in the buffer: p is src, q is dest */
2928         p = q = (char*)buf;
2929         while (p < (char *)buf + bytes_read) {
2930             if (*p == CTRLZ) {
2931                 /* if fh is not a device, set ctrl-z flag */
2932                 if (!(_osfile(fh) & FDEV))
2933                     _osfile(fh) |= FEOFLAG;
2934                 break;              /* stop translating */
2935             }
2936             else if (*p != CR)
2937                 *q++ = *p++;
2938             else {
2939                 /* *p is CR, so must check next char for LF */
2940                 if (p < (char *)buf + bytes_read - 1) {
2941                     if (*(p+1) == LF) {
2942                         p += 2;
2943                         *q++ = LF;  /* convert CR-LF to LF */
2944                     }
2945                     else
2946                         *q++ = *p++;    /* store char normally */
2947                 }
2948                 else {
2949                     /* This is the hard part.  We found a CR at end of
2950                        buffer.  We must peek ahead to see if next char
2951                        is an LF. */
2952                     ++p;
2953
2954                     dosretval = 0;
2955                     if (!ReadFile((HANDLE)_osfhnd(fh), &peekchr, 1,
2956                                     (LPDWORD)&os_read, NULL))
2957                         dosretval = GetLastError();
2958
2959                     if (dosretval != 0 || os_read == 0) {
2960                         /* couldn't read ahead, store CR */
2961                         *q++ = CR;
2962                     }
2963                     else {
2964                         /* peekchr now has the extra character -- we now
2965                            have several possibilities:
2966                            1. disk file and char is not LF; just seek back
2967                               and copy CR
2968                            2. disk file and char is LF; store LF, don't seek back
2969                            3. pipe/device and char is LF; store LF.
2970                            4. pipe/device and char isn't LF, store CR and
2971                               put char in pipe lookahead buffer. */
2972                         if (_osfile(fh) & (FDEV|FPIPE)) {
2973                             /* non-seekable device */
2974                             if (peekchr == LF)
2975                                 *q++ = LF;
2976                             else {
2977                                 *q++ = CR;
2978                                 _pipech(fh) = peekchr;
2979                             }
2980                         }
2981                         else {
2982                             /* disk file */
2983                             if (peekchr == LF) {
2984                                 /* nothing read yet; must make some
2985                                    progress */
2986                                 *q++ = LF;
2987                                 /* turn on this flag for tell routine */
2988                                 _osfile(fh) |= FCRLF;
2989                             }
2990                             else {
2991                                 HANDLE osHandle;        /* o.s. handle value */
2992                                 /* seek back */
2993                                 if ((osHandle = (HANDLE)_get_osfhandle(fh)) != (HANDLE)-1)
2994                                 {
2995                                     if ((filepos = SetFilePointer(osHandle, -1, NULL, FILE_CURRENT)) == -1)
2996                                         dosretval = GetLastError();
2997                                 }
2998                                 if (peekchr != LF)
2999                                     *q++ = CR;
3000                             }
3001                         }
3002                     }
3003                 }
3004             }
3005         }
3006
3007         /* we now change bytes_read to reflect the true number of chars
3008            in the buffer */
3009         bytes_read = q - (char *)buf;
3010     }
3011
3012 functionexit:   
3013     if (_pioinfo(fh)->lockinitflag)
3014         LeaveCriticalSection(&(_pioinfo(fh)->lock));    /* unlock file */
3015
3016     return bytes_read;
3017 }
3018
3019 #endif  /* PERL_MSVCRT_READFIX */
3020
3021 DllExport int
3022 win32_read(int fd, void *buf, unsigned int cnt)
3023 {
3024 #ifdef PERL_MSVCRT_READFIX
3025     return _fixed_read(fd, buf, cnt);
3026 #else
3027     return read(fd, buf, cnt);
3028 #endif
3029 }
3030
3031 DllExport int
3032 win32_write(int fd, const void *buf, unsigned int cnt)
3033 {
3034     return write(fd, buf, cnt);
3035 }
3036
3037 DllExport int
3038 win32_mkdir(const char *dir, int mode)
3039 {
3040     dTHX;
3041     if (USING_WIDE()) {
3042         WCHAR wBuffer[MAX_PATH+1];
3043         A2WHELPER(dir, wBuffer, sizeof(wBuffer));
3044         return _wmkdir(PerlDir_mapW(wBuffer));
3045     }
3046     return mkdir(PerlDir_mapA(dir)); /* just ignore mode */
3047 }
3048
3049 DllExport int
3050 win32_rmdir(const char *dir)
3051 {
3052     dTHX;
3053     if (USING_WIDE()) {
3054         WCHAR wBuffer[MAX_PATH+1];
3055         A2WHELPER(dir, wBuffer, sizeof(wBuffer));
3056         return _wrmdir(PerlDir_mapW(wBuffer));
3057     }
3058     return rmdir(PerlDir_mapA(dir));
3059 }
3060
3061 DllExport int
3062 win32_chdir(const char *dir)
3063 {
3064     dTHX;
3065     if (!dir) {
3066         errno = ENOENT;
3067         return -1;
3068     }
3069     if (USING_WIDE()) {
3070         WCHAR wBuffer[MAX_PATH+1];
3071         A2WHELPER(dir, wBuffer, sizeof(wBuffer));
3072         return _wchdir(wBuffer);
3073     }
3074     return chdir(dir);
3075 }
3076
3077 DllExport  int
3078 win32_access(const char *path, int mode)
3079 {
3080     dTHX;
3081     if (USING_WIDE()) {
3082         WCHAR wBuffer[MAX_PATH+1];
3083         A2WHELPER(path, wBuffer, sizeof(wBuffer));
3084         return _waccess(PerlDir_mapW(wBuffer), mode);
3085     }
3086     return access(PerlDir_mapA(path), mode);
3087 }
3088
3089 DllExport  int
3090 win32_chmod(const char *path, int mode)
3091 {
3092     dTHX;
3093     if (USING_WIDE()) {
3094         WCHAR wBuffer[MAX_PATH+1];
3095         A2WHELPER(path, wBuffer, sizeof(wBuffer));
3096         return _wchmod(PerlDir_mapW(wBuffer), mode);
3097     }
3098     return chmod(PerlDir_mapA(path), mode);
3099 }
3100
3101
3102 static char *
3103 create_command_line(char *cname, STRLEN clen, const char * const *args)
3104 {
3105     dTHX;
3106     int index, argc;
3107     char *cmd, *ptr;
3108     const char *arg;
3109     STRLEN len = 0;
3110     bool bat_file = FALSE;
3111     bool cmd_shell = FALSE;
3112     bool dumb_shell = FALSE;
3113     bool extra_quotes = FALSE;
3114     bool quote_next = FALSE;
3115
3116     if (!cname)
3117         cname = (char*)args[0];
3118
3119     /* The NT cmd.exe shell has the following peculiarity that needs to be
3120      * worked around.  It strips a leading and trailing dquote when any
3121      * of the following is true:
3122      *    1. the /S switch was used
3123      *    2. there are more than two dquotes
3124      *    3. there is a special character from this set: &<>()@^|
3125      *    4. no whitespace characters within the two dquotes
3126      *    5. string between two dquotes isn't an executable file
3127      * To work around this, we always add a leading and trailing dquote
3128      * to the string, if the first argument is either "cmd.exe" or "cmd",
3129      * and there were at least two or more arguments passed to cmd.exe
3130      * (not including switches).
3131      * XXX the above rules (from "cmd /?") don't seem to be applied
3132      * always, making for the convolutions below :-(
3133      */
3134     if (cname) {
3135         if (!clen)
3136             clen = strlen(cname);
3137
3138         if (clen > 4
3139             && (stricmp(&cname[clen-4], ".bat") == 0
3140                 || (IsWinNT() && stricmp(&cname[clen-4], ".cmd") == 0)))
3141         {
3142             bat_file = TRUE;
3143             len += 3;
3144         }
3145         else {
3146             char *exe = strrchr(cname, '/');
3147             char *exe2 = strrchr(cname, '\\');
3148             if (exe2 > exe)
3149                 exe = exe2;
3150             if (exe)
3151                 ++exe;
3152             else
3153                 exe = cname;
3154             if (stricmp(exe, "cmd.exe") == 0 || stricmp(exe, "cmd") == 0) {
3155                 cmd_shell = TRUE;
3156                 len += 3;
3157             }
3158             else if (stricmp(exe, "command.com") == 0
3159                      || stricmp(exe, "command") == 0)
3160             {
3161                 dumb_shell = TRUE;
3162             }
3163         }
3164     }
3165
3166     DEBUG_p(PerlIO_printf(Perl_debug_log, "Args "));
3167     for (index = 0; (arg = (char*)args[index]) != NULL; ++index) {
3168         STRLEN curlen = strlen(arg);
3169         if (!(arg[0] == '"' && arg[curlen-1] == '"'))
3170             len += 2;   /* assume quoting needed (worst case) */
3171         len += curlen + 1;
3172         DEBUG_p(PerlIO_printf(Perl_debug_log, "[%s]",arg));
3173     }
3174     DEBUG_p(PerlIO_printf(Perl_debug_log, "\n"));
3175
3176     argc = index;
3177     New(1310, cmd, len, char);
3178     ptr = cmd;
3179
3180     if (bat_file) {
3181         *ptr++ = '"';
3182         extra_quotes = TRUE;
3183     }
3184
3185     for (index = 0; (arg = (char*)args[index]) != NULL; ++index) {
3186         bool do_quote = 0;
3187         STRLEN curlen = strlen(arg);
3188
3189         /* we want to protect empty arguments and ones with spaces with
3190          * dquotes, but only if they aren't already there */
3191         if (!dumb_shell) {
3192             if (!curlen) {
3193                 do_quote = 1;
3194             }
3195             else if (quote_next) {
3196                 /* see if it really is multiple arguments pretending to
3197                  * be one and force a set of quotes around it */
3198                 if (*find_next_space(arg))
3199                     do_quote = 1;
3200             }
3201             else if (!(arg[0] == '"' && curlen > 1 && arg[curlen-1] == '"')) {
3202                 STRLEN i = 0;
3203                 while (i < curlen) {
3204                     if (isSPACE(arg[i])) {
3205                         do_quote = 1;
3206                     }
3207                     else if (arg[i] == '"') {
3208                         do_quote = 0;
3209                         break;
3210                     }
3211                     i++;
3212                 }
3213             }
3214         }
3215
3216         if (do_quote)
3217             *ptr++ = '"';
3218
3219         strcpy(ptr, arg);
3220         ptr += curlen;
3221
3222         if (do_quote)
3223             *ptr++ = '"';
3224
3225         if (args[index+1])
3226             *ptr++ = ' ';
3227
3228         if (!extra_quotes
3229             && cmd_shell
3230             && (stricmp(arg, "/x/c") == 0 || stricmp(arg, "/c") == 0))
3231         {
3232             /* is there a next argument? */
3233             if (args[index+1]) {
3234                 /* are there two or more next arguments? */
3235                 if (args[index+2]) {
3236                     *ptr++ = '"';
3237                     extra_quotes = TRUE;
3238                 }
3239                 else {
3240                     /* single argument, force quoting if it has spaces */
3241                     quote_next = TRUE;
3242                 }
3243             }
3244         }
3245     }
3246
3247     if (extra_quotes)
3248         *ptr++ = '"';
3249
3250     *ptr = '\0';
3251
3252     return cmd;
3253 }
3254
3255 static char *
3256 qualified_path(const char *cmd)
3257 {
3258     dTHX;
3259     char *pathstr;
3260     char *fullcmd, *curfullcmd;
3261     STRLEN cmdlen = 0;
3262     int has_slash = 0;
3263
3264     if (!cmd)
3265         return Nullch;
3266     fullcmd = (char*)cmd;
3267     while (*fullcmd) {
3268         if (*fullcmd == '/' || *fullcmd == '\\')
3269             has_slash++;
3270         fullcmd++;
3271         cmdlen++;
3272     }
3273
3274     /* look in PATH */
3275     pathstr = PerlEnv_getenv("PATH");
3276     New(0, fullcmd, MAX_PATH+1, char);
3277     curfullcmd = fullcmd;
3278
3279     while (1) {
3280         DWORD res;
3281
3282         /* start by appending the name to the current prefix */
3283         strcpy(curfullcmd, cmd);
3284         curfullcmd += cmdlen;
3285
3286         /* if it doesn't end with '.', or has no extension, try adding
3287          * a trailing .exe first */
3288         if (cmd[cmdlen-1] != '.'
3289             && (cmdlen < 4 || cmd[cmdlen-4] != '.'))
3290         {
3291             strcpy(curfullcmd, ".exe");
3292             res = GetFileAttributes(fullcmd);
3293             if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
3294                 return fullcmd;
3295             *curfullcmd = '\0';
3296         }
3297
3298         /* that failed, try the bare name */
3299         res = GetFileAttributes(fullcmd);
3300         if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
3301             return fullcmd;
3302
3303         /* quit if no other path exists, or if cmd already has path */
3304         if (!pathstr || !*pathstr || has_slash)
3305             break;
3306
3307         /* skip leading semis */
3308         while (*pathstr == ';')
3309             pathstr++;
3310
3311         /* build a new prefix from scratch */
3312         curfullcmd = fullcmd;
3313         while (*pathstr && *pathstr != ';') {
3314             if (*pathstr == '"') {      /* foo;"baz;etc";bar */
3315                 pathstr++;              /* skip initial '"' */
3316                 while (*pathstr && *pathstr != '"') {
3317                     if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
3318                         *curfullcmd++ = *pathstr;
3319                     pathstr++;
3320                 }
3321                 if (*pathstr)
3322                     pathstr++;          /* skip trailing '"' */
3323             }
3324             else {
3325                 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
3326                     *curfullcmd++ = *pathstr;
3327                 pathstr++;
3328             }
3329         }
3330         if (*pathstr)
3331             pathstr++;                  /* skip trailing semi */
3332         if (curfullcmd > fullcmd        /* append a dir separator */
3333             && curfullcmd[-1] != '/' && curfullcmd[-1] != '\\')
3334         {
3335             *curfullcmd++ = '\\';
3336         }
3337     }
3338 GIVE_UP:
3339     Safefree(fullcmd);
3340     return Nullch;
3341 }
3342
3343 /* The following are just place holders.
3344  * Some hosts may provide and environment that the OS is
3345  * not tracking, therefore, these host must provide that
3346  * environment and the current directory to CreateProcess
3347  */
3348
3349 DllExport void*
3350 win32_get_childenv(void)
3351 {
3352     return NULL;
3353 }
3354
3355 DllExport void
3356 win32_free_childenv(void* d)
3357 {
3358 }
3359
3360 DllExport void
3361 win32_clearenv(void)
3362 {
3363     char *envv = GetEnvironmentStrings();
3364     char *cur = envv;
3365     STRLEN len;
3366     while (*cur) {
3367         char *end = strchr(cur,'=');
3368         if (end && end != cur) {
3369             *end = '\0';
3370             SetEnvironmentVariable(cur, NULL);
3371             *end = '=';
3372             cur = end + strlen(end+1)+2;
3373         }
3374         else if ((len = strlen(cur)))
3375             cur += len+1;
3376     }
3377     FreeEnvironmentStrings(envv);
3378 }
3379
3380 DllExport char*
3381 win32_get_childdir(void)
3382 {
3383     dTHX;
3384     char* ptr;
3385     char szfilename[(MAX_PATH+1)*2];
3386     if (USING_WIDE()) {
3387         WCHAR wfilename[MAX_PATH+1];
3388         GetCurrentDirectoryW(MAX_PATH+1, wfilename);
3389         W2AHELPER(wfilename, szfilename, sizeof(szfilename));
3390     }
3391     else {
3392         GetCurrentDirectoryA(MAX_PATH+1, szfilename);
3393     }
3394
3395     New(0, ptr, strlen(szfilename)+1, char);
3396     strcpy(ptr, szfilename);
3397     return ptr;
3398 }
3399
3400 DllExport void
3401 win32_free_childdir(char* d)
3402 {
3403     dTHX;
3404     Safefree(d);
3405 }
3406
3407
3408 /* XXX this needs to be made more compatible with the spawnvp()
3409  * provided by the various RTLs.  In particular, searching for
3410  * *.{com,bat,cmd} files (as done by the RTLs) is unimplemented.
3411  * This doesn't significantly affect perl itself, because we
3412  * always invoke things using PERL5SHELL if a direct attempt to
3413  * spawn the executable fails.
3414  * 
3415  * XXX splitting and rejoining the commandline between do_aspawn()
3416  * and win32_spawnvp() could also be avoided.
3417  */
3418
3419 DllExport int
3420 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
3421 {
3422 #ifdef USE_RTL_SPAWNVP
3423     return spawnvp(mode, cmdname, (char * const *)argv);
3424 #else
3425     dTHX;
3426     int ret;
3427     void* env;
3428     char* dir;
3429     child_IO_table tbl;
3430     STARTUPINFO StartupInfo;
3431     PROCESS_INFORMATION ProcessInformation;
3432     DWORD create = 0;
3433     char *cmd;
3434     char *fullcmd = Nullch;
3435     char *cname = (char *)cmdname;
3436     STRLEN clen = 0;
3437
3438     if (cname) {
3439         clen = strlen(cname);
3440         /* if command name contains dquotes, must remove them */
3441         if (strchr(cname, '"')) {
3442             cmd = cname;
3443             New(0,cname,clen+1,char);
3444             clen = 0;
3445             while (*cmd) {
3446                 if (*cmd != '"') {
3447                     cname[clen] = *cmd;
3448                     ++clen;
3449                 }
3450                 ++cmd;
3451             }
3452             cname[clen] = '\0';
3453         }
3454     }
3455
3456     cmd = create_command_line(cname, clen, argv);
3457
3458     env = PerlEnv_get_childenv();
3459     dir = PerlEnv_get_childdir();
3460
3461     switch(mode) {
3462     case P_NOWAIT:      /* asynch + remember result */
3463         if (w32_num_children >= MAXIMUM_WAIT_OBJECTS) {
3464             errno = EAGAIN;
3465             ret = -1;
3466             goto RETVAL;
3467         }
3468         /* FALL THROUGH */
3469     case P_WAIT:        /* synchronous execution */
3470         break;
3471     default:            /* invalid mode */
3472         errno = EINVAL;
3473         ret = -1;
3474         goto RETVAL;
3475     }
3476     memset(&StartupInfo,0,sizeof(StartupInfo));
3477     StartupInfo.cb = sizeof(StartupInfo);
3478     memset(&tbl,0,sizeof(tbl));
3479     PerlEnv_get_child_IO(&tbl);
3480     StartupInfo.dwFlags         = tbl.dwFlags;
3481     StartupInfo.dwX             = tbl.dwX; 
3482     StartupInfo.dwY             = tbl.dwY; 
3483     StartupInfo.dwXSize         = tbl.dwXSize; 
3484     StartupInfo.dwYSize         = tbl.dwYSize; 
3485     StartupInfo.dwXCountChars   = tbl.dwXCountChars; 
3486     StartupInfo.dwYCountChars   = tbl.dwYCountChars; 
3487     StartupInfo.dwFillAttribute = tbl.dwFillAttribute; 
3488     StartupInfo.wShowWindow     = tbl.wShowWindow; 
3489     StartupInfo.hStdInput       = tbl.childStdIn;
3490     StartupInfo.hStdOutput      = tbl.childStdOut;
3491     StartupInfo.hStdError       = tbl.childStdErr;
3492     if (StartupInfo.hStdInput != INVALID_HANDLE_VALUE &&
3493         StartupInfo.hStdOutput != INVALID_HANDLE_VALUE &&
3494         StartupInfo.hStdError != INVALID_HANDLE_VALUE)
3495     {
3496         StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
3497     }
3498     else {
3499         create |= CREATE_NEW_CONSOLE;
3500     }
3501
3502     DEBUG_p(PerlIO_printf(Perl_debug_log, "Spawning [%s] with [%s]\n",
3503                           cname,cmd));
3504 RETRY:
3505     if (!CreateProcess(cname,           /* search PATH to find executable */
3506                        cmd,             /* executable, and its arguments */
3507                        NULL,            /* process attributes */
3508                        NULL,            /* thread attributes */
3509                        TRUE,            /* inherit handles */
3510                        create,          /* creation flags */
3511                        (LPVOID)env,     /* inherit environment */
3512                        dir,             /* inherit cwd */
3513                        &StartupInfo,
3514                        &ProcessInformation))
3515     {
3516         /* initial NULL argument to CreateProcess() does a PATH
3517          * search, but it always first looks in the directory
3518          * where the current process was started, which behavior
3519          * is undesirable for backward compatibility.  So we
3520          * jump through our own hoops by picking out the path
3521          * we really want it to use. */
3522         if (!fullcmd) {
3523             fullcmd = qualified_path(cname);
3524             if (fullcmd) {
3525                 if (cname != cmdname)
3526                     Safefree(cname);
3527                 cname = fullcmd;
3528                 DEBUG_p(PerlIO_printf(Perl_debug_log,
3529                                       "Retrying [%s] with same args\n",
3530                                       cname));
3531                 goto RETRY;
3532             }
3533         }
3534         errno = ENOENT;
3535         ret = -1;
3536         goto RETVAL;
3537     }
3538
3539     if (mode == P_NOWAIT) {
3540         /* asynchronous spawn -- store handle, return PID */
3541         ret = (int)ProcessInformation.dwProcessId;
3542         if (IsWin95() && ret < 0)
3543             ret = -ret;
3544
3545         w32_child_handles[w32_num_children] = ProcessInformation.hProcess;
3546         w32_child_pids[w32_num_children] = (DWORD)ret;
3547         ++w32_num_children;
3548     }
3549     else  {
3550         DWORD status;
3551         WaitForSingleObject(ProcessInformation.hProcess, INFINITE);
3552         GetExitCodeProcess(ProcessInformation.hProcess, &status);
3553         ret = (int)status;
3554         CloseHandle(ProcessInformation.hProcess);
3555     }
3556
3557     CloseHandle(ProcessInformation.hThread);
3558
3559 RETVAL:
3560     PerlEnv_free_childenv(env);
3561     PerlEnv_free_childdir(dir);
3562     Safefree(cmd);
3563     if (cname != cmdname)
3564         Safefree(cname);
3565     return ret;
3566 #endif
3567 }
3568
3569 DllExport int
3570 win32_execv(const char *cmdname, const char *const *argv)
3571 {
3572 #ifdef USE_ITHREADS
3573     dTHX;
3574     /* if this is a pseudo-forked child, we just want to spawn
3575      * the new program, and return */
3576     if (w32_pseudo_id)
3577         return spawnv(P_WAIT, cmdname, (char *const *)argv);
3578 #endif
3579     return execv(cmdname, (char *const *)argv);
3580 }
3581
3582 DllExport int
3583 win32_execvp(const char *cmdname, const char *const *argv)
3584 {
3585 #ifdef USE_ITHREADS
3586     dTHX;
3587     /* if this is a pseudo-forked child, we just want to spawn
3588      * the new program, and return */
3589     if (w32_pseudo_id) {
3590         int status = win32_spawnvp(P_WAIT, cmdname, (char *const *)argv);
3591         if (status != -1) {
3592             my_exit(status);
3593             return 0;
3594         }
3595         else
3596             return status;
3597     }
3598 #endif
3599     return execvp(cmdname, (char *const *)argv);
3600 }
3601
3602 DllExport void
3603 win32_perror(const char *str)
3604 {
3605     perror(str);
3606 }
3607
3608 DllExport void
3609 win32_setbuf(FILE *pf, char *buf)
3610 {
3611     setbuf(pf, buf);
3612 }
3613
3614 DllExport int
3615 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
3616 {
3617     return setvbuf(pf, buf, type, size);
3618 }
3619
3620 DllExport int
3621 win32_flushall(void)
3622 {
3623     return flushall();
3624 }
3625
3626 DllExport int
3627 win32_fcloseall(void)
3628 {
3629     return fcloseall();
3630 }
3631
3632 DllExport char*
3633 win32_fgets(char *s, int n, FILE *pf)
3634 {
3635     return fgets(s, n, pf);
3636 }
3637
3638 DllExport char*
3639 win32_gets(char *s)
3640 {
3641     return gets(s);
3642 }
3643
3644 DllExport int
3645 win32_fgetc(FILE *pf)
3646 {
3647     return fgetc(pf);
3648 }
3649
3650 DllExport int
3651 win32_putc(int c, FILE *pf)
3652 {
3653     return putc(c,pf);
3654 }
3655
3656 DllExport int
3657 win32_puts(const char *s)
3658 {
3659     return puts(s);
3660 }
3661
3662 DllExport int
3663 win32_getchar(void)
3664 {
3665     return getchar();
3666 }
3667
3668 DllExport int
3669 win32_putchar(int c)
3670 {
3671     return putchar(c);
3672 }
3673
3674 #ifdef MYMALLOC
3675
3676 #ifndef USE_PERL_SBRK
3677
3678 static char *committed = NULL;          /* XXX threadead */
3679 static char *base      = NULL;          /* XXX threadead */
3680 static char *reserved  = NULL;          /* XXX threadead */
3681 static char *brk       = NULL;          /* XXX threadead */
3682 static DWORD pagesize  = 0;             /* XXX threadead */
3683 static DWORD allocsize = 0;             /* XXX threadead */
3684
3685 void *
3686 sbrk(int need)
3687 {
3688  void *result;
3689  if (!pagesize)
3690   {SYSTEM_INFO info;
3691    GetSystemInfo(&info);
3692    /* Pretend page size is larger so we don't perpetually
3693     * call the OS to commit just one page ...
3694     */
3695    pagesize = info.dwPageSize << 3;
3696    allocsize = info.dwAllocationGranularity;
3697   }
3698  /* This scheme fails eventually if request for contiguous
3699   * block is denied so reserve big blocks - this is only 
3700   * address space not memory ...
3701   */
3702  if (brk+need >= reserved)
3703   {
3704    DWORD size = 64*1024*1024;
3705    char *addr;
3706    if (committed && reserved && committed < reserved)
3707     {
3708      /* Commit last of previous chunk cannot span allocations */
3709      addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
3710      if (addr)
3711       committed = reserved;
3712     }
3713    /* Reserve some (more) space 
3714     * Note this is a little sneaky, 1st call passes NULL as reserved
3715     * so lets system choose where we start, subsequent calls pass
3716     * the old end address so ask for a contiguous block
3717     */
3718    addr  = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
3719    if (addr)
3720     {
3721      reserved = addr+size;
3722      if (!base)
3723       base = addr;
3724      if (!committed)
3725       committed = base;
3726      if (!brk)
3727       brk = committed;
3728     }
3729    else
3730     {
3731      return (void *) -1;
3732     }
3733   }
3734  result = brk;
3735  brk += need;
3736  if (brk > committed)
3737   {
3738    DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
3739    char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
3740    if (addr)
3741     {
3742      committed += size;
3743     }
3744    else
3745     return (void *) -1;
3746   }
3747  return result;
3748 }
3749
3750 #endif
3751 #endif
3752
3753 DllExport void*
3754 win32_malloc(size_t size)
3755 {
3756     return malloc(size);
3757 }
3758
3759 DllExport void*
3760 win32_calloc(size_t numitems, size_t size)
3761 {
3762     return calloc(numitems,size);
3763 }
3764
3765 DllExport void*
3766 win32_realloc(void *block, size_t size)
3767 {
3768     return realloc(block,size);
3769 }
3770
3771 DllExport void
3772 win32_free(void *block)
3773 {
3774     free(block);
3775 }
3776
3777
3778 int
3779 win32_open_osfhandle(long handle, int flags)
3780 {
3781 #ifdef USE_FIXED_OSFHANDLE
3782     if (IsWin95())
3783         return my_open_osfhandle(handle, flags);
3784 #endif
3785     return _open_osfhandle(handle, flags);
3786 }
3787
3788 long
3789 win32_get_osfhandle(int fd)
3790 {
3791     return _get_osfhandle(fd);
3792 }
3793
3794 DllExport void*
3795 win32_dynaload(const char* filename)
3796 {
3797     dTHX;
3798     HMODULE hModule;
3799     char buf[MAX_PATH+1];
3800     char *first;
3801
3802     /* LoadLibrary() doesn't recognize forward slashes correctly,
3803      * so turn 'em back. */
3804     first = strchr(filename, '/');
3805     if (first) {
3806         STRLEN len = strlen(filename);
3807         if (len <= MAX_PATH) {
3808             strcpy(buf, filename);
3809             filename = &buf[first - filename];
3810             while (*filename) {
3811                 if (*filename == '/')
3812                     *(char*)filename = '\\';
3813                 ++filename;
3814             }
3815             filename = buf;
3816         }
3817     }
3818     if (USING_WIDE()) {
3819         WCHAR wfilename[MAX_PATH+1];
3820         A2WHELPER(filename, wfilename, sizeof(wfilename));
3821         hModule = LoadLibraryExW(PerlDir_mapW(wfilename), NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
3822     }
3823     else {
3824         hModule = LoadLibraryExA(PerlDir_mapA(filename), NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
3825     }
3826     return hModule;
3827 }
3828
3829 /*
3830  * Extras.
3831  */
3832
3833 static
3834 XS(w32_GetCwd)
3835 {
3836     dXSARGS;
3837     /* Make the host for current directory */
3838     char* ptr = PerlEnv_get_childdir();
3839     /* 
3840      * If ptr != Nullch 
3841      *   then it worked, set PV valid, 
3842      *   else return 'undef' 
3843      */
3844     if (ptr) {
3845         SV *sv = sv_newmortal();
3846         sv_setpv(sv, ptr);
3847         PerlEnv_free_childdir(ptr);
3848
3849 #ifndef INCOMPLETE_TAINTS
3850         SvTAINTED_on(sv);
3851 #endif
3852
3853         EXTEND(SP,1);
3854         SvPOK_on(sv);
3855         ST(0) = sv;
3856         XSRETURN(1);
3857     }
3858     XSRETURN_UNDEF;
3859 }
3860
3861 static
3862 XS(w32_SetCwd)
3863 {
3864     dXSARGS;
3865     if (items != 1)
3866         Perl_croak(aTHX_ "usage: Win32::SetCurrentDirectory($cwd)");
3867     if (!PerlDir_chdir(SvPV_nolen(ST(0))))
3868         XSRETURN_YES;
3869
3870     XSRETURN_NO;
3871 }
3872
3873 static
3874 XS(w32_GetNextAvailDrive)
3875 {
3876     dXSARGS;
3877     char ix = 'C';
3878     char root[] = "_:\\";
3879
3880     EXTEND(SP,1);
3881     while (ix <= 'Z') {
3882         root[0] = ix++;
3883         if (GetDriveType(root) == 1) {
3884             root[2] = '\0';
3885             XSRETURN_PV(root);
3886         }
3887     }
3888     XSRETURN_UNDEF;
3889 }
3890
3891 static
3892 XS(w32_GetLastError)
3893 {
3894     dXSARGS;
3895     EXTEND(SP,1);
3896     XSRETURN_IV(GetLastError());
3897 }
3898
3899 static
3900 XS(w32_SetLastError)
3901 {
3902     dXSARGS;
3903     if (items != 1)
3904         Perl_croak(aTHX_ "usage: Win32::SetLastError($error)");
3905     SetLastError(SvIV(ST(0)));
3906     XSRETURN_EMPTY;
3907 }
3908
3909 static
3910 XS(w32_LoginName)
3911 {
3912     dXSARGS;
3913     char *name = w32_getlogin_buffer;
3914     DWORD size = sizeof(w32_getlogin_buffer);
3915     EXTEND(SP,1);
3916     if (GetUserName(name,&size)) {
3917         /* size includes NULL */
3918         ST(0) = sv_2mortal(newSVpvn(name,size-1));
3919         XSRETURN(1);
3920     }
3921     XSRETURN_UNDEF;
3922 }
3923
3924 static
3925 XS(w32_NodeName)
3926 {
3927     dXSARGS;
3928     char name[MAX_COMPUTERNAME_LENGTH+1];
3929     DWORD size = sizeof(name);
3930     EXTEND(SP,1);
3931     if (GetComputerName(name,&size)) {
3932         /* size does NOT include NULL :-( */
3933         ST(0) = sv_2mortal(newSVpvn(name,size));
3934         XSRETURN(1);
3935     }
3936     XSRETURN_UNDEF;
3937 }
3938
3939
3940 static
3941 XS(w32_DomainName)
3942 {
3943     dXSARGS;
3944     HINSTANCE hNetApi32 = LoadLibrary("netapi32.dll");
3945     DWORD (__stdcall *pfnNetApiBufferFree)(LPVOID Buffer);
3946     DWORD (__stdcall *pfnNetWkstaGetInfo)(LPWSTR servername, DWORD level,
3947                                           void *bufptr);
3948
3949     if (hNetApi32) {
3950         pfnNetApiBufferFree = (DWORD (__stdcall *)(void *))
3951             GetProcAddress(hNetApi32, "NetApiBufferFree");
3952         pfnNetWkstaGetInfo = (DWORD (__stdcall *)(LPWSTR, DWORD, void *))
3953             GetProcAddress(hNetApi32, "NetWkstaGetInfo");
3954     }
3955     EXTEND(SP,1);
3956     if (hNetApi32 && pfnNetWkstaGetInfo && pfnNetApiBufferFree) {
3957         /* this way is more reliable, in case user has a local account. */
3958         char dname[256];
3959         DWORD dnamelen = sizeof(dname);
3960         struct {
3961             DWORD   wki100_platform_id;
3962             LPWSTR  wki100_computername;
3963             LPWSTR  wki100_langroup;
3964             DWORD   wki100_ver_major;
3965             DWORD   wki100_ver_minor;
3966         } *pwi;
3967         /* NERR_Success *is* 0*/
3968         if (0 == pfnNetWkstaGetInfo(NULL, 100, &pwi)) {
3969             if (pwi->wki100_langroup && *(pwi->wki100_langroup)) {
3970                 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_langroup,
3971                                     -1, (LPSTR)dname, dnamelen, NULL, NULL);
3972             }
3973             else {
3974                 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_computername,
3975                                     -1, (LPSTR)dname, dnamelen, NULL, NULL);
3976             }
3977             pfnNetApiBufferFree(pwi);
3978             FreeLibrary(hNetApi32);
3979             XSRETURN_PV(dname);
3980         }
3981         FreeLibrary(hNetApi32);
3982     }
3983     else {
3984         /* Win95 doesn't have NetWksta*(), so do it the old way */
3985         char name[256];
3986         DWORD size = sizeof(name);
3987         if (hNetApi32)
3988             FreeLibrary(hNetApi32);
3989         if (GetUserName(name,&size)) {
3990             char sid[ONE_K_BUFSIZE];
3991             DWORD sidlen = sizeof(sid);
3992             char dname[256];
3993             DWORD dnamelen = sizeof(dname);
3994             SID_NAME_USE snu;
3995             if (LookupAccountName(NULL, name, (PSID)&sid, &sidlen,
3996                                   dname, &dnamelen, &snu)) {
3997                 XSRETURN_PV(dname);             /* all that for this */
3998             }
3999         }
4000     }
4001     XSRETURN_UNDEF;
4002 }
4003
4004 static
4005 XS(w32_FsType)
4006 {
4007     dXSARGS;
4008     char fsname[256];
4009     DWORD flags, filecomplen;
4010     if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
4011                          &flags, fsname, sizeof(fsname))) {
4012         if (GIMME_V == G_ARRAY) {
4013             XPUSHs(sv_2mortal(newSVpvn(fsname,strlen(fsname))));
4014             XPUSHs(sv_2mortal(newSViv(flags)));
4015             XPUSHs(sv_2mortal(newSViv(filecomplen)));
4016             PUTBACK;
4017             return;
4018         }
4019         EXTEND(SP,1);
4020         XSRETURN_PV(fsname);
4021     }
4022     XSRETURN_EMPTY;
4023 }
4024
4025 static
4026 XS(w32_GetOSVersion)
4027 {
4028     dXSARGS;
4029     OSVERSIONINFOA osver;
4030
4031     if (USING_WIDE()) {
4032         OSVERSIONINFOW osverw;
4033         char szCSDVersion[sizeof(osverw.szCSDVersion)];
4034         osverw.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
4035         if (!GetVersionExW(&osverw)) {
4036             XSRETURN_EMPTY;
4037         }
4038         W2AHELPER(osverw.szCSDVersion, szCSDVersion, sizeof(szCSDVersion));
4039         XPUSHs(newSVpvn(szCSDVersion, strlen(szCSDVersion)));
4040         osver.dwMajorVersion = osverw.dwMajorVersion;
4041         osver.dwMinorVersion = osverw.dwMinorVersion;
4042         osver.dwBuildNumber = osverw.dwBuildNumber;
4043         osver.dwPlatformId = osverw.dwPlatformId;
4044     }
4045     else {
4046         osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOA);
4047         if (!GetVersionExA(&osver)) {
4048             XSRETURN_EMPTY;
4049         }
4050         XPUSHs(newSVpvn(osver.szCSDVersion, strlen(osver.szCSDVersion)));
4051     }
4052     XPUSHs(newSViv(osver.dwMajorVersion));
4053     XPUSHs(newSViv(osver.dwMinorVersion));
4054     XPUSHs(newSViv(osver.dwBuildNumber));
4055     XPUSHs(newSViv(osver.dwPlatformId));
4056     PUTBACK;
4057 }
4058
4059 static
4060 XS(w32_IsWinNT)
4061 {
4062     dXSARGS;
4063     EXTEND(SP,1);
4064     XSRETURN_IV(IsWinNT());
4065 }
4066
4067 static
4068 XS(w32_IsWin95)
4069 {
4070     dXSARGS;
4071     EXTEND(SP,1);
4072     XSRETURN_IV(IsWin95());
4073 }
4074
4075 static
4076 XS(w32_FormatMessage)
4077 {
4078     dXSARGS;
4079     DWORD source = 0;
4080     char msgbuf[ONE_K_BUFSIZE];
4081
4082     if (items != 1)
4083         Perl_croak(aTHX_ "usage: Win32::FormatMessage($errno)");
4084
4085     if (USING_WIDE()) {
4086         WCHAR wmsgbuf[ONE_K_BUFSIZE];
4087         if (FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM,
4088                           &source, SvIV(ST(0)), 0,
4089                           wmsgbuf, ONE_K_BUFSIZE-1, NULL))
4090         {
4091             W2AHELPER(wmsgbuf, msgbuf, sizeof(msgbuf));
4092             XSRETURN_PV(msgbuf);
4093         }
4094     }
4095     else {
4096         if (FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM,
4097                           &source, SvIV(ST(0)), 0,
4098                           msgbuf, sizeof(msgbuf)-1, NULL))
4099             XSRETURN_PV(msgbuf);
4100     }
4101
4102     XSRETURN_UNDEF;
4103 }
4104
4105 static
4106 XS(w32_Spawn)
4107 {
4108     dXSARGS;
4109     char *cmd, *args;
4110     void *env;
4111     char *dir;
4112     PROCESS_INFORMATION stProcInfo;
4113     STARTUPINFO stStartInfo;
4114     BOOL bSuccess = FALSE;
4115
4116     if (items != 3)
4117         Perl_croak(aTHX_ "usage: Win32::Spawn($cmdName, $args, $PID)");
4118
4119     cmd = SvPV_nolen(ST(0));
4120     args = SvPV_nolen(ST(1));
4121
4122     env = PerlEnv_get_childenv();
4123     dir = PerlEnv_get_childdir();
4124
4125     memset(&stStartInfo, 0, sizeof(stStartInfo));   /* Clear the block */
4126     stStartInfo.cb = sizeof(stStartInfo);           /* Set the structure size */
4127     stStartInfo.dwFlags = STARTF_USESHOWWINDOW;     /* Enable wShowWindow control */
4128     stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE;   /* Start min (normal) */
4129
4130     if (CreateProcess(
4131                 cmd,                    /* Image path */
4132                 args,                   /* Arguments for command line */
4133                 NULL,                   /* Default process security */
4134                 NULL,                   /* Default thread security */
4135                 FALSE,                  /* Must be TRUE to use std handles */
4136                 NORMAL_PRIORITY_CLASS,  /* No special scheduling */
4137                 env,                    /* Inherit our environment block */
4138                 dir,                    /* Inherit our currrent directory */
4139                 &stStartInfo,           /* -> Startup info */
4140                 &stProcInfo))           /* <- Process info (if OK) */
4141     {
4142         int pid = (int)stProcInfo.dwProcessId;
4143         if (IsWin95() && pid < 0)
4144             pid = -pid;
4145         sv_setiv(ST(2), pid);
4146         CloseHandle(stProcInfo.hThread);/* library source code does this. */
4147         bSuccess = TRUE;
4148     }
4149     PerlEnv_free_childenv(env);
4150     PerlEnv_free_childdir(dir);
4151     XSRETURN_IV(bSuccess);
4152 }
4153
4154 static
4155 XS(w32_GetTickCount)
4156 {
4157     dXSARGS;
4158     DWORD msec = GetTickCount();
4159     EXTEND(SP,1);
4160     if ((IV)msec > 0)
4161         XSRETURN_IV(msec);
4162     XSRETURN_NV(msec);
4163 }
4164
4165 static
4166 XS(w32_GetShortPathName)
4167 {
4168     dXSARGS;
4169     SV *shortpath;
4170     DWORD len;
4171
4172     if (items != 1)
4173         Perl_croak(aTHX_ "usage: Win32::GetShortPathName($longPathName)");
4174
4175     shortpath = sv_mortalcopy(ST(0));
4176     SvUPGRADE(shortpath, SVt_PV);
4177     if (!SvPVX(shortpath) || !SvLEN(shortpath))
4178         XSRETURN_UNDEF;
4179
4180     /* src == target is allowed */
4181     do {
4182         len = GetShortPathName(SvPVX(shortpath),
4183                                SvPVX(shortpath),
4184                                SvLEN(shortpath));
4185     } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
4186     if (len) {
4187         SvCUR_set(shortpath,len);
4188         ST(0) = shortpath;
4189         XSRETURN(1);
4190     }
4191     XSRETURN_UNDEF;
4192 }
4193
4194 static
4195 XS(w32_GetFullPathName)
4196 {
4197     dXSARGS;
4198     SV *filename;
4199     SV *fullpath;
4200     char *filepart;
4201     DWORD len;
4202
4203     if (items != 1)
4204         Perl_croak(aTHX_ "usage: Win32::GetFullPathName($filename)");
4205
4206     filename = ST(0);
4207     fullpath = sv_mortalcopy(filename);
4208     SvUPGRADE(fullpath, SVt_PV);
4209     if (!SvPVX(fullpath) || !SvLEN(fullpath))
4210         XSRETURN_UNDEF;
4211
4212     do {
4213         len = GetFullPathName(SvPVX(filename),
4214                               SvLEN(fullpath),
4215                               SvPVX(fullpath),
4216                               &filepart);
4217     } while (len >= SvLEN(fullpath) && sv_grow(fullpath,len+1));
4218     if (len) {
4219         if (GIMME_V == G_ARRAY) {
4220             EXTEND(SP,1);
4221             XST_mPV(1,filepart);
4222             len = filepart - SvPVX(fullpath);
4223             items = 2;
4224         }
4225         SvCUR_set(fullpath,len);
4226         ST(0) = fullpath;
4227         XSRETURN(items);
4228     }
4229     XSRETURN_EMPTY;
4230 }
4231
4232 static
4233 XS(w32_GetLongPathName)
4234 {
4235     dXSARGS;
4236     SV *path;
4237     char tmpbuf[MAX_PATH+1];
4238     char *pathstr;
4239     STRLEN len;
4240
4241     if (items != 1)
4242         Perl_croak(aTHX_ "usage: Win32::GetLongPathName($pathname)");
4243
4244     path = ST(0);
4245     pathstr = SvPV(path,len);
4246     strcpy(tmpbuf, pathstr);
4247     pathstr = win32_longpath(tmpbuf);
4248     if (pathstr) {
4249         ST(0) = sv_2mortal(newSVpvn(pathstr, strlen(pathstr)));
4250         XSRETURN(1);
4251     }
4252     XSRETURN_EMPTY;
4253 }
4254
4255 static
4256 XS(w32_Sleep)
4257 {
4258     dXSARGS;
4259     if (items != 1)
4260         Perl_croak(aTHX_ "usage: Win32::Sleep($milliseconds)");
4261     Sleep(SvIV(ST(0)));
4262     XSRETURN_YES;
4263 }
4264
4265 static
4266 XS(w32_CopyFile)
4267 {
4268     dXSARGS;
4269     BOOL bResult;
4270     if (items != 3)
4271         Perl_croak(aTHX_ "usage: Win32::CopyFile($from, $to, $overwrite)");
4272     if (USING_WIDE()) {
4273         WCHAR wSourceFile[MAX_PATH+1];
4274         WCHAR wDestFile[MAX_PATH+1];
4275         A2WHELPER(SvPV_nolen(ST(0)), wSourceFile, sizeof(wSourceFile));
4276         wcscpy(wSourceFile, PerlDir_mapW(wSourceFile));
4277         A2WHELPER(SvPV_nolen(ST(1)), wDestFile, sizeof(wDestFile));
4278         bResult = CopyFileW(wSourceFile, PerlDir_mapW(wDestFile), !SvTRUE(ST(2)));
4279     }
4280     else {
4281         char szSourceFile[MAX_PATH+1];
4282         strcpy(szSourceFile, PerlDir_mapA(SvPV_nolen(ST(0))));
4283         bResult = CopyFileA(szSourceFile, PerlDir_mapA(SvPV_nolen(ST(1))), !SvTRUE(ST(2)));
4284     }
4285
4286     if (bResult)
4287         XSRETURN_YES;
4288     XSRETURN_NO;
4289 }
4290
4291 void
4292 Perl_init_os_extras(void)
4293 {
4294     dTHX;
4295     char *file = __FILE__;
4296     dXSUB_SYS;
4297
4298     /* these names are Activeware compatible */
4299     newXS("Win32::GetCwd", w32_GetCwd, file);
4300     newXS("Win32::SetCwd", w32_SetCwd, file);
4301     newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
4302     newXS("Win32::GetLastError", w32_GetLastError, file);
4303     newXS("Win32::SetLastError", w32_SetLastError, file);
4304     newXS("Win32::LoginName", w32_LoginName, file);
4305     newXS("Win32::NodeName", w32_NodeName, file);
4306     newXS("Win32::DomainName", w32_DomainName, file);
4307     newXS("Win32::FsType", w32_FsType, file);
4308     newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
4309     newXS("Win32::IsWinNT", w32_IsWinNT, file);
4310     newXS("Win32::IsWin95", w32_IsWin95, file);
4311     newXS("Win32::FormatMessage", w32_FormatMessage, file);
4312     newXS("Win32::Spawn", w32_Spawn, file);
4313     newXS("Win32::GetTickCount", w32_GetTickCount, file);
4314     newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
4315     newXS("Win32::GetFullPathName", w32_GetFullPathName, file);
4316     newXS("Win32::GetLongPathName", w32_GetLongPathName, file);
4317     newXS("Win32::CopyFile", w32_CopyFile, file);
4318     newXS("Win32::Sleep", w32_Sleep, file);
4319
4320     /* XXX Bloat Alert! The following Activeware preloads really
4321      * ought to be part of Win32::Sys::*, so they're not included
4322      * here.
4323      */
4324     /* LookupAccountName
4325      * LookupAccountSID
4326      * InitiateSystemShutdown
4327      * AbortSystemShutdown
4328      * ExpandEnvrironmentStrings
4329      */
4330 }
4331
4332 void
4333 Perl_win32_init(int *argcp, char ***argvp)
4334 {
4335     /* Disable floating point errors, Perl will trap the ones we
4336      * care about.  VC++ RTL defaults to switching these off
4337      * already, but the Borland RTL doesn't.  Since we don't
4338      * want to be at the vendor's whim on the default, we set
4339      * it explicitly here.
4340      */
4341 #if !defined(_ALPHA_) && !defined(__GNUC__)
4342     _control87(MCW_EM, MCW_EM);
4343 #endif
4344     MALLOC_INIT;
4345 }
4346
4347 void
4348 win32_get_child_IO(child_IO_table* ptbl)
4349 {
4350     ptbl->childStdIn    = GetStdHandle(STD_INPUT_HANDLE);
4351     ptbl->childStdOut   = GetStdHandle(STD_OUTPUT_HANDLE);
4352     ptbl->childStdErr   = GetStdHandle(STD_ERROR_HANDLE);
4353 }
4354
4355 #ifdef HAVE_INTERP_INTERN
4356
4357 void
4358 Perl_sys_intern_init(pTHX)
4359 {
4360     w32_perlshell_tokens        = Nullch;
4361     w32_perlshell_vec           = (char**)NULL;
4362     w32_perlshell_items         = 0;
4363     w32_fdpid                   = newAV();
4364     New(1313, w32_children, 1, child_tab);
4365     w32_num_children            = 0;
4366 #  ifdef USE_ITHREADS
4367     w32_pseudo_id               = 0;
4368     New(1313, w32_pseudo_children, 1, child_tab);
4369     w32_num_pseudo_children     = 0;
4370 #  endif
4371     w32_init_socktype           = 0;
4372 }
4373
4374 void
4375 Perl_sys_intern_clear(pTHX)
4376 {
4377     Safefree(w32_perlshell_tokens);
4378     Safefree(w32_perlshell_vec);
4379     /* NOTE: w32_fdpid is freed by sv_clean_all() */
4380     Safefree(w32_children);
4381 #  ifdef USE_ITHREADS
4382     Safefree(w32_pseudo_children);
4383 #  endif
4384 }
4385
4386 #  ifdef USE_ITHREADS
4387
4388 void
4389 Perl_sys_intern_dup(pTHX_ struct interp_intern *src, struct interp_intern *dst)
4390 {
4391     dst->perlshell_tokens       = Nullch;
4392     dst->perlshell_vec          = (char**)NULL;
4393     dst->perlshell_items        = 0;
4394     dst->fdpid                  = newAV();
4395     Newz(1313, dst->children, 1, child_tab);
4396     dst->pseudo_id              = 0;
4397     Newz(1313, dst->pseudo_children, 1, child_tab);
4398     dst->thr_intern.Winit_socktype = 0;
4399 }
4400 #  endif /* USE_ITHREADS */
4401 #endif /* HAVE_INTERP_INTERN */
4402
4403 static void
4404 win32_free_argvw(pTHX_ void *ptr)
4405 {
4406     char** argv = (char**)ptr;
4407     while(*argv) {
4408         Safefree(*argv);
4409         *argv++ = Nullch;
4410     }
4411 }
4412
4413 void
4414 win32_argv2utf8(int argc, char** argv)
4415 {
4416     dTHX;
4417     char* psz;
4418     int length, wargc;
4419     LPWSTR* lpwStr = CommandLineToArgvW(GetCommandLineW(), &wargc);
4420     if (lpwStr && argc) {
4421         while (argc--) {
4422             length = WideCharToMultiByte(CP_UTF8, 0, lpwStr[--wargc], -1, NULL, 0, NULL, NULL);
4423             Newz(0, psz, length, char);
4424             WideCharToMultiByte(CP_UTF8, 0, lpwStr[wargc], -1, psz, length, NULL, NULL);
4425             argv[argc] = psz;
4426         }
4427         call_atexit(win32_free_argvw, argv);
4428     }
4429     GlobalFree((HGLOBAL)lpwStr);
4430 }
4431