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