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