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