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