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