The new smart match dispatch table for 5.10.1 onwards
[p5sagit/p5-mst-13.2.git] / win32 / wince.c
CommitLineData
e1caacb4 1/* WINCE.C - stuff for Windows CE
2 *
ca6c63e1 3 * Time-stamp: <26/10/01 15:25:20 keuchel@keuchelnt>
e1caacb4 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 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 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 44#define GetCurrentDirectoryW XCEGetCurrentDirectoryW
45
e1caacb4 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 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 71static long filetime_to_clock(PFILETIME ft);
72static BOOL filetime_from_time(PFILETIME ft, time_t t);
e6a0bbf8 73static char * get_emd_part(SV **leading, STRLEN *const len,
74 char *trailing, ...);
814ffeea 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 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 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 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 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 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 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 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 232 if(len)
233 *len = SvCUR(*prev_pathp);
e1caacb4 234 return SvPVX(*prev_pathp);
235 }
236
4e205ed6 237 return NULL;
e1caacb4 238}
239
240char *
e6a0bbf8 241win32_get_privlib(const char *pl, STRLEN *const len)
e1caacb4 242{
acfe0abc 243 dTHX;
e1caacb4 244 char *stdlib = "lib";
245 char buffer[MAX_PATH+1];
4e205ed6 246 SV *sv = NULL;
e1caacb4 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 255}
256
257static char *
e6a0bbf8 258win32_get_xlib(const char *pl, const char *xlib, const char *libname,
259 STRLEN *const len)
e1caacb4 260{
acfe0abc 261 dTHX;
e1caacb4 262 char regstr[40];
263 char pathstr[MAX_PATH+1];
264 DWORD datalen;
265 int len, newsize;
4e205ed6 266 SV *sv1 = NULL;
267 SV *sv2 = NULL;
e1caacb4 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 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 285
286 if (!sv1 && !sv2)
4e205ed6 287 return NULL;
e6a0bbf8 288 if (!sv1) {
289 sv1 = sv2;
290 } else if (sv2) {
291 sv_catpvn(sv1, ";", 1);
292 sv_catsv(sv1, sv2);
293 }
e1caacb4 294
e6a0bbf8 295 if (len)
296 *len = SvCUR(sv1);
e1caacb4 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 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 314}
315
814ffeea 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 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 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 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 403}
404
814ffeea 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 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 422 Newx(ret, slen+2, char);
423 Newx(retv, (slen+3)/2, char*);
814ffeea 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 450 *ret++ = '\0';
451 *ret = '\0';
452 }
453 *dest = retstart;
454 *destv = retvstart;
455 return items;
e1caacb4 456}
457
458DllExport int
459win32_pipe(int *pfd, unsigned int size, int mode)
460{
216db7ee 461 dTHX;
e1caacb4 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 470 Perl_croak(aTHX_ PL_no_func, "times");
471 return -1;
472}
473
216db7ee 474Sighandler_t
475win32_signal(int sig, Sighandler_t subcode)
42165d27 476{
1829b0dc 477 return xcesignal(sig, subcode);
42165d27 478}
216db7ee 479
814ffeea 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 504 PERL_ARGS_ASSERT_DO_ASPAWN;
505
814ffeea 506 Perl_croak(aTHX_ PL_no_func, "aspawn");
507 return -1;
508}
42165d27 509
814ffeea 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 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 548 Newx(argv, strlen(cmd) / 2 + 2, char*);
549 Newx(cmd2, strlen(cmd) + 1, char);
814ffeea 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 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 587 while (++i < w32_perlshell_items)
588 argv[i] = w32_perlshell_vec[i];
589 argv[i++] = cmd;
4e205ed6 590 argv[i] = NULL;
814ffeea 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 629 PERL_ARGS_ASSERT_DO_SPAWN;
630
814ffeea 631 return do_spawn2(aTHX_ cmd, EXECF_SPAWN);
632}
633
634int
635Perl_do_spawn_nowait(pTHX_ char *cmd)
636{
7918f24d 637 PERL_ARGS_ASSERT_DO_SPAWN_NOWAIT;
638
814ffeea 639 return do_spawn2(aTHX_ cmd, EXECF_SPAWN_NOWAIT);
640}
641
642bool
751e07d2 643Perl_do_exec(pTHX_ const char *cmd)
814ffeea 644{
7918f24d 645 PERL_ARGS_ASSERT_DO_EXEC;
646
814ffeea 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 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 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 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 829}
830
814ffeea 831#else
832/////!!!!!!!!!!! return here and do right stuff!!!!
833
e1caacb4 834DllExport DIR *
0e06f75d 835win32_opendir(const char *filename)
e1caacb4 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 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 858 Perl_croak(aTHX_ PL_no_func, "seekdir");
859}
860
861DllExport void
862win32_rewinddir(DIR *dirp)
863{
216db7ee 864 dTHX;
e1caacb4 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 875
876DllExport int
877win32_kill(int pid, int sig)
878{
216db7ee 879 dTHX;
e1caacb4 880 Perl_croak(aTHX_ PL_no_func, "kill");
881 return -1;
882}
883
e1caacb4 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
896#ifndef USE_WIN32_RTL_ENV
897
898DllExport char *
899win32_getenv(const char *name)
900{
901 return xcegetenv(name);
902}
903
904DllExport int
905win32_putenv(const char *name)
906{
907 return xceputenv(name);
908}
909
910#endif
911
912static long
913filetime_to_clock(PFILETIME ft)
914{
915 __int64 qw = ft->dwHighDateTime;
916 qw <<= 32;
917 qw |= ft->dwLowDateTime;
918 qw /= 10000; /* File time ticks at 0.1uS, clock at 1mS */
919 return (long) qw;
920}
921
922/* fix utime() so it works on directories in NT */
923static BOOL
924filetime_from_time(PFILETIME pFileTime, time_t Time)
925{
926 struct tm *pTM = localtime(&Time);
927 SYSTEMTIME SystemTime;
928 FILETIME LocalTime;
929
930 if (pTM == NULL)
931 return FALSE;
932
933 SystemTime.wYear = pTM->tm_year + 1900;
934 SystemTime.wMonth = pTM->tm_mon + 1;
935 SystemTime.wDay = pTM->tm_mday;
936 SystemTime.wHour = pTM->tm_hour;
937 SystemTime.wMinute = pTM->tm_min;
938 SystemTime.wSecond = pTM->tm_sec;
939 SystemTime.wMilliseconds = 0;
940
941 return SystemTimeToFileTime(&SystemTime, &LocalTime) &&
942 LocalFileTimeToFileTime(&LocalTime, pFileTime);
943}
944
945DllExport int
946win32_unlink(const char *filename)
947{
948 return xceunlink(filename);
949}
950
951DllExport int
952win32_utime(const char *filename, struct utimbuf *times)
953{
954 return xceutime(filename, (struct _utimbuf *) times);
955}
956
957DllExport int
e2a02c1e 958win32_gettimeofday(struct timeval *tp, void *not_used)
959{
960 return xcegettimeofday(tp,not_used);
961}
962
963DllExport int
e1caacb4 964win32_uname(struct utsname *name)
965{
966 struct hostent *hep;
967 STRLEN nodemax = sizeof(name->nodename)-1;
968 OSVERSIONINFOA osver;
969
970 memset(&osver, 0, sizeof(OSVERSIONINFOA));
971 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOA);
972 if (XCEGetVersionExA(&osver)) {
973 /* sysname */
974 switch (osver.dwPlatformId) {
975 case VER_PLATFORM_WIN32_CE:
976 strcpy(name->sysname, "Windows CE");
977 break;
978 case VER_PLATFORM_WIN32_WINDOWS:
979 strcpy(name->sysname, "Windows");
980 break;
981 case VER_PLATFORM_WIN32_NT:
982 strcpy(name->sysname, "Windows NT");
983 break;
984 case VER_PLATFORM_WIN32s:
985 strcpy(name->sysname, "Win32s");
986 break;
987 default:
988 strcpy(name->sysname, "Win32 Unknown");
989 break;
990 }
991
992 /* release */
993 sprintf(name->release, "%d.%d",
994 osver.dwMajorVersion, osver.dwMinorVersion);
995
996 /* version */
997 sprintf(name->version, "Build %d",
998 osver.dwPlatformId == VER_PLATFORM_WIN32_NT
999 ? osver.dwBuildNumber : (osver.dwBuildNumber & 0xffff));
1000 if (osver.szCSDVersion[0]) {
1001 char *buf = name->version + strlen(name->version);
1002 sprintf(buf, " (%s)", osver.szCSDVersion);
1003 }
1004 }
1005 else {
1006 *name->sysname = '\0';
1007 *name->version = '\0';
1008 *name->release = '\0';
1009 }
1010
1011 /* nodename */
1012 hep = win32_gethostbyname("localhost");
1013 if (hep) {
1014 STRLEN len = strlen(hep->h_name);
1015 if (len <= nodemax) {
1016 strcpy(name->nodename, hep->h_name);
1017 }
1018 else {
1019 strncpy(name->nodename, hep->h_name, nodemax);
1020 name->nodename[nodemax] = '\0';
1021 }
1022 }
1023 else {
1024 DWORD sz = nodemax;
1025 if (!XCEGetComputerNameA(name->nodename, &sz))
1026 *name->nodename = '\0';
1027 }
1028
1029 /* machine (architecture) */
1030 {
1031 SYSTEM_INFO info;
1032 char *arch;
1033 GetSystemInfo(&info);
1034
e1caacb4 1035 switch (info.wProcessorArchitecture) {
e1caacb4 1036 case PROCESSOR_ARCHITECTURE_INTEL:
1037 arch = "x86"; break;
1038 case PROCESSOR_ARCHITECTURE_MIPS:
1039 arch = "mips"; break;
1040 case PROCESSOR_ARCHITECTURE_ALPHA:
1041 arch = "alpha"; break;
1042 case PROCESSOR_ARCHITECTURE_PPC:
1043 arch = "ppc"; break;
1044 case PROCESSOR_ARCHITECTURE_ARM:
1045 arch = "arm"; break;
1046 case PROCESSOR_HITACHI_SH3:
1047 arch = "sh3"; break;
1048 case PROCESSOR_SHx_SH3:
1049 arch = "sh3"; break;
1050
1051 default:
1052 arch = "unknown"; break;
1053 }
1054 strcpy(name->machine, arch);
1055 }
1056 return 0;
1057}
1058
814ffeea 1059/* Timing related stuff */
1060
1061int
f4257e4d 1062do_raise(pTHX_ int sig)
814ffeea 1063{
1064 if (sig < SIG_SIZE) {
1065 Sighandler_t handler = w32_sighandler[sig];
1066 if (handler == SIG_IGN) {
1067 return 0;
1068 }
1069 else if (handler != SIG_DFL) {
1070 (*handler)(sig);
1071 return 0;
1072 }
1073 else {
1074 /* Choose correct default behaviour */
1075 switch (sig) {
1076#ifdef SIGCLD
1077 case SIGCLD:
1078#endif
1079#ifdef SIGCHLD
1080 case SIGCHLD:
1081#endif
1082 case 0:
1083 return 0;
1084 case SIGTERM:
1085 default:
1086 break;
1087 }
1088 }
1089 }
1090 /* Tell caller to exit thread/process as approriate */
1091 return 1;
1092}
1093
216db7ee 1094void
1095sig_terminate(pTHX_ int sig)
1096{
2e332e71 1097 Perl_warn(aTHX_ "Terminating on signal SIG%s(%d)\n",PL_sig_name[sig], sig);
f4257e4d 1098 /* exit() seems to be safe, my_exit() or die() is a problem in ^C
1099 thread
216db7ee 1100 */
1101 exit(sig);
1102}
1103
1104DllExport int
1105win32_async_check(pTHX)
1106{
1107 MSG msg;
1108 int ours = 1;
1109 /* Passing PeekMessage -1 as HWND (2nd arg) only get PostThreadMessage() messages
1110 * and ignores window messages - should co-exist better with windows apps e.g. Tk
1111 */
1112 while (PeekMessage(&msg, (HWND)-1, 0, 0, PM_REMOVE|PM_NOYIELD)) {
1113 int sig;
1114 switch(msg.message) {
1115
1116#if 0
1117 /* Perhaps some other messages could map to signals ? ... */
1118 case WM_CLOSE:
1119 case WM_QUIT:
1120 /* Treat WM_QUIT like SIGHUP? */
1121 sig = SIGHUP;
1122 goto Raise;
1123 break;
1124#endif
2e332e71 1125
216db7ee 1126 /* We use WM_USER to fake kill() with other signals */
1127 case WM_USER: {
1128 sig = msg.wParam;
1129 Raise:
1130 if (do_raise(aTHX_ sig)) {
1131 sig_terminate(aTHX_ sig);
1132 }
1133 break;
1134 }
1135
1136 case WM_TIMER: {
1137 /* alarm() is a one-shot but SetTimer() repeats so kill it */
1138 if (w32_timerid) {
1139 KillTimer(NULL,w32_timerid);
1140 w32_timerid=0;
1141 }
1142 /* Now fake a call to signal handler */
1143 if (do_raise(aTHX_ 14)) {
1144 sig_terminate(aTHX_ 14);
1145 }
1146 break;
1147 }
1148
1149 /* Otherwise do normal Win32 thing - in case it is useful */
1150 default:
1151 TranslateMessage(&msg);
1152 DispatchMessage(&msg);
1153 ours = 0;
1154 break;
1155 }
1156 }
1157 w32_poll_count = 0;
1158
1159 /* Above or other stuff may have set a signal flag */
1160 if (PL_sig_pending) {
1161 despatch_signals();
1162 }
1163 return ours;
1164}
1165
1166/* This function will not return until the timeout has elapsed, or until
1167 * one of the handles is ready. */
1168DllExport DWORD
1169win32_msgwait(pTHX_ DWORD count, LPHANDLE handles, DWORD timeout, LPDWORD resultp)
1170{
1171 /* We may need several goes at this - so compute when we stop */
1172 DWORD ticks = 0;
1173 if (timeout != INFINITE) {
1174 ticks = GetTickCount();
1175 timeout += ticks;
1176 }
1177 while (1) {
1178 DWORD result = MsgWaitForMultipleObjects(count,handles,FALSE,timeout-ticks, QS_ALLEVENTS);
1179 if (resultp)
1180 *resultp = result;
1181 if (result == WAIT_TIMEOUT) {
1182 /* Ran out of time - explicit return of zero to avoid -ve if we
1183 have scheduling issues
1184 */
1185 return 0;
1186 }
1187 if (timeout != INFINITE) {
1188 ticks = GetTickCount();
1189 }
1190 if (result == WAIT_OBJECT_0 + count) {
1191 /* Message has arrived - check it */
1192 (void)win32_async_check(aTHX);
1193 }
1194 else {
1195 /* Not timeout or message - one of handles is ready */
1196 break;
1197 }
1198 }
1199 /* compute time left to wait */
1200 ticks = timeout - ticks;
1201 /* If we are past the end say zero */
1202 return (ticks > 0) ? ticks : 0;
1203}
1204
e1caacb4 1205static UINT timerid = 0;
1206
1207static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
1208{
acfe0abc 1209 dTHX;
e1caacb4 1210 KillTimer(NULL,timerid);
f4257e4d 1211 timerid=0;
e1caacb4 1212 sighandler(14);
1213}
e1caacb4 1214
1215DllExport unsigned int
814ffeea 1216win32_sleep(unsigned int t)
1217{
1218 return xcesleep(t);
1219}
1220
1221DllExport unsigned int
e1caacb4 1222win32_alarm(unsigned int sec)
1223{
f4257e4d 1224 /*
e1caacb4 1225 * the 'obvious' implentation is SetTimer() with a callback
f4257e4d 1226 * which does whatever receiving SIGALRM would do
1227 * we cannot use SIGALRM even via raise() as it is not
e1caacb4 1228 * one of the supported codes in <signal.h>
1229 *
1230 * Snag is unless something is looking at the message queue
1231 * nothing happens :-(
f4257e4d 1232 */
acfe0abc 1233 dTHX;
e1caacb4 1234 if (sec)
1235 {
1236 timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
1237 if (!timerid)
1238 Perl_croak_nocontext("Cannot set timer");
f4257e4d 1239 }
e1caacb4 1240 else
1241 {
1242 if (timerid)
1243 {
1244 KillTimer(NULL,timerid);
f4257e4d 1245 timerid=0;
e1caacb4 1246 }
1247 }
e1caacb4 1248 return 0;
1249}
1250
1251#ifdef HAVE_DES_FCRYPT
1252extern char * des_fcrypt(const char *txt, const char *salt, char *cbuf);
1253#endif
1254
1255DllExport char *
1256win32_crypt(const char *txt, const char *salt)
1257{
acfe0abc 1258 dTHX;
e1caacb4 1259#ifdef HAVE_DES_FCRYPT
1260 dTHR;
1261 return des_fcrypt(txt, salt, w32_crypt_buffer);
1262#else
1263 Perl_croak(aTHX_ "The crypt() function is unimplemented due to excessive paranoia.");
4e205ed6 1264 return NULL;
e1caacb4 1265#endif
1266}
1267
e1caacb4 1268
1269/*
1270 * redirected io subsystem for all XS modules
1271 *
1272 */
1273
1274DllExport int *
1275win32_errno(void)
1276{
1277 return (&errno);
1278}
1279
814ffeea 1280DllExport char ***
1281win32_environ(void)
1282{
1283 return (&(environ));
1284}
1285
e1caacb4 1286/* the rest are the remapped stdio routines */
1287DllExport FILE *
1288win32_stderr(void)
1289{
1290 return (stderr);
1291}
1292
216db7ee 1293char *g_getlogin() {
1294 return "no-getlogin";
1295}
1296
e1caacb4 1297DllExport FILE *
1298win32_stdin(void)
1299{
1300 return (stdin);
1301}
1302
1303DllExport FILE *
1304win32_stdout()
1305{
1306 return (stdout);
1307}
1308
1309DllExport int
1310win32_ferror(FILE *fp)
1311{
1312 return (ferror(fp));
1313}
1314
1315
1316DllExport int
1317win32_feof(FILE *fp)
1318{
1319 return (feof(fp));
1320}
1321
1322/*
f4257e4d 1323 * Since the errors returned by the socket error function
e1caacb4 1324 * WSAGetLastError() are not known by the library routine strerror
1325 * we have to roll our own.
1326 */
1327
1328DllExport char *
814ffeea 1329win32_strerror(int e)
e1caacb4 1330{
1331 return xcestrerror(e);
1332}
1333
1334DllExport void
1335win32_str_os_error(void *sv, DWORD dwErr)
1336{
acfe0abc 1337 dTHX;
e1caacb4 1338
1339 sv_setpvn((SV*)sv, "Error", 5);
1340}
1341
1342
1343DllExport int
1344win32_fprintf(FILE *fp, const char *format, ...)
1345{
1346 va_list marker;
1347 va_start(marker, format); /* Initialize variable arguments. */
1348
1349 return (vfprintf(fp, format, marker));
1350}
1351
1352DllExport int
1353win32_printf(const char *format, ...)
1354{
1355 va_list marker;
1356 va_start(marker, format); /* Initialize variable arguments. */
1357
1358 return (vprintf(format, marker));
1359}
1360
1361DllExport int
1362win32_vfprintf(FILE *fp, const char *format, va_list args)
1363{
1364 return (vfprintf(fp, format, args));
1365}
1366
1367DllExport int
1368win32_vprintf(const char *format, va_list args)
1369{
1370 return (vprintf(format, args));
1371}
1372
1373DllExport size_t
1374win32_fread(void *buf, size_t size, size_t count, FILE *fp)
1375{
1376 return fread(buf, size, count, fp);
1377}
1378
1379DllExport size_t
1380win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
1381{
1382 return fwrite(buf, size, count, fp);
1383}
1384
1385DllExport FILE *
1386win32_fopen(const char *filename, const char *mode)
1387{
1388 return xcefopen(filename, mode);
1389}
1390
1391DllExport FILE *
1392win32_fdopen(int handle, const char *mode)
1393{
1394 return palm_fdopen(handle, mode);
1395}
1396
1397DllExport FILE *
1398win32_freopen(const char *path, const char *mode, FILE *stream)
1399{
1400 return xcefreopen(path, mode, stream);
1401}
1402
1403DllExport int
1404win32_fclose(FILE *pf)
1405{
1406 return xcefclose(pf);
1407}
1408
1409DllExport int
1410win32_fputs(const char *s,FILE *pf)
1411{
1412 return fputs(s, pf);
1413}
1414
1415DllExport int
1416win32_fputc(int c,FILE *pf)
1417{
1418 return fputc(c,pf);
1419}
1420
1421DllExport int
1422win32_ungetc(int c,FILE *pf)
1423{
1424 return ungetc(c,pf);
1425}
1426
1427DllExport int
1428win32_getc(FILE *pf)
1429{
1430 return getc(pf);
1431}
1432
1433DllExport int
1434win32_fileno(FILE *pf)
1435{
1436 return palm_fileno(pf);
1437}
1438
1439DllExport void
1440win32_clearerr(FILE *pf)
1441{
1442 clearerr(pf);
1443 return;
1444}
1445
1446DllExport int
1447win32_fflush(FILE *pf)
1448{
1449 return fflush(pf);
1450}
1451
1452DllExport long
1453win32_ftell(FILE *pf)
1454{
1455 return ftell(pf);
1456}
1457
1458DllExport int
814ffeea 1459win32_fseek(FILE *pf, Off_t offset,int origin)
e1caacb4 1460{
1461 return fseek(pf, offset, origin);
1462}
1463
cb69f87a 1464/* fpos_t seems to be int64 on hpc pro! Really stupid. */
1465/* But maybe someday there will be such large disks in a hpc... */
e1caacb4 1466DllExport int
1467win32_fgetpos(FILE *pf, fpos_t *p)
1468{
1469 return fgetpos(pf, p);
1470}
1471
1472DllExport int
1473win32_fsetpos(FILE *pf, const fpos_t *p)
1474{
1475 return fsetpos(pf, p);
1476}
1477
1478DllExport void
1479win32_rewind(FILE *pf)
1480{
1481 fseek(pf, 0, SEEK_SET);
1482 return;
1483}
1484
81003058 1485DllExport int
1486win32_tmpfd(void)
1487{
1488 dTHX;
1489 char prefix[MAX_PATH+1];
1490 char filename[MAX_PATH+1];
1491 DWORD len = GetTempPath(MAX_PATH, prefix);
1492 if (len && len < MAX_PATH) {
1493 if (GetTempFileName(prefix, "plx", 0, filename)) {
1494 HANDLE fh = CreateFile(filename,
1495 DELETE | GENERIC_READ | GENERIC_WRITE,
1496 0,
1497 NULL,
1498 CREATE_ALWAYS,
1499 FILE_ATTRIBUTE_NORMAL
1500 | FILE_FLAG_DELETE_ON_CLOSE,
1501 NULL);
1502 if (fh != INVALID_HANDLE_VALUE) {
1503 int fd = win32_open_osfhandle((intptr_t)fh, 0);
1504 if (fd >= 0) {
1505#if defined(__BORLANDC__)
1506 setmode(fd,O_BINARY);
1507#endif
1508 DEBUG_p(PerlIO_printf(Perl_debug_log,
1509 "Created tmpfile=%s\n",filename));
1510 return fd;
1511 }
1512 }
1513 }
1514 }
1515 return -1;
1516}
1517
e1caacb4 1518DllExport FILE*
1519win32_tmpfile(void)
1520{
81003058 1521 int fd = win32_tmpfd();
1522 if (fd >= 0)
1523 return win32_fdopen(fd, "w+b");
1524 return NULL;
e1caacb4 1525}
1526
1527DllExport void
1528win32_abort(void)
1529{
1530 xceabort();
1531
1532 return;
1533}
1534
1535DllExport int
1536win32_fstat(int fd, struct stat *sbufptr)
1537{
1538 return xcefstat(fd, sbufptr);
1539}
1540
1541DllExport int
1542win32_link(const char *oldname, const char *newname)
1543{
216db7ee 1544 dTHX;
e1caacb4 1545 Perl_croak(aTHX_ PL_no_func, "link");
1546
1547 return -1;
1548}
1549
1550DllExport int
1551win32_rename(const char *oname, const char *newname)
1552{
1553 return xcerename(oname, newname);
1554}
1555
1556DllExport int
1557win32_setmode(int fd, int mode)
1558{
bcdf844e 1559 /* currently 'celib' seem to have this function in src, but not
1560 * exported. When it will be, we'll uncomment following line.
1561 */
1562 /* return xcesetmode(fd, mode); */
1563 return 0;
e1caacb4 1564}
1565
216db7ee 1566DllExport int
1567win32_chsize(int fd, Off_t size)
1568{
1569 return chsize(fd, size);
1570}
1571
e1caacb4 1572DllExport long
814ffeea 1573win32_lseek(int fd, Off_t offset, int origin)
e1caacb4 1574{
1575 return xcelseek(fd, offset, origin);
1576}
1577
1578DllExport long
1579win32_tell(int fd)
1580{
1581 return xcelseek(fd, 0, SEEK_CUR);
1582}
1583
1584DllExport int
1585win32_open(const char *path, int flag, ...)
1586{
1587 int pmode;
1588 va_list ap;
1589
1590 va_start(ap, flag);
1591 pmode = va_arg(ap, int);
1592 va_end(ap);
1593
1594 return xceopen(path, flag, pmode);
1595}
1596
1597DllExport int
1598win32_close(int fd)
1599{
1600 return xceclose(fd);
1601}
1602
1603DllExport int
1604win32_eof(int fd)
1605{
216db7ee 1606 dTHX;
e1caacb4 1607 Perl_croak(aTHX_ PL_no_func, "eof");
1608 return -1;
1609}
1610
1611DllExport int
1612win32_dup(int fd)
1613{
216db7ee 1614 return xcedup(fd); /* from celib/ceio.c; requires some more work on it */
e1caacb4 1615}
1616
1617DllExport int
1618win32_dup2(int fd1,int fd2)
1619{
aebd5ec7 1620 return xcedup2(fd1,fd2);
e1caacb4 1621}
1622
1623DllExport int
1624win32_read(int fd, void *buf, unsigned int cnt)
1625{
1626 return xceread(fd, buf, cnt);
1627}
1628
1629DllExport int
1630win32_write(int fd, const void *buf, unsigned int cnt)
1631{
1632 return xcewrite(fd, (void *) buf, cnt);
1633}
1634
1635DllExport int
1636win32_mkdir(const char *dir, int mode)
1637{
1638 return xcemkdir(dir);
1639}
1640
1641DllExport int
1642win32_rmdir(const char *dir)
1643{
1644 return xcermdir(dir);
1645}
1646
1647DllExport int
1648win32_chdir(const char *dir)
1649{
1650 return xcechdir(dir);
1651}
1652
1653DllExport int
1654win32_access(const char *path, int mode)
1655{
1656 return xceaccess(path, mode);
1657}
1658
1659DllExport int
1660win32_chmod(const char *path, int mode)
1661{
1662 return xcechmod(path, mode);
1663}
1664
814ffeea 1665static char *
1666create_command_line(char *cname, STRLEN clen, const char * const *args)
216db7ee 1667{
1668 dTHX;
1669 int index, argc;
1670 char *cmd, *ptr;
1671 const char *arg;
1672 STRLEN len = 0;
1673 bool bat_file = FALSE;
1674 bool cmd_shell = FALSE;
1675 bool dumb_shell = FALSE;
1676 bool extra_quotes = FALSE;
1677 bool quote_next = FALSE;
1678
1679 if (!cname)
1680 cname = (char*)args[0];
1681
1682 /* The NT cmd.exe shell has the following peculiarity that needs to be
1683 * worked around. It strips a leading and trailing dquote when any
1684 * of the following is true:
1685 * 1. the /S switch was used
1686 * 2. there are more than two dquotes
1687 * 3. there is a special character from this set: &<>()@^|
1688 * 4. no whitespace characters within the two dquotes
1689 * 5. string between two dquotes isn't an executable file
1690 * To work around this, we always add a leading and trailing dquote
1691 * to the string, if the first argument is either "cmd.exe" or "cmd",
1692 * and there were at least two or more arguments passed to cmd.exe
1693 * (not including switches).
1694 * XXX the above rules (from "cmd /?") don't seem to be applied
1695 * always, making for the convolutions below :-(
1696 */
1697 if (cname) {
1698 if (!clen)
1699 clen = strlen(cname);
1700
1701 if (clen > 4
1702 && (stricmp(&cname[clen-4], ".bat") == 0
1703 || (IsWinNT() && stricmp(&cname[clen-4], ".cmd") == 0)))
1704 {
1705 bat_file = TRUE;
1706 len += 3;
1707 }
1708 else {
1709 char *exe = strrchr(cname, '/');
1710 char *exe2 = strrchr(cname, '\\');
1711 if (exe2 > exe)
1712 exe = exe2;
1713 if (exe)
1714 ++exe;
1715 else
1716 exe = cname;
1717 if (stricmp(exe, "cmd.exe") == 0 || stricmp(exe, "cmd") == 0) {
1718 cmd_shell = TRUE;
1719 len += 3;
1720 }
1721 else if (stricmp(exe, "command.com") == 0
1722 || stricmp(exe, "command") == 0)
1723 {
1724 dumb_shell = TRUE;
1725 }
1726 }
1727 }
1728
1729 DEBUG_p(PerlIO_printf(Perl_debug_log, "Args "));
1730 for (index = 0; (arg = (char*)args[index]) != NULL; ++index) {
1731 STRLEN curlen = strlen(arg);
1732 if (!(arg[0] == '"' && arg[curlen-1] == '"'))
1733 len += 2; /* assume quoting needed (worst case) */
1734 len += curlen + 1;
1735 DEBUG_p(PerlIO_printf(Perl_debug_log, "[%s]",arg));
1736 }
1737 DEBUG_p(PerlIO_printf(Perl_debug_log, "\n"));
1738
1739 argc = index;
a02a5408 1740 Newx(cmd, len, char);
216db7ee 1741 ptr = cmd;
1742
1743 if (bat_file) {
1744 *ptr++ = '"';
1745 extra_quotes = TRUE;
1746 }
1747
1748 for (index = 0; (arg = (char*)args[index]) != NULL; ++index) {
1749 bool do_quote = 0;
1750 STRLEN curlen = strlen(arg);
1751
1752 /* we want to protect empty arguments and ones with spaces with
1753 * dquotes, but only if they aren't already there */
1754 if (!dumb_shell) {
1755 if (!curlen) {
1756 do_quote = 1;
1757 }
1758 else if (quote_next) {
1759 /* see if it really is multiple arguments pretending to
1760 * be one and force a set of quotes around it */
1761 if (*find_next_space(arg))
1762 do_quote = 1;
1763 }
1764 else if (!(arg[0] == '"' && curlen > 1 && arg[curlen-1] == '"')) {
1765 STRLEN i = 0;
1766 while (i < curlen) {
1767 if (isSPACE(arg[i])) {
1768 do_quote = 1;
1769 }
1770 else if (arg[i] == '"') {
1771 do_quote = 0;
1772 break;
1773 }
1774 i++;
1775 }
1776 }
1777 }
1778
1779 if (do_quote)
1780 *ptr++ = '"';
1781
1782 strcpy(ptr, arg);
1783 ptr += curlen;
1784
1785 if (do_quote)
1786 *ptr++ = '"';
1787
1788 if (args[index+1])
1789 *ptr++ = ' ';
1790
1791 if (!extra_quotes
1792 && cmd_shell
1793 && curlen >= 2
1794 && *arg == '/' /* see if arg is "/c", "/x/c", "/x/d/c" etc. */
1795 && stricmp(arg+curlen-2, "/c") == 0)
1796 {
1797 /* is there a next argument? */
1798 if (args[index+1]) {
1799 /* are there two or more next arguments? */
1800 if (args[index+2]) {
1801 *ptr++ = '"';
1802 extra_quotes = TRUE;
1803 }
1804 else {
1805 /* single argument, force quoting if it has spaces */
1806 quote_next = TRUE;
1807 }
1808 }
1809 }
1810 }
1811
1812 if (extra_quotes)
1813 *ptr++ = '"';
1814
1815 *ptr = '\0';
1816
1817 return cmd;
1818}
1819
1820static char *
1821qualified_path(const char *cmd)
1822{
1823 dTHX;
1824 char *pathstr;
1825 char *fullcmd, *curfullcmd;
1826 STRLEN cmdlen = 0;
1827 int has_slash = 0;
1828
1829 if (!cmd)
4e205ed6 1830 return NULL;
216db7ee 1831 fullcmd = (char*)cmd;
1832 while (*fullcmd) {
1833 if (*fullcmd == '/' || *fullcmd == '\\')
1834 has_slash++;
1835 fullcmd++;
1836 cmdlen++;
1837 }
1838
1839 /* look in PATH */
1840 pathstr = PerlEnv_getenv("PATH");
a02a5408 1841 Newx(fullcmd, MAX_PATH+1, char);
216db7ee 1842 curfullcmd = fullcmd;
1843
1844 while (1) {
1845 DWORD res;
1846
1847 /* start by appending the name to the current prefix */
1848 strcpy(curfullcmd, cmd);
1849 curfullcmd += cmdlen;
1850
1851 /* if it doesn't end with '.', or has no extension, try adding
1852 * a trailing .exe first */
1853 if (cmd[cmdlen-1] != '.'
1854 && (cmdlen < 4 || cmd[cmdlen-4] != '.'))
1855 {
1856 strcpy(curfullcmd, ".exe");
1857 res = GetFileAttributes(fullcmd);
1858 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
1859 return fullcmd;
1860 *curfullcmd = '\0';
1861 }
1862
1863 /* that failed, try the bare name */
1864 res = GetFileAttributes(fullcmd);
1865 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
1866 return fullcmd;
1867
1868 /* quit if no other path exists, or if cmd already has path */
1869 if (!pathstr || !*pathstr || has_slash)
1870 break;
1871
1872 /* skip leading semis */
1873 while (*pathstr == ';')
1874 pathstr++;
1875
1876 /* build a new prefix from scratch */
1877 curfullcmd = fullcmd;
1878 while (*pathstr && *pathstr != ';') {
1879 if (*pathstr == '"') { /* foo;"baz;etc";bar */
1880 pathstr++; /* skip initial '"' */
1881 while (*pathstr && *pathstr != '"') {
1882 if ((STRLEN)(curfullcmd-fullcmd) < MAX_PATH-cmdlen-5)
1883 *curfullcmd++ = *pathstr;
1884 pathstr++;
1885 }
1886 if (*pathstr)
1887 pathstr++; /* skip trailing '"' */
1888 }
1889 else {
1890 if ((STRLEN)(curfullcmd-fullcmd) < MAX_PATH-cmdlen-5)
1891 *curfullcmd++ = *pathstr;
1892 pathstr++;
1893 }
1894 }
1895 if (*pathstr)
1896 pathstr++; /* skip trailing semi */
1897 if (curfullcmd > fullcmd /* append a dir separator */
1898 && curfullcmd[-1] != '/' && curfullcmd[-1] != '\\')
1899 {
1900 *curfullcmd++ = '\\';
1901 }
1902 }
1903
1904 Safefree(fullcmd);
4e205ed6 1905 return NULL;
216db7ee 1906}
1907
8f33b42a 1908/* The following are just place holders.
1909 * Some hosts may provide and environment that the OS is
1910 * not tracking, therefore, these host must provide that
1911 * environment and the current directory to CreateProcess
1912 */
1913
1914DllExport void*
1915win32_get_childenv(void)
1916{
1917 return NULL;
1918}
1919
1920DllExport void
1921win32_free_childenv(void* d)
1922{
1923}
1924
1925DllExport void
1926win32_clearenv(void)
1927{
1928 char *envv = GetEnvironmentStrings();
1929 char *cur = envv;
1930 STRLEN len;
1931 while (*cur) {
1932 char *end = strchr(cur,'=');
1933 if (end && end != cur) {
1934 *end = '\0';
1935 xcesetenv(cur, "", 0);
1936 *end = '=';
1937 cur = end + strlen(end+1)+2;
1938 }
1939 else if ((len = strlen(cur)))
1940 cur += len+1;
1941 }
1942 FreeEnvironmentStrings(envv);
1943}
1944
1945DllExport char*
1946win32_get_childdir(void)
1947{
1948 dTHX;
1949 char* ptr;
8c56068e 1950 char szfilename[MAX_PATH+1];
1951 GetCurrentDirectoryA(MAX_PATH+1, szfilename);
8f33b42a 1952
a02a5408 1953 Newx(ptr, strlen(szfilename)+1, char);
8f33b42a 1954 strcpy(ptr, szfilename);
1955 return ptr;
1956}
1957
1958DllExport void
1959win32_free_childdir(char* d)
1960{
1961 dTHX;
1962 Safefree(d);
1963}
1964
216db7ee 1965/* XXX this needs to be made more compatible with the spawnvp()
1966 * provided by the various RTLs. In particular, searching for
1967 * *.{com,bat,cmd} files (as done by the RTLs) is unimplemented.
1968 * This doesn't significantly affect perl itself, because we
1969 * always invoke things using PERL5SHELL if a direct attempt to
1970 * spawn the executable fails.
1971 *
1972 * XXX splitting and rejoining the commandline between do_aspawn()
1973 * and win32_spawnvp() could also be avoided.
1974 */
1975
216db7ee 1976DllExport int
1977win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
1978{
1979#ifdef USE_RTL_SPAWNVP
1980 return spawnvp(mode, cmdname, (char * const *)argv);
1981#else
1982 dTHX;
1983 int ret;
1984 void* env;
1985 char* dir;
1986 child_IO_table tbl;
1987 STARTUPINFO StartupInfo;
1988 PROCESS_INFORMATION ProcessInformation;
1989 DWORD create = 0;
1990 char *cmd;
4e205ed6 1991 char *fullcmd = NULL;
216db7ee 1992 char *cname = (char *)cmdname;
1993 STRLEN clen = 0;
1994
1995 if (cname) {
1996 clen = strlen(cname);
1997 /* if command name contains dquotes, must remove them */
1998 if (strchr(cname, '"')) {
1999 cmd = cname;
a02a5408 2000 Newx(cname,clen+1,char);
216db7ee 2001 clen = 0;
2002 while (*cmd) {
2003 if (*cmd != '"') {
2004 cname[clen] = *cmd;
2005 ++clen;
2006 }
2007 ++cmd;
2008 }
2009 cname[clen] = '\0';
2010 }
2011 }
2012
2013 cmd = create_command_line(cname, clen, argv);
2014
2015 env = PerlEnv_get_childenv();
2016 dir = PerlEnv_get_childdir();
2017
2018 switch(mode) {
2019 case P_NOWAIT: /* asynch + remember result */
2020 if (w32_num_children >= MAXIMUM_WAIT_OBJECTS) {
2021 errno = EAGAIN;
2022 ret = -1;
2023 goto RETVAL;
2024 }
2025 /* Create a new process group so we can use GenerateConsoleCtrlEvent()
2026 * in win32_kill()
2027 */
2028 /* not supported on CE create |= CREATE_NEW_PROCESS_GROUP; */
2029 /* FALL THROUGH */
2030
2031 case P_WAIT: /* synchronous execution */
2032 break;
2033 default: /* invalid mode */
2034 errno = EINVAL;
2035 ret = -1;
2036 goto RETVAL;
2037 }
2038 memset(&StartupInfo,0,sizeof(StartupInfo));
2039 StartupInfo.cb = sizeof(StartupInfo);
2040 memset(&tbl,0,sizeof(tbl));
2041 PerlEnv_get_child_IO(&tbl);
2042 StartupInfo.dwFlags = tbl.dwFlags;
2043 StartupInfo.dwX = tbl.dwX;
2044 StartupInfo.dwY = tbl.dwY;
2045 StartupInfo.dwXSize = tbl.dwXSize;
2046 StartupInfo.dwYSize = tbl.dwYSize;
2047 StartupInfo.dwXCountChars = tbl.dwXCountChars;
2048 StartupInfo.dwYCountChars = tbl.dwYCountChars;
2049 StartupInfo.dwFillAttribute = tbl.dwFillAttribute;
2050 StartupInfo.wShowWindow = tbl.wShowWindow;
2051 StartupInfo.hStdInput = tbl.childStdIn;
2052 StartupInfo.hStdOutput = tbl.childStdOut;
2053 StartupInfo.hStdError = tbl.childStdErr;
2054 if (StartupInfo.hStdInput == INVALID_HANDLE_VALUE &&
2055 StartupInfo.hStdOutput == INVALID_HANDLE_VALUE &&
2056 StartupInfo.hStdError == INVALID_HANDLE_VALUE)
2057 {
2058 create |= CREATE_NEW_CONSOLE;
2059 }
2060 else {
2061 StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
2062 }
2063 if (w32_use_showwindow) {
2064 StartupInfo.dwFlags |= STARTF_USESHOWWINDOW;
2065 StartupInfo.wShowWindow = w32_showwindow;
2066 }
2067
2068 DEBUG_p(PerlIO_printf(Perl_debug_log, "Spawning [%s] with [%s]\n",
2069 cname,cmd));
2070RETRY:
2071 if (!CreateProcess(cname, /* search PATH to find executable */
2072 cmd, /* executable, and its arguments */
2073 NULL, /* process attributes */
2074 NULL, /* thread attributes */
2075 TRUE, /* inherit handles */
2076 create, /* creation flags */
2077 (LPVOID)env, /* inherit environment */
2078 dir, /* inherit cwd */
2079 &StartupInfo,
2080 &ProcessInformation))
2081 {
2082 /* initial NULL argument to CreateProcess() does a PATH
2083 * search, but it always first looks in the directory
2084 * where the current process was started, which behavior
2085 * is undesirable for backward compatibility. So we
2086 * jump through our own hoops by picking out the path
2087 * we really want it to use. */
2088 if (!fullcmd) {
2089 fullcmd = qualified_path(cname);
2090 if (fullcmd) {
2091 if (cname != cmdname)
2092 Safefree(cname);
2093 cname = fullcmd;
2094 DEBUG_p(PerlIO_printf(Perl_debug_log,
2095 "Retrying [%s] with same args\n",
2096 cname));
2097 goto RETRY;
2098 }
2099 }
2100 errno = ENOENT;
2101 ret = -1;
2102 goto RETVAL;
2103 }
2104
2105 if (mode == P_NOWAIT) {
2106 /* asynchronous spawn -- store handle, return PID */
2107 ret = (int)ProcessInformation.dwProcessId;
2108 if (IsWin95() && ret < 0)
2109 ret = -ret;
2110
2111 w32_child_handles[w32_num_children] = ProcessInformation.hProcess;
2112 w32_child_pids[w32_num_children] = (DWORD)ret;
2113 ++w32_num_children;
2114 }
2115 else {
2116 DWORD status;
2117 win32_msgwait(aTHX_ 1, &ProcessInformation.hProcess, INFINITE, NULL);
2118 /* FIXME: if msgwait returned due to message perhaps forward the
2119 "signal" to the process
2120 */
2121 GetExitCodeProcess(ProcessInformation.hProcess, &status);
2122 ret = (int)status;
2123 CloseHandle(ProcessInformation.hProcess);
2124 }
2125
2126 CloseHandle(ProcessInformation.hThread);
2127
2128RETVAL:
2129 PerlEnv_free_childenv(env);
2130 PerlEnv_free_childdir(dir);
2131 Safefree(cmd);
2132 if (cname != cmdname)
2133 Safefree(cname);
2134 return ret;
2135#endif
2136}
2137
e1caacb4 2138DllExport int
2139win32_execv(const char *cmdname, const char *const *argv)
2140{
216db7ee 2141 dTHX;
e1caacb4 2142 Perl_croak(aTHX_ PL_no_func, "execv");
2143 return -1;
2144}
2145
2146DllExport int
2147win32_execvp(const char *cmdname, const char *const *argv)
2148{
216db7ee 2149 dTHX;
e1caacb4 2150 Perl_croak(aTHX_ PL_no_func, "execvp");
2151 return -1;
2152}
2153
814ffeea 2154DllExport void
2155win32_perror(const char *str)
e1caacb4 2156{
814ffeea 2157 xceperror(str);
2158}
e1caacb4 2159
814ffeea 2160DllExport void
2161win32_setbuf(FILE *pf, char *buf)
2162{
2163 dTHX;
2164 Perl_croak(aTHX_ PL_no_func, "setbuf");
2165}
e1caacb4 2166
814ffeea 2167DllExport int
2168win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
2169{
2170 return setvbuf(pf, buf, type, size);
e1caacb4 2171}
2172
814ffeea 2173DllExport int
2174win32_flushall(void)
2175{
2176 return flushall();
2177}
e1caacb4 2178
814ffeea 2179DllExport int
2180win32_fcloseall(void)
e1caacb4 2181{
814ffeea 2182 return fcloseall();
2183}
e1caacb4 2184
814ffeea 2185DllExport char*
2186win32_fgets(char *s, int n, FILE *pf)
2187{
2188 return fgets(s, n, pf);
2189}
e1caacb4 2190
814ffeea 2191DllExport char*
2192win32_gets(char *s)
2193{
2194 return gets(s);
e1caacb4 2195}
2196
814ffeea 2197DllExport int
2198win32_fgetc(FILE *pf)
e1caacb4 2199{
814ffeea 2200 return fgetc(pf);
2201}
e1caacb4 2202
814ffeea 2203DllExport int
2204win32_putc(int c, FILE *pf)
2205{
2206 return putc(c,pf);
2207}
2208
2209DllExport int
2210win32_puts(const char *s)
2211{
2212 return puts(s);
2213}
2214
2215DllExport int
2216win32_getchar(void)
2217{
2218 return getchar();
2219}
2220
2221DllExport int
2222win32_putchar(int c)
2223{
2224 return putchar(c);
2225}
2226
2227#ifdef MYMALLOC
2228
2229#ifndef USE_PERL_SBRK
2230
2231static char *committed = NULL;
2232static char *base = NULL;
2233static char *reserved = NULL;
2234static char *brk = NULL;
2235static DWORD pagesize = 0;
2236static DWORD allocsize = 0;
2237
2238void *
2239sbrk(int need)
2240{
2241 void *result;
2242 if (!pagesize)
2243 {SYSTEM_INFO info;
2244 GetSystemInfo(&info);
2245 /* Pretend page size is larger so we don't perpetually
2246 * call the OS to commit just one page ...
2247 */
2248 pagesize = info.dwPageSize << 3;
2249 allocsize = info.dwAllocationGranularity;
2250 }
2251 /* This scheme fails eventually if request for contiguous
f4257e4d 2252 * block is denied so reserve big blocks - this is only
814ffeea 2253 * address space not memory ...
2254 */
2255 if (brk+need >= reserved)
2256 {
2257 DWORD size = 64*1024*1024;
2258 char *addr;
2259 if (committed && reserved && committed < reserved)
2260 {
2261 /* Commit last of previous chunk cannot span allocations */
2262 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
2263 if (addr)
2264 committed = reserved;
2265 }
f4257e4d 2266 /* Reserve some (more) space
814ffeea 2267 * Note this is a little sneaky, 1st call passes NULL as reserved
2268 * so lets system choose where we start, subsequent calls pass
2269 * the old end address so ask for a contiguous block
2270 */
2271 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
2272 if (addr)
2273 {
2274 reserved = addr+size;
2275 if (!base)
2276 base = addr;
2277 if (!committed)
2278 committed = base;
2279 if (!brk)
2280 brk = committed;
2281 }
2282 else
2283 {
2284 return (void *) -1;
2285 }
2286 }
2287 result = brk;
2288 brk += need;
2289 if (brk > committed)
2290 {
2291 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
2292 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
2293 if (addr)
2294 {
2295 committed += size;
2296 }
2297 else
2298 return (void *) -1;
2299 }
2300 return result;
2301}
2302
2303#endif
2304#endif
2305
2306DllExport void*
2307win32_malloc(size_t size)
2308{
2309 return malloc(size);
2310}
2311
2312DllExport void*
2313win32_calloc(size_t numitems, size_t size)
2314{
2315 return calloc(numitems,size);
2316}
2317
2318DllExport void*
2319win32_realloc(void *block, size_t size)
2320{
2321 return realloc(block,size);
2322}
2323
2324DllExport void
2325win32_free(void *block)
2326{
2327 free(block);
2328}
2329
2330int
2331win32_open_osfhandle(intptr_t osfhandle, int flags)
2332{
2333 int fh;
2334 char fileflags=0; /* _osfile flags */
2335
2336 Perl_croak_nocontext("win32_open_osfhandle() TBD on this platform");
2337 return 0;
2338}
2339
2340int
2341win32_get_osfhandle(int fd)
2342{
2343 int fh;
2344 char fileflags=0; /* _osfile flags */
2345
2346 Perl_croak_nocontext("win32_get_osfhandle() TBD on this platform");
2347 return 0;
2348}
2349
2350FILE *
2351win32_fdupopen(FILE *pf)
2352{
2353 FILE* pfdup;
2354 fpos_t pos;
2355 char mode[3];
2356 int fileno = win32_dup(win32_fileno(pf));
2357 int fmode = palm_fgetmode(pfdup);
2358
2359 fprintf(stderr,"DEBUG for win32_fdupopen()\n");
2360
2361 /* open the file in the same mode */
2362 if(fmode & O_RDONLY) {
2363 mode[0] = 'r';
2364 mode[1] = 0;
2365 }
2366 else if(fmode & O_APPEND) {
2367 mode[0] = 'a';
2368 mode[1] = 0;
2369 }
2370 else if(fmode & O_RDWR) {
2371 mode[0] = 'r';
2372 mode[1] = '+';
2373 mode[2] = 0;
2374 }
2375
2376 /* it appears that the binmode is attached to the
2377 * file descriptor so binmode files will be handled
2378 * correctly
2379 */
2380 pfdup = win32_fdopen(fileno, mode);
2381
2382 /* move the file pointer to the same position */
2383 if (!fgetpos(pf, &pos)) {
2384 fsetpos(pfdup, &pos);
2385 }
2386 return pfdup;
2387}
2388
2389DllExport void*
2390win32_dynaload(const char* filename)
2391{
2392 dTHX;
2393 HMODULE hModule;
2394
2395 hModule = XCELoadLibraryA(filename);
2396
2397 return hModule;
2398}
2399
2400/* this is needed by Cwd.pm... */
2401
2402static
2403XS(w32_GetCwd)
2404{
2405 dXSARGS;
2406 char buf[MAX_PATH];
2407 SV *sv = sv_newmortal();
2408
2409 xcegetcwd(buf, sizeof(buf));
2410
2411 sv_setpv(sv, xcestrdup(buf));
2412 EXTEND(SP,1);
2413 SvPOK_on(sv);
2414 ST(0) = sv;
2415#ifndef INCOMPLETE_TAINTS
2416 SvTAINTED_on(ST(0));
2417#endif
2418 XSRETURN(1);
2419}
2420
2421static
2422XS(w32_SetCwd)
2423{
2424 dXSARGS;
2425
2426 if (items != 1)
e1caacb4 2427 Perl_croak(aTHX_ "usage: Win32::SetCwd($cwd)");
2428
2429 if (!xcechdir(SvPV_nolen(ST(0))))
2430 XSRETURN_YES;
2431
2432 XSRETURN_NO;
2433}
2434
2435static
2436XS(w32_GetTickCount)
2437{
2438 dXSARGS;
2439 DWORD msec = GetTickCount();
2440 EXTEND(SP,1);
2441 if ((IV)msec > 0)
2442 XSRETURN_IV(msec);
2443 XSRETURN_NV(msec);
2444}
2445
2446static
2447XS(w32_GetOSVersion)
2448{
2449 dXSARGS;
2450 OSVERSIONINFOA osver;
2451
2452 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOA);
2453 if (!XCEGetVersionExA(&osver)) {
2454 XSRETURN_EMPTY;
2455 }
22f1178f 2456 mXPUSHp(osver.szCSDVersion, strlen(osver.szCSDVersion));
2457 mXPUSHi(osver.dwMajorVersion);
2458 mXPUSHi(osver.dwMinorVersion);
2459 mXPUSHi(osver.dwBuildNumber);
cb69f87a 2460 /* WINCE = 3 */
22f1178f 2461 mXPUSHi(osver.dwPlatformId);
e1caacb4 2462 PUTBACK;
2463}
2464
2465static
2466XS(w32_IsWinNT)
2467{
2468 dXSARGS;
2469 EXTEND(SP,1);
2470 XSRETURN_IV(IsWinNT());
2471}
2472
2473static
2474XS(w32_IsWin95)
2475{
2476 dXSARGS;
2477 EXTEND(SP,1);
2478 XSRETURN_IV(IsWin95());
2479}
2480
2481static
2482XS(w32_IsWinCE)
2483{
2484 dXSARGS;
2485 EXTEND(SP,1);
2486 XSRETURN_IV(IsWinCE());
2487}
2488
2489static
2490XS(w32_GetOemInfo)
2491{
2492 dXSARGS;
2493 wchar_t wbuf[126];
2494 char buf[126];
2495
2496 if(SystemParametersInfoW(SPI_GETOEMINFO, sizeof(wbuf), wbuf, FALSE))
2497 WideCharToMultiByte(CP_ACP, 0, wbuf, -1, buf, sizeof(buf), 0, 0);
2498 else
2499 sprintf(buf, "SystemParametersInfo failed: %d", GetLastError());
2500
2501 EXTEND(SP,1);
2502 XSRETURN_PV(buf);
2503}
2504
2505static
2506XS(w32_Sleep)
2507{
2508 dXSARGS;
2509 if (items != 1)
2510 Perl_croak(aTHX_ "usage: Win32::Sleep($milliseconds)");
2511 Sleep(SvIV(ST(0)));
2512 XSRETURN_YES;
2513}
2514
2515static
2516XS(w32_CopyFile)
2517{
2518 dXSARGS;
2519 BOOL bResult;
2520 if (items != 3)
2521 Perl_croak(aTHX_ "usage: Win32::CopyFile($from, $to, $overwrite)");
2522
2523 {
2524 char szSourceFile[MAX_PATH+1];
2525 strcpy(szSourceFile, PerlDir_mapA(SvPV_nolen(ST(0))));
f4257e4d 2526 bResult = XCECopyFileA(szSourceFile, SvPV_nolen(ST(1)),
e1caacb4 2527 !SvTRUE(ST(2)));
2528 }
2529
2530 if (bResult)
2531 XSRETURN_YES;
2532
2533 XSRETURN_NO;
2534}
2535
2536static
2537XS(w32_MessageBox)
2538{
2539 dXSARGS;
2540
2541 char *txt;
2542 unsigned int res;
2543 unsigned int flags = MB_OK;
2544
2545 txt = SvPV_nolen(ST(0));
f4257e4d 2546
e1caacb4 2547 if (items < 1 || items > 2)
2548 Perl_croak(aTHX_ "usage: Win32::MessageBox($txt, [$flags])");
2549
2550 if(items == 2)
2551 flags = SvIV(ST(1));
2552
2553 res = XCEMessageBoxA(NULL, txt, "Perl", flags);
2554
2555 XSRETURN_IV(res);
2556}
2557
2558static
2559XS(w32_GetPowerStatus)
2560{
2561 dXSARGS;
2562
2563 SYSTEM_POWER_STATUS_EX sps;
2564
2565 if(GetSystemPowerStatusEx(&sps, TRUE) == FALSE)
2566 {
2567 XSRETURN_EMPTY;
2568 }
2569
22f1178f 2570 mXPUSHi(sps.ACLineStatus);
2571 mXPUSHi(sps.BatteryFlag);
2572 mXPUSHi(sps.BatteryLifePercent);
2573 mXPUSHi(sps.BatteryLifeTime);
2574 mXPUSHi(sps.BatteryFullLifeTime);
2575 mXPUSHi(sps.BackupBatteryFlag);
2576 mXPUSHi(sps.BackupBatteryLifePercent);
2577 mXPUSHi(sps.BackupBatteryLifeTime);
2578 mXPUSHi(sps.BackupBatteryFullLifeTime);
e1caacb4 2579
2580 PUTBACK;
2581}
2582
2583#if UNDER_CE > 200
2584static
2585XS(w32_ShellEx)
2586{
2587 dXSARGS;
2588
2589 char buf[126];
2590 SHELLEXECUTEINFO si;
2591 char *file, *verb;
2592 wchar_t wfile[MAX_PATH];
2593 wchar_t wverb[20];
2594
2595 if (items != 2)
2596 Perl_croak(aTHX_ "usage: Win32::ShellEx($file, $verb)");
2597
2598 file = SvPV_nolen(ST(0));
2599 verb = SvPV_nolen(ST(1));
2600
2601 memset(&si, 0, sizeof(si));
2602 si.cbSize = sizeof(si);
2603 si.fMask = SEE_MASK_FLAG_NO_UI;
2604
f4257e4d 2605 MultiByteToWideChar(CP_ACP, 0, verb, -1,
e1caacb4 2606 wverb, sizeof(wverb)/2);
2607 si.lpVerb = (TCHAR *)wverb;
2608
f4257e4d 2609 MultiByteToWideChar(CP_ACP, 0, file, -1,
e1caacb4 2610 wfile, sizeof(wfile)/2);
2611 si.lpFile = (TCHAR *)wfile;
2612
2613 if(ShellExecuteEx(&si) == FALSE)
2614 {
2615 XSRETURN_NO;
2616 }
2617 XSRETURN_YES;
2618}
2619#endif
2620
2621void
2622Perl_init_os_extras(void)
2623{
acfe0abc 2624 dTHX;
e1caacb4 2625 char *file = __FILE__;
2626 dXSUB_SYS;
2627
4e205ed6 2628 w32_perlshell_tokens = NULL;
e1caacb4 2629 w32_perlshell_items = -1;
2630 w32_fdpid = newAV(); /* XX needs to be in Perl_win32_init()? */
a02a5408 2631 Newx(w32_children, 1, child_tab);
e1caacb4 2632 w32_num_children = 0;
2633
2634 newXS("Win32::GetCwd", w32_GetCwd, file);
2635 newXS("Win32::SetCwd", w32_SetCwd, file);
2636 newXS("Win32::GetTickCount", w32_GetTickCount, file);
2637 newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
2638#if UNDER_CE > 200
2639 newXS("Win32::ShellEx", w32_ShellEx, file);
2640#endif
2641 newXS("Win32::IsWinNT", w32_IsWinNT, file);
2642 newXS("Win32::IsWin95", w32_IsWin95, file);
2643 newXS("Win32::IsWinCE", w32_IsWinCE, file);
2644 newXS("Win32::CopyFile", w32_CopyFile, file);
2645 newXS("Win32::Sleep", w32_Sleep, file);
2646 newXS("Win32::MessageBox", w32_MessageBox, file);
2647 newXS("Win32::GetPowerStatus", w32_GetPowerStatus, file);
2648 newXS("Win32::GetOemInfo", w32_GetOemInfo, file);
2649}
2650
2651void
2652myexit(void)
2653{
2654 char buf[126];
2655
2656 puts("Hit return");
2657 fgets(buf, sizeof(buf), stdin);
2658}
2659
2660void
2661Perl_win32_init(int *argcp, char ***argvp)
2662{
2663#ifdef UNDER_CE
2664 char *p;
2665
2666 if((p = xcegetenv("PERLDEBUG")) && (p[0] == 'y' || p[0] == 'Y'))
2667 atexit(myexit);
2668#endif
2669
2670 MALLOC_INIT;
2671}
2672
216db7ee 2673DllExport void
2674Perl_win32_term(void)
2675{
3890ecea 2676 dTHX;
71ad1b0c 2677 HINTS_REFCNT_TERM;
216db7ee 2678 OP_REFCNT_TERM;
3890ecea 2679 PERLIO_TERM;
216db7ee 2680 MALLOC_TERM;
2681}
2682
2683void
2684win32_get_child_IO(child_IO_table* ptbl)
2685{
2686 ptbl->childStdIn = GetStdHandle(STD_INPUT_HANDLE);
2687 ptbl->childStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
2688 ptbl->childStdErr = GetStdHandle(STD_ERROR_HANDLE);
2689}
2690
e1caacb4 2691win32_flock(int fd, int oper)
2692{
216db7ee 2693 dTHX;
e1caacb4 2694 Perl_croak(aTHX_ PL_no_func, "flock");
2695 return -1;
2696}
2697
2698DllExport int
2699win32_waitpid(int pid, int *status, int flags)
2700{
216db7ee 2701 dTHX;
e1caacb4 2702 Perl_croak(aTHX_ PL_no_func, "waitpid");
2703 return -1;
2704}
2705
2706DllExport int
2707win32_wait(int *status)
2708{
216db7ee 2709 dTHX;
e1caacb4 2710 Perl_croak(aTHX_ PL_no_func, "wait");
2711 return -1;
2712}
2713
2714int
e1caacb4 2715wce_reopen_stdout(char *fname)
f4257e4d 2716{
e1caacb4 2717 if(xcefreopen(fname, "w", stdout) == NULL)
2718 return -1;
2719
2720 return 0;
2721}
2722
2723void
2724wce_hitreturn()
2725{
2726 char buf[126];
2727
2728 printf("Hit RETURN");
2729 fflush(stdout);
2730 fgets(buf, sizeof(buf), stdin);
2731 return;
2732}
2733
cb69f87a 2734/* //////////////////////////////////////////////////////////////////// */
e1caacb4 2735
ca6c63e1 2736#undef getcwd
2737
2738char *
2739getcwd(char *buf, size_t size)
2740{
2741 return xcegetcwd(buf, size);
2742}
2743
f4257e4d 2744int
ca6c63e1 2745isnan(double d)
2746{
2747 return _isnan(d);
2748}
2749
18f68570 2750
814ffeea 2751DllExport PerlIO*
2752win32_popenlist(const char *mode, IV narg, SV **args)
18f68570 2753{
814ffeea 2754 dTHX;
2755 Perl_croak(aTHX_ "List form of pipe open not implemented");
2756 return NULL;
18f68570 2757}
2758
2759/*
2760 * a popen() clone that respects PERL5SHELL
2761 *
2762 * changed to return PerlIO* rather than FILE * by BKS, 11-11-2000
2763 */
2764
2765DllExport PerlIO*
2766win32_popen(const char *command, const char *mode)
2767{
814ffeea 2768 return _popen(command, mode);
216db7ee 2769}
2770
18f68570 2771/*
2772 * pclose() clone
2773 */
2774
2775DllExport int
2776win32_pclose(PerlIO *pf)
2777{
18f68570 2778 return _pclose(pf);
18f68570 2779}
2780
216db7ee 2781#ifdef HAVE_INTERP_INTERN
2782
2783
2784static void
2785win32_csighandler(int sig)
2786{
2787#if 0
2788 dTHXa(PERL_GET_SIG_CONTEXT);
2789 Perl_warn(aTHX_ "Got signal %d",sig);
2790#endif
2791 /* Does nothing */
2792}
2793
2794void
2795Perl_sys_intern_init(pTHX)
2796{
2797 int i;
4e205ed6 2798 w32_perlshell_tokens = NULL;
216db7ee 2799 w32_perlshell_vec = (char**)NULL;
2800 w32_perlshell_items = 0;
2801 w32_fdpid = newAV();
a02a5408 2802 Newx(w32_children, 1, child_tab);
216db7ee 2803 w32_num_children = 0;
2804# ifdef USE_ITHREADS
2805 w32_pseudo_id = 0;
a02a5408 2806 Newx(w32_pseudo_children, 1, child_tab);
216db7ee 2807 w32_num_pseudo_children = 0;
2808# endif
2809 w32_init_socktype = 0;
2810 w32_timerid = 0;
2811 w32_poll_count = 0;
2812}
2813
2814void
2815Perl_sys_intern_clear(pTHX)
2816{
2817 Safefree(w32_perlshell_tokens);
2818 Safefree(w32_perlshell_vec);
2819 /* NOTE: w32_fdpid is freed by sv_clean_all() */
2820 Safefree(w32_children);
2821 if (w32_timerid) {
2822 KillTimer(NULL,w32_timerid);
2823 w32_timerid=0;
2824 }
2825# ifdef USE_ITHREADS
2826 Safefree(w32_pseudo_children);
2827# endif
2828}
2829
2830# ifdef USE_ITHREADS
2831
2832void
2833Perl_sys_intern_dup(pTHX_ struct interp_intern *src, struct interp_intern *dst)
2834{
4e205ed6 2835 dst->perlshell_tokens = NULL;
216db7ee 2836 dst->perlshell_vec = (char**)NULL;
2837 dst->perlshell_items = 0;
2838 dst->fdpid = newAV();
a02a5408 2839 Newxz(dst->children, 1, child_tab);
216db7ee 2840 dst->pseudo_id = 0;
a02a5408 2841 Newxz(dst->pseudo_children, 1, child_tab);
216db7ee 2842 dst->thr_intern.Winit_socktype = 0;
2843 dst->timerid = 0;
2844 dst->poll_count = 0;
2845 Copy(src->sigtable,dst->sigtable,SIG_SIZE,Sighandler_t);
2846}
2847# endif /* USE_ITHREADS */
2848#endif /* HAVE_INTERP_INTERN */
2849
216db7ee 2850// added to remove undefied symbol error in CodeWarrior compilation
2851int
2852Perl_Ireentrant_buffer_ptr(aTHX)
2853{
2854 return 0;
2855}