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