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