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