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