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