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