This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
update Changes
[perl5.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             if (l >= 4 && path[l-4] == '.') {
1136                 const char *e = path + l - 3;
1137                 if (strnicmp(e,"exe",3)
1138                     && strnicmp(e,"bat",3)
1139                     && strnicmp(e,"com",3)
1140                     && (IsWin95() || strnicmp(e,"cmd",3)))
1141                     sbuf->st_mode &= ~S_IEXEC;
1142                 else
1143                     sbuf->st_mode |= S_IEXEC;
1144             }
1145             else
1146                 sbuf->st_mode &= ~S_IEXEC;
1147         }
1148 #endif
1149     }
1150     return res;
1151 }
1152
1153 /* Find the longname of a given path.  path is destructively modified.
1154  * It should have space for at least MAX_PATH characters. */
1155 DllExport char *
1156 win32_longpath(char *path)
1157 {
1158     WIN32_FIND_DATA fdata;
1159     HANDLE fhand;
1160     char tmpbuf[MAX_PATH+1];
1161     char *tmpstart = tmpbuf;
1162     char *start = path;
1163     char sep;
1164     if (!path)
1165         return Nullch;
1166
1167     /* drive prefix */
1168     if (isALPHA(path[0]) && path[1] == ':' &&
1169         (path[2] == '/' || path[2] == '\\'))
1170     {
1171         start = path + 2;
1172         *tmpstart++ = path[0];
1173         *tmpstart++ = ':';
1174     }
1175     /* UNC prefix */
1176     else if ((path[0] == '/' || path[0] == '\\') &&
1177              (path[1] == '/' || path[1] == '\\'))
1178     {
1179         start = path + 2;
1180         *tmpstart++ = path[0];
1181         *tmpstart++ = path[1];
1182         /* copy machine name */
1183         while (*start && *start != '/' && *start != '\\')
1184             *tmpstart++ = *start++;
1185         if (*start) {
1186             *tmpstart++ = *start;
1187             start++;
1188             /* copy share name */
1189             while (*start && *start != '/' && *start != '\\')
1190                 *tmpstart++ = *start++;
1191         }
1192     }
1193     sep = *start++;
1194     if (sep == '/' || sep == '\\')
1195         *tmpstart++ = sep;
1196     *tmpstart = '\0';
1197     while (sep) {
1198         /* walk up to slash */
1199         while (*start && *start != '/' && *start != '\\')
1200             ++start;
1201
1202         /* discard doubled slashes */
1203         while (*start && (start[1] == '/' || start[1] == '\\'))
1204             ++start;
1205         sep = *start;
1206
1207         /* stop and find full name of component */
1208         *start = '\0';
1209         fhand = FindFirstFile(path,&fdata);
1210         if (fhand != INVALID_HANDLE_VALUE) {
1211             strcpy(tmpstart, fdata.cFileName);
1212             tmpstart += strlen(fdata.cFileName);
1213             if (sep)
1214                 *tmpstart++ = sep;
1215             *tmpstart = '\0';
1216             *start++ = sep;
1217             FindClose(fhand);
1218         }
1219         else {
1220             /* failed a step, just return without side effects */
1221             /*PerlIO_printf(Perl_debug_log, "Failed to find %s\n", path);*/
1222             *start = sep;
1223             return Nullch;
1224         }
1225     }
1226     strcpy(path,tmpbuf);
1227     return path;
1228 }
1229
1230 #ifndef USE_WIN32_RTL_ENV
1231
1232 DllExport char *
1233 win32_getenv(const char *name)
1234 {
1235     dTHXo;
1236     WCHAR wBuffer[MAX_PATH+1];
1237     DWORD needlen;
1238     SV *curitem = Nullsv;
1239
1240     if (USING_WIDE()) {
1241         A2WHELPER(name, wBuffer, sizeof(wBuffer));
1242         needlen = GetEnvironmentVariableW(wBuffer, NULL, 0);
1243     }
1244     else
1245         needlen = GetEnvironmentVariableA(name,NULL,0);
1246     if (needlen != 0) {
1247         curitem = sv_2mortal(newSVpvn("", 0));
1248         if (USING_WIDE()) {
1249             SV *acuritem;
1250             do {
1251                 SvGROW(curitem, (needlen+1)*sizeof(WCHAR));
1252                 needlen = GetEnvironmentVariableW(wBuffer,
1253                                                   (WCHAR*)SvPVX(curitem),
1254                                                   needlen);
1255             } while (needlen >= SvLEN(curitem)/sizeof(WCHAR));
1256             SvCUR_set(curitem, (needlen*sizeof(WCHAR))+1);
1257             acuritem = sv_2mortal(newSVsv(curitem));
1258             W2AHELPER((WCHAR*)SvPVX(acuritem), SvPVX(curitem), SvCUR(curitem));
1259         }
1260         else {
1261             do {
1262                 SvGROW(curitem, needlen+1);
1263                 needlen = GetEnvironmentVariableA(name,SvPVX(curitem),
1264                                                   needlen);
1265             } while (needlen >= SvLEN(curitem));
1266             SvCUR_set(curitem, needlen);
1267         }
1268     }
1269     else {
1270         /* allow any environment variables that begin with 'PERL'
1271            to be stored in the registry */
1272         if (strncmp(name, "PERL", 4) == 0)
1273             (void)get_regstr(name, &curitem);
1274     }
1275     if (curitem && SvCUR(curitem))
1276         return SvPVX(curitem);
1277
1278     return Nullch;
1279 }
1280
1281 DllExport int
1282 win32_putenv(const char *name)
1283 {
1284     dTHXo;
1285     char* curitem;
1286     char* val;
1287     WCHAR* wCuritem;
1288     WCHAR* wVal;
1289     int length, relval = -1;
1290
1291     if (name) {
1292         if (USING_WIDE()) {
1293             length = strlen(name)+1;
1294             New(1309,wCuritem,length,WCHAR);
1295             A2WHELPER(name, wCuritem, length*sizeof(WCHAR));
1296             wVal = wcschr(wCuritem, '=');
1297             if (wVal) {
1298                 *wVal++ = '\0';
1299                 if (SetEnvironmentVariableW(wCuritem, *wVal ? wVal : NULL))
1300                     relval = 0;
1301             }
1302             Safefree(wCuritem);
1303         }
1304         else {
1305             New(1309,curitem,strlen(name)+1,char);
1306             strcpy(curitem, name);
1307             val = strchr(curitem, '=');
1308             if (val) {
1309                 /* The sane way to deal with the environment.
1310                  * Has these advantages over putenv() & co.:
1311                  *  * enables us to store a truly empty value in the
1312                  *    environment (like in UNIX).
1313                  *  * we don't have to deal with RTL globals, bugs and leaks.
1314                  *  * Much faster.
1315                  * Why you may want to enable USE_WIN32_RTL_ENV:
1316                  *  * environ[] and RTL functions will not reflect changes,
1317                  *    which might be an issue if extensions want to access
1318                  *    the env. via RTL.  This cuts both ways, since RTL will
1319                  *    not see changes made by extensions that call the Win32
1320                  *    functions directly, either.
1321                  * GSAR 97-06-07
1322                  */
1323                 *val++ = '\0';
1324                 if (SetEnvironmentVariableA(curitem, *val ? val : NULL))
1325                     relval = 0;
1326             }
1327             Safefree(curitem);
1328         }
1329     }
1330     return relval;
1331 }
1332
1333 #endif
1334
1335 static long
1336 filetime_to_clock(PFILETIME ft)
1337 {
1338     __int64 qw = ft->dwHighDateTime;
1339     qw <<= 32;
1340     qw |= ft->dwLowDateTime;
1341     qw /= 10000;  /* File time ticks at 0.1uS, clock at 1mS */
1342     return (long) qw;
1343 }
1344
1345 DllExport int
1346 win32_times(struct tms *timebuf)
1347 {
1348     FILETIME user;
1349     FILETIME kernel;
1350     FILETIME dummy;
1351     if (GetProcessTimes(GetCurrentProcess(), &dummy, &dummy, 
1352                         &kernel,&user)) {
1353         timebuf->tms_utime = filetime_to_clock(&user);
1354         timebuf->tms_stime = filetime_to_clock(&kernel);
1355         timebuf->tms_cutime = 0;
1356         timebuf->tms_cstime = 0;
1357         
1358     } else { 
1359         /* That failed - e.g. Win95 fallback to clock() */
1360         clock_t t = clock();
1361         timebuf->tms_utime = t;
1362         timebuf->tms_stime = 0;
1363         timebuf->tms_cutime = 0;
1364         timebuf->tms_cstime = 0;
1365     }
1366     return 0;
1367 }
1368
1369 /* fix utime() so it works on directories in NT */
1370 static BOOL
1371 filetime_from_time(PFILETIME pFileTime, time_t Time)
1372 {
1373     struct tm *pTM = localtime(&Time);
1374     SYSTEMTIME SystemTime;
1375     FILETIME LocalTime;
1376
1377     if (pTM == NULL)
1378         return FALSE;
1379
1380     SystemTime.wYear   = pTM->tm_year + 1900;
1381     SystemTime.wMonth  = pTM->tm_mon + 1;
1382     SystemTime.wDay    = pTM->tm_mday;
1383     SystemTime.wHour   = pTM->tm_hour;
1384     SystemTime.wMinute = pTM->tm_min;
1385     SystemTime.wSecond = pTM->tm_sec;
1386     SystemTime.wMilliseconds = 0;
1387
1388     return SystemTimeToFileTime(&SystemTime, &LocalTime) &&
1389            LocalFileTimeToFileTime(&LocalTime, pFileTime);
1390 }
1391
1392 DllExport int
1393 win32_unlink(const char *filename)
1394 {
1395     dTHXo;
1396     int ret;
1397     DWORD attrs;
1398
1399     if (USING_WIDE()) {
1400         WCHAR wBuffer[MAX_PATH+1];
1401         WCHAR* pwBuffer;
1402
1403         A2WHELPER(filename, wBuffer, sizeof(wBuffer));
1404         pwBuffer = PerlDir_mapW(wBuffer);
1405         attrs = GetFileAttributesW(pwBuffer);
1406         if (attrs == 0xFFFFFFFF)
1407             goto fail;
1408         if (attrs & FILE_ATTRIBUTE_READONLY) {
1409             (void)SetFileAttributesW(pwBuffer, attrs & ~FILE_ATTRIBUTE_READONLY);
1410             ret = _wunlink(pwBuffer);
1411             if (ret == -1)
1412                 (void)SetFileAttributesW(pwBuffer, attrs);
1413         }
1414         else
1415             ret = _wunlink(pwBuffer);
1416     }
1417     else {
1418         filename = PerlDir_mapA(filename);
1419         attrs = GetFileAttributesA(filename);
1420         if (attrs == 0xFFFFFFFF)
1421             goto fail;
1422         if (attrs & FILE_ATTRIBUTE_READONLY) {
1423             (void)SetFileAttributesA(filename, attrs & ~FILE_ATTRIBUTE_READONLY);
1424             ret = unlink(filename);
1425             if (ret == -1)
1426                 (void)SetFileAttributesA(filename, attrs);
1427         }
1428         else
1429             ret = unlink(filename);
1430     }
1431     return ret;
1432 fail:
1433     errno = ENOENT;
1434     return -1;
1435 }
1436
1437 DllExport int
1438 win32_utime(const char *filename, struct utimbuf *times)
1439 {
1440     dTHXo;
1441     HANDLE handle;
1442     FILETIME ftCreate;
1443     FILETIME ftAccess;
1444     FILETIME ftWrite;
1445     struct utimbuf TimeBuffer;
1446     WCHAR wbuffer[MAX_PATH+1];
1447     WCHAR* pwbuffer;
1448
1449     int rc;
1450     if (USING_WIDE()) {
1451         A2WHELPER(filename, wbuffer, sizeof(wbuffer));
1452         pwbuffer = PerlDir_mapW(wbuffer);
1453         rc = _wutime(pwbuffer, (struct _utimbuf*)times);
1454     }
1455     else {
1456         filename = PerlDir_mapA(filename);
1457         rc = utime(filename, times);
1458     }
1459     /* EACCES: path specifies directory or readonly file */
1460     if (rc == 0 || errno != EACCES /* || !IsWinNT() */)
1461         return rc;
1462
1463     if (times == NULL) {
1464         times = &TimeBuffer;
1465         time(&times->actime);
1466         times->modtime = times->actime;
1467     }
1468
1469     /* This will (and should) still fail on readonly files */
1470     if (USING_WIDE()) {
1471         handle = CreateFileW(pwbuffer, GENERIC_READ | GENERIC_WRITE,
1472                             FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1473                             OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1474     }
1475     else {
1476         handle = CreateFileA(filename, GENERIC_READ | GENERIC_WRITE,
1477                             FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1478                             OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1479     }
1480     if (handle == INVALID_HANDLE_VALUE)
1481         return rc;
1482
1483     if (GetFileTime(handle, &ftCreate, &ftAccess, &ftWrite) &&
1484         filetime_from_time(&ftAccess, times->actime) &&
1485         filetime_from_time(&ftWrite, times->modtime) &&
1486         SetFileTime(handle, &ftCreate, &ftAccess, &ftWrite))
1487     {
1488         rc = 0;
1489     }
1490
1491     CloseHandle(handle);
1492     return rc;
1493 }
1494
1495 DllExport int
1496 win32_uname(struct utsname *name)
1497 {
1498     struct hostent *hep;
1499     STRLEN nodemax = sizeof(name->nodename)-1;
1500     OSVERSIONINFO osver;
1501
1502     memset(&osver, 0, sizeof(OSVERSIONINFO));
1503     osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1504     if (GetVersionEx(&osver)) {
1505         /* sysname */
1506         switch (osver.dwPlatformId) {
1507         case VER_PLATFORM_WIN32_WINDOWS:
1508             strcpy(name->sysname, "Windows");
1509             break;
1510         case VER_PLATFORM_WIN32_NT:
1511             strcpy(name->sysname, "Windows NT");
1512             break;
1513         case VER_PLATFORM_WIN32s:
1514             strcpy(name->sysname, "Win32s");
1515             break;
1516         default:
1517             strcpy(name->sysname, "Win32 Unknown");
1518             break;
1519         }
1520
1521         /* release */
1522         sprintf(name->release, "%d.%d",
1523                 osver.dwMajorVersion, osver.dwMinorVersion);
1524
1525         /* version */
1526         sprintf(name->version, "Build %d",
1527                 osver.dwPlatformId == VER_PLATFORM_WIN32_NT
1528                 ? osver.dwBuildNumber : (osver.dwBuildNumber & 0xffff));
1529         if (osver.szCSDVersion[0]) {
1530             char *buf = name->version + strlen(name->version);
1531             sprintf(buf, " (%s)", osver.szCSDVersion);
1532         }
1533     }
1534     else {
1535         *name->sysname = '\0';
1536         *name->version = '\0';
1537         *name->release = '\0';
1538     }
1539
1540     /* nodename */
1541     hep = win32_gethostbyname("localhost");
1542     if (hep) {
1543         STRLEN len = strlen(hep->h_name);
1544         if (len <= nodemax) {
1545             strcpy(name->nodename, hep->h_name);
1546         }
1547         else {
1548             strncpy(name->nodename, hep->h_name, nodemax);
1549             name->nodename[nodemax] = '\0';
1550         }
1551     }
1552     else {
1553         DWORD sz = nodemax;
1554         if (!GetComputerName(name->nodename, &sz))
1555             *name->nodename = '\0';
1556     }
1557
1558     /* machine (architecture) */
1559     {
1560         SYSTEM_INFO info;
1561         char *arch;
1562         GetSystemInfo(&info);
1563
1564 #if defined(__BORLANDC__) || defined(__MINGW32__)
1565         switch (info.u.s.wProcessorArchitecture) {
1566 #else
1567         switch (info.wProcessorArchitecture) {
1568 #endif
1569         case PROCESSOR_ARCHITECTURE_INTEL:
1570             arch = "x86"; break;
1571         case PROCESSOR_ARCHITECTURE_MIPS:
1572             arch = "mips"; break;
1573         case PROCESSOR_ARCHITECTURE_ALPHA:
1574             arch = "alpha"; break;
1575         case PROCESSOR_ARCHITECTURE_PPC:
1576             arch = "ppc"; break;
1577         default:
1578             arch = "unknown"; break;
1579         }
1580         strcpy(name->machine, arch);
1581     }
1582     return 0;
1583 }
1584
1585 DllExport int
1586 win32_waitpid(int pid, int *status, int flags)
1587 {
1588     dTHXo;
1589     int retval = -1;
1590     if (pid == -1)                              /* XXX threadid == 1 ? */
1591         return win32_wait(status);
1592 #ifdef USE_ITHREADS
1593     else if (pid < 0) {
1594         long child = find_pseudo_pid(-pid);
1595         if (child >= 0) {
1596             HANDLE hThread = w32_pseudo_child_handles[child];
1597             DWORD waitcode = WaitForSingleObject(hThread, INFINITE);
1598             if (waitcode != WAIT_FAILED) {
1599                 if (GetExitCodeThread(hThread, &waitcode)) {
1600                     *status = (int)((waitcode & 0xff) << 8);
1601                     retval = (int)w32_pseudo_child_pids[child];
1602                     remove_dead_pseudo_process(child);
1603                     return retval;
1604                 }
1605             }
1606             else
1607                 errno = ECHILD;
1608         }
1609     }
1610 #endif
1611     else {
1612         long child = find_pid(pid);
1613         if (child >= 0) {
1614             HANDLE hProcess = w32_child_handles[child];
1615             DWORD waitcode = WaitForSingleObject(hProcess, INFINITE);
1616             if (waitcode != WAIT_FAILED) {
1617                 if (GetExitCodeProcess(hProcess, &waitcode)) {
1618                     *status = (int)((waitcode & 0xff) << 8);
1619                     retval = (int)w32_child_pids[child];
1620                     remove_dead_process(child);
1621                     return retval;
1622                 }
1623             }
1624             else
1625                 errno = ECHILD;
1626         }
1627         else {
1628             retval = cwait(status, pid, WAIT_CHILD);
1629             /* cwait() returns "correctly" on Borland */
1630 #ifndef __BORLANDC__
1631             if (status)
1632                 *status *= 256;
1633 #endif
1634         }
1635     }
1636     return retval >= 0 ? pid : retval;                
1637 }
1638
1639 DllExport int
1640 win32_wait(int *status)
1641 {
1642     /* XXX this wait emulation only knows about processes
1643      * spawned via win32_spawnvp(P_NOWAIT, ...).
1644      */
1645     dTHXo;
1646     int i, retval;
1647     DWORD exitcode, waitcode;
1648
1649 #ifdef USE_ITHREADS
1650     if (w32_num_pseudo_children) {
1651         waitcode = WaitForMultipleObjects(w32_num_pseudo_children,
1652                                           w32_pseudo_child_handles,
1653                                           FALSE,
1654                                           INFINITE);
1655         if (waitcode != WAIT_FAILED) {
1656             if (waitcode >= WAIT_ABANDONED_0
1657                 && waitcode < WAIT_ABANDONED_0 + w32_num_pseudo_children)
1658                 i = waitcode - WAIT_ABANDONED_0;
1659             else
1660                 i = waitcode - WAIT_OBJECT_0;
1661             if (GetExitCodeThread(w32_pseudo_child_handles[i], &exitcode)) {
1662                 *status = (int)((exitcode & 0xff) << 8);
1663                 retval = (int)w32_pseudo_child_pids[i];
1664                 remove_dead_pseudo_process(i);
1665                 return retval;
1666             }
1667         }
1668     }
1669 #endif
1670
1671     if (!w32_num_children) {
1672         errno = ECHILD;
1673         return -1;
1674     }
1675
1676     /* if a child exists, wait for it to die */
1677     waitcode = WaitForMultipleObjects(w32_num_children,
1678                                       w32_child_handles,
1679                                       FALSE,
1680                                       INFINITE);
1681     if (waitcode != WAIT_FAILED) {
1682         if (waitcode >= WAIT_ABANDONED_0
1683             && waitcode < WAIT_ABANDONED_0 + w32_num_children)
1684             i = waitcode - WAIT_ABANDONED_0;
1685         else
1686             i = waitcode - WAIT_OBJECT_0;
1687         if (GetExitCodeProcess(w32_child_handles[i], &exitcode) ) {
1688             *status = (int)((exitcode & 0xff) << 8);
1689             retval = (int)w32_child_pids[i];
1690             remove_dead_process(i);
1691             return retval;
1692         }
1693     }
1694
1695 FAILED:
1696     errno = GetLastError();
1697     return -1;
1698 }
1699
1700 #ifndef PERL_OBJECT
1701
1702 static UINT timerid = 0;
1703
1704 static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
1705 {
1706     dTHXo;
1707     KillTimer(NULL,timerid);
1708     timerid=0;  
1709     sighandler(14);
1710 }
1711 #endif  /* !PERL_OBJECT */
1712
1713 DllExport unsigned int
1714 win32_alarm(unsigned int sec)
1715 {
1716 #ifndef PERL_OBJECT
1717     /* 
1718      * the 'obvious' implentation is SetTimer() with a callback
1719      * which does whatever receiving SIGALRM would do 
1720      * we cannot use SIGALRM even via raise() as it is not 
1721      * one of the supported codes in <signal.h>
1722      *
1723      * Snag is unless something is looking at the message queue
1724      * nothing happens :-(
1725      */ 
1726     dTHXo;
1727     if (sec)
1728      {
1729       timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
1730       if (!timerid)
1731        Perl_croak_nocontext("Cannot set timer");
1732      } 
1733     else
1734      {
1735       if (timerid)
1736        {
1737         KillTimer(NULL,timerid);
1738         timerid=0;  
1739        }
1740      }
1741 #endif  /* !PERL_OBJECT */
1742     return 0;
1743 }
1744
1745 #ifdef HAVE_DES_FCRYPT
1746 extern char *   des_fcrypt(const char *txt, const char *salt, char *cbuf);
1747 #endif
1748
1749 DllExport char *
1750 win32_crypt(const char *txt, const char *salt)
1751 {
1752     dTHXo;
1753 #ifdef HAVE_DES_FCRYPT
1754     dTHR;
1755     return des_fcrypt(txt, salt, w32_crypt_buffer);
1756 #else
1757     Perl_croak(aTHX_ "The crypt() function is unimplemented due to excessive paranoia.");
1758     return Nullch;
1759 #endif
1760 }
1761
1762 /* C doesn't like repeat struct definitions */
1763
1764 #if defined(USE_FIXED_OSFHANDLE) || defined(PERL_MSVCRT_READFIX)
1765
1766 #ifndef _CRTIMP
1767 #define _CRTIMP __declspec(dllimport)
1768 #endif
1769
1770 /*
1771  * Control structure for lowio file handles
1772  */
1773 typedef struct {
1774     long osfhnd;    /* underlying OS file HANDLE */
1775     char osfile;    /* attributes of file (e.g., open in text mode?) */
1776     char pipech;    /* one char buffer for handles opened on pipes */
1777     int lockinitflag;
1778     CRITICAL_SECTION lock;
1779 } ioinfo;
1780
1781
1782 /*
1783  * Array of arrays of control structures for lowio files.
1784  */
1785 EXTERN_C _CRTIMP ioinfo* __pioinfo[];
1786
1787 /*
1788  * Definition of IOINFO_L2E, the log base 2 of the number of elements in each
1789  * array of ioinfo structs.
1790  */
1791 #define IOINFO_L2E          5
1792
1793 /*
1794  * Definition of IOINFO_ARRAY_ELTS, the number of elements in ioinfo array
1795  */
1796 #define IOINFO_ARRAY_ELTS   (1 << IOINFO_L2E)
1797
1798 /*
1799  * Access macros for getting at an ioinfo struct and its fields from a
1800  * file handle
1801  */
1802 #define _pioinfo(i) (__pioinfo[(i) >> IOINFO_L2E] + ((i) & (IOINFO_ARRAY_ELTS - 1)))
1803 #define _osfhnd(i)  (_pioinfo(i)->osfhnd)
1804 #define _osfile(i)  (_pioinfo(i)->osfile)
1805 #define _pipech(i)  (_pioinfo(i)->pipech)
1806
1807 #endif
1808
1809 #ifdef USE_FIXED_OSFHANDLE
1810
1811 #define FOPEN                   0x01    /* file handle open */
1812 #define FNOINHERIT              0x10    /* file handle opened O_NOINHERIT */
1813 #define FAPPEND                 0x20    /* file handle opened O_APPEND */
1814 #define FDEV                    0x40    /* file handle refers to device */
1815 #define FTEXT                   0x80    /* file handle is in text mode */
1816
1817 /***
1818 *int my_open_osfhandle(long osfhandle, int flags) - open C Runtime file handle
1819 *
1820 *Purpose:
1821 *       This function allocates a free C Runtime file handle and associates
1822 *       it with the Win32 HANDLE specified by the first parameter. This is a
1823 *       temperary fix for WIN95's brain damage GetFileType() error on socket
1824 *       we just bypass that call for socket
1825 *
1826 *       This works with MSVC++ 4.0+ or GCC/Mingw32
1827 *
1828 *Entry:
1829 *       long osfhandle - Win32 HANDLE to associate with C Runtime file handle.
1830 *       int flags      - flags to associate with C Runtime file handle.
1831 *
1832 *Exit:
1833 *       returns index of entry in fh, if successful
1834 *       return -1, if no free entry is found
1835 *
1836 *Exceptions:
1837 *
1838 *******************************************************************************/
1839
1840 /*
1841  * we fake up some parts of the CRT that aren't exported by MSVCRT.dll
1842  * this lets sockets work on Win9X with GCC and should fix the problems
1843  * with perl95.exe
1844  *      -- BKS, 1-23-2000
1845 */
1846
1847 /* since we are not doing a dup2(), this works fine */
1848
1849 #define _set_osfhnd(fh, osfh) (void)(_osfhnd(fh) = osfh)
1850
1851 /* create an ioinfo entry, kill its handle, and steal the entry */
1852
1853 static int
1854 _alloc_osfhnd(void)
1855 {
1856     HANDLE hF = CreateFile("NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
1857     int fh = _open_osfhandle((long)hF, 0);
1858     CloseHandle(hF);
1859     if (fh == -1)
1860         return fh;
1861     EnterCriticalSection(&(_pioinfo(fh)->lock));
1862     return fh;
1863 }
1864
1865 static int
1866 my_open_osfhandle(long osfhandle, int flags)
1867 {
1868     int fh;
1869     char fileflags;             /* _osfile flags */
1870
1871     /* copy relevant flags from second parameter */
1872     fileflags = FDEV;
1873
1874     if (flags & O_APPEND)
1875         fileflags |= FAPPEND;
1876
1877     if (flags & O_TEXT)
1878         fileflags |= FTEXT;
1879
1880     if (flags & O_NOINHERIT)
1881         fileflags |= FNOINHERIT;
1882
1883     /* attempt to allocate a C Runtime file handle */
1884     if ((fh = _alloc_osfhnd()) == -1) {
1885         errno = EMFILE;         /* too many open files */
1886         _doserrno = 0L;         /* not an OS error */
1887         return -1;              /* return error to caller */
1888     }
1889
1890     /* the file is open. now, set the info in _osfhnd array */
1891     _set_osfhnd(fh, osfhandle);
1892
1893     fileflags |= FOPEN;         /* mark as open */
1894
1895     _osfile(fh) = fileflags;    /* set osfile entry */
1896     LeaveCriticalSection(&_pioinfo(fh)->lock);
1897
1898     return fh;                  /* return handle */
1899 }
1900
1901 #endif  /* USE_FIXED_OSFHANDLE */
1902
1903 /* simulate flock by locking a range on the file */
1904
1905 #define LK_ERR(f,i)     ((f) ? (i = 0) : (errno = GetLastError()))
1906 #define LK_LEN          0xffff0000
1907
1908 DllExport int
1909 win32_flock(int fd, int oper)
1910 {
1911     OVERLAPPED o;
1912     int i = -1;
1913     HANDLE fh;
1914
1915     if (!IsWinNT()) {
1916         dTHXo;
1917         Perl_croak_nocontext("flock() unimplemented on this platform");
1918         return -1;
1919     }
1920     fh = (HANDLE)_get_osfhandle(fd);
1921     memset(&o, 0, sizeof(o));
1922
1923     switch(oper) {
1924     case LOCK_SH:               /* shared lock */
1925         LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
1926         break;
1927     case LOCK_EX:               /* exclusive lock */
1928         LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
1929         break;
1930     case LOCK_SH|LOCK_NB:       /* non-blocking shared lock */
1931         LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
1932         break;
1933     case LOCK_EX|LOCK_NB:       /* non-blocking exclusive lock */
1934         LK_ERR(LockFileEx(fh,
1935                        LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
1936                        0, LK_LEN, 0, &o),i);
1937         break;
1938     case LOCK_UN:               /* unlock lock */
1939         LK_ERR(UnlockFileEx(fh, 0, LK_LEN, 0, &o),i);
1940         break;
1941     default:                    /* unknown */
1942         errno = EINVAL;
1943         break;
1944     }
1945     return i;
1946 }
1947
1948 #undef LK_ERR
1949 #undef LK_LEN
1950
1951 /*
1952  *  redirected io subsystem for all XS modules
1953  *
1954  */
1955
1956 DllExport int *
1957 win32_errno(void)
1958 {
1959     return (&errno);
1960 }
1961
1962 DllExport char ***
1963 win32_environ(void)
1964 {
1965     return (&(_environ));
1966 }
1967
1968 /* the rest are the remapped stdio routines */
1969 DllExport FILE *
1970 win32_stderr(void)
1971 {
1972     return (stderr);
1973 }
1974
1975 DllExport FILE *
1976 win32_stdin(void)
1977 {
1978     return (stdin);
1979 }
1980
1981 DllExport FILE *
1982 win32_stdout()
1983 {
1984     return (stdout);
1985 }
1986
1987 DllExport int
1988 win32_ferror(FILE *fp)
1989 {
1990     return (ferror(fp));
1991 }
1992
1993
1994 DllExport int
1995 win32_feof(FILE *fp)
1996 {
1997     return (feof(fp));
1998 }
1999
2000 /*
2001  * Since the errors returned by the socket error function 
2002  * WSAGetLastError() are not known by the library routine strerror
2003  * we have to roll our own.
2004  */
2005
2006 DllExport char *
2007 win32_strerror(int e) 
2008 {
2009 #ifndef __BORLANDC__            /* Borland intolerance */
2010     extern int sys_nerr;
2011 #endif
2012     DWORD source = 0;
2013
2014     if (e < 0 || e > sys_nerr) {
2015         dTHXo;
2016         if (e < 0)
2017             e = GetLastError();
2018
2019         if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
2020                           w32_strerror_buffer,
2021                           sizeof(w32_strerror_buffer), NULL) == 0) 
2022             strcpy(w32_strerror_buffer, "Unknown Error");
2023
2024         return w32_strerror_buffer;
2025     }
2026     return strerror(e);
2027 }
2028
2029 DllExport void
2030 win32_str_os_error(void *sv, DWORD dwErr)
2031 {
2032     DWORD dwLen;
2033     char *sMsg;
2034     dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
2035                           |FORMAT_MESSAGE_IGNORE_INSERTS
2036                           |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
2037                            dwErr, 0, (char *)&sMsg, 1, NULL);
2038     /* strip trailing whitespace and period */
2039     if (0 < dwLen) {
2040         do {
2041             --dwLen;    /* dwLen doesn't include trailing null */
2042         } while (0 < dwLen && isSPACE(sMsg[dwLen]));
2043         if ('.' != sMsg[dwLen])
2044             dwLen++;
2045         sMsg[dwLen] = '\0';
2046     }
2047     if (0 == dwLen) {
2048         sMsg = (char*)LocalAlloc(0, 64/**sizeof(TCHAR)*/);
2049         if (sMsg)
2050             dwLen = sprintf(sMsg,
2051                             "Unknown error #0x%lX (lookup 0x%lX)",
2052                             dwErr, GetLastError());
2053     }
2054     if (sMsg) {
2055         dTHXo;
2056         sv_setpvn((SV*)sv, sMsg, dwLen);
2057         LocalFree(sMsg);
2058     }
2059 }
2060
2061
2062 DllExport int
2063 win32_fprintf(FILE *fp, const char *format, ...)
2064 {
2065     va_list marker;
2066     va_start(marker, format);     /* Initialize variable arguments. */
2067
2068     return (vfprintf(fp, format, marker));
2069 }
2070
2071 DllExport int
2072 win32_printf(const char *format, ...)
2073 {
2074     va_list marker;
2075     va_start(marker, format);     /* Initialize variable arguments. */
2076
2077     return (vprintf(format, marker));
2078 }
2079
2080 DllExport int
2081 win32_vfprintf(FILE *fp, const char *format, va_list args)
2082 {
2083     return (vfprintf(fp, format, args));
2084 }
2085
2086 DllExport int
2087 win32_vprintf(const char *format, va_list args)
2088 {
2089     return (vprintf(format, args));
2090 }
2091
2092 DllExport size_t
2093 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
2094 {
2095     return fread(buf, size, count, fp);
2096 }
2097
2098 DllExport size_t
2099 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
2100 {
2101     return fwrite(buf, size, count, fp);
2102 }
2103
2104 #define MODE_SIZE 10
2105
2106 DllExport FILE *
2107 win32_fopen(const char *filename, const char *mode)
2108 {
2109     dTHXo;
2110     WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH+1];
2111     FILE *f;
2112     
2113     if (!*filename)
2114         return NULL;
2115
2116     if (stricmp(filename, "/dev/null")==0)
2117         filename = "NUL";
2118
2119     if (USING_WIDE()) {
2120         A2WHELPER(mode, wMode, sizeof(wMode));
2121         A2WHELPER(filename, wBuffer, sizeof(wBuffer));
2122         f = _wfopen(PerlDir_mapW(wBuffer), wMode);
2123     }
2124     else
2125         f = fopen(PerlDir_mapA(filename), mode);
2126     /* avoid buffering headaches for child processes */
2127     if (f && *mode == 'a')
2128         win32_fseek(f, 0, SEEK_END);
2129     return f;
2130 }
2131
2132 #ifndef USE_SOCKETS_AS_HANDLES
2133 #undef fdopen
2134 #define fdopen my_fdopen
2135 #endif
2136
2137 DllExport FILE *
2138 win32_fdopen(int handle, const char *mode)
2139 {
2140     dTHXo;
2141     WCHAR wMode[MODE_SIZE];
2142     FILE *f;
2143     if (USING_WIDE()) {
2144         A2WHELPER(mode, wMode, sizeof(wMode));
2145         f = _wfdopen(handle, wMode);
2146     }
2147     else
2148         f = fdopen(handle, (char *) mode);
2149     /* avoid buffering headaches for child processes */
2150     if (f && *mode == 'a')
2151         win32_fseek(f, 0, SEEK_END);
2152     return f;
2153 }
2154
2155 DllExport FILE *
2156 win32_freopen(const char *path, const char *mode, FILE *stream)
2157 {
2158     dTHXo;
2159     WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH+1];
2160     if (stricmp(path, "/dev/null")==0)
2161         path = "NUL";
2162
2163     if (USING_WIDE()) {
2164         A2WHELPER(mode, wMode, sizeof(wMode));
2165         A2WHELPER(path, wBuffer, sizeof(wBuffer));
2166         return _wfreopen(PerlDir_mapW(wBuffer), wMode, stream);
2167     }
2168     return freopen(PerlDir_mapA(path), mode, stream);
2169 }
2170
2171 DllExport int
2172 win32_fclose(FILE *pf)
2173 {
2174     return my_fclose(pf);       /* defined in win32sck.c */
2175 }
2176
2177 DllExport int
2178 win32_fputs(const char *s,FILE *pf)
2179 {
2180     return fputs(s, pf);
2181 }
2182
2183 DllExport int
2184 win32_fputc(int c,FILE *pf)
2185 {
2186     return fputc(c,pf);
2187 }
2188
2189 DllExport int
2190 win32_ungetc(int c,FILE *pf)
2191 {
2192     return ungetc(c,pf);
2193 }
2194
2195 DllExport int
2196 win32_getc(FILE *pf)
2197 {
2198     return getc(pf);
2199 }
2200
2201 DllExport int
2202 win32_fileno(FILE *pf)
2203 {
2204     return fileno(pf);
2205 }
2206
2207 DllExport void
2208 win32_clearerr(FILE *pf)
2209 {
2210     clearerr(pf);
2211     return;
2212 }
2213
2214 DllExport int
2215 win32_fflush(FILE *pf)
2216 {
2217     return fflush(pf);
2218 }
2219
2220 DllExport long
2221 win32_ftell(FILE *pf)
2222 {
2223     return ftell(pf);
2224 }
2225
2226 DllExport int
2227 win32_fseek(FILE *pf,long offset,int origin)
2228 {
2229     return fseek(pf, offset, origin);
2230 }
2231
2232 DllExport int
2233 win32_fgetpos(FILE *pf,fpos_t *p)
2234 {
2235     return fgetpos(pf, p);
2236 }
2237
2238 DllExport int
2239 win32_fsetpos(FILE *pf,const fpos_t *p)
2240 {
2241     return fsetpos(pf, p);
2242 }
2243
2244 DllExport void
2245 win32_rewind(FILE *pf)
2246 {
2247     rewind(pf);
2248     return;
2249 }
2250
2251 DllExport FILE*
2252 win32_tmpfile(void)
2253 {
2254     return tmpfile();
2255 }
2256
2257 DllExport void
2258 win32_abort(void)
2259 {
2260     abort();
2261     return;
2262 }
2263
2264 DllExport int
2265 win32_fstat(int fd,struct stat *sbufptr)
2266 {
2267     return fstat(fd,sbufptr);
2268 }
2269
2270 DllExport int
2271 win32_pipe(int *pfd, unsigned int size, int mode)
2272 {
2273     return _pipe(pfd, size, mode);
2274 }
2275
2276 /*
2277  * a popen() clone that respects PERL5SHELL
2278  */
2279
2280 DllExport FILE*
2281 win32_popen(const char *command, const char *mode)
2282 {
2283 #ifdef USE_RTL_POPEN
2284     return _popen(command, mode);
2285 #else
2286     int p[2];
2287     int parent, child;
2288     int stdfd, oldfd;
2289     int ourmode;
2290     int childpid;
2291
2292     /* establish which ends read and write */
2293     if (strchr(mode,'w')) {
2294         stdfd = 0;              /* stdin */
2295         parent = 1;
2296         child = 0;
2297     }
2298     else if (strchr(mode,'r')) {
2299         stdfd = 1;              /* stdout */
2300         parent = 0;
2301         child = 1;
2302     }
2303     else
2304         return NULL;
2305
2306     /* set the correct mode */
2307     if (strchr(mode,'b'))
2308         ourmode = O_BINARY;
2309     else if (strchr(mode,'t'))
2310         ourmode = O_TEXT;
2311     else
2312         ourmode = _fmode & (O_TEXT | O_BINARY);
2313
2314     /* the child doesn't inherit handles */
2315     ourmode |= O_NOINHERIT;
2316
2317     if (win32_pipe( p, 512, ourmode) == -1)
2318         return NULL;
2319
2320     /* save current stdfd */
2321     if ((oldfd = win32_dup(stdfd)) == -1)
2322         goto cleanup;
2323
2324     /* make stdfd go to child end of pipe (implicitly closes stdfd) */
2325     /* stdfd will be inherited by the child */
2326     if (win32_dup2(p[child], stdfd) == -1)
2327         goto cleanup;
2328
2329     /* close the child end in parent */
2330     win32_close(p[child]);
2331
2332     /* start the child */
2333     {
2334         dTHXo;
2335         if ((childpid = do_spawn_nowait((char*)command)) == -1)
2336             goto cleanup;
2337
2338         /* revert stdfd to whatever it was before */
2339         if (win32_dup2(oldfd, stdfd) == -1)
2340             goto cleanup;
2341
2342         /* close saved handle */
2343         win32_close(oldfd);
2344
2345         sv_setiv(*av_fetch(w32_fdpid, p[parent], TRUE), childpid);
2346
2347         /* set process id so that it can be returned by perl's open() */
2348         PL_forkprocess = childpid;
2349     }
2350
2351     /* we have an fd, return a file stream */
2352     return (win32_fdopen(p[parent], (char *)mode));
2353
2354 cleanup:
2355     /* we don't need to check for errors here */
2356     win32_close(p[0]);
2357     win32_close(p[1]);
2358     if (oldfd != -1) {
2359         win32_dup2(oldfd, stdfd);
2360         win32_close(oldfd);
2361     }
2362     return (NULL);
2363
2364 #endif /* USE_RTL_POPEN */
2365 }
2366
2367 /*
2368  * pclose() clone
2369  */
2370
2371 DllExport int
2372 win32_pclose(FILE *pf)
2373 {
2374 #ifdef USE_RTL_POPEN
2375     return _pclose(pf);
2376 #else
2377     dTHXo;
2378     int childpid, status;
2379     SV *sv;
2380
2381     sv = *av_fetch(w32_fdpid, win32_fileno(pf), TRUE);
2382     if (SvIOK(sv))
2383         childpid = SvIVX(sv);
2384     else
2385         childpid = 0;
2386
2387     if (!childpid) {
2388         errno = EBADF;
2389         return -1;
2390     }
2391
2392     win32_fclose(pf);
2393     SvIVX(sv) = 0;
2394
2395     if (win32_waitpid(childpid, &status, 0) == -1)
2396         return -1;
2397
2398     return status;
2399
2400 #endif /* USE_RTL_POPEN */
2401 }
2402
2403 static BOOL WINAPI
2404 Nt4CreateHardLinkW(
2405     LPCWSTR lpFileName,
2406     LPCWSTR lpExistingFileName,
2407     LPSECURITY_ATTRIBUTES lpSecurityAttributes)
2408 {
2409     HANDLE handle;
2410     WCHAR wFullName[MAX_PATH+1];
2411     LPVOID lpContext = NULL;
2412     WIN32_STREAM_ID StreamId;
2413     DWORD dwSize = (char*)&StreamId.cStreamName - (char*)&StreamId;
2414     DWORD dwWritten;
2415     DWORD dwLen;
2416     BOOL bSuccess;
2417
2418     BOOL (__stdcall *pfnBackupWrite)(HANDLE, LPBYTE, DWORD, LPDWORD,
2419                                      BOOL, BOOL, LPVOID*) =
2420         (BOOL (__stdcall *)(HANDLE, LPBYTE, DWORD, LPDWORD,
2421                             BOOL, BOOL, LPVOID*))
2422         GetProcAddress(GetModuleHandle("kernel32.dll"), "BackupWrite");
2423     if (pfnBackupWrite == NULL)
2424         return 0;
2425
2426     dwLen = GetFullPathNameW(lpFileName, MAX_PATH, wFullName, NULL);
2427     if (dwLen == 0)
2428         return 0;
2429     dwLen = (dwLen+1)*sizeof(WCHAR);
2430
2431     handle = CreateFileW(lpExistingFileName, FILE_WRITE_ATTRIBUTES,
2432                          FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
2433                          NULL, OPEN_EXISTING, 0, NULL);
2434     if (handle == INVALID_HANDLE_VALUE)
2435         return 0;
2436
2437     StreamId.dwStreamId = BACKUP_LINK;
2438     StreamId.dwStreamAttributes = 0;
2439     StreamId.dwStreamNameSize = 0;
2440 #if defined(__BORLANDC__) || defined(__MINGW32__)
2441     StreamId.Size.u.HighPart = 0;
2442     StreamId.Size.u.LowPart = dwLen;
2443 #else
2444     StreamId.Size.HighPart = 0;
2445     StreamId.Size.LowPart = dwLen;
2446 #endif
2447
2448     bSuccess = pfnBackupWrite(handle, (LPBYTE)&StreamId, dwSize, &dwWritten,
2449                               FALSE, FALSE, &lpContext);
2450     if (bSuccess) {
2451         bSuccess = pfnBackupWrite(handle, (LPBYTE)wFullName, dwLen, &dwWritten,
2452                                   FALSE, FALSE, &lpContext);
2453         pfnBackupWrite(handle, NULL, 0, &dwWritten, TRUE, FALSE, &lpContext);
2454     }
2455
2456     CloseHandle(handle);
2457     return bSuccess;
2458 }
2459
2460 DllExport int
2461 win32_link(const char *oldname, const char *newname)
2462 {
2463     dTHXo;
2464     BOOL (__stdcall *pfnCreateHardLinkW)(LPCWSTR,LPCWSTR,LPSECURITY_ATTRIBUTES);
2465     WCHAR wOldName[MAX_PATH+1];
2466     WCHAR wNewName[MAX_PATH+1];
2467
2468     if (IsWin95())
2469         Perl_croak(aTHX_ PL_no_func, "link");
2470
2471     pfnCreateHardLinkW =
2472         (BOOL (__stdcall *)(LPCWSTR, LPCWSTR, LPSECURITY_ATTRIBUTES))
2473         GetProcAddress(GetModuleHandle("kernel32.dll"), "CreateHardLinkW");
2474     if (pfnCreateHardLinkW == NULL)
2475         pfnCreateHardLinkW = Nt4CreateHardLinkW;
2476
2477     if ((A2WHELPER(oldname, wOldName, sizeof(wOldName))) &&
2478         (A2WHELPER(newname, wNewName, sizeof(wNewName))) &&
2479         (wcscpy(wOldName, PerlDir_mapW(wOldName)),
2480         pfnCreateHardLinkW(PerlDir_mapW(wNewName), wOldName, NULL)))
2481     {
2482         return 0;
2483     }
2484     errno = (GetLastError() == ERROR_FILE_NOT_FOUND) ? ENOENT : EINVAL;
2485     return -1;
2486 }
2487
2488 DllExport int
2489 win32_rename(const char *oname, const char *newname)
2490 {
2491     WCHAR wOldName[MAX_PATH+1];
2492     WCHAR wNewName[MAX_PATH+1];
2493     char szOldName[MAX_PATH+1];
2494     char szNewName[MAX_PATH+1];
2495     BOOL bResult;
2496     dTHXo;
2497
2498     /* XXX despite what the documentation says about MoveFileEx(),
2499      * it doesn't work under Windows95!
2500      */
2501     if (IsWinNT()) {
2502         DWORD dwFlags = MOVEFILE_COPY_ALLOWED;
2503         if (USING_WIDE()) {
2504             A2WHELPER(oname, wOldName, sizeof(wOldName));
2505             A2WHELPER(newname, wNewName, sizeof(wNewName));
2506             if (wcsicmp(wNewName, wOldName))
2507                 dwFlags |= MOVEFILE_REPLACE_EXISTING;
2508             wcscpy(wOldName, PerlDir_mapW(wOldName));
2509             bResult = MoveFileExW(wOldName,PerlDir_mapW(wNewName), dwFlags);
2510         }
2511         else {
2512             if (stricmp(newname, oname))
2513                 dwFlags |= MOVEFILE_REPLACE_EXISTING;
2514             strcpy(szOldName, PerlDir_mapA(oname));
2515             bResult = MoveFileExA(szOldName,PerlDir_mapA(newname), dwFlags);
2516         }
2517         if (!bResult) {
2518             DWORD err = GetLastError();
2519             switch (err) {
2520             case ERROR_BAD_NET_NAME:
2521             case ERROR_BAD_NETPATH:
2522             case ERROR_BAD_PATHNAME:
2523             case ERROR_FILE_NOT_FOUND:
2524             case ERROR_FILENAME_EXCED_RANGE:
2525             case ERROR_INVALID_DRIVE:
2526             case ERROR_NO_MORE_FILES:
2527             case ERROR_PATH_NOT_FOUND:
2528                 errno = ENOENT;
2529                 break;
2530             default:
2531                 errno = EACCES;
2532                 break;
2533             }
2534             return -1;
2535         }
2536         return 0;
2537     }
2538     else {
2539         int retval = 0;
2540         char szTmpName[MAX_PATH+1];
2541         char dname[MAX_PATH+1];
2542         char *endname = Nullch;
2543         STRLEN tmplen = 0;
2544         DWORD from_attr, to_attr;
2545
2546         strcpy(szOldName, PerlDir_mapA(oname));
2547         strcpy(szNewName, PerlDir_mapA(newname));
2548
2549         /* if oname doesn't exist, do nothing */
2550         from_attr = GetFileAttributes(szOldName);
2551         if (from_attr == 0xFFFFFFFF) {
2552             errno = ENOENT;
2553             return -1;
2554         }
2555
2556         /* if newname exists, rename it to a temporary name so that we
2557          * don't delete it in case oname happens to be the same file
2558          * (but perhaps accessed via a different path)
2559          */
2560         to_attr = GetFileAttributes(szNewName);
2561         if (to_attr != 0xFFFFFFFF) {
2562             /* if newname is a directory, we fail
2563              * XXX could overcome this with yet more convoluted logic */
2564             if (to_attr & FILE_ATTRIBUTE_DIRECTORY) {
2565                 errno = EACCES;
2566                 return -1;
2567             }
2568             tmplen = strlen(szNewName);
2569             strcpy(szTmpName,szNewName);
2570             endname = szTmpName+tmplen;
2571             for (; endname > szTmpName ; --endname) {
2572                 if (*endname == '/' || *endname == '\\') {
2573                     *endname = '\0';
2574                     break;
2575                 }
2576             }
2577             if (endname > szTmpName)
2578                 endname = strcpy(dname,szTmpName);
2579             else
2580                 endname = ".";
2581
2582             /* get a temporary filename in same directory
2583              * XXX is this really the best we can do? */
2584             if (!GetTempFileName((LPCTSTR)endname, "plr", 0, szTmpName)) {
2585                 errno = ENOENT;
2586                 return -1;
2587             }
2588             DeleteFile(szTmpName);
2589
2590             retval = rename(szNewName, szTmpName);
2591             if (retval != 0) {
2592                 errno = EACCES;
2593                 return retval;
2594             }
2595         }
2596
2597         /* rename oname to newname */
2598         retval = rename(szOldName, szNewName);
2599
2600         /* if we created a temporary file before ... */
2601         if (endname != Nullch) {
2602             /* ...and rename succeeded, delete temporary file/directory */
2603             if (retval == 0)
2604                 DeleteFile(szTmpName);
2605             /* else restore it to what it was */
2606             else
2607                 (void)rename(szTmpName, szNewName);
2608         }
2609         return retval;
2610     }
2611 }
2612
2613 DllExport int
2614 win32_setmode(int fd, int mode)
2615 {
2616     return setmode(fd, mode);
2617 }
2618
2619 DllExport long
2620 win32_lseek(int fd, long offset, int origin)
2621 {
2622     return lseek(fd, offset, origin);
2623 }
2624
2625 DllExport long
2626 win32_tell(int fd)
2627 {
2628     return tell(fd);
2629 }
2630
2631 DllExport int
2632 win32_open(const char *path, int flag, ...)
2633 {
2634     dTHXo;
2635     va_list ap;
2636     int pmode;
2637     WCHAR wBuffer[MAX_PATH+1];
2638
2639     va_start(ap, flag);
2640     pmode = va_arg(ap, int);
2641     va_end(ap);
2642
2643     if (stricmp(path, "/dev/null")==0)
2644         path = "NUL";
2645
2646     if (USING_WIDE()) {
2647         A2WHELPER(path, wBuffer, sizeof(wBuffer));
2648         return _wopen(PerlDir_mapW(wBuffer), flag, pmode);
2649     }
2650     return open(PerlDir_mapA(path), flag, pmode);
2651 }
2652
2653 DllExport int
2654 win32_close(int fd)
2655 {
2656     return close(fd);
2657 }
2658
2659 DllExport int
2660 win32_eof(int fd)
2661 {
2662     return eof(fd);
2663 }
2664
2665 DllExport int
2666 win32_dup(int fd)
2667 {
2668     return dup(fd);
2669 }
2670
2671 DllExport int
2672 win32_dup2(int fd1,int fd2)
2673 {
2674     return dup2(fd1,fd2);
2675 }
2676
2677 #ifdef PERL_MSVCRT_READFIX
2678
2679 #define LF              10      /* line feed */
2680 #define CR              13      /* carriage return */
2681 #define CTRLZ           26      /* ctrl-z means eof for text */
2682 #define FOPEN           0x01    /* file handle open */
2683 #define FEOFLAG         0x02    /* end of file has been encountered */
2684 #define FCRLF           0x04    /* CR-LF across read buffer (in text mode) */
2685 #define FPIPE           0x08    /* file handle refers to a pipe */
2686 #define FAPPEND         0x20    /* file handle opened O_APPEND */
2687 #define FDEV            0x40    /* file handle refers to device */
2688 #define FTEXT           0x80    /* file handle is in text mode */
2689 #define MAX_DESCRIPTOR_COUNT    (64*32) /* this is the maximun that MSVCRT can handle */
2690
2691 int __cdecl
2692 _fixed_read(int fh, void *buf, unsigned cnt)
2693 {
2694     int bytes_read;                 /* number of bytes read */
2695     char *buffer;                   /* buffer to read to */
2696     int os_read;                    /* bytes read on OS call */
2697     char *p, *q;                    /* pointers into buffer */
2698     char peekchr;                   /* peek-ahead character */
2699     ULONG filepos;                  /* file position after seek */
2700     ULONG dosretval;                /* o.s. return value */
2701
2702     /* validate handle */
2703     if (((unsigned)fh >= (unsigned)MAX_DESCRIPTOR_COUNT) ||
2704          !(_osfile(fh) & FOPEN))
2705     {
2706         /* out of range -- return error */
2707         errno = EBADF;
2708         _doserrno = 0;  /* not o.s. error */
2709         return -1;
2710     }
2711
2712     EnterCriticalSection(&(_pioinfo(fh)->lock));  /* lock file */
2713
2714     bytes_read = 0;                 /* nothing read yet */
2715     buffer = (char*)buf;
2716
2717     if (cnt == 0 || (_osfile(fh) & FEOFLAG)) {
2718         /* nothing to read or at EOF, so return 0 read */
2719         goto functionexit;
2720     }
2721
2722     if ((_osfile(fh) & (FPIPE|FDEV)) && _pipech(fh) != LF) {
2723         /* a pipe/device and pipe lookahead non-empty: read the lookahead
2724          * char */
2725         *buffer++ = _pipech(fh);
2726         ++bytes_read;
2727         --cnt;
2728         _pipech(fh) = LF;           /* mark as empty */
2729     }
2730
2731     /* read the data */
2732
2733     if (!ReadFile((HANDLE)_osfhnd(fh), buffer, cnt, (LPDWORD)&os_read, NULL))
2734     {
2735         /* ReadFile has reported an error. recognize two special cases.
2736          *
2737          *      1. map ERROR_ACCESS_DENIED to EBADF
2738          *
2739          *      2. just return 0 if ERROR_BROKEN_PIPE has occurred. it
2740          *         means the handle is a read-handle on a pipe for which
2741          *         all write-handles have been closed and all data has been
2742          *         read. */
2743
2744         if ((dosretval = GetLastError()) == ERROR_ACCESS_DENIED) {
2745             /* wrong read/write mode should return EBADF, not EACCES */
2746             errno = EBADF;
2747             _doserrno = dosretval;
2748             bytes_read = -1;
2749             goto functionexit;
2750         }
2751         else if (dosretval == ERROR_BROKEN_PIPE) {
2752             bytes_read = 0;
2753             goto functionexit;
2754         }
2755         else {
2756             bytes_read = -1;
2757             goto functionexit;
2758         }
2759     }
2760
2761     bytes_read += os_read;          /* update bytes read */
2762
2763     if (_osfile(fh) & FTEXT) {
2764         /* now must translate CR-LFs to LFs in the buffer */
2765
2766         /* set CRLF flag to indicate LF at beginning of buffer */
2767         /* if ((os_read != 0) && (*(char *)buf == LF))   */
2768         /*    _osfile(fh) |= FCRLF;                      */
2769         /* else                                          */
2770         /*    _osfile(fh) &= ~FCRLF;                     */
2771
2772         _osfile(fh) &= ~FCRLF;
2773
2774         /* convert chars in the buffer: p is src, q is dest */
2775         p = q = (char*)buf;
2776         while (p < (char *)buf + bytes_read) {
2777             if (*p == CTRLZ) {
2778                 /* if fh is not a device, set ctrl-z flag */
2779                 if (!(_osfile(fh) & FDEV))
2780                     _osfile(fh) |= FEOFLAG;
2781                 break;              /* stop translating */
2782             }
2783             else if (*p != CR)
2784                 *q++ = *p++;
2785             else {
2786                 /* *p is CR, so must check next char for LF */
2787                 if (p < (char *)buf + bytes_read - 1) {
2788                     if (*(p+1) == LF) {
2789                         p += 2;
2790                         *q++ = LF;  /* convert CR-LF to LF */
2791                     }
2792                     else
2793                         *q++ = *p++;    /* store char normally */
2794                 }
2795                 else {
2796                     /* This is the hard part.  We found a CR at end of
2797                        buffer.  We must peek ahead to see if next char
2798                        is an LF. */
2799                     ++p;
2800
2801                     dosretval = 0;
2802                     if (!ReadFile((HANDLE)_osfhnd(fh), &peekchr, 1,
2803                                     (LPDWORD)&os_read, NULL))
2804                         dosretval = GetLastError();
2805
2806                     if (dosretval != 0 || os_read == 0) {
2807                         /* couldn't read ahead, store CR */
2808                         *q++ = CR;
2809                     }
2810                     else {
2811                         /* peekchr now has the extra character -- we now
2812                            have several possibilities:
2813                            1. disk file and char is not LF; just seek back
2814                               and copy CR
2815                            2. disk file and char is LF; store LF, don't seek back
2816                            3. pipe/device and char is LF; store LF.
2817                            4. pipe/device and char isn't LF, store CR and
2818                               put char in pipe lookahead buffer. */
2819                         if (_osfile(fh) & (FDEV|FPIPE)) {
2820                             /* non-seekable device */
2821                             if (peekchr == LF)
2822                                 *q++ = LF;
2823                             else {
2824                                 *q++ = CR;
2825                                 _pipech(fh) = peekchr;
2826                             }
2827                         }
2828                         else {
2829                             /* disk file */
2830                             if (peekchr == LF) {
2831                                 /* nothing read yet; must make some
2832                                    progress */
2833                                 *q++ = LF;
2834                                 /* turn on this flag for tell routine */
2835                                 _osfile(fh) |= FCRLF;
2836                             }
2837                             else {
2838                                 HANDLE osHandle;        /* o.s. handle value */
2839                                 /* seek back */
2840                                 if ((osHandle = (HANDLE)_get_osfhandle(fh)) != (HANDLE)-1)
2841                                 {
2842                                     if ((filepos = SetFilePointer(osHandle, -1, NULL, FILE_CURRENT)) == -1)
2843                                         dosretval = GetLastError();
2844                                 }
2845                                 if (peekchr != LF)
2846                                     *q++ = CR;
2847                             }
2848                         }
2849                     }
2850                 }
2851             }
2852         }
2853
2854         /* we now change bytes_read to reflect the true number of chars
2855            in the buffer */
2856         bytes_read = q - (char *)buf;
2857     }
2858
2859 functionexit:   
2860     LeaveCriticalSection(&(_pioinfo(fh)->lock));    /* unlock file */
2861
2862     return bytes_read;
2863 }
2864
2865 #endif  /* PERL_MSVCRT_READFIX */
2866
2867 DllExport int
2868 win32_read(int fd, void *buf, unsigned int cnt)
2869 {
2870 #ifdef PERL_MSVCRT_READFIX
2871     return _fixed_read(fd, buf, cnt);
2872 #else
2873     return read(fd, buf, cnt);
2874 #endif
2875 }
2876
2877 DllExport int
2878 win32_write(int fd, const void *buf, unsigned int cnt)
2879 {
2880     return write(fd, buf, cnt);
2881 }
2882
2883 DllExport int
2884 win32_mkdir(const char *dir, int mode)
2885 {
2886     dTHXo;
2887     if (USING_WIDE()) {
2888         WCHAR wBuffer[MAX_PATH+1];
2889         A2WHELPER(dir, wBuffer, sizeof(wBuffer));
2890         return _wmkdir(PerlDir_mapW(wBuffer));
2891     }
2892     return mkdir(PerlDir_mapA(dir)); /* just ignore mode */
2893 }
2894
2895 DllExport int
2896 win32_rmdir(const char *dir)
2897 {
2898     dTHXo;
2899     if (USING_WIDE()) {
2900         WCHAR wBuffer[MAX_PATH+1];
2901         A2WHELPER(dir, wBuffer, sizeof(wBuffer));
2902         return _wrmdir(PerlDir_mapW(wBuffer));
2903     }
2904     return rmdir(PerlDir_mapA(dir));
2905 }
2906
2907 DllExport int
2908 win32_chdir(const char *dir)
2909 {
2910     dTHXo;
2911     if (USING_WIDE()) {
2912         WCHAR wBuffer[MAX_PATH+1];
2913         A2WHELPER(dir, wBuffer, sizeof(wBuffer));
2914         return _wchdir(wBuffer);
2915     }
2916     return chdir(dir);
2917 }
2918
2919 DllExport  int
2920 win32_access(const char *path, int mode)
2921 {
2922     dTHXo;
2923     if (USING_WIDE()) {
2924         WCHAR wBuffer[MAX_PATH+1];
2925         A2WHELPER(path, wBuffer, sizeof(wBuffer));
2926         return _waccess(PerlDir_mapW(wBuffer), mode);
2927     }
2928     return access(PerlDir_mapA(path), mode);
2929 }
2930
2931 DllExport  int
2932 win32_chmod(const char *path, int mode)
2933 {
2934     dTHXo;
2935     if (USING_WIDE()) {
2936         WCHAR wBuffer[MAX_PATH+1];
2937         A2WHELPER(path, wBuffer, sizeof(wBuffer));
2938         return _wchmod(PerlDir_mapW(wBuffer), mode);
2939     }
2940     return chmod(PerlDir_mapA(path), mode);
2941 }
2942
2943
2944 static char *
2945 create_command_line(const char* command, const char * const *args)
2946 {
2947     dTHXo;
2948     int index;
2949     char *cmd, *ptr, *arg;
2950     STRLEN len = strlen(command) + 1;
2951
2952     for (index = 0; (ptr = (char*)args[index]) != NULL; ++index)
2953         len += strlen(ptr) + 1;
2954
2955     New(1310, cmd, len, char);
2956     ptr = cmd;
2957     strcpy(ptr, command);
2958
2959     for (index = 0; (arg = (char*)args[index]) != NULL; ++index) {
2960         ptr += strlen(ptr);
2961         *ptr++ = ' ';
2962         strcpy(ptr, arg);
2963     }
2964
2965     return cmd;
2966 }
2967
2968 static char *
2969 qualified_path(const char *cmd)
2970 {
2971     dTHXo;
2972     char *pathstr;
2973     char *fullcmd, *curfullcmd;
2974     STRLEN cmdlen = 0;
2975     int has_slash = 0;
2976
2977     if (!cmd)
2978         return Nullch;
2979     fullcmd = (char*)cmd;
2980     while (*fullcmd) {
2981         if (*fullcmd == '/' || *fullcmd == '\\')
2982             has_slash++;
2983         fullcmd++;
2984         cmdlen++;
2985     }
2986
2987     /* look in PATH */
2988     pathstr = win32_getenv("PATH");
2989     New(0, fullcmd, MAX_PATH+1, char);
2990     curfullcmd = fullcmd;
2991
2992     while (1) {
2993         DWORD res;
2994
2995         /* start by appending the name to the current prefix */
2996         strcpy(curfullcmd, cmd);
2997         curfullcmd += cmdlen;
2998
2999         /* if it doesn't end with '.', or has no extension, try adding
3000          * a trailing .exe first */
3001         if (cmd[cmdlen-1] != '.'
3002             && (cmdlen < 4 || cmd[cmdlen-4] != '.'))
3003         {
3004             strcpy(curfullcmd, ".exe");
3005             res = GetFileAttributes(fullcmd);
3006             if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
3007                 return fullcmd;
3008             *curfullcmd = '\0';
3009         }
3010
3011         /* that failed, try the bare name */
3012         res = GetFileAttributes(fullcmd);
3013         if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
3014             return fullcmd;
3015
3016         /* quit if no other path exists, or if cmd already has path */
3017         if (!pathstr || !*pathstr || has_slash)
3018             break;
3019
3020         /* skip leading semis */
3021         while (*pathstr == ';')
3022             pathstr++;
3023
3024         /* build a new prefix from scratch */
3025         curfullcmd = fullcmd;
3026         while (*pathstr && *pathstr != ';') {
3027             if (*pathstr == '"') {      /* foo;"baz;etc";bar */
3028                 pathstr++;              /* skip initial '"' */
3029                 while (*pathstr && *pathstr != '"') {
3030                     if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
3031                         *curfullcmd++ = *pathstr;
3032                     pathstr++;
3033                 }
3034                 if (*pathstr)
3035                     pathstr++;          /* skip trailing '"' */
3036             }
3037             else {
3038                 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
3039                     *curfullcmd++ = *pathstr;
3040                 pathstr++;
3041             }
3042         }
3043         if (*pathstr)
3044             pathstr++;                  /* skip trailing semi */
3045         if (curfullcmd > fullcmd        /* append a dir separator */
3046             && curfullcmd[-1] != '/' && curfullcmd[-1] != '\\')
3047         {
3048             *curfullcmd++ = '\\';
3049         }
3050     }
3051 GIVE_UP:
3052     Safefree(fullcmd);
3053     return Nullch;
3054 }
3055
3056 /* The following are just place holders.
3057  * Some hosts may provide and environment that the OS is
3058  * not tracking, therefore, these host must provide that
3059  * environment and the current directory to CreateProcess
3060  */
3061
3062 void*
3063 get_childenv(void)
3064 {
3065     return NULL;
3066 }
3067
3068 void
3069 free_childenv(void* d)
3070 {
3071 }
3072
3073 char*
3074 get_childdir(void)
3075 {
3076     dTHXo;
3077     char* ptr;
3078     char szfilename[(MAX_PATH+1)*2];
3079     if (USING_WIDE()) {
3080         WCHAR wfilename[MAX_PATH+1];
3081         GetCurrentDirectoryW(MAX_PATH+1, wfilename);
3082         W2AHELPER(wfilename, szfilename, sizeof(szfilename));
3083     }
3084     else {
3085         GetCurrentDirectoryA(MAX_PATH+1, szfilename);
3086     }
3087
3088     New(0, ptr, strlen(szfilename)+1, char);
3089     strcpy(ptr, szfilename);
3090     return ptr;
3091 }
3092
3093 void
3094 free_childdir(char* d)
3095 {
3096     dTHXo;
3097     Safefree(d);
3098 }
3099
3100
3101 /* XXX this needs to be made more compatible with the spawnvp()
3102  * provided by the various RTLs.  In particular, searching for
3103  * *.{com,bat,cmd} files (as done by the RTLs) is unimplemented.
3104  * This doesn't significantly affect perl itself, because we
3105  * always invoke things using PERL5SHELL if a direct attempt to
3106  * spawn the executable fails.
3107  * 
3108  * XXX splitting and rejoining the commandline between do_aspawn()
3109  * and win32_spawnvp() could also be avoided.
3110  */
3111
3112 DllExport int
3113 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
3114 {
3115 #ifdef USE_RTL_SPAWNVP
3116     return spawnvp(mode, cmdname, (char * const *)argv);
3117 #else
3118     dTHXo;
3119     int ret;
3120     void* env;
3121     char* dir;
3122     STARTUPINFO StartupInfo;
3123     PROCESS_INFORMATION ProcessInformation;
3124     DWORD create = 0;
3125
3126     char *cmd = create_command_line(cmdname, strcmp(cmdname, argv[0]) == 0
3127                                              ? &argv[1] : argv);
3128     char *fullcmd = Nullch;
3129
3130     env = PerlEnv_get_childenv();
3131     dir = PerlEnv_get_childdir();
3132
3133     switch(mode) {
3134     case P_NOWAIT:      /* asynch + remember result */
3135         if (w32_num_children >= MAXIMUM_WAIT_OBJECTS) {
3136             errno = EAGAIN;
3137             ret = -1;
3138             goto RETVAL;
3139         }
3140         /* FALL THROUGH */
3141     case P_WAIT:        /* synchronous execution */
3142         break;
3143     default:            /* invalid mode */
3144         errno = EINVAL;
3145         ret = -1;
3146         goto RETVAL;
3147     }
3148     memset(&StartupInfo,0,sizeof(StartupInfo));
3149     StartupInfo.cb = sizeof(StartupInfo);
3150     StartupInfo.hStdInput  = GetStdHandle(STD_INPUT_HANDLE);
3151     StartupInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
3152     StartupInfo.hStdError  = GetStdHandle(STD_ERROR_HANDLE);
3153     if (StartupInfo.hStdInput != INVALID_HANDLE_VALUE &&
3154         StartupInfo.hStdOutput != INVALID_HANDLE_VALUE &&
3155         StartupInfo.hStdError != INVALID_HANDLE_VALUE)
3156     {
3157         StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
3158     }
3159     else {
3160         create |= CREATE_NEW_CONSOLE;
3161     }
3162
3163 RETRY:
3164     if (!CreateProcess(cmdname,         /* search PATH to find executable */
3165                        cmd,             /* executable, and its arguments */
3166                        NULL,            /* process attributes */
3167                        NULL,            /* thread attributes */
3168                        TRUE,            /* inherit handles */
3169                        create,          /* creation flags */
3170                        (LPVOID)env,     /* inherit environment */
3171                        dir,             /* inherit cwd */
3172                        &StartupInfo,
3173                        &ProcessInformation))
3174     {
3175         /* initial NULL argument to CreateProcess() does a PATH
3176          * search, but it always first looks in the directory
3177          * where the current process was started, which behavior
3178          * is undesirable for backward compatibility.  So we
3179          * jump through our own hoops by picking out the path
3180          * we really want it to use. */
3181         if (!fullcmd) {
3182             fullcmd = qualified_path(cmdname);
3183             if (fullcmd) {
3184                 cmdname = fullcmd;
3185                 goto RETRY;
3186             }
3187         }
3188         errno = ENOENT;
3189         ret = -1;
3190         goto RETVAL;
3191     }
3192
3193     if (mode == P_NOWAIT) {
3194         /* asynchronous spawn -- store handle, return PID */
3195         w32_child_handles[w32_num_children] = ProcessInformation.hProcess;
3196         w32_child_pids[w32_num_children] = ProcessInformation.dwProcessId;
3197         ret = (int)ProcessInformation.dwProcessId;
3198         ++w32_num_children;
3199     }
3200     else  {
3201         DWORD status;
3202         WaitForSingleObject(ProcessInformation.hProcess, INFINITE);
3203         GetExitCodeProcess(ProcessInformation.hProcess, &status);
3204         ret = (int)status;
3205         CloseHandle(ProcessInformation.hProcess);
3206     }
3207
3208     CloseHandle(ProcessInformation.hThread);
3209
3210 RETVAL:
3211     PerlEnv_free_childenv(env);
3212     PerlEnv_free_childdir(dir);
3213     Safefree(cmd);
3214     Safefree(fullcmd);
3215     return ret;
3216 #endif
3217 }
3218
3219 DllExport int
3220 win32_execv(const char *cmdname, const char *const *argv)
3221 {
3222 #ifdef USE_ITHREADS
3223     dTHXo;
3224     /* if this is a pseudo-forked child, we just want to spawn
3225      * the new program, and return */
3226     if (w32_pseudo_id)
3227         return spawnv(P_WAIT, cmdname, (char *const *)argv);
3228 #endif
3229     return execv(cmdname, (char *const *)argv);
3230 }
3231
3232 DllExport int
3233 win32_execvp(const char *cmdname, const char *const *argv)
3234 {
3235 #ifdef USE_ITHREADS
3236     dTHXo;
3237     /* if this is a pseudo-forked child, we just want to spawn
3238      * the new program, and return */
3239     if (w32_pseudo_id)
3240         return win32_spawnvp(P_WAIT, cmdname, (char *const *)argv);
3241 #endif
3242     return execvp(cmdname, (char *const *)argv);
3243 }
3244
3245 DllExport void
3246 win32_perror(const char *str)
3247 {
3248     perror(str);
3249 }
3250
3251 DllExport void
3252 win32_setbuf(FILE *pf, char *buf)
3253 {
3254     setbuf(pf, buf);
3255 }
3256
3257 DllExport int
3258 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
3259 {
3260     return setvbuf(pf, buf, type, size);
3261 }
3262
3263 DllExport int
3264 win32_flushall(void)
3265 {
3266     return flushall();
3267 }
3268
3269 DllExport int
3270 win32_fcloseall(void)
3271 {
3272     return fcloseall();
3273 }
3274
3275 DllExport char*
3276 win32_fgets(char *s, int n, FILE *pf)
3277 {
3278     return fgets(s, n, pf);
3279 }
3280
3281 DllExport char*
3282 win32_gets(char *s)
3283 {
3284     return gets(s);
3285 }
3286
3287 DllExport int
3288 win32_fgetc(FILE *pf)
3289 {
3290     return fgetc(pf);
3291 }
3292
3293 DllExport int
3294 win32_putc(int c, FILE *pf)
3295 {
3296     return putc(c,pf);
3297 }
3298
3299 DllExport int
3300 win32_puts(const char *s)
3301 {
3302     return puts(s);
3303 }
3304
3305 DllExport int
3306 win32_getchar(void)
3307 {
3308     return getchar();
3309 }
3310
3311 DllExport int
3312 win32_putchar(int c)
3313 {
3314     return putchar(c);
3315 }
3316
3317 #ifdef MYMALLOC
3318
3319 #ifndef USE_PERL_SBRK
3320
3321 static char *committed = NULL;
3322 static char *base      = NULL;
3323 static char *reserved  = NULL;
3324 static char *brk       = NULL;
3325 static DWORD pagesize  = 0;
3326 static DWORD allocsize = 0;
3327
3328 void *
3329 sbrk(int need)
3330 {
3331  void *result;
3332  if (!pagesize)
3333   {SYSTEM_INFO info;
3334    GetSystemInfo(&info);
3335    /* Pretend page size is larger so we don't perpetually
3336     * call the OS to commit just one page ...
3337     */
3338    pagesize = info.dwPageSize << 3;
3339    allocsize = info.dwAllocationGranularity;
3340   }
3341  /* This scheme fails eventually if request for contiguous
3342   * block is denied so reserve big blocks - this is only 
3343   * address space not memory ...
3344   */
3345  if (brk+need >= reserved)
3346   {
3347    DWORD size = 64*1024*1024;
3348    char *addr;
3349    if (committed && reserved && committed < reserved)
3350     {
3351      /* Commit last of previous chunk cannot span allocations */
3352      addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
3353      if (addr)
3354       committed = reserved;
3355     }
3356    /* Reserve some (more) space 
3357     * Note this is a little sneaky, 1st call passes NULL as reserved
3358     * so lets system choose where we start, subsequent calls pass
3359     * the old end address so ask for a contiguous block
3360     */
3361    addr  = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
3362    if (addr)
3363     {
3364      reserved = addr+size;
3365      if (!base)
3366       base = addr;
3367      if (!committed)
3368       committed = base;
3369      if (!brk)
3370       brk = committed;
3371     }
3372    else
3373     {
3374      return (void *) -1;
3375     }
3376   }
3377  result = brk;
3378  brk += need;
3379  if (brk > committed)
3380   {
3381    DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
3382    char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
3383    if (addr)
3384     {
3385      committed += size;
3386     }
3387    else
3388     return (void *) -1;
3389   }
3390  return result;
3391 }
3392
3393 #endif
3394 #endif
3395
3396 DllExport void*
3397 win32_malloc(size_t size)
3398 {
3399     return malloc(size);
3400 }
3401
3402 DllExport void*
3403 win32_calloc(size_t numitems, size_t size)
3404 {
3405     return calloc(numitems,size);
3406 }
3407
3408 DllExport void*
3409 win32_realloc(void *block, size_t size)
3410 {
3411     return realloc(block,size);
3412 }
3413
3414 DllExport void
3415 win32_free(void *block)
3416 {
3417     free(block);
3418 }
3419
3420
3421 int
3422 win32_open_osfhandle(long handle, int flags)
3423 {
3424 #ifdef USE_FIXED_OSFHANDLE
3425     if (IsWin95())
3426         return my_open_osfhandle(handle, flags);
3427 #endif
3428     return _open_osfhandle(handle, flags);
3429 }
3430
3431 long
3432 win32_get_osfhandle(int fd)
3433 {
3434     return _get_osfhandle(fd);
3435 }
3436
3437 DllExport void*
3438 win32_dynaload(const char* filename)
3439 {
3440     dTHXo;
3441     HMODULE hModule;
3442     if (USING_WIDE()) {
3443         WCHAR wfilename[MAX_PATH+1];
3444         A2WHELPER(filename, wfilename, sizeof(wfilename));
3445         hModule = LoadLibraryExW(PerlDir_mapW(wfilename), NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
3446     }
3447     else {
3448         hModule = LoadLibraryExA(PerlDir_mapA(filename), NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
3449     }
3450     return hModule;
3451 }
3452
3453 /*
3454  * Extras.
3455  */
3456
3457 static
3458 XS(w32_GetCwd)
3459 {
3460     dXSARGS;
3461     /* Make the host for current directory */
3462     char* ptr = PerlEnv_get_childdir();
3463     /* 
3464      * If ptr != Nullch 
3465      *   then it worked, set PV valid, 
3466      *   else return 'undef' 
3467      */
3468     if (ptr) {
3469         SV *sv = sv_newmortal();
3470         sv_setpv(sv, ptr);
3471         PerlEnv_free_childdir(ptr);
3472
3473         EXTEND(SP,1);
3474         SvPOK_on(sv);
3475         ST(0) = sv;
3476         XSRETURN(1);
3477     }
3478     XSRETURN_UNDEF;
3479 }
3480
3481 static
3482 XS(w32_SetCwd)
3483 {
3484     dXSARGS;
3485     if (items != 1)
3486         Perl_croak(aTHX_ "usage: Win32::SetCurrentDirectory($cwd)");
3487     if (!PerlDir_chdir(SvPV_nolen(ST(0))))
3488         XSRETURN_YES;
3489
3490     XSRETURN_NO;
3491 }
3492
3493 static
3494 XS(w32_GetNextAvailDrive)
3495 {
3496     dXSARGS;
3497     char ix = 'C';
3498     char root[] = "_:\\";
3499
3500     EXTEND(SP,1);
3501     while (ix <= 'Z') {
3502         root[0] = ix++;
3503         if (GetDriveType(root) == 1) {
3504             root[2] = '\0';
3505             XSRETURN_PV(root);
3506         }
3507     }
3508     XSRETURN_UNDEF;
3509 }
3510
3511 static
3512 XS(w32_GetLastError)
3513 {
3514     dXSARGS;
3515     EXTEND(SP,1);
3516     XSRETURN_IV(GetLastError());
3517 }
3518
3519 static
3520 XS(w32_SetLastError)
3521 {
3522     dXSARGS;
3523     if (items != 1)
3524         Perl_croak(aTHX_ "usage: Win32::SetLastError($error)");
3525     SetLastError(SvIV(ST(0)));
3526     XSRETURN_EMPTY;
3527 }
3528
3529 static
3530 XS(w32_LoginName)
3531 {
3532     dXSARGS;
3533     char *name = w32_getlogin_buffer;
3534     DWORD size = sizeof(w32_getlogin_buffer);
3535     EXTEND(SP,1);
3536     if (GetUserName(name,&size)) {
3537         /* size includes NULL */
3538         ST(0) = sv_2mortal(newSVpvn(name,size-1));
3539         XSRETURN(1);
3540     }
3541     XSRETURN_UNDEF;
3542 }
3543
3544 static
3545 XS(w32_NodeName)
3546 {
3547     dXSARGS;
3548     char name[MAX_COMPUTERNAME_LENGTH+1];
3549     DWORD size = sizeof(name);
3550     EXTEND(SP,1);
3551     if (GetComputerName(name,&size)) {
3552         /* size does NOT include NULL :-( */
3553         ST(0) = sv_2mortal(newSVpvn(name,size));
3554         XSRETURN(1);
3555     }
3556     XSRETURN_UNDEF;
3557 }
3558
3559
3560 static
3561 XS(w32_DomainName)
3562 {
3563     dXSARGS;
3564     HINSTANCE hNetApi32 = LoadLibrary("netapi32.dll");
3565     DWORD (__stdcall *pfnNetApiBufferFree)(LPVOID Buffer);
3566     DWORD (__stdcall *pfnNetWkstaGetInfo)(LPWSTR servername, DWORD level,
3567                                           void *bufptr);
3568
3569     if (hNetApi32) {
3570         pfnNetApiBufferFree = (DWORD (__stdcall *)(void *))
3571             GetProcAddress(hNetApi32, "NetApiBufferFree");
3572         pfnNetWkstaGetInfo = (DWORD (__stdcall *)(LPWSTR, DWORD, void *))
3573             GetProcAddress(hNetApi32, "NetWkstaGetInfo");
3574     }
3575     EXTEND(SP,1);
3576     if (hNetApi32 && pfnNetWkstaGetInfo && pfnNetApiBufferFree) {
3577         /* this way is more reliable, in case user has a local account. */
3578         char dname[256];
3579         DWORD dnamelen = sizeof(dname);
3580         struct {
3581             DWORD   wki100_platform_id;
3582             LPWSTR  wki100_computername;
3583             LPWSTR  wki100_langroup;
3584             DWORD   wki100_ver_major;
3585             DWORD   wki100_ver_minor;
3586         } *pwi;
3587         /* NERR_Success *is* 0*/
3588         if (0 == pfnNetWkstaGetInfo(NULL, 100, &pwi)) {
3589             if (pwi->wki100_langroup && *(pwi->wki100_langroup)) {
3590                 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_langroup,
3591                                     -1, (LPSTR)dname, dnamelen, NULL, NULL);
3592             }
3593             else {
3594                 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_computername,
3595                                     -1, (LPSTR)dname, dnamelen, NULL, NULL);
3596             }
3597             pfnNetApiBufferFree(pwi);
3598             FreeLibrary(hNetApi32);
3599             XSRETURN_PV(dname);
3600         }
3601         FreeLibrary(hNetApi32);
3602     }
3603     else {
3604         /* Win95 doesn't have NetWksta*(), so do it the old way */
3605         char name[256];
3606         DWORD size = sizeof(name);
3607         if (hNetApi32)
3608             FreeLibrary(hNetApi32);
3609         if (GetUserName(name,&size)) {
3610             char sid[ONE_K_BUFSIZE];
3611             DWORD sidlen = sizeof(sid);
3612             char dname[256];
3613             DWORD dnamelen = sizeof(dname);
3614             SID_NAME_USE snu;
3615             if (LookupAccountName(NULL, name, (PSID)&sid, &sidlen,
3616                                   dname, &dnamelen, &snu)) {
3617                 XSRETURN_PV(dname);             /* all that for this */
3618             }
3619         }
3620     }
3621     XSRETURN_UNDEF;
3622 }
3623
3624 static
3625 XS(w32_FsType)
3626 {
3627     dXSARGS;
3628     char fsname[256];
3629     DWORD flags, filecomplen;
3630     if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
3631                          &flags, fsname, sizeof(fsname))) {
3632         if (GIMME_V == G_ARRAY) {
3633             XPUSHs(sv_2mortal(newSVpvn(fsname,strlen(fsname))));
3634             XPUSHs(sv_2mortal(newSViv(flags)));
3635             XPUSHs(sv_2mortal(newSViv(filecomplen)));
3636             PUTBACK;
3637             return;
3638         }
3639         EXTEND(SP,1);
3640         XSRETURN_PV(fsname);
3641     }
3642     XSRETURN_EMPTY;
3643 }
3644
3645 static
3646 XS(w32_GetOSVersion)
3647 {
3648     dXSARGS;
3649     OSVERSIONINFOA osver;
3650
3651     if (USING_WIDE()) {
3652         OSVERSIONINFOW osverw;
3653         char szCSDVersion[sizeof(osverw.szCSDVersion)];
3654         osverw.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
3655         if (!GetVersionExW(&osverw)) {
3656             XSRETURN_EMPTY;
3657         }
3658         W2AHELPER(osverw.szCSDVersion, szCSDVersion, sizeof(szCSDVersion));
3659         XPUSHs(newSVpvn(szCSDVersion, strlen(szCSDVersion)));
3660         osver.dwMajorVersion = osverw.dwMajorVersion;
3661         osver.dwMinorVersion = osverw.dwMinorVersion;
3662         osver.dwBuildNumber = osverw.dwBuildNumber;
3663         osver.dwPlatformId = osverw.dwPlatformId;
3664     }
3665     else {
3666         osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOA);
3667         if (!GetVersionExA(&osver)) {
3668             XSRETURN_EMPTY;
3669         }
3670         XPUSHs(newSVpvn(osver.szCSDVersion, strlen(osver.szCSDVersion)));
3671     }
3672     XPUSHs(newSViv(osver.dwMajorVersion));
3673     XPUSHs(newSViv(osver.dwMinorVersion));
3674     XPUSHs(newSViv(osver.dwBuildNumber));
3675     XPUSHs(newSViv(osver.dwPlatformId));
3676     PUTBACK;
3677 }
3678
3679 static
3680 XS(w32_IsWinNT)
3681 {
3682     dXSARGS;
3683     EXTEND(SP,1);
3684     XSRETURN_IV(IsWinNT());
3685 }
3686
3687 static
3688 XS(w32_IsWin95)
3689 {
3690     dXSARGS;
3691     EXTEND(SP,1);
3692     XSRETURN_IV(IsWin95());
3693 }
3694
3695 static
3696 XS(w32_FormatMessage)
3697 {
3698     dXSARGS;
3699     DWORD source = 0;
3700     char msgbuf[ONE_K_BUFSIZE];
3701
3702     if (items != 1)
3703         Perl_croak(aTHX_ "usage: Win32::FormatMessage($errno)");
3704
3705     if (USING_WIDE()) {
3706         WCHAR wmsgbuf[ONE_K_BUFSIZE];
3707         if (FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM,
3708                           &source, SvIV(ST(0)), 0,
3709                           wmsgbuf, ONE_K_BUFSIZE-1, NULL))
3710         {
3711             W2AHELPER(wmsgbuf, msgbuf, sizeof(msgbuf));
3712             XSRETURN_PV(msgbuf);
3713         }
3714     }
3715     else {
3716         if (FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM,
3717                           &source, SvIV(ST(0)), 0,
3718                           msgbuf, sizeof(msgbuf)-1, NULL))
3719             XSRETURN_PV(msgbuf);
3720     }
3721
3722     XSRETURN_UNDEF;
3723 }
3724
3725 static
3726 XS(w32_Spawn)
3727 {
3728     dXSARGS;
3729     char *cmd, *args;
3730     PROCESS_INFORMATION stProcInfo;
3731     STARTUPINFO stStartInfo;
3732     BOOL bSuccess = FALSE;
3733
3734     if (items != 3)
3735         Perl_croak(aTHX_ "usage: Win32::Spawn($cmdName, $args, $PID)");
3736
3737     cmd = SvPV_nolen(ST(0));
3738     args = SvPV_nolen(ST(1));
3739
3740     memset(&stStartInfo, 0, sizeof(stStartInfo));   /* Clear the block */
3741     stStartInfo.cb = sizeof(stStartInfo);           /* Set the structure size */
3742     stStartInfo.dwFlags = STARTF_USESHOWWINDOW;     /* Enable wShowWindow control */
3743     stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE;   /* Start min (normal) */
3744
3745     if (CreateProcess(
3746                 cmd,                    /* Image path */
3747                 args,                   /* Arguments for command line */
3748                 NULL,                   /* Default process security */
3749                 NULL,                   /* Default thread security */
3750                 FALSE,                  /* Must be TRUE to use std handles */
3751                 NORMAL_PRIORITY_CLASS,  /* No special scheduling */
3752                 NULL,                   /* Inherit our environment block */
3753                 NULL,                   /* Inherit our currrent directory */
3754                 &stStartInfo,           /* -> Startup info */
3755                 &stProcInfo))           /* <- Process info (if OK) */
3756     {
3757         CloseHandle(stProcInfo.hThread);/* library source code does this. */
3758         sv_setiv(ST(2), stProcInfo.dwProcessId);
3759         bSuccess = TRUE;
3760     }
3761     XSRETURN_IV(bSuccess);
3762 }
3763
3764 static
3765 XS(w32_GetTickCount)
3766 {
3767     dXSARGS;
3768     DWORD msec = GetTickCount();
3769     EXTEND(SP,1);
3770     if ((IV)msec > 0)
3771         XSRETURN_IV(msec);
3772     XSRETURN_NV(msec);
3773 }
3774
3775 static
3776 XS(w32_GetShortPathName)
3777 {
3778     dXSARGS;
3779     SV *shortpath;
3780     DWORD len;
3781
3782     if (items != 1)
3783         Perl_croak(aTHX_ "usage: Win32::GetShortPathName($longPathName)");
3784
3785     shortpath = sv_mortalcopy(ST(0));
3786     SvUPGRADE(shortpath, SVt_PV);
3787     /* src == target is allowed */
3788     do {
3789         len = GetShortPathName(SvPVX(shortpath),
3790                                SvPVX(shortpath),
3791                                SvLEN(shortpath));
3792     } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
3793     if (len) {
3794         SvCUR_set(shortpath,len);
3795         ST(0) = shortpath;
3796         XSRETURN(1);
3797     }
3798     XSRETURN_UNDEF;
3799 }
3800
3801 static
3802 XS(w32_GetFullPathName)
3803 {
3804     dXSARGS;
3805     SV *filename;
3806     SV *fullpath;
3807     char *filepart;
3808     DWORD len;
3809
3810     if (items != 1)
3811         Perl_croak(aTHX_ "usage: Win32::GetFullPathName($filename)");
3812
3813     filename = ST(0);
3814     fullpath = sv_mortalcopy(filename);
3815     SvUPGRADE(fullpath, SVt_PV);
3816     do {
3817         len = GetFullPathName(SvPVX(filename),
3818                               SvLEN(fullpath),
3819                               SvPVX(fullpath),
3820                               &filepart);
3821     } while (len >= SvLEN(fullpath) && sv_grow(fullpath,len+1));
3822     if (len) {
3823         if (GIMME_V == G_ARRAY) {
3824             EXTEND(SP,1);
3825             XST_mPV(1,filepart);
3826             len = filepart - SvPVX(fullpath);
3827             items = 2;
3828         }
3829         SvCUR_set(fullpath,len);
3830         ST(0) = fullpath;
3831         XSRETURN(items);
3832     }
3833     XSRETURN_EMPTY;
3834 }
3835
3836 static
3837 XS(w32_GetLongPathName)
3838 {
3839     dXSARGS;
3840     SV *path;
3841     char tmpbuf[MAX_PATH+1];
3842     char *pathstr;
3843     STRLEN len;
3844
3845     if (items != 1)
3846         Perl_croak(aTHX_ "usage: Win32::GetLongPathName($pathname)");
3847
3848     path = ST(0);
3849     pathstr = SvPV(path,len);
3850     strcpy(tmpbuf, pathstr);
3851     pathstr = win32_longpath(tmpbuf);
3852     if (pathstr) {
3853         ST(0) = sv_2mortal(newSVpvn(pathstr, strlen(pathstr)));
3854         XSRETURN(1);
3855     }
3856     XSRETURN_EMPTY;
3857 }
3858
3859 static
3860 XS(w32_Sleep)
3861 {
3862     dXSARGS;
3863     if (items != 1)
3864         Perl_croak(aTHX_ "usage: Win32::Sleep($milliseconds)");
3865     Sleep(SvIV(ST(0)));
3866     XSRETURN_YES;
3867 }
3868
3869 static
3870 XS(w32_CopyFile)
3871 {
3872     dXSARGS;
3873     BOOL bResult;
3874     if (items != 3)
3875         Perl_croak(aTHX_ "usage: Win32::CopyFile($from, $to, $overwrite)");
3876     if (USING_WIDE()) {
3877         WCHAR wSourceFile[MAX_PATH+1];
3878         WCHAR wDestFile[MAX_PATH+1];
3879         A2WHELPER(SvPV_nolen(ST(0)), wSourceFile, sizeof(wSourceFile));
3880         wcscpy(wSourceFile, PerlDir_mapW(wSourceFile));
3881         A2WHELPER(SvPV_nolen(ST(1)), wDestFile, sizeof(wDestFile));
3882         bResult = CopyFileW(wSourceFile, PerlDir_mapW(wDestFile), !SvTRUE(ST(2)));
3883     }
3884     else {
3885         char szSourceFile[MAX_PATH+1];
3886         strcpy(szSourceFile, PerlDir_mapA(SvPV_nolen(ST(0))));
3887         bResult = CopyFileA(szSourceFile, PerlDir_mapA(SvPV_nolen(ST(1))), !SvTRUE(ST(2)));
3888     }
3889
3890     if (bResult)
3891         XSRETURN_YES;
3892     XSRETURN_NO;
3893 }
3894
3895 void
3896 Perl_init_os_extras(void)
3897 {
3898     dTHXo;
3899     char *file = __FILE__;
3900     dXSUB_SYS;
3901
3902     w32_perlshell_tokens = Nullch;
3903     w32_perlshell_items = -1;
3904     w32_fdpid = newAV();                /* XXX needs to be in Perl_win32_init()? */
3905     New(1313, w32_children, 1, child_tab);
3906     w32_num_children = 0;
3907     w32_init_socktype = 0;
3908 #ifdef USE_ITHREADS
3909     w32_pseudo_id = 0;
3910     New(1313, w32_pseudo_children, 1, child_tab);
3911     w32_num_pseudo_children = 0;
3912 #endif
3913
3914     /* these names are Activeware compatible */
3915     newXS("Win32::GetCwd", w32_GetCwd, file);
3916     newXS("Win32::SetCwd", w32_SetCwd, file);
3917     newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
3918     newXS("Win32::GetLastError", w32_GetLastError, file);
3919     newXS("Win32::SetLastError", w32_SetLastError, file);
3920     newXS("Win32::LoginName", w32_LoginName, file);
3921     newXS("Win32::NodeName", w32_NodeName, file);
3922     newXS("Win32::DomainName", w32_DomainName, file);
3923     newXS("Win32::FsType", w32_FsType, file);
3924     newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
3925     newXS("Win32::IsWinNT", w32_IsWinNT, file);
3926     newXS("Win32::IsWin95", w32_IsWin95, file);
3927     newXS("Win32::FormatMessage", w32_FormatMessage, file);
3928     newXS("Win32::Spawn", w32_Spawn, file);
3929     newXS("Win32::GetTickCount", w32_GetTickCount, file);
3930     newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
3931     newXS("Win32::GetFullPathName", w32_GetFullPathName, file);
3932     newXS("Win32::GetLongPathName", w32_GetLongPathName, file);
3933     newXS("Win32::CopyFile", w32_CopyFile, file);
3934     newXS("Win32::Sleep", w32_Sleep, file);
3935
3936     /* XXX Bloat Alert! The following Activeware preloads really
3937      * ought to be part of Win32::Sys::*, so they're not included
3938      * here.
3939      */
3940     /* LookupAccountName
3941      * LookupAccountSID
3942      * InitiateSystemShutdown
3943      * AbortSystemShutdown
3944      * ExpandEnvrironmentStrings
3945      */
3946 }
3947
3948 void
3949 Perl_win32_init(int *argcp, char ***argvp)
3950 {
3951     /* Disable floating point errors, Perl will trap the ones we
3952      * care about.  VC++ RTL defaults to switching these off
3953      * already, but the Borland RTL doesn't.  Since we don't
3954      * want to be at the vendor's whim on the default, we set
3955      * it explicitly here.
3956      */
3957 #if !defined(_ALPHA_) && !defined(__GNUC__)
3958     _control87(MCW_EM, MCW_EM);
3959 #endif
3960     MALLOC_INIT;
3961 }
3962
3963 #ifdef USE_ITHREADS
3964
3965 #  ifdef PERL_OBJECT
3966 #    undef Perl_sys_intern_dup
3967 #    define Perl_sys_intern_dup CPerlObj::Perl_sys_intern_dup
3968 #    define pPerl this
3969 #  endif
3970
3971 void
3972 Perl_sys_intern_dup(pTHX_ struct interp_intern *src, struct interp_intern *dst)
3973 {
3974     dst->perlshell_tokens       = Nullch;
3975     dst->perlshell_vec          = (char**)NULL;
3976     dst->perlshell_items        = 0;
3977     dst->fdpid                  = newAV();
3978     Newz(1313, dst->children, 1, child_tab);
3979     Newz(1313, dst->pseudo_children, 1, child_tab);
3980     dst->pseudo_id              = 0;
3981     dst->children->num          = 0;
3982     dst->thr_intern.Winit_socktype = src->thr_intern.Winit_socktype;
3983 }
3984 #endif
3985