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