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