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