better implementation of change#3326; open(local $foo,...) now
[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     StreamId.Size.HighPart = 0;
2373     StreamId.Size.LowPart = dwLen;
2374
2375     bSuccess = pfnBackupWrite(handle, (LPBYTE)&StreamId, dwSize, &dwWritten,
2376                               FALSE, FALSE, &lpContext);
2377     if (bSuccess) {
2378         bSuccess = pfnBackupWrite(handle, (LPBYTE)wFullName, dwLen, &dwWritten,
2379                                   FALSE, FALSE, &lpContext);
2380         pfnBackupWrite(handle, NULL, 0, &dwWritten, TRUE, FALSE, &lpContext);
2381     }
2382
2383     CloseHandle(handle);
2384     return bSuccess;
2385 }
2386
2387 DllExport int
2388 win32_link(const char *oldname, const char *newname)
2389 {
2390     dTHXo;
2391     BOOL (__stdcall *pfnCreateHardLinkW)(LPCWSTR,LPCWSTR,LPSECURITY_ATTRIBUTES);
2392     WCHAR wOldName[MAX_PATH];
2393     WCHAR wNewName[MAX_PATH];
2394
2395     if (IsWin95())
2396         Perl_die(aTHX_ PL_no_func, "link");
2397
2398     pfnCreateHardLinkW =
2399         (BOOL (__stdcall *)(LPCWSTR, LPCWSTR, LPSECURITY_ATTRIBUTES))
2400         GetProcAddress(GetModuleHandle("kernel32.dll"), "CreateHardLinkW");
2401     if (pfnCreateHardLinkW == NULL)
2402         pfnCreateHardLinkW = Nt4CreateHardLinkW;
2403
2404     if ((A2WHELPER(oldname, wOldName, sizeof(wOldName))) &&
2405         (A2WHELPER(newname, wNewName, sizeof(wNewName))) &&
2406         (wcscpy(wOldName, PerlDir_mapW(wOldName)),
2407         pfnCreateHardLinkW(PerlDir_mapW(wNewName), wOldName, NULL)))
2408     {
2409         return 0;
2410     }
2411     errno = (GetLastError() == ERROR_FILE_NOT_FOUND) ? ENOENT : EINVAL;
2412     return -1;
2413 }
2414
2415 DllExport int
2416 win32_rename(const char *oname, const char *newname)
2417 {
2418     WCHAR wOldName[MAX_PATH];
2419     WCHAR wNewName[MAX_PATH];
2420     char szOldName[MAX_PATH];
2421     BOOL bResult;
2422     /* XXX despite what the documentation says about MoveFileEx(),
2423      * it doesn't work under Windows95!
2424      */
2425     if (IsWinNT()) {
2426         dTHXo;
2427         if (USING_WIDE()) {
2428             A2WHELPER(oname, wOldName, sizeof(wOldName));
2429             A2WHELPER(newname, wNewName, sizeof(wNewName));
2430             wcscpy(wOldName, PerlDir_mapW(wOldName));
2431             bResult = MoveFileExW(wOldName,PerlDir_mapW(wNewName),
2432                         MOVEFILE_COPY_ALLOWED|MOVEFILE_REPLACE_EXISTING);
2433         }
2434         else {
2435             strcpy(szOldName, PerlDir_mapA(szOldName));
2436             bResult = MoveFileExA(szOldName,PerlDir_mapA(newname),
2437                         MOVEFILE_COPY_ALLOWED|MOVEFILE_REPLACE_EXISTING);
2438         }
2439         if (!bResult) {
2440             DWORD err = GetLastError();
2441             switch (err) {
2442             case ERROR_BAD_NET_NAME:
2443             case ERROR_BAD_NETPATH:
2444             case ERROR_BAD_PATHNAME:
2445             case ERROR_FILE_NOT_FOUND:
2446             case ERROR_FILENAME_EXCED_RANGE:
2447             case ERROR_INVALID_DRIVE:
2448             case ERROR_NO_MORE_FILES:
2449             case ERROR_PATH_NOT_FOUND:
2450                 errno = ENOENT;
2451                 break;
2452             default:
2453                 errno = EACCES;
2454                 break;
2455             }
2456             return -1;
2457         }
2458         return 0;
2459     }
2460     else {
2461         int retval = 0;
2462         char tmpname[MAX_PATH+1];
2463         char dname[MAX_PATH+1];
2464         char *endname = Nullch;
2465         STRLEN tmplen = 0;
2466         DWORD from_attr, to_attr;
2467
2468         /* if oname doesn't exist, do nothing */
2469         from_attr = GetFileAttributes(oname);
2470         if (from_attr == 0xFFFFFFFF) {
2471             errno = ENOENT;
2472             return -1;
2473         }
2474
2475         /* if newname exists, rename it to a temporary name so that we
2476          * don't delete it in case oname happens to be the same file
2477          * (but perhaps accessed via a different path)
2478          */
2479         to_attr = GetFileAttributes(newname);
2480         if (to_attr != 0xFFFFFFFF) {
2481             /* if newname is a directory, we fail
2482              * XXX could overcome this with yet more convoluted logic */
2483             if (to_attr & FILE_ATTRIBUTE_DIRECTORY) {
2484                 errno = EACCES;
2485                 return -1;
2486             }
2487             tmplen = strlen(newname);
2488             strcpy(tmpname,newname);
2489             endname = tmpname+tmplen;
2490             for (; endname > tmpname ; --endname) {
2491                 if (*endname == '/' || *endname == '\\') {
2492                     *endname = '\0';
2493                     break;
2494                 }
2495             }
2496             if (endname > tmpname)
2497                 endname = strcpy(dname,tmpname);
2498             else
2499                 endname = ".";
2500
2501             /* get a temporary filename in same directory
2502              * XXX is this really the best we can do? */
2503             if (!GetTempFileName((LPCTSTR)endname, "plr", 0, tmpname)) {
2504                 errno = ENOENT;
2505                 return -1;
2506             }
2507             DeleteFile(tmpname);
2508
2509             retval = rename(newname, tmpname);
2510             if (retval != 0) {
2511                 errno = EACCES;
2512                 return retval;
2513             }
2514         }
2515
2516         /* rename oname to newname */
2517         retval = rename(oname, newname);
2518
2519         /* if we created a temporary file before ... */
2520         if (endname != Nullch) {
2521             /* ...and rename succeeded, delete temporary file/directory */
2522             if (retval == 0)
2523                 DeleteFile(tmpname);
2524             /* else restore it to what it was */
2525             else
2526                 (void)rename(tmpname, newname);
2527         }
2528         return retval;
2529     }
2530 }
2531
2532 DllExport int
2533 win32_setmode(int fd, int mode)
2534 {
2535     return setmode(fd, mode);
2536 }
2537
2538 DllExport long
2539 win32_lseek(int fd, long offset, int origin)
2540 {
2541     return lseek(fd, offset, origin);
2542 }
2543
2544 DllExport long
2545 win32_tell(int fd)
2546 {
2547     return tell(fd);
2548 }
2549
2550 DllExport int
2551 win32_open(const char *path, int flag, ...)
2552 {
2553     dTHXo;
2554     va_list ap;
2555     int pmode;
2556     WCHAR wBuffer[MAX_PATH];
2557
2558     va_start(ap, flag);
2559     pmode = va_arg(ap, int);
2560     va_end(ap);
2561
2562     if (stricmp(path, "/dev/null")==0)
2563         path = "NUL";
2564
2565     if (USING_WIDE()) {
2566         A2WHELPER(path, wBuffer, sizeof(wBuffer));
2567         return _wopen(PerlDir_mapW(wBuffer), flag, pmode);
2568     }
2569     return open(PerlDir_mapA(path), flag, pmode);
2570 }
2571
2572 DllExport int
2573 win32_close(int fd)
2574 {
2575     return close(fd);
2576 }
2577
2578 DllExport int
2579 win32_eof(int fd)
2580 {
2581     return eof(fd);
2582 }
2583
2584 DllExport int
2585 win32_dup(int fd)
2586 {
2587     return dup(fd);
2588 }
2589
2590 DllExport int
2591 win32_dup2(int fd1,int fd2)
2592 {
2593     return dup2(fd1,fd2);
2594 }
2595
2596 DllExport int
2597 win32_read(int fd, void *buf, unsigned int cnt)
2598 {
2599     return read(fd, buf, cnt);
2600 }
2601
2602 DllExport int
2603 win32_write(int fd, const void *buf, unsigned int cnt)
2604 {
2605     return write(fd, buf, cnt);
2606 }
2607
2608 DllExport int
2609 win32_mkdir(const char *dir, int mode)
2610 {
2611     dTHXo;
2612     if (USING_WIDE()) {
2613         WCHAR wBuffer[MAX_PATH];
2614         A2WHELPER(dir, wBuffer, sizeof(wBuffer));
2615         return _wmkdir(PerlDir_mapW(wBuffer));
2616     }
2617     return mkdir(PerlDir_mapA(dir)); /* just ignore mode */
2618 }
2619
2620 DllExport int
2621 win32_rmdir(const char *dir)
2622 {
2623     dTHXo;
2624     if (USING_WIDE()) {
2625         WCHAR wBuffer[MAX_PATH];
2626         A2WHELPER(dir, wBuffer, sizeof(wBuffer));
2627         return _wrmdir(PerlDir_mapW(wBuffer));
2628     }
2629     return rmdir(PerlDir_mapA(dir));
2630 }
2631
2632 DllExport int
2633 win32_chdir(const char *dir)
2634 {
2635     dTHXo;
2636     if (USING_WIDE()) {
2637         WCHAR wBuffer[MAX_PATH];
2638         A2WHELPER(dir, wBuffer, sizeof(wBuffer));
2639         return _wchdir(wBuffer);
2640     }
2641     return chdir(dir);
2642 }
2643
2644 DllExport  int
2645 win32_access(const char *path, int mode)
2646 {
2647     dTHXo;
2648     if (USING_WIDE()) {
2649         WCHAR wBuffer[MAX_PATH];
2650         A2WHELPER(path, wBuffer, sizeof(wBuffer));
2651         return _waccess(PerlDir_mapW(wBuffer), mode);
2652     }
2653     return access(PerlDir_mapA(path), mode);
2654 }
2655
2656 DllExport  int
2657 win32_chmod(const char *path, int mode)
2658 {
2659     dTHXo;
2660     if (USING_WIDE()) {
2661         WCHAR wBuffer[MAX_PATH];
2662         A2WHELPER(path, wBuffer, sizeof(wBuffer));
2663         return _wchmod(PerlDir_mapW(wBuffer), mode);
2664     }
2665     return chmod(PerlDir_mapA(path), mode);
2666 }
2667
2668
2669 static char *
2670 create_command_line(const char* command, const char * const *args)
2671 {
2672     dTHXo;
2673     int index;
2674     char *cmd, *ptr, *arg;
2675     STRLEN len = strlen(command) + 1;
2676
2677     for (index = 0; (ptr = (char*)args[index]) != NULL; ++index)
2678         len += strlen(ptr) + 1;
2679
2680     New(1310, cmd, len, char);
2681     ptr = cmd;
2682     strcpy(ptr, command);
2683
2684     for (index = 0; (arg = (char*)args[index]) != NULL; ++index) {
2685         ptr += strlen(ptr);
2686         *ptr++ = ' ';
2687         strcpy(ptr, arg);
2688     }
2689
2690     return cmd;
2691 }
2692
2693 static char *
2694 qualified_path(const char *cmd)
2695 {
2696     dTHXo;
2697     char *pathstr;
2698     char *fullcmd, *curfullcmd;
2699     STRLEN cmdlen = 0;
2700     int has_slash = 0;
2701
2702     if (!cmd)
2703         return Nullch;
2704     fullcmd = (char*)cmd;
2705     while (*fullcmd) {
2706         if (*fullcmd == '/' || *fullcmd == '\\')
2707             has_slash++;
2708         fullcmd++;
2709         cmdlen++;
2710     }
2711
2712     /* look in PATH */
2713     pathstr = win32_getenv("PATH");
2714     New(0, fullcmd, MAX_PATH+1, char);
2715     curfullcmd = fullcmd;
2716
2717     while (1) {
2718         DWORD res;
2719
2720         /* start by appending the name to the current prefix */
2721         strcpy(curfullcmd, cmd);
2722         curfullcmd += cmdlen;
2723
2724         /* if it doesn't end with '.', or has no extension, try adding
2725          * a trailing .exe first */
2726         if (cmd[cmdlen-1] != '.'
2727             && (cmdlen < 4 || cmd[cmdlen-4] != '.'))
2728         {
2729             strcpy(curfullcmd, ".exe");
2730             res = GetFileAttributes(fullcmd);
2731             if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
2732                 return fullcmd;
2733             *curfullcmd = '\0';
2734         }
2735
2736         /* that failed, try the bare name */
2737         res = GetFileAttributes(fullcmd);
2738         if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
2739             return fullcmd;
2740
2741         /* quit if no other path exists, or if cmd already has path */
2742         if (!pathstr || !*pathstr || has_slash)
2743             break;
2744
2745         /* skip leading semis */
2746         while (*pathstr == ';')
2747             pathstr++;
2748
2749         /* build a new prefix from scratch */
2750         curfullcmd = fullcmd;
2751         while (*pathstr && *pathstr != ';') {
2752             if (*pathstr == '"') {      /* foo;"baz;etc";bar */
2753                 pathstr++;              /* skip initial '"' */
2754                 while (*pathstr && *pathstr != '"') {
2755                     if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
2756                         *curfullcmd++ = *pathstr;
2757                     pathstr++;
2758                 }
2759                 if (*pathstr)
2760                     pathstr++;          /* skip trailing '"' */
2761             }
2762             else {
2763                 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
2764                     *curfullcmd++ = *pathstr;
2765                 pathstr++;
2766             }
2767         }
2768         if (*pathstr)
2769             pathstr++;                  /* skip trailing semi */
2770         if (curfullcmd > fullcmd        /* append a dir separator */
2771             && curfullcmd[-1] != '/' && curfullcmd[-1] != '\\')
2772         {
2773             *curfullcmd++ = '\\';
2774         }
2775     }
2776 GIVE_UP:
2777     Safefree(fullcmd);
2778     return Nullch;
2779 }
2780
2781 /* The following are just place holders.
2782  * Some hosts may provide and environment that the OS is
2783  * not tracking, therefore, these host must provide that
2784  * environment and the current directory to CreateProcess
2785  */
2786
2787 void*
2788 get_childenv(void)
2789 {
2790     return NULL;
2791 }
2792
2793 void
2794 free_childenv(void* d)
2795 {
2796 }
2797
2798 char*
2799 get_childdir(void)
2800 {
2801     dTHXo;
2802     char* ptr;
2803     char szfilename[(MAX_PATH+1)*2];
2804     if (USING_WIDE()) {
2805         WCHAR wfilename[MAX_PATH+1];
2806         GetCurrentDirectoryW(MAX_PATH+1, wfilename);
2807         W2AHELPER(wfilename, szfilename, sizeof(szfilename));
2808     }
2809     else {
2810         GetCurrentDirectoryA(MAX_PATH+1, szfilename);
2811     }
2812
2813     New(0, ptr, strlen(szfilename)+1, char);
2814     strcpy(ptr, szfilename);
2815     return ptr;
2816 }
2817
2818 void
2819 free_childdir(char* d)
2820 {
2821     dTHXo;
2822     Safefree(d);
2823 }
2824
2825
2826 /* XXX this needs to be made more compatible with the spawnvp()
2827  * provided by the various RTLs.  In particular, searching for
2828  * *.{com,bat,cmd} files (as done by the RTLs) is unimplemented.
2829  * This doesn't significantly affect perl itself, because we
2830  * always invoke things using PERL5SHELL if a direct attempt to
2831  * spawn the executable fails.
2832  * 
2833  * XXX splitting and rejoining the commandline between do_aspawn()
2834  * and win32_spawnvp() could also be avoided.
2835  */
2836
2837 DllExport int
2838 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
2839 {
2840 #ifdef USE_RTL_SPAWNVP
2841     return spawnvp(mode, cmdname, (char * const *)argv);
2842 #else
2843     dTHXo;
2844     int ret;
2845     void* env;
2846     char* dir;
2847     STARTUPINFO StartupInfo;
2848     PROCESS_INFORMATION ProcessInformation;
2849     DWORD create = 0;
2850
2851     char *cmd = create_command_line(cmdname, strcmp(cmdname, argv[0]) == 0
2852                                              ? &argv[1] : argv);
2853     char *fullcmd = Nullch;
2854
2855     env = PerlEnv_get_childenv();
2856     dir = PerlEnv_get_childdir();
2857
2858     switch(mode) {
2859     case P_NOWAIT:      /* asynch + remember result */
2860         if (w32_num_children >= MAXIMUM_WAIT_OBJECTS) {
2861             errno = EAGAIN;
2862             ret = -1;
2863             goto RETVAL;
2864         }
2865         /* FALL THROUGH */
2866     case P_WAIT:        /* synchronous execution */
2867         break;
2868     default:            /* invalid mode */
2869         errno = EINVAL;
2870         ret = -1;
2871         goto RETVAL;
2872     }
2873     memset(&StartupInfo,0,sizeof(StartupInfo));
2874     StartupInfo.cb = sizeof(StartupInfo);
2875     StartupInfo.hStdInput  = GetStdHandle(STD_INPUT_HANDLE);
2876     StartupInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
2877     StartupInfo.hStdError  = GetStdHandle(STD_ERROR_HANDLE);
2878     if (StartupInfo.hStdInput != INVALID_HANDLE_VALUE &&
2879         StartupInfo.hStdOutput != INVALID_HANDLE_VALUE &&
2880         StartupInfo.hStdError != INVALID_HANDLE_VALUE)
2881     {
2882         StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
2883     }
2884     else {
2885         create |= CREATE_NEW_CONSOLE;
2886     }
2887
2888 RETRY:
2889     if (!CreateProcess(cmdname,         /* search PATH to find executable */
2890                        cmd,             /* executable, and its arguments */
2891                        NULL,            /* process attributes */
2892                        NULL,            /* thread attributes */
2893                        TRUE,            /* inherit handles */
2894                        create,          /* creation flags */
2895                        (LPVOID)env,     /* inherit environment */
2896                        dir,             /* inherit cwd */
2897                        &StartupInfo,
2898                        &ProcessInformation))
2899     {
2900         /* initial NULL argument to CreateProcess() does a PATH
2901          * search, but it always first looks in the directory
2902          * where the current process was started, which behavior
2903          * is undesirable for backward compatibility.  So we
2904          * jump through our own hoops by picking out the path
2905          * we really want it to use. */
2906         if (!fullcmd) {
2907             fullcmd = qualified_path(cmdname);
2908             if (fullcmd) {
2909                 cmdname = fullcmd;
2910                 goto RETRY;
2911             }
2912         }
2913         errno = ENOENT;
2914         ret = -1;
2915         goto RETVAL;
2916     }
2917
2918     if (mode == P_NOWAIT) {
2919         /* asynchronous spawn -- store handle, return PID */
2920         w32_child_handles[w32_num_children] = ProcessInformation.hProcess;
2921         w32_child_pids[w32_num_children] = ProcessInformation.dwProcessId;
2922         ret = (int)ProcessInformation.dwProcessId;
2923         ++w32_num_children;
2924     }
2925     else  {
2926         DWORD status;
2927         WaitForSingleObject(ProcessInformation.hProcess, INFINITE);
2928         GetExitCodeProcess(ProcessInformation.hProcess, &status);
2929         ret = (int)status;
2930         CloseHandle(ProcessInformation.hProcess);
2931     }
2932
2933     CloseHandle(ProcessInformation.hThread);
2934
2935 RETVAL:
2936     PerlEnv_free_childenv(env);
2937     PerlEnv_free_childdir(dir);
2938     Safefree(cmd);
2939     Safefree(fullcmd);
2940     return ret;
2941 #endif
2942 }
2943
2944 DllExport int
2945 win32_execv(const char *cmdname, const char *const *argv)
2946 {
2947 #ifdef USE_ITHREADS
2948     dTHXo;
2949     /* if this is a pseudo-forked child, we just want to spawn
2950      * the new program, and return */
2951     if (w32_pseudo_id)
2952         return spawnv(P_WAIT, cmdname, (char *const *)argv);
2953 #endif
2954     return execv(cmdname, (char *const *)argv);
2955 }
2956
2957 DllExport int
2958 win32_execvp(const char *cmdname, const char *const *argv)
2959 {
2960 #ifdef USE_ITHREADS
2961     dTHXo;
2962     /* if this is a pseudo-forked child, we just want to spawn
2963      * the new program, and return */
2964     if (w32_pseudo_id)
2965         return win32_spawnvp(P_WAIT, cmdname, (char *const *)argv);
2966 #endif
2967     return execvp(cmdname, (char *const *)argv);
2968 }
2969
2970 DllExport void
2971 win32_perror(const char *str)
2972 {
2973     perror(str);
2974 }
2975
2976 DllExport void
2977 win32_setbuf(FILE *pf, char *buf)
2978 {
2979     setbuf(pf, buf);
2980 }
2981
2982 DllExport int
2983 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
2984 {
2985     return setvbuf(pf, buf, type, size);
2986 }
2987
2988 DllExport int
2989 win32_flushall(void)
2990 {
2991     return flushall();
2992 }
2993
2994 DllExport int
2995 win32_fcloseall(void)
2996 {
2997     return fcloseall();
2998 }
2999
3000 DllExport char*
3001 win32_fgets(char *s, int n, FILE *pf)
3002 {
3003     return fgets(s, n, pf);
3004 }
3005
3006 DllExport char*
3007 win32_gets(char *s)
3008 {
3009     return gets(s);
3010 }
3011
3012 DllExport int
3013 win32_fgetc(FILE *pf)
3014 {
3015     return fgetc(pf);
3016 }
3017
3018 DllExport int
3019 win32_putc(int c, FILE *pf)
3020 {
3021     return putc(c,pf);
3022 }
3023
3024 DllExport int
3025 win32_puts(const char *s)
3026 {
3027     return puts(s);
3028 }
3029
3030 DllExport int
3031 win32_getchar(void)
3032 {
3033     return getchar();
3034 }
3035
3036 DllExport int
3037 win32_putchar(int c)
3038 {
3039     return putchar(c);
3040 }
3041
3042 #ifdef MYMALLOC
3043
3044 #ifndef USE_PERL_SBRK
3045
3046 static char *committed = NULL;
3047 static char *base      = NULL;
3048 static char *reserved  = NULL;
3049 static char *brk       = NULL;
3050 static DWORD pagesize  = 0;
3051 static DWORD allocsize = 0;
3052
3053 void *
3054 sbrk(int need)
3055 {
3056  void *result;
3057  if (!pagesize)
3058   {SYSTEM_INFO info;
3059    GetSystemInfo(&info);
3060    /* Pretend page size is larger so we don't perpetually
3061     * call the OS to commit just one page ...
3062     */
3063    pagesize = info.dwPageSize << 3;
3064    allocsize = info.dwAllocationGranularity;
3065   }
3066  /* This scheme fails eventually if request for contiguous
3067   * block is denied so reserve big blocks - this is only 
3068   * address space not memory ...
3069   */
3070  if (brk+need >= reserved)
3071   {
3072    DWORD size = 64*1024*1024;
3073    char *addr;
3074    if (committed && reserved && committed < reserved)
3075     {
3076      /* Commit last of previous chunk cannot span allocations */
3077      addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
3078      if (addr)
3079       committed = reserved;
3080     }
3081    /* Reserve some (more) space 
3082     * Note this is a little sneaky, 1st call passes NULL as reserved
3083     * so lets system choose where we start, subsequent calls pass
3084     * the old end address so ask for a contiguous block
3085     */
3086    addr  = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
3087    if (addr)
3088     {
3089      reserved = addr+size;
3090      if (!base)
3091       base = addr;
3092      if (!committed)
3093       committed = base;
3094      if (!brk)
3095       brk = committed;
3096     }
3097    else
3098     {
3099      return (void *) -1;
3100     }
3101   }
3102  result = brk;
3103  brk += need;
3104  if (brk > committed)
3105   {
3106    DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
3107    char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
3108    if (addr)
3109     {
3110      committed += size;
3111     }
3112    else
3113     return (void *) -1;
3114   }
3115  return result;
3116 }
3117
3118 #endif
3119 #endif
3120
3121 DllExport void*
3122 win32_malloc(size_t size)
3123 {
3124     return malloc(size);
3125 }
3126
3127 DllExport void*
3128 win32_calloc(size_t numitems, size_t size)
3129 {
3130     return calloc(numitems,size);
3131 }
3132
3133 DllExport void*
3134 win32_realloc(void *block, size_t size)
3135 {
3136     return realloc(block,size);
3137 }
3138
3139 DllExport void
3140 win32_free(void *block)
3141 {
3142     free(block);
3143 }
3144
3145
3146 int
3147 win32_open_osfhandle(long handle, int flags)
3148 {
3149     return _open_osfhandle(handle, flags);
3150 }
3151
3152 long
3153 win32_get_osfhandle(int fd)
3154 {
3155     return _get_osfhandle(fd);
3156 }
3157
3158 DllExport void*
3159 win32_dynaload(const char* filename)
3160 {
3161     dTHXo;
3162     HMODULE hModule;
3163     if (USING_WIDE()) {
3164         WCHAR wfilename[MAX_PATH];
3165         A2WHELPER(filename, wfilename, sizeof(wfilename));
3166         hModule = LoadLibraryExW(PerlDir_mapW(wfilename), NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
3167     }
3168     else {
3169         hModule = LoadLibraryExA(PerlDir_mapA(filename), NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
3170     }
3171     return hModule;
3172 }
3173
3174 /*
3175  * Extras.
3176  */
3177
3178 static
3179 XS(w32_GetCwd)
3180 {
3181     dXSARGS;
3182     /* Make the host for current directory */
3183     char* ptr = PerlEnv_get_childdir();
3184     /* 
3185      * If ptr != Nullch 
3186      *   then it worked, set PV valid, 
3187      *   else return 'undef' 
3188      */
3189     if (ptr) {
3190         SV *sv = sv_newmortal();
3191         sv_setpv(sv, ptr);
3192         PerlEnv_free_childdir(ptr);
3193
3194         EXTEND(SP,1);
3195         SvPOK_on(sv);
3196         ST(0) = sv;
3197         XSRETURN(1);
3198     }
3199     XSRETURN_UNDEF;
3200 }
3201
3202 static
3203 XS(w32_SetCwd)
3204 {
3205     dXSARGS;
3206     if (items != 1)
3207         Perl_croak(aTHX_ "usage: Win32::SetCurrentDirectory($cwd)");
3208     if (!PerlDir_chdir(SvPV_nolen(ST(0))))
3209         XSRETURN_YES;
3210
3211     XSRETURN_NO;
3212 }
3213
3214 static
3215 XS(w32_GetNextAvailDrive)
3216 {
3217     dXSARGS;
3218     char ix = 'C';
3219     char root[] = "_:\\";
3220
3221     EXTEND(SP,1);
3222     while (ix <= 'Z') {
3223         root[0] = ix++;
3224         if (GetDriveType(root) == 1) {
3225             root[2] = '\0';
3226             XSRETURN_PV(root);
3227         }
3228     }
3229     XSRETURN_UNDEF;
3230 }
3231
3232 static
3233 XS(w32_GetLastError)
3234 {
3235     dXSARGS;
3236     EXTEND(SP,1);
3237     XSRETURN_IV(GetLastError());
3238 }
3239
3240 static
3241 XS(w32_SetLastError)
3242 {
3243     dXSARGS;
3244     if (items != 1)
3245         Perl_croak(aTHX_ "usage: Win32::SetLastError($error)");
3246     SetLastError(SvIV(ST(0)));
3247     XSRETURN_EMPTY;
3248 }
3249
3250 static
3251 XS(w32_LoginName)
3252 {
3253     dXSARGS;
3254     char *name = w32_getlogin_buffer;
3255     DWORD size = sizeof(w32_getlogin_buffer);
3256     EXTEND(SP,1);
3257     if (GetUserName(name,&size)) {
3258         /* size includes NULL */
3259         ST(0) = sv_2mortal(newSVpvn(name,size-1));
3260         XSRETURN(1);
3261     }
3262     XSRETURN_UNDEF;
3263 }
3264
3265 static
3266 XS(w32_NodeName)
3267 {
3268     dXSARGS;
3269     char name[MAX_COMPUTERNAME_LENGTH+1];
3270     DWORD size = sizeof(name);
3271     EXTEND(SP,1);
3272     if (GetComputerName(name,&size)) {
3273         /* size does NOT include NULL :-( */
3274         ST(0) = sv_2mortal(newSVpvn(name,size));
3275         XSRETURN(1);
3276     }
3277     XSRETURN_UNDEF;
3278 }
3279
3280
3281 static
3282 XS(w32_DomainName)
3283 {
3284     dXSARGS;
3285     HINSTANCE hNetApi32 = LoadLibrary("netapi32.dll");
3286     DWORD (__stdcall *pfnNetApiBufferFree)(LPVOID Buffer);
3287     DWORD (__stdcall *pfnNetWkstaGetInfo)(LPWSTR servername, DWORD level,
3288                                           void *bufptr);
3289
3290     if (hNetApi32) {
3291         pfnNetApiBufferFree = (DWORD (__stdcall *)(void *))
3292             GetProcAddress(hNetApi32, "NetApiBufferFree");
3293         pfnNetWkstaGetInfo = (DWORD (__stdcall *)(LPWSTR, DWORD, void *))
3294             GetProcAddress(hNetApi32, "NetWkstaGetInfo");
3295     }
3296     EXTEND(SP,1);
3297     if (hNetApi32 && pfnNetWkstaGetInfo && pfnNetApiBufferFree) {
3298         /* this way is more reliable, in case user has a local account. */
3299         char dname[256];
3300         DWORD dnamelen = sizeof(dname);
3301         struct {
3302             DWORD   wki100_platform_id;
3303             LPWSTR  wki100_computername;
3304             LPWSTR  wki100_langroup;
3305             DWORD   wki100_ver_major;
3306             DWORD   wki100_ver_minor;
3307         } *pwi;
3308         /* NERR_Success *is* 0*/
3309         if (0 == pfnNetWkstaGetInfo(NULL, 100, &pwi)) {
3310             if (pwi->wki100_langroup && *(pwi->wki100_langroup)) {
3311                 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_langroup,
3312                                     -1, (LPSTR)dname, dnamelen, NULL, NULL);
3313             }
3314             else {
3315                 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_computername,
3316                                     -1, (LPSTR)dname, dnamelen, NULL, NULL);
3317             }
3318             pfnNetApiBufferFree(pwi);
3319             FreeLibrary(hNetApi32);
3320             XSRETURN_PV(dname);
3321         }
3322         FreeLibrary(hNetApi32);
3323     }
3324     else {
3325         /* Win95 doesn't have NetWksta*(), so do it the old way */
3326         char name[256];
3327         DWORD size = sizeof(name);
3328         if (hNetApi32)
3329             FreeLibrary(hNetApi32);
3330         if (GetUserName(name,&size)) {
3331             char sid[ONE_K_BUFSIZE];
3332             DWORD sidlen = sizeof(sid);
3333             char dname[256];
3334             DWORD dnamelen = sizeof(dname);
3335             SID_NAME_USE snu;
3336             if (LookupAccountName(NULL, name, (PSID)&sid, &sidlen,
3337                                   dname, &dnamelen, &snu)) {
3338                 XSRETURN_PV(dname);             /* all that for this */
3339             }
3340         }
3341     }
3342     XSRETURN_UNDEF;
3343 }
3344
3345 static
3346 XS(w32_FsType)
3347 {
3348     dXSARGS;
3349     char fsname[256];
3350     DWORD flags, filecomplen;
3351     if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
3352                          &flags, fsname, sizeof(fsname))) {
3353         if (GIMME_V == G_ARRAY) {
3354             XPUSHs(sv_2mortal(newSVpvn(fsname,strlen(fsname))));
3355             XPUSHs(sv_2mortal(newSViv(flags)));
3356             XPUSHs(sv_2mortal(newSViv(filecomplen)));
3357             PUTBACK;
3358             return;
3359         }
3360         EXTEND(SP,1);
3361         XSRETURN_PV(fsname);
3362     }
3363     XSRETURN_EMPTY;
3364 }
3365
3366 static
3367 XS(w32_GetOSVersion)
3368 {
3369     dXSARGS;
3370     OSVERSIONINFOA osver;
3371
3372     if (USING_WIDE()) {
3373         OSVERSIONINFOW osverw;
3374         char szCSDVersion[sizeof(osverw.szCSDVersion)];
3375         osverw.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
3376         if (!GetVersionExW(&osverw)) {
3377             XSRETURN_EMPTY;
3378         }
3379         W2AHELPER(osverw.szCSDVersion, szCSDVersion, sizeof(szCSDVersion));
3380         XPUSHs(newSVpvn(szCSDVersion, strlen(szCSDVersion)));
3381         osver.dwMajorVersion = osverw.dwMajorVersion;
3382         osver.dwMinorVersion = osverw.dwMinorVersion;
3383         osver.dwBuildNumber = osverw.dwBuildNumber;
3384         osver.dwPlatformId = osverw.dwPlatformId;
3385     }
3386     else {
3387         osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOA);
3388         if (!GetVersionExA(&osver)) {
3389             XSRETURN_EMPTY;
3390         }
3391         XPUSHs(newSVpvn(osver.szCSDVersion, strlen(osver.szCSDVersion)));
3392     }
3393     XPUSHs(newSViv(osver.dwMajorVersion));
3394     XPUSHs(newSViv(osver.dwMinorVersion));
3395     XPUSHs(newSViv(osver.dwBuildNumber));
3396     XPUSHs(newSViv(osver.dwPlatformId));
3397     PUTBACK;
3398 }
3399
3400 static
3401 XS(w32_IsWinNT)
3402 {
3403     dXSARGS;
3404     EXTEND(SP,1);
3405     XSRETURN_IV(IsWinNT());
3406 }
3407
3408 static
3409 XS(w32_IsWin95)
3410 {
3411     dXSARGS;
3412     EXTEND(SP,1);
3413     XSRETURN_IV(IsWin95());
3414 }
3415
3416 static
3417 XS(w32_FormatMessage)
3418 {
3419     dXSARGS;
3420     DWORD source = 0;
3421     char msgbuf[ONE_K_BUFSIZE];
3422
3423     if (items != 1)
3424         Perl_croak(aTHX_ "usage: Win32::FormatMessage($errno)");
3425
3426     if (USING_WIDE()) {
3427         WCHAR wmsgbuf[ONE_K_BUFSIZE];
3428         if (FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM,
3429                           &source, SvIV(ST(0)), 0,
3430                           wmsgbuf, ONE_K_BUFSIZE-1, NULL))
3431         {
3432             W2AHELPER(wmsgbuf, msgbuf, sizeof(msgbuf));
3433             XSRETURN_PV(msgbuf);
3434         }
3435     }
3436     else {
3437         if (FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM,
3438                           &source, SvIV(ST(0)), 0,
3439                           msgbuf, sizeof(msgbuf)-1, NULL))
3440             XSRETURN_PV(msgbuf);
3441     }
3442
3443     XSRETURN_UNDEF;
3444 }
3445
3446 static
3447 XS(w32_Spawn)
3448 {
3449     dXSARGS;
3450     char *cmd, *args;
3451     PROCESS_INFORMATION stProcInfo;
3452     STARTUPINFO stStartInfo;
3453     BOOL bSuccess = FALSE;
3454
3455     if (items != 3)
3456         Perl_croak(aTHX_ "usage: Win32::Spawn($cmdName, $args, $PID)");
3457
3458     cmd = SvPV_nolen(ST(0));
3459     args = SvPV_nolen(ST(1));
3460
3461     memset(&stStartInfo, 0, sizeof(stStartInfo));   /* Clear the block */
3462     stStartInfo.cb = sizeof(stStartInfo);           /* Set the structure size */
3463     stStartInfo.dwFlags = STARTF_USESHOWWINDOW;     /* Enable wShowWindow control */
3464     stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE;   /* Start min (normal) */
3465
3466     if (CreateProcess(
3467                 cmd,                    /* Image path */
3468                 args,                   /* Arguments for command line */
3469                 NULL,                   /* Default process security */
3470                 NULL,                   /* Default thread security */
3471                 FALSE,                  /* Must be TRUE to use std handles */
3472                 NORMAL_PRIORITY_CLASS,  /* No special scheduling */
3473                 NULL,                   /* Inherit our environment block */
3474                 NULL,                   /* Inherit our currrent directory */
3475                 &stStartInfo,           /* -> Startup info */
3476                 &stProcInfo))           /* <- Process info (if OK) */
3477     {
3478         CloseHandle(stProcInfo.hThread);/* library source code does this. */
3479         sv_setiv(ST(2), stProcInfo.dwProcessId);
3480         bSuccess = TRUE;
3481     }
3482     XSRETURN_IV(bSuccess);
3483 }
3484
3485 static
3486 XS(w32_GetTickCount)
3487 {
3488     dXSARGS;
3489     DWORD msec = GetTickCount();
3490     EXTEND(SP,1);
3491     if ((IV)msec > 0)
3492         XSRETURN_IV(msec);
3493     XSRETURN_NV(msec);
3494 }
3495
3496 static
3497 XS(w32_GetShortPathName)
3498 {
3499     dXSARGS;
3500     SV *shortpath;
3501     DWORD len;
3502
3503     if (items != 1)
3504         Perl_croak(aTHX_ "usage: Win32::GetShortPathName($longPathName)");
3505
3506     shortpath = sv_mortalcopy(ST(0));
3507     SvUPGRADE(shortpath, SVt_PV);
3508     /* src == target is allowed */
3509     do {
3510         len = GetShortPathName(SvPVX(shortpath),
3511                                SvPVX(shortpath),
3512                                SvLEN(shortpath));
3513     } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
3514     if (len) {
3515         SvCUR_set(shortpath,len);
3516         ST(0) = shortpath;
3517         XSRETURN(1);
3518     }
3519     XSRETURN_UNDEF;
3520 }
3521
3522 static
3523 XS(w32_GetFullPathName)
3524 {
3525     dXSARGS;
3526     SV *filename;
3527     SV *fullpath;
3528     char *filepart;
3529     DWORD len;
3530
3531     if (items != 1)
3532         Perl_croak(aTHX_ "usage: Win32::GetFullPathName($filename)");
3533
3534     filename = ST(0);
3535     fullpath = sv_mortalcopy(filename);
3536     SvUPGRADE(fullpath, SVt_PV);
3537     do {
3538         len = GetFullPathName(SvPVX(filename),
3539                               SvLEN(fullpath),
3540                               SvPVX(fullpath),
3541                               &filepart);
3542     } while (len >= SvLEN(fullpath) && sv_grow(fullpath,len+1));
3543     if (len) {
3544         if (GIMME_V == G_ARRAY) {
3545             EXTEND(SP,1);
3546             XST_mPV(1,filepart);
3547             len = filepart - SvPVX(fullpath);
3548             items = 2;
3549         }
3550         SvCUR_set(fullpath,len);
3551         ST(0) = fullpath;
3552         XSRETURN(items);
3553     }
3554     XSRETURN_EMPTY;
3555 }
3556
3557 static
3558 XS(w32_GetLongPathName)
3559 {
3560     dXSARGS;
3561     SV *path;
3562     char tmpbuf[MAX_PATH+1];
3563     char *pathstr;
3564     STRLEN len;
3565
3566     if (items != 1)
3567         Perl_croak(aTHX_ "usage: Win32::GetLongPathName($pathname)");
3568
3569     path = ST(0);
3570     pathstr = SvPV(path,len);
3571     strcpy(tmpbuf, pathstr);
3572     pathstr = win32_longpath(tmpbuf);
3573     if (pathstr) {
3574         ST(0) = sv_2mortal(newSVpvn(pathstr, strlen(pathstr)));
3575         XSRETURN(1);
3576     }
3577     XSRETURN_EMPTY;
3578 }
3579
3580 static
3581 XS(w32_Sleep)
3582 {
3583     dXSARGS;
3584     if (items != 1)
3585         Perl_croak(aTHX_ "usage: Win32::Sleep($milliseconds)");
3586     Sleep(SvIV(ST(0)));
3587     XSRETURN_YES;
3588 }
3589
3590 static
3591 XS(w32_CopyFile)
3592 {
3593     dXSARGS;
3594     BOOL bResult;
3595     if (items != 3)
3596         Perl_croak(aTHX_ "usage: Win32::CopyFile($from, $to, $overwrite)");
3597     if (USING_WIDE()) {
3598         WCHAR wSourceFile[MAX_PATH];
3599         WCHAR wDestFile[MAX_PATH];
3600         A2WHELPER(SvPV_nolen(ST(0)), wSourceFile, sizeof(wSourceFile));
3601         wcscpy(wSourceFile, PerlDir_mapW(wSourceFile));
3602         A2WHELPER(SvPV_nolen(ST(1)), wDestFile, sizeof(wDestFile));
3603         bResult = CopyFileW(wSourceFile, PerlDir_mapW(wDestFile), !SvTRUE(ST(2)));
3604     }
3605     else {
3606         char szSourceFile[MAX_PATH];
3607         strcpy(szSourceFile, PerlDir_mapA(SvPV_nolen(ST(0))));
3608         bResult = CopyFileA(szSourceFile, PerlDir_mapA(SvPV_nolen(ST(1))), !SvTRUE(ST(2)));
3609     }
3610
3611     if (bResult)
3612         XSRETURN_YES;
3613     XSRETURN_NO;
3614 }
3615
3616 void
3617 Perl_init_os_extras(void)
3618 {
3619     dTHXo;
3620     char *file = __FILE__;
3621     dXSUB_SYS;
3622
3623     w32_perlshell_tokens = Nullch;
3624     w32_perlshell_items = -1;
3625     w32_fdpid = newAV();                /* XXX needs to be in Perl_win32_init()? */
3626     New(1313, w32_children, 1, child_tab);
3627     w32_num_children = 0;
3628     w32_init_socktype = 0;
3629 #ifdef USE_ITHREADS
3630     w32_pseudo_id = 0;
3631     New(1313, w32_pseudo_children, 1, child_tab);
3632     w32_num_pseudo_children = 0;
3633 #endif
3634
3635     /* these names are Activeware compatible */
3636     newXS("Win32::GetCwd", w32_GetCwd, file);
3637     newXS("Win32::SetCwd", w32_SetCwd, file);
3638     newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
3639     newXS("Win32::GetLastError", w32_GetLastError, file);
3640     newXS("Win32::SetLastError", w32_SetLastError, file);
3641     newXS("Win32::LoginName", w32_LoginName, file);
3642     newXS("Win32::NodeName", w32_NodeName, file);
3643     newXS("Win32::DomainName", w32_DomainName, file);
3644     newXS("Win32::FsType", w32_FsType, file);
3645     newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
3646     newXS("Win32::IsWinNT", w32_IsWinNT, file);
3647     newXS("Win32::IsWin95", w32_IsWin95, file);
3648     newXS("Win32::FormatMessage", w32_FormatMessage, file);
3649     newXS("Win32::Spawn", w32_Spawn, file);
3650     newXS("Win32::GetTickCount", w32_GetTickCount, file);
3651     newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
3652     newXS("Win32::GetFullPathName", w32_GetFullPathName, file);
3653     newXS("Win32::GetLongPathName", w32_GetLongPathName, file);
3654     newXS("Win32::CopyFile", w32_CopyFile, file);
3655     newXS("Win32::Sleep", w32_Sleep, file);
3656
3657     /* XXX Bloat Alert! The following Activeware preloads really
3658      * ought to be part of Win32::Sys::*, so they're not included
3659      * here.
3660      */
3661     /* LookupAccountName
3662      * LookupAccountSID
3663      * InitiateSystemShutdown
3664      * AbortSystemShutdown
3665      * ExpandEnvrironmentStrings
3666      */
3667 }
3668
3669 void
3670 Perl_win32_init(int *argcp, char ***argvp)
3671 {
3672     /* Disable floating point errors, Perl will trap the ones we
3673      * care about.  VC++ RTL defaults to switching these off
3674      * already, but the Borland RTL doesn't.  Since we don't
3675      * want to be at the vendor's whim on the default, we set
3676      * it explicitly here.
3677      */
3678 #if !defined(_ALPHA_) && !defined(__GNUC__)
3679     _control87(MCW_EM, MCW_EM);
3680 #endif
3681     MALLOC_INIT;
3682 }
3683
3684 #ifdef USE_BINMODE_SCRIPTS
3685
3686 void
3687 win32_strip_return(SV *sv)
3688 {
3689  char *s = SvPVX(sv);
3690  char *e = s+SvCUR(sv);
3691  char *d = s;
3692  while (s < e)
3693   {
3694    if (*s == '\r' && s[1] == '\n')
3695     {
3696      *d++ = '\n';
3697      s += 2;
3698     }
3699    else 
3700     {
3701      *d++ = *s++;
3702     }   
3703   }
3704  SvCUR_set(sv,d-SvPVX(sv)); 
3705 }
3706
3707 #endif
3708
3709 #ifdef USE_ITHREADS
3710
3711 #  ifdef PERL_OBJECT
3712 #    undef Perl_sys_intern_dup
3713 #    define Perl_sys_intern_dup CPerlObj::Perl_sys_intern_dup
3714 #    define pPerl this
3715 #  endif
3716
3717 void
3718 Perl_sys_intern_dup(pTHX_ struct interp_intern *src, struct interp_intern *dst)
3719 {
3720     dst->perlshell_tokens       = Nullch;
3721     dst->perlshell_vec          = (char**)NULL;
3722     dst->perlshell_items        = 0;
3723     dst->fdpid                  = newAV();
3724     Newz(1313, dst->children, 1, child_tab);
3725     Newz(1313, dst->pseudo_children, 1, child_tab);
3726     dst->pseudo_id              = 0;
3727     dst->children->num          = 0;
3728     dst->thr_intern.Winit_socktype = src->thr_intern.Winit_socktype;
3729 }
3730 #endif
3731