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