This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Call FETCH once for $tied_ref =~ y/a/b/
[perl5.git] / win32 / wince.c
CommitLineData
e1caacb4
JH
1/* WINCE.C - stuff for Windows CE
2 *
ca6c63e1 3 * Time-stamp: <26/10/01 15:25:20 keuchel@keuchelnt>
e1caacb4
JH
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>
216db7ee 12#include <signal.h>
e1caacb4 13
f4257e4d 14#define PERLIO_NOT_STDIO 0
e1caacb4
JH
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>
814ffeea 35#include <process.h>
e1caacb4
JH
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
94081db1
VK
44#define GetCurrentDirectoryW XCEGetCurrentDirectoryW
45
e1caacb4
JH
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
814ffeea
VK
67static void get_shell(void);
68static long tokenize(const char *str, char **dest, char ***destv);
69static int do_spawn2(pTHX_ char *cmd, int exectype);
70static BOOL has_shell_metachars(char *ptr);
e1caacb4
JH
71static long filetime_to_clock(PFILETIME ft);
72static BOOL filetime_from_time(PFILETIME ft, time_t t);
e6a0bbf8
NC
73static char * get_emd_part(SV **leading, STRLEN *const len,
74 char *trailing, ...);
814ffeea
VK
75static void remove_dead_process(long deceased);
76static long find_pid(int pid);
77static char * qualified_path(const char *cmd);
e1caacb4 78static char * win32_get_xlib(const char *pl, const char *xlib,
e6a0bbf8 79 const char *libname, STRLEN *const len);
e1caacb4 80
814ffeea
VK
81#ifdef USE_ITHREADS
82static void remove_dead_pseudo_process(long child);
83static long find_pseudo_pid(int pid);
84#endif
85
86int _fmode = O_TEXT; /* celib do not provide _fmode, so we define it here */
87
e1caacb4
JH
88START_EXTERN_C
89HANDLE w32_perldll_handle = INVALID_HANDLE_VALUE;
90char w32_module_name[MAX_PATH+1];
91END_EXTERN_C
92
93static DWORD w32_platform = (DWORD)-1;
94
f4257e4d 95int
e1caacb4
JH
96IsWin95(void)
97{
98 return (win32_os_id() == VER_PLATFORM_WIN32_WINDOWS);
99}
100
101int
102IsWinNT(void)
103{
104 return (win32_os_id() == VER_PLATFORM_WIN32_NT);
105}
106
107int
108IsWinCE(void)
109{
110 return (win32_os_id() == VER_PLATFORM_WIN32_CE);
111}
112
113EXTERN_C void
114set_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)) */
132static char*
133get_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";
4e205ed6 139 char *str = NULL;
e1caacb4
JH
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) {
acfe0abc 147 dTHX;
e1caacb4
JH
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)) */
164static char*
165get_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)) */
174static char *
e6a0bbf8 175get_emd_part(SV **prev_pathp, STRLEN *const len, char *trailing_path, ...)
e1caacb4
JH
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 */
acfe0abc 227 dTHX;
e1caacb4
JH
228 if (!*prev_pathp)
229 *prev_pathp = sv_2mortal(newSVpvn("",0));
230 sv_catpvn(*prev_pathp, ";", 1);
231 sv_catpv(*prev_pathp, mod_name);
e6a0bbf8
NC
232 if(len)
233 *len = SvCUR(*prev_pathp);
e1caacb4
JH
234 return SvPVX(*prev_pathp);
235 }
236
4e205ed6 237 return NULL;
e1caacb4
JH
238}
239
240char *
e6a0bbf8 241win32_get_privlib(const char *pl, STRLEN *const len)
e1caacb4 242{
acfe0abc 243 dTHX;
e1caacb4
JH
244 char *stdlib = "lib";
245 char buffer[MAX_PATH+1];
4e205ed6 246 SV *sv = NULL;
e1caacb4
JH
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" */
e6a0bbf8 254 return get_emd_part(&sv, len, stdlib, ARCHNAME, "bin", NULL);
e1caacb4
JH
255}
256
257static char *
e6a0bbf8
NC
258win32_get_xlib(const char *pl, const char *xlib, const char *libname,
259 STRLEN *const len)
e1caacb4 260{
acfe0abc 261 dTHX;
e1caacb4
JH
262 char regstr[40];
263 char pathstr[MAX_PATH+1];
264 DWORD datalen;
265 int len, newsize;
4e205ed6
SP
266 SV *sv1 = NULL;
267 SV *sv2 = NULL;
e1caacb4
JH
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);
e6a0bbf8 276 (void)get_emd_part(&sv1, NULL, pathstr, ARCHNAME, "bin", pl, NULL);
e1caacb4
JH
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);
e6a0bbf8 284 (void)get_emd_part(&sv2, NULL, pathstr, ARCHNAME, "bin", pl, NULL);
e1caacb4
JH
285
286 if (!sv1 && !sv2)
4e205ed6 287 return NULL;
e6a0bbf8
NC
288 if (!sv1) {
289 sv1 = sv2;
290 } else if (sv2) {
291 sv_catpvn(sv1, ";", 1);
292 sv_catsv(sv1, sv2);
293 }
e1caacb4 294
e6a0bbf8
NC
295 if (len)
296 *len = SvCUR(sv1);
e1caacb4
JH
297 return SvPVX(sv1);
298}
299
300char *
e6a0bbf8 301win32_get_sitelib(const char *pl, STRLEN *const len)
e1caacb4 302{
e6a0bbf8 303 return win32_get_xlib(pl, "sitelib", "site", len);
e1caacb4
JH
304}
305
306#ifndef PERL_VENDORLIB_NAME
307# define PERL_VENDORLIB_NAME "vendor"
308#endif
309
310char *
e6a0bbf8 311win32_get_vendorlib(const char *pl, STRLEN *const len)
e1caacb4 312{
e6a0bbf8 313 return win32_get_xlib(pl, "vendorlib", PERL_VENDORLIB_NAME, len);
e1caacb4
JH
314}
315
814ffeea
VK
316static BOOL
317has_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
e1caacb4
JH
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 */
361PerlIO *
751e07d2 362Perl_my_popen(pTHX_ const char *cmd, const char *mode)
e1caacb4
JH
363{
364 printf("popen(%s)\n", cmd);
365
366 Perl_croak(aTHX_ PL_no_func, "popen");
367 return NULL;
368}
369
370long
371Perl_my_pclose(pTHX_ PerlIO *fp)
372{
373 Perl_croak(aTHX_ PL_no_func, "pclose");
374 return -1;
375}
376#endif
377
378DllExport unsigned long
379win32_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
392DllExport int
393win32_getpid(void)
394{
814ffeea
VK
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;
e1caacb4
JH
403}
404
814ffeea
VK
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 */
411static long
412tokenize(const char *str, char **dest, char ***destv)
e1caacb4 413{
4e205ed6 414 char *retstart = NULL;
814ffeea
VK
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;
a02a5408
JC
422 Newx(ret, slen+2, char);
423 Newx(retv, (slen+3)/2, char*);
814ffeea
VK
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 }
4e205ed6 449 retvstart[items] = NULL;
814ffeea
VK
450 *ret++ = '\0';
451 *ret = '\0';
452 }
453 *dest = retstart;
454 *destv = retvstart;
455 return items;
e1caacb4
JH
456}
457
458DllExport int
459win32_pipe(int *pfd, unsigned int size, int mode)
460{
216db7ee 461 dTHX;
e1caacb4
JH
462 Perl_croak(aTHX_ PL_no_func, "pipe");
463 return -1;
464}
465
466DllExport int
467win32_times(struct tms *timebuf)
468{
216db7ee 469 dTHX;
e1caacb4
JH
470 Perl_croak(aTHX_ PL_no_func, "times");
471 return -1;
472}
473
216db7ee
VK
474Sighandler_t
475win32_signal(int sig, Sighandler_t subcode)
42165d27 476{
1829b0dc 477 return xcesignal(sig, subcode);
42165d27 478}
216db7ee 479
814ffeea
VK
480static void
481get_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
501int
502Perl_do_aspawn(pTHX_ SV *really, SV **mark, SV **sp)
503{
7918f24d
NC
504 PERL_ARGS_ASSERT_DO_ASPAWN;
505
814ffeea
VK
506 Perl_croak(aTHX_ PL_no_func, "aspawn");
507 return -1;
508}
42165d27 509
814ffeea
VK
510/* returns pointer to the next unquoted space or the end of the string */
511static char*
512find_next_space(const char *s)
e1caacb4 513{
814ffeea
VK
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
535static int
536do_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)) {
a02a5408
JC
548 Newx(argv, strlen(cmd) / 2 + 2, char*);
549 Newx(cmd2, strlen(cmd) + 1, char);
814ffeea
VK
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 }
4e205ed6 561 *a = NULL;
814ffeea
VK
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();
a02a5408 586 Newx(argv, w32_perlshell_items + 2, char*);
814ffeea
VK
587 while (++i < w32_perlshell_items)
588 argv[i] = w32_perlshell_vec[i];
589 argv[i++] = cmd;
4e205ed6 590 argv[i] = NULL;
814ffeea
VK
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
626int
627Perl_do_spawn(pTHX_ char *cmd)
628{
7918f24d
NC
629 PERL_ARGS_ASSERT_DO_SPAWN;
630
814ffeea
VK
631 return do_spawn2(aTHX_ cmd, EXECF_SPAWN);
632}
633
634int
635Perl_do_spawn_nowait(pTHX_ char *cmd)
636{
7918f24d
NC
637 PERL_ARGS_ASSERT_DO_SPAWN_NOWAIT;
638
814ffeea
VK
639 return do_spawn2(aTHX_ cmd, EXECF_SPAWN_NOWAIT);
640}
641
642bool
751e07d2 643Perl_do_exec(pTHX_ const char *cmd)
814ffeea 644{
7918f24d
NC
645 PERL_ARGS_ASSERT_DO_EXEC;
646
814ffeea
VK
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 */
655DllExport DIR *
0e06f75d 656win32_opendir(const char *filename)
814ffeea
VK
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 */
a02a5408 680 Newxz(dirp, 1, DIR);
814ffeea
VK
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;
a02a5408 729 Newx(dirp->start, dirp->size, char);
814ffeea
VK
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 */
741DllExport struct direct *
742win32_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 */
796DllExport long
797win32_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 */
806DllExport void
807win32_seekdir(DIR *dirp, long loc)
808{
809 dirp->curr = dirp->start + loc;
810}
811
812/* Rewinddir resets the string pointer to the start */
813DllExport void
814win32_rewinddir(DIR *dirp)
815{
816 dirp->curr = dirp->start;
817}
818
819/* free the memory allocated by opendir */
820DllExport int
821win32_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;
e1caacb4
JH
829}
830
814ffeea
VK
831#else
832/////!!!!!!!!!!! return here and do right stuff!!!!
833
e1caacb4 834DllExport DIR *
0e06f75d 835win32_opendir(const char *filename)
e1caacb4
JH
836{
837 return opendir(filename);
838}
839
840DllExport struct direct *
841win32_readdir(DIR *dirp)
842{
843 return readdir(dirp);
844}
845
846DllExport long
847win32_telldir(DIR *dirp)
848{
216db7ee 849 dTHX;
e1caacb4
JH
850 Perl_croak(aTHX_ PL_no_func, "telldir");
851 return -1;
852}
853
854DllExport void
855win32_seekdir(DIR *dirp, long loc)
856{
216db7ee 857 dTHX;
e1caacb4
JH
858 Perl_croak(aTHX_ PL_no_func, "seekdir");
859}
860
861DllExport void
862win32_rewinddir(DIR *dirp)
863{
216db7ee 864 dTHX;
e1caacb4
JH
865 Perl_croak(aTHX_ PL_no_func, "rewinddir");
866}
867
868DllExport int
869win32_closedir(DIR *dirp)
870{
871 closedir(dirp);
872 return 0;
873}
814ffeea 874#endif // 1
e1caacb4
JH
875
876DllExport int
877win32_kill(int pid, int sig)
878{
216db7ee 879 dTHX;
e1caacb4
JH
880 Perl_croak(aTHX_ PL_no_func, "kill");
881 return -1;
882}
883
e1caacb4
JH
884DllExport int
885win32_stat(const char *path, struct stat *sbuf)
886{
887 return xcestat(path, sbuf);
888}
889
890DllExport char *
891win32_longpath(char *path)
892{
893 return path;
894}
895
e1caacb4
JH
896DllExport char *
897win32_getenv(const char *name)
898{
899 return xcegetenv(name);
900}
901
902DllExport int
903win32_putenv(const char *name)
904{
905 return xceputenv(name);
906}
907
e1caacb4
JH
908static long
909filetime_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 */
919static BOOL
920filetime_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
941DllExport int
942win32_unlink(const char *filename)
943{
944 return xceunlink(filename);
945}
946
947DllExport int
948win32_utime(const char *filename, struct utimbuf *times)
949{
950 return xceutime(filename, (struct _utimbuf *) times);
951}
952
953DllExport int
e2a02c1e
VK
954win32_gettimeofday(struct timeval *tp, void *not_used)
955{
956 return xcegettimeofday(tp,not_used);
957}
958
959DllExport int
e1caacb4
JH
960win32_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
e1caacb4 1031 switch (info.wProcessorArchitecture) {
e1caacb4
JH
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
814ffeea
VK
1055/* Timing related stuff */
1056
1057int
f4257e4d 1058do_raise(pTHX_ int sig)
814ffeea
VK
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
216db7ee
VK
1090void
1091sig_terminate(pTHX_ int sig)
1092{
2e332e71 1093 Perl_warn(aTHX_ "Terminating on signal SIG%s(%d)\n",PL_sig_name[sig], sig);
f4257e4d
YO
1094 /* exit() seems to be safe, my_exit() or die() is a problem in ^C
1095 thread
216db7ee
VK
1096 */
1097 exit(sig);
1098}
1099
1100DllExport int
1101win32_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
2e332e71 1121
216db7ee
VK
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. */
1164DllExport DWORD
1165win32_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
e1caacb4
JH
1201static UINT timerid = 0;
1202
1203static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
1204{
acfe0abc 1205 dTHX;
e1caacb4 1206 KillTimer(NULL,timerid);
f4257e4d 1207 timerid=0;
e1caacb4
JH
1208 sighandler(14);
1209}
e1caacb4
JH
1210
1211DllExport unsigned int
814ffeea
VK
1212win32_sleep(unsigned int t)
1213{
1214 return xcesleep(t);
1215}
1216
1217DllExport unsigned int
e1caacb4
JH
1218win32_alarm(unsigned int sec)
1219{
f4257e4d 1220 /*
e1caacb4 1221 * the 'obvious' implentation is SetTimer() with a callback
f4257e4d
YO
1222 * which does whatever receiving SIGALRM would do
1223 * we cannot use SIGALRM even via raise() as it is not
e1caacb4
JH
1224 * one of the supported codes in <signal.h>
1225 *
1226 * Snag is unless something is looking at the message queue
1227 * nothing happens :-(
f4257e4d 1228 */
acfe0abc 1229 dTHX;
e1caacb4
JH
1230 if (sec)
1231 {
1232 timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
1233 if (!timerid)
1234 Perl_croak_nocontext("Cannot set timer");
f4257e4d 1235 }
e1caacb4
JH
1236 else
1237 {
1238 if (timerid)
1239 {
1240 KillTimer(NULL,timerid);
f4257e4d 1241 timerid=0;
e1caacb4
JH
1242 }
1243 }
e1caacb4
JH
1244 return 0;
1245}
1246
1247#ifdef HAVE_DES_FCRYPT
1248extern char * des_fcrypt(const char *txt, const char *salt, char *cbuf);
1249#endif
1250
1251DllExport char *
1252win32_crypt(const char *txt, const char *salt)
1253{
acfe0abc 1254 dTHX;
e1caacb4
JH
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.");
4e205ed6 1260 return NULL;
e1caacb4
JH
1261#endif
1262}
1263
e1caacb4
JH
1264
1265/*
1266 * redirected io subsystem for all XS modules
1267 *
1268 */
1269
1270DllExport int *
1271win32_errno(void)
1272{
1273 return (&errno);
1274}
1275
814ffeea
VK
1276DllExport char ***
1277win32_environ(void)
1278{
1279 return (&(environ));
1280}
1281
e1caacb4
JH
1282/* the rest are the remapped stdio routines */
1283DllExport FILE *
1284win32_stderr(void)
1285{
1286 return (stderr);
1287}
1288
216db7ee
VK
1289char *g_getlogin() {
1290 return "no-getlogin";
1291}
1292
e1caacb4
JH
1293DllExport FILE *
1294win32_stdin(void)
1295{
1296 return (stdin);
1297}
1298
1299DllExport FILE *
1300win32_stdout()
1301{
1302 return (stdout);
1303}
1304
1305DllExport int
1306win32_ferror(FILE *fp)
1307{
1308 return (ferror(fp));
1309}
1310
1311
1312DllExport int
1313win32_feof(FILE *fp)
1314{
1315 return (feof(fp));
1316}
1317
1318/*
f4257e4d 1319 * Since the errors returned by the socket error function
e1caacb4
JH
1320 * WSAGetLastError() are not known by the library routine strerror
1321 * we have to roll our own.
1322 */
1323
1324DllExport char *
814ffeea 1325win32_strerror(int e)
e1caacb4
JH
1326{
1327 return xcestrerror(e);
1328}
1329
1330DllExport void
1331win32_str_os_error(void *sv, DWORD dwErr)
1332{
acfe0abc 1333 dTHX;
e1caacb4
JH
1334
1335 sv_setpvn((SV*)sv, "Error", 5);
1336}
1337
1338
1339DllExport int
1340win32_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
1348DllExport int
1349win32_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
1357DllExport int
1358win32_vfprintf(FILE *fp, const char *format, va_list args)
1359{
1360 return (vfprintf(fp, format, args));
1361}
1362
1363DllExport int
1364win32_vprintf(const char *format, va_list args)
1365{
1366 return (vprintf(format, args));
1367}
1368
1369DllExport size_t
1370win32_fread(void *buf, size_t size, size_t count, FILE *fp)
1371{
1372 return fread(buf, size, count, fp);
1373}
1374
1375DllExport size_t
1376win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
1377{
1378 return fwrite(buf, size, count, fp);
1379}
1380
1381DllExport FILE *
1382win32_fopen(const char *filename, const char *mode)
1383{
1384 return xcefopen(filename, mode);
1385}
1386
1387DllExport FILE *
1388win32_fdopen(int handle, const char *mode)
1389{
1390 return palm_fdopen(handle, mode);
1391}
1392
1393DllExport FILE *
1394win32_freopen(const char *path, const char *mode, FILE *stream)
1395{
1396 return xcefreopen(path, mode, stream);
1397}
1398
1399DllExport int
1400win32_fclose(FILE *pf)
1401{
1402 return xcefclose(pf);
1403}
1404
1405DllExport int
1406win32_fputs(const char *s,FILE *pf)
1407{
1408 return fputs(s, pf);
1409}
1410
1411DllExport int
1412win32_fputc(int c,FILE *pf)
1413{
1414 return fputc(c,pf);
1415}
1416
1417DllExport int
1418win32_ungetc(int c,FILE *pf)
1419{
1420 return ungetc(c,pf);
1421}
1422
1423DllExport int
1424win32_getc(FILE *pf)
1425{
1426 return getc(pf);
1427}
1428
1429DllExport int
1430win32_fileno(FILE *pf)
1431{
1432 return palm_fileno(pf);
1433}
1434
1435DllExport void
1436win32_clearerr(FILE *pf)
1437{
1438 clearerr(pf);
1439 return;
1440}
1441
1442DllExport int
1443win32_fflush(FILE *pf)
1444{
1445 return fflush(pf);
1446}
1447
1448DllExport long
1449win32_ftell(FILE *pf)
1450{
1451 return ftell(pf);
1452}
1453
1454DllExport int
814ffeea 1455win32_fseek(FILE *pf, Off_t offset,int origin)
e1caacb4
JH
1456{
1457 return fseek(pf, offset, origin);
1458}
1459
cb69f87a
MB
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... */
e1caacb4
JH
1462DllExport int
1463win32_fgetpos(FILE *pf, fpos_t *p)
1464{
1465 return fgetpos(pf, p);
1466}
1467
1468DllExport int
1469win32_fsetpos(FILE *pf, const fpos_t *p)
1470{
1471 return fsetpos(pf, p);
1472}
1473
1474DllExport void
1475win32_rewind(FILE *pf)
1476{
1477 fseek(pf, 0, SEEK_SET);
1478 return;
1479}
1480
81003058
VK
1481DllExport int
1482win32_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) {
81003058
VK
1501 DEBUG_p(PerlIO_printf(Perl_debug_log,
1502 "Created tmpfile=%s\n",filename));
1503 return fd;
1504 }
1505 }
1506 }
1507 }
1508 return -1;
1509}
1510
e1caacb4
JH
1511DllExport FILE*
1512win32_tmpfile(void)
1513{
81003058
VK
1514 int fd = win32_tmpfd();
1515 if (fd >= 0)
1516 return win32_fdopen(fd, "w+b");
1517 return NULL;
e1caacb4
JH
1518}
1519
1520DllExport void
1521win32_abort(void)
1522{
1523 xceabort();
1524
1525 return;
1526}
1527
1528DllExport int
1529win32_fstat(int fd, struct stat *sbufptr)
1530{
1531 return xcefstat(fd, sbufptr);
1532}
1533
1534DllExport int
1535win32_link(const char *oldname, const char *newname)
1536{
216db7ee 1537 dTHX;
e1caacb4
JH
1538 Perl_croak(aTHX_ PL_no_func, "link");
1539
1540 return -1;
1541}
1542
1543DllExport int
1544win32_rename(const char *oname, const char *newname)
1545{
1546 return xcerename(oname, newname);
1547}
1548
1549DllExport int
1550win32_setmode(int fd, int mode)
1551{
bcdf844e
VK
1552 /* currently 'celib' seem to have this function in src, but not
1553 * exported. When it will be, we'll uncomment following line.
1554 */
1555 /* return xcesetmode(fd, mode); */
1556 return 0;
e1caacb4
JH
1557}
1558
216db7ee
VK
1559DllExport int
1560win32_chsize(int fd, Off_t size)
1561{
1562 return chsize(fd, size);
1563}
1564
e1caacb4 1565DllExport long
814ffeea 1566win32_lseek(int fd, Off_t offset, int origin)
e1caacb4
JH
1567{
1568 return xcelseek(fd, offset, origin);
1569}
1570
1571DllExport long
1572win32_tell(int fd)
1573{
1574 return xcelseek(fd, 0, SEEK_CUR);
1575}
1576
1577DllExport int
1578win32_open(const char *path, int flag, ...)
1579{
1580 int pmode;
1581 va_list ap;
1582
1583 va_start(ap, flag);
1584 pmode = va_arg(ap, int);
1585 va_end(ap);
1586
1587 return xceopen(path, flag, pmode);
1588}
1589
1590DllExport int
1591win32_close(int fd)
1592{
1593 return xceclose(fd);
1594}
1595
1596DllExport int
1597win32_eof(int fd)
1598{
216db7ee 1599 dTHX;
e1caacb4
JH
1600 Perl_croak(aTHX_ PL_no_func, "eof");
1601 return -1;
1602}
1603
1604DllExport int
1605win32_dup(int fd)
1606{
216db7ee 1607 return xcedup(fd); /* from celib/ceio.c; requires some more work on it */
e1caacb4
JH
1608}
1609
1610DllExport int
1611win32_dup2(int fd1,int fd2)
1612{
aebd5ec7 1613 return xcedup2(fd1,fd2);
e1caacb4
JH
1614}
1615
1616DllExport int
1617win32_read(int fd, void *buf, unsigned int cnt)
1618{
1619 return xceread(fd, buf, cnt);
1620}
1621
1622DllExport int
1623win32_write(int fd, const void *buf, unsigned int cnt)
1624{
1625 return xcewrite(fd, (void *) buf, cnt);
1626}
1627
1628DllExport int
1629win32_mkdir(const char *dir, int mode)
1630{
1631 return xcemkdir(dir);
1632}
1633
1634DllExport int
1635win32_rmdir(const char *dir)
1636{
1637 return xcermdir(dir);
1638}
1639
1640DllExport int
1641win32_chdir(const char *dir)
1642{
1643 return xcechdir(dir);
1644}
1645
1646DllExport int
1647win32_access(const char *path, int mode)
1648{
1649 return xceaccess(path, mode);
1650}
1651
1652DllExport int
1653win32_chmod(const char *path, int mode)
1654{
1655 return xcechmod(path, mode);
1656}
1657
814ffeea
VK
1658static char *
1659create_command_line(char *cname, STRLEN clen, const char * const *args)
216db7ee
VK
1660{
1661 dTHX;
1662 int index, argc;
1663 char *cmd, *ptr;
1664 const char *arg;
1665 STRLEN len = 0;
1666 bool bat_file = FALSE;
1667 bool cmd_shell = FALSE;
1668 bool dumb_shell = FALSE;
1669 bool extra_quotes = FALSE;
1670 bool quote_next = FALSE;
1671
1672 if (!cname)
1673 cname = (char*)args[0];
1674
1675 /* The NT cmd.exe shell has the following peculiarity that needs to be
1676 * worked around. It strips a leading and trailing dquote when any
1677 * of the following is true:
1678 * 1. the /S switch was used
1679 * 2. there are more than two dquotes
1680 * 3. there is a special character from this set: &<>()@^|
1681 * 4. no whitespace characters within the two dquotes
1682 * 5. string between two dquotes isn't an executable file
1683 * To work around this, we always add a leading and trailing dquote
1684 * to the string, if the first argument is either "cmd.exe" or "cmd",
1685 * and there were at least two or more arguments passed to cmd.exe
1686 * (not including switches).
1687 * XXX the above rules (from "cmd /?") don't seem to be applied
1688 * always, making for the convolutions below :-(
1689 */
1690 if (cname) {
1691 if (!clen)
1692 clen = strlen(cname);
1693
1694 if (clen > 4
1695 && (stricmp(&cname[clen-4], ".bat") == 0
1696 || (IsWinNT() && stricmp(&cname[clen-4], ".cmd") == 0)))
1697 {
1698 bat_file = TRUE;
1699 len += 3;
1700 }
1701 else {
1702 char *exe = strrchr(cname, '/');
1703 char *exe2 = strrchr(cname, '\\');
1704 if (exe2 > exe)
1705 exe = exe2;
1706 if (exe)
1707 ++exe;
1708 else
1709 exe = cname;
1710 if (stricmp(exe, "cmd.exe") == 0 || stricmp(exe, "cmd") == 0) {
1711 cmd_shell = TRUE;
1712 len += 3;
1713 }
1714 else if (stricmp(exe, "command.com") == 0
1715 || stricmp(exe, "command") == 0)
1716 {
1717 dumb_shell = TRUE;
1718 }
1719 }
1720 }
1721
1722 DEBUG_p(PerlIO_printf(Perl_debug_log, "Args "));
1723 for (index = 0; (arg = (char*)args[index]) != NULL; ++index) {
1724 STRLEN curlen = strlen(arg);
1725 if (!(arg[0] == '"' && arg[curlen-1] == '"'))
1726 len += 2; /* assume quoting needed (worst case) */
1727 len += curlen + 1;
1728 DEBUG_p(PerlIO_printf(Perl_debug_log, "[%s]",arg));
1729 }
1730 DEBUG_p(PerlIO_printf(Perl_debug_log, "\n"));
1731
1732 argc = index;
a02a5408 1733 Newx(cmd, len, char);
216db7ee
VK
1734 ptr = cmd;
1735
1736 if (bat_file) {
1737 *ptr++ = '"';
1738 extra_quotes = TRUE;
1739 }
1740
1741 for (index = 0; (arg = (char*)args[index]) != NULL; ++index) {
1742 bool do_quote = 0;
1743 STRLEN curlen = strlen(arg);
1744
1745 /* we want to protect empty arguments and ones with spaces with
1746 * dquotes, but only if they aren't already there */
1747 if (!dumb_shell) {
1748 if (!curlen) {
1749 do_quote = 1;
1750 }
1751 else if (quote_next) {
1752 /* see if it really is multiple arguments pretending to
1753 * be one and force a set of quotes around it */
1754 if (*find_next_space(arg))
1755 do_quote = 1;
1756 }
1757 else if (!(arg[0] == '"' && curlen > 1 && arg[curlen-1] == '"')) {
1758 STRLEN i = 0;
1759 while (i < curlen) {
1760 if (isSPACE(arg[i])) {
1761 do_quote = 1;
1762 }
1763 else if (arg[i] == '"') {
1764 do_quote = 0;
1765 break;
1766 }
1767 i++;
1768 }
1769 }
1770 }
1771
1772 if (do_quote)
1773 *ptr++ = '"';
1774
1775 strcpy(ptr, arg);
1776 ptr += curlen;
1777
1778 if (do_quote)
1779 *ptr++ = '"';
1780
1781 if (args[index+1])
1782 *ptr++ = ' ';
1783
1784 if (!extra_quotes
1785 && cmd_shell
1786 && curlen >= 2
1787 && *arg == '/' /* see if arg is "/c", "/x/c", "/x/d/c" etc. */
1788 && stricmp(arg+curlen-2, "/c") == 0)
1789 {
1790 /* is there a next argument? */
1791 if (args[index+1]) {
1792 /* are there two or more next arguments? */
1793 if (args[index+2]) {
1794 *ptr++ = '"';
1795 extra_quotes = TRUE;
1796 }
1797 else {
1798 /* single argument, force quoting if it has spaces */
1799 quote_next = TRUE;
1800 }
1801 }
1802 }
1803 }
1804
1805 if (extra_quotes)
1806 *ptr++ = '"';
1807
1808 *ptr = '\0';
1809
1810 return cmd;
1811}
1812
1813static char *
1814qualified_path(const char *cmd)
1815{
1816 dTHX;
1817 char *pathstr;
1818 char *fullcmd, *curfullcmd;
1819 STRLEN cmdlen = 0;
1820 int has_slash = 0;
1821
1822 if (!cmd)
4e205ed6 1823 return NULL;
216db7ee
VK
1824 fullcmd = (char*)cmd;
1825 while (*fullcmd) {
1826 if (*fullcmd == '/' || *fullcmd == '\\')
1827 has_slash++;
1828 fullcmd++;
1829 cmdlen++;
1830 }
1831
1832 /* look in PATH */
1833 pathstr = PerlEnv_getenv("PATH");
a02a5408 1834 Newx(fullcmd, MAX_PATH+1, char);
216db7ee
VK
1835 curfullcmd = fullcmd;
1836
1837 while (1) {
1838 DWORD res;
1839
1840 /* start by appending the name to the current prefix */
1841 strcpy(curfullcmd, cmd);
1842 curfullcmd += cmdlen;
1843
1844 /* if it doesn't end with '.', or has no extension, try adding
1845 * a trailing .exe first */
1846 if (cmd[cmdlen-1] != '.'
1847 && (cmdlen < 4 || cmd[cmdlen-4] != '.'))
1848 {
1849 strcpy(curfullcmd, ".exe");
1850 res = GetFileAttributes(fullcmd);
1851 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
1852 return fullcmd;
1853 *curfullcmd = '\0';
1854 }
1855
1856 /* that failed, try the bare name */
1857 res = GetFileAttributes(fullcmd);
1858 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
1859 return fullcmd;
1860
1861 /* quit if no other path exists, or if cmd already has path */
1862 if (!pathstr || !*pathstr || has_slash)
1863 break;
1864
1865 /* skip leading semis */
1866 while (*pathstr == ';')
1867 pathstr++;
1868
1869 /* build a new prefix from scratch */
1870 curfullcmd = fullcmd;
1871 while (*pathstr && *pathstr != ';') {
1872 if (*pathstr == '"') { /* foo;"baz;etc";bar */
1873 pathstr++; /* skip initial '"' */
1874 while (*pathstr && *pathstr != '"') {
1875 if ((STRLEN)(curfullcmd-fullcmd) < MAX_PATH-cmdlen-5)
1876 *curfullcmd++ = *pathstr;
1877 pathstr++;
1878 }
1879 if (*pathstr)
1880 pathstr++; /* skip trailing '"' */
1881 }
1882 else {
1883 if ((STRLEN)(curfullcmd-fullcmd) < MAX_PATH-cmdlen-5)
1884 *curfullcmd++ = *pathstr;
1885 pathstr++;
1886 }
1887 }
1888 if (*pathstr)
1889 pathstr++; /* skip trailing semi */
1890 if (curfullcmd > fullcmd /* append a dir separator */
1891 && curfullcmd[-1] != '/' && curfullcmd[-1] != '\\')
1892 {
1893 *curfullcmd++ = '\\';
1894 }
1895 }
1896
1897 Safefree(fullcmd);
4e205ed6 1898 return NULL;
216db7ee
VK
1899}
1900
8f33b42a
VK
1901/* The following are just place holders.
1902 * Some hosts may provide and environment that the OS is
1903 * not tracking, therefore, these host must provide that
1904 * environment and the current directory to CreateProcess
1905 */
1906
1907DllExport void*
1908win32_get_childenv(void)
1909{
1910 return NULL;
1911}
1912
1913DllExport void
1914win32_free_childenv(void* d)
1915{
1916}
1917
1918DllExport void
1919win32_clearenv(void)
1920{
1921 char *envv = GetEnvironmentStrings();
1922 char *cur = envv;
1923 STRLEN len;
1924 while (*cur) {
1925 char *end = strchr(cur,'=');
1926 if (end && end != cur) {
1927 *end = '\0';
1928 xcesetenv(cur, "", 0);
1929 *end = '=';
1930 cur = end + strlen(end+1)+2;
1931 }
1932 else if ((len = strlen(cur)))
1933 cur += len+1;
1934 }
1935 FreeEnvironmentStrings(envv);
1936}
1937
1938DllExport char*
1939win32_get_childdir(void)
1940{
1941 dTHX;
1942 char* ptr;
8c56068e
JD
1943 char szfilename[MAX_PATH+1];
1944 GetCurrentDirectoryA(MAX_PATH+1, szfilename);
8f33b42a 1945
a02a5408 1946 Newx(ptr, strlen(szfilename)+1, char);
8f33b42a
VK
1947 strcpy(ptr, szfilename);
1948 return ptr;
1949}
1950
1951DllExport void
1952win32_free_childdir(char* d)
1953{
1954 dTHX;
1955 Safefree(d);
1956}
1957
216db7ee
VK
1958/* XXX this needs to be made more compatible with the spawnvp()
1959 * provided by the various RTLs. In particular, searching for
1960 * *.{com,bat,cmd} files (as done by the RTLs) is unimplemented.
1961 * This doesn't significantly affect perl itself, because we
1962 * always invoke things using PERL5SHELL if a direct attempt to
1963 * spawn the executable fails.
1964 *
1965 * XXX splitting and rejoining the commandline between do_aspawn()
1966 * and win32_spawnvp() could also be avoided.
1967 */
1968
216db7ee
VK
1969DllExport int
1970win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
1971{
1972#ifdef USE_RTL_SPAWNVP
1973 return spawnvp(mode, cmdname, (char * const *)argv);
1974#else
1975 dTHX;
1976 int ret;
1977 void* env;
1978 char* dir;
1979 child_IO_table tbl;
1980 STARTUPINFO StartupInfo;
1981 PROCESS_INFORMATION ProcessInformation;
1982 DWORD create = 0;
1983 char *cmd;
4e205ed6 1984 char *fullcmd = NULL;
216db7ee
VK
1985 char *cname = (char *)cmdname;
1986 STRLEN clen = 0;
1987
1988 if (cname) {
1989 clen = strlen(cname);
1990 /* if command name contains dquotes, must remove them */
1991 if (strchr(cname, '"')) {
1992 cmd = cname;
a02a5408 1993 Newx(cname,clen+1,char);
216db7ee
VK
1994 clen = 0;
1995 while (*cmd) {
1996 if (*cmd != '"') {
1997 cname[clen] = *cmd;
1998 ++clen;
1999 }
2000 ++cmd;
2001 }
2002 cname[clen] = '\0';
2003 }
2004 }
2005
2006 cmd = create_command_line(cname, clen, argv);
2007
2008 env = PerlEnv_get_childenv();
2009 dir = PerlEnv_get_childdir();
2010
2011 switch(mode) {
2012 case P_NOWAIT: /* asynch + remember result */
2013 if (w32_num_children >= MAXIMUM_WAIT_OBJECTS) {
2014 errno = EAGAIN;
2015 ret = -1;
2016 goto RETVAL;
2017 }
2018 /* Create a new process group so we can use GenerateConsoleCtrlEvent()
2019 * in win32_kill()
2020 */
2021 /* not supported on CE create |= CREATE_NEW_PROCESS_GROUP; */
2022 /* FALL THROUGH */
2023
2024 case P_WAIT: /* synchronous execution */
2025 break;
2026 default: /* invalid mode */
2027 errno = EINVAL;
2028 ret = -1;
2029 goto RETVAL;
2030 }
2031 memset(&StartupInfo,0,sizeof(StartupInfo));
2032 StartupInfo.cb = sizeof(StartupInfo);
2033 memset(&tbl,0,sizeof(tbl));
2034 PerlEnv_get_child_IO(&tbl);
2035 StartupInfo.dwFlags = tbl.dwFlags;
2036 StartupInfo.dwX = tbl.dwX;
2037 StartupInfo.dwY = tbl.dwY;
2038 StartupInfo.dwXSize = tbl.dwXSize;
2039 StartupInfo.dwYSize = tbl.dwYSize;
2040 StartupInfo.dwXCountChars = tbl.dwXCountChars;
2041 StartupInfo.dwYCountChars = tbl.dwYCountChars;
2042 StartupInfo.dwFillAttribute = tbl.dwFillAttribute;
2043 StartupInfo.wShowWindow = tbl.wShowWindow;
2044 StartupInfo.hStdInput = tbl.childStdIn;
2045 StartupInfo.hStdOutput = tbl.childStdOut;
2046 StartupInfo.hStdError = tbl.childStdErr;
2047 if (StartupInfo.hStdInput == INVALID_HANDLE_VALUE &&
2048 StartupInfo.hStdOutput == INVALID_HANDLE_VALUE &&
2049 StartupInfo.hStdError == INVALID_HANDLE_VALUE)
2050 {
2051 create |= CREATE_NEW_CONSOLE;
2052 }
2053 else {
2054 StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
2055 }
2056 if (w32_use_showwindow) {
2057 StartupInfo.dwFlags |= STARTF_USESHOWWINDOW;
2058 StartupInfo.wShowWindow = w32_showwindow;
2059 }
2060
2061 DEBUG_p(PerlIO_printf(Perl_debug_log, "Spawning [%s] with [%s]\n",
2062 cname,cmd));
2063RETRY:
2064 if (!CreateProcess(cname, /* search PATH to find executable */
2065 cmd, /* executable, and its arguments */
2066 NULL, /* process attributes */
2067 NULL, /* thread attributes */
2068 TRUE, /* inherit handles */
2069 create, /* creation flags */
2070 (LPVOID)env, /* inherit environment */
2071 dir, /* inherit cwd */
2072 &StartupInfo,
2073 &ProcessInformation))
2074 {
2075 /* initial NULL argument to CreateProcess() does a PATH
2076 * search, but it always first looks in the directory
2077 * where the current process was started, which behavior
2078 * is undesirable for backward compatibility. So we
2079 * jump through our own hoops by picking out the path
2080 * we really want it to use. */
2081 if (!fullcmd) {
2082 fullcmd = qualified_path(cname);
2083 if (fullcmd) {
2084 if (cname != cmdname)
2085 Safefree(cname);
2086 cname = fullcmd;
2087 DEBUG_p(PerlIO_printf(Perl_debug_log,
2088 "Retrying [%s] with same args\n",
2089 cname));
2090 goto RETRY;
2091 }
2092 }
2093 errno = ENOENT;
2094 ret = -1;
2095 goto RETVAL;
2096 }
2097
2098 if (mode == P_NOWAIT) {
2099 /* asynchronous spawn -- store handle, return PID */
2100 ret = (int)ProcessInformation.dwProcessId;
2101 if (IsWin95() && ret < 0)
2102 ret = -ret;
2103
2104 w32_child_handles[w32_num_children] = ProcessInformation.hProcess;
2105 w32_child_pids[w32_num_children] = (DWORD)ret;
2106 ++w32_num_children;
2107 }
2108 else {
2109 DWORD status;
2110 win32_msgwait(aTHX_ 1, &ProcessInformation.hProcess, INFINITE, NULL);
2111 /* FIXME: if msgwait returned due to message perhaps forward the
2112 "signal" to the process
2113 */
2114 GetExitCodeProcess(ProcessInformation.hProcess, &status);
2115 ret = (int)status;
2116 CloseHandle(ProcessInformation.hProcess);
2117 }
2118
2119 CloseHandle(ProcessInformation.hThread);
2120
2121RETVAL:
2122 PerlEnv_free_childenv(env);
2123 PerlEnv_free_childdir(dir);
2124 Safefree(cmd);
2125 if (cname != cmdname)
2126 Safefree(cname);
2127 return ret;
2128#endif
2129}
2130
e1caacb4
JH
2131DllExport int
2132win32_execv(const char *cmdname, const char *const *argv)
2133{
216db7ee 2134 dTHX;
e1caacb4
JH
2135 Perl_croak(aTHX_ PL_no_func, "execv");
2136 return -1;
2137}
2138
2139DllExport int
2140win32_execvp(const char *cmdname, const char *const *argv)
2141{
216db7ee 2142 dTHX;
e1caacb4
JH
2143 Perl_croak(aTHX_ PL_no_func, "execvp");
2144 return -1;
2145}
2146
814ffeea
VK
2147DllExport void
2148win32_perror(const char *str)
e1caacb4 2149{
814ffeea
VK
2150 xceperror(str);
2151}
e1caacb4 2152
814ffeea
VK
2153DllExport void
2154win32_setbuf(FILE *pf, char *buf)
2155{
2156 dTHX;
2157 Perl_croak(aTHX_ PL_no_func, "setbuf");
2158}
e1caacb4 2159
814ffeea
VK
2160DllExport int
2161win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
2162{
2163 return setvbuf(pf, buf, type, size);
e1caacb4
JH
2164}
2165
814ffeea
VK
2166DllExport int
2167win32_flushall(void)
2168{
2169 return flushall();
2170}
e1caacb4 2171
814ffeea
VK
2172DllExport int
2173win32_fcloseall(void)
e1caacb4 2174{
814ffeea
VK
2175 return fcloseall();
2176}
e1caacb4 2177
814ffeea
VK
2178DllExport char*
2179win32_fgets(char *s, int n, FILE *pf)
2180{
2181 return fgets(s, n, pf);
2182}
e1caacb4 2183
814ffeea
VK
2184DllExport char*
2185win32_gets(char *s)
2186{
2187 return gets(s);
e1caacb4
JH
2188}
2189
814ffeea
VK
2190DllExport int
2191win32_fgetc(FILE *pf)
e1caacb4 2192{
814ffeea
VK
2193 return fgetc(pf);
2194}
e1caacb4 2195
814ffeea
VK
2196DllExport int
2197win32_putc(int c, FILE *pf)
2198{
2199 return putc(c,pf);
2200}
2201
2202DllExport int
2203win32_puts(const char *s)
2204{
2205 return puts(s);
2206}
2207
2208DllExport int
2209win32_getchar(void)
2210{
2211 return getchar();
2212}
2213
2214DllExport int
2215win32_putchar(int c)
2216{
2217 return putchar(c);
2218}
2219
2220#ifdef MYMALLOC
2221
2222#ifndef USE_PERL_SBRK
2223
2224static char *committed = NULL;
2225static char *base = NULL;
2226static char *reserved = NULL;
2227static char *brk = NULL;
2228static DWORD pagesize = 0;
2229static DWORD allocsize = 0;
2230
2231void *
2232sbrk(int need)
2233{
2234 void *result;
2235 if (!pagesize)
2236 {SYSTEM_INFO info;
2237 GetSystemInfo(&info);
2238 /* Pretend page size is larger so we don't perpetually
2239 * call the OS to commit just one page ...
2240 */
2241 pagesize = info.dwPageSize << 3;
2242 allocsize = info.dwAllocationGranularity;
2243 }
2244 /* This scheme fails eventually if request for contiguous
f4257e4d 2245 * block is denied so reserve big blocks - this is only
814ffeea
VK
2246 * address space not memory ...
2247 */
2248 if (brk+need >= reserved)
2249 {
2250 DWORD size = 64*1024*1024;
2251 char *addr;
2252 if (committed && reserved && committed < reserved)
2253 {
2254 /* Commit last of previous chunk cannot span allocations */
2255 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
2256 if (addr)
2257 committed = reserved;
2258 }
f4257e4d 2259 /* Reserve some (more) space
814ffeea
VK
2260 * Note this is a little sneaky, 1st call passes NULL as reserved
2261 * so lets system choose where we start, subsequent calls pass
2262 * the old end address so ask for a contiguous block
2263 */
2264 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
2265 if (addr)
2266 {
2267 reserved = addr+size;
2268 if (!base)
2269 base = addr;
2270 if (!committed)
2271 committed = base;
2272 if (!brk)
2273 brk = committed;
2274 }
2275 else
2276 {
2277 return (void *) -1;
2278 }
2279 }
2280 result = brk;
2281 brk += need;
2282 if (brk > committed)
2283 {
2284 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
2285 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
2286 if (addr)
2287 {
2288 committed += size;
2289 }
2290 else
2291 return (void *) -1;
2292 }
2293 return result;
2294}
2295
2296#endif
2297#endif
2298
2299DllExport void*
2300win32_malloc(size_t size)
2301{
2302 return malloc(size);
2303}
2304
2305DllExport void*
2306win32_calloc(size_t numitems, size_t size)
2307{
2308 return calloc(numitems,size);
2309}
2310
2311DllExport void*
2312win32_realloc(void *block, size_t size)
2313{
2314 return realloc(block,size);
2315}
2316
2317DllExport void
2318win32_free(void *block)
2319{
2320 free(block);
2321}
2322
2323int
2324win32_open_osfhandle(intptr_t osfhandle, int flags)
2325{
2326 int fh;
2327 char fileflags=0; /* _osfile flags */
2328
2329 Perl_croak_nocontext("win32_open_osfhandle() TBD on this platform");
2330 return 0;
2331}
2332
2333int
2334win32_get_osfhandle(int fd)
2335{
2336 int fh;
2337 char fileflags=0; /* _osfile flags */
2338
2339 Perl_croak_nocontext("win32_get_osfhandle() TBD on this platform");
2340 return 0;
2341}
2342
2343FILE *
2344win32_fdupopen(FILE *pf)
2345{
2346 FILE* pfdup;
2347 fpos_t pos;
2348 char mode[3];
2349 int fileno = win32_dup(win32_fileno(pf));
2350 int fmode = palm_fgetmode(pfdup);
2351
2352 fprintf(stderr,"DEBUG for win32_fdupopen()\n");
2353
2354 /* open the file in the same mode */
2355 if(fmode & O_RDONLY) {
2356 mode[0] = 'r';
2357 mode[1] = 0;
2358 }
2359 else if(fmode & O_APPEND) {
2360 mode[0] = 'a';
2361 mode[1] = 0;
2362 }
2363 else if(fmode & O_RDWR) {
2364 mode[0] = 'r';
2365 mode[1] = '+';
2366 mode[2] = 0;
2367 }
2368
2369 /* it appears that the binmode is attached to the
2370 * file descriptor so binmode files will be handled
2371 * correctly
2372 */
2373 pfdup = win32_fdopen(fileno, mode);
2374
2375 /* move the file pointer to the same position */
2376 if (!fgetpos(pf, &pos)) {
2377 fsetpos(pfdup, &pos);
2378 }
2379 return pfdup;
2380}
2381
2382DllExport void*
2383win32_dynaload(const char* filename)
2384{
2385 dTHX;
2386 HMODULE hModule;
2387
2388 hModule = XCELoadLibraryA(filename);
2389
2390 return hModule;
2391}
2392
2393/* this is needed by Cwd.pm... */
2394
2395static
2396XS(w32_GetCwd)
2397{
2398 dXSARGS;
2399 char buf[MAX_PATH];
2400 SV *sv = sv_newmortal();
2401
2402 xcegetcwd(buf, sizeof(buf));
2403
2404 sv_setpv(sv, xcestrdup(buf));
2405 EXTEND(SP,1);
2406 SvPOK_on(sv);
2407 ST(0) = sv;
2408#ifndef INCOMPLETE_TAINTS
2409 SvTAINTED_on(ST(0));
2410#endif
2411 XSRETURN(1);
2412}
2413
2414static
2415XS(w32_SetCwd)
2416{
2417 dXSARGS;
2418
2419 if (items != 1)
e1caacb4
JH
2420 Perl_croak(aTHX_ "usage: Win32::SetCwd($cwd)");
2421
2422 if (!xcechdir(SvPV_nolen(ST(0))))
2423 XSRETURN_YES;
2424
2425 XSRETURN_NO;
2426}
2427
2428static
2429XS(w32_GetTickCount)
2430{
2431 dXSARGS;
2432 DWORD msec = GetTickCount();
2433 EXTEND(SP,1);
2434 if ((IV)msec > 0)
2435 XSRETURN_IV(msec);
2436 XSRETURN_NV(msec);
2437}
2438
2439static
2440XS(w32_GetOSVersion)
2441{
2442 dXSARGS;
2443 OSVERSIONINFOA osver;
2444
2445 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOA);
2446 if (!XCEGetVersionExA(&osver)) {
2447 XSRETURN_EMPTY;
2448 }
22f1178f
VP
2449 mXPUSHp(osver.szCSDVersion, strlen(osver.szCSDVersion));
2450 mXPUSHi(osver.dwMajorVersion);
2451 mXPUSHi(osver.dwMinorVersion);
2452 mXPUSHi(osver.dwBuildNumber);
cb69f87a 2453 /* WINCE = 3 */
22f1178f 2454 mXPUSHi(osver.dwPlatformId);
e1caacb4
JH
2455 PUTBACK;
2456}
2457
2458static
2459XS(w32_IsWinNT)
2460{
2461 dXSARGS;
2462 EXTEND(SP,1);
2463 XSRETURN_IV(IsWinNT());
2464}
2465
2466static
2467XS(w32_IsWin95)
2468{
2469 dXSARGS;
2470 EXTEND(SP,1);
2471 XSRETURN_IV(IsWin95());
2472}
2473
2474static
2475XS(w32_IsWinCE)
2476{
2477 dXSARGS;
2478 EXTEND(SP,1);
2479 XSRETURN_IV(IsWinCE());
2480}
2481
2482static
2483XS(w32_GetOemInfo)
2484{
2485 dXSARGS;
2486 wchar_t wbuf[126];
2487 char buf[126];
2488
2489 if(SystemParametersInfoW(SPI_GETOEMINFO, sizeof(wbuf), wbuf, FALSE))
2490 WideCharToMultiByte(CP_ACP, 0, wbuf, -1, buf, sizeof(buf), 0, 0);
2491 else
2492 sprintf(buf, "SystemParametersInfo failed: %d", GetLastError());
2493
2494 EXTEND(SP,1);
2495 XSRETURN_PV(buf);
2496}
2497
2498static
2499XS(w32_Sleep)
2500{
2501 dXSARGS;
2502 if (items != 1)
2503 Perl_croak(aTHX_ "usage: Win32::Sleep($milliseconds)");
2504 Sleep(SvIV(ST(0)));
2505 XSRETURN_YES;
2506}
2507
2508static
2509XS(w32_CopyFile)
2510{
2511 dXSARGS;
2512 BOOL bResult;
2513 if (items != 3)
2514 Perl_croak(aTHX_ "usage: Win32::CopyFile($from, $to, $overwrite)");
2515
2516 {
2517 char szSourceFile[MAX_PATH+1];
2518 strcpy(szSourceFile, PerlDir_mapA(SvPV_nolen(ST(0))));
f4257e4d 2519 bResult = XCECopyFileA(szSourceFile, SvPV_nolen(ST(1)),
e1caacb4
JH
2520 !SvTRUE(ST(2)));
2521 }
2522
2523 if (bResult)
2524 XSRETURN_YES;
2525
2526 XSRETURN_NO;
2527}
2528
2529static
2530XS(w32_MessageBox)
2531{
2532 dXSARGS;
2533
2534 char *txt;
2535 unsigned int res;
2536 unsigned int flags = MB_OK;
2537
2538 txt = SvPV_nolen(ST(0));
f4257e4d 2539
e1caacb4
JH
2540 if (items < 1 || items > 2)
2541 Perl_croak(aTHX_ "usage: Win32::MessageBox($txt, [$flags])");
2542
2543 if(items == 2)
2544 flags = SvIV(ST(1));
2545
2546 res = XCEMessageBoxA(NULL, txt, "Perl", flags);
2547
2548 XSRETURN_IV(res);
2549}
2550
2551static
2552XS(w32_GetPowerStatus)
2553{
2554 dXSARGS;
2555
2556 SYSTEM_POWER_STATUS_EX sps;
2557
2558 if(GetSystemPowerStatusEx(&sps, TRUE) == FALSE)
2559 {
2560 XSRETURN_EMPTY;
2561 }
2562
22f1178f
VP
2563 mXPUSHi(sps.ACLineStatus);
2564 mXPUSHi(sps.BatteryFlag);
2565 mXPUSHi(sps.BatteryLifePercent);
2566 mXPUSHi(sps.BatteryLifeTime);
2567 mXPUSHi(sps.BatteryFullLifeTime);
2568 mXPUSHi(sps.BackupBatteryFlag);
2569 mXPUSHi(sps.BackupBatteryLifePercent);
2570 mXPUSHi(sps.BackupBatteryLifeTime);
2571 mXPUSHi(sps.BackupBatteryFullLifeTime);
e1caacb4
JH
2572
2573 PUTBACK;
2574}
2575
2576#if UNDER_CE > 200
2577static
2578XS(w32_ShellEx)
2579{
2580 dXSARGS;
2581
2582 char buf[126];
2583 SHELLEXECUTEINFO si;
2584 char *file, *verb;
2585 wchar_t wfile[MAX_PATH];
2586 wchar_t wverb[20];
2587
2588 if (items != 2)
2589 Perl_croak(aTHX_ "usage: Win32::ShellEx($file, $verb)");
2590
2591 file = SvPV_nolen(ST(0));
2592 verb = SvPV_nolen(ST(1));
2593
2594 memset(&si, 0, sizeof(si));
2595 si.cbSize = sizeof(si);
2596 si.fMask = SEE_MASK_FLAG_NO_UI;
2597
f4257e4d 2598 MultiByteToWideChar(CP_ACP, 0, verb, -1,
e1caacb4
JH
2599 wverb, sizeof(wverb)/2);
2600 si.lpVerb = (TCHAR *)wverb;
2601
f4257e4d 2602 MultiByteToWideChar(CP_ACP, 0, file, -1,
e1caacb4
JH
2603 wfile, sizeof(wfile)/2);
2604 si.lpFile = (TCHAR *)wfile;
2605
2606 if(ShellExecuteEx(&si) == FALSE)
2607 {
2608 XSRETURN_NO;
2609 }
2610 XSRETURN_YES;
2611}
2612#endif
2613
2614void
2615Perl_init_os_extras(void)
2616{
acfe0abc 2617 dTHX;
e1caacb4
JH
2618 char *file = __FILE__;
2619 dXSUB_SYS;
2620
4e205ed6 2621 w32_perlshell_tokens = NULL;
e1caacb4
JH
2622 w32_perlshell_items = -1;
2623 w32_fdpid = newAV(); /* XX needs to be in Perl_win32_init()? */
a02a5408 2624 Newx(w32_children, 1, child_tab);
e1caacb4
JH
2625 w32_num_children = 0;
2626
2627 newXS("Win32::GetCwd", w32_GetCwd, file);
2628 newXS("Win32::SetCwd", w32_SetCwd, file);
2629 newXS("Win32::GetTickCount", w32_GetTickCount, file);
2630 newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
2631#if UNDER_CE > 200
2632 newXS("Win32::ShellEx", w32_ShellEx, file);
2633#endif
2634 newXS("Win32::IsWinNT", w32_IsWinNT, file);
2635 newXS("Win32::IsWin95", w32_IsWin95, file);
2636 newXS("Win32::IsWinCE", w32_IsWinCE, file);
2637 newXS("Win32::CopyFile", w32_CopyFile, file);
2638 newXS("Win32::Sleep", w32_Sleep, file);
2639 newXS("Win32::MessageBox", w32_MessageBox, file);
2640 newXS("Win32::GetPowerStatus", w32_GetPowerStatus, file);
2641 newXS("Win32::GetOemInfo", w32_GetOemInfo, file);
2642}
2643
2644void
2645myexit(void)
2646{
2647 char buf[126];
2648
2649 puts("Hit return");
2650 fgets(buf, sizeof(buf), stdin);
2651}
2652
2653void
2654Perl_win32_init(int *argcp, char ***argvp)
2655{
2656#ifdef UNDER_CE
2657 char *p;
2658
2659 if((p = xcegetenv("PERLDEBUG")) && (p[0] == 'y' || p[0] == 'Y'))
2660 atexit(myexit);
2661#endif
2662
2663 MALLOC_INIT;
2664}
2665
216db7ee
VK
2666DllExport void
2667Perl_win32_term(void)
2668{
3890ecea 2669 dTHX;
71ad1b0c 2670 HINTS_REFCNT_TERM;
216db7ee 2671 OP_REFCNT_TERM;
3890ecea 2672 PERLIO_TERM;
216db7ee
VK
2673 MALLOC_TERM;
2674}
2675
2676void
2677win32_get_child_IO(child_IO_table* ptbl)
2678{
2679 ptbl->childStdIn = GetStdHandle(STD_INPUT_HANDLE);
2680 ptbl->childStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
2681 ptbl->childStdErr = GetStdHandle(STD_ERROR_HANDLE);
2682}
2683
e1caacb4
JH
2684win32_flock(int fd, int oper)
2685{
216db7ee 2686 dTHX;
e1caacb4
JH
2687 Perl_croak(aTHX_ PL_no_func, "flock");
2688 return -1;
2689}
2690
2691DllExport int
2692win32_waitpid(int pid, int *status, int flags)
2693{
216db7ee 2694 dTHX;
e1caacb4
JH
2695 Perl_croak(aTHX_ PL_no_func, "waitpid");
2696 return -1;
2697}
2698
2699DllExport int
2700win32_wait(int *status)
2701{
216db7ee 2702 dTHX;
e1caacb4
JH
2703 Perl_croak(aTHX_ PL_no_func, "wait");
2704 return -1;
2705}
2706
2707int
e1caacb4 2708wce_reopen_stdout(char *fname)
f4257e4d 2709{
e1caacb4
JH
2710 if(xcefreopen(fname, "w", stdout) == NULL)
2711 return -1;
2712
2713 return 0;
2714}
2715
2716void
2717wce_hitreturn()
2718{
2719 char buf[126];
2720
2721 printf("Hit RETURN");
2722 fflush(stdout);
2723 fgets(buf, sizeof(buf), stdin);
2724 return;
2725}
2726
cb69f87a 2727/* //////////////////////////////////////////////////////////////////// */
e1caacb4 2728
ca6c63e1
JH
2729#undef getcwd
2730
2731char *
2732getcwd(char *buf, size_t size)
2733{
2734 return xcegetcwd(buf, size);
2735}
2736
f4257e4d 2737int
ca6c63e1
JH
2738isnan(double d)
2739{
2740 return _isnan(d);
2741}
2742
18f68570 2743
814ffeea
VK
2744DllExport PerlIO*
2745win32_popenlist(const char *mode, IV narg, SV **args)
18f68570 2746{
814ffeea
VK
2747 dTHX;
2748 Perl_croak(aTHX_ "List form of pipe open not implemented");
2749 return NULL;
18f68570
VK
2750}
2751
2752/*
2753 * a popen() clone that respects PERL5SHELL
2754 *
2755 * changed to return PerlIO* rather than FILE * by BKS, 11-11-2000
2756 */
2757
2758DllExport PerlIO*
2759win32_popen(const char *command, const char *mode)
2760{
814ffeea 2761 return _popen(command, mode);
216db7ee
VK
2762}
2763
18f68570
VK
2764/*
2765 * pclose() clone
2766 */
2767
2768DllExport int
2769win32_pclose(PerlIO *pf)
2770{
18f68570 2771 return _pclose(pf);
18f68570
VK
2772}
2773
216db7ee
VK
2774#ifdef HAVE_INTERP_INTERN
2775
2776
2777static void
2778win32_csighandler(int sig)
2779{
2780#if 0
2781 dTHXa(PERL_GET_SIG_CONTEXT);
2782 Perl_warn(aTHX_ "Got signal %d",sig);
2783#endif
2784 /* Does nothing */
2785}
2786
2787void
2788Perl_sys_intern_init(pTHX)
2789{
2790 int i;
4e205ed6 2791 w32_perlshell_tokens = NULL;
216db7ee
VK
2792 w32_perlshell_vec = (char**)NULL;
2793 w32_perlshell_items = 0;
2794 w32_fdpid = newAV();
a02a5408 2795 Newx(w32_children, 1, child_tab);
216db7ee
VK
2796 w32_num_children = 0;
2797# ifdef USE_ITHREADS
2798 w32_pseudo_id = 0;
a02a5408 2799 Newx(w32_pseudo_children, 1, child_tab);
216db7ee
VK
2800 w32_num_pseudo_children = 0;
2801# endif
2802 w32_init_socktype = 0;
2803 w32_timerid = 0;
2804 w32_poll_count = 0;
2805}
2806
2807void
2808Perl_sys_intern_clear(pTHX)
2809{
2810 Safefree(w32_perlshell_tokens);
2811 Safefree(w32_perlshell_vec);
2812 /* NOTE: w32_fdpid is freed by sv_clean_all() */
2813 Safefree(w32_children);
2814 if (w32_timerid) {
2815 KillTimer(NULL,w32_timerid);
2816 w32_timerid=0;
2817 }
2818# ifdef USE_ITHREADS
2819 Safefree(w32_pseudo_children);
2820# endif
2821}
2822
2823# ifdef USE_ITHREADS
2824
2825void
2826Perl_sys_intern_dup(pTHX_ struct interp_intern *src, struct interp_intern *dst)
2827{
4e205ed6 2828 dst->perlshell_tokens = NULL;
216db7ee
VK
2829 dst->perlshell_vec = (char**)NULL;
2830 dst->perlshell_items = 0;
2831 dst->fdpid = newAV();
a02a5408 2832 Newxz(dst->children, 1, child_tab);
216db7ee 2833 dst->pseudo_id = 0;
a02a5408 2834 Newxz(dst->pseudo_children, 1, child_tab);
216db7ee
VK
2835 dst->thr_intern.Winit_socktype = 0;
2836 dst->timerid = 0;
2837 dst->poll_count = 0;
2838 Copy(src->sigtable,dst->sigtable,SIG_SIZE,Sighandler_t);
2839}
2840# endif /* USE_ITHREADS */
2841#endif /* HAVE_INTERP_INTERN */
2842
216db7ee
VK
2843// added to remove undefied symbol error in CodeWarrior compilation
2844int
2845Perl_Ireentrant_buffer_ptr(aTHX)
2846{
2847 return 0;
2848}