This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Rename "perl59" to "perl510"
[perl5.git] / win32 / wince.c
CommitLineData
e1caacb4
JH
1/* WINCE.C - stuff for Windows CE
2 *
ca6c63e1 3 * Time-stamp: <26/10/01 15:25:20 keuchel@keuchelnt>
e1caacb4
JH
4 *
5 * You may distribute under the terms of either the GNU General Public
6 * License or the Artistic License, as specified in the README file.
7 */
8
9#define WIN32_LEAN_AND_MEAN
10#define WIN32IO_IS_STDIO
11#include <windows.h>
216db7ee 12#include <signal.h>
e1caacb4 13
f4257e4d 14#define PERLIO_NOT_STDIO 0
e1caacb4
JH
15
16#if !defined(PERLIO_IS_STDIO) && !defined(USE_SFIO)
17#define PerlIO FILE
18#endif
19
20#define wince_private
21#include "errno.h"
22
23#include "EXTERN.h"
24#include "perl.h"
25
26#define NO_XSLOCKS
27#define PERL_NO_GET_CONTEXT
28#include "XSUB.h"
29
30#include "win32iop.h"
31#include <string.h>
32#include <stdarg.h>
33#include <float.h>
34#include <shellapi.h>
814ffeea 35#include <process.h>
e1caacb4
JH
36
37#define perl
38#include "celib_defs.h"
39#include "cewin32.h"
40#include "cecrt.h"
41#include "cewin32_defs.h"
42#include "cecrt_defs.h"
43
94081db1
VK
44#define GetCurrentDirectoryW XCEGetCurrentDirectoryW
45
e1caacb4
JH
46#ifdef PALM_SIZE
47#include "stdio-palmsize.h"
48#endif
49
50#define EXECF_EXEC 1
51#define EXECF_SPAWN 2
52#define EXECF_SPAWN_NOWAIT 3
53
54#if defined(PERL_IMPLICIT_SYS)
55# undef win32_get_privlib
56# define win32_get_privlib g_win32_get_privlib
57# undef win32_get_sitelib
58# define win32_get_sitelib g_win32_get_sitelib
59# undef win32_get_vendorlib
60# define win32_get_vendorlib g_win32_get_vendorlib
61# undef do_spawn
62# define do_spawn g_do_spawn
63# undef getlogin
64# define getlogin g_getlogin
65#endif
66
814ffeea
VK
67static void get_shell(void);
68static long tokenize(const char *str, char **dest, char ***destv);
69static int do_spawn2(pTHX_ char *cmd, int exectype);
70static BOOL has_shell_metachars(char *ptr);
e1caacb4
JH
71static long filetime_to_clock(PFILETIME ft);
72static BOOL filetime_from_time(PFILETIME ft, time_t t);
73static char * get_emd_part(SV **leading, char *trailing, ...);
814ffeea
VK
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
814ffeea
VK
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
f4257e4d 94int
e1caacb4
JH
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
814ffeea
VK
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 *
751e07d2 357Perl_my_popen(pTHX_ const char *cmd, const char *mode)
e1caacb4
JH
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{
814ffeea
VK
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
814ffeea
VK
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{
814ffeea
VK
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;
a02a5408
JC
417 Newx(ret, slen+2, char);
418 Newx(retv, (slen+3)/2, char*);
814ffeea
VK
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{
216db7ee 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{
216db7ee 464 dTHX;
e1caacb4
JH
465 Perl_croak(aTHX_ PL_no_func, "times");
466 return -1;
467}
468
216db7ee
VK
469Sighandler_t
470win32_signal(int sig, Sighandler_t subcode)
42165d27 471{
1829b0dc 472 return xcesignal(sig, subcode);
42165d27 473}
216db7ee 474
814ffeea
VK
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
814ffeea
VK
503/* returns pointer to the next unquoted space or the end of the string */
504static char*
505find_next_space(const char *s)
e1caacb4 506{
814ffeea
VK
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)) {
a02a5408
JC
541 Newx(argv, strlen(cmd) / 2 + 2, char*);
542 Newx(cmd2, strlen(cmd) + 1, char);
814ffeea
VK
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();
a02a5408 579 Newx(argv, w32_perlshell_items + 2, char*);
814ffeea
VK
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
751e07d2 632Perl_do_exec(pTHX_ const char *cmd)
814ffeea
VK
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 *
0e06f75d 643win32_opendir(const char *filename)
814ffeea
VK
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 */
a02a5408 667 Newxz(dirp, 1, DIR);
814ffeea
VK
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;
a02a5408 716 Newx(dirp->start, dirp->size, char);
814ffeea
VK
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
814ffeea
VK
818#else
819/////!!!!!!!!!!! return here and do right stuff!!!!
820
e1caacb4 821DllExport DIR *
0e06f75d 822win32_opendir(const char *filename)
e1caacb4
JH
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{
216db7ee 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{
216db7ee 844 dTHX;
e1caacb4
JH
845 Perl_croak(aTHX_ PL_no_func, "seekdir");
846}
847
848DllExport void
849win32_rewinddir(DIR *dirp)
850{
216db7ee 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}
814ffeea 861#endif // 1
e1caacb4
JH
862
863DllExport int
864win32_kill(int pid, int sig)
865{
216db7ee 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
814ffeea
VK
1046/* Timing related stuff */
1047
1048int
f4257e4d 1049do_raise(pTHX_ int sig)
814ffeea
VK
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
216db7ee
VK
1081void
1082sig_terminate(pTHX_ int sig)
1083{
2e332e71 1084 Perl_warn(aTHX_ "Terminating on signal SIG%s(%d)\n",PL_sig_name[sig], sig);
f4257e4d
YO
1085 /* exit() seems to be safe, my_exit() or die() is a problem in ^C
1086 thread
216db7ee
VK
1087 */
1088 exit(sig);
1089}
1090
1091DllExport int
1092win32_async_check(pTHX)
1093{
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
2e332e71 1112
216db7ee
VK
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;
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 1197 KillTimer(NULL,timerid);
f4257e4d 1198 timerid=0;
e1caacb4
JH
1199 sighandler(14);
1200}
e1caacb4
JH
1201
1202DllExport unsigned int
814ffeea
VK
1203win32_sleep(unsigned int t)
1204{
1205 return xcesleep(t);
1206}
1207
1208DllExport unsigned int
e1caacb4
JH
1209win32_alarm(unsigned int sec)
1210{
f4257e4d 1211 /*
e1caacb4 1212 * the 'obvious' implentation is SetTimer() with a callback
f4257e4d
YO
1213 * which does whatever receiving SIGALRM would do
1214 * we cannot use SIGALRM even via raise() as it is not
e1caacb4
JH
1215 * one of the supported codes in <signal.h>
1216 *
1217 * Snag is unless something is looking at the message queue
1218 * nothing happens :-(
f4257e4d 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");
f4257e4d 1226 }
e1caacb4
JH
1227 else
1228 {
1229 if (timerid)
1230 {
1231 KillTimer(NULL,timerid);
f4257e4d 1232 timerid=0;
e1caacb4
JH
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
814ffeea
VK
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
216db7ee
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/*
f4257e4d 1310 * Since the errors returned by the socket error function
e1caacb4
JH
1311 * WSAGetLastError() are not known by the library routine strerror
1312 * we have to roll our own.
1313 */
1314
1315DllExport char *
814ffeea 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
814ffeea 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
81003058
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{
81003058
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{
216db7ee 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
216db7ee
VK
1553DllExport int
1554win32_chsize(int fd, Off_t size)
1555{
1556 return chsize(fd, size);
1557}
1558
e1caacb4 1559DllExport long
814ffeea 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{
216db7ee 1593 dTHX;
e1caacb4
JH
1594 Perl_croak(aTHX_ PL_no_func, "eof");
1595 return -1;
1596}
1597
1598DllExport int
1599win32_dup(int fd)
1600{
216db7ee 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{
aebd5ec7 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
814ffeea
VK
1652static char *
1653create_command_line(char *cname, STRLEN clen, const char * const *args)
216db7ee
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;
a02a5408 1727 Newx(cmd, len, char);
216db7ee
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");
a02a5408 1828 Newx(fullcmd, MAX_PATH+1, char);
216db7ee
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
8f33b42a
VK
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;
8c56068e
JD
1937 char szfilename[MAX_PATH+1];
1938 GetCurrentDirectoryA(MAX_PATH+1, szfilename);
8f33b42a 1939
a02a5408 1940 Newx(ptr, strlen(szfilename)+1, char);
8f33b42a
VK
1941 strcpy(ptr, szfilename);
1942 return ptr;
1943}
1944
1945DllExport void
1946win32_free_childdir(char* d)
1947{
1948 dTHX;
1949 Safefree(d);
1950}
1951
216db7ee
VK
1952/* XXX this needs to be made more compatible with the spawnvp()
1953 * provided by the various RTLs. In particular, searching for
1954 * *.{com,bat,cmd} files (as done by the RTLs) is unimplemented.
1955 * This doesn't significantly affect perl itself, because we
1956 * always invoke things using PERL5SHELL if a direct attempt to
1957 * spawn the executable fails.
1958 *
1959 * XXX splitting and rejoining the commandline between do_aspawn()
1960 * and win32_spawnvp() could also be avoided.
1961 */
1962
216db7ee
VK
1963DllExport int
1964win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
1965{
1966#ifdef USE_RTL_SPAWNVP
1967 return spawnvp(mode, cmdname, (char * const *)argv);
1968#else
1969 dTHX;
1970 int ret;
1971 void* env;
1972 char* dir;
1973 child_IO_table tbl;
1974 STARTUPINFO StartupInfo;
1975 PROCESS_INFORMATION ProcessInformation;
1976 DWORD create = 0;
1977 char *cmd;
1978 char *fullcmd = Nullch;
1979 char *cname = (char *)cmdname;
1980 STRLEN clen = 0;
1981
1982 if (cname) {
1983 clen = strlen(cname);
1984 /* if command name contains dquotes, must remove them */
1985 if (strchr(cname, '"')) {
1986 cmd = cname;
a02a5408 1987 Newx(cname,clen+1,char);
216db7ee
VK
1988 clen = 0;
1989 while (*cmd) {
1990 if (*cmd != '"') {
1991 cname[clen] = *cmd;
1992 ++clen;
1993 }
1994 ++cmd;
1995 }
1996 cname[clen] = '\0';
1997 }
1998 }
1999
2000 cmd = create_command_line(cname, clen, argv);
2001
2002 env = PerlEnv_get_childenv();
2003 dir = PerlEnv_get_childdir();
2004
2005 switch(mode) {
2006 case P_NOWAIT: /* asynch + remember result */
2007 if (w32_num_children >= MAXIMUM_WAIT_OBJECTS) {
2008 errno = EAGAIN;
2009 ret = -1;
2010 goto RETVAL;
2011 }
2012 /* Create a new process group so we can use GenerateConsoleCtrlEvent()
2013 * in win32_kill()
2014 */
2015 /* not supported on CE create |= CREATE_NEW_PROCESS_GROUP; */
2016 /* FALL THROUGH */
2017
2018 case P_WAIT: /* synchronous execution */
2019 break;
2020 default: /* invalid mode */
2021 errno = EINVAL;
2022 ret = -1;
2023 goto RETVAL;
2024 }
2025 memset(&StartupInfo,0,sizeof(StartupInfo));
2026 StartupInfo.cb = sizeof(StartupInfo);
2027 memset(&tbl,0,sizeof(tbl));
2028 PerlEnv_get_child_IO(&tbl);
2029 StartupInfo.dwFlags = tbl.dwFlags;
2030 StartupInfo.dwX = tbl.dwX;
2031 StartupInfo.dwY = tbl.dwY;
2032 StartupInfo.dwXSize = tbl.dwXSize;
2033 StartupInfo.dwYSize = tbl.dwYSize;
2034 StartupInfo.dwXCountChars = tbl.dwXCountChars;
2035 StartupInfo.dwYCountChars = tbl.dwYCountChars;
2036 StartupInfo.dwFillAttribute = tbl.dwFillAttribute;
2037 StartupInfo.wShowWindow = tbl.wShowWindow;
2038 StartupInfo.hStdInput = tbl.childStdIn;
2039 StartupInfo.hStdOutput = tbl.childStdOut;
2040 StartupInfo.hStdError = tbl.childStdErr;
2041 if (StartupInfo.hStdInput == INVALID_HANDLE_VALUE &&
2042 StartupInfo.hStdOutput == INVALID_HANDLE_VALUE &&
2043 StartupInfo.hStdError == INVALID_HANDLE_VALUE)
2044 {
2045 create |= CREATE_NEW_CONSOLE;
2046 }
2047 else {
2048 StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
2049 }
2050 if (w32_use_showwindow) {
2051 StartupInfo.dwFlags |= STARTF_USESHOWWINDOW;
2052 StartupInfo.wShowWindow = w32_showwindow;
2053 }
2054
2055 DEBUG_p(PerlIO_printf(Perl_debug_log, "Spawning [%s] with [%s]\n",
2056 cname,cmd));
2057RETRY:
2058 if (!CreateProcess(cname, /* search PATH to find executable */
2059 cmd, /* executable, and its arguments */
2060 NULL, /* process attributes */
2061 NULL, /* thread attributes */
2062 TRUE, /* inherit handles */
2063 create, /* creation flags */
2064 (LPVOID)env, /* inherit environment */
2065 dir, /* inherit cwd */
2066 &StartupInfo,
2067 &ProcessInformation))
2068 {
2069 /* initial NULL argument to CreateProcess() does a PATH
2070 * search, but it always first looks in the directory
2071 * where the current process was started, which behavior
2072 * is undesirable for backward compatibility. So we
2073 * jump through our own hoops by picking out the path
2074 * we really want it to use. */
2075 if (!fullcmd) {
2076 fullcmd = qualified_path(cname);
2077 if (fullcmd) {
2078 if (cname != cmdname)
2079 Safefree(cname);
2080 cname = fullcmd;
2081 DEBUG_p(PerlIO_printf(Perl_debug_log,
2082 "Retrying [%s] with same args\n",
2083 cname));
2084 goto RETRY;
2085 }
2086 }
2087 errno = ENOENT;
2088 ret = -1;
2089 goto RETVAL;
2090 }
2091
2092 if (mode == P_NOWAIT) {
2093 /* asynchronous spawn -- store handle, return PID */
2094 ret = (int)ProcessInformation.dwProcessId;
2095 if (IsWin95() && ret < 0)
2096 ret = -ret;
2097
2098 w32_child_handles[w32_num_children] = ProcessInformation.hProcess;
2099 w32_child_pids[w32_num_children] = (DWORD)ret;
2100 ++w32_num_children;
2101 }
2102 else {
2103 DWORD status;
2104 win32_msgwait(aTHX_ 1, &ProcessInformation.hProcess, INFINITE, NULL);
2105 /* FIXME: if msgwait returned due to message perhaps forward the
2106 "signal" to the process
2107 */
2108 GetExitCodeProcess(ProcessInformation.hProcess, &status);
2109 ret = (int)status;
2110 CloseHandle(ProcessInformation.hProcess);
2111 }
2112
2113 CloseHandle(ProcessInformation.hThread);
2114
2115RETVAL:
2116 PerlEnv_free_childenv(env);
2117 PerlEnv_free_childdir(dir);
2118 Safefree(cmd);
2119 if (cname != cmdname)
2120 Safefree(cname);
2121 return ret;
2122#endif
2123}
2124
e1caacb4
JH
2125DllExport int
2126win32_execv(const char *cmdname, const char *const *argv)
2127{
216db7ee 2128 dTHX;
e1caacb4
JH
2129 Perl_croak(aTHX_ PL_no_func, "execv");
2130 return -1;
2131}
2132
2133DllExport int
2134win32_execvp(const char *cmdname, const char *const *argv)
2135{
216db7ee 2136 dTHX;
e1caacb4
JH
2137 Perl_croak(aTHX_ PL_no_func, "execvp");
2138 return -1;
2139}
2140
814ffeea
VK
2141DllExport void
2142win32_perror(const char *str)
e1caacb4 2143{
814ffeea
VK
2144 xceperror(str);
2145}
e1caacb4 2146
814ffeea
VK
2147DllExport void
2148win32_setbuf(FILE *pf, char *buf)
2149{
2150 dTHX;
2151 Perl_croak(aTHX_ PL_no_func, "setbuf");
2152}
e1caacb4 2153
814ffeea
VK
2154DllExport int
2155win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
2156{
2157 return setvbuf(pf, buf, type, size);
e1caacb4
JH
2158}
2159
814ffeea
VK
2160DllExport int
2161win32_flushall(void)
2162{
2163 return flushall();
2164}
e1caacb4 2165
814ffeea
VK
2166DllExport int
2167win32_fcloseall(void)
e1caacb4 2168{
814ffeea
VK
2169 return fcloseall();
2170}
e1caacb4 2171
814ffeea
VK
2172DllExport char*
2173win32_fgets(char *s, int n, FILE *pf)
2174{
2175 return fgets(s, n, pf);
2176}
e1caacb4 2177
814ffeea
VK
2178DllExport char*
2179win32_gets(char *s)
2180{
2181 return gets(s);
e1caacb4
JH
2182}
2183
814ffeea
VK
2184DllExport int
2185win32_fgetc(FILE *pf)
e1caacb4 2186{
814ffeea
VK
2187 return fgetc(pf);
2188}
e1caacb4 2189
814ffeea
VK
2190DllExport int
2191win32_putc(int c, FILE *pf)
2192{
2193 return putc(c,pf);
2194}
2195
2196DllExport int
2197win32_puts(const char *s)
2198{
2199 return puts(s);
2200}
2201
2202DllExport int
2203win32_getchar(void)
2204{
2205 return getchar();
2206}
2207
2208DllExport int
2209win32_putchar(int c)
2210{
2211 return putchar(c);
2212}
2213
2214#ifdef MYMALLOC
2215
2216#ifndef USE_PERL_SBRK
2217
2218static char *committed = NULL;
2219static char *base = NULL;
2220static char *reserved = NULL;
2221static char *brk = NULL;
2222static DWORD pagesize = 0;
2223static DWORD allocsize = 0;
2224
2225void *
2226sbrk(int need)
2227{
2228 void *result;
2229 if (!pagesize)
2230 {SYSTEM_INFO info;
2231 GetSystemInfo(&info);
2232 /* Pretend page size is larger so we don't perpetually
2233 * call the OS to commit just one page ...
2234 */
2235 pagesize = info.dwPageSize << 3;
2236 allocsize = info.dwAllocationGranularity;
2237 }
2238 /* This scheme fails eventually if request for contiguous
f4257e4d 2239 * block is denied so reserve big blocks - this is only
814ffeea
VK
2240 * address space not memory ...
2241 */
2242 if (brk+need >= reserved)
2243 {
2244 DWORD size = 64*1024*1024;
2245 char *addr;
2246 if (committed && reserved && committed < reserved)
2247 {
2248 /* Commit last of previous chunk cannot span allocations */
2249 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
2250 if (addr)
2251 committed = reserved;
2252 }
f4257e4d 2253 /* Reserve some (more) space
814ffeea
VK
2254 * Note this is a little sneaky, 1st call passes NULL as reserved
2255 * so lets system choose where we start, subsequent calls pass
2256 * the old end address so ask for a contiguous block
2257 */
2258 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
2259 if (addr)
2260 {
2261 reserved = addr+size;
2262 if (!base)
2263 base = addr;
2264 if (!committed)
2265 committed = base;
2266 if (!brk)
2267 brk = committed;
2268 }
2269 else
2270 {
2271 return (void *) -1;
2272 }
2273 }
2274 result = brk;
2275 brk += need;
2276 if (brk > committed)
2277 {
2278 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
2279 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
2280 if (addr)
2281 {
2282 committed += size;
2283 }
2284 else
2285 return (void *) -1;
2286 }
2287 return result;
2288}
2289
2290#endif
2291#endif
2292
2293DllExport void*
2294win32_malloc(size_t size)
2295{
2296 return malloc(size);
2297}
2298
2299DllExport void*
2300win32_calloc(size_t numitems, size_t size)
2301{
2302 return calloc(numitems,size);
2303}
2304
2305DllExport void*
2306win32_realloc(void *block, size_t size)
2307{
2308 return realloc(block,size);
2309}
2310
2311DllExport void
2312win32_free(void *block)
2313{
2314 free(block);
2315}
2316
2317int
2318win32_open_osfhandle(intptr_t osfhandle, int flags)
2319{
2320 int fh;
2321 char fileflags=0; /* _osfile flags */
2322
2323 Perl_croak_nocontext("win32_open_osfhandle() TBD on this platform");
2324 return 0;
2325}
2326
2327int
2328win32_get_osfhandle(int fd)
2329{
2330 int fh;
2331 char fileflags=0; /* _osfile flags */
2332
2333 Perl_croak_nocontext("win32_get_osfhandle() TBD on this platform");
2334 return 0;
2335}
2336
2337FILE *
2338win32_fdupopen(FILE *pf)
2339{
2340 FILE* pfdup;
2341 fpos_t pos;
2342 char mode[3];
2343 int fileno = win32_dup(win32_fileno(pf));
2344 int fmode = palm_fgetmode(pfdup);
2345
2346 fprintf(stderr,"DEBUG for win32_fdupopen()\n");
2347
2348 /* open the file in the same mode */
2349 if(fmode & O_RDONLY) {
2350 mode[0] = 'r';
2351 mode[1] = 0;
2352 }
2353 else if(fmode & O_APPEND) {
2354 mode[0] = 'a';
2355 mode[1] = 0;
2356 }
2357 else if(fmode & O_RDWR) {
2358 mode[0] = 'r';
2359 mode[1] = '+';
2360 mode[2] = 0;
2361 }
2362
2363 /* it appears that the binmode is attached to the
2364 * file descriptor so binmode files will be handled
2365 * correctly
2366 */
2367 pfdup = win32_fdopen(fileno, mode);
2368
2369 /* move the file pointer to the same position */
2370 if (!fgetpos(pf, &pos)) {
2371 fsetpos(pfdup, &pos);
2372 }
2373 return pfdup;
2374}
2375
2376DllExport void*
2377win32_dynaload(const char* filename)
2378{
2379 dTHX;
2380 HMODULE hModule;
2381
2382 hModule = XCELoadLibraryA(filename);
2383
2384 return hModule;
2385}
2386
2387/* this is needed by Cwd.pm... */
2388
2389static
2390XS(w32_GetCwd)
2391{
2392 dXSARGS;
2393 char buf[MAX_PATH];
2394 SV *sv = sv_newmortal();
2395
2396 xcegetcwd(buf, sizeof(buf));
2397
2398 sv_setpv(sv, xcestrdup(buf));
2399 EXTEND(SP,1);
2400 SvPOK_on(sv);
2401 ST(0) = sv;
2402#ifndef INCOMPLETE_TAINTS
2403 SvTAINTED_on(ST(0));
2404#endif
2405 XSRETURN(1);
2406}
2407
2408static
2409XS(w32_SetCwd)
2410{
2411 dXSARGS;
2412
2413 if (items != 1)
e1caacb4
JH
2414 Perl_croak(aTHX_ "usage: Win32::SetCwd($cwd)");
2415
2416 if (!xcechdir(SvPV_nolen(ST(0))))
2417 XSRETURN_YES;
2418
2419 XSRETURN_NO;
2420}
2421
2422static
2423XS(w32_GetTickCount)
2424{
2425 dXSARGS;
2426 DWORD msec = GetTickCount();
2427 EXTEND(SP,1);
2428 if ((IV)msec > 0)
2429 XSRETURN_IV(msec);
2430 XSRETURN_NV(msec);
2431}
2432
2433static
2434XS(w32_GetOSVersion)
2435{
2436 dXSARGS;
2437 OSVERSIONINFOA osver;
2438
2439 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOA);
2440 if (!XCEGetVersionExA(&osver)) {
2441 XSRETURN_EMPTY;
2442 }
2443 XPUSHs(newSVpvn(osver.szCSDVersion, strlen(osver.szCSDVersion)));
2444 XPUSHs(newSViv(osver.dwMajorVersion));
2445 XPUSHs(newSViv(osver.dwMinorVersion));
2446 XPUSHs(newSViv(osver.dwBuildNumber));
cb69f87a 2447 /* WINCE = 3 */
e1caacb4
JH
2448 XPUSHs(newSViv(osver.dwPlatformId));
2449 PUTBACK;
2450}
2451
2452static
2453XS(w32_IsWinNT)
2454{
2455 dXSARGS;
2456 EXTEND(SP,1);
2457 XSRETURN_IV(IsWinNT());
2458}
2459
2460static
2461XS(w32_IsWin95)
2462{
2463 dXSARGS;
2464 EXTEND(SP,1);
2465 XSRETURN_IV(IsWin95());
2466}
2467
2468static
2469XS(w32_IsWinCE)
2470{
2471 dXSARGS;
2472 EXTEND(SP,1);
2473 XSRETURN_IV(IsWinCE());
2474}
2475
2476static
2477XS(w32_GetOemInfo)
2478{
2479 dXSARGS;
2480 wchar_t wbuf[126];
2481 char buf[126];
2482
2483 if(SystemParametersInfoW(SPI_GETOEMINFO, sizeof(wbuf), wbuf, FALSE))
2484 WideCharToMultiByte(CP_ACP, 0, wbuf, -1, buf, sizeof(buf), 0, 0);
2485 else
2486 sprintf(buf, "SystemParametersInfo failed: %d", GetLastError());
2487
2488 EXTEND(SP,1);
2489 XSRETURN_PV(buf);
2490}
2491
2492static
2493XS(w32_Sleep)
2494{
2495 dXSARGS;
2496 if (items != 1)
2497 Perl_croak(aTHX_ "usage: Win32::Sleep($milliseconds)");
2498 Sleep(SvIV(ST(0)));
2499 XSRETURN_YES;
2500}
2501
2502static
2503XS(w32_CopyFile)
2504{
2505 dXSARGS;
2506 BOOL bResult;
2507 if (items != 3)
2508 Perl_croak(aTHX_ "usage: Win32::CopyFile($from, $to, $overwrite)");
2509
2510 {
2511 char szSourceFile[MAX_PATH+1];
2512 strcpy(szSourceFile, PerlDir_mapA(SvPV_nolen(ST(0))));
f4257e4d 2513 bResult = XCECopyFileA(szSourceFile, SvPV_nolen(ST(1)),
e1caacb4
JH
2514 !SvTRUE(ST(2)));
2515 }
2516
2517 if (bResult)
2518 XSRETURN_YES;
2519
2520 XSRETURN_NO;
2521}
2522
2523static
2524XS(w32_MessageBox)
2525{
2526 dXSARGS;
2527
2528 char *txt;
2529 unsigned int res;
2530 unsigned int flags = MB_OK;
2531
2532 txt = SvPV_nolen(ST(0));
f4257e4d 2533
e1caacb4
JH
2534 if (items < 1 || items > 2)
2535 Perl_croak(aTHX_ "usage: Win32::MessageBox($txt, [$flags])");
2536
2537 if(items == 2)
2538 flags = SvIV(ST(1));
2539
2540 res = XCEMessageBoxA(NULL, txt, "Perl", flags);
2541
2542 XSRETURN_IV(res);
2543}
2544
2545static
2546XS(w32_GetPowerStatus)
2547{
2548 dXSARGS;
2549
2550 SYSTEM_POWER_STATUS_EX sps;
2551
2552 if(GetSystemPowerStatusEx(&sps, TRUE) == FALSE)
2553 {
2554 XSRETURN_EMPTY;
2555 }
2556
2557 XPUSHs(newSViv(sps.ACLineStatus));
2558 XPUSHs(newSViv(sps.BatteryFlag));
2559 XPUSHs(newSViv(sps.BatteryLifePercent));
2560 XPUSHs(newSViv(sps.BatteryLifeTime));
2561 XPUSHs(newSViv(sps.BatteryFullLifeTime));
2562 XPUSHs(newSViv(sps.BackupBatteryFlag));
2563 XPUSHs(newSViv(sps.BackupBatteryLifePercent));
2564 XPUSHs(newSViv(sps.BackupBatteryLifeTime));
2565 XPUSHs(newSViv(sps.BackupBatteryFullLifeTime));
2566
2567 PUTBACK;
2568}
2569
2570#if UNDER_CE > 200
2571static
2572XS(w32_ShellEx)
2573{
2574 dXSARGS;
2575
2576 char buf[126];
2577 SHELLEXECUTEINFO si;
2578 char *file, *verb;
2579 wchar_t wfile[MAX_PATH];
2580 wchar_t wverb[20];
2581
2582 if (items != 2)
2583 Perl_croak(aTHX_ "usage: Win32::ShellEx($file, $verb)");
2584
2585 file = SvPV_nolen(ST(0));
2586 verb = SvPV_nolen(ST(1));
2587
2588 memset(&si, 0, sizeof(si));
2589 si.cbSize = sizeof(si);
2590 si.fMask = SEE_MASK_FLAG_NO_UI;
2591
f4257e4d 2592 MultiByteToWideChar(CP_ACP, 0, verb, -1,
e1caacb4
JH
2593 wverb, sizeof(wverb)/2);
2594 si.lpVerb = (TCHAR *)wverb;
2595
f4257e4d 2596 MultiByteToWideChar(CP_ACP, 0, file, -1,
e1caacb4
JH
2597 wfile, sizeof(wfile)/2);
2598 si.lpFile = (TCHAR *)wfile;
2599
2600 if(ShellExecuteEx(&si) == FALSE)
2601 {
2602 XSRETURN_NO;
2603 }
2604 XSRETURN_YES;
2605}
2606#endif
2607
2608void
2609Perl_init_os_extras(void)
2610{
acfe0abc 2611 dTHX;
e1caacb4
JH
2612 char *file = __FILE__;
2613 dXSUB_SYS;
2614
2615 w32_perlshell_tokens = Nullch;
2616 w32_perlshell_items = -1;
2617 w32_fdpid = newAV(); /* XX needs to be in Perl_win32_init()? */
a02a5408 2618 Newx(w32_children, 1, child_tab);
e1caacb4
JH
2619 w32_num_children = 0;
2620
2621 newXS("Win32::GetCwd", w32_GetCwd, file);
2622 newXS("Win32::SetCwd", w32_SetCwd, file);
2623 newXS("Win32::GetTickCount", w32_GetTickCount, file);
2624 newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
2625#if UNDER_CE > 200
2626 newXS("Win32::ShellEx", w32_ShellEx, file);
2627#endif
2628 newXS("Win32::IsWinNT", w32_IsWinNT, file);
2629 newXS("Win32::IsWin95", w32_IsWin95, file);
2630 newXS("Win32::IsWinCE", w32_IsWinCE, file);
2631 newXS("Win32::CopyFile", w32_CopyFile, file);
2632 newXS("Win32::Sleep", w32_Sleep, file);
2633 newXS("Win32::MessageBox", w32_MessageBox, file);
2634 newXS("Win32::GetPowerStatus", w32_GetPowerStatus, file);
2635 newXS("Win32::GetOemInfo", w32_GetOemInfo, file);
2636}
2637
2638void
2639myexit(void)
2640{
2641 char buf[126];
2642
2643 puts("Hit return");
2644 fgets(buf, sizeof(buf), stdin);
2645}
2646
2647void
2648Perl_win32_init(int *argcp, char ***argvp)
2649{
2650#ifdef UNDER_CE
2651 char *p;
2652
2653 if((p = xcegetenv("PERLDEBUG")) && (p[0] == 'y' || p[0] == 'Y'))
2654 atexit(myexit);
2655#endif
2656
2657 MALLOC_INIT;
2658}
2659
216db7ee
VK
2660DllExport void
2661Perl_win32_term(void)
2662{
3890ecea 2663 dTHX;
71ad1b0c 2664 HINTS_REFCNT_TERM;
216db7ee 2665 OP_REFCNT_TERM;
3890ecea 2666 PERLIO_TERM;
216db7ee
VK
2667 MALLOC_TERM;
2668}
2669
2670void
2671win32_get_child_IO(child_IO_table* ptbl)
2672{
2673 ptbl->childStdIn = GetStdHandle(STD_INPUT_HANDLE);
2674 ptbl->childStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
2675 ptbl->childStdErr = GetStdHandle(STD_ERROR_HANDLE);
2676}
2677
e1caacb4
JH
2678win32_flock(int fd, int oper)
2679{
216db7ee 2680 dTHX;
e1caacb4
JH
2681 Perl_croak(aTHX_ PL_no_func, "flock");
2682 return -1;
2683}
2684
2685DllExport int
2686win32_waitpid(int pid, int *status, int flags)
2687{
216db7ee 2688 dTHX;
e1caacb4
JH
2689 Perl_croak(aTHX_ PL_no_func, "waitpid");
2690 return -1;
2691}
2692
2693DllExport int
2694win32_wait(int *status)
2695{
216db7ee 2696 dTHX;
e1caacb4
JH
2697 Perl_croak(aTHX_ PL_no_func, "wait");
2698 return -1;
2699}
2700
2701int
e1caacb4 2702wce_reopen_stdout(char *fname)
f4257e4d 2703{
e1caacb4
JH
2704 if(xcefreopen(fname, "w", stdout) == NULL)
2705 return -1;
2706
2707 return 0;
2708}
2709
2710void
2711wce_hitreturn()
2712{
2713 char buf[126];
2714
2715 printf("Hit RETURN");
2716 fflush(stdout);
2717 fgets(buf, sizeof(buf), stdin);
2718 return;
2719}
2720
cb69f87a 2721/* //////////////////////////////////////////////////////////////////// */
e1caacb4 2722
ca6c63e1
JH
2723#undef getcwd
2724
2725char *
2726getcwd(char *buf, size_t size)
2727{
2728 return xcegetcwd(buf, size);
2729}
2730
f4257e4d 2731int
ca6c63e1
JH
2732isnan(double d)
2733{
2734 return _isnan(d);
2735}
2736
18f68570 2737
814ffeea
VK
2738DllExport PerlIO*
2739win32_popenlist(const char *mode, IV narg, SV **args)
18f68570 2740{
814ffeea
VK
2741 dTHX;
2742 Perl_croak(aTHX_ "List form of pipe open not implemented");
2743 return NULL;
18f68570
VK
2744}
2745
2746/*
2747 * a popen() clone that respects PERL5SHELL
2748 *
2749 * changed to return PerlIO* rather than FILE * by BKS, 11-11-2000
2750 */
2751
2752DllExport PerlIO*
2753win32_popen(const char *command, const char *mode)
2754{
814ffeea 2755 return _popen(command, mode);
216db7ee
VK
2756}
2757
18f68570
VK
2758/*
2759 * pclose() clone
2760 */
2761
2762DllExport int
2763win32_pclose(PerlIO *pf)
2764{
18f68570 2765 return _pclose(pf);
18f68570
VK
2766}
2767
216db7ee
VK
2768#ifdef HAVE_INTERP_INTERN
2769
2770
2771static void
2772win32_csighandler(int sig)
2773{
2774#if 0
2775 dTHXa(PERL_GET_SIG_CONTEXT);
2776 Perl_warn(aTHX_ "Got signal %d",sig);
2777#endif
2778 /* Does nothing */
2779}
2780
2781void
2782Perl_sys_intern_init(pTHX)
2783{
2784 int i;
2785 w32_perlshell_tokens = Nullch;
2786 w32_perlshell_vec = (char**)NULL;
2787 w32_perlshell_items = 0;
2788 w32_fdpid = newAV();
a02a5408 2789 Newx(w32_children, 1, child_tab);
216db7ee
VK
2790 w32_num_children = 0;
2791# ifdef USE_ITHREADS
2792 w32_pseudo_id = 0;
a02a5408 2793 Newx(w32_pseudo_children, 1, child_tab);
216db7ee
VK
2794 w32_num_pseudo_children = 0;
2795# endif
2796 w32_init_socktype = 0;
2797 w32_timerid = 0;
2798 w32_poll_count = 0;
2799}
2800
2801void
2802Perl_sys_intern_clear(pTHX)
2803{
2804 Safefree(w32_perlshell_tokens);
2805 Safefree(w32_perlshell_vec);
2806 /* NOTE: w32_fdpid is freed by sv_clean_all() */
2807 Safefree(w32_children);
2808 if (w32_timerid) {
2809 KillTimer(NULL,w32_timerid);
2810 w32_timerid=0;
2811 }
2812# ifdef USE_ITHREADS
2813 Safefree(w32_pseudo_children);
2814# endif
2815}
2816
2817# ifdef USE_ITHREADS
2818
2819void
2820Perl_sys_intern_dup(pTHX_ struct interp_intern *src, struct interp_intern *dst)
2821{
2822 dst->perlshell_tokens = Nullch;
2823 dst->perlshell_vec = (char**)NULL;
2824 dst->perlshell_items = 0;
2825 dst->fdpid = newAV();
a02a5408 2826 Newxz(dst->children, 1, child_tab);
216db7ee 2827 dst->pseudo_id = 0;
a02a5408 2828 Newxz(dst->pseudo_children, 1, child_tab);
216db7ee
VK
2829 dst->thr_intern.Winit_socktype = 0;
2830 dst->timerid = 0;
2831 dst->poll_count = 0;
2832 Copy(src->sigtable,dst->sigtable,SIG_SIZE,Sighandler_t);
2833}
2834# endif /* USE_ITHREADS */
2835#endif /* HAVE_INTERP_INTERN */
2836
216db7ee
VK
2837// added to remove undefied symbol error in CodeWarrior compilation
2838int
2839Perl_Ireentrant_buffer_ptr(aTHX)
2840{
2841 return 0;
2842}