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