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