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