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