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