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