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