414e4c5dfcae0dfa8c6282e92ddbc74e9ed993fd
[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
19 #ifndef __MINGW32__
20 #include <lmcons.h>
21 #include <lmerr.h>
22 /* ugliness to work around a buggy struct definition in lmwksta.h */
23 #undef LPTSTR
24 #define LPTSTR LPWSTR
25 #include <lmwksta.h>
26 #undef LPTSTR
27 #define LPTSTR LPSTR
28 #include <lmapibuf.h>
29 #endif /* __MINGW32__ */
30
31 /* #include "config.h" */
32
33 #define PERLIO_NOT_STDIO 0 
34 #if !defined(PERLIO_IS_STDIO) && !defined(USE_SFIO)
35 #define PerlIO FILE
36 #endif
37
38 #include "EXTERN.h"
39 #include "perl.h"
40
41 #define NO_XSLOCKS
42 #ifdef PERL_OBJECT
43 extern CPerlObj* pPerl;
44 #endif
45 #include "XSUB.h"
46
47 #include "Win32iop.h"
48 #include <fcntl.h>
49 #include <sys/stat.h>
50 #ifndef __GNUC__
51 /* assert.h conflicts with #define of assert in perl.h */
52 #include <assert.h>
53 #endif
54 #include <string.h>
55 #include <stdarg.h>
56 #include <float.h>
57 #include <time.h>
58 #if defined(_MSC_VER) || defined(__MINGW32__)
59 #include <sys/utime.h>
60 #else
61 #include <utime.h>
62 #endif
63
64 #ifdef __GNUC__
65 /* Mingw32 defaults to globing command line 
66  * So we turn it off like this:
67  */
68 int _CRT_glob = 0;
69 #endif
70
71 #define EXECF_EXEC 1
72 #define EXECF_SPAWN 2
73 #define EXECF_SPAWN_NOWAIT 3
74
75 #if defined(PERL_OBJECT)
76 #undef win32_get_privlib
77 #define win32_get_privlib g_win32_get_privlib
78 #undef win32_get_sitelib
79 #define win32_get_sitelib g_win32_get_sitelib
80 #undef do_aspawn
81 #define do_aspawn g_do_aspawn
82 #undef do_spawn
83 #define do_spawn g_do_spawn
84 #undef do_exec
85 #define do_exec g_do_exec
86 #undef getlogin
87 #define getlogin g_getlogin
88 #endif
89
90 static DWORD            os_id(void);
91 static void             get_shell(void);
92 static long             tokenize(char *str, char **dest, char ***destv);
93         int             do_spawn2(char *cmd, int exectype);
94 static BOOL             has_shell_metachars(char *ptr);
95 static long             filetime_to_clock(PFILETIME ft);
96 static BOOL             filetime_from_time(PFILETIME ft, time_t t);
97 static char *           get_emd_part(char *leading, char *trailing, ...);
98 static void             remove_dead_process(long deceased);
99 static long             find_pid(int pid);
100 static char *           qualified_path(const char *cmd);
101
102 HANDLE  w32_perldll_handle = INVALID_HANDLE_VALUE;
103 char    w32_module_name[MAX_PATH+1];
104 static DWORD    w32_platform = (DWORD)-1;
105
106 #ifdef USE_THREADS
107 #  ifdef USE_DECLSPEC_THREAD
108 __declspec(thread) char strerror_buffer[512];
109 __declspec(thread) char getlogin_buffer[128];
110 __declspec(thread) char w32_perllib_root[MAX_PATH+1];
111 #    ifdef HAVE_DES_FCRYPT
112 __declspec(thread) char crypt_buffer[30];
113 #    endif
114 #  else
115 #    define strerror_buffer     (thr->i.Wstrerror_buffer)
116 #    define getlogin_buffer     (thr->i.Wgetlogin_buffer)
117 #    define w32_perllib_root    (thr->i.Ww32_perllib_root)
118 #    define crypt_buffer        (thr->i.Wcrypt_buffer)
119 #  endif
120 #else
121 static char     strerror_buffer[512];
122 static char     getlogin_buffer[128];
123 static char     w32_perllib_root[MAX_PATH+1];
124 #  ifdef HAVE_DES_FCRYPT
125 static char     crypt_buffer[30];
126 #  endif
127 #endif
128
129 int 
130 IsWin95(void) {
131     return (os_id() == VER_PLATFORM_WIN32_WINDOWS);
132 }
133
134 int
135 IsWinNT(void) {
136     return (os_id() == VER_PLATFORM_WIN32_NT);
137 }
138
139 char*
140 GetRegStrFromKey(HKEY hkey, const char *lpszValueName, char** ptr, DWORD* lpDataLen)
141 {   /* Retrieve a REG_SZ or REG_EXPAND_SZ from the registry */
142     HKEY handle;
143     DWORD type;
144     const char *subkey = "Software\\Perl";
145     long retval;
146
147     retval = RegOpenKeyEx(hkey, subkey, 0, KEY_READ, &handle);
148     if (retval == ERROR_SUCCESS){
149         retval = RegQueryValueEx(handle, lpszValueName, 0, &type, NULL, lpDataLen);
150         if (retval == ERROR_SUCCESS && type == REG_SZ) {
151             if (*ptr) {
152                 Renew(*ptr, *lpDataLen, char);
153             }
154             else {
155                 New(1312, *ptr, *lpDataLen, char);
156             }
157             retval = RegQueryValueEx(handle, lpszValueName, 0, NULL, (PBYTE)*ptr, lpDataLen);
158             if (retval != ERROR_SUCCESS) {
159                 Safefree(*ptr);
160                 *ptr = Nullch;
161             }
162         }
163         RegCloseKey(handle);
164     }
165     return *ptr;
166 }
167
168 char*
169 GetRegStr(const char *lpszValueName, char** ptr, DWORD* lpDataLen)
170 {
171     *ptr = GetRegStrFromKey(HKEY_CURRENT_USER, lpszValueName, ptr, lpDataLen);
172     if (*ptr == Nullch)
173     {
174         *ptr = GetRegStrFromKey(HKEY_LOCAL_MACHINE, lpszValueName, ptr, lpDataLen);
175     }
176     return *ptr;
177 }
178
179 static char *
180 get_emd_part(char *prev_path, char *trailing_path, ...)
181 {
182     char base[10];
183     va_list ap;
184     char mod_name[MAX_PATH+1];
185     char *ptr;
186     char *optr;
187     char *strip;
188     int oldsize, newsize;
189
190     va_start(ap, trailing_path);
191     strip = va_arg(ap, char *);
192
193     sprintf(base, "%5.3f",
194             (double)PERL_REVISION + ((double)PERL_VERSION / (double)1000));
195
196     if (!*w32_module_name) {
197         GetModuleFileName((HMODULE)((w32_perldll_handle == INVALID_HANDLE_VALUE)
198                                     ? GetModuleHandle(NULL)
199                                     : w32_perldll_handle),
200                           w32_module_name, sizeof(w32_module_name));
201
202         /* try to get full path to binary (which may be mangled when perl is
203          * run from a 16-bit app) */
204         /*PerlIO_printf(PerlIO_stderr(), "Before %s\n", w32_module_name);*/
205         (void)win32_longpath(w32_module_name);
206         /*PerlIO_printf(PerlIO_stderr(), "After  %s\n", w32_module_name);*/
207
208         /* normalize to forward slashes */
209         ptr = w32_module_name;
210         while (*ptr) {
211             if (*ptr == '\\')
212                 *ptr = '/';
213             ++ptr;
214         }
215     }
216     strcpy(mod_name, w32_module_name);
217     ptr = strrchr(mod_name, '/');
218     while (ptr && strip) {
219         /* look for directories to skip back */
220         optr = ptr;
221         *ptr = '\0';
222         ptr = strrchr(mod_name, '/');
223         if (!ptr || stricmp(ptr+1, strip) != 0) {
224             if(!(*strip == '5' && *(ptr+1) == '5'
225                  && strncmp(strip, base, 5) == 0
226                  && strncmp(ptr+1, base, 5) == 0))
227             {
228                 *optr = '/';
229                 ptr = optr;
230             }
231         }
232         strip = va_arg(ap, char *);
233     }
234     if (!ptr) {
235         ptr = mod_name;
236         *ptr++ = '.';
237         *ptr = '/';
238     }
239     va_end(ap);
240     strcpy(++ptr, trailing_path);
241
242     /* only add directory if it exists */
243     if(GetFileAttributes(mod_name) != (DWORD) -1) {
244         /* directory exists */
245         newsize = strlen(mod_name) + 1;
246         if (prev_path) {
247             oldsize = strlen(prev_path) + 1;
248             newsize += oldsize;                 /* includes plus 1 for ';' */
249             Renew(prev_path, newsize, char);
250             prev_path[oldsize-1] = ';';
251             strcpy(&prev_path[oldsize], mod_name);
252         }
253         else {
254             New(1311, prev_path, newsize, char);
255             strcpy(prev_path, mod_name);
256         }
257     }
258
259     return prev_path;
260 }
261
262 char *
263 win32_get_privlib(char *pl)
264 {
265     char *stdlib = "lib";
266     char buffer[MAX_PATH+1];
267     char *path = Nullch;
268     DWORD datalen;
269
270     /* $stdlib = $HKCU{"lib-$]"} || $HKLM{"lib-$]"} || $HKCU{"lib"} || $HKLM{"lib"} || "";  */
271     sprintf(buffer, "%s-%s", stdlib, pl);
272     path = GetRegStr(buffer, &path, &datalen);
273     if (!path)
274         path = GetRegStr(stdlib, &path, &datalen);
275
276     /* $stdlib .= ";$EMD/../../lib" */
277     return get_emd_part(path, stdlib, ARCHNAME, "bin", Nullch);
278 }
279
280 char *
281 win32_get_sitelib(char *pl)
282 {
283     char *sitelib = "sitelib";
284     char regstr[40];
285     char pathstr[MAX_PATH+1];
286     DWORD datalen;
287     char *path1 = Nullch;
288     char *path2 = Nullch;
289     int len, newsize;
290
291     /* $HKCU{"sitelib-$]"} || $HKLM{"sitelib-$]"} . ---; */
292     sprintf(regstr, "%s-%s", sitelib, pl);
293     path1 = GetRegStr(regstr, &path1, &datalen);
294
295     /* $sitelib .=
296      * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/site/$]/lib";  */
297     sprintf(pathstr, "site/%s/lib", pl);
298     path1 = get_emd_part(path1, pathstr, ARCHNAME, "bin", pl, Nullch);
299
300     /* $HKCU{'sitelib'} || $HKLM{'sitelib'} . ---; */
301     path2 = GetRegStr(sitelib, &path2, &datalen);
302
303     /* $sitelib .=
304      * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/site/lib";  */
305     path2 = get_emd_part(path2, "site/lib", ARCHNAME, "bin", pl, Nullch);
306
307     if (!path1)
308         return path2;
309
310     if (!path2)
311         return path1;
312
313     len = strlen(path1);
314     newsize = len + strlen(path2) + 2; /* plus one for ';' */
315
316     Renew(path1, newsize, char);
317     path1[len++] = ';';
318     strcpy(&path1[len], path2);
319
320     Safefree(path2);
321     return path1;
322 }
323
324
325 static BOOL
326 has_shell_metachars(char *ptr)
327 {
328     int inquote = 0;
329     char quote = '\0';
330
331     /*
332      * Scan string looking for redirection (< or >) or pipe
333      * characters (|) that are not in a quoted string.
334      * Shell variable interpolation (%VAR%) can also happen inside strings.
335      */
336     while (*ptr) {
337         switch(*ptr) {
338         case '%':
339             return TRUE;
340         case '\'':
341         case '\"':
342             if (inquote) {
343                 if (quote == *ptr) {
344                     inquote = 0;
345                     quote = '\0';
346                 }
347             }
348             else {
349                 quote = *ptr;
350                 inquote++;
351             }
352             break;
353         case '>':
354         case '<':
355         case '|':
356             if (!inquote)
357                 return TRUE;
358         default:
359             break;
360         }
361         ++ptr;
362     }
363     return FALSE;
364 }
365
366 #if !defined(PERL_OBJECT)
367 /* since the current process environment is being updated in util.c
368  * the library functions will get the correct environment
369  */
370 PerlIO *
371 my_popen(char *cmd, char *mode)
372 {
373 #ifdef FIXCMD
374 #define fixcmd(x)       {                                       \
375                             char *pspace = strchr((x),' ');     \
376                             if (pspace) {                       \
377                                 char *p = (x);                  \
378                                 while (p < pspace) {            \
379                                     if (*p == '/')              \
380                                         *p = '\\';              \
381                                     p++;                        \
382                                 }                               \
383                             }                                   \
384                         }
385 #else
386 #define fixcmd(x)
387 #endif
388     fixcmd(cmd);
389     PERL_FLUSHALL_FOR_CHILD;
390     return win32_popen(cmd, mode);
391 }
392
393 long
394 my_pclose(PerlIO *fp)
395 {
396     return win32_pclose(fp);
397 }
398 #endif
399
400 static DWORD
401 os_id(void)
402 {
403     static OSVERSIONINFO osver;
404
405     if (osver.dwPlatformId != w32_platform) {
406         memset(&osver, 0, sizeof(OSVERSIONINFO));
407         osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
408         GetVersionEx(&osver);
409         w32_platform = osver.dwPlatformId;
410     }
411     return (w32_platform);
412 }
413
414 /* Tokenize a string.  Words are null-separated, and the list
415  * ends with a doubled null.  Any character (except null and
416  * including backslash) may be escaped by preceding it with a
417  * backslash (the backslash will be stripped).
418  * Returns number of words in result buffer.
419  */
420 static long
421 tokenize(char *str, char **dest, char ***destv)
422 {
423     char *retstart = Nullch;
424     char **retvstart = 0;
425     int items = -1;
426     if (str) {
427         int slen = strlen(str);
428         register char *ret;
429         register char **retv;
430         New(1307, ret, slen+2, char);
431         New(1308, retv, (slen+3)/2, char*);
432
433         retstart = ret;
434         retvstart = retv;
435         *retv = ret;
436         items = 0;
437         while (*str) {
438             *ret = *str++;
439             if (*ret == '\\' && *str)
440                 *ret = *str++;
441             else if (*ret == ' ') {
442                 while (*str == ' ')
443                     str++;
444                 if (ret == retstart)
445                     ret--;
446                 else {
447                     *ret = '\0';
448                     ++items;
449                     if (*str)
450                         *++retv = ret+1;
451                 }
452             }
453             else if (!*str)
454                 ++items;
455             ret++;
456         }
457         retvstart[items] = Nullch;
458         *ret++ = '\0';
459         *ret = '\0';
460     }
461     *dest = retstart;
462     *destv = retvstart;
463     return items;
464 }
465
466 static void
467 get_shell(void)
468 {
469     if (!w32_perlshell_tokens) {
470         /* we don't use COMSPEC here for two reasons:
471          *  1. the same reason perl on UNIX doesn't use SHELL--rampant and
472          *     uncontrolled unportability of the ensuing scripts.
473          *  2. PERL5SHELL could be set to a shell that may not be fit for
474          *     interactive use (which is what most programs look in COMSPEC
475          *     for).
476          */
477         char* defaultshell = (IsWinNT() ? "cmd.exe /x/c" : "command.com /c");
478         char *usershell = getenv("PERL5SHELL");
479         w32_perlshell_items = tokenize(usershell ? usershell : defaultshell,
480                                        &w32_perlshell_tokens,
481                                        &w32_perlshell_vec);
482     }
483 }
484
485 int
486 do_aspawn(void *vreally, void **vmark, void **vsp)
487 {
488     SV *really = (SV*)vreally;
489     SV **mark = (SV**)vmark;
490     SV **sp = (SV**)vsp;
491     char **argv;
492     char *str;
493     int status;
494     int flag = P_WAIT;
495     int index = 0;
496
497     if (sp <= mark)
498         return -1;
499
500     get_shell();
501     New(1306, argv, (sp - mark) + w32_perlshell_items + 2, char*);
502
503     if (SvNIOKp(*(mark+1)) && !SvPOKp(*(mark+1))) {
504         ++mark;
505         flag = SvIVx(*mark);
506     }
507
508     while (++mark <= sp) {
509         if (*mark && (str = SvPV_nolen(*mark)))
510             argv[index++] = str;
511         else
512             argv[index++] = "";
513     }
514     argv[index++] = 0;
515    
516     status = win32_spawnvp(flag,
517                            (const char*)(really ? SvPV_nolen(really) : argv[0]),
518                            (const char* const*)argv);
519
520     if (status < 0 && (errno == ENOEXEC || errno == ENOENT)) {
521         /* possible shell-builtin, invoke with shell */
522         int sh_items;
523         sh_items = w32_perlshell_items;
524         while (--index >= 0)
525             argv[index+sh_items] = argv[index];
526         while (--sh_items >= 0)
527             argv[sh_items] = w32_perlshell_vec[sh_items];
528    
529         status = win32_spawnvp(flag,
530                                (const char*)(really ? SvPV_nolen(really) : argv[0]),
531                                (const char* const*)argv);
532     }
533
534     if (flag != P_NOWAIT) {
535         if (status < 0) {
536             if (PL_dowarn)
537                 warn("Can't spawn \"%s\": %s", argv[0], strerror(errno));
538             status = 255 * 256;
539         }
540         else
541             status *= 256;
542         PL_statusvalue = status;
543     }
544     Safefree(argv);
545     return (status);
546 }
547
548 int
549 do_spawn2(char *cmd, int exectype)
550 {
551     char **a;
552     char *s;
553     char **argv;
554     int status = -1;
555     BOOL needToTry = TRUE;
556     char *cmd2;
557
558     /* Save an extra exec if possible. See if there are shell
559      * metacharacters in it */
560     if (!has_shell_metachars(cmd)) {
561         New(1301,argv, strlen(cmd) / 2 + 2, char*);
562         New(1302,cmd2, strlen(cmd) + 1, char);
563         strcpy(cmd2, cmd);
564         a = argv;
565         for (s = cmd2; *s;) {
566             while (*s && isspace(*s))
567                 s++;
568             if (*s)
569                 *(a++) = s;
570             while (*s && !isspace(*s))
571                 s++;
572             if (*s)
573                 *s++ = '\0';
574         }
575         *a = Nullch;
576         if (argv[0]) {
577             switch (exectype) {
578             case EXECF_SPAWN:
579                 status = win32_spawnvp(P_WAIT, argv[0],
580                                        (const char* const*)argv);
581                 break;
582             case EXECF_SPAWN_NOWAIT:
583                 status = win32_spawnvp(P_NOWAIT, argv[0],
584                                        (const char* const*)argv);
585                 break;
586             case EXECF_EXEC:
587                 status = win32_execvp(argv[0], (const char* const*)argv);
588                 break;
589             }
590             if (status != -1 || errno == 0)
591                 needToTry = FALSE;
592         }
593         Safefree(argv);
594         Safefree(cmd2);
595     }
596     if (needToTry) {
597         char **argv;
598         int i = -1;
599         get_shell();
600         New(1306, argv, w32_perlshell_items + 2, char*);
601         while (++i < w32_perlshell_items)
602             argv[i] = w32_perlshell_vec[i];
603         argv[i++] = cmd;
604         argv[i] = Nullch;
605         switch (exectype) {
606         case EXECF_SPAWN:
607             status = win32_spawnvp(P_WAIT, argv[0],
608                                    (const char* const*)argv);
609             break;
610         case EXECF_SPAWN_NOWAIT:
611             status = win32_spawnvp(P_NOWAIT, argv[0],
612                                    (const char* const*)argv);
613             break;
614         case EXECF_EXEC:
615             status = win32_execvp(argv[0], (const char* const*)argv);
616             break;
617         }
618         cmd = argv[0];
619         Safefree(argv);
620     }
621     if (exectype != EXECF_SPAWN_NOWAIT) {
622         if (status < 0) {
623             if (PL_dowarn)
624                 warn("Can't %s \"%s\": %s",
625                      (exectype == EXECF_EXEC ? "exec" : "spawn"),
626                      cmd, strerror(errno));
627             status = 255 * 256;
628         }
629         else
630             status *= 256;
631         PL_statusvalue = status;
632     }
633     return (status);
634 }
635
636 int
637 do_spawn(char *cmd)
638 {
639     return do_spawn2(cmd, EXECF_SPAWN);
640 }
641
642 int
643 do_spawn_nowait(char *cmd)
644 {
645     return do_spawn2(cmd, EXECF_SPAWN_NOWAIT);
646 }
647
648 bool
649 do_exec(char *cmd)
650 {
651     do_spawn2(cmd, EXECF_EXEC);
652     return FALSE;
653 }
654
655 /* The idea here is to read all the directory names into a string table
656  * (separated by nulls) and when one of the other dir functions is called
657  * return the pointer to the current file name.
658  */
659 DIR *
660 win32_opendir(char *filename)
661 {
662     DIR                 *p;
663     long                len;
664     long                idx;
665     char                scanname[MAX_PATH+3];
666     struct stat         sbuf;
667     WIN32_FIND_DATA     FindData;
668     HANDLE              fh;
669
670     len = strlen(filename);
671     if (len > MAX_PATH)
672         return NULL;
673
674     /* check to see if filename is a directory */
675     if (win32_stat(filename, &sbuf) < 0 || !S_ISDIR(sbuf.st_mode))
676         return NULL;
677
678     /* Get us a DIR structure */
679     Newz(1303, p, 1, DIR);
680     if (p == NULL)
681         return NULL;
682
683     /* Create the search pattern */
684     strcpy(scanname, filename);
685     if (scanname[len-1] != '/' && scanname[len-1] != '\\')
686         scanname[len++] = '/';
687     scanname[len++] = '*';
688     scanname[len] = '\0';
689
690     /* do the FindFirstFile call */
691     fh = FindFirstFile(scanname, &FindData);
692     if (fh == INVALID_HANDLE_VALUE) {
693         /* FindFirstFile() fails on empty drives! */
694         if (GetLastError() == ERROR_FILE_NOT_FOUND)
695             return p;
696         Safefree( p);
697         return NULL;
698     }
699
700     /* now allocate the first part of the string table for
701      * the filenames that we find.
702      */
703     idx = strlen(FindData.cFileName)+1;
704     New(1304, p->start, idx, char);
705     if (p->start == NULL)
706         croak("opendir: malloc failed!\n");
707     strcpy(p->start, FindData.cFileName);
708     p->nfiles++;
709
710     /* loop finding all the files that match the wildcard
711      * (which should be all of them in this directory!).
712      * the variable idx should point one past the null terminator
713      * of the previous string found.
714      */
715     while (FindNextFile(fh, &FindData)) {
716         len = strlen(FindData.cFileName);
717         /* bump the string table size by enough for the
718          * new name and it's null terminator
719          */
720         Renew(p->start, idx+len+1, char);
721         if (p->start == NULL)
722             croak("opendir: malloc failed!\n");
723         strcpy(&p->start[idx], FindData.cFileName);
724         p->nfiles++;
725         idx += len+1;
726     }
727     FindClose(fh);
728     p->size = idx;
729     p->curr = p->start;
730     return p;
731 }
732
733
734 /* Readdir just returns the current string pointer and bumps the
735  * string pointer to the nDllExport entry.
736  */
737 struct direct *
738 win32_readdir(DIR *dirp)
739 {
740     int         len;
741     static int  dummy = 0;
742
743     if (dirp->curr) {
744         /* first set up the structure to return */
745         len = strlen(dirp->curr);
746         strcpy(dirp->dirstr.d_name, dirp->curr);
747         dirp->dirstr.d_namlen = len;
748
749         /* Fake an inode */
750         dirp->dirstr.d_ino = dummy++;
751
752         /* Now set up for the nDllExport call to readdir */
753         dirp->curr += len + 1;
754         if (dirp->curr >= (dirp->start + dirp->size)) {
755             dirp->curr = NULL;
756         }
757
758         return &(dirp->dirstr);
759     } 
760     else
761         return NULL;
762 }
763
764 /* Telldir returns the current string pointer position */
765 long
766 win32_telldir(DIR *dirp)
767 {
768     return (long) dirp->curr;
769 }
770
771
772 /* Seekdir moves the string pointer to a previously saved position
773  *(Saved by telldir).
774  */
775 void
776 win32_seekdir(DIR *dirp, long loc)
777 {
778     dirp->curr = (char *)loc;
779 }
780
781 /* Rewinddir resets the string pointer to the start */
782 void
783 win32_rewinddir(DIR *dirp)
784 {
785     dirp->curr = dirp->start;
786 }
787
788 /* free the memory allocated by opendir */
789 int
790 win32_closedir(DIR *dirp)
791 {
792     Safefree(dirp->start);
793     Safefree(dirp);
794     return 1;
795 }
796
797
798 /*
799  * various stubs
800  */
801
802
803 /* Ownership
804  *
805  * Just pretend that everyone is a superuser. NT will let us know if
806  * we don\'t really have permission to do something.
807  */
808
809 #define ROOT_UID    ((uid_t)0)
810 #define ROOT_GID    ((gid_t)0)
811
812 uid_t
813 getuid(void)
814 {
815     return ROOT_UID;
816 }
817
818 uid_t
819 geteuid(void)
820 {
821     return ROOT_UID;
822 }
823
824 gid_t
825 getgid(void)
826 {
827     return ROOT_GID;
828 }
829
830 gid_t
831 getegid(void)
832 {
833     return ROOT_GID;
834 }
835
836 int
837 setuid(uid_t auid)
838
839     return (auid == ROOT_UID ? 0 : -1);
840 }
841
842 int
843 setgid(gid_t agid)
844 {
845     return (agid == ROOT_GID ? 0 : -1);
846 }
847
848 char *
849 getlogin(void)
850 {
851     dTHR;
852     char *buf = getlogin_buffer;
853     DWORD size = sizeof(getlogin_buffer);
854     if (GetUserName(buf,&size))
855         return buf;
856     return (char*)NULL;
857 }
858
859 int
860 chown(const char *path, uid_t owner, gid_t group)
861 {
862     /* XXX noop */
863     return 0;
864 }
865
866 static long
867 find_pid(int pid)
868 {
869     long child;
870     for (child = 0 ; child < w32_num_children ; ++child) {
871         if (w32_child_pids[child] == pid)
872             return child;
873     }
874     return -1;
875 }
876
877 static void
878 remove_dead_process(long child)
879 {
880     if (child >= 0) {
881         CloseHandle(w32_child_handles[child]);
882         Copy(&w32_child_handles[child+1], &w32_child_handles[child],
883              (w32_num_children-child-1), HANDLE);
884         Copy(&w32_child_pids[child+1], &w32_child_pids[child],
885              (w32_num_children-child-1), DWORD);
886         w32_num_children--;
887     }
888 }
889
890 DllExport int
891 win32_kill(int pid, int sig)
892 {
893     HANDLE hProcess;
894     hProcess = OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid);
895     if (hProcess && TerminateProcess(hProcess, sig))
896         CloseHandle(hProcess);
897     else {
898         errno = EINVAL;
899         return -1;
900     }
901     return 0;
902 }
903
904 /*
905  * File system stuff
906  */
907
908 DllExport unsigned int
909 win32_sleep(unsigned int t)
910 {
911     Sleep(t*1000);
912     return 0;
913 }
914
915 DllExport int
916 win32_stat(const char *path, struct stat *buffer)
917 {
918     char        t[MAX_PATH+1]; 
919     int         l = strlen(path);
920     int         res;
921
922     if (l > 1) {
923         switch(path[l - 1]) {
924         /* FindFirstFile() and stat() are buggy with a trailing
925          * backslash, so change it to a forward slash :-( */
926         case '\\':
927             strncpy(t, path, l-1);
928             t[l - 1] = '/';
929             t[l] = '\0';
930             path = t;
931             break;
932         /* FindFirstFile() is buggy with "x:", so add a slash :-( */
933         case ':':
934             if (l == 2 && isALPHA(path[0])) {
935                 t[0] = path[0]; t[1] = ':'; t[2] = '/'; t[3] = '\0';
936                 l = 3;
937                 path = t;
938             }
939             break;
940         }
941     }
942     res = stat(path,buffer);
943     if (res < 0) {
944         /* CRT is buggy on sharenames, so make sure it really isn't.
945          * XXX using GetFileAttributesEx() will enable us to set
946          * buffer->st_*time (but note that's not available on the
947          * Windows of 1995) */
948         DWORD r = GetFileAttributes(path);
949         if (r != 0xffffffff && (r & FILE_ATTRIBUTE_DIRECTORY)) {
950             /* buffer may still contain old garbage since stat() failed */
951             Zero(buffer, 1, struct stat);
952             buffer->st_mode = S_IFDIR | S_IREAD;
953             errno = 0;
954             if (!(r & FILE_ATTRIBUTE_READONLY))
955                 buffer->st_mode |= S_IWRITE | S_IEXEC;
956             return 0;
957         }
958     }
959     else {
960         if (l == 3 && isALPHA(path[0]) && path[1] == ':'
961             && (path[2] == '\\' || path[2] == '/'))
962         {
963             /* The drive can be inaccessible, some _stat()s are buggy */
964             if (!GetVolumeInformation(path,NULL,0,NULL,NULL,NULL,NULL,0)) {
965                 errno = ENOENT;
966                 return -1;
967             }
968         }
969 #ifdef __BORLANDC__
970         if (S_ISDIR(buffer->st_mode))
971             buffer->st_mode |= S_IWRITE | S_IEXEC;
972         else if (S_ISREG(buffer->st_mode)) {
973             if (l >= 4 && path[l-4] == '.') {
974                 const char *e = path + l - 3;
975                 if (strnicmp(e,"exe",3)
976                     && strnicmp(e,"bat",3)
977                     && strnicmp(e,"com",3)
978                     && (IsWin95() || strnicmp(e,"cmd",3)))
979                     buffer->st_mode &= ~S_IEXEC;
980                 else
981                     buffer->st_mode |= S_IEXEC;
982             }
983             else
984                 buffer->st_mode &= ~S_IEXEC;
985         }
986 #endif
987     }
988     return res;
989 }
990
991 /* Find the longname of a given path.  path is destructively modified.
992  * It should have space for at least MAX_PATH characters. */
993 DllExport char *
994 win32_longpath(char *path)
995 {
996     WIN32_FIND_DATA fdata;
997     HANDLE fhand;
998     char tmpbuf[MAX_PATH+1];
999     char *tmpstart = tmpbuf;
1000     char *start = path;
1001     char sep;
1002     if (!path)
1003         return Nullch;
1004
1005     /* drive prefix */
1006     if (isALPHA(path[0]) && path[1] == ':' &&
1007         (path[2] == '/' || path[2] == '\\'))
1008     {
1009         start = path + 2;
1010         *tmpstart++ = path[0];
1011         *tmpstart++ = ':';
1012     }
1013     /* UNC prefix */
1014     else if ((path[0] == '/' || path[0] == '\\') &&
1015              (path[1] == '/' || path[1] == '\\'))
1016     {
1017         start = path + 2;
1018         *tmpstart++ = '/';
1019         *tmpstart++ = '/';
1020         /* copy machine name */
1021         while (*start && *start != '/' && *start != '\\')
1022             *tmpstart++ = *start++;
1023         if (*start) {
1024             *tmpstart++ = '/';
1025             start++;
1026             /* copy share name */
1027             while (*start && *start != '/' && *start != '\\')
1028                 *tmpstart++ = *start++;
1029         }
1030     }
1031     sep = *start++;
1032     if (sep == '/' || sep == '\\')
1033         *tmpstart++ = '/';
1034     *tmpstart = '\0';
1035     while (sep) {
1036         /* walk up to slash */
1037         while (*start && *start != '/' && *start != '\\')
1038             ++start;
1039
1040         /* discard doubled slashes */
1041         while (*start && (start[1] == '/' || start[1] == '\\'))
1042             ++start;
1043         sep = *start;
1044
1045         /* stop and find full name of component */
1046         *start = '\0';
1047         fhand = FindFirstFile(path,&fdata);
1048         if (fhand != INVALID_HANDLE_VALUE) {
1049             strcpy(tmpstart, fdata.cFileName);
1050             tmpstart += strlen(fdata.cFileName);
1051             if (sep)
1052                 *tmpstart++ = '/';
1053             *tmpstart = '\0';
1054             *start++ = sep;
1055             FindClose(fhand);
1056         }
1057         else {
1058             /* failed a step, just return without side effects */
1059             /*PerlIO_printf(PerlIO_stderr(), "Failed to find %s\n", path);*/
1060             *start = sep;
1061             return Nullch;
1062         }
1063     }
1064     strcpy(path,tmpbuf);
1065     return path;
1066 }
1067
1068 #ifndef USE_WIN32_RTL_ENV
1069
1070 DllExport char *
1071 win32_getenv(const char *name)
1072 {
1073     static char *curitem = Nullch;      /* XXX threadead */
1074     static DWORD curlen = 0;            /* XXX threadead */
1075     DWORD needlen;
1076     if (!curitem) {
1077         curlen = 512;
1078         New(1305,curitem,curlen,char);
1079     }
1080
1081     needlen = GetEnvironmentVariable(name,curitem,curlen);
1082     if (needlen != 0) {
1083         while (needlen > curlen) {
1084             Renew(curitem,needlen,char);
1085             curlen = needlen;
1086             needlen = GetEnvironmentVariable(name,curitem,curlen);
1087         }
1088     }
1089     else {
1090         /* allow any environment variables that begin with 'PERL'
1091            to be stored in the registry */
1092         if (curitem)
1093             *curitem = '\0';
1094
1095         if (strncmp(name, "PERL", 4) == 0) {
1096             if (curitem) {
1097                 Safefree(curitem);
1098                 curitem = Nullch;
1099                 curlen = 0;
1100             }
1101             curitem = GetRegStr(name, &curitem, &curlen);
1102         }
1103     }
1104     if (curitem && *curitem == '\0')
1105         return Nullch;
1106
1107     return curitem;
1108 }
1109
1110 DllExport int
1111 win32_putenv(const char *name)
1112 {
1113     char* curitem;
1114     char* val;
1115     int relval = -1;
1116     if(name) {
1117         New(1309,curitem,strlen(name)+1,char);
1118         strcpy(curitem, name);
1119         val = strchr(curitem, '=');
1120         if(val) {
1121             /* The sane way to deal with the environment.
1122              * Has these advantages over putenv() & co.:
1123              *  * enables us to store a truly empty value in the
1124              *    environment (like in UNIX).
1125              *  * we don't have to deal with RTL globals, bugs and leaks.
1126              *  * Much faster.
1127              * Why you may want to enable USE_WIN32_RTL_ENV:
1128              *  * environ[] and RTL functions will not reflect changes,
1129              *    which might be an issue if extensions want to access
1130              *    the env. via RTL.  This cuts both ways, since RTL will
1131              *    not see changes made by extensions that call the Win32
1132              *    functions directly, either.
1133              * GSAR 97-06-07
1134              */
1135             *val++ = '\0';
1136             if(SetEnvironmentVariable(curitem, *val ? val : NULL))
1137                 relval = 0;
1138         }
1139         Safefree(curitem);
1140     }
1141     return relval;
1142 }
1143
1144 #endif
1145
1146 static long
1147 filetime_to_clock(PFILETIME ft)
1148 {
1149  __int64 qw = ft->dwHighDateTime;
1150  qw <<= 32;
1151  qw |= ft->dwLowDateTime;
1152  qw /= 10000;  /* File time ticks at 0.1uS, clock at 1mS */
1153  return (long) qw;
1154 }
1155
1156 DllExport int
1157 win32_times(struct tms *timebuf)
1158 {
1159     FILETIME user;
1160     FILETIME kernel;
1161     FILETIME dummy;
1162     if (GetProcessTimes(GetCurrentProcess(), &dummy, &dummy, 
1163                         &kernel,&user)) {
1164         timebuf->tms_utime = filetime_to_clock(&user);
1165         timebuf->tms_stime = filetime_to_clock(&kernel);
1166         timebuf->tms_cutime = 0;
1167         timebuf->tms_cstime = 0;
1168         
1169     } else { 
1170         /* That failed - e.g. Win95 fallback to clock() */
1171         clock_t t = clock();
1172         timebuf->tms_utime = t;
1173         timebuf->tms_stime = 0;
1174         timebuf->tms_cutime = 0;
1175         timebuf->tms_cstime = 0;
1176     }
1177     return 0;
1178 }
1179
1180 /* fix utime() so it works on directories in NT
1181  * thanks to Jan Dubois <jan.dubois@ibm.net>
1182  */
1183 static BOOL
1184 filetime_from_time(PFILETIME pFileTime, time_t Time)
1185 {
1186     struct tm *pTM = gmtime(&Time);
1187     SYSTEMTIME SystemTime;
1188
1189     if (pTM == NULL)
1190         return FALSE;
1191
1192     SystemTime.wYear   = pTM->tm_year + 1900;
1193     SystemTime.wMonth  = pTM->tm_mon + 1;
1194     SystemTime.wDay    = pTM->tm_mday;
1195     SystemTime.wHour   = pTM->tm_hour;
1196     SystemTime.wMinute = pTM->tm_min;
1197     SystemTime.wSecond = pTM->tm_sec;
1198     SystemTime.wMilliseconds = 0;
1199
1200     return SystemTimeToFileTime(&SystemTime, pFileTime);
1201 }
1202
1203 DllExport int
1204 win32_utime(const char *filename, struct utimbuf *times)
1205 {
1206     HANDLE handle;
1207     FILETIME ftCreate;
1208     FILETIME ftAccess;
1209     FILETIME ftWrite;
1210     struct utimbuf TimeBuffer;
1211
1212     int rc = utime(filename,times);
1213     /* EACCES: path specifies directory or readonly file */
1214     if (rc == 0 || errno != EACCES /* || !IsWinNT() */)
1215         return rc;
1216
1217     if (times == NULL) {
1218         times = &TimeBuffer;
1219         time(&times->actime);
1220         times->modtime = times->actime;
1221     }
1222
1223     /* This will (and should) still fail on readonly files */
1224     handle = CreateFile(filename, GENERIC_READ | GENERIC_WRITE,
1225                         FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1226                         OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1227     if (handle == INVALID_HANDLE_VALUE)
1228         return rc;
1229
1230     if (GetFileTime(handle, &ftCreate, &ftAccess, &ftWrite) &&
1231         filetime_from_time(&ftAccess, times->actime) &&
1232         filetime_from_time(&ftWrite, times->modtime) &&
1233         SetFileTime(handle, &ftCreate, &ftAccess, &ftWrite))
1234     {
1235         rc = 0;
1236     }
1237
1238     CloseHandle(handle);
1239     return rc;
1240 }
1241
1242 DllExport int
1243 win32_uname(struct utsname *name)
1244 {
1245     struct hostent *hep;
1246     STRLEN nodemax = sizeof(name->nodename)-1;
1247     OSVERSIONINFO osver;
1248
1249     memset(&osver, 0, sizeof(OSVERSIONINFO));
1250     osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1251     if (GetVersionEx(&osver)) {
1252         /* sysname */
1253         switch (osver.dwPlatformId) {
1254         case VER_PLATFORM_WIN32_WINDOWS:
1255             strcpy(name->sysname, "Windows");
1256             break;
1257         case VER_PLATFORM_WIN32_NT:
1258             strcpy(name->sysname, "Windows NT");
1259             break;
1260         case VER_PLATFORM_WIN32s:
1261             strcpy(name->sysname, "Win32s");
1262             break;
1263         default:
1264             strcpy(name->sysname, "Win32 Unknown");
1265             break;
1266         }
1267
1268         /* release */
1269         sprintf(name->release, "%d.%d",
1270                 osver.dwMajorVersion, osver.dwMinorVersion);
1271
1272         /* version */
1273         sprintf(name->version, "Build %d",
1274                 osver.dwPlatformId == VER_PLATFORM_WIN32_NT
1275                 ? osver.dwBuildNumber : (osver.dwBuildNumber & 0xffff));
1276         if (osver.szCSDVersion[0]) {
1277             char *buf = name->version + strlen(name->version);
1278             sprintf(buf, " (%s)", osver.szCSDVersion);
1279         }
1280     }
1281     else {
1282         *name->sysname = '\0';
1283         *name->version = '\0';
1284         *name->release = '\0';
1285     }
1286
1287     /* nodename */
1288     hep = win32_gethostbyname("localhost");
1289     if (hep) {
1290         STRLEN len = strlen(hep->h_name);
1291         if (len <= nodemax) {
1292             strcpy(name->nodename, hep->h_name);
1293         }
1294         else {
1295             strncpy(name->nodename, hep->h_name, nodemax);
1296             name->nodename[nodemax] = '\0';
1297         }
1298     }
1299     else {
1300         DWORD sz = nodemax;
1301         if (!GetComputerName(name->nodename, &sz))
1302             *name->nodename = '\0';
1303     }
1304
1305     /* machine (architecture) */
1306     {
1307         SYSTEM_INFO info;
1308         char *arch;
1309         GetSystemInfo(&info);
1310         switch (info.wProcessorArchitecture) {
1311         case PROCESSOR_ARCHITECTURE_INTEL:
1312             arch = "x86"; break;
1313         case PROCESSOR_ARCHITECTURE_MIPS:
1314             arch = "mips"; break;
1315         case PROCESSOR_ARCHITECTURE_ALPHA:
1316             arch = "alpha"; break;
1317         case PROCESSOR_ARCHITECTURE_PPC:
1318             arch = "ppc"; break;
1319         default:
1320             arch = "unknown"; break;
1321         }
1322         strcpy(name->machine, arch);
1323     }
1324     return 0;
1325 }
1326
1327 DllExport int
1328 win32_waitpid(int pid, int *status, int flags)
1329 {
1330     int retval = -1;
1331     if (pid == -1) 
1332         return win32_wait(status);
1333     else {
1334         long child = find_pid(pid);
1335         if (child >= 0) {
1336             HANDLE hProcess = w32_child_handles[child];
1337             DWORD waitcode = WaitForSingleObject(hProcess, INFINITE);
1338             if (waitcode != WAIT_FAILED) {
1339                 if (GetExitCodeProcess(hProcess, &waitcode)) {
1340                     *status = (int)((waitcode & 0xff) << 8);
1341                     retval = (int)w32_child_pids[child];
1342                     remove_dead_process(child);
1343                     return retval;
1344                 }
1345             }
1346             else
1347                 errno = ECHILD;
1348         }
1349         else {
1350             retval = cwait(status, pid, WAIT_CHILD);
1351             /* cwait() returns "correctly" on Borland */
1352 #ifndef __BORLANDC__
1353             if (status)
1354                 *status *= 256;
1355 #endif
1356         }
1357     }
1358     return retval >= 0 ? pid : retval;                
1359 }
1360
1361 DllExport int
1362 win32_wait(int *status)
1363 {
1364     /* XXX this wait emulation only knows about processes
1365      * spawned via win32_spawnvp(P_NOWAIT, ...).
1366      */
1367     int i, retval;
1368     DWORD exitcode, waitcode;
1369
1370     if (!w32_num_children) {
1371         errno = ECHILD;
1372         return -1;
1373     }
1374
1375     /* if a child exists, wait for it to die */
1376     waitcode = WaitForMultipleObjects(w32_num_children,
1377                                       w32_child_handles,
1378                                       FALSE,
1379                                       INFINITE);
1380     if (waitcode != WAIT_FAILED) {
1381         if (waitcode >= WAIT_ABANDONED_0
1382             && waitcode < WAIT_ABANDONED_0 + w32_num_children)
1383             i = waitcode - WAIT_ABANDONED_0;
1384         else
1385             i = waitcode - WAIT_OBJECT_0;
1386         if (GetExitCodeProcess(w32_child_handles[i], &exitcode) ) {
1387             *status = (int)((exitcode & 0xff) << 8);
1388             retval = (int)w32_child_pids[i];
1389             remove_dead_process(i);
1390             return retval;
1391         }
1392     }
1393
1394 FAILED:
1395     errno = GetLastError();
1396     return -1;
1397 }
1398
1399 static UINT timerid = 0;
1400
1401 static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
1402 {
1403  KillTimer(NULL,timerid);
1404  timerid=0;  
1405  sighandler(14);
1406 }
1407
1408 DllExport unsigned int
1409 win32_alarm(unsigned int sec)
1410 {
1411     /* 
1412      * the 'obvious' implentation is SetTimer() with a callback
1413      * which does whatever receiving SIGALRM would do 
1414      * we cannot use SIGALRM even via raise() as it is not 
1415      * one of the supported codes in <signal.h>
1416      *
1417      * Snag is unless something is looking at the message queue
1418      * nothing happens :-(
1419      */ 
1420     if (sec)
1421      {
1422       timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
1423       if (!timerid)
1424        croak("Cannot set timer");
1425      } 
1426     else
1427      {
1428       if (timerid)
1429        {
1430         KillTimer(NULL,timerid);
1431         timerid=0;  
1432        }
1433      }
1434     return 0;
1435 }
1436
1437 #if defined(HAVE_DES_FCRYPT) || defined(PERL_OBJECT)
1438 #ifdef HAVE_DES_FCRYPT
1439 extern char *   des_fcrypt(const char *txt, const char *salt, char *cbuf);
1440 #endif
1441
1442 DllExport char *
1443 win32_crypt(const char *txt, const char *salt)
1444 {
1445 #ifdef HAVE_DES_FCRYPT
1446     dTHR;
1447     return des_fcrypt(txt, salt, crypt_buffer);
1448 #else
1449     die("The crypt() function is unimplemented due to excessive paranoia.");
1450     return Nullch;
1451 #endif
1452 }
1453 #endif
1454
1455 #ifdef USE_FIXED_OSFHANDLE
1456
1457 EXTERN_C int __cdecl _alloc_osfhnd(void);
1458 EXTERN_C int __cdecl _set_osfhnd(int fh, long value);
1459 EXTERN_C void __cdecl _lock_fhandle(int);
1460 EXTERN_C void __cdecl _unlock_fhandle(int);
1461 EXTERN_C void __cdecl _unlock(int);
1462
1463 #if     (_MSC_VER >= 1000)
1464 typedef struct  {
1465     long osfhnd;    /* underlying OS file HANDLE */
1466     char osfile;    /* attributes of file (e.g., open in text mode?) */
1467     char pipech;    /* one char buffer for handles opened on pipes */
1468 #if defined (_MT) && !defined (DLL_FOR_WIN32S)
1469     int lockinitflag;
1470     CRITICAL_SECTION lock;
1471 #endif  /* defined (_MT) && !defined (DLL_FOR_WIN32S) */
1472 }       ioinfo;
1473
1474 EXTERN_C ioinfo * __pioinfo[];
1475
1476 #define IOINFO_L2E                      5
1477 #define IOINFO_ARRAY_ELTS       (1 << IOINFO_L2E)
1478 #define _pioinfo(i)     (__pioinfo[i >> IOINFO_L2E] + (i & (IOINFO_ARRAY_ELTS - 1)))
1479 #define _osfile(i)      (_pioinfo(i)->osfile)
1480
1481 #else   /* (_MSC_VER >= 1000) */
1482 extern char _osfile[];
1483 #endif  /* (_MSC_VER >= 1000) */
1484
1485 #define FOPEN                   0x01    /* file handle open */
1486 #define FAPPEND                 0x20    /* file handle opened O_APPEND */
1487 #define FDEV                    0x40    /* file handle refers to device */
1488 #define FTEXT                   0x80    /* file handle is in text mode */
1489
1490 #define _STREAM_LOCKS   26              /* Table of stream locks */
1491 #define _LAST_STREAM_LOCK  (_STREAM_LOCKS+_NSTREAM_-1)  /* Last stream lock */
1492 #define _FH_LOCKS          (_LAST_STREAM_LOCK+1)        /* Table of fh locks */
1493
1494 /***
1495 *int my_open_osfhandle(long osfhandle, int flags) - open C Runtime file handle
1496 *
1497 *Purpose:
1498 *       This function allocates a free C Runtime file handle and associates
1499 *       it with the Win32 HANDLE specified by the first parameter. This is a
1500 *               temperary fix for WIN95's brain damage GetFileType() error on socket
1501 *               we just bypass that call for socket
1502 *
1503 *Entry:
1504 *       long osfhandle - Win32 HANDLE to associate with C Runtime file handle.
1505 *       int flags      - flags to associate with C Runtime file handle.
1506 *
1507 *Exit:
1508 *       returns index of entry in fh, if successful
1509 *       return -1, if no free entry is found
1510 *
1511 *Exceptions:
1512 *
1513 *******************************************************************************/
1514
1515 static int
1516 my_open_osfhandle(long osfhandle, int flags)
1517 {
1518     int fh;
1519     char fileflags;             /* _osfile flags */
1520
1521     /* copy relevant flags from second parameter */
1522     fileflags = FDEV;
1523
1524     if (flags & O_APPEND)
1525         fileflags |= FAPPEND;
1526
1527     if (flags & O_TEXT)
1528         fileflags |= FTEXT;
1529
1530     /* attempt to allocate a C Runtime file handle */
1531     if ((fh = _alloc_osfhnd()) == -1) {
1532         errno = EMFILE;         /* too many open files */
1533         _doserrno = 0L;         /* not an OS error */
1534         return -1;              /* return error to caller */
1535     }
1536
1537     /* the file is open. now, set the info in _osfhnd array */
1538     _set_osfhnd(fh, osfhandle);
1539
1540     fileflags |= FOPEN;         /* mark as open */
1541
1542 #if (_MSC_VER >= 1000)
1543     _osfile(fh) = fileflags;    /* set osfile entry */
1544     _unlock_fhandle(fh);
1545 #else
1546     _osfile[fh] = fileflags;    /* set osfile entry */
1547     _unlock(fh+_FH_LOCKS);              /* unlock handle */
1548 #endif
1549
1550     return fh;                  /* return handle */
1551 }
1552
1553 #define _open_osfhandle my_open_osfhandle
1554 #endif  /* USE_FIXED_OSFHANDLE */
1555
1556 /* simulate flock by locking a range on the file */
1557
1558 #define LK_ERR(f,i)     ((f) ? (i = 0) : (errno = GetLastError()))
1559 #define LK_LEN          0xffff0000
1560
1561 DllExport int
1562 win32_flock(int fd, int oper)
1563 {
1564     OVERLAPPED o;
1565     int i = -1;
1566     HANDLE fh;
1567
1568     if (!IsWinNT()) {
1569         croak("flock() unimplemented on this platform");
1570         return -1;
1571     }
1572     fh = (HANDLE)_get_osfhandle(fd);
1573     memset(&o, 0, sizeof(o));
1574
1575     switch(oper) {
1576     case LOCK_SH:               /* shared lock */
1577         LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
1578         break;
1579     case LOCK_EX:               /* exclusive lock */
1580         LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
1581         break;
1582     case LOCK_SH|LOCK_NB:       /* non-blocking shared lock */
1583         LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
1584         break;
1585     case LOCK_EX|LOCK_NB:       /* non-blocking exclusive lock */
1586         LK_ERR(LockFileEx(fh,
1587                        LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
1588                        0, LK_LEN, 0, &o),i);
1589         break;
1590     case LOCK_UN:               /* unlock lock */
1591         LK_ERR(UnlockFileEx(fh, 0, LK_LEN, 0, &o),i);
1592         break;
1593     default:                    /* unknown */
1594         errno = EINVAL;
1595         break;
1596     }
1597     return i;
1598 }
1599
1600 #undef LK_ERR
1601 #undef LK_LEN
1602
1603 /*
1604  *  redirected io subsystem for all XS modules
1605  *
1606  */
1607
1608 DllExport int *
1609 win32_errno(void)
1610 {
1611     return (&errno);
1612 }
1613
1614 DllExport char ***
1615 win32_environ(void)
1616 {
1617     return (&(_environ));
1618 }
1619
1620 /* the rest are the remapped stdio routines */
1621 DllExport FILE *
1622 win32_stderr(void)
1623 {
1624     return (stderr);
1625 }
1626
1627 DllExport FILE *
1628 win32_stdin(void)
1629 {
1630     return (stdin);
1631 }
1632
1633 DllExport FILE *
1634 win32_stdout()
1635 {
1636     return (stdout);
1637 }
1638
1639 DllExport int
1640 win32_ferror(FILE *fp)
1641 {
1642     return (ferror(fp));
1643 }
1644
1645
1646 DllExport int
1647 win32_feof(FILE *fp)
1648 {
1649     return (feof(fp));
1650 }
1651
1652 /*
1653  * Since the errors returned by the socket error function 
1654  * WSAGetLastError() are not known by the library routine strerror
1655  * we have to roll our own.
1656  */
1657
1658 DllExport char *
1659 win32_strerror(int e) 
1660 {
1661 #ifndef __BORLANDC__            /* Borland intolerance */
1662     extern int sys_nerr;
1663 #endif
1664     DWORD source = 0;
1665
1666     if (e < 0 || e > sys_nerr) {
1667         dTHR;
1668         if (e < 0)
1669             e = GetLastError();
1670
1671         if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
1672                          strerror_buffer, sizeof(strerror_buffer), NULL) == 0) 
1673             strcpy(strerror_buffer, "Unknown Error");
1674
1675         return strerror_buffer;
1676     }
1677     return strerror(e);
1678 }
1679
1680 DllExport void
1681 win32_str_os_error(void *sv, DWORD dwErr)
1682 {
1683     DWORD dwLen;
1684     char *sMsg;
1685     dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
1686                           |FORMAT_MESSAGE_IGNORE_INSERTS
1687                           |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
1688                            dwErr, 0, (char *)&sMsg, 1, NULL);
1689     if (0 < dwLen) {
1690         while (0 < dwLen  &&  isspace(sMsg[--dwLen]))
1691             ;
1692         if ('.' != sMsg[dwLen])
1693             dwLen++;
1694         sMsg[dwLen]= '\0';
1695     }
1696     if (0 == dwLen) {
1697         sMsg = (char*)LocalAlloc(0, 64/**sizeof(TCHAR)*/);
1698         dwLen = sprintf(sMsg,
1699                         "Unknown error #0x%lX (lookup 0x%lX)",
1700                         dwErr, GetLastError());
1701     }
1702     sv_setpvn((SV*)sv, sMsg, dwLen);
1703     LocalFree(sMsg);
1704 }
1705
1706
1707 DllExport int
1708 win32_fprintf(FILE *fp, const char *format, ...)
1709 {
1710     va_list marker;
1711     va_start(marker, format);     /* Initialize variable arguments. */
1712
1713     return (vfprintf(fp, format, marker));
1714 }
1715
1716 DllExport int
1717 win32_printf(const char *format, ...)
1718 {
1719     va_list marker;
1720     va_start(marker, format);     /* Initialize variable arguments. */
1721
1722     return (vprintf(format, marker));
1723 }
1724
1725 DllExport int
1726 win32_vfprintf(FILE *fp, const char *format, va_list args)
1727 {
1728     return (vfprintf(fp, format, args));
1729 }
1730
1731 DllExport int
1732 win32_vprintf(const char *format, va_list args)
1733 {
1734     return (vprintf(format, args));
1735 }
1736
1737 DllExport size_t
1738 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
1739 {
1740     return fread(buf, size, count, fp);
1741 }
1742
1743 DllExport size_t
1744 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
1745 {
1746     return fwrite(buf, size, count, fp);
1747 }
1748
1749 DllExport FILE *
1750 win32_fopen(const char *filename, const char *mode)
1751 {
1752     if (stricmp(filename, "/dev/null")==0)
1753         return fopen("NUL", mode);
1754     return fopen(filename, mode);
1755 }
1756
1757 #ifndef USE_SOCKETS_AS_HANDLES
1758 #undef fdopen
1759 #define fdopen my_fdopen
1760 #endif
1761
1762 DllExport FILE *
1763 win32_fdopen( int handle, const char *mode)
1764 {
1765     return fdopen(handle, (char *) mode);
1766 }
1767
1768 DllExport FILE *
1769 win32_freopen( const char *path, const char *mode, FILE *stream)
1770 {
1771     if (stricmp(path, "/dev/null")==0)
1772         return freopen("NUL", mode, stream);
1773     return freopen(path, mode, stream);
1774 }
1775
1776 DllExport int
1777 win32_fclose(FILE *pf)
1778 {
1779     return my_fclose(pf);       /* defined in win32sck.c */
1780 }
1781
1782 DllExport int
1783 win32_fputs(const char *s,FILE *pf)
1784 {
1785     return fputs(s, pf);
1786 }
1787
1788 DllExport int
1789 win32_fputc(int c,FILE *pf)
1790 {
1791     return fputc(c,pf);
1792 }
1793
1794 DllExport int
1795 win32_ungetc(int c,FILE *pf)
1796 {
1797     return ungetc(c,pf);
1798 }
1799
1800 DllExport int
1801 win32_getc(FILE *pf)
1802 {
1803     return getc(pf);
1804 }
1805
1806 DllExport int
1807 win32_fileno(FILE *pf)
1808 {
1809     return fileno(pf);
1810 }
1811
1812 DllExport void
1813 win32_clearerr(FILE *pf)
1814 {
1815     clearerr(pf);
1816     return;
1817 }
1818
1819 DllExport int
1820 win32_fflush(FILE *pf)
1821 {
1822     return fflush(pf);
1823 }
1824
1825 DllExport long
1826 win32_ftell(FILE *pf)
1827 {
1828     return ftell(pf);
1829 }
1830
1831 DllExport int
1832 win32_fseek(FILE *pf,long offset,int origin)
1833 {
1834     return fseek(pf, offset, origin);
1835 }
1836
1837 DllExport int
1838 win32_fgetpos(FILE *pf,fpos_t *p)
1839 {
1840     return fgetpos(pf, p);
1841 }
1842
1843 DllExport int
1844 win32_fsetpos(FILE *pf,const fpos_t *p)
1845 {
1846     return fsetpos(pf, p);
1847 }
1848
1849 DllExport void
1850 win32_rewind(FILE *pf)
1851 {
1852     rewind(pf);
1853     return;
1854 }
1855
1856 DllExport FILE*
1857 win32_tmpfile(void)
1858 {
1859     return tmpfile();
1860 }
1861
1862 DllExport void
1863 win32_abort(void)
1864 {
1865     abort();
1866     return;
1867 }
1868
1869 DllExport int
1870 win32_fstat(int fd,struct stat *sbufptr)
1871 {
1872     return fstat(fd,sbufptr);
1873 }
1874
1875 DllExport int
1876 win32_pipe(int *pfd, unsigned int size, int mode)
1877 {
1878     return _pipe(pfd, size, mode);
1879 }
1880
1881 /*
1882  * a popen() clone that respects PERL5SHELL
1883  */
1884
1885 DllExport FILE*
1886 win32_popen(const char *command, const char *mode)
1887 {
1888 #ifdef USE_RTL_POPEN
1889     return _popen(command, mode);
1890 #else
1891     int p[2];
1892     int parent, child;
1893     int stdfd, oldfd;
1894     int ourmode;
1895     int childpid;
1896
1897     /* establish which ends read and write */
1898     if (strchr(mode,'w')) {
1899         stdfd = 0;              /* stdin */
1900         parent = 1;
1901         child = 0;
1902     }
1903     else if (strchr(mode,'r')) {
1904         stdfd = 1;              /* stdout */
1905         parent = 0;
1906         child = 1;
1907     }
1908     else
1909         return NULL;
1910
1911     /* set the correct mode */
1912     if (strchr(mode,'b'))
1913         ourmode = O_BINARY;
1914     else if (strchr(mode,'t'))
1915         ourmode = O_TEXT;
1916     else
1917         ourmode = _fmode & (O_TEXT | O_BINARY);
1918
1919     /* the child doesn't inherit handles */
1920     ourmode |= O_NOINHERIT;
1921
1922     if (win32_pipe( p, 512, ourmode) == -1)
1923         return NULL;
1924
1925     /* save current stdfd */
1926     if ((oldfd = win32_dup(stdfd)) == -1)
1927         goto cleanup;
1928
1929     /* make stdfd go to child end of pipe (implicitly closes stdfd) */
1930     /* stdfd will be inherited by the child */
1931     if (win32_dup2(p[child], stdfd) == -1)
1932         goto cleanup;
1933
1934     /* close the child end in parent */
1935     win32_close(p[child]);
1936
1937     /* start the child */
1938     if ((childpid = do_spawn_nowait((char*)command)) == -1)
1939         goto cleanup;
1940
1941     /* revert stdfd to whatever it was before */
1942     if (win32_dup2(oldfd, stdfd) == -1)
1943         goto cleanup;
1944
1945     /* close saved handle */
1946     win32_close(oldfd);
1947
1948     sv_setiv(*av_fetch(w32_fdpid, p[parent], TRUE), childpid);
1949
1950     /* we have an fd, return a file stream */
1951     return (win32_fdopen(p[parent], (char *)mode));
1952
1953 cleanup:
1954     /* we don't need to check for errors here */
1955     win32_close(p[0]);
1956     win32_close(p[1]);
1957     if (oldfd != -1) {
1958         win32_dup2(oldfd, stdfd);
1959         win32_close(oldfd);
1960     }
1961     return (NULL);
1962
1963 #endif /* USE_RTL_POPEN */
1964 }
1965
1966 /*
1967  * pclose() clone
1968  */
1969
1970 DllExport int
1971 win32_pclose(FILE *pf)
1972 {
1973 #ifdef USE_RTL_POPEN
1974     return _pclose(pf);
1975 #else
1976
1977     int childpid, status;
1978     SV *sv;
1979
1980     sv = *av_fetch(w32_fdpid, win32_fileno(pf), TRUE);
1981     if (SvIOK(sv))
1982         childpid = SvIVX(sv);
1983     else
1984         childpid = 0;
1985
1986     if (!childpid) {
1987         errno = EBADF;
1988         return -1;
1989     }
1990
1991     win32_fclose(pf);
1992     SvIVX(sv) = 0;
1993
1994     if (win32_waitpid(childpid, &status, 0) == -1)
1995         return -1;
1996
1997     return status;
1998
1999 #endif /* USE_RTL_POPEN */
2000 }
2001
2002 DllExport int
2003 win32_rename(const char *oname, const char *newname)
2004 {
2005     /* XXX despite what the documentation says about MoveFileEx(),
2006      * it doesn't work under Windows95!
2007      */
2008     if (IsWinNT()) {
2009         if (!MoveFileEx(oname,newname,
2010                         MOVEFILE_COPY_ALLOWED|MOVEFILE_REPLACE_EXISTING)) {
2011             DWORD err = GetLastError();
2012             switch (err) {
2013             case ERROR_BAD_NET_NAME:
2014             case ERROR_BAD_NETPATH:
2015             case ERROR_BAD_PATHNAME:
2016             case ERROR_FILE_NOT_FOUND:
2017             case ERROR_FILENAME_EXCED_RANGE:
2018             case ERROR_INVALID_DRIVE:
2019             case ERROR_NO_MORE_FILES:
2020             case ERROR_PATH_NOT_FOUND:
2021                 errno = ENOENT;
2022                 break;
2023             default:
2024                 errno = EACCES;
2025                 break;
2026             }
2027             return -1;
2028         }
2029         return 0;
2030     }
2031     else {
2032         int retval = 0;
2033         char tmpname[MAX_PATH+1];
2034         char dname[MAX_PATH+1];
2035         char *endname = Nullch;
2036         STRLEN tmplen = 0;
2037         DWORD from_attr, to_attr;
2038
2039         /* if oname doesn't exist, do nothing */
2040         from_attr = GetFileAttributes(oname);
2041         if (from_attr == 0xFFFFFFFF) {
2042             errno = ENOENT;
2043             return -1;
2044         }
2045
2046         /* if newname exists, rename it to a temporary name so that we
2047          * don't delete it in case oname happens to be the same file
2048          * (but perhaps accessed via a different path)
2049          */
2050         to_attr = GetFileAttributes(newname);
2051         if (to_attr != 0xFFFFFFFF) {
2052             /* if newname is a directory, we fail
2053              * XXX could overcome this with yet more convoluted logic */
2054             if (to_attr & FILE_ATTRIBUTE_DIRECTORY) {
2055                 errno = EACCES;
2056                 return -1;
2057             }
2058             tmplen = strlen(newname);
2059             strcpy(tmpname,newname);
2060             endname = tmpname+tmplen;
2061             for (; endname > tmpname ; --endname) {
2062                 if (*endname == '/' || *endname == '\\') {
2063                     *endname = '\0';
2064                     break;
2065                 }
2066             }
2067             if (endname > tmpname)
2068                 endname = strcpy(dname,tmpname);
2069             else
2070                 endname = ".";
2071
2072             /* get a temporary filename in same directory
2073              * XXX is this really the best we can do? */
2074             if (!GetTempFileName((LPCTSTR)endname, "plr", 0, tmpname)) {
2075                 errno = ENOENT;
2076                 return -1;
2077             }
2078             DeleteFile(tmpname);
2079
2080             retval = rename(newname, tmpname);
2081             if (retval != 0) {
2082                 errno = EACCES;
2083                 return retval;
2084             }
2085         }
2086
2087         /* rename oname to newname */
2088         retval = rename(oname, newname);
2089
2090         /* if we created a temporary file before ... */
2091         if (endname != Nullch) {
2092             /* ...and rename succeeded, delete temporary file/directory */
2093             if (retval == 0)
2094                 DeleteFile(tmpname);
2095             /* else restore it to what it was */
2096             else
2097                 (void)rename(tmpname, newname);
2098         }
2099         return retval;
2100     }
2101 }
2102
2103 DllExport int
2104 win32_setmode(int fd, int mode)
2105 {
2106     return setmode(fd, mode);
2107 }
2108
2109 DllExport long
2110 win32_lseek(int fd, long offset, int origin)
2111 {
2112     return lseek(fd, offset, origin);
2113 }
2114
2115 DllExport long
2116 win32_tell(int fd)
2117 {
2118     return tell(fd);
2119 }
2120
2121 DllExport int
2122 win32_open(const char *path, int flag, ...)
2123 {
2124     va_list ap;
2125     int pmode;
2126
2127     va_start(ap, flag);
2128     pmode = va_arg(ap, int);
2129     va_end(ap);
2130
2131     if (stricmp(path, "/dev/null")==0)
2132         return open("NUL", flag, pmode);
2133     return open(path,flag,pmode);
2134 }
2135
2136 DllExport int
2137 win32_close(int fd)
2138 {
2139     return close(fd);
2140 }
2141
2142 DllExport int
2143 win32_eof(int fd)
2144 {
2145     return eof(fd);
2146 }
2147
2148 DllExport int
2149 win32_dup(int fd)
2150 {
2151     return dup(fd);
2152 }
2153
2154 DllExport int
2155 win32_dup2(int fd1,int fd2)
2156 {
2157     return dup2(fd1,fd2);
2158 }
2159
2160 DllExport int
2161 win32_read(int fd, void *buf, unsigned int cnt)
2162 {
2163     return read(fd, buf, cnt);
2164 }
2165
2166 DllExport int
2167 win32_write(int fd, const void *buf, unsigned int cnt)
2168 {
2169     return write(fd, buf, cnt);
2170 }
2171
2172 DllExport int
2173 win32_mkdir(const char *dir, int mode)
2174 {
2175     return mkdir(dir); /* just ignore mode */
2176 }
2177
2178 DllExport int
2179 win32_rmdir(const char *dir)
2180 {
2181     return rmdir(dir);
2182 }
2183
2184 DllExport int
2185 win32_chdir(const char *dir)
2186 {
2187     return chdir(dir);
2188 }
2189
2190 static char *
2191 create_command_line(const char* command, const char * const *args)
2192 {
2193     int index;
2194     char *cmd, *ptr, *arg;
2195     STRLEN len = strlen(command) + 1;
2196
2197     for (index = 0; (ptr = (char*)args[index]) != NULL; ++index)
2198         len += strlen(ptr) + 1;
2199
2200     New(1310, cmd, len, char);
2201     ptr = cmd;
2202     strcpy(ptr, command);
2203
2204     for (index = 0; (arg = (char*)args[index]) != NULL; ++index) {
2205         ptr += strlen(ptr);
2206         *ptr++ = ' ';
2207         strcpy(ptr, arg);
2208     }
2209
2210     return cmd;
2211 }
2212
2213 static char *
2214 qualified_path(const char *cmd)
2215 {
2216     char *pathstr;
2217     char *fullcmd, *curfullcmd;
2218     STRLEN cmdlen = 0;
2219     int has_slash = 0;
2220
2221     if (!cmd)
2222         return Nullch;
2223     fullcmd = (char*)cmd;
2224     while (*fullcmd) {
2225         if (*fullcmd == '/' || *fullcmd == '\\')
2226             has_slash++;
2227         fullcmd++;
2228         cmdlen++;
2229     }
2230
2231     /* look in PATH */
2232     pathstr = win32_getenv("PATH");
2233     New(0, fullcmd, MAX_PATH+1, char);
2234     curfullcmd = fullcmd;
2235
2236     while (1) {
2237         DWORD res;
2238
2239         /* start by appending the name to the current prefix */
2240         strcpy(curfullcmd, cmd);
2241         curfullcmd += cmdlen;
2242
2243         /* if it doesn't end with '.', or has no extension, try adding
2244          * a trailing .exe first */
2245         if (cmd[cmdlen-1] != '.'
2246             && (cmdlen < 4 || cmd[cmdlen-4] != '.'))
2247         {
2248             strcpy(curfullcmd, ".exe");
2249             res = GetFileAttributes(fullcmd);
2250             if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
2251                 return fullcmd;
2252             *curfullcmd = '\0';
2253         }
2254
2255         /* that failed, try the bare name */
2256         res = GetFileAttributes(fullcmd);
2257         if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
2258             return fullcmd;
2259
2260         /* quit if no other path exists, or if cmd already has path */
2261         if (!pathstr || !*pathstr || has_slash)
2262             break;
2263
2264         /* skip leading semis */
2265         while (*pathstr == ';')
2266             pathstr++;
2267
2268         /* build a new prefix from scratch */
2269         curfullcmd = fullcmd;
2270         while (*pathstr && *pathstr != ';') {
2271             if (*pathstr == '"') {      /* foo;"baz;etc";bar */
2272                 pathstr++;              /* skip initial '"' */
2273                 while (*pathstr && *pathstr != '"') {
2274                     if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
2275                         *curfullcmd++ = *pathstr;
2276                     pathstr++;
2277                 }
2278                 if (*pathstr)
2279                     pathstr++;          /* skip trailing '"' */
2280             }
2281             else {
2282                 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
2283                     *curfullcmd++ = *pathstr;
2284                 pathstr++;
2285             }
2286         }
2287         if (*pathstr)
2288             pathstr++;                  /* skip trailing semi */
2289         if (curfullcmd > fullcmd        /* append a dir separator */
2290             && curfullcmd[-1] != '/' && curfullcmd[-1] != '\\')
2291         {
2292             *curfullcmd++ = '\\';
2293         }
2294     }
2295 GIVE_UP:
2296     Safefree(fullcmd);
2297     return Nullch;
2298 }
2299
2300 /* XXX this needs to be made more compatible with the spawnvp()
2301  * provided by the various RTLs.  In particular, searching for
2302  * *.{com,bat,cmd} files (as done by the RTLs) is unimplemented.
2303  * This doesn't significantly affect perl itself, because we
2304  * always invoke things using PERL5SHELL if a direct attempt to
2305  * spawn the executable fails.
2306  * 
2307  * XXX splitting and rejoining the commandline between do_aspawn()
2308  * and win32_spawnvp() could also be avoided.
2309  */
2310
2311 DllExport int
2312 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
2313 {
2314 #ifdef USE_RTL_SPAWNVP
2315     return spawnvp(mode, cmdname, (char * const *)argv);
2316 #else
2317     DWORD ret;
2318     STARTUPINFO StartupInfo;
2319     PROCESS_INFORMATION ProcessInformation;
2320     DWORD create = 0;
2321
2322     char *cmd = create_command_line(cmdname, strcmp(cmdname, argv[0]) == 0
2323                                              ? &argv[1] : argv);
2324     char *fullcmd = Nullch;
2325
2326     switch(mode) {
2327     case P_NOWAIT:      /* asynch + remember result */
2328         if (w32_num_children >= MAXIMUM_WAIT_OBJECTS) {
2329             errno = EAGAIN;
2330             ret = -1;
2331             goto RETVAL;
2332         }
2333         /* FALL THROUGH */
2334     case P_WAIT:        /* synchronous execution */
2335         break;
2336     default:            /* invalid mode */
2337         errno = EINVAL;
2338         ret = -1;
2339         goto RETVAL;
2340     }
2341     memset(&StartupInfo,0,sizeof(StartupInfo));
2342     StartupInfo.cb = sizeof(StartupInfo);
2343     StartupInfo.wShowWindow = SW_SHOWDEFAULT;
2344
2345 RETRY:
2346     if (!CreateProcess(cmdname,         /* search PATH to find executable */
2347                        cmd,             /* executable, and its arguments */
2348                        NULL,            /* process attributes */
2349                        NULL,            /* thread attributes */
2350                        TRUE,            /* inherit handles */
2351                        create,          /* creation flags */
2352                        NULL,            /* inherit environment */
2353                        NULL,            /* inherit cwd */
2354                        &StartupInfo,
2355                        &ProcessInformation))
2356     {
2357         /* initial NULL argument to CreateProcess() does a PATH
2358          * search, but it always first looks in the directory
2359          * where the current process was started, which behavior
2360          * is undesirable for backward compatibility.  So we
2361          * jump through our own hoops by picking out the path
2362          * we really want it to use. */
2363         if (!fullcmd) {
2364             fullcmd = qualified_path(cmdname);
2365             if (fullcmd) {
2366                 cmdname = fullcmd;
2367                 goto RETRY;
2368             }
2369         }
2370         errno = ENOENT;
2371         ret = -1;
2372         goto RETVAL;
2373     }
2374
2375     if (mode == P_NOWAIT) {
2376         /* asynchronous spawn -- store handle, return PID */
2377         w32_child_handles[w32_num_children] = ProcessInformation.hProcess;
2378         ret = w32_child_pids[w32_num_children] = ProcessInformation.dwProcessId;
2379         ++w32_num_children;
2380     }
2381     else  {
2382         WaitForSingleObject(ProcessInformation.hProcess, INFINITE);
2383         GetExitCodeProcess(ProcessInformation.hProcess, &ret);
2384         CloseHandle(ProcessInformation.hProcess);
2385     }
2386
2387     CloseHandle(ProcessInformation.hThread);
2388 RETVAL:
2389     Safefree(cmd);
2390     Safefree(fullcmd);
2391     return (int)ret;
2392 #endif
2393 }
2394
2395 DllExport int
2396 win32_execv(const char *cmdname, const char *const *argv)
2397 {
2398     return execv(cmdname, (char *const *)argv);
2399 }
2400
2401 DllExport int
2402 win32_execvp(const char *cmdname, const char *const *argv)
2403 {
2404     return execvp(cmdname, (char *const *)argv);
2405 }
2406
2407 DllExport void
2408 win32_perror(const char *str)
2409 {
2410     perror(str);
2411 }
2412
2413 DllExport void
2414 win32_setbuf(FILE *pf, char *buf)
2415 {
2416     setbuf(pf, buf);
2417 }
2418
2419 DllExport int
2420 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
2421 {
2422     return setvbuf(pf, buf, type, size);
2423 }
2424
2425 DllExport int
2426 win32_flushall(void)
2427 {
2428     return flushall();
2429 }
2430
2431 DllExport int
2432 win32_fcloseall(void)
2433 {
2434     return fcloseall();
2435 }
2436
2437 DllExport char*
2438 win32_fgets(char *s, int n, FILE *pf)
2439 {
2440     return fgets(s, n, pf);
2441 }
2442
2443 DllExport char*
2444 win32_gets(char *s)
2445 {
2446     return gets(s);
2447 }
2448
2449 DllExport int
2450 win32_fgetc(FILE *pf)
2451 {
2452     return fgetc(pf);
2453 }
2454
2455 DllExport int
2456 win32_putc(int c, FILE *pf)
2457 {
2458     return putc(c,pf);
2459 }
2460
2461 DllExport int
2462 win32_puts(const char *s)
2463 {
2464     return puts(s);
2465 }
2466
2467 DllExport int
2468 win32_getchar(void)
2469 {
2470     return getchar();
2471 }
2472
2473 DllExport int
2474 win32_putchar(int c)
2475 {
2476     return putchar(c);
2477 }
2478
2479 #ifdef MYMALLOC
2480
2481 #ifndef USE_PERL_SBRK
2482
2483 static char *committed = NULL;
2484 static char *base      = NULL;
2485 static char *reserved  = NULL;
2486 static char *brk       = NULL;
2487 static DWORD pagesize  = 0;
2488 static DWORD allocsize = 0;
2489
2490 void *
2491 sbrk(int need)
2492 {
2493  void *result;
2494  if (!pagesize)
2495   {SYSTEM_INFO info;
2496    GetSystemInfo(&info);
2497    /* Pretend page size is larger so we don't perpetually
2498     * call the OS to commit just one page ...
2499     */
2500    pagesize = info.dwPageSize << 3;
2501    allocsize = info.dwAllocationGranularity;
2502   }
2503  /* This scheme fails eventually if request for contiguous
2504   * block is denied so reserve big blocks - this is only 
2505   * address space not memory ...
2506   */
2507  if (brk+need >= reserved)
2508   {
2509    DWORD size = 64*1024*1024;
2510    char *addr;
2511    if (committed && reserved && committed < reserved)
2512     {
2513      /* Commit last of previous chunk cannot span allocations */
2514      addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
2515      if (addr)
2516       committed = reserved;
2517     }
2518    /* Reserve some (more) space 
2519     * Note this is a little sneaky, 1st call passes NULL as reserved
2520     * so lets system choose where we start, subsequent calls pass
2521     * the old end address so ask for a contiguous block
2522     */
2523    addr  = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
2524    if (addr)
2525     {
2526      reserved = addr+size;
2527      if (!base)
2528       base = addr;
2529      if (!committed)
2530       committed = base;
2531      if (!brk)
2532       brk = committed;
2533     }
2534    else
2535     {
2536      return (void *) -1;
2537     }
2538   }
2539  result = brk;
2540  brk += need;
2541  if (brk > committed)
2542   {
2543    DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
2544    char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
2545    if (addr)
2546     {
2547      committed += size;
2548     }
2549    else
2550     return (void *) -1;
2551   }
2552  return result;
2553 }
2554
2555 #endif
2556 #endif
2557
2558 DllExport void*
2559 win32_malloc(size_t size)
2560 {
2561     return malloc(size);
2562 }
2563
2564 DllExport void*
2565 win32_calloc(size_t numitems, size_t size)
2566 {
2567     return calloc(numitems,size);
2568 }
2569
2570 DllExport void*
2571 win32_realloc(void *block, size_t size)
2572 {
2573     return realloc(block,size);
2574 }
2575
2576 DllExport void
2577 win32_free(void *block)
2578 {
2579     free(block);
2580 }
2581
2582
2583 int
2584 win32_open_osfhandle(long handle, int flags)
2585 {
2586     return _open_osfhandle(handle, flags);
2587 }
2588
2589 long
2590 win32_get_osfhandle(int fd)
2591 {
2592     return _get_osfhandle(fd);
2593 }
2594
2595 /*
2596  * Extras.
2597  */
2598
2599 static
2600 XS(w32_GetCwd)
2601 {
2602     dXSARGS;
2603     SV *sv = sv_newmortal();
2604     /* Make one call with zero size - return value is required size */
2605     DWORD len = GetCurrentDirectory((DWORD)0,NULL);
2606     SvUPGRADE(sv,SVt_PV);
2607     SvGROW(sv,len);
2608     SvCUR(sv) = GetCurrentDirectory((DWORD) SvLEN(sv), SvPVX(sv));
2609     /* 
2610      * If result != 0 
2611      *   then it worked, set PV valid, 
2612      *   else leave it 'undef' 
2613      */
2614     EXTEND(SP,1);
2615     if (SvCUR(sv)) {
2616         SvPOK_on(sv);
2617         ST(0) = sv;
2618         XSRETURN(1);
2619     }
2620     XSRETURN_UNDEF;
2621 }
2622
2623 static
2624 XS(w32_SetCwd)
2625 {
2626     dXSARGS;
2627     if (items != 1)
2628         croak("usage: Win32::SetCurrentDirectory($cwd)");
2629     if (SetCurrentDirectory(SvPV_nolen(ST(0))))
2630         XSRETURN_YES;
2631
2632     XSRETURN_NO;
2633 }
2634
2635 static
2636 XS(w32_GetNextAvailDrive)
2637 {
2638     dXSARGS;
2639     char ix = 'C';
2640     char root[] = "_:\\";
2641
2642     EXTEND(SP,1);
2643     while (ix <= 'Z') {
2644         root[0] = ix++;
2645         if (GetDriveType(root) == 1) {
2646             root[2] = '\0';
2647             XSRETURN_PV(root);
2648         }
2649     }
2650     XSRETURN_UNDEF;
2651 }
2652
2653 static
2654 XS(w32_GetLastError)
2655 {
2656     dXSARGS;
2657     EXTEND(SP,1);
2658     XSRETURN_IV(GetLastError());
2659 }
2660
2661 static
2662 XS(w32_SetLastError)
2663 {
2664     dXSARGS;
2665     if (items != 1)
2666         croak("usage: Win32::SetLastError($error)");
2667     SetLastError(SvIV(ST(0)));
2668     XSRETURN_EMPTY;
2669 }
2670
2671 static
2672 XS(w32_LoginName)
2673 {
2674     dXSARGS;
2675     char *name = getlogin_buffer;
2676     DWORD size = sizeof(getlogin_buffer);
2677     EXTEND(SP,1);
2678     if (GetUserName(name,&size)) {
2679         /* size includes NULL */
2680         ST(0) = sv_2mortal(newSVpvn(name,size-1));
2681         XSRETURN(1);
2682     }
2683     XSRETURN_UNDEF;
2684 }
2685
2686 static
2687 XS(w32_NodeName)
2688 {
2689     dXSARGS;
2690     char name[MAX_COMPUTERNAME_LENGTH+1];
2691     DWORD size = sizeof(name);
2692     EXTEND(SP,1);
2693     if (GetComputerName(name,&size)) {
2694         /* size does NOT include NULL :-( */
2695         ST(0) = sv_2mortal(newSVpvn(name,size));
2696         XSRETURN(1);
2697     }
2698     XSRETURN_UNDEF;
2699 }
2700
2701
2702 static
2703 XS(w32_DomainName)
2704 {
2705     dXSARGS;
2706 #ifndef HAS_NETWKSTAGETINFO
2707     /* mingw32 (and Win95) don't have NetWksta*(), so do it the old way */
2708     char name[256];
2709     DWORD size = sizeof(name);
2710     EXTEND(SP,1);
2711     if (GetUserName(name,&size)) {
2712         char sid[1024];
2713         DWORD sidlen = sizeof(sid);
2714         char dname[256];
2715         DWORD dnamelen = sizeof(dname);
2716         SID_NAME_USE snu;
2717         if (LookupAccountName(NULL, name, (PSID)&sid, &sidlen,
2718                               dname, &dnamelen, &snu)) {
2719             XSRETURN_PV(dname);         /* all that for this */
2720         }
2721     }
2722 #else
2723     /* this way is more reliable, in case user has a local account.
2724      * XXX need dynamic binding of netapi32.dll symbols or this will fail on
2725      * Win95. Probably makes more sense to move it into libwin32. */
2726     char dname[256];
2727     DWORD dnamelen = sizeof(dname);
2728     PWKSTA_INFO_100 pwi;
2729     EXTEND(SP,1);
2730     if (NERR_Success == NetWkstaGetInfo(NULL, 100, (LPBYTE*)&pwi)) {
2731         if (pwi->wki100_langroup && *(pwi->wki100_langroup)) {
2732             WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_langroup,
2733                                 -1, (LPSTR)dname, dnamelen, NULL, NULL);
2734         }
2735         else {
2736             WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_computername,
2737                                 -1, (LPSTR)dname, dnamelen, NULL, NULL);
2738         }
2739         NetApiBufferFree(pwi);
2740         XSRETURN_PV(dname);
2741     }
2742 #endif
2743     XSRETURN_UNDEF;
2744 }
2745
2746 static
2747 XS(w32_FsType)
2748 {
2749     dXSARGS;
2750     char fsname[256];
2751     DWORD flags, filecomplen;
2752     if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
2753                          &flags, fsname, sizeof(fsname))) {
2754         if (GIMME_V == G_ARRAY) {
2755             XPUSHs(sv_2mortal(newSVpvn(fsname,strlen(fsname))));
2756             XPUSHs(sv_2mortal(newSViv(flags)));
2757             XPUSHs(sv_2mortal(newSViv(filecomplen)));
2758             PUTBACK;
2759             return;
2760         }
2761         EXTEND(SP,1);
2762         XSRETURN_PV(fsname);
2763     }
2764     XSRETURN_EMPTY;
2765 }
2766
2767 static
2768 XS(w32_GetOSVersion)
2769 {
2770     dXSARGS;
2771     OSVERSIONINFO osver;
2772
2773     osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
2774     if (GetVersionEx(&osver)) {
2775         XPUSHs(newSVpvn(osver.szCSDVersion, strlen(osver.szCSDVersion)));
2776         XPUSHs(newSViv(osver.dwMajorVersion));
2777         XPUSHs(newSViv(osver.dwMinorVersion));
2778         XPUSHs(newSViv(osver.dwBuildNumber));
2779         XPUSHs(newSViv(osver.dwPlatformId));
2780         PUTBACK;
2781         return;
2782     }
2783     XSRETURN_EMPTY;
2784 }
2785
2786 static
2787 XS(w32_IsWinNT)
2788 {
2789     dXSARGS;
2790     EXTEND(SP,1);
2791     XSRETURN_IV(IsWinNT());
2792 }
2793
2794 static
2795 XS(w32_IsWin95)
2796 {
2797     dXSARGS;
2798     EXTEND(SP,1);
2799     XSRETURN_IV(IsWin95());
2800 }
2801
2802 static
2803 XS(w32_FormatMessage)
2804 {
2805     dXSARGS;
2806     DWORD source = 0;
2807     char msgbuf[1024];
2808
2809     if (items != 1)
2810         croak("usage: Win32::FormatMessage($errno)");
2811
2812     if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
2813                       &source, SvIV(ST(0)), 0,
2814                       msgbuf, sizeof(msgbuf)-1, NULL))
2815         XSRETURN_PV(msgbuf);
2816
2817     XSRETURN_UNDEF;
2818 }
2819
2820 static
2821 XS(w32_Spawn)
2822 {
2823     dXSARGS;
2824     char *cmd, *args;
2825     PROCESS_INFORMATION stProcInfo;
2826     STARTUPINFO stStartInfo;
2827     BOOL bSuccess = FALSE;
2828
2829     if (items != 3)
2830         croak("usage: Win32::Spawn($cmdName, $args, $PID)");
2831
2832     cmd = SvPV_nolen(ST(0));
2833     args = SvPV_nolen(ST(1));
2834
2835     memset(&stStartInfo, 0, sizeof(stStartInfo));   /* Clear the block */
2836     stStartInfo.cb = sizeof(stStartInfo);           /* Set the structure size */
2837     stStartInfo.dwFlags = STARTF_USESHOWWINDOW;     /* Enable wShowWindow control */
2838     stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE;   /* Start min (normal) */
2839
2840     if (CreateProcess(
2841                 cmd,                    /* Image path */
2842                 args,                   /* Arguments for command line */
2843                 NULL,                   /* Default process security */
2844                 NULL,                   /* Default thread security */
2845                 FALSE,                  /* Must be TRUE to use std handles */
2846                 NORMAL_PRIORITY_CLASS,  /* No special scheduling */
2847                 NULL,                   /* Inherit our environment block */
2848                 NULL,                   /* Inherit our currrent directory */
2849                 &stStartInfo,           /* -> Startup info */
2850                 &stProcInfo))           /* <- Process info (if OK) */
2851     {
2852         CloseHandle(stProcInfo.hThread);/* library source code does this. */
2853         sv_setiv(ST(2), stProcInfo.dwProcessId);
2854         bSuccess = TRUE;
2855     }
2856     XSRETURN_IV(bSuccess);
2857 }
2858
2859 static
2860 XS(w32_GetTickCount)
2861 {
2862     dXSARGS;
2863     EXTEND(SP,1);
2864     DWORD msec = GetTickCount();
2865     if ((IV)msec > 0)
2866         XSRETURN_IV(msec);
2867     XSRETURN_NV(msec);
2868 }
2869
2870 static
2871 XS(w32_GetShortPathName)
2872 {
2873     dXSARGS;
2874     SV *shortpath;
2875     DWORD len;
2876
2877     if (items != 1)
2878         croak("usage: Win32::GetShortPathName($longPathName)");
2879
2880     shortpath = sv_mortalcopy(ST(0));
2881     SvUPGRADE(shortpath, SVt_PV);
2882     /* src == target is allowed */
2883     do {
2884         len = GetShortPathName(SvPVX(shortpath),
2885                                SvPVX(shortpath),
2886                                SvLEN(shortpath));
2887     } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
2888     if (len) {
2889         SvCUR_set(shortpath,len);
2890         ST(0) = shortpath;
2891         XSRETURN(1);
2892     }
2893     XSRETURN_UNDEF;
2894 }
2895
2896 static
2897 XS(w32_GetFullPathName)
2898 {
2899     dXSARGS;
2900     SV *filename;
2901     SV *fullpath;
2902     char *filepart;
2903     DWORD len;
2904
2905     if (items != 1)
2906         croak("usage: Win32::GetFullPathName($filename)");
2907
2908     filename = ST(0);
2909     fullpath = sv_mortalcopy(filename);
2910     SvUPGRADE(fullpath, SVt_PV);
2911     do {
2912         len = GetFullPathName(SvPVX(filename),
2913                               SvLEN(fullpath),
2914                               SvPVX(fullpath),
2915                               &filepart);
2916     } while (len >= SvLEN(fullpath) && sv_grow(fullpath,len+1));
2917     if (len) {
2918         if (GIMME_V == G_ARRAY) {
2919             EXTEND(SP,1);
2920             XST_mPV(1,filepart);
2921             len = filepart - SvPVX(fullpath);
2922             items = 2;
2923         }
2924         SvCUR_set(fullpath,len);
2925         ST(0) = fullpath;
2926         XSRETURN(items);
2927     }
2928     XSRETURN_EMPTY;
2929 }
2930
2931 static
2932 XS(w32_GetLongPathName)
2933 {
2934     dXSARGS;
2935     SV *path;
2936     char tmpbuf[MAX_PATH+1];
2937     char *pathstr;
2938     STRLEN len;
2939
2940     if (items != 1)
2941         croak("usage: Win32::GetLongPathName($pathname)");
2942
2943     path = ST(0);
2944     pathstr = SvPV(path,len);
2945     strcpy(tmpbuf, pathstr);
2946     pathstr = win32_longpath(tmpbuf);
2947     if (pathstr) {
2948         ST(0) = sv_2mortal(newSVpvn(pathstr, strlen(pathstr)));
2949         XSRETURN(1);
2950     }
2951     XSRETURN_EMPTY;
2952 }
2953
2954 static
2955 XS(w32_Sleep)
2956 {
2957     dXSARGS;
2958     if (items != 1)
2959         croak("usage: Win32::Sleep($milliseconds)");
2960     Sleep(SvIV(ST(0)));
2961     XSRETURN_YES;
2962 }
2963
2964 static
2965 XS(w32_CopyFile)
2966 {
2967     dXSARGS;
2968     if (items != 3)
2969         croak("usage: Win32::CopyFile($from, $to, $overwrite)");
2970     if (CopyFile(SvPV_nolen(ST(0)), SvPV_nolen(ST(1)), !SvTRUE(ST(2))))
2971         XSRETURN_YES;
2972     XSRETURN_NO;
2973 }
2974
2975 void
2976 Perl_init_os_extras()
2977 {
2978     char *file = __FILE__;
2979     dXSUB_SYS;
2980
2981     w32_perlshell_tokens = Nullch;
2982     w32_perlshell_items = -1;
2983     w32_fdpid = newAV();                /* XXX needs to be in Perl_win32_init()? */
2984     New(1313, w32_children, 1, child_tab);
2985     w32_num_children = 0;
2986
2987     /* these names are Activeware compatible */
2988     newXS("Win32::GetCwd", w32_GetCwd, file);
2989     newXS("Win32::SetCwd", w32_SetCwd, file);
2990     newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
2991     newXS("Win32::GetLastError", w32_GetLastError, file);
2992     newXS("Win32::SetLastError", w32_SetLastError, file);
2993     newXS("Win32::LoginName", w32_LoginName, file);
2994     newXS("Win32::NodeName", w32_NodeName, file);
2995     newXS("Win32::DomainName", w32_DomainName, file);
2996     newXS("Win32::FsType", w32_FsType, file);
2997     newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
2998     newXS("Win32::IsWinNT", w32_IsWinNT, file);
2999     newXS("Win32::IsWin95", w32_IsWin95, file);
3000     newXS("Win32::FormatMessage", w32_FormatMessage, file);
3001     newXS("Win32::Spawn", w32_Spawn, file);
3002     newXS("Win32::GetTickCount", w32_GetTickCount, file);
3003     newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
3004     newXS("Win32::GetFullPathName", w32_GetFullPathName, file);
3005     newXS("Win32::GetLongPathName", w32_GetLongPathName, file);
3006     newXS("Win32::CopyFile", w32_CopyFile, file);
3007     newXS("Win32::Sleep", w32_Sleep, file);
3008
3009     /* XXX Bloat Alert! The following Activeware preloads really
3010      * ought to be part of Win32::Sys::*, so they're not included
3011      * here.
3012      */
3013     /* LookupAccountName
3014      * LookupAccountSID
3015      * InitiateSystemShutdown
3016      * AbortSystemShutdown
3017      * ExpandEnvrironmentStrings
3018      */
3019 }
3020
3021 void
3022 Perl_win32_init(int *argcp, char ***argvp)
3023 {
3024     /* Disable floating point errors, Perl will trap the ones we
3025      * care about.  VC++ RTL defaults to switching these off
3026      * already, but the Borland RTL doesn't.  Since we don't
3027      * want to be at the vendor's whim on the default, we set
3028      * it explicitly here.
3029      */
3030 #if !defined(_ALPHA_) && !defined(__GNUC__)
3031     _control87(MCW_EM, MCW_EM);
3032 #endif
3033     MALLOC_INIT;
3034 }
3035
3036 #ifdef USE_BINMODE_SCRIPTS
3037
3038 void
3039 win32_strip_return(SV *sv)
3040 {
3041  char *s = SvPVX(sv);
3042  char *e = s+SvCUR(sv);
3043  char *d = s;
3044  while (s < e)
3045   {
3046    if (*s == '\r' && s[1] == '\n')
3047     {
3048      *d++ = '\n';
3049      s += 2;
3050     }
3051    else 
3052     {
3053      *d++ = *s++;
3054     }   
3055   }
3056  SvCUR_set(sv,d-SvPVX(sv)); 
3057 }
3058
3059 #endif