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