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