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