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