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