1 /* WINCE.C - stuff for Windows CE
3 * Time-stamp: <26/10/01 15:25:20 keuchel@keuchelnt>
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.
9 #define WIN32_LEAN_AND_MEAN
10 #define WIN32IO_IS_STDIO
14 #define PERLIO_NOT_STDIO 0
16 #if !defined(PERLIO_IS_STDIO) && !defined(USE_SFIO)
27 #define PERL_NO_GET_CONTEXT
38 #include "celib_defs.h"
41 #include "cewin32_defs.h"
42 #include "cecrt_defs.h"
45 #include "stdio-palmsize.h"
50 #define EXECF_SPAWN_NOWAIT 3
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
60 # define do_spawn g_do_spawn
62 # define getlogin g_getlogin
65 static void get_shell(void);
66 static long tokenize(const char *str, char **dest, char ***destv);
67 static int do_spawn2(pTHX_ char *cmd, int exectype);
68 static BOOL has_shell_metachars(char *ptr);
69 static long filetime_to_clock(PFILETIME ft);
70 static BOOL filetime_from_time(PFILETIME ft, time_t t);
71 static char * get_emd_part(SV **leading, char *trailing, ...);
72 static void remove_dead_process(long deceased);
73 static long find_pid(int pid);
74 static char * qualified_path(const char *cmd);
75 static char * win32_get_xlib(const char *pl, const char *xlib,
79 static void remove_dead_pseudo_process(long child);
80 static long find_pseudo_pid(int pid);
83 int _fmode = O_TEXT; /* celib do not provide _fmode, so we define it here */
86 HANDLE w32_perldll_handle = INVALID_HANDLE_VALUE;
87 char w32_module_name[MAX_PATH+1];
90 static DWORD w32_platform = (DWORD)-1;
95 return (win32_os_id() == VER_PLATFORM_WIN32_WINDOWS);
101 return (win32_os_id() == VER_PLATFORM_WIN32_NT);
107 return (win32_os_id() == VER_PLATFORM_WIN32_CE);
111 set_w32_module_name(void)
114 XCEGetModuleFileNameA((HMODULE)((w32_perldll_handle == INVALID_HANDLE_VALUE)
115 ? XCEGetModuleHandleA(NULL)
116 : w32_perldll_handle),
117 w32_module_name, sizeof(w32_module_name));
119 /* normalize to forward slashes */
120 ptr = w32_module_name;
128 /* *svp (if non-NULL) is expected to be POK (valid allocated SvPVX(*svp)) */
130 get_regstr_from(HKEY hkey, const char *valuename, SV **svp)
132 /* Retrieve a REG_SZ or REG_EXPAND_SZ from the registry */
135 const char *subkey = "Software\\Perl";
139 retval = XCERegOpenKeyExA(hkey, subkey, 0, KEY_READ, &handle);
140 if (retval == ERROR_SUCCESS) {
142 retval = XCERegQueryValueExA(handle, valuename, 0, &type, NULL, &datalen);
143 if (retval == ERROR_SUCCESS && type == REG_SZ) {
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) {
152 SvCUR_set(*svp,datalen-1);
160 /* *svp (if non-NULL) is expected to be POK (valid allocated SvPVX(*svp)) */
162 get_regstr(const char *valuename, SV **svp)
164 char *str = get_regstr_from(HKEY_CURRENT_USER, valuename, svp);
166 str = get_regstr_from(HKEY_LOCAL_MACHINE, valuename, svp);
170 /* *prev_pathp (if non-NULL) is expected to be POK (valid allocated SvPVX(sv)) */
172 get_emd_part(SV **prev_pathp, char *trailing_path, ...)
176 char mod_name[MAX_PATH+1];
180 int oldsize, newsize;
183 va_start(ap, trailing_path);
184 strip = va_arg(ap, char *);
186 sprintf(base, "%d.%d", (int)PERL_REVISION, (int)PERL_VERSION);
187 baselen = strlen(base);
189 if (!*w32_module_name) {
190 set_w32_module_name();
192 strcpy(mod_name, w32_module_name);
193 ptr = strrchr(mod_name, '/');
194 while (ptr && strip) {
195 /* look for directories to skip back */
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))
211 strip = va_arg(ap, char *);
219 strcpy(++ptr, trailing_path);
221 /* only add directory if it exists */
222 if (XCEGetFileAttributesA(mod_name) != (DWORD) -1) {
223 /* directory exists */
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);
236 win32_get_privlib(const char *pl)
239 char *stdlib = "lib";
240 char buffer[MAX_PATH+1];
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);
248 /* $stdlib .= ";$EMD/../../lib" */
249 return get_emd_part(&sv, stdlib, ARCHNAME, "bin", Nullch);
253 win32_get_xlib(const char *pl, const char *xlib, const char *libname)
257 char pathstr[MAX_PATH+1];
263 /* $HKCU{"$xlib-$]"} || $HKLM{"$xlib-$]"} . ---; */
264 sprintf(regstr, "%s-%s", xlib, pl);
265 (void)get_regstr(regstr, &sv1);
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);
272 /* $HKCU{$xlib} || $HKLM{$xlib} . ---; */
273 (void)get_regstr(xlib, &sv2);
276 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/$libname/lib"; */
277 sprintf(pathstr, "%s/lib", libname);
278 (void)get_emd_part(&sv2, pathstr, ARCHNAME, "bin", pl, Nullch);
287 sv_catpvn(sv1, ";", 1);
294 win32_get_sitelib(const char *pl)
296 return win32_get_xlib(pl, "sitelib", "site");
299 #ifndef PERL_VENDORLIB_NAME
300 # define PERL_VENDORLIB_NAME "vendor"
304 win32_get_vendorlib(const char *pl)
306 return win32_get_xlib(pl, "vendorlib", PERL_VENDORLIB_NAME);
310 has_shell_metachars(char *ptr)
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.
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
355 Perl_my_popen(pTHX_ char *cmd, char *mode)
357 printf("popen(%s)\n", cmd);
359 Perl_croak(aTHX_ PL_no_func, "popen");
364 Perl_my_pclose(pTHX_ PerlIO *fp)
366 Perl_croak(aTHX_ PL_no_func, "pclose");
371 DllExport unsigned long
374 static OSVERSIONINFOA osver;
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;
382 return (unsigned long)w32_platform;
392 return -((int)w32_pseudo_id);
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.
405 tokenize(const char *str, char **dest, char ***destv)
407 char *retstart = Nullch;
408 char **retvstart = 0;
412 int slen = strlen(str);
414 register char **retv;
415 New(1307, ret, slen+2, char);
416 New(1308, retv, (slen+3)/2, char*);
424 if (*ret == '\\' && *str)
426 else if (*ret == ' ') {
442 retvstart[items] = Nullch;
452 win32_pipe(int *pfd, unsigned int size, int mode)
455 Perl_croak(aTHX_ PL_no_func, "pipe");
460 win32_times(struct tms *timebuf)
463 Perl_croak(aTHX_ PL_no_func, "times");
469 win32_signal(int sig, Sighandler_t subcode)
472 Perl_croak_nocontext("signal() TBD on this platform");
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
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,
498 Perl_do_aspawn(pTHX_ SV *really, SV **mark, SV **sp)
500 Perl_croak(aTHX_ PL_no_func, "aspawn");
504 /* returns pointer to the next unquoted space or the end of the string */
506 find_next_space(const char *s)
508 bool in_quotes = FALSE;
510 /* ignore doubled backslashes, or backslash+quote */
511 if (*s == '\\' && (s[1] == '\\' || s[1] == '"')) {
514 /* keep track of when we're within quotes */
515 else if (*s == '"') {
517 in_quotes = !in_quotes;
519 /* break it up only at spaces that aren't in quotes */
520 else if (!in_quotes && isSPACE(*s))
530 do_spawn2(pTHX_ char *cmd, int exectype)
536 BOOL needToTry = TRUE;
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);
546 for (s = cmd2; *s;) {
547 while (*s && isSPACE(*s))
551 s = find_next_space(s);
559 status = win32_spawnvp(P_WAIT, argv[0],
560 (const char* const*)argv);
562 case EXECF_SPAWN_NOWAIT:
563 status = win32_spawnvp(P_NOWAIT, argv[0],
564 (const char* const*)argv);
567 status = win32_execvp(argv[0], (const char* const*)argv);
570 if (status != -1 || errno == 0)
580 New(1306, argv, w32_perlshell_items + 2, char*);
581 while (++i < w32_perlshell_items)
582 argv[i] = w32_perlshell_vec[i];
587 status = win32_spawnvp(P_WAIT, argv[0],
588 (const char* const*)argv);
590 case EXECF_SPAWN_NOWAIT:
591 status = win32_spawnvp(P_NOWAIT, argv[0],
592 (const char* const*)argv);
595 status = win32_execvp(argv[0], (const char* const*)argv);
601 if (exectype == EXECF_SPAWN_NOWAIT) {
603 PL_statusvalue = -1; /* >16bits hint for pp_system() */
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));
615 PL_statusvalue = status;
621 Perl_do_spawn(pTHX_ char *cmd)
623 return do_spawn2(aTHX_ cmd, EXECF_SPAWN);
627 Perl_do_spawn_nowait(pTHX_ char *cmd)
629 return do_spawn2(aTHX_ cmd, EXECF_SPAWN_NOWAIT);
633 Perl_do_exec(pTHX_ char *cmd)
635 do_spawn2(aTHX_ cmd, EXECF_EXEC);
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.
644 win32_opendir(char *filename)
650 char scanname[MAX_PATH+3];
652 WIN32_FIND_DATAA aFindData;
653 WIN32_FIND_DATAW wFindData;
655 char buffer[MAX_PATH*2];
656 WCHAR wbuffer[MAX_PATH+1];
659 len = strlen(filename);
663 /* check to see if filename is a directory */
664 if (win32_stat(filename, &sbuf) < 0 || !S_ISDIR(sbuf.st_mode))
667 /* Get us a DIR structure */
668 Newz(1303, dirp, 1, DIR);
670 /* Create the search pattern */
671 strcpy(scanname, filename);
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++] = '/';
678 else if (scanname[len-1] != '/' && scanname[len-1] != '\\') {
679 scanname[len++] = '/';
681 scanname[len++] = '*';
682 scanname[len] = '\0';
684 /* do the FindFirstFile call */
685 fh = FindFirstFile(PerlDir_mapA(scanname), &aFindData);
687 if (fh == INVALID_HANDLE_VALUE) {
688 DWORD err = GetLastError();
689 /* FindFirstFile() fails on empty drives! */
691 case ERROR_FILE_NOT_FOUND:
693 case ERROR_NO_MORE_FILES:
694 case ERROR_PATH_NOT_FOUND:
697 case ERROR_NOT_ENOUGH_MEMORY:
708 /* now allocate the first part of the string table for
709 * the filenames that we find.
711 ptr = aFindData.cFileName;
717 New(1304, dirp->start, dirp->size, char);
718 strcpy(dirp->start, ptr);
720 dirp->end = dirp->curr = dirp->start;
726 /* Readdir just returns the current string pointer and bumps the
727 * string pointer to the nDllExport entry.
729 DllExport struct direct *
730 win32_readdir(DIR *dirp)
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;
741 dirp->dirstr.d_ino = dirp->curr - dirp->start;
743 /* Now set up for the next call to readdir */
744 dirp->curr += len + 1;
745 if (dirp->curr >= dirp->end) {
749 WIN32_FIND_DATAW wFindData;
750 WIN32_FIND_DATAA aFindData;
751 char buffer[MAX_PATH*2];
753 /* finding the next file that matches the wildcard
754 * (which should be all of them in this directory!).
756 res = FindNextFile(dirp->handle, &aFindData);
758 ptr = aFindData.cFileName;
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;
767 Renew(dirp->start, dirp->size, char);
768 dirp->curr = dirp->start + curpos;
770 strcpy(dirp->start + endpos, ptr);
771 dirp->end = dirp->start + newsize;
777 return &(dirp->dirstr);
783 /* Telldir returns the current string pointer position */
785 win32_telldir(DIR *dirp)
787 return (dirp->curr - dirp->start);
791 /* Seekdir moves the string pointer to a previously saved position
792 * (returned by telldir).
795 win32_seekdir(DIR *dirp, long loc)
797 dirp->curr = dirp->start + loc;
800 /* Rewinddir resets the string pointer to the start */
802 win32_rewinddir(DIR *dirp)
804 dirp->curr = dirp->start;
807 /* free the memory allocated by opendir */
809 win32_closedir(DIR *dirp)
812 if (dirp->handle != INVALID_HANDLE_VALUE)
813 FindClose(dirp->handle);
814 Safefree(dirp->start);
820 /////!!!!!!!!!!! return here and do right stuff!!!!
823 win32_opendir(char *filename)
825 return opendir(filename);
828 DllExport struct direct *
829 win32_readdir(DIR *dirp)
831 return readdir(dirp);
835 win32_telldir(DIR *dirp)
838 Perl_croak(aTHX_ PL_no_func, "telldir");
843 win32_seekdir(DIR *dirp, long loc)
846 Perl_croak(aTHX_ PL_no_func, "seekdir");
850 win32_rewinddir(DIR *dirp)
853 Perl_croak(aTHX_ PL_no_func, "rewinddir");
857 win32_closedir(DIR *dirp)
865 win32_kill(int pid, int sig)
868 Perl_croak(aTHX_ PL_no_func, "kill");
873 win32_stat(const char *path, struct stat *sbuf)
875 return xcestat(path, sbuf);
879 win32_longpath(char *path)
884 #ifndef USE_WIN32_RTL_ENV
887 win32_getenv(const char *name)
889 return xcegetenv(name);
893 win32_putenv(const char *name)
895 return xceputenv(name);
901 filetime_to_clock(PFILETIME ft)
903 __int64 qw = ft->dwHighDateTime;
905 qw |= ft->dwLowDateTime;
906 qw /= 10000; /* File time ticks at 0.1uS, clock at 1mS */
910 /* fix utime() so it works on directories in NT */
912 filetime_from_time(PFILETIME pFileTime, time_t Time)
914 struct tm *pTM = localtime(&Time);
915 SYSTEMTIME SystemTime;
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;
929 return SystemTimeToFileTime(&SystemTime, &LocalTime) &&
930 LocalFileTimeToFileTime(&LocalTime, pFileTime);
934 win32_unlink(const char *filename)
936 return xceunlink(filename);
940 win32_utime(const char *filename, struct utimbuf *times)
942 return xceutime(filename, (struct _utimbuf *) times);
946 win32_gettimeofday(struct timeval *tp, void *not_used)
948 return xcegettimeofday(tp,not_used);
952 win32_uname(struct utsname *name)
955 STRLEN nodemax = sizeof(name->nodename)-1;
956 OSVERSIONINFOA osver;
958 memset(&osver, 0, sizeof(OSVERSIONINFOA));
959 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOA);
960 if (XCEGetVersionExA(&osver)) {
962 switch (osver.dwPlatformId) {
963 case VER_PLATFORM_WIN32_CE:
964 strcpy(name->sysname, "Windows CE");
966 case VER_PLATFORM_WIN32_WINDOWS:
967 strcpy(name->sysname, "Windows");
969 case VER_PLATFORM_WIN32_NT:
970 strcpy(name->sysname, "Windows NT");
972 case VER_PLATFORM_WIN32s:
973 strcpy(name->sysname, "Win32s");
976 strcpy(name->sysname, "Win32 Unknown");
981 sprintf(name->release, "%d.%d",
982 osver.dwMajorVersion, osver.dwMinorVersion);
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);
994 *name->sysname = '\0';
995 *name->version = '\0';
996 *name->release = '\0';
1000 hep = win32_gethostbyname("localhost");
1002 STRLEN len = strlen(hep->h_name);
1003 if (len <= nodemax) {
1004 strcpy(name->nodename, hep->h_name);
1007 strncpy(name->nodename, hep->h_name, nodemax);
1008 name->nodename[nodemax] = '\0';
1013 if (!XCEGetComputerNameA(name->nodename, &sz))
1014 *name->nodename = '\0';
1017 /* machine (architecture) */
1021 GetSystemInfo(&info);
1023 switch (info.wProcessorArchitecture) {
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;
1040 arch = "unknown"; break;
1042 strcpy(name->machine, arch);
1047 /* Timing related stuff */
1050 do_raise(pTHX_ int sig)
1052 if (sig < SIG_SIZE) {
1053 Sighandler_t handler = w32_sighandler[sig];
1054 if (handler == SIG_IGN) {
1057 else if (handler != SIG_DFL) {
1062 /* Choose correct default behaviour */
1078 /* Tell caller to exit thread/process as approriate */
1083 sig_terminate(pTHX_ int sig)
1085 Perl_warn(aTHX_ "Terminating on signal SIG%s(%d)\n",PL_sig_name[sig], sig);
1086 /* exit() seems to be safe, my_exit() or die() is a problem in ^C
1093 win32_async_check(pTHX)
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
1100 while (PeekMessage(&msg, (HWND)-1, 0, 0, PM_REMOVE|PM_NOYIELD)) {
1102 switch(msg.message) {
1105 /* Perhaps some other messages could map to signals ? ... */
1108 /* Treat WM_QUIT like SIGHUP? */
1114 /* We use WM_USER to fake kill() with other signals */
1118 if (do_raise(aTHX_ sig)) {
1119 sig_terminate(aTHX_ sig);
1125 /* alarm() is a one-shot but SetTimer() repeats so kill it */
1127 KillTimer(NULL,w32_timerid);
1130 /* Now fake a call to signal handler */
1131 if (do_raise(aTHX_ 14)) {
1132 sig_terminate(aTHX_ 14);
1137 /* Otherwise do normal Win32 thing - in case it is useful */
1139 TranslateMessage(&msg);
1140 DispatchMessage(&msg);
1147 /* Above or other stuff may have set a signal flag */
1148 if (PL_sig_pending) {
1154 /* This function will not return until the timeout has elapsed, or until
1155 * one of the handles is ready. */
1157 win32_msgwait(pTHX_ DWORD count, LPHANDLE handles, DWORD timeout, LPDWORD resultp)
1159 /* We may need several goes at this - so compute when we stop */
1161 if (timeout != INFINITE) {
1162 ticks = GetTickCount();
1166 DWORD result = MsgWaitForMultipleObjects(count,handles,FALSE,timeout-ticks, QS_ALLEVENTS);
1169 if (result == WAIT_TIMEOUT) {
1170 /* Ran out of time - explicit return of zero to avoid -ve if we
1171 have scheduling issues
1175 if (timeout != INFINITE) {
1176 ticks = GetTickCount();
1178 if (result == WAIT_OBJECT_0 + count) {
1179 /* Message has arrived - check it */
1180 (void)win32_async_check(aTHX);
1183 /* Not timeout or message - one of handles is ready */
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;
1193 static UINT timerid = 0;
1195 static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
1198 KillTimer(NULL,timerid);
1203 DllExport unsigned int
1204 win32_sleep(unsigned int t)
1209 DllExport unsigned int
1210 win32_alarm(unsigned int sec)
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>
1218 * Snag is unless something is looking at the message queue
1219 * nothing happens :-(
1224 timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
1226 Perl_croak_nocontext("Cannot set timer");
1232 KillTimer(NULL,timerid);
1239 #ifdef HAVE_DES_FCRYPT
1240 extern char * des_fcrypt(const char *txt, const char *salt, char *cbuf);
1244 win32_crypt(const char *txt, const char *salt)
1247 #ifdef HAVE_DES_FCRYPT
1249 return des_fcrypt(txt, salt, w32_crypt_buffer);
1251 Perl_croak(aTHX_ "The crypt() function is unimplemented due to excessive paranoia.");
1256 /* C doesn't like repeat struct definitions */
1258 #if defined(USE_FIXED_OSFHANDLE) || defined(PERL_MSVCRT_READFIX)
1261 #define _CRTIMP __declspec(dllimport)
1265 * Control structure for lowio file handles
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 */
1272 CRITICAL_SECTION lock;
1277 * Array of arrays of control structures for lowio files.
1279 EXTERN_C _CRTIMP ioinfo* __pioinfo[];
1282 * Definition of IOINFO_L2E, the log base 2 of the number of elements in each
1283 * array of ioinfo structs.
1285 #define IOINFO_L2E 5
1288 * Definition of IOINFO_ARRAY_ELTS, the number of elements in ioinfo array
1290 #define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
1293 * Access macros for getting at an ioinfo struct and its fields from a
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)
1304 * redirected io subsystem for all XS modules
1317 return (&(environ));
1320 /* the rest are the remapped stdio routines */
1327 char *g_getlogin() {
1328 return "no-getlogin";
1344 win32_ferror(FILE *fp)
1346 return (ferror(fp));
1351 win32_feof(FILE *fp)
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.
1363 win32_strerror(int e)
1365 return xcestrerror(e);
1369 win32_str_os_error(void *sv, DWORD dwErr)
1373 sv_setpvn((SV*)sv, "Error", 5);
1378 win32_fprintf(FILE *fp, const char *format, ...)
1381 va_start(marker, format); /* Initialize variable arguments. */
1383 return (vfprintf(fp, format, marker));
1387 win32_printf(const char *format, ...)
1390 va_start(marker, format); /* Initialize variable arguments. */
1392 return (vprintf(format, marker));
1396 win32_vfprintf(FILE *fp, const char *format, va_list args)
1398 return (vfprintf(fp, format, args));
1402 win32_vprintf(const char *format, va_list args)
1404 return (vprintf(format, args));
1408 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
1410 return fread(buf, size, count, fp);
1414 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
1416 return fwrite(buf, size, count, fp);
1420 win32_fopen(const char *filename, const char *mode)
1422 return xcefopen(filename, mode);
1426 win32_fdopen(int handle, const char *mode)
1428 return palm_fdopen(handle, mode);
1432 win32_freopen(const char *path, const char *mode, FILE *stream)
1434 return xcefreopen(path, mode, stream);
1438 win32_fclose(FILE *pf)
1440 return xcefclose(pf);
1444 win32_fputs(const char *s,FILE *pf)
1446 return fputs(s, pf);
1450 win32_fputc(int c,FILE *pf)
1456 win32_ungetc(int c,FILE *pf)
1458 return ungetc(c,pf);
1462 win32_getc(FILE *pf)
1468 win32_fileno(FILE *pf)
1470 return palm_fileno(pf);
1474 win32_clearerr(FILE *pf)
1481 win32_fflush(FILE *pf)
1487 win32_ftell(FILE *pf)
1493 win32_fseek(FILE *pf, Off_t offset,int origin)
1495 return fseek(pf, offset, origin);
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... */
1501 win32_fgetpos(FILE *pf, fpos_t *p)
1503 return fgetpos(pf, p);
1507 win32_fsetpos(FILE *pf, const fpos_t *p)
1509 return fsetpos(pf, p);
1513 win32_rewind(FILE *pf)
1515 fseek(pf, 0, SEEK_SET);
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,
1533 FILE_ATTRIBUTE_NORMAL
1534 | FILE_FLAG_DELETE_ON_CLOSE,
1536 if (fh != INVALID_HANDLE_VALUE) {
1537 int fd = win32_open_osfhandle((intptr_t)fh, 0);
1539 #if defined(__BORLANDC__)
1540 setmode(fd,O_BINARY);
1542 DEBUG_p(PerlIO_printf(Perl_debug_log,
1543 "Created tmpfile=%s\n",filename));
1555 int fd = win32_tmpfd();
1557 return win32_fdopen(fd, "w+b");
1570 win32_fstat(int fd, struct stat *sbufptr)
1572 return xcefstat(fd, sbufptr);
1576 win32_link(const char *oldname, const char *newname)
1579 Perl_croak(aTHX_ PL_no_func, "link");
1585 win32_rename(const char *oname, const char *newname)
1587 return xcerename(oname, newname);
1591 win32_setmode(int fd, int mode)
1593 /* currently 'celib' seem to have this function in src, but not
1594 * exported. When it will be, we'll uncomment following line.
1596 /* return xcesetmode(fd, mode); */
1601 win32_chsize(int fd, Off_t size)
1603 return chsize(fd, size);
1607 win32_lseek(int fd, Off_t offset, int origin)
1609 return xcelseek(fd, offset, origin);
1615 return xcelseek(fd, 0, SEEK_CUR);
1619 win32_open(const char *path, int flag, ...)
1625 pmode = va_arg(ap, int);
1628 return xceopen(path, flag, pmode);
1634 return xceclose(fd);
1641 Perl_croak(aTHX_ PL_no_func, "eof");
1648 return xcedup(fd); /* from celib/ceio.c; requires some more work on it */
1652 win32_dup2(int fd1,int fd2)
1654 return xcedup2(fd1,fd2);
1658 win32_read(int fd, void *buf, unsigned int cnt)
1660 return xceread(fd, buf, cnt);
1664 win32_write(int fd, const void *buf, unsigned int cnt)
1666 return xcewrite(fd, (void *) buf, cnt);
1670 win32_mkdir(const char *dir, int mode)
1672 return xcemkdir(dir);
1676 win32_rmdir(const char *dir)
1678 return xcermdir(dir);
1682 win32_chdir(const char *dir)
1684 return xcechdir(dir);
1688 win32_access(const char *path, int mode)
1690 return xceaccess(path, mode);
1694 win32_chmod(const char *path, int mode)
1696 return xcechmod(path, mode);
1700 create_command_line(char *cname, STRLEN clen, const char * const *args)
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;
1714 cname = (char*)args[0];
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 :-(
1733 clen = strlen(cname);
1736 && (stricmp(&cname[clen-4], ".bat") == 0
1737 || (IsWinNT() && stricmp(&cname[clen-4], ".cmd") == 0)))
1743 char *exe = strrchr(cname, '/');
1744 char *exe2 = strrchr(cname, '\\');
1751 if (stricmp(exe, "cmd.exe") == 0 || stricmp(exe, "cmd") == 0) {
1755 else if (stricmp(exe, "command.com") == 0
1756 || stricmp(exe, "command") == 0)
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) */
1769 DEBUG_p(PerlIO_printf(Perl_debug_log, "[%s]",arg));
1771 DEBUG_p(PerlIO_printf(Perl_debug_log, "\n"));
1774 New(1310, cmd, len, char);
1779 extra_quotes = TRUE;
1782 for (index = 0; (arg = (char*)args[index]) != NULL; ++index) {
1784 STRLEN curlen = strlen(arg);
1786 /* we want to protect empty arguments and ones with spaces with
1787 * dquotes, but only if they aren't already there */
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))
1798 else if (!(arg[0] == '"' && curlen > 1 && arg[curlen-1] == '"')) {
1800 while (i < curlen) {
1801 if (isSPACE(arg[i])) {
1804 else if (arg[i] == '"') {
1828 && *arg == '/' /* see if arg is "/c", "/x/c", "/x/d/c" etc. */
1829 && stricmp(arg+curlen-2, "/c") == 0)
1831 /* is there a next argument? */
1832 if (args[index+1]) {
1833 /* are there two or more next arguments? */
1834 if (args[index+2]) {
1836 extra_quotes = TRUE;
1839 /* single argument, force quoting if it has spaces */
1855 qualified_path(const char *cmd)
1859 char *fullcmd, *curfullcmd;
1865 fullcmd = (char*)cmd;
1867 if (*fullcmd == '/' || *fullcmd == '\\')
1874 pathstr = PerlEnv_getenv("PATH");
1875 New(0, fullcmd, MAX_PATH+1, char);
1876 curfullcmd = fullcmd;
1881 /* start by appending the name to the current prefix */
1882 strcpy(curfullcmd, cmd);
1883 curfullcmd += cmdlen;
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] != '.'))
1890 strcpy(curfullcmd, ".exe");
1891 res = GetFileAttributes(fullcmd);
1892 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
1897 /* that failed, try the bare name */
1898 res = GetFileAttributes(fullcmd);
1899 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
1902 /* quit if no other path exists, or if cmd already has path */
1903 if (!pathstr || !*pathstr || has_slash)
1906 /* skip leading semis */
1907 while (*pathstr == ';')
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;
1921 pathstr++; /* skip trailing '"' */
1924 if ((STRLEN)(curfullcmd-fullcmd) < MAX_PATH-cmdlen-5)
1925 *curfullcmd++ = *pathstr;
1930 pathstr++; /* skip trailing semi */
1931 if (curfullcmd > fullcmd /* append a dir separator */
1932 && curfullcmd[-1] != '/' && curfullcmd[-1] != '\\')
1934 *curfullcmd++ = '\\';
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
1949 win32_get_childenv(void)
1955 win32_free_childenv(void* d)
1960 win32_clearenv(void)
1962 char *envv = GetEnvironmentStrings();
1966 char *end = strchr(cur,'=');
1967 if (end && end != cur) {
1969 xcesetenv(cur, "", 0);
1971 cur = end + strlen(end+1)+2;
1973 else if ((len = strlen(cur)))
1976 FreeEnvironmentStrings(envv);
1980 win32_get_childdir(void)
1984 char szfilename[(MAX_PATH+1)*2];
1986 WCHAR wfilename[MAX_PATH+1];
1987 GetCurrentDirectoryW(MAX_PATH+1, wfilename);
1988 W2AHELPER(wfilename, szfilename, sizeof(szfilename));
1991 GetCurrentDirectoryA(MAX_PATH+1, szfilename);
1994 New(0, ptr, strlen(szfilename)+1, char);
1995 strcpy(ptr, szfilename);
2000 win32_free_childdir(char* d)
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.
2013 * XXX splitting and rejoining the commandline between do_aspawn()
2014 * and win32_spawnvp() could also be avoided.
2018 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
2020 #ifdef USE_RTL_SPAWNVP
2021 return spawnvp(mode, cmdname, (char * const *)argv);
2028 STARTUPINFO StartupInfo;
2029 PROCESS_INFORMATION ProcessInformation;
2032 char *fullcmd = Nullch;
2033 char *cname = (char *)cmdname;
2037 clen = strlen(cname);
2038 /* if command name contains dquotes, must remove them */
2039 if (strchr(cname, '"')) {
2041 New(0,cname,clen+1,char);
2054 cmd = create_command_line(cname, clen, argv);
2056 env = PerlEnv_get_childenv();
2057 dir = PerlEnv_get_childdir();
2060 case P_NOWAIT: /* asynch + remember result */
2061 if (w32_num_children >= MAXIMUM_WAIT_OBJECTS) {
2066 /* Create a new process group so we can use GenerateConsoleCtrlEvent()
2069 /* not supported on CE create |= CREATE_NEW_PROCESS_GROUP; */
2072 case P_WAIT: /* synchronous execution */
2074 default: /* invalid mode */
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)
2099 create |= CREATE_NEW_CONSOLE;
2102 StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
2104 if (w32_use_showwindow) {
2105 StartupInfo.dwFlags |= STARTF_USESHOWWINDOW;
2106 StartupInfo.wShowWindow = w32_showwindow;
2109 DEBUG_p(PerlIO_printf(Perl_debug_log, "Spawning [%s] with [%s]\n",
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 */
2121 &ProcessInformation))
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. */
2130 fullcmd = qualified_path(cname);
2132 if (cname != cmdname)
2135 DEBUG_p(PerlIO_printf(Perl_debug_log,
2136 "Retrying [%s] with same args\n",
2146 if (mode == P_NOWAIT) {
2147 /* asynchronous spawn -- store handle, return PID */
2148 ret = (int)ProcessInformation.dwProcessId;
2149 if (IsWin95() && ret < 0)
2152 w32_child_handles[w32_num_children] = ProcessInformation.hProcess;
2153 w32_child_pids[w32_num_children] = (DWORD)ret;
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
2162 GetExitCodeProcess(ProcessInformation.hProcess, &status);
2164 CloseHandle(ProcessInformation.hProcess);
2167 CloseHandle(ProcessInformation.hThread);
2170 PerlEnv_free_childenv(env);
2171 PerlEnv_free_childdir(dir);
2173 if (cname != cmdname)
2180 win32_execv(const char *cmdname, const char *const *argv)
2183 Perl_croak(aTHX_ PL_no_func, "execv");
2188 win32_execvp(const char *cmdname, const char *const *argv)
2191 Perl_croak(aTHX_ PL_no_func, "execvp");
2196 win32_perror(const char *str)
2202 win32_setbuf(FILE *pf, char *buf)
2205 Perl_croak(aTHX_ PL_no_func, "setbuf");
2209 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
2211 return setvbuf(pf, buf, type, size);
2215 win32_flushall(void)
2221 win32_fcloseall(void)
2227 win32_fgets(char *s, int n, FILE *pf)
2229 return fgets(s, n, pf);
2239 win32_fgetc(FILE *pf)
2245 win32_putc(int c, FILE *pf)
2251 win32_puts(const char *s)
2263 win32_putchar(int c)
2270 #ifndef USE_PERL_SBRK
2272 static char *committed = NULL;
2273 static char *base = NULL;
2274 static char *reserved = NULL;
2275 static char *brk = NULL;
2276 static DWORD pagesize = 0;
2277 static DWORD allocsize = 0;
2285 GetSystemInfo(&info);
2286 /* Pretend page size is larger so we don't perpetually
2287 * call the OS to commit just one page ...
2289 pagesize = info.dwPageSize << 3;
2290 allocsize = info.dwAllocationGranularity;
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 ...
2296 if (brk+need >= reserved)
2298 DWORD size = 64*1024*1024;
2300 if (committed && reserved && committed < reserved)
2302 /* Commit last of previous chunk cannot span allocations */
2303 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
2305 committed = reserved;
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
2312 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
2315 reserved = addr+size;
2330 if (brk > committed)
2332 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
2333 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
2348 win32_malloc(size_t size)
2350 return malloc(size);
2354 win32_calloc(size_t numitems, size_t size)
2356 return calloc(numitems,size);
2360 win32_realloc(void *block, size_t size)
2362 return realloc(block,size);
2366 win32_free(void *block)
2372 win32_open_osfhandle(intptr_t osfhandle, int flags)
2375 char fileflags=0; /* _osfile flags */
2377 Perl_croak_nocontext("win32_open_osfhandle() TBD on this platform");
2382 win32_get_osfhandle(int fd)
2385 char fileflags=0; /* _osfile flags */
2387 Perl_croak_nocontext("win32_get_osfhandle() TBD on this platform");
2392 win32_fdupopen(FILE *pf)
2397 int fileno = win32_dup(win32_fileno(pf));
2398 int fmode = palm_fgetmode(pfdup);
2400 fprintf(stderr,"DEBUG for win32_fdupopen()\n");
2402 /* open the file in the same mode */
2403 if(fmode & O_RDONLY) {
2407 else if(fmode & O_APPEND) {
2411 else if(fmode & O_RDWR) {
2417 /* it appears that the binmode is attached to the
2418 * file descriptor so binmode files will be handled
2421 pfdup = win32_fdopen(fileno, mode);
2423 /* move the file pointer to the same position */
2424 if (!fgetpos(pf, &pos)) {
2425 fsetpos(pfdup, &pos);
2431 win32_dynaload(const char* filename)
2436 hModule = XCELoadLibraryA(filename);
2441 /* this is needed by Cwd.pm... */
2448 SV *sv = sv_newmortal();
2450 xcegetcwd(buf, sizeof(buf));
2452 sv_setpv(sv, xcestrdup(buf));
2456 #ifndef INCOMPLETE_TAINTS
2457 SvTAINTED_on(ST(0));
2468 Perl_croak(aTHX_ "usage: Win32::SetCwd($cwd)");
2470 if (!xcechdir(SvPV_nolen(ST(0))))
2477 XS(w32_GetTickCount)
2480 DWORD msec = GetTickCount();
2488 XS(w32_GetOSVersion)
2491 OSVERSIONINFOA osver;
2493 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOA);
2494 if (!XCEGetVersionExA(&osver)) {
2497 XPUSHs(newSVpvn(osver.szCSDVersion, strlen(osver.szCSDVersion)));
2498 XPUSHs(newSViv(osver.dwMajorVersion));
2499 XPUSHs(newSViv(osver.dwMinorVersion));
2500 XPUSHs(newSViv(osver.dwBuildNumber));
2502 XPUSHs(newSViv(osver.dwPlatformId));
2511 XSRETURN_IV(IsWinNT());
2519 XSRETURN_IV(IsWin95());
2527 XSRETURN_IV(IsWinCE());
2537 if(SystemParametersInfoW(SPI_GETOEMINFO, sizeof(wbuf), wbuf, FALSE))
2538 WideCharToMultiByte(CP_ACP, 0, wbuf, -1, buf, sizeof(buf), 0, 0);
2540 sprintf(buf, "SystemParametersInfo failed: %d", GetLastError());
2551 Perl_croak(aTHX_ "usage: Win32::Sleep($milliseconds)");
2562 Perl_croak(aTHX_ "usage: Win32::CopyFile($from, $to, $overwrite)");
2565 char szSourceFile[MAX_PATH+1];
2566 strcpy(szSourceFile, PerlDir_mapA(SvPV_nolen(ST(0))));
2567 bResult = XCECopyFileA(szSourceFile, SvPV_nolen(ST(1)),
2584 unsigned int flags = MB_OK;
2586 txt = SvPV_nolen(ST(0));
2588 if (items < 1 || items > 2)
2589 Perl_croak(aTHX_ "usage: Win32::MessageBox($txt, [$flags])");
2592 flags = SvIV(ST(1));
2594 res = XCEMessageBoxA(NULL, txt, "Perl", flags);
2600 XS(w32_GetPowerStatus)
2604 SYSTEM_POWER_STATUS_EX sps;
2606 if(GetSystemPowerStatusEx(&sps, TRUE) == FALSE)
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));
2631 SHELLEXECUTEINFO si;
2633 wchar_t wfile[MAX_PATH];
2637 Perl_croak(aTHX_ "usage: Win32::ShellEx($file, $verb)");
2639 file = SvPV_nolen(ST(0));
2640 verb = SvPV_nolen(ST(1));
2642 memset(&si, 0, sizeof(si));
2643 si.cbSize = sizeof(si);
2644 si.fMask = SEE_MASK_FLAG_NO_UI;
2646 MultiByteToWideChar(CP_ACP, 0, verb, -1,
2647 wverb, sizeof(wverb)/2);
2648 si.lpVerb = (TCHAR *)wverb;
2650 MultiByteToWideChar(CP_ACP, 0, file, -1,
2651 wfile, sizeof(wfile)/2);
2652 si.lpFile = (TCHAR *)wfile;
2654 if(ShellExecuteEx(&si) == FALSE)
2663 Perl_init_os_extras(void)
2666 char *file = __FILE__;
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;
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);
2680 newXS("Win32::ShellEx", w32_ShellEx, file);
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);
2698 fgets(buf, sizeof(buf), stdin);
2702 Perl_win32_init(int *argcp, char ***argvp)
2707 if((p = xcegetenv("PERLDEBUG")) && (p[0] == 'y' || p[0] == 'Y'))
2715 Perl_win32_term(void)
2722 win32_get_child_IO(child_IO_table* ptbl)
2724 ptbl->childStdIn = GetStdHandle(STD_INPUT_HANDLE);
2725 ptbl->childStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
2726 ptbl->childStdErr = GetStdHandle(STD_ERROR_HANDLE);
2729 win32_flock(int fd, int oper)
2732 Perl_croak(aTHX_ PL_no_func, "flock");
2737 win32_waitpid(int pid, int *status, int flags)
2740 Perl_croak(aTHX_ PL_no_func, "waitpid");
2745 win32_wait(int *status)
2748 Perl_croak(aTHX_ PL_no_func, "wait");
2753 wce_reopen_stdout(char *fname)
2755 if(xcefreopen(fname, "w", stdout) == NULL)
2766 printf("Hit RETURN");
2768 fgets(buf, sizeof(buf), stdin);
2772 /* //////////////////////////////////////////////////////////////////// */
2777 getcwd(char *buf, size_t size)
2779 return xcegetcwd(buf, size);
2790 win32_popenlist(const char *mode, IV narg, SV **args)
2793 Perl_croak(aTHX_ "List form of pipe open not implemented");
2798 * a popen() clone that respects PERL5SHELL
2800 * changed to return PerlIO* rather than FILE * by BKS, 11-11-2000
2804 win32_popen(const char *command, const char *mode)
2806 #ifdef USE_RTL_POPEN
2807 return _popen(command, mode);
2819 /* establish which ends read and write */
2820 if (strchr(mode,'w')) {
2821 stdfd = 0; /* stdin */
2824 nhandle = STD_INPUT_HANDLE;
2826 else if (strchr(mode,'r')) {
2827 stdfd = 1; /* stdout */
2830 nhandle = STD_OUTPUT_HANDLE;
2835 /* set the correct mode */
2836 if (strchr(mode,'b'))
2838 else if (strchr(mode,'t'))
2841 ourmode = _fmode & (O_TEXT | O_BINARY);
2843 /* the child doesn't inherit handles */
2844 ourmode |= O_NOINHERIT;
2846 if (win32_pipe(p, 512, ourmode) == -1)
2849 /* save current stdfd */
2850 if ((oldfd = win32_dup(stdfd)) == -1)
2853 /* save the old std handle (this needs to happen before the
2854 * dup2(), since that might call SetStdHandle() too) */
2857 old_h = GetStdHandle(nhandle);
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)
2864 /* close the child end in parent */
2865 win32_close(p[child]);
2867 /* set the new std handle (in case dup2() above didn't) */
2868 SetStdHandle(nhandle, (HANDLE)_get_osfhandle(stdfd));
2870 /* start the child */
2873 if ((childpid = do_spawn_nowait((char*)command)) == -1)
2876 /* revert stdfd to whatever it was before */
2877 if (win32_dup2(oldfd, stdfd) == -1)
2880 /* restore the old std handle (this needs to happen after the
2881 * dup2(), since that might call SetStdHandle() too */
2883 SetStdHandle(nhandle, old_h);
2888 /* close saved handle */
2892 sv_setiv(*av_fetch(w32_fdpid, p[parent], TRUE), childpid);
2895 /* set process id so that it can be returned by perl's open() */
2896 PL_forkprocess = childpid;
2899 /* we have an fd, return a file stream */
2900 return (PerlIO_fdopen(p[parent], (char *)mode));
2903 /* we don't need to check for errors here */
2907 SetStdHandle(nhandle, old_h);
2912 win32_dup2(oldfd, stdfd);
2917 #endif /* USE_RTL_POPEN */
2925 win32_pclose(PerlIO *pf)
2927 #ifdef USE_RTL_POPEN
2931 int childpid, status;
2935 sv = *av_fetch(w32_fdpid, PerlIO_fileno(pf), TRUE);
2938 childpid = SvIVX(sv);
2955 if (win32_waitpid(childpid, &status, 0) == -1)
2960 #endif /* USE_RTL_POPEN */
2963 #ifdef HAVE_INTERP_INTERN
2967 win32_csighandler(int sig)
2970 dTHXa(PERL_GET_SIG_CONTEXT);
2971 Perl_warn(aTHX_ "Got signal %d",sig);
2977 Perl_sys_intern_init(pTHX)
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
2988 New(1313, w32_pseudo_children, 1, child_tab);
2989 w32_num_pseudo_children = 0;
2991 w32_init_socktype = 0;
2997 Perl_sys_intern_clear(pTHX)
2999 Safefree(w32_perlshell_tokens);
3000 Safefree(w32_perlshell_vec);
3001 /* NOTE: w32_fdpid is freed by sv_clean_all() */
3002 Safefree(w32_children);
3004 KillTimer(NULL,w32_timerid);
3007 # ifdef USE_ITHREADS
3008 Safefree(w32_pseudo_children);
3012 # ifdef USE_ITHREADS
3015 Perl_sys_intern_dup(pTHX_ struct interp_intern *src, struct interp_intern *dst)
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);
3023 Newz(1313, dst->pseudo_children, 1, child_tab);
3024 dst->thr_intern.Winit_socktype = 0;
3026 dst->poll_count = 0;
3027 Copy(src->sigtable,dst->sigtable,SIG_SIZE,Sighandler_t);
3029 # endif /* USE_ITHREADS */
3030 #endif /* HAVE_INTERP_INTERN */
3033 win32_free_argvw(pTHX_ void *ptr)
3035 char** argv = (char**)ptr;
3043 win32_argv2utf8(int argc, char** argv)
3045 /* do nothing, since we're not aware of command line arguments
3052 Perl_sys_intern_clear(pTHX)
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);
3064 // added to remove undefied symbol error in CodeWarrior compilation
3066 Perl_Ireentrant_buffer_ptr(aTHX)