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