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