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