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