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