This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
better perl version output in corelist-diff
[perl5.git] / win32 / wince.c
1 /*  WINCE.C - stuff for Windows CE
2  *
3  *  Time-stamp: <26/10/01 15:25:20 keuchel@keuchelnt>
4  *
5  *  You may distribute under the terms of either the GNU General Public
6  *  License or the Artistic License, as specified in the README file.
7  */
8
9 #define WIN32_LEAN_AND_MEAN
10 #define WIN32IO_IS_STDIO
11 #include <windows.h>
12 #include <signal.h>
13
14 #define PERLIO_NOT_STDIO 0
15
16 #if !defined(PERLIO_IS_STDIO) && !defined(USE_SFIO)
17 #define PerlIO FILE
18 #endif
19
20 #define wince_private
21 #include "errno.h"
22
23 #include "EXTERN.h"
24 #include "perl.h"
25
26 #define NO_XSLOCKS
27 #define PERL_NO_GET_CONTEXT
28 #include "XSUB.h"
29
30 #include "win32iop.h"
31 #include <string.h>
32 #include <stdarg.h>
33 #include <float.h>
34 #include <shellapi.h>
35 #include <process.h>
36
37 #define perl
38 #include "celib_defs.h"
39 #include "cewin32.h"
40 #include "cecrt.h"
41 #include "cewin32_defs.h"
42 #include "cecrt_defs.h"
43
44 #define GetCurrentDirectoryW XCEGetCurrentDirectoryW
45
46 #ifdef PALM_SIZE
47 #include "stdio-palmsize.h"
48 #endif
49
50 #define EXECF_EXEC 1
51 #define EXECF_SPAWN 2
52 #define EXECF_SPAWN_NOWAIT 3
53
54 #if defined(PERL_IMPLICIT_SYS)
55 #  undef win32_get_privlib
56 #  define win32_get_privlib g_win32_get_privlib
57 #  undef win32_get_sitelib
58 #  define win32_get_sitelib g_win32_get_sitelib
59 #  undef win32_get_vendorlib
60 #  define win32_get_vendorlib g_win32_get_vendorlib
61 #  undef do_spawn
62 #  define do_spawn g_do_spawn
63 #  undef getlogin
64 #  define getlogin g_getlogin
65 #endif
66
67 static void             get_shell(void);
68 static long             tokenize(const char *str, char **dest, char ***destv);
69 static int              do_spawn2(pTHX_ char *cmd, int exectype);
70 static BOOL             has_shell_metachars(char *ptr);
71 static long             filetime_to_clock(PFILETIME ft);
72 static BOOL             filetime_from_time(PFILETIME ft, time_t t);
73 static char *           get_emd_part(SV **leading, STRLEN *const len,
74                                      char *trailing, ...);
75 static void             remove_dead_process(long deceased);
76 static long             find_pid(int pid);
77 static char *           qualified_path(const char *cmd);
78 static char *           win32_get_xlib(const char *pl, const char *xlib,
79                                        const char *libname, STRLEN *const len);
80
81 #ifdef USE_ITHREADS
82 static void             remove_dead_pseudo_process(long child);
83 static long             find_pseudo_pid(int pid);
84 #endif
85
86 int _fmode = O_TEXT; /* celib do not provide _fmode, so we define it here */
87
88 START_EXTERN_C
89 HANDLE  w32_perldll_handle = INVALID_HANDLE_VALUE;
90 char    w32_module_name[MAX_PATH+1];
91 END_EXTERN_C
92
93 static DWORD    w32_platform = (DWORD)-1;
94
95 int
96 IsWin95(void)
97 {
98   return (win32_os_id() == VER_PLATFORM_WIN32_WINDOWS);
99 }
100
101 int
102 IsWinNT(void)
103 {
104   return (win32_os_id() == VER_PLATFORM_WIN32_NT);
105 }
106
107 int
108 IsWinCE(void)
109 {
110   return (win32_os_id() == VER_PLATFORM_WIN32_CE);
111 }
112
113 EXTERN_C void
114 set_w32_module_name(void)
115 {
116   char* ptr;
117   XCEGetModuleFileNameA((HMODULE)((w32_perldll_handle == INVALID_HANDLE_VALUE)
118                                   ? XCEGetModuleHandleA(NULL)
119                                   : w32_perldll_handle),
120                         w32_module_name, sizeof(w32_module_name));
121
122   /* normalize to forward slashes */
123   ptr = w32_module_name;
124   while (*ptr) {
125     if (*ptr == '\\')
126       *ptr = '/';
127     ++ptr;
128   }
129 }
130
131 /* *svp (if non-NULL) is expected to be POK (valid allocated SvPVX(*svp)) */
132 static char*
133 get_regstr_from(HKEY hkey, const char *valuename, SV **svp)
134 {
135     /* Retrieve a REG_SZ or REG_EXPAND_SZ from the registry */
136     HKEY handle;
137     DWORD type;
138     const char *subkey = "Software\\Perl";
139     char *str = NULL;
140     long retval;
141
142     retval = XCERegOpenKeyExA(hkey, subkey, 0, KEY_READ, &handle);
143     if (retval == ERROR_SUCCESS) {
144         DWORD datalen;
145         retval = XCERegQueryValueExA(handle, valuename, 0, &type, NULL, &datalen);
146         if (retval == ERROR_SUCCESS && type == REG_SZ) {
147             dTHX;
148             if (!*svp)
149                 *svp = sv_2mortal(newSVpvn("",0));
150             SvGROW(*svp, datalen);
151             retval = XCERegQueryValueExA(handle, valuename, 0, NULL,
152                                      (PBYTE)SvPVX(*svp), &datalen);
153             if (retval == ERROR_SUCCESS) {
154                 str = SvPVX(*svp);
155                 SvCUR_set(*svp,datalen-1);
156             }
157         }
158         RegCloseKey(handle);
159     }
160     return str;
161 }
162
163 /* *svp (if non-NULL) is expected to be POK (valid allocated SvPVX(*svp)) */
164 static char*
165 get_regstr(const char *valuename, SV **svp)
166 {
167     char *str = get_regstr_from(HKEY_CURRENT_USER, valuename, svp);
168     if (!str)
169         str = get_regstr_from(HKEY_LOCAL_MACHINE, valuename, svp);
170     return str;
171 }
172
173 /* *prev_pathp (if non-NULL) is expected to be POK (valid allocated SvPVX(sv)) */
174 static char *
175 get_emd_part(SV **prev_pathp, STRLEN *const len, char *trailing_path, ...)
176 {
177     char base[10];
178     va_list ap;
179     char mod_name[MAX_PATH+1];
180     char *ptr;
181     char *optr;
182     char *strip;
183     int oldsize, newsize;
184     STRLEN baselen;
185
186     va_start(ap, trailing_path);
187     strip = va_arg(ap, char *);
188
189     sprintf(base, "%d.%d", (int)PERL_REVISION, (int)PERL_VERSION);
190     baselen = strlen(base);
191
192     if (!*w32_module_name) {
193         set_w32_module_name();
194     }
195     strcpy(mod_name, w32_module_name);
196     ptr = strrchr(mod_name, '/');
197     while (ptr && strip) {
198         /* look for directories to skip back */
199         optr = ptr;
200         *ptr = '\0';
201         ptr = strrchr(mod_name, '/');
202         /* avoid stripping component if there is no slash,
203          * or it doesn't match ... */
204         if (!ptr || stricmp(ptr+1, strip) != 0) {
205             /* ... but not if component matches m|5\.$patchlevel.*| */
206             if (!ptr || !(*strip == '5' && *(ptr+1) == '5'
207                           && strncmp(strip, base, baselen) == 0
208                           && strncmp(ptr+1, base, baselen) == 0))
209             {
210                 *optr = '/';
211                 ptr = optr;
212             }
213         }
214         strip = va_arg(ap, char *);
215     }
216     if (!ptr) {
217         ptr = mod_name;
218         *ptr++ = '.';
219         *ptr = '/';
220     }
221     va_end(ap);
222     strcpy(++ptr, trailing_path);
223
224     /* only add directory if it exists */
225     if (XCEGetFileAttributesA(mod_name) != (DWORD) -1) {
226         /* directory exists */
227         dTHX;
228         if (!*prev_pathp)
229             *prev_pathp = sv_2mortal(newSVpvn("",0));
230         sv_catpvn(*prev_pathp, ";", 1);
231         sv_catpv(*prev_pathp, mod_name);
232         if(len)
233             *len = SvCUR(*prev_pathp);
234         return SvPVX(*prev_pathp);
235     }
236
237     return NULL;
238 }
239
240 char *
241 win32_get_privlib(const char *pl, STRLEN *const len)
242 {
243     dTHX;
244     char *stdlib = "lib";
245     char buffer[MAX_PATH+1];
246     SV *sv = NULL;
247
248     /* $stdlib = $HKCU{"lib-$]"} || $HKLM{"lib-$]"} || $HKCU{"lib"} || $HKLM{"lib"} || "";  */
249     sprintf(buffer, "%s-%s", stdlib, pl);
250     if (!get_regstr(buffer, &sv))
251         (void)get_regstr(stdlib, &sv);
252
253     /* $stdlib .= ";$EMD/../../lib" */
254     return get_emd_part(&sv, len, stdlib, ARCHNAME, "bin", NULL);
255 }
256
257 static char *
258 win32_get_xlib(const char *pl, const char *xlib, const char *libname,
259                STRLEN *const len)
260 {
261     dTHX;
262     char regstr[40];
263     char pathstr[MAX_PATH+1];
264     DWORD datalen;
265     int len, newsize;
266     SV *sv1 = NULL;
267     SV *sv2 = NULL;
268
269     /* $HKCU{"$xlib-$]"} || $HKLM{"$xlib-$]"} . ---; */
270     sprintf(regstr, "%s-%s", xlib, pl);
271     (void)get_regstr(regstr, &sv1);
272
273     /* $xlib .=
274      * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/$libname/$]/lib";  */
275     sprintf(pathstr, "%s/%s/lib", libname, pl);
276     (void)get_emd_part(&sv1, NULL, pathstr, ARCHNAME, "bin", pl, NULL);
277
278     /* $HKCU{$xlib} || $HKLM{$xlib} . ---; */
279     (void)get_regstr(xlib, &sv2);
280
281     /* $xlib .=
282      * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/$libname/lib";  */
283     sprintf(pathstr, "%s/lib", libname);
284     (void)get_emd_part(&sv2, NULL, pathstr, ARCHNAME, "bin", pl, NULL);
285
286     if (!sv1 && !sv2)
287         return NULL;
288     if (!sv1) {
289         sv1 = sv2;
290     } else if (sv2) {
291         sv_catpvn(sv1, ";", 1);
292         sv_catsv(sv1, sv2);
293     }
294
295     if (len)
296         *len = SvCUR(sv1);
297     return SvPVX(sv1);
298 }
299
300 char *
301 win32_get_sitelib(const char *pl, STRLEN *const len)
302 {
303     return win32_get_xlib(pl, "sitelib", "site", len);
304 }
305
306 #ifndef PERL_VENDORLIB_NAME
307 #  define PERL_VENDORLIB_NAME   "vendor"
308 #endif
309
310 char *
311 win32_get_vendorlib(const char *pl, STRLEN *const len)
312 {
313     return win32_get_xlib(pl, "vendorlib", PERL_VENDORLIB_NAME, len);
314 }
315
316 static BOOL
317 has_shell_metachars(char *ptr)
318 {
319     int inquote = 0;
320     char quote = '\0';
321
322     /*
323      * Scan string looking for redirection (< or >) or pipe
324      * characters (|) that are not in a quoted string.
325      * Shell variable interpolation (%VAR%) can also happen inside strings.
326      */
327     while (*ptr) {
328         switch(*ptr) {
329         case '%':
330             return TRUE;
331         case '\'':
332         case '\"':
333             if (inquote) {
334                 if (quote == *ptr) {
335                     inquote = 0;
336                     quote = '\0';
337                 }
338             }
339             else {
340                 quote = *ptr;
341                 inquote++;
342             }
343             break;
344         case '>':
345         case '<':
346         case '|':
347             if (!inquote)
348                 return TRUE;
349         default:
350             break;
351         }
352         ++ptr;
353     }
354     return FALSE;
355 }
356
357 #if !defined(PERL_IMPLICIT_SYS)
358 /* since the current process environment is being updated in util.c
359  * the library functions will get the correct environment
360  */
361 PerlIO *
362 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
363 {
364   printf("popen(%s)\n", cmd);
365
366   Perl_croak(aTHX_ PL_no_func, "popen");
367   return NULL;
368 }
369
370 long
371 Perl_my_pclose(pTHX_ PerlIO *fp)
372 {
373   Perl_croak(aTHX_ PL_no_func, "pclose");
374   return -1;
375 }
376 #endif
377
378 DllExport unsigned long
379 win32_os_id(void)
380 {
381     static OSVERSIONINFOA osver;
382
383     if (osver.dwPlatformId != w32_platform) {
384         memset(&osver, 0, sizeof(OSVERSIONINFOA));
385         osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOA);
386         XCEGetVersionExA(&osver);
387         w32_platform = osver.dwPlatformId;
388     }
389     return (unsigned long)w32_platform;
390 }
391
392 DllExport int
393 win32_getpid(void)
394 {
395     int pid;
396 #ifdef USE_ITHREADS
397     dTHX;
398     if (w32_pseudo_id)
399         return -((int)w32_pseudo_id);
400 #endif
401     pid = xcegetpid();
402     return pid;
403 }
404
405 /* Tokenize a string.  Words are null-separated, and the list
406  * ends with a doubled null.  Any character (except null and
407  * including backslash) may be escaped by preceding it with a
408  * backslash (the backslash will be stripped).
409  * Returns number of words in result buffer.
410  */
411 static long
412 tokenize(const char *str, char **dest, char ***destv)
413 {
414     char *retstart = NULL;
415     char **retvstart = 0;
416     int items = -1;
417     if (str) {
418         dTHX;
419         int slen = strlen(str);
420         register char *ret;
421         register char **retv;
422         Newx(ret, slen+2, char);
423         Newx(retv, (slen+3)/2, char*);
424
425         retstart = ret;
426         retvstart = retv;
427         *retv = ret;
428         items = 0;
429         while (*str) {
430             *ret = *str++;
431             if (*ret == '\\' && *str)
432                 *ret = *str++;
433             else if (*ret == ' ') {
434                 while (*str == ' ')
435                     str++;
436                 if (ret == retstart)
437                     ret--;
438                 else {
439                     *ret = '\0';
440                     ++items;
441                     if (*str)
442                         *++retv = ret+1;
443                 }
444             }
445             else if (!*str)
446                 ++items;
447             ret++;
448         }
449         retvstart[items] = NULL;
450         *ret++ = '\0';
451         *ret = '\0';
452     }
453     *dest = retstart;
454     *destv = retvstart;
455     return items;
456 }
457
458 DllExport int
459 win32_pipe(int *pfd, unsigned int size, int mode)
460 {
461   dTHX;
462   Perl_croak(aTHX_ PL_no_func, "pipe");
463   return -1;
464 }
465
466 DllExport int
467 win32_times(struct tms *timebuf)
468 {
469   dTHX;
470   Perl_croak(aTHX_ PL_no_func, "times");
471   return -1;
472 }
473
474 Sighandler_t
475 win32_signal(int sig, Sighandler_t subcode)
476 {
477   return xcesignal(sig, subcode);
478 }
479
480 static void
481 get_shell(void)
482 {
483     dTHX;
484     if (!w32_perlshell_tokens) {
485         /* we don't use COMSPEC here for two reasons:
486          *  1. the same reason perl on UNIX doesn't use SHELL--rampant and
487          *     uncontrolled unportability of the ensuing scripts.
488          *  2. PERL5SHELL could be set to a shell that may not be fit for
489          *     interactive use (which is what most programs look in COMSPEC
490          *     for).
491          */
492         const char* defaultshell = (IsWinNT()
493                                     ? "cmd.exe /x/d/c" : "command.com /c");
494         const char *usershell = PerlEnv_getenv("PERL5SHELL");
495         w32_perlshell_items = tokenize(usershell ? usershell : defaultshell,
496                                        &w32_perlshell_tokens,
497                                        &w32_perlshell_vec);
498     }
499 }
500
501 int
502 Perl_do_aspawn(pTHX_ SV *really, SV **mark, SV **sp)
503 {
504   PERL_ARGS_ASSERT_DO_ASPAWN;
505
506   Perl_croak(aTHX_ PL_no_func, "aspawn");
507   return -1;
508 }
509
510 /* returns pointer to the next unquoted space or the end of the string */
511 static char*
512 find_next_space(const char *s)
513 {
514     bool in_quotes = FALSE;
515     while (*s) {
516         /* ignore doubled backslashes, or backslash+quote */
517         if (*s == '\\' && (s[1] == '\\' || s[1] == '"')) {
518             s += 2;
519         }
520         /* keep track of when we're within quotes */
521         else if (*s == '"') {
522             s++;
523             in_quotes = !in_quotes;
524         }
525         /* break it up only at spaces that aren't in quotes */
526         else if (!in_quotes && isSPACE(*s))
527             return (char*)s;
528         else
529             s++;
530     }
531     return (char*)s;
532 }
533
534 #if 1
535 static int
536 do_spawn2(pTHX_ char *cmd, int exectype)
537 {
538     char **a;
539     char *s;
540     char **argv;
541     int status = -1;
542     BOOL needToTry = TRUE;
543     char *cmd2;
544
545     /* Save an extra exec if possible. See if there are shell
546      * metacharacters in it */
547     if (!has_shell_metachars(cmd)) {
548         Newx(argv, strlen(cmd) / 2 + 2, char*);
549         Newx(cmd2, strlen(cmd) + 1, char);
550         strcpy(cmd2, cmd);
551         a = argv;
552         for (s = cmd2; *s;) {
553             while (*s && isSPACE(*s))
554                 s++;
555             if (*s)
556                 *(a++) = s;
557             s = find_next_space(s);
558             if (*s)
559                 *s++ = '\0';
560         }
561         *a = NULL;
562         if (argv[0]) {
563             switch (exectype) {
564             case EXECF_SPAWN:
565                 status = win32_spawnvp(P_WAIT, argv[0],
566                                        (const char* const*)argv);
567                 break;
568             case EXECF_SPAWN_NOWAIT:
569                 status = win32_spawnvp(P_NOWAIT, argv[0],
570                                        (const char* const*)argv);
571                 break;
572             case EXECF_EXEC:
573                 status = win32_execvp(argv[0], (const char* const*)argv);
574                 break;
575             }
576             if (status != -1 || errno == 0)
577                 needToTry = FALSE;
578         }
579         Safefree(argv);
580         Safefree(cmd2);
581     }
582     if (needToTry) {
583         char **argv;
584         int i = -1;
585         get_shell();
586         Newx(argv, w32_perlshell_items + 2, char*);
587         while (++i < w32_perlshell_items)
588             argv[i] = w32_perlshell_vec[i];
589         argv[i++] = cmd;
590         argv[i] = NULL;
591         switch (exectype) {
592         case EXECF_SPAWN:
593             status = win32_spawnvp(P_WAIT, argv[0],
594                                    (const char* const*)argv);
595             break;
596         case EXECF_SPAWN_NOWAIT:
597             status = win32_spawnvp(P_NOWAIT, argv[0],
598                                    (const char* const*)argv);
599             break;
600         case EXECF_EXEC:
601             status = win32_execvp(argv[0], (const char* const*)argv);
602             break;
603         }
604         cmd = argv[0];
605         Safefree(argv);
606     }
607     if (exectype == EXECF_SPAWN_NOWAIT) {
608         if (IsWin95())
609             PL_statusvalue = -1;        /* >16bits hint for pp_system() */
610     }
611     else {
612         if (status < 0) {
613             if (ckWARN(WARN_EXEC))
614                 Perl_warner(aTHX_ packWARN(WARN_EXEC), "Can't %s \"%s\": %s",
615                      (exectype == EXECF_EXEC ? "exec" : "spawn"),
616                      cmd, strerror(errno));
617             status = 255 * 256;
618         }
619         else
620             status *= 256;
621         PL_statusvalue = status;
622     }
623     return (status);
624 }
625
626 int
627 Perl_do_spawn(pTHX_ char *cmd)
628 {
629     PERL_ARGS_ASSERT_DO_SPAWN;
630
631     return do_spawn2(aTHX_ cmd, EXECF_SPAWN);
632 }
633
634 int
635 Perl_do_spawn_nowait(pTHX_ char *cmd)
636 {
637     PERL_ARGS_ASSERT_DO_SPAWN_NOWAIT;
638
639     return do_spawn2(aTHX_ cmd, EXECF_SPAWN_NOWAIT);
640 }
641
642 bool
643 Perl_do_exec(pTHX_ const char *cmd)
644 {
645     PERL_ARGS_ASSERT_DO_EXEC;
646
647     do_spawn2(aTHX_ cmd, EXECF_EXEC);
648     return FALSE;
649 }
650
651 /* The idea here is to read all the directory names into a string table
652  * (separated by nulls) and when one of the other dir functions is called
653  * return the pointer to the current file name.
654  */
655 DllExport DIR *
656 win32_opendir(const char *filename)
657 {
658     dTHX;
659     DIR                 *dirp;
660     long                len;
661     long                idx;
662     char                scanname[MAX_PATH+3];
663     Stat_t              sbuf;
664     WIN32_FIND_DATAA    aFindData;
665     WIN32_FIND_DATAW    wFindData;
666     HANDLE              fh;
667     char                buffer[MAX_PATH*2];
668     WCHAR               wbuffer[MAX_PATH+1];
669     char*               ptr;
670
671     len = strlen(filename);
672     if (len > MAX_PATH)
673         return NULL;
674
675     /* check to see if filename is a directory */
676     if (win32_stat(filename, &sbuf) < 0 || !S_ISDIR(sbuf.st_mode))
677         return NULL;
678
679     /* Get us a DIR structure */
680     Newxz(dirp, 1, DIR);
681
682     /* Create the search pattern */
683     strcpy(scanname, filename);
684
685     /* bare drive name means look in cwd for drive */
686     if (len == 2 && isALPHA(scanname[0]) && scanname[1] == ':') {
687         scanname[len++] = '.';
688         scanname[len++] = '/';
689     }
690     else if (scanname[len-1] != '/' && scanname[len-1] != '\\') {
691         scanname[len++] = '/';
692     }
693     scanname[len++] = '*';
694     scanname[len] = '\0';
695
696     /* do the FindFirstFile call */
697     fh = FindFirstFile(PerlDir_mapA(scanname), &aFindData);
698     dirp->handle = fh;
699     if (fh == INVALID_HANDLE_VALUE) {
700         DWORD err = GetLastError();
701         /* FindFirstFile() fails on empty drives! */
702         switch (err) {
703         case ERROR_FILE_NOT_FOUND:
704             return dirp;
705         case ERROR_NO_MORE_FILES:
706         case ERROR_PATH_NOT_FOUND:
707             errno = ENOENT;
708             break;
709         case ERROR_NOT_ENOUGH_MEMORY:
710             errno = ENOMEM;
711             break;
712         default:
713             errno = EINVAL;
714             break;
715         }
716         Safefree(dirp);
717         return NULL;
718     }
719
720     /* now allocate the first part of the string table for
721      * the filenames that we find.
722      */
723     ptr = aFindData.cFileName;
724     idx = strlen(ptr)+1;
725     if (idx < 256)
726         dirp->size = 128;
727     else
728         dirp->size = idx;
729     Newx(dirp->start, dirp->size, char);
730     strcpy(dirp->start, ptr);
731     dirp->nfiles++;
732     dirp->end = dirp->curr = dirp->start;
733     dirp->end += idx;
734     return dirp;
735 }
736
737
738 /* Readdir just returns the current string pointer and bumps the
739  * string pointer to the nDllExport entry.
740  */
741 DllExport struct direct *
742 win32_readdir(DIR *dirp)
743 {
744     long         len;
745
746     if (dirp->curr) {
747         /* first set up the structure to return */
748         len = strlen(dirp->curr);
749         strcpy(dirp->dirstr.d_name, dirp->curr);
750         dirp->dirstr.d_namlen = len;
751
752         /* Fake an inode */
753         dirp->dirstr.d_ino = dirp->curr - dirp->start;
754
755         /* Now set up for the next call to readdir */
756         dirp->curr += len + 1;
757         if (dirp->curr >= dirp->end) {
758             dTHX;
759             char*               ptr;
760             BOOL                res;
761             WIN32_FIND_DATAW    wFindData;
762             WIN32_FIND_DATAA    aFindData;
763             char                buffer[MAX_PATH*2];
764
765             /* finding the next file that matches the wildcard
766              * (which should be all of them in this directory!).
767              */
768             res = FindNextFile(dirp->handle, &aFindData);
769             if (res)
770                 ptr = aFindData.cFileName;
771             if (res) {
772                 long endpos = dirp->end - dirp->start;
773                 long newsize = endpos + strlen(ptr) + 1;
774                 /* bump the string table size by enough for the
775                  * new name and its null terminator */
776                 while (newsize > dirp->size) {
777                     long curpos = dirp->curr - dirp->start;
778                     dirp->size *= 2;
779                     Renew(dirp->start, dirp->size, char);
780                     dirp->curr = dirp->start + curpos;
781                 }
782                 strcpy(dirp->start + endpos, ptr);
783                 dirp->end = dirp->start + newsize;
784                 dirp->nfiles++;
785             }
786             else
787                 dirp->curr = NULL;
788         }
789         return &(dirp->dirstr);
790     }
791     else
792         return NULL;
793 }
794
795 /* Telldir returns the current string pointer position */
796 DllExport long
797 win32_telldir(DIR *dirp)
798 {
799     return (dirp->curr - dirp->start);
800 }
801
802
803 /* Seekdir moves the string pointer to a previously saved position
804  * (returned by telldir).
805  */
806 DllExport void
807 win32_seekdir(DIR *dirp, long loc)
808 {
809     dirp->curr = dirp->start + loc;
810 }
811
812 /* Rewinddir resets the string pointer to the start */
813 DllExport void
814 win32_rewinddir(DIR *dirp)
815 {
816     dirp->curr = dirp->start;
817 }
818
819 /* free the memory allocated by opendir */
820 DllExport int
821 win32_closedir(DIR *dirp)
822 {
823     dTHX;
824     if (dirp->handle != INVALID_HANDLE_VALUE)
825         FindClose(dirp->handle);
826     Safefree(dirp->start);
827     Safefree(dirp);
828     return 1;
829 }
830
831 #else
832 /////!!!!!!!!!!! return here and do right stuff!!!!
833
834 DllExport DIR *
835 win32_opendir(const char *filename)
836 {
837   return opendir(filename);
838 }
839
840 DllExport struct direct *
841 win32_readdir(DIR *dirp)
842 {
843   return readdir(dirp);
844 }
845
846 DllExport long
847 win32_telldir(DIR *dirp)
848 {
849   dTHX;
850   Perl_croak(aTHX_ PL_no_func, "telldir");
851   return -1;
852 }
853
854 DllExport void
855 win32_seekdir(DIR *dirp, long loc)
856 {
857   dTHX;
858   Perl_croak(aTHX_ PL_no_func, "seekdir");
859 }
860
861 DllExport void
862 win32_rewinddir(DIR *dirp)
863 {
864   dTHX;
865   Perl_croak(aTHX_ PL_no_func, "rewinddir");
866 }
867
868 DllExport int
869 win32_closedir(DIR *dirp)
870 {
871   closedir(dirp);
872   return 0;
873 }
874 #endif   // 1
875
876 DllExport int
877 win32_kill(int pid, int sig)
878 {
879   dTHX;
880   Perl_croak(aTHX_ PL_no_func, "kill");
881   return -1;
882 }
883
884 DllExport int
885 win32_stat(const char *path, struct stat *sbuf)
886 {
887   return xcestat(path, sbuf);
888 }
889
890 DllExport char *
891 win32_longpath(char *path)
892 {
893   return path;
894 }
895
896 DllExport char *
897 win32_getenv(const char *name)
898 {
899   return xcegetenv(name);
900 }
901
902 DllExport int
903 win32_putenv(const char *name)
904 {
905   return xceputenv(name);
906 }
907
908 static long
909 filetime_to_clock(PFILETIME ft)
910 {
911     __int64 qw = ft->dwHighDateTime;
912     qw <<= 32;
913     qw |= ft->dwLowDateTime;
914     qw /= 10000;  /* File time ticks at 0.1uS, clock at 1mS */
915     return (long) qw;
916 }
917
918 /* fix utime() so it works on directories in NT */
919 static BOOL
920 filetime_from_time(PFILETIME pFileTime, time_t Time)
921 {
922     struct tm *pTM = localtime(&Time);
923     SYSTEMTIME SystemTime;
924     FILETIME LocalTime;
925
926     if (pTM == NULL)
927         return FALSE;
928
929     SystemTime.wYear   = pTM->tm_year + 1900;
930     SystemTime.wMonth  = pTM->tm_mon + 1;
931     SystemTime.wDay    = pTM->tm_mday;
932     SystemTime.wHour   = pTM->tm_hour;
933     SystemTime.wMinute = pTM->tm_min;
934     SystemTime.wSecond = pTM->tm_sec;
935     SystemTime.wMilliseconds = 0;
936
937     return SystemTimeToFileTime(&SystemTime, &LocalTime) &&
938            LocalFileTimeToFileTime(&LocalTime, pFileTime);
939 }
940
941 DllExport int
942 win32_unlink(const char *filename)
943 {
944   return xceunlink(filename);
945 }
946
947 DllExport int
948 win32_utime(const char *filename, struct utimbuf *times)
949 {
950   return xceutime(filename, (struct _utimbuf *) times);
951 }
952
953 DllExport int
954 win32_gettimeofday(struct timeval *tp, void *not_used)
955 {
956     return xcegettimeofday(tp,not_used);
957 }
958
959 DllExport int
960 win32_uname(struct utsname *name)
961 {
962     struct hostent *hep;
963     STRLEN nodemax = sizeof(name->nodename)-1;
964     OSVERSIONINFOA osver;
965
966     memset(&osver, 0, sizeof(OSVERSIONINFOA));
967     osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOA);
968     if (XCEGetVersionExA(&osver)) {
969         /* sysname */
970         switch (osver.dwPlatformId) {
971         case VER_PLATFORM_WIN32_CE:
972             strcpy(name->sysname, "Windows CE");
973             break;
974         case VER_PLATFORM_WIN32_WINDOWS:
975             strcpy(name->sysname, "Windows");
976             break;
977         case VER_PLATFORM_WIN32_NT:
978             strcpy(name->sysname, "Windows NT");
979             break;
980         case VER_PLATFORM_WIN32s:
981             strcpy(name->sysname, "Win32s");
982             break;
983         default:
984             strcpy(name->sysname, "Win32 Unknown");
985             break;
986         }
987
988         /* release */
989         sprintf(name->release, "%d.%d",
990                 osver.dwMajorVersion, osver.dwMinorVersion);
991
992         /* version */
993         sprintf(name->version, "Build %d",
994                 osver.dwPlatformId == VER_PLATFORM_WIN32_NT
995                 ? osver.dwBuildNumber : (osver.dwBuildNumber & 0xffff));
996         if (osver.szCSDVersion[0]) {
997             char *buf = name->version + strlen(name->version);
998             sprintf(buf, " (%s)", osver.szCSDVersion);
999         }
1000     }
1001     else {
1002         *name->sysname = '\0';
1003         *name->version = '\0';
1004         *name->release = '\0';
1005     }
1006
1007     /* nodename */
1008     hep = win32_gethostbyname("localhost");
1009     if (hep) {
1010         STRLEN len = strlen(hep->h_name);
1011         if (len <= nodemax) {
1012             strcpy(name->nodename, hep->h_name);
1013         }
1014         else {
1015             strncpy(name->nodename, hep->h_name, nodemax);
1016             name->nodename[nodemax] = '\0';
1017         }
1018     }
1019     else {
1020         DWORD sz = nodemax;
1021         if (!XCEGetComputerNameA(name->nodename, &sz))
1022             *name->nodename = '\0';
1023     }
1024
1025     /* machine (architecture) */
1026     {
1027         SYSTEM_INFO info;
1028         char *arch;
1029         GetSystemInfo(&info);
1030
1031         switch (info.wProcessorArchitecture) {
1032         case PROCESSOR_ARCHITECTURE_INTEL:
1033             arch = "x86"; break;
1034         case PROCESSOR_ARCHITECTURE_MIPS:
1035             arch = "mips"; break;
1036         case PROCESSOR_ARCHITECTURE_ALPHA:
1037             arch = "alpha"; break;
1038         case PROCESSOR_ARCHITECTURE_PPC:
1039             arch = "ppc"; break;
1040         case PROCESSOR_ARCHITECTURE_ARM:
1041             arch = "arm"; break;
1042         case PROCESSOR_HITACHI_SH3:
1043             arch = "sh3"; break;
1044         case PROCESSOR_SHx_SH3:
1045             arch = "sh3"; break;
1046
1047         default:
1048             arch = "unknown"; break;
1049         }
1050         strcpy(name->machine, arch);
1051     }
1052     return 0;
1053 }
1054
1055 /* Timing related stuff */
1056
1057 int
1058 do_raise(pTHX_ int sig)
1059 {
1060     if (sig < SIG_SIZE) {
1061         Sighandler_t handler = w32_sighandler[sig];
1062         if (handler == SIG_IGN) {
1063             return 0;
1064         }
1065         else if (handler != SIG_DFL) {
1066             (*handler)(sig);
1067             return 0;
1068         }
1069         else {
1070             /* Choose correct default behaviour */
1071             switch (sig) {
1072 #ifdef SIGCLD
1073                 case SIGCLD:
1074 #endif
1075 #ifdef SIGCHLD
1076                 case SIGCHLD:
1077 #endif
1078                 case 0:
1079                     return 0;
1080                 case SIGTERM:
1081                 default:
1082                     break;
1083             }
1084         }
1085     }
1086     /* Tell caller to exit thread/process as approriate */
1087     return 1;
1088 }
1089
1090 void
1091 sig_terminate(pTHX_ int sig)
1092 {
1093     Perl_warn(aTHX_ "Terminating on signal SIG%s(%d)\n",PL_sig_name[sig], sig);
1094     /* exit() seems to be safe, my_exit() or die() is a problem in ^C
1095        thread
1096      */
1097     exit(sig);
1098 }
1099
1100 DllExport int
1101 win32_async_check(pTHX)
1102 {
1103     MSG msg;
1104     int ours = 1;
1105     /* Passing PeekMessage -1 as HWND (2nd arg) only get PostThreadMessage() messages
1106      * and ignores window messages - should co-exist better with windows apps e.g. Tk
1107      */
1108     while (PeekMessage(&msg, (HWND)-1, 0, 0, PM_REMOVE|PM_NOYIELD)) {
1109         int sig;
1110         switch(msg.message) {
1111
1112 #if 0
1113     /* Perhaps some other messages could map to signals ? ... */
1114         case WM_CLOSE:
1115         case WM_QUIT:
1116             /* Treat WM_QUIT like SIGHUP?  */
1117             sig = SIGHUP;
1118             goto Raise;
1119             break;
1120 #endif
1121
1122         /* We use WM_USER to fake kill() with other signals */
1123         case WM_USER: {
1124             sig = msg.wParam;
1125         Raise:
1126             if (do_raise(aTHX_ sig)) {
1127                    sig_terminate(aTHX_ sig);
1128             }
1129             break;
1130         }
1131
1132         case WM_TIMER: {
1133             /* alarm() is a one-shot but SetTimer() repeats so kill it */
1134             if (w32_timerid) {
1135                 KillTimer(NULL,w32_timerid);
1136                 w32_timerid=0;
1137             }
1138             /* Now fake a call to signal handler */
1139             if (do_raise(aTHX_ 14)) {
1140                 sig_terminate(aTHX_ 14);
1141             }
1142             break;
1143         }
1144
1145         /* Otherwise do normal Win32 thing - in case it is useful */
1146         default:
1147             TranslateMessage(&msg);
1148             DispatchMessage(&msg);
1149             ours = 0;
1150             break;
1151         }
1152     }
1153     w32_poll_count = 0;
1154
1155     /* Above or other stuff may have set a signal flag */
1156     if (PL_sig_pending) {
1157         despatch_signals();
1158     }
1159     return ours;
1160 }
1161
1162 /* This function will not return until the timeout has elapsed, or until
1163  * one of the handles is ready. */
1164 DllExport DWORD
1165 win32_msgwait(pTHX_ DWORD count, LPHANDLE handles, DWORD timeout, LPDWORD resultp)
1166 {
1167     /* We may need several goes at this - so compute when we stop */
1168     DWORD ticks = 0;
1169     if (timeout != INFINITE) {
1170         ticks = GetTickCount();
1171         timeout += ticks;
1172     }
1173     while (1) {
1174         DWORD result = MsgWaitForMultipleObjects(count,handles,FALSE,timeout-ticks, QS_ALLEVENTS);
1175         if (resultp)
1176            *resultp = result;
1177         if (result == WAIT_TIMEOUT) {
1178             /* Ran out of time - explicit return of zero to avoid -ve if we
1179                have scheduling issues
1180              */
1181             return 0;
1182         }
1183         if (timeout != INFINITE) {
1184             ticks = GetTickCount();
1185         }
1186         if (result == WAIT_OBJECT_0 + count) {
1187             /* Message has arrived - check it */
1188             (void)win32_async_check(aTHX);
1189         }
1190         else {
1191            /* Not timeout or message - one of handles is ready */
1192            break;
1193         }
1194     }
1195     /* compute time left to wait */
1196     ticks = timeout - ticks;
1197     /* If we are past the end say zero */
1198     return (ticks > 0) ? ticks : 0;
1199 }
1200
1201 static UINT timerid = 0;
1202
1203 static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
1204 {
1205     dTHX;
1206     KillTimer(NULL,timerid);
1207     timerid=0;
1208     sighandler(14);
1209 }
1210
1211 DllExport unsigned int
1212 win32_sleep(unsigned int t)
1213 {
1214   return xcesleep(t);
1215 }
1216
1217 DllExport unsigned int
1218 win32_alarm(unsigned int sec)
1219 {
1220     /*
1221      * the 'obvious' implentation is SetTimer() with a callback
1222      * which does whatever receiving SIGALRM would do
1223      * we cannot use SIGALRM even via raise() as it is not
1224      * one of the supported codes in <signal.h>
1225      *
1226      * Snag is unless something is looking at the message queue
1227      * nothing happens :-(
1228      */
1229     dTHX;
1230     if (sec)
1231      {
1232       timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
1233       if (!timerid)
1234        Perl_croak_nocontext("Cannot set timer");
1235      }
1236     else
1237      {
1238       if (timerid)
1239        {
1240         KillTimer(NULL,timerid);
1241         timerid=0;
1242        }
1243      }
1244     return 0;
1245 }
1246
1247 #ifdef HAVE_DES_FCRYPT
1248 extern char *   des_fcrypt(const char *txt, const char *salt, char *cbuf);
1249 #endif
1250
1251 DllExport char *
1252 win32_crypt(const char *txt, const char *salt)
1253 {
1254     dTHX;
1255 #ifdef HAVE_DES_FCRYPT
1256     dTHR;
1257     return des_fcrypt(txt, salt, w32_crypt_buffer);
1258 #else
1259     Perl_croak(aTHX_ "The crypt() function is unimplemented due to excessive paranoia.");
1260     return NULL;
1261 #endif
1262 }
1263
1264
1265 /*
1266  *  redirected io subsystem for all XS modules
1267  *
1268  */
1269
1270 DllExport int *
1271 win32_errno(void)
1272 {
1273     return (&errno);
1274 }
1275
1276 DllExport char ***
1277 win32_environ(void)
1278 {
1279   return (&(environ));
1280 }
1281
1282 /* the rest are the remapped stdio routines */
1283 DllExport FILE *
1284 win32_stderr(void)
1285 {
1286     return (stderr);
1287 }
1288
1289 char *g_getlogin() {
1290     return "no-getlogin";
1291 }
1292
1293 DllExport FILE *
1294 win32_stdin(void)
1295 {
1296     return (stdin);
1297 }
1298
1299 DllExport FILE *
1300 win32_stdout()
1301 {
1302     return (stdout);
1303 }
1304
1305 DllExport int
1306 win32_ferror(FILE *fp)
1307 {
1308     return (ferror(fp));
1309 }
1310
1311
1312 DllExport int
1313 win32_feof(FILE *fp)
1314 {
1315     return (feof(fp));
1316 }
1317
1318 /*
1319  * Since the errors returned by the socket error function
1320  * WSAGetLastError() are not known by the library routine strerror
1321  * we have to roll our own.
1322  */
1323
1324 DllExport char *
1325 win32_strerror(int e)
1326 {
1327   return xcestrerror(e);
1328 }
1329
1330 DllExport void
1331 win32_str_os_error(void *sv, DWORD dwErr)
1332 {
1333   dTHX;
1334
1335   sv_setpvn((SV*)sv, "Error", 5);
1336 }
1337
1338
1339 DllExport int
1340 win32_fprintf(FILE *fp, const char *format, ...)
1341 {
1342     va_list marker;
1343     va_start(marker, format);     /* Initialize variable arguments. */
1344
1345     return (vfprintf(fp, format, marker));
1346 }
1347
1348 DllExport int
1349 win32_printf(const char *format, ...)
1350 {
1351     va_list marker;
1352     va_start(marker, format);     /* Initialize variable arguments. */
1353
1354     return (vprintf(format, marker));
1355 }
1356
1357 DllExport int
1358 win32_vfprintf(FILE *fp, const char *format, va_list args)
1359 {
1360     return (vfprintf(fp, format, args));
1361 }
1362
1363 DllExport int
1364 win32_vprintf(const char *format, va_list args)
1365 {
1366     return (vprintf(format, args));
1367 }
1368
1369 DllExport size_t
1370 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
1371 {
1372   return fread(buf, size, count, fp);
1373 }
1374
1375 DllExport size_t
1376 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
1377 {
1378   return fwrite(buf, size, count, fp);
1379 }
1380
1381 DllExport FILE *
1382 win32_fopen(const char *filename, const char *mode)
1383 {
1384   return xcefopen(filename, mode);
1385 }
1386
1387 DllExport FILE *
1388 win32_fdopen(int handle, const char *mode)
1389 {
1390   return palm_fdopen(handle, mode);
1391 }
1392
1393 DllExport FILE *
1394 win32_freopen(const char *path, const char *mode, FILE *stream)
1395 {
1396   return xcefreopen(path, mode, stream);
1397 }
1398
1399 DllExport int
1400 win32_fclose(FILE *pf)
1401 {
1402   return xcefclose(pf);
1403 }
1404
1405 DllExport int
1406 win32_fputs(const char *s,FILE *pf)
1407 {
1408   return fputs(s, pf);
1409 }
1410
1411 DllExport int
1412 win32_fputc(int c,FILE *pf)
1413 {
1414   return fputc(c,pf);
1415 }
1416
1417 DllExport int
1418 win32_ungetc(int c,FILE *pf)
1419 {
1420   return ungetc(c,pf);
1421 }
1422
1423 DllExport int
1424 win32_getc(FILE *pf)
1425 {
1426   return getc(pf);
1427 }
1428
1429 DllExport int
1430 win32_fileno(FILE *pf)
1431 {
1432   return palm_fileno(pf);
1433 }
1434
1435 DllExport void
1436 win32_clearerr(FILE *pf)
1437 {
1438   clearerr(pf);
1439   return;
1440 }
1441
1442 DllExport int
1443 win32_fflush(FILE *pf)
1444 {
1445   return fflush(pf);
1446 }
1447
1448 DllExport long
1449 win32_ftell(FILE *pf)
1450 {
1451   return ftell(pf);
1452 }
1453
1454 DllExport int
1455 win32_fseek(FILE *pf, Off_t offset,int origin)
1456 {
1457   return fseek(pf, offset, origin);
1458 }
1459
1460 /* fpos_t seems to be int64 on hpc pro! Really stupid. */
1461 /* But maybe someday there will be such large disks in a hpc... */
1462 DllExport int
1463 win32_fgetpos(FILE *pf, fpos_t *p)
1464 {
1465   return fgetpos(pf, p);
1466 }
1467
1468 DllExport int
1469 win32_fsetpos(FILE *pf, const fpos_t *p)
1470 {
1471   return fsetpos(pf, p);
1472 }
1473
1474 DllExport void
1475 win32_rewind(FILE *pf)
1476 {
1477   fseek(pf, 0, SEEK_SET);
1478   return;
1479 }
1480
1481 DllExport int
1482 win32_tmpfd(void)
1483 {
1484     dTHX;
1485     char prefix[MAX_PATH+1];
1486     char filename[MAX_PATH+1];
1487     DWORD len = GetTempPath(MAX_PATH, prefix);
1488     if (len && len < MAX_PATH) {
1489         if (GetTempFileName(prefix, "plx", 0, filename)) {
1490             HANDLE fh = CreateFile(filename,
1491                                    DELETE | GENERIC_READ | GENERIC_WRITE,
1492                                    0,
1493                                    NULL,
1494                                    CREATE_ALWAYS,
1495                                    FILE_ATTRIBUTE_NORMAL
1496                                    | FILE_FLAG_DELETE_ON_CLOSE,
1497                                    NULL);
1498             if (fh != INVALID_HANDLE_VALUE) {
1499                 int fd = win32_open_osfhandle((intptr_t)fh, 0);
1500                 if (fd >= 0) {
1501 #if defined(__BORLANDC__)
1502                     setmode(fd,O_BINARY);
1503 #endif
1504                     DEBUG_p(PerlIO_printf(Perl_debug_log,
1505                                           "Created tmpfile=%s\n",filename));
1506                     return fd;
1507                 }
1508             }
1509         }
1510     }
1511     return -1;
1512 }
1513
1514 DllExport FILE*
1515 win32_tmpfile(void)
1516 {
1517     int fd = win32_tmpfd();
1518     if (fd >= 0)
1519         return win32_fdopen(fd, "w+b");
1520     return NULL;
1521 }
1522
1523 DllExport void
1524 win32_abort(void)
1525 {
1526   xceabort();
1527
1528   return;
1529 }
1530
1531 DllExport int
1532 win32_fstat(int fd, struct stat *sbufptr)
1533 {
1534   return xcefstat(fd, sbufptr);
1535 }
1536
1537 DllExport int
1538 win32_link(const char *oldname, const char *newname)
1539 {
1540   dTHX;
1541   Perl_croak(aTHX_ PL_no_func, "link");
1542
1543   return -1;
1544 }
1545
1546 DllExport int
1547 win32_rename(const char *oname, const char *newname)
1548 {
1549   return xcerename(oname, newname);
1550 }
1551
1552 DllExport int
1553 win32_setmode(int fd, int mode)
1554 {
1555     /* currently 'celib' seem to have this function in src, but not
1556      * exported. When it will be, we'll uncomment following line.
1557      */
1558     /* return xcesetmode(fd, mode); */
1559     return 0;
1560 }
1561
1562 DllExport int
1563 win32_chsize(int fd, Off_t size)
1564 {
1565     return chsize(fd, size);
1566 }
1567
1568 DllExport long
1569 win32_lseek(int fd, Off_t offset, int origin)
1570 {
1571   return xcelseek(fd, offset, origin);
1572 }
1573
1574 DllExport long
1575 win32_tell(int fd)
1576 {
1577   return xcelseek(fd, 0, SEEK_CUR);
1578 }
1579
1580 DllExport int
1581 win32_open(const char *path, int flag, ...)
1582 {
1583   int pmode;
1584   va_list ap;
1585
1586   va_start(ap, flag);
1587   pmode = va_arg(ap, int);
1588   va_end(ap);
1589
1590   return xceopen(path, flag, pmode);
1591 }
1592
1593 DllExport int
1594 win32_close(int fd)
1595 {
1596   return xceclose(fd);
1597 }
1598
1599 DllExport int
1600 win32_eof(int fd)
1601 {
1602   dTHX;
1603   Perl_croak(aTHX_ PL_no_func, "eof");
1604   return -1;
1605 }
1606
1607 DllExport int
1608 win32_dup(int fd)
1609 {
1610   return xcedup(fd); /* from celib/ceio.c; requires some more work on it */
1611 }
1612
1613 DllExport int
1614 win32_dup2(int fd1,int fd2)
1615 {
1616   return xcedup2(fd1,fd2);
1617 }
1618
1619 DllExport int
1620 win32_read(int fd, void *buf, unsigned int cnt)
1621 {
1622   return xceread(fd, buf, cnt);
1623 }
1624
1625 DllExport int
1626 win32_write(int fd, const void *buf, unsigned int cnt)
1627 {
1628   return xcewrite(fd, (void *) buf, cnt);
1629 }
1630
1631 DllExport int
1632 win32_mkdir(const char *dir, int mode)
1633 {
1634   return xcemkdir(dir);
1635 }
1636
1637 DllExport int
1638 win32_rmdir(const char *dir)
1639 {
1640   return xcermdir(dir);
1641 }
1642
1643 DllExport int
1644 win32_chdir(const char *dir)
1645 {
1646   return xcechdir(dir);
1647 }
1648
1649 DllExport  int
1650 win32_access(const char *path, int mode)
1651 {
1652   return xceaccess(path, mode);
1653 }
1654
1655 DllExport  int
1656 win32_chmod(const char *path, int mode)
1657 {
1658   return xcechmod(path, mode);
1659 }
1660
1661 static char *
1662 create_command_line(char *cname, STRLEN clen, const char * const *args)
1663 {
1664     dTHX;
1665     int index, argc;
1666     char *cmd, *ptr;
1667     const char *arg;
1668     STRLEN len = 0;
1669     bool bat_file = FALSE;
1670     bool cmd_shell = FALSE;
1671     bool dumb_shell = FALSE;
1672     bool extra_quotes = FALSE;
1673     bool quote_next = FALSE;
1674
1675     if (!cname)
1676         cname = (char*)args[0];
1677
1678     /* The NT cmd.exe shell has the following peculiarity that needs to be
1679      * worked around.  It strips a leading and trailing dquote when any
1680      * of the following is true:
1681      *    1. the /S switch was used
1682      *    2. there are more than two dquotes
1683      *    3. there is a special character from this set: &<>()@^|
1684      *    4. no whitespace characters within the two dquotes
1685      *    5. string between two dquotes isn't an executable file
1686      * To work around this, we always add a leading and trailing dquote
1687      * to the string, if the first argument is either "cmd.exe" or "cmd",
1688      * and there were at least two or more arguments passed to cmd.exe
1689      * (not including switches).
1690      * XXX the above rules (from "cmd /?") don't seem to be applied
1691      * always, making for the convolutions below :-(
1692      */
1693     if (cname) {
1694         if (!clen)
1695             clen = strlen(cname);
1696
1697         if (clen > 4
1698             && (stricmp(&cname[clen-4], ".bat") == 0
1699                 || (IsWinNT() && stricmp(&cname[clen-4], ".cmd") == 0)))
1700         {
1701             bat_file = TRUE;
1702             len += 3;
1703         }
1704         else {
1705             char *exe = strrchr(cname, '/');
1706             char *exe2 = strrchr(cname, '\\');
1707             if (exe2 > exe)
1708                 exe = exe2;
1709             if (exe)
1710                 ++exe;
1711             else
1712                 exe = cname;
1713             if (stricmp(exe, "cmd.exe") == 0 || stricmp(exe, "cmd") == 0) {
1714                 cmd_shell = TRUE;
1715                 len += 3;
1716             }
1717             else if (stricmp(exe, "command.com") == 0
1718                      || stricmp(exe, "command") == 0)
1719             {
1720                 dumb_shell = TRUE;
1721             }
1722         }
1723     }
1724
1725     DEBUG_p(PerlIO_printf(Perl_debug_log, "Args "));
1726     for (index = 0; (arg = (char*)args[index]) != NULL; ++index) {
1727         STRLEN curlen = strlen(arg);
1728         if (!(arg[0] == '"' && arg[curlen-1] == '"'))
1729             len += 2;   /* assume quoting needed (worst case) */
1730         len += curlen + 1;
1731         DEBUG_p(PerlIO_printf(Perl_debug_log, "[%s]",arg));
1732     }
1733     DEBUG_p(PerlIO_printf(Perl_debug_log, "\n"));
1734
1735     argc = index;
1736     Newx(cmd, len, char);
1737     ptr = cmd;
1738
1739     if (bat_file) {
1740         *ptr++ = '"';
1741         extra_quotes = TRUE;
1742     }
1743
1744     for (index = 0; (arg = (char*)args[index]) != NULL; ++index) {
1745         bool do_quote = 0;
1746         STRLEN curlen = strlen(arg);
1747
1748         /* we want to protect empty arguments and ones with spaces with
1749          * dquotes, but only if they aren't already there */
1750         if (!dumb_shell) {
1751             if (!curlen) {
1752                 do_quote = 1;
1753             }
1754             else if (quote_next) {
1755                 /* see if it really is multiple arguments pretending to
1756                  * be one and force a set of quotes around it */
1757                 if (*find_next_space(arg))
1758                     do_quote = 1;
1759             }
1760             else if (!(arg[0] == '"' && curlen > 1 && arg[curlen-1] == '"')) {
1761                 STRLEN i = 0;
1762                 while (i < curlen) {
1763                     if (isSPACE(arg[i])) {
1764                         do_quote = 1;
1765                     }
1766                     else if (arg[i] == '"') {
1767                         do_quote = 0;
1768                         break;
1769                     }
1770                     i++;
1771                 }
1772             }
1773         }
1774
1775         if (do_quote)
1776             *ptr++ = '"';
1777
1778         strcpy(ptr, arg);
1779         ptr += curlen;
1780
1781         if (do_quote)
1782             *ptr++ = '"';
1783
1784         if (args[index+1])
1785             *ptr++ = ' ';
1786
1787         if (!extra_quotes
1788             && cmd_shell
1789             && curlen >= 2
1790             && *arg  == '/'     /* see if arg is "/c", "/x/c", "/x/d/c" etc. */
1791             && stricmp(arg+curlen-2, "/c") == 0)
1792         {
1793             /* is there a next argument? */
1794             if (args[index+1]) {
1795                 /* are there two or more next arguments? */
1796                 if (args[index+2]) {
1797                     *ptr++ = '"';
1798                     extra_quotes = TRUE;
1799                 }
1800                 else {
1801                     /* single argument, force quoting if it has spaces */
1802                     quote_next = TRUE;
1803                 }
1804             }
1805         }
1806     }
1807
1808     if (extra_quotes)
1809         *ptr++ = '"';
1810
1811     *ptr = '\0';
1812
1813     return cmd;
1814 }
1815
1816 static char *
1817 qualified_path(const char *cmd)
1818 {
1819     dTHX;
1820     char *pathstr;
1821     char *fullcmd, *curfullcmd;
1822     STRLEN cmdlen = 0;
1823     int has_slash = 0;
1824
1825     if (!cmd)
1826         return NULL;
1827     fullcmd = (char*)cmd;
1828     while (*fullcmd) {
1829         if (*fullcmd == '/' || *fullcmd == '\\')
1830             has_slash++;
1831         fullcmd++;
1832         cmdlen++;
1833     }
1834
1835     /* look in PATH */
1836     pathstr = PerlEnv_getenv("PATH");
1837     Newx(fullcmd, MAX_PATH+1, char);
1838     curfullcmd = fullcmd;
1839
1840     while (1) {
1841         DWORD res;
1842
1843         /* start by appending the name to the current prefix */
1844         strcpy(curfullcmd, cmd);
1845         curfullcmd += cmdlen;
1846
1847         /* if it doesn't end with '.', or has no extension, try adding
1848          * a trailing .exe first */
1849         if (cmd[cmdlen-1] != '.'
1850             && (cmdlen < 4 || cmd[cmdlen-4] != '.'))
1851         {
1852             strcpy(curfullcmd, ".exe");
1853             res = GetFileAttributes(fullcmd);
1854             if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
1855                 return fullcmd;
1856             *curfullcmd = '\0';
1857         }
1858
1859         /* that failed, try the bare name */
1860         res = GetFileAttributes(fullcmd);
1861         if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
1862             return fullcmd;
1863
1864         /* quit if no other path exists, or if cmd already has path */
1865         if (!pathstr || !*pathstr || has_slash)
1866             break;
1867
1868         /* skip leading semis */
1869         while (*pathstr == ';')
1870             pathstr++;
1871
1872         /* build a new prefix from scratch */
1873         curfullcmd = fullcmd;
1874         while (*pathstr && *pathstr != ';') {
1875             if (*pathstr == '"') {      /* foo;"baz;etc";bar */
1876                 pathstr++;              /* skip initial '"' */
1877                 while (*pathstr && *pathstr != '"') {
1878                     if ((STRLEN)(curfullcmd-fullcmd) < MAX_PATH-cmdlen-5)
1879                         *curfullcmd++ = *pathstr;
1880                     pathstr++;
1881                 }
1882                 if (*pathstr)
1883                     pathstr++;          /* skip trailing '"' */
1884             }
1885             else {
1886                 if ((STRLEN)(curfullcmd-fullcmd) < MAX_PATH-cmdlen-5)
1887                     *curfullcmd++ = *pathstr;
1888                 pathstr++;
1889             }
1890         }
1891         if (*pathstr)
1892             pathstr++;                  /* skip trailing semi */
1893         if (curfullcmd > fullcmd        /* append a dir separator */
1894             && curfullcmd[-1] != '/' && curfullcmd[-1] != '\\')
1895         {
1896             *curfullcmd++ = '\\';
1897         }
1898     }
1899
1900     Safefree(fullcmd);
1901     return NULL;
1902 }
1903
1904 /* The following are just place holders.
1905  * Some hosts may provide and environment that the OS is
1906  * not tracking, therefore, these host must provide that
1907  * environment and the current directory to CreateProcess
1908  */
1909
1910 DllExport void*
1911 win32_get_childenv(void)
1912 {
1913     return NULL;
1914 }
1915
1916 DllExport void
1917 win32_free_childenv(void* d)
1918 {
1919 }
1920
1921 DllExport void
1922 win32_clearenv(void)
1923 {
1924     char *envv = GetEnvironmentStrings();
1925     char *cur = envv;
1926     STRLEN len;
1927     while (*cur) {
1928         char *end = strchr(cur,'=');
1929         if (end && end != cur) {
1930             *end = '\0';
1931             xcesetenv(cur, "", 0);
1932             *end = '=';
1933             cur = end + strlen(end+1)+2;
1934         }
1935         else if ((len = strlen(cur)))
1936             cur += len+1;
1937     }
1938     FreeEnvironmentStrings(envv);
1939 }
1940
1941 DllExport char*
1942 win32_get_childdir(void)
1943 {
1944     dTHX;
1945     char* ptr;
1946     char szfilename[MAX_PATH+1];
1947     GetCurrentDirectoryA(MAX_PATH+1, szfilename);
1948
1949     Newx(ptr, strlen(szfilename)+1, char);
1950     strcpy(ptr, szfilename);
1951     return ptr;
1952 }
1953
1954 DllExport void
1955 win32_free_childdir(char* d)
1956 {
1957     dTHX;
1958     Safefree(d);
1959 }
1960
1961 /* XXX this needs to be made more compatible with the spawnvp()
1962  * provided by the various RTLs.  In particular, searching for
1963  * *.{com,bat,cmd} files (as done by the RTLs) is unimplemented.
1964  * This doesn't significantly affect perl itself, because we
1965  * always invoke things using PERL5SHELL if a direct attempt to
1966  * spawn the executable fails.
1967  *
1968  * XXX splitting and rejoining the commandline between do_aspawn()
1969  * and win32_spawnvp() could also be avoided.
1970  */
1971
1972 DllExport int
1973 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
1974 {
1975 #ifdef USE_RTL_SPAWNVP
1976     return spawnvp(mode, cmdname, (char * const *)argv);
1977 #else
1978     dTHX;
1979     int ret;
1980     void* env;
1981     char* dir;
1982     child_IO_table tbl;
1983     STARTUPINFO StartupInfo;
1984     PROCESS_INFORMATION ProcessInformation;
1985     DWORD create = 0;
1986     char *cmd;
1987     char *fullcmd = NULL;
1988     char *cname = (char *)cmdname;
1989     STRLEN clen = 0;
1990
1991     if (cname) {
1992         clen = strlen(cname);
1993         /* if command name contains dquotes, must remove them */
1994         if (strchr(cname, '"')) {
1995             cmd = cname;
1996             Newx(cname,clen+1,char);
1997             clen = 0;
1998             while (*cmd) {
1999                 if (*cmd != '"') {
2000                     cname[clen] = *cmd;
2001                     ++clen;
2002                 }
2003                 ++cmd;
2004             }
2005             cname[clen] = '\0';
2006         }
2007     }
2008
2009     cmd = create_command_line(cname, clen, argv);
2010
2011     env = PerlEnv_get_childenv();
2012     dir = PerlEnv_get_childdir();
2013
2014     switch(mode) {
2015     case P_NOWAIT:      /* asynch + remember result */
2016         if (w32_num_children >= MAXIMUM_WAIT_OBJECTS) {
2017             errno = EAGAIN;
2018             ret = -1;
2019             goto RETVAL;
2020         }
2021         /* Create a new process group so we can use GenerateConsoleCtrlEvent()
2022          * in win32_kill()
2023          */
2024         /* not supported on CE create |= CREATE_NEW_PROCESS_GROUP; */
2025         /* FALL THROUGH */
2026
2027     case P_WAIT:        /* synchronous execution */
2028         break;
2029     default:            /* invalid mode */
2030         errno = EINVAL;
2031         ret = -1;
2032         goto RETVAL;
2033     }
2034     memset(&StartupInfo,0,sizeof(StartupInfo));
2035     StartupInfo.cb = sizeof(StartupInfo);
2036     memset(&tbl,0,sizeof(tbl));
2037     PerlEnv_get_child_IO(&tbl);
2038     StartupInfo.dwFlags         = tbl.dwFlags;
2039     StartupInfo.dwX             = tbl.dwX;
2040     StartupInfo.dwY             = tbl.dwY;
2041     StartupInfo.dwXSize         = tbl.dwXSize;
2042     StartupInfo.dwYSize         = tbl.dwYSize;
2043     StartupInfo.dwXCountChars   = tbl.dwXCountChars;
2044     StartupInfo.dwYCountChars   = tbl.dwYCountChars;
2045     StartupInfo.dwFillAttribute = tbl.dwFillAttribute;
2046     StartupInfo.wShowWindow     = tbl.wShowWindow;
2047     StartupInfo.hStdInput       = tbl.childStdIn;
2048     StartupInfo.hStdOutput      = tbl.childStdOut;
2049     StartupInfo.hStdError       = tbl.childStdErr;
2050     if (StartupInfo.hStdInput == INVALID_HANDLE_VALUE &&
2051         StartupInfo.hStdOutput == INVALID_HANDLE_VALUE &&
2052         StartupInfo.hStdError == INVALID_HANDLE_VALUE)
2053     {
2054         create |= CREATE_NEW_CONSOLE;
2055     }
2056     else {
2057         StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
2058     }
2059     if (w32_use_showwindow) {
2060         StartupInfo.dwFlags |= STARTF_USESHOWWINDOW;
2061         StartupInfo.wShowWindow = w32_showwindow;
2062     }
2063
2064     DEBUG_p(PerlIO_printf(Perl_debug_log, "Spawning [%s] with [%s]\n",
2065                           cname,cmd));
2066 RETRY:
2067     if (!CreateProcess(cname,           /* search PATH to find executable */
2068                        cmd,             /* executable, and its arguments */
2069                        NULL,            /* process attributes */
2070                        NULL,            /* thread attributes */
2071                        TRUE,            /* inherit handles */
2072                        create,          /* creation flags */
2073                        (LPVOID)env,     /* inherit environment */
2074                        dir,             /* inherit cwd */
2075                        &StartupInfo,
2076                        &ProcessInformation))
2077     {
2078         /* initial NULL argument to CreateProcess() does a PATH
2079          * search, but it always first looks in the directory
2080          * where the current process was started, which behavior
2081          * is undesirable for backward compatibility.  So we
2082          * jump through our own hoops by picking out the path
2083          * we really want it to use. */
2084         if (!fullcmd) {
2085             fullcmd = qualified_path(cname);
2086             if (fullcmd) {
2087                 if (cname != cmdname)
2088                     Safefree(cname);
2089                 cname = fullcmd;
2090                 DEBUG_p(PerlIO_printf(Perl_debug_log,
2091                                       "Retrying [%s] with same args\n",
2092                                       cname));
2093                 goto RETRY;
2094             }
2095         }
2096         errno = ENOENT;
2097         ret = -1;
2098         goto RETVAL;
2099     }
2100
2101     if (mode == P_NOWAIT) {
2102         /* asynchronous spawn -- store handle, return PID */
2103         ret = (int)ProcessInformation.dwProcessId;
2104         if (IsWin95() && ret < 0)
2105             ret = -ret;
2106
2107         w32_child_handles[w32_num_children] = ProcessInformation.hProcess;
2108         w32_child_pids[w32_num_children] = (DWORD)ret;
2109         ++w32_num_children;
2110     }
2111     else  {
2112         DWORD status;
2113         win32_msgwait(aTHX_ 1, &ProcessInformation.hProcess, INFINITE, NULL);
2114         /* FIXME: if msgwait returned due to message perhaps forward the
2115            "signal" to the process
2116          */
2117         GetExitCodeProcess(ProcessInformation.hProcess, &status);
2118         ret = (int)status;
2119         CloseHandle(ProcessInformation.hProcess);
2120     }
2121
2122     CloseHandle(ProcessInformation.hThread);
2123
2124 RETVAL:
2125     PerlEnv_free_childenv(env);
2126     PerlEnv_free_childdir(dir);
2127     Safefree(cmd);
2128     if (cname != cmdname)
2129         Safefree(cname);
2130     return ret;
2131 #endif
2132 }
2133
2134 DllExport int
2135 win32_execv(const char *cmdname, const char *const *argv)
2136 {
2137   dTHX;
2138   Perl_croak(aTHX_ PL_no_func, "execv");
2139   return -1;
2140 }
2141
2142 DllExport int
2143 win32_execvp(const char *cmdname, const char *const *argv)
2144 {
2145   dTHX;
2146   Perl_croak(aTHX_ PL_no_func, "execvp");
2147   return -1;
2148 }
2149
2150 DllExport void
2151 win32_perror(const char *str)
2152 {
2153   xceperror(str);
2154 }
2155
2156 DllExport void
2157 win32_setbuf(FILE *pf, char *buf)
2158 {
2159   dTHX;
2160   Perl_croak(aTHX_ PL_no_func, "setbuf");
2161 }
2162
2163 DllExport int
2164 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
2165 {
2166   return setvbuf(pf, buf, type, size);
2167 }
2168
2169 DllExport int
2170 win32_flushall(void)
2171 {
2172   return flushall();
2173 }
2174
2175 DllExport int
2176 win32_fcloseall(void)
2177 {
2178   return fcloseall();
2179 }
2180
2181 DllExport char*
2182 win32_fgets(char *s, int n, FILE *pf)
2183 {
2184   return fgets(s, n, pf);
2185 }
2186
2187 DllExport char*
2188 win32_gets(char *s)
2189 {
2190   return gets(s);
2191 }
2192
2193 DllExport int
2194 win32_fgetc(FILE *pf)
2195 {
2196   return fgetc(pf);
2197 }
2198
2199 DllExport int
2200 win32_putc(int c, FILE *pf)
2201 {
2202   return putc(c,pf);
2203 }
2204
2205 DllExport int
2206 win32_puts(const char *s)
2207 {
2208   return puts(s);
2209 }
2210
2211 DllExport int
2212 win32_getchar(void)
2213 {
2214   return getchar();
2215 }
2216
2217 DllExport int
2218 win32_putchar(int c)
2219 {
2220   return putchar(c);
2221 }
2222
2223 #ifdef MYMALLOC
2224
2225 #ifndef USE_PERL_SBRK
2226
2227 static char *committed = NULL;
2228 static char *base      = NULL;
2229 static char *reserved  = NULL;
2230 static char *brk       = NULL;
2231 static DWORD pagesize  = 0;
2232 static DWORD allocsize = 0;
2233
2234 void *
2235 sbrk(int need)
2236 {
2237  void *result;
2238  if (!pagesize)
2239   {SYSTEM_INFO info;
2240    GetSystemInfo(&info);
2241    /* Pretend page size is larger so we don't perpetually
2242     * call the OS to commit just one page ...
2243     */
2244    pagesize = info.dwPageSize << 3;
2245    allocsize = info.dwAllocationGranularity;
2246   }
2247  /* This scheme fails eventually if request for contiguous
2248   * block is denied so reserve big blocks - this is only
2249   * address space not memory ...
2250   */
2251  if (brk+need >= reserved)
2252   {
2253    DWORD size = 64*1024*1024;
2254    char *addr;
2255    if (committed && reserved && committed < reserved)
2256     {
2257      /* Commit last of previous chunk cannot span allocations */
2258      addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
2259      if (addr)
2260       committed = reserved;
2261     }
2262    /* Reserve some (more) space
2263     * Note this is a little sneaky, 1st call passes NULL as reserved
2264     * so lets system choose where we start, subsequent calls pass
2265     * the old end address so ask for a contiguous block
2266     */
2267    addr  = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
2268    if (addr)
2269     {
2270      reserved = addr+size;
2271      if (!base)
2272       base = addr;
2273      if (!committed)
2274       committed = base;
2275      if (!brk)
2276       brk = committed;
2277     }
2278    else
2279     {
2280      return (void *) -1;
2281     }
2282   }
2283  result = brk;
2284  brk += need;
2285  if (brk > committed)
2286   {
2287    DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
2288    char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
2289    if (addr)
2290     {
2291      committed += size;
2292     }
2293    else
2294     return (void *) -1;
2295   }
2296  return result;
2297 }
2298
2299 #endif
2300 #endif
2301
2302 DllExport void*
2303 win32_malloc(size_t size)
2304 {
2305     return malloc(size);
2306 }
2307
2308 DllExport void*
2309 win32_calloc(size_t numitems, size_t size)
2310 {
2311     return calloc(numitems,size);
2312 }
2313
2314 DllExport void*
2315 win32_realloc(void *block, size_t size)
2316 {
2317     return realloc(block,size);
2318 }
2319
2320 DllExport void
2321 win32_free(void *block)
2322 {
2323     free(block);
2324 }
2325
2326 int
2327 win32_open_osfhandle(intptr_t osfhandle, int flags)
2328 {
2329     int fh;
2330     char fileflags=0;           /* _osfile flags */
2331
2332     Perl_croak_nocontext("win32_open_osfhandle() TBD on this platform");
2333     return 0;
2334 }
2335
2336 int
2337 win32_get_osfhandle(int fd)
2338 {
2339     int fh;
2340     char fileflags=0;           /* _osfile flags */
2341
2342     Perl_croak_nocontext("win32_get_osfhandle() TBD on this platform");
2343     return 0;
2344 }
2345
2346 FILE *
2347 win32_fdupopen(FILE *pf)
2348 {
2349     FILE* pfdup;
2350     fpos_t pos;
2351     char mode[3];
2352     int fileno = win32_dup(win32_fileno(pf));
2353     int fmode = palm_fgetmode(pfdup);
2354
2355     fprintf(stderr,"DEBUG for win32_fdupopen()\n");
2356
2357     /* open the file in the same mode */
2358     if(fmode & O_RDONLY) {
2359         mode[0] = 'r';
2360         mode[1] = 0;
2361     }
2362     else if(fmode & O_APPEND) {
2363         mode[0] = 'a';
2364         mode[1] = 0;
2365     }
2366     else if(fmode & O_RDWR) {
2367         mode[0] = 'r';
2368         mode[1] = '+';
2369         mode[2] = 0;
2370     }
2371
2372     /* it appears that the binmode is attached to the
2373      * file descriptor so binmode files will be handled
2374      * correctly
2375      */
2376     pfdup = win32_fdopen(fileno, mode);
2377
2378     /* move the file pointer to the same position */
2379     if (!fgetpos(pf, &pos)) {
2380         fsetpos(pfdup, &pos);
2381     }
2382     return pfdup;
2383 }
2384
2385 DllExport void*
2386 win32_dynaload(const char* filename)
2387 {
2388     dTHX;
2389     HMODULE hModule;
2390
2391     hModule = XCELoadLibraryA(filename);
2392
2393     return hModule;
2394 }
2395
2396 /* this is needed by Cwd.pm... */
2397
2398 static
2399 XS(w32_GetCwd)
2400 {
2401   dXSARGS;
2402   char buf[MAX_PATH];
2403   SV *sv = sv_newmortal();
2404
2405   xcegetcwd(buf, sizeof(buf));
2406
2407   sv_setpv(sv, xcestrdup(buf));
2408   EXTEND(SP,1);
2409   SvPOK_on(sv);
2410   ST(0) = sv;
2411 #ifndef INCOMPLETE_TAINTS
2412   SvTAINTED_on(ST(0));
2413 #endif
2414   XSRETURN(1);
2415 }
2416
2417 static
2418 XS(w32_SetCwd)
2419 {
2420   dXSARGS;
2421
2422   if (items != 1)
2423     Perl_croak(aTHX_ "usage: Win32::SetCwd($cwd)");
2424
2425   if (!xcechdir(SvPV_nolen(ST(0))))
2426     XSRETURN_YES;
2427
2428   XSRETURN_NO;
2429 }
2430
2431 static
2432 XS(w32_GetTickCount)
2433 {
2434     dXSARGS;
2435     DWORD msec = GetTickCount();
2436     EXTEND(SP,1);
2437     if ((IV)msec > 0)
2438         XSRETURN_IV(msec);
2439     XSRETURN_NV(msec);
2440 }
2441
2442 static
2443 XS(w32_GetOSVersion)
2444 {
2445     dXSARGS;
2446     OSVERSIONINFOA osver;
2447
2448     osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOA);
2449     if (!XCEGetVersionExA(&osver)) {
2450       XSRETURN_EMPTY;
2451     }
2452     mXPUSHp(osver.szCSDVersion, strlen(osver.szCSDVersion));
2453     mXPUSHi(osver.dwMajorVersion);
2454     mXPUSHi(osver.dwMinorVersion);
2455     mXPUSHi(osver.dwBuildNumber);
2456     /* WINCE = 3 */
2457     mXPUSHi(osver.dwPlatformId);
2458     PUTBACK;
2459 }
2460
2461 static
2462 XS(w32_IsWinNT)
2463 {
2464     dXSARGS;
2465     EXTEND(SP,1);
2466     XSRETURN_IV(IsWinNT());
2467 }
2468
2469 static
2470 XS(w32_IsWin95)
2471 {
2472     dXSARGS;
2473     EXTEND(SP,1);
2474     XSRETURN_IV(IsWin95());
2475 }
2476
2477 static
2478 XS(w32_IsWinCE)
2479 {
2480     dXSARGS;
2481     EXTEND(SP,1);
2482     XSRETURN_IV(IsWinCE());
2483 }
2484
2485 static
2486 XS(w32_GetOemInfo)
2487 {
2488   dXSARGS;
2489   wchar_t wbuf[126];
2490   char buf[126];
2491
2492   if(SystemParametersInfoW(SPI_GETOEMINFO, sizeof(wbuf), wbuf, FALSE))
2493     WideCharToMultiByte(CP_ACP, 0, wbuf, -1, buf, sizeof(buf), 0, 0);
2494   else
2495     sprintf(buf, "SystemParametersInfo failed: %d", GetLastError());
2496
2497   EXTEND(SP,1);
2498   XSRETURN_PV(buf);
2499 }
2500
2501 static
2502 XS(w32_Sleep)
2503 {
2504     dXSARGS;
2505     if (items != 1)
2506         Perl_croak(aTHX_ "usage: Win32::Sleep($milliseconds)");
2507     Sleep(SvIV(ST(0)));
2508     XSRETURN_YES;
2509 }
2510
2511 static
2512 XS(w32_CopyFile)
2513 {
2514     dXSARGS;
2515     BOOL bResult;
2516     if (items != 3)
2517         Perl_croak(aTHX_ "usage: Win32::CopyFile($from, $to, $overwrite)");
2518
2519     {
2520       char szSourceFile[MAX_PATH+1];
2521       strcpy(szSourceFile, PerlDir_mapA(SvPV_nolen(ST(0))));
2522       bResult = XCECopyFileA(szSourceFile, SvPV_nolen(ST(1)),
2523                              !SvTRUE(ST(2)));
2524     }
2525
2526     if (bResult)
2527         XSRETURN_YES;
2528
2529     XSRETURN_NO;
2530 }
2531
2532 static
2533 XS(w32_MessageBox)
2534 {
2535     dXSARGS;
2536
2537     char *txt;
2538     unsigned int res;
2539     unsigned int flags = MB_OK;
2540
2541     txt = SvPV_nolen(ST(0));
2542
2543     if (items < 1 || items > 2)
2544         Perl_croak(aTHX_ "usage: Win32::MessageBox($txt, [$flags])");
2545
2546     if(items == 2)
2547       flags = SvIV(ST(1));
2548
2549     res = XCEMessageBoxA(NULL, txt, "Perl", flags);
2550
2551     XSRETURN_IV(res);
2552 }
2553
2554 static
2555 XS(w32_GetPowerStatus)
2556 {
2557   dXSARGS;
2558
2559   SYSTEM_POWER_STATUS_EX sps;
2560
2561   if(GetSystemPowerStatusEx(&sps, TRUE) == FALSE)
2562     {
2563       XSRETURN_EMPTY;
2564     }
2565
2566   mXPUSHi(sps.ACLineStatus);
2567   mXPUSHi(sps.BatteryFlag);
2568   mXPUSHi(sps.BatteryLifePercent);
2569   mXPUSHi(sps.BatteryLifeTime);
2570   mXPUSHi(sps.BatteryFullLifeTime);
2571   mXPUSHi(sps.BackupBatteryFlag);
2572   mXPUSHi(sps.BackupBatteryLifePercent);
2573   mXPUSHi(sps.BackupBatteryLifeTime);
2574   mXPUSHi(sps.BackupBatteryFullLifeTime);
2575
2576   PUTBACK;
2577 }
2578
2579 #if UNDER_CE > 200
2580 static
2581 XS(w32_ShellEx)
2582 {
2583   dXSARGS;
2584
2585   char buf[126];
2586   SHELLEXECUTEINFO si;
2587   char *file, *verb;
2588   wchar_t wfile[MAX_PATH];
2589   wchar_t wverb[20];
2590
2591   if (items != 2)
2592     Perl_croak(aTHX_ "usage: Win32::ShellEx($file, $verb)");
2593
2594   file = SvPV_nolen(ST(0));
2595   verb = SvPV_nolen(ST(1));
2596
2597   memset(&si, 0, sizeof(si));
2598   si.cbSize = sizeof(si);
2599   si.fMask = SEE_MASK_FLAG_NO_UI;
2600
2601   MultiByteToWideChar(CP_ACP, 0, verb, -1,
2602                       wverb, sizeof(wverb)/2);
2603   si.lpVerb = (TCHAR *)wverb;
2604
2605   MultiByteToWideChar(CP_ACP, 0, file, -1,
2606                       wfile, sizeof(wfile)/2);
2607   si.lpFile = (TCHAR *)wfile;
2608
2609   if(ShellExecuteEx(&si) == FALSE)
2610     {
2611       XSRETURN_NO;
2612     }
2613   XSRETURN_YES;
2614 }
2615 #endif
2616
2617 void
2618 Perl_init_os_extras(void)
2619 {
2620     dTHX;
2621     char *file = __FILE__;
2622     dXSUB_SYS;
2623
2624     w32_perlshell_tokens = NULL;
2625     w32_perlshell_items = -1;
2626     w32_fdpid = newAV(); /* XX needs to be in Perl_win32_init()? */
2627     Newx(w32_children, 1, child_tab);
2628     w32_num_children = 0;
2629
2630     newXS("Win32::GetCwd", w32_GetCwd, file);
2631     newXS("Win32::SetCwd", w32_SetCwd, file);
2632     newXS("Win32::GetTickCount", w32_GetTickCount, file);
2633     newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
2634 #if UNDER_CE > 200
2635     newXS("Win32::ShellEx", w32_ShellEx, file);
2636 #endif
2637     newXS("Win32::IsWinNT", w32_IsWinNT, file);
2638     newXS("Win32::IsWin95", w32_IsWin95, file);
2639     newXS("Win32::IsWinCE", w32_IsWinCE, file);
2640     newXS("Win32::CopyFile", w32_CopyFile, file);
2641     newXS("Win32::Sleep", w32_Sleep, file);
2642     newXS("Win32::MessageBox", w32_MessageBox, file);
2643     newXS("Win32::GetPowerStatus", w32_GetPowerStatus, file);
2644     newXS("Win32::GetOemInfo", w32_GetOemInfo, file);
2645 }
2646
2647 void
2648 myexit(void)
2649 {
2650   char buf[126];
2651
2652   puts("Hit return");
2653   fgets(buf, sizeof(buf), stdin);
2654 }
2655
2656 void
2657 Perl_win32_init(int *argcp, char ***argvp)
2658 {
2659 #ifdef UNDER_CE
2660   char *p;
2661
2662   if((p = xcegetenv("PERLDEBUG")) && (p[0] == 'y' || p[0] == 'Y'))
2663     atexit(myexit);
2664 #endif
2665
2666   MALLOC_INIT;
2667 }
2668
2669 DllExport void
2670 Perl_win32_term(void)
2671 {
2672     dTHX;
2673     HINTS_REFCNT_TERM;
2674     OP_REFCNT_TERM;
2675     PERLIO_TERM;
2676     MALLOC_TERM;
2677 }
2678
2679 void
2680 win32_get_child_IO(child_IO_table* ptbl)
2681 {
2682     ptbl->childStdIn    = GetStdHandle(STD_INPUT_HANDLE);
2683     ptbl->childStdOut   = GetStdHandle(STD_OUTPUT_HANDLE);
2684     ptbl->childStdErr   = GetStdHandle(STD_ERROR_HANDLE);
2685 }
2686
2687 win32_flock(int fd, int oper)
2688 {
2689   dTHX;
2690   Perl_croak(aTHX_ PL_no_func, "flock");
2691   return -1;
2692 }
2693
2694 DllExport int
2695 win32_waitpid(int pid, int *status, int flags)
2696 {
2697   dTHX;
2698   Perl_croak(aTHX_ PL_no_func, "waitpid");
2699   return -1;
2700 }
2701
2702 DllExport int
2703 win32_wait(int *status)
2704 {
2705   dTHX;
2706   Perl_croak(aTHX_ PL_no_func, "wait");
2707   return -1;
2708 }
2709
2710 int
2711 wce_reopen_stdout(char *fname)
2712 {
2713   if(xcefreopen(fname, "w", stdout) == NULL)
2714     return -1;
2715
2716   return 0;
2717 }
2718
2719 void
2720 wce_hitreturn()
2721 {
2722   char buf[126];
2723
2724   printf("Hit RETURN");
2725   fflush(stdout);
2726   fgets(buf, sizeof(buf), stdin);
2727   return;
2728 }
2729
2730 /* //////////////////////////////////////////////////////////////////// */
2731
2732 #undef getcwd
2733
2734 char *
2735 getcwd(char *buf, size_t size)
2736 {
2737   return xcegetcwd(buf, size);
2738 }
2739
2740 int
2741 isnan(double d)
2742 {
2743   return _isnan(d);
2744 }
2745
2746
2747 DllExport PerlIO*
2748 win32_popenlist(const char *mode, IV narg, SV **args)
2749 {
2750  dTHX;
2751  Perl_croak(aTHX_ "List form of pipe open not implemented");
2752  return NULL;
2753 }
2754
2755 /*
2756  * a popen() clone that respects PERL5SHELL
2757  *
2758  * changed to return PerlIO* rather than FILE * by BKS, 11-11-2000
2759  */
2760
2761 DllExport PerlIO*
2762 win32_popen(const char *command, const char *mode)
2763 {
2764     return _popen(command, mode);
2765 }
2766
2767 /*
2768  * pclose() clone
2769  */
2770
2771 DllExport int
2772 win32_pclose(PerlIO *pf)
2773 {
2774     return _pclose(pf);
2775 }
2776
2777 #ifdef HAVE_INTERP_INTERN
2778
2779
2780 static void
2781 win32_csighandler(int sig)
2782 {
2783 #if 0
2784     dTHXa(PERL_GET_SIG_CONTEXT);
2785     Perl_warn(aTHX_ "Got signal %d",sig);
2786 #endif
2787     /* Does nothing */
2788 }
2789
2790 void
2791 Perl_sys_intern_init(pTHX)
2792 {
2793     int i;
2794     w32_perlshell_tokens        = NULL;
2795     w32_perlshell_vec           = (char**)NULL;
2796     w32_perlshell_items         = 0;
2797     w32_fdpid                   = newAV();
2798     Newx(w32_children, 1, child_tab);
2799     w32_num_children            = 0;
2800 #  ifdef USE_ITHREADS
2801     w32_pseudo_id               = 0;
2802     Newx(w32_pseudo_children, 1, child_tab);
2803     w32_num_pseudo_children     = 0;
2804 #  endif
2805     w32_init_socktype           = 0;
2806     w32_timerid                 = 0;
2807     w32_poll_count              = 0;
2808 }
2809
2810 void
2811 Perl_sys_intern_clear(pTHX)
2812 {
2813     Safefree(w32_perlshell_tokens);
2814     Safefree(w32_perlshell_vec);
2815     /* NOTE: w32_fdpid is freed by sv_clean_all() */
2816     Safefree(w32_children);
2817     if (w32_timerid) {
2818         KillTimer(NULL,w32_timerid);
2819         w32_timerid=0;
2820     }
2821 #  ifdef USE_ITHREADS
2822     Safefree(w32_pseudo_children);
2823 #  endif
2824 }
2825
2826 #  ifdef USE_ITHREADS
2827
2828 void
2829 Perl_sys_intern_dup(pTHX_ struct interp_intern *src, struct interp_intern *dst)
2830 {
2831     dst->perlshell_tokens       = NULL;
2832     dst->perlshell_vec          = (char**)NULL;
2833     dst->perlshell_items        = 0;
2834     dst->fdpid                  = newAV();
2835     Newxz(dst->children, 1, child_tab);
2836     dst->pseudo_id              = 0;
2837     Newxz(dst->pseudo_children, 1, child_tab);
2838     dst->thr_intern.Winit_socktype = 0;
2839     dst->timerid                 = 0;
2840     dst->poll_count              = 0;
2841     Copy(src->sigtable,dst->sigtable,SIG_SIZE,Sighandler_t);
2842 }
2843 #  endif /* USE_ITHREADS */
2844 #endif /* HAVE_INTERP_INTERN */
2845
2846 // added to remove undefied symbol error in CodeWarrior compilation
2847 int
2848 Perl_Ireentrant_buffer_ptr(aTHX)
2849 {
2850         return 0;
2851 }