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