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