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