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