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