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