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