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