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