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