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