Integer constants (0x, 0[0-7], 0b) now overflow fatally,
[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     /* strip trailing whitespace and period */
1806     if (0 < dwLen) {
1807         do {
1808             --dwLen;    /* dwLen doesn't include trailing null */
1809         } while (0 < dwLen && isSPACE(sMsg[dwLen]));
1810         if ('.' != sMsg[dwLen])
1811             dwLen++;
1812         sMsg[dwLen] = '\0';
1813     }
1814     if (0 == dwLen) {
1815         sMsg = (char*)LocalAlloc(0, 64/**sizeof(TCHAR)*/);
1816         if (sMsg)
1817             dwLen = sprintf(sMsg,
1818                             "Unknown error #0x%lX (lookup 0x%lX)",
1819                             dwErr, GetLastError());
1820     }
1821     if (sMsg) {
1822         dTHXo;
1823         sv_setpvn((SV*)sv, sMsg, dwLen);
1824         LocalFree(sMsg);
1825     }
1826 }
1827
1828
1829 DllExport int
1830 win32_fprintf(FILE *fp, const char *format, ...)
1831 {
1832     va_list marker;
1833     va_start(marker, format);     /* Initialize variable arguments. */
1834
1835     return (vfprintf(fp, format, marker));
1836 }
1837
1838 DllExport int
1839 win32_printf(const char *format, ...)
1840 {
1841     va_list marker;
1842     va_start(marker, format);     /* Initialize variable arguments. */
1843
1844     return (vprintf(format, marker));
1845 }
1846
1847 DllExport int
1848 win32_vfprintf(FILE *fp, const char *format, va_list args)
1849 {
1850     return (vfprintf(fp, format, args));
1851 }
1852
1853 DllExport int
1854 win32_vprintf(const char *format, va_list args)
1855 {
1856     return (vprintf(format, args));
1857 }
1858
1859 DllExport size_t
1860 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
1861 {
1862     return fread(buf, size, count, fp);
1863 }
1864
1865 DllExport size_t
1866 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
1867 {
1868     return fwrite(buf, size, count, fp);
1869 }
1870
1871 #define MODE_SIZE 10
1872
1873 DllExport FILE *
1874 win32_fopen(const char *filename, const char *mode)
1875 {
1876     dTHXo;
1877     WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH];
1878     
1879     if (!*filename)
1880         return NULL;
1881
1882     if (stricmp(filename, "/dev/null")==0)
1883         filename = "NUL";
1884
1885     if (USING_WIDE()) {
1886         A2WHELPER(mode, wMode, sizeof(wMode));
1887         A2WHELPER(filename, wBuffer, sizeof(wBuffer));
1888         return _wfopen(wBuffer, wMode);
1889     }
1890     return fopen(filename, mode);
1891 }
1892
1893 #ifndef USE_SOCKETS_AS_HANDLES
1894 #undef fdopen
1895 #define fdopen my_fdopen
1896 #endif
1897
1898 DllExport FILE *
1899 win32_fdopen(int handle, const char *mode)
1900 {
1901     dTHXo;
1902     WCHAR wMode[MODE_SIZE];
1903     if (USING_WIDE()) {
1904         A2WHELPER(mode, wMode, sizeof(wMode));
1905         return _wfdopen(handle, wMode);
1906     }
1907     return fdopen(handle, (char *) mode);
1908 }
1909
1910 DllExport FILE *
1911 win32_freopen(const char *path, const char *mode, FILE *stream)
1912 {
1913     dTHXo;
1914     WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH];
1915     if (stricmp(path, "/dev/null")==0)
1916         path = "NUL";
1917
1918     if (USING_WIDE()) {
1919         A2WHELPER(mode, wMode, sizeof(wMode));
1920         A2WHELPER(path, wBuffer, sizeof(wBuffer));
1921         return _wfreopen(wBuffer, wMode, stream);
1922     }
1923     return freopen(path, mode, stream);
1924 }
1925
1926 DllExport int
1927 win32_fclose(FILE *pf)
1928 {
1929     return my_fclose(pf);       /* defined in win32sck.c */
1930 }
1931
1932 DllExport int
1933 win32_fputs(const char *s,FILE *pf)
1934 {
1935     return fputs(s, pf);
1936 }
1937
1938 DllExport int
1939 win32_fputc(int c,FILE *pf)
1940 {
1941     return fputc(c,pf);
1942 }
1943
1944 DllExport int
1945 win32_ungetc(int c,FILE *pf)
1946 {
1947     return ungetc(c,pf);
1948 }
1949
1950 DllExport int
1951 win32_getc(FILE *pf)
1952 {
1953     return getc(pf);
1954 }
1955
1956 DllExport int
1957 win32_fileno(FILE *pf)
1958 {
1959     return fileno(pf);
1960 }
1961
1962 DllExport void
1963 win32_clearerr(FILE *pf)
1964 {
1965     clearerr(pf);
1966     return;
1967 }
1968
1969 DllExport int
1970 win32_fflush(FILE *pf)
1971 {
1972     return fflush(pf);
1973 }
1974
1975 DllExport long
1976 win32_ftell(FILE *pf)
1977 {
1978     return ftell(pf);
1979 }
1980
1981 DllExport int
1982 win32_fseek(FILE *pf,long offset,int origin)
1983 {
1984     return fseek(pf, offset, origin);
1985 }
1986
1987 DllExport int
1988 win32_fgetpos(FILE *pf,fpos_t *p)
1989 {
1990     return fgetpos(pf, p);
1991 }
1992
1993 DllExport int
1994 win32_fsetpos(FILE *pf,const fpos_t *p)
1995 {
1996     return fsetpos(pf, p);
1997 }
1998
1999 DllExport void
2000 win32_rewind(FILE *pf)
2001 {
2002     rewind(pf);
2003     return;
2004 }
2005
2006 DllExport FILE*
2007 win32_tmpfile(void)
2008 {
2009     return tmpfile();
2010 }
2011
2012 DllExport void
2013 win32_abort(void)
2014 {
2015     abort();
2016     return;
2017 }
2018
2019 DllExport int
2020 win32_fstat(int fd,struct stat *sbufptr)
2021 {
2022     return fstat(fd,sbufptr);
2023 }
2024
2025 DllExport int
2026 win32_pipe(int *pfd, unsigned int size, int mode)
2027 {
2028     return _pipe(pfd, size, mode);
2029 }
2030
2031 /*
2032  * a popen() clone that respects PERL5SHELL
2033  */
2034
2035 DllExport FILE*
2036 win32_popen(const char *command, const char *mode)
2037 {
2038 #ifdef USE_RTL_POPEN
2039     return _popen(command, mode);
2040 #else
2041     int p[2];
2042     int parent, child;
2043     int stdfd, oldfd;
2044     int ourmode;
2045     int childpid;
2046
2047     /* establish which ends read and write */
2048     if (strchr(mode,'w')) {
2049         stdfd = 0;              /* stdin */
2050         parent = 1;
2051         child = 0;
2052     }
2053     else if (strchr(mode,'r')) {
2054         stdfd = 1;              /* stdout */
2055         parent = 0;
2056         child = 1;
2057     }
2058     else
2059         return NULL;
2060
2061     /* set the correct mode */
2062     if (strchr(mode,'b'))
2063         ourmode = O_BINARY;
2064     else if (strchr(mode,'t'))
2065         ourmode = O_TEXT;
2066     else
2067         ourmode = _fmode & (O_TEXT | O_BINARY);
2068
2069     /* the child doesn't inherit handles */
2070     ourmode |= O_NOINHERIT;
2071
2072     if (win32_pipe( p, 512, ourmode) == -1)
2073         return NULL;
2074
2075     /* save current stdfd */
2076     if ((oldfd = win32_dup(stdfd)) == -1)
2077         goto cleanup;
2078
2079     /* make stdfd go to child end of pipe (implicitly closes stdfd) */
2080     /* stdfd will be inherited by the child */
2081     if (win32_dup2(p[child], stdfd) == -1)
2082         goto cleanup;
2083
2084     /* close the child end in parent */
2085     win32_close(p[child]);
2086
2087     /* start the child */
2088     {
2089         dTHXo;
2090         if ((childpid = do_spawn_nowait((char*)command)) == -1)
2091             goto cleanup;
2092
2093         /* revert stdfd to whatever it was before */
2094         if (win32_dup2(oldfd, stdfd) == -1)
2095             goto cleanup;
2096
2097         /* close saved handle */
2098         win32_close(oldfd);
2099
2100         sv_setiv(*av_fetch(w32_fdpid, p[parent], TRUE), childpid);
2101
2102         /* set process id so that it can be returned by perl's open() */
2103         PL_forkprocess = childpid;
2104     }
2105
2106     /* we have an fd, return a file stream */
2107     return (win32_fdopen(p[parent], (char *)mode));
2108
2109 cleanup:
2110     /* we don't need to check for errors here */
2111     win32_close(p[0]);
2112     win32_close(p[1]);
2113     if (oldfd != -1) {
2114         win32_dup2(oldfd, stdfd);
2115         win32_close(oldfd);
2116     }
2117     return (NULL);
2118
2119 #endif /* USE_RTL_POPEN */
2120 }
2121
2122 /*
2123  * pclose() clone
2124  */
2125
2126 DllExport int
2127 win32_pclose(FILE *pf)
2128 {
2129 #ifdef USE_RTL_POPEN
2130     return _pclose(pf);
2131 #else
2132     dTHXo;
2133     int childpid, status;
2134     SV *sv;
2135
2136     sv = *av_fetch(w32_fdpid, win32_fileno(pf), TRUE);
2137     if (SvIOK(sv))
2138         childpid = SvIVX(sv);
2139     else
2140         childpid = 0;
2141
2142     if (!childpid) {
2143         errno = EBADF;
2144         return -1;
2145     }
2146
2147     win32_fclose(pf);
2148     SvIVX(sv) = 0;
2149
2150     if (win32_waitpid(childpid, &status, 0) == -1)
2151         return -1;
2152
2153     return status;
2154
2155 #endif /* USE_RTL_POPEN */
2156 }
2157
2158 DllExport int
2159 win32_rename(const char *oname, const char *newname)
2160 {
2161     WCHAR wOldName[MAX_PATH];
2162     WCHAR wNewName[MAX_PATH];
2163     BOOL bResult;
2164     /* XXX despite what the documentation says about MoveFileEx(),
2165      * it doesn't work under Windows95!
2166      */
2167     if (IsWinNT()) {
2168         dTHXo;
2169         if (USING_WIDE()) {
2170             A2WHELPER(oname, wOldName, sizeof(wOldName));
2171             A2WHELPER(newname, wNewName, sizeof(wNewName));
2172             bResult = MoveFileExW(wOldName,wNewName,
2173                         MOVEFILE_COPY_ALLOWED|MOVEFILE_REPLACE_EXISTING);
2174         }
2175         else {
2176             bResult = MoveFileExA(oname,newname,
2177                         MOVEFILE_COPY_ALLOWED|MOVEFILE_REPLACE_EXISTING);
2178         }
2179         if (!bResult) {
2180             DWORD err = GetLastError();
2181             switch (err) {
2182             case ERROR_BAD_NET_NAME:
2183             case ERROR_BAD_NETPATH:
2184             case ERROR_BAD_PATHNAME:
2185             case ERROR_FILE_NOT_FOUND:
2186             case ERROR_FILENAME_EXCED_RANGE:
2187             case ERROR_INVALID_DRIVE:
2188             case ERROR_NO_MORE_FILES:
2189             case ERROR_PATH_NOT_FOUND:
2190                 errno = ENOENT;
2191                 break;
2192             default:
2193                 errno = EACCES;
2194                 break;
2195             }
2196             return -1;
2197         }
2198         return 0;
2199     }
2200     else {
2201         int retval = 0;
2202         char tmpname[MAX_PATH+1];
2203         char dname[MAX_PATH+1];
2204         char *endname = Nullch;
2205         STRLEN tmplen = 0;
2206         DWORD from_attr, to_attr;
2207
2208         /* if oname doesn't exist, do nothing */
2209         from_attr = GetFileAttributes(oname);
2210         if (from_attr == 0xFFFFFFFF) {
2211             errno = ENOENT;
2212             return -1;
2213         }
2214
2215         /* if newname exists, rename it to a temporary name so that we
2216          * don't delete it in case oname happens to be the same file
2217          * (but perhaps accessed via a different path)
2218          */
2219         to_attr = GetFileAttributes(newname);
2220         if (to_attr != 0xFFFFFFFF) {
2221             /* if newname is a directory, we fail
2222              * XXX could overcome this with yet more convoluted logic */
2223             if (to_attr & FILE_ATTRIBUTE_DIRECTORY) {
2224                 errno = EACCES;
2225                 return -1;
2226             }
2227             tmplen = strlen(newname);
2228             strcpy(tmpname,newname);
2229             endname = tmpname+tmplen;
2230             for (; endname > tmpname ; --endname) {
2231                 if (*endname == '/' || *endname == '\\') {
2232                     *endname = '\0';
2233                     break;
2234                 }
2235             }
2236             if (endname > tmpname)
2237                 endname = strcpy(dname,tmpname);
2238             else
2239                 endname = ".";
2240
2241             /* get a temporary filename in same directory
2242              * XXX is this really the best we can do? */
2243             if (!GetTempFileName((LPCTSTR)endname, "plr", 0, tmpname)) {
2244                 errno = ENOENT;
2245                 return -1;
2246             }
2247             DeleteFile(tmpname);
2248
2249             retval = rename(newname, tmpname);
2250             if (retval != 0) {
2251                 errno = EACCES;
2252                 return retval;
2253             }
2254         }
2255
2256         /* rename oname to newname */
2257         retval = rename(oname, newname);
2258
2259         /* if we created a temporary file before ... */
2260         if (endname != Nullch) {
2261             /* ...and rename succeeded, delete temporary file/directory */
2262             if (retval == 0)
2263                 DeleteFile(tmpname);
2264             /* else restore it to what it was */
2265             else
2266                 (void)rename(tmpname, newname);
2267         }
2268         return retval;
2269     }
2270 }
2271
2272 DllExport int
2273 win32_setmode(int fd, int mode)
2274 {
2275     return setmode(fd, mode);
2276 }
2277
2278 DllExport long
2279 win32_lseek(int fd, long offset, int origin)
2280 {
2281     return lseek(fd, offset, origin);
2282 }
2283
2284 DllExport long
2285 win32_tell(int fd)
2286 {
2287     return tell(fd);
2288 }
2289
2290 DllExport int
2291 win32_open(const char *path, int flag, ...)
2292 {
2293     dTHXo;
2294     va_list ap;
2295     int pmode;
2296     WCHAR wBuffer[MAX_PATH];
2297
2298     va_start(ap, flag);
2299     pmode = va_arg(ap, int);
2300     va_end(ap);
2301
2302     if (stricmp(path, "/dev/null")==0)
2303         path = "NUL";
2304
2305     if (USING_WIDE()) {
2306         A2WHELPER(path, wBuffer, sizeof(wBuffer));
2307         return _wopen(wBuffer, flag, pmode);
2308     }
2309     return open(path,flag,pmode);
2310 }
2311
2312 DllExport int
2313 win32_close(int fd)
2314 {
2315     return close(fd);
2316 }
2317
2318 DllExport int
2319 win32_eof(int fd)
2320 {
2321     return eof(fd);
2322 }
2323
2324 DllExport int
2325 win32_dup(int fd)
2326 {
2327     return dup(fd);
2328 }
2329
2330 DllExport int
2331 win32_dup2(int fd1,int fd2)
2332 {
2333     return dup2(fd1,fd2);
2334 }
2335
2336 DllExport int
2337 win32_read(int fd, void *buf, unsigned int cnt)
2338 {
2339     return read(fd, buf, cnt);
2340 }
2341
2342 DllExport int
2343 win32_write(int fd, const void *buf, unsigned int cnt)
2344 {
2345     return write(fd, buf, cnt);
2346 }
2347
2348 DllExport int
2349 win32_mkdir(const char *dir, int mode)
2350 {
2351     return mkdir(dir); /* just ignore mode */
2352 }
2353
2354 DllExport int
2355 win32_rmdir(const char *dir)
2356 {
2357     return rmdir(dir);
2358 }
2359
2360 DllExport int
2361 win32_chdir(const char *dir)
2362 {
2363     return chdir(dir);
2364 }
2365
2366 static char *
2367 create_command_line(const char* command, const char * const *args)
2368 {
2369     dTHXo;
2370     int index;
2371     char *cmd, *ptr, *arg;
2372     STRLEN len = strlen(command) + 1;
2373
2374     for (index = 0; (ptr = (char*)args[index]) != NULL; ++index)
2375         len += strlen(ptr) + 1;
2376
2377     New(1310, cmd, len, char);
2378     ptr = cmd;
2379     strcpy(ptr, command);
2380
2381     for (index = 0; (arg = (char*)args[index]) != NULL; ++index) {
2382         ptr += strlen(ptr);
2383         *ptr++ = ' ';
2384         strcpy(ptr, arg);
2385     }
2386
2387     return cmd;
2388 }
2389
2390 static char *
2391 qualified_path(const char *cmd)
2392 {
2393     dTHXo;
2394     char *pathstr;
2395     char *fullcmd, *curfullcmd;
2396     STRLEN cmdlen = 0;
2397     int has_slash = 0;
2398
2399     if (!cmd)
2400         return Nullch;
2401     fullcmd = (char*)cmd;
2402     while (*fullcmd) {
2403         if (*fullcmd == '/' || *fullcmd == '\\')
2404             has_slash++;
2405         fullcmd++;
2406         cmdlen++;
2407     }
2408
2409     /* look in PATH */
2410     pathstr = win32_getenv("PATH");
2411     New(0, fullcmd, MAX_PATH+1, char);
2412     curfullcmd = fullcmd;
2413
2414     while (1) {
2415         DWORD res;
2416
2417         /* start by appending the name to the current prefix */
2418         strcpy(curfullcmd, cmd);
2419         curfullcmd += cmdlen;
2420
2421         /* if it doesn't end with '.', or has no extension, try adding
2422          * a trailing .exe first */
2423         if (cmd[cmdlen-1] != '.'
2424             && (cmdlen < 4 || cmd[cmdlen-4] != '.'))
2425         {
2426             strcpy(curfullcmd, ".exe");
2427             res = GetFileAttributes(fullcmd);
2428             if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
2429                 return fullcmd;
2430             *curfullcmd = '\0';
2431         }
2432
2433         /* that failed, try the bare name */
2434         res = GetFileAttributes(fullcmd);
2435         if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
2436             return fullcmd;
2437
2438         /* quit if no other path exists, or if cmd already has path */
2439         if (!pathstr || !*pathstr || has_slash)
2440             break;
2441
2442         /* skip leading semis */
2443         while (*pathstr == ';')
2444             pathstr++;
2445
2446         /* build a new prefix from scratch */
2447         curfullcmd = fullcmd;
2448         while (*pathstr && *pathstr != ';') {
2449             if (*pathstr == '"') {      /* foo;"baz;etc";bar */
2450                 pathstr++;              /* skip initial '"' */
2451                 while (*pathstr && *pathstr != '"') {
2452                     if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
2453                         *curfullcmd++ = *pathstr;
2454                     pathstr++;
2455                 }
2456                 if (*pathstr)
2457                     pathstr++;          /* skip trailing '"' */
2458             }
2459             else {
2460                 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
2461                     *curfullcmd++ = *pathstr;
2462                 pathstr++;
2463             }
2464         }
2465         if (*pathstr)
2466             pathstr++;                  /* skip trailing semi */
2467         if (curfullcmd > fullcmd        /* append a dir separator */
2468             && curfullcmd[-1] != '/' && curfullcmd[-1] != '\\')
2469         {
2470             *curfullcmd++ = '\\';
2471         }
2472     }
2473 GIVE_UP:
2474     Safefree(fullcmd);
2475     return Nullch;
2476 }
2477
2478 /* XXX this needs to be made more compatible with the spawnvp()
2479  * provided by the various RTLs.  In particular, searching for
2480  * *.{com,bat,cmd} files (as done by the RTLs) is unimplemented.
2481  * This doesn't significantly affect perl itself, because we
2482  * always invoke things using PERL5SHELL if a direct attempt to
2483  * spawn the executable fails.
2484  * 
2485  * XXX splitting and rejoining the commandline between do_aspawn()
2486  * and win32_spawnvp() could also be avoided.
2487  */
2488
2489 DllExport int
2490 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
2491 {
2492 #ifdef USE_RTL_SPAWNVP
2493     return spawnvp(mode, cmdname, (char * const *)argv);
2494 #else
2495     dTHXo;
2496     DWORD ret;
2497     STARTUPINFO StartupInfo;
2498     PROCESS_INFORMATION ProcessInformation;
2499     DWORD create = 0;
2500
2501     char *cmd = create_command_line(cmdname, strcmp(cmdname, argv[0]) == 0
2502                                              ? &argv[1] : argv);
2503     char *fullcmd = Nullch;
2504
2505     switch(mode) {
2506     case P_NOWAIT:      /* asynch + remember result */
2507         if (w32_num_children >= MAXIMUM_WAIT_OBJECTS) {
2508             errno = EAGAIN;
2509             ret = -1;
2510             goto RETVAL;
2511         }
2512         /* FALL THROUGH */
2513     case P_WAIT:        /* synchronous execution */
2514         break;
2515     default:            /* invalid mode */
2516         errno = EINVAL;
2517         ret = -1;
2518         goto RETVAL;
2519     }
2520     memset(&StartupInfo,0,sizeof(StartupInfo));
2521     StartupInfo.cb = sizeof(StartupInfo);
2522     StartupInfo.hStdInput  = GetStdHandle(STD_INPUT_HANDLE);
2523     StartupInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
2524     StartupInfo.hStdError  = GetStdHandle(STD_ERROR_HANDLE);
2525     if (StartupInfo.hStdInput != INVALID_HANDLE_VALUE &&
2526         StartupInfo.hStdOutput != INVALID_HANDLE_VALUE &&
2527         StartupInfo.hStdError != INVALID_HANDLE_VALUE)
2528     {
2529         StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
2530     }
2531     else {
2532         create |= CREATE_NEW_CONSOLE;
2533     }
2534
2535 #ifndef DEBUGGING
2536     StartupInfo.dwFlags |= STARTF_USESHOWWINDOW;
2537     StartupInfo.wShowWindow = SW_HIDE;
2538 #endif
2539
2540 RETRY:
2541     if (!CreateProcess(cmdname,         /* search PATH to find executable */
2542                        cmd,             /* executable, and its arguments */
2543                        NULL,            /* process attributes */
2544                        NULL,            /* thread attributes */
2545                        TRUE,            /* inherit handles */
2546                        create,          /* creation flags */
2547                        NULL,            /* inherit environment */
2548                        NULL,            /* inherit cwd */
2549                        &StartupInfo,
2550                        &ProcessInformation))
2551     {
2552         /* initial NULL argument to CreateProcess() does a PATH
2553          * search, but it always first looks in the directory
2554          * where the current process was started, which behavior
2555          * is undesirable for backward compatibility.  So we
2556          * jump through our own hoops by picking out the path
2557          * we really want it to use. */
2558         if (!fullcmd) {
2559             fullcmd = qualified_path(cmdname);
2560             if (fullcmd) {
2561                 cmdname = fullcmd;
2562                 goto RETRY;
2563             }
2564         }
2565         errno = ENOENT;
2566         ret = -1;
2567         goto RETVAL;
2568     }
2569
2570     if (mode == P_NOWAIT) {
2571         /* asynchronous spawn -- store handle, return PID */
2572         w32_child_handles[w32_num_children] = ProcessInformation.hProcess;
2573         ret = w32_child_pids[w32_num_children] = ProcessInformation.dwProcessId;
2574         ++w32_num_children;
2575     }
2576     else  {
2577         WaitForSingleObject(ProcessInformation.hProcess, INFINITE);
2578         GetExitCodeProcess(ProcessInformation.hProcess, &ret);
2579         CloseHandle(ProcessInformation.hProcess);
2580     }
2581
2582     CloseHandle(ProcessInformation.hThread);
2583 RETVAL:
2584     Safefree(cmd);
2585     Safefree(fullcmd);
2586     return (int)ret;
2587 #endif
2588 }
2589
2590 DllExport int
2591 win32_execv(const char *cmdname, const char *const *argv)
2592 {
2593     return execv(cmdname, (char *const *)argv);
2594 }
2595
2596 DllExport int
2597 win32_execvp(const char *cmdname, const char *const *argv)
2598 {
2599     return execvp(cmdname, (char *const *)argv);
2600 }
2601
2602 DllExport void
2603 win32_perror(const char *str)
2604 {
2605     perror(str);
2606 }
2607
2608 DllExport void
2609 win32_setbuf(FILE *pf, char *buf)
2610 {
2611     setbuf(pf, buf);
2612 }
2613
2614 DllExport int
2615 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
2616 {
2617     return setvbuf(pf, buf, type, size);
2618 }
2619
2620 DllExport int
2621 win32_flushall(void)
2622 {
2623     return flushall();
2624 }
2625
2626 DllExport int
2627 win32_fcloseall(void)
2628 {
2629     return fcloseall();
2630 }
2631
2632 DllExport char*
2633 win32_fgets(char *s, int n, FILE *pf)
2634 {
2635     return fgets(s, n, pf);
2636 }
2637
2638 DllExport char*
2639 win32_gets(char *s)
2640 {
2641     return gets(s);
2642 }
2643
2644 DllExport int
2645 win32_fgetc(FILE *pf)
2646 {
2647     return fgetc(pf);
2648 }
2649
2650 DllExport int
2651 win32_putc(int c, FILE *pf)
2652 {
2653     return putc(c,pf);
2654 }
2655
2656 DllExport int
2657 win32_puts(const char *s)
2658 {
2659     return puts(s);
2660 }
2661
2662 DllExport int
2663 win32_getchar(void)
2664 {
2665     return getchar();
2666 }
2667
2668 DllExport int
2669 win32_putchar(int c)
2670 {
2671     return putchar(c);
2672 }
2673
2674 #ifdef MYMALLOC
2675
2676 #ifndef USE_PERL_SBRK
2677
2678 static char *committed = NULL;
2679 static char *base      = NULL;
2680 static char *reserved  = NULL;
2681 static char *brk       = NULL;
2682 static DWORD pagesize  = 0;
2683 static DWORD allocsize = 0;
2684
2685 void *
2686 sbrk(int need)
2687 {
2688  void *result;
2689  if (!pagesize)
2690   {SYSTEM_INFO info;
2691    GetSystemInfo(&info);
2692    /* Pretend page size is larger so we don't perpetually
2693     * call the OS to commit just one page ...
2694     */
2695    pagesize = info.dwPageSize << 3;
2696    allocsize = info.dwAllocationGranularity;
2697   }
2698  /* This scheme fails eventually if request for contiguous
2699   * block is denied so reserve big blocks - this is only 
2700   * address space not memory ...
2701   */
2702  if (brk+need >= reserved)
2703   {
2704    DWORD size = 64*1024*1024;
2705    char *addr;
2706    if (committed && reserved && committed < reserved)
2707     {
2708      /* Commit last of previous chunk cannot span allocations */
2709      addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
2710      if (addr)
2711       committed = reserved;
2712     }
2713    /* Reserve some (more) space 
2714     * Note this is a little sneaky, 1st call passes NULL as reserved
2715     * so lets system choose where we start, subsequent calls pass
2716     * the old end address so ask for a contiguous block
2717     */
2718    addr  = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
2719    if (addr)
2720     {
2721      reserved = addr+size;
2722      if (!base)
2723       base = addr;
2724      if (!committed)
2725       committed = base;
2726      if (!brk)
2727       brk = committed;
2728     }
2729    else
2730     {
2731      return (void *) -1;
2732     }
2733   }
2734  result = brk;
2735  brk += need;
2736  if (brk > committed)
2737   {
2738    DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
2739    char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
2740    if (addr)
2741     {
2742      committed += size;
2743     }
2744    else
2745     return (void *) -1;
2746   }
2747  return result;
2748 }
2749
2750 #endif
2751 #endif
2752
2753 DllExport void*
2754 win32_malloc(size_t size)
2755 {
2756     return malloc(size);
2757 }
2758
2759 DllExport void*
2760 win32_calloc(size_t numitems, size_t size)
2761 {
2762     return calloc(numitems,size);
2763 }
2764
2765 DllExport void*
2766 win32_realloc(void *block, size_t size)
2767 {
2768     return realloc(block,size);
2769 }
2770
2771 DllExport void
2772 win32_free(void *block)
2773 {
2774     free(block);
2775 }
2776
2777
2778 int
2779 win32_open_osfhandle(long handle, int flags)
2780 {
2781     return _open_osfhandle(handle, flags);
2782 }
2783
2784 long
2785 win32_get_osfhandle(int fd)
2786 {
2787     return _get_osfhandle(fd);
2788 }
2789
2790 DllExport void*
2791 win32_dynaload(const char* filename)
2792 {
2793     dTHXo;
2794     HMODULE hModule;
2795     if (USING_WIDE()) {
2796         WCHAR wfilename[MAX_PATH];
2797         A2WHELPER(filename, wfilename, sizeof(wfilename));
2798         hModule = LoadLibraryExW(wfilename, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
2799     }
2800     else {
2801         hModule = LoadLibraryExA(filename, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
2802     }
2803     return hModule;
2804 }
2805
2806 DllExport int
2807 win32_add_host(char *nameId, void *data)
2808 {
2809     /*
2810      * This must be called before the script is parsed,
2811      * therefore no locking of threads is needed
2812      */
2813     dTHXo;
2814     struct host_link *link;
2815     New(1314, link, 1, struct host_link);
2816     link->host_data = data;
2817     link->nameId = nameId;
2818     link->next = w32_host_link;
2819     w32_host_link = link;
2820     return 1;
2821 }
2822
2823 DllExport void *
2824 win32_get_host_data(char *nameId)
2825 {
2826     dTHXo;
2827     struct host_link *link = w32_host_link;
2828     while(link) {
2829         if(strEQ(link->nameId, nameId))
2830             return link->host_data;
2831         link = link->next;
2832     }
2833     return Nullch;
2834 }
2835
2836 /*
2837  * Extras.
2838  */
2839
2840 static
2841 XS(w32_GetCwd)
2842 {
2843     dXSARGS;
2844     SV *sv = sv_newmortal();
2845     /* Make one call with zero size - return value is required size */
2846     DWORD len = GetCurrentDirectory((DWORD)0,NULL);
2847     SvUPGRADE(sv,SVt_PV);
2848     SvGROW(sv,len);
2849     SvCUR(sv) = GetCurrentDirectory((DWORD) SvLEN(sv), SvPVX(sv));
2850     /* 
2851      * If result != 0 
2852      *   then it worked, set PV valid, 
2853      *   else leave it 'undef' 
2854      */
2855     EXTEND(SP,1);
2856     if (SvCUR(sv)) {
2857         SvPOK_on(sv);
2858         ST(0) = sv;
2859         XSRETURN(1);
2860     }
2861     XSRETURN_UNDEF;
2862 }
2863
2864 static
2865 XS(w32_SetCwd)
2866 {
2867     dXSARGS;
2868     if (items != 1)
2869         Perl_croak(aTHX_ "usage: Win32::SetCurrentDirectory($cwd)");
2870     if (SetCurrentDirectory(SvPV_nolen(ST(0))))
2871         XSRETURN_YES;
2872
2873     XSRETURN_NO;
2874 }
2875
2876 static
2877 XS(w32_GetNextAvailDrive)
2878 {
2879     dXSARGS;
2880     char ix = 'C';
2881     char root[] = "_:\\";
2882
2883     EXTEND(SP,1);
2884     while (ix <= 'Z') {
2885         root[0] = ix++;
2886         if (GetDriveType(root) == 1) {
2887             root[2] = '\0';
2888             XSRETURN_PV(root);
2889         }
2890     }
2891     XSRETURN_UNDEF;
2892 }
2893
2894 static
2895 XS(w32_GetLastError)
2896 {
2897     dXSARGS;
2898     EXTEND(SP,1);
2899     XSRETURN_IV(GetLastError());
2900 }
2901
2902 static
2903 XS(w32_SetLastError)
2904 {
2905     dXSARGS;
2906     if (items != 1)
2907         Perl_croak(aTHX_ "usage: Win32::SetLastError($error)");
2908     SetLastError(SvIV(ST(0)));
2909     XSRETURN_EMPTY;
2910 }
2911
2912 static
2913 XS(w32_LoginName)
2914 {
2915     dXSARGS;
2916     char *name = getlogin_buffer;
2917     DWORD size = sizeof(getlogin_buffer);
2918     EXTEND(SP,1);
2919     if (GetUserName(name,&size)) {
2920         /* size includes NULL */
2921         ST(0) = sv_2mortal(newSVpvn(name,size-1));
2922         XSRETURN(1);
2923     }
2924     XSRETURN_UNDEF;
2925 }
2926
2927 static
2928 XS(w32_NodeName)
2929 {
2930     dXSARGS;
2931     char name[MAX_COMPUTERNAME_LENGTH+1];
2932     DWORD size = sizeof(name);
2933     EXTEND(SP,1);
2934     if (GetComputerName(name,&size)) {
2935         /* size does NOT include NULL :-( */
2936         ST(0) = sv_2mortal(newSVpvn(name,size));
2937         XSRETURN(1);
2938     }
2939     XSRETURN_UNDEF;
2940 }
2941
2942
2943 static
2944 XS(w32_DomainName)
2945 {
2946     dXSARGS;
2947 #ifndef HAS_NETWKSTAGETINFO
2948     /* mingw32 (and Win95) don't have NetWksta*(), so do it the old way */
2949     char name[256];
2950     DWORD size = sizeof(name);
2951     EXTEND(SP,1);
2952     if (GetUserName(name,&size)) {
2953         char sid[1024];
2954         DWORD sidlen = sizeof(sid);
2955         char dname[256];
2956         DWORD dnamelen = sizeof(dname);
2957         SID_NAME_USE snu;
2958         if (LookupAccountName(NULL, name, (PSID)&sid, &sidlen,
2959                               dname, &dnamelen, &snu)) {
2960             XSRETURN_PV(dname);         /* all that for this */
2961         }
2962     }
2963 #else
2964     /* this way is more reliable, in case user has a local account.
2965      * XXX need dynamic binding of netapi32.dll symbols or this will fail on
2966      * Win95. Probably makes more sense to move it into libwin32. */
2967     char dname[256];
2968     DWORD dnamelen = sizeof(dname);
2969     PWKSTA_INFO_100 pwi;
2970     EXTEND(SP,1);
2971     if (NERR_Success == NetWkstaGetInfo(NULL, 100, (LPBYTE*)&pwi)) {
2972         if (pwi->wki100_langroup && *(pwi->wki100_langroup)) {
2973             WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_langroup,
2974                                 -1, (LPSTR)dname, dnamelen, NULL, NULL);
2975         }
2976         else {
2977             WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_computername,
2978                                 -1, (LPSTR)dname, dnamelen, NULL, NULL);
2979         }
2980         NetApiBufferFree(pwi);
2981         XSRETURN_PV(dname);
2982     }
2983 #endif
2984     XSRETURN_UNDEF;
2985 }
2986
2987 static
2988 XS(w32_FsType)
2989 {
2990     dXSARGS;
2991     char fsname[256];
2992     DWORD flags, filecomplen;
2993     if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
2994                          &flags, fsname, sizeof(fsname))) {
2995         if (GIMME_V == G_ARRAY) {
2996             XPUSHs(sv_2mortal(newSVpvn(fsname,strlen(fsname))));
2997             XPUSHs(sv_2mortal(newSViv(flags)));
2998             XPUSHs(sv_2mortal(newSViv(filecomplen)));
2999             PUTBACK;
3000             return;
3001         }
3002         EXTEND(SP,1);
3003         XSRETURN_PV(fsname);
3004     }
3005     XSRETURN_EMPTY;
3006 }
3007
3008 static
3009 XS(w32_GetOSVersion)
3010 {
3011     dXSARGS;
3012     OSVERSIONINFO osver;
3013
3014     osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
3015     if (GetVersionEx(&osver)) {
3016         XPUSHs(newSVpvn(osver.szCSDVersion, strlen(osver.szCSDVersion)));
3017         XPUSHs(newSViv(osver.dwMajorVersion));
3018         XPUSHs(newSViv(osver.dwMinorVersion));
3019         XPUSHs(newSViv(osver.dwBuildNumber));
3020         XPUSHs(newSViv(osver.dwPlatformId));
3021         PUTBACK;
3022         return;
3023     }
3024     XSRETURN_EMPTY;
3025 }
3026
3027 static
3028 XS(w32_IsWinNT)
3029 {
3030     dXSARGS;
3031     EXTEND(SP,1);
3032     XSRETURN_IV(IsWinNT());
3033 }
3034
3035 static
3036 XS(w32_IsWin95)
3037 {
3038     dXSARGS;
3039     EXTEND(SP,1);
3040     XSRETURN_IV(IsWin95());
3041 }
3042
3043 static
3044 XS(w32_FormatMessage)
3045 {
3046     dXSARGS;
3047     DWORD source = 0;
3048     char msgbuf[1024];
3049
3050     if (items != 1)
3051         Perl_croak(aTHX_ "usage: Win32::FormatMessage($errno)");
3052
3053     if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
3054                       &source, SvIV(ST(0)), 0,
3055                       msgbuf, sizeof(msgbuf)-1, NULL))
3056         XSRETURN_PV(msgbuf);
3057
3058     XSRETURN_UNDEF;
3059 }
3060
3061 static
3062 XS(w32_Spawn)
3063 {
3064     dXSARGS;
3065     char *cmd, *args;
3066     PROCESS_INFORMATION stProcInfo;
3067     STARTUPINFO stStartInfo;
3068     BOOL bSuccess = FALSE;
3069
3070     if (items != 3)
3071         Perl_croak(aTHX_ "usage: Win32::Spawn($cmdName, $args, $PID)");
3072
3073     cmd = SvPV_nolen(ST(0));
3074     args = SvPV_nolen(ST(1));
3075
3076     memset(&stStartInfo, 0, sizeof(stStartInfo));   /* Clear the block */
3077     stStartInfo.cb = sizeof(stStartInfo);           /* Set the structure size */
3078     stStartInfo.dwFlags = STARTF_USESHOWWINDOW;     /* Enable wShowWindow control */
3079     stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE;   /* Start min (normal) */
3080
3081     if (CreateProcess(
3082                 cmd,                    /* Image path */
3083                 args,                   /* Arguments for command line */
3084                 NULL,                   /* Default process security */
3085                 NULL,                   /* Default thread security */
3086                 FALSE,                  /* Must be TRUE to use std handles */
3087                 NORMAL_PRIORITY_CLASS,  /* No special scheduling */
3088                 NULL,                   /* Inherit our environment block */
3089                 NULL,                   /* Inherit our currrent directory */
3090                 &stStartInfo,           /* -> Startup info */
3091                 &stProcInfo))           /* <- Process info (if OK) */
3092     {
3093         CloseHandle(stProcInfo.hThread);/* library source code does this. */
3094         sv_setiv(ST(2), stProcInfo.dwProcessId);
3095         bSuccess = TRUE;
3096     }
3097     XSRETURN_IV(bSuccess);
3098 }
3099
3100 static
3101 XS(w32_GetTickCount)
3102 {
3103     dXSARGS;
3104     DWORD msec = GetTickCount();
3105     EXTEND(SP,1);
3106     if ((IV)msec > 0)
3107         XSRETURN_IV(msec);
3108     XSRETURN_NV(msec);
3109 }
3110
3111 static
3112 XS(w32_GetShortPathName)
3113 {
3114     dXSARGS;
3115     SV *shortpath;
3116     DWORD len;
3117
3118     if (items != 1)
3119         Perl_croak(aTHX_ "usage: Win32::GetShortPathName($longPathName)");
3120
3121     shortpath = sv_mortalcopy(ST(0));
3122     SvUPGRADE(shortpath, SVt_PV);
3123     /* src == target is allowed */
3124     do {
3125         len = GetShortPathName(SvPVX(shortpath),
3126                                SvPVX(shortpath),
3127                                SvLEN(shortpath));
3128     } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
3129     if (len) {
3130         SvCUR_set(shortpath,len);
3131         ST(0) = shortpath;
3132         XSRETURN(1);
3133     }
3134     XSRETURN_UNDEF;
3135 }
3136
3137 static
3138 XS(w32_GetFullPathName)
3139 {
3140     dXSARGS;
3141     SV *filename;
3142     SV *fullpath;
3143     char *filepart;
3144     DWORD len;
3145
3146     if (items != 1)
3147         Perl_croak(aTHX_ "usage: Win32::GetFullPathName($filename)");
3148
3149     filename = ST(0);
3150     fullpath = sv_mortalcopy(filename);
3151     SvUPGRADE(fullpath, SVt_PV);
3152     do {
3153         len = GetFullPathName(SvPVX(filename),
3154                               SvLEN(fullpath),
3155                               SvPVX(fullpath),
3156                               &filepart);
3157     } while (len >= SvLEN(fullpath) && sv_grow(fullpath,len+1));
3158     if (len) {
3159         if (GIMME_V == G_ARRAY) {
3160             EXTEND(SP,1);
3161             XST_mPV(1,filepart);
3162             len = filepart - SvPVX(fullpath);
3163             items = 2;
3164         }
3165         SvCUR_set(fullpath,len);
3166         ST(0) = fullpath;
3167         XSRETURN(items);
3168     }
3169     XSRETURN_EMPTY;
3170 }
3171
3172 static
3173 XS(w32_GetLongPathName)
3174 {
3175     dXSARGS;
3176     SV *path;
3177     char tmpbuf[MAX_PATH+1];
3178     char *pathstr;
3179     STRLEN len;
3180
3181     if (items != 1)
3182         Perl_croak(aTHX_ "usage: Win32::GetLongPathName($pathname)");
3183
3184     path = ST(0);
3185     pathstr = SvPV(path,len);
3186     strcpy(tmpbuf, pathstr);
3187     pathstr = win32_longpath(tmpbuf);
3188     if (pathstr) {
3189         ST(0) = sv_2mortal(newSVpvn(pathstr, strlen(pathstr)));
3190         XSRETURN(1);
3191     }
3192     XSRETURN_EMPTY;
3193 }
3194
3195 static
3196 XS(w32_Sleep)
3197 {
3198     dXSARGS;
3199     if (items != 1)
3200         Perl_croak(aTHX_ "usage: Win32::Sleep($milliseconds)");
3201     Sleep(SvIV(ST(0)));
3202     XSRETURN_YES;
3203 }
3204
3205 static
3206 XS(w32_CopyFile)
3207 {
3208     dXSARGS;
3209     if (items != 3)
3210         Perl_croak(aTHX_ "usage: Win32::CopyFile($from, $to, $overwrite)");
3211     if (CopyFile(SvPV_nolen(ST(0)), SvPV_nolen(ST(1)), !SvTRUE(ST(2))))
3212         XSRETURN_YES;
3213     XSRETURN_NO;
3214 }
3215
3216 void
3217 Perl_init_os_extras(void)
3218 {
3219     dTHXo;
3220     char *file = __FILE__;
3221     dXSUB_SYS;
3222
3223     w32_perlshell_tokens = Nullch;
3224     w32_perlshell_items = -1;
3225     w32_fdpid = newAV();                /* XXX needs to be in Perl_win32_init()? */
3226     New(1313, w32_children, 1, child_tab);
3227     w32_num_children = 0;
3228
3229     /* these names are Activeware compatible */
3230     newXS("Win32::GetCwd", w32_GetCwd, file);
3231     newXS("Win32::SetCwd", w32_SetCwd, file);
3232     newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
3233     newXS("Win32::GetLastError", w32_GetLastError, file);
3234     newXS("Win32::SetLastError", w32_SetLastError, file);
3235     newXS("Win32::LoginName", w32_LoginName, file);
3236     newXS("Win32::NodeName", w32_NodeName, file);
3237     newXS("Win32::DomainName", w32_DomainName, file);
3238     newXS("Win32::FsType", w32_FsType, file);
3239     newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
3240     newXS("Win32::IsWinNT", w32_IsWinNT, file);
3241     newXS("Win32::IsWin95", w32_IsWin95, file);
3242     newXS("Win32::FormatMessage", w32_FormatMessage, file);
3243     newXS("Win32::Spawn", w32_Spawn, file);
3244     newXS("Win32::GetTickCount", w32_GetTickCount, file);
3245     newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
3246     newXS("Win32::GetFullPathName", w32_GetFullPathName, file);
3247     newXS("Win32::GetLongPathName", w32_GetLongPathName, file);
3248     newXS("Win32::CopyFile", w32_CopyFile, file);
3249     newXS("Win32::Sleep", w32_Sleep, file);
3250
3251     /* XXX Bloat Alert! The following Activeware preloads really
3252      * ought to be part of Win32::Sys::*, so they're not included
3253      * here.
3254      */
3255     /* LookupAccountName
3256      * LookupAccountSID
3257      * InitiateSystemShutdown
3258      * AbortSystemShutdown
3259      * ExpandEnvrironmentStrings
3260      */
3261 }
3262
3263 void
3264 Perl_win32_init(int *argcp, char ***argvp)
3265 {
3266     /* Disable floating point errors, Perl will trap the ones we
3267      * care about.  VC++ RTL defaults to switching these off
3268      * already, but the Borland RTL doesn't.  Since we don't
3269      * want to be at the vendor's whim on the default, we set
3270      * it explicitly here.
3271      */
3272 #if !defined(_ALPHA_) && !defined(__GNUC__)
3273     _control87(MCW_EM, MCW_EM);
3274 #endif
3275     MALLOC_INIT;
3276 }
3277
3278 #ifdef USE_BINMODE_SCRIPTS
3279
3280 void
3281 win32_strip_return(SV *sv)
3282 {
3283  char *s = SvPVX(sv);
3284  char *e = s+SvCUR(sv);
3285  char *d = s;
3286  while (s < e)
3287   {
3288    if (*s == '\r' && s[1] == '\n')
3289     {
3290      *d++ = '\n';
3291      s += 2;
3292     }
3293    else 
3294     {
3295      *d++ = *s++;
3296     }   
3297   }
3298  SvCUR_set(sv,d-SvPVX(sv)); 
3299 }
3300
3301 #endif
3302