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"
44 #define GetCurrentDirectoryW XCEGetCurrentDirectoryW
47 #include "stdio-palmsize.h"
52 #define EXECF_SPAWN_NOWAIT 3
54 #if defined(PERL_IMPLICIT_SYS)
55 # undef win32_get_privlib
56 # define win32_get_privlib g_win32_get_privlib
57 # undef win32_get_sitelib
58 # define win32_get_sitelib g_win32_get_sitelib
59 # undef win32_get_vendorlib
60 # define win32_get_vendorlib g_win32_get_vendorlib
62 # define do_spawn g_do_spawn
64 # define getlogin g_getlogin
67 static void get_shell(void);
68 static long tokenize(const char *str, char **dest, char ***destv);
69 static int do_spawn2(pTHX_ char *cmd, int exectype);
70 static BOOL has_shell_metachars(char *ptr);
71 static long filetime_to_clock(PFILETIME ft);
72 static BOOL filetime_from_time(PFILETIME ft, time_t t);
73 static char * get_emd_part(SV **leading, char *trailing, ...);
74 static void remove_dead_process(long deceased);
75 static long find_pid(int pid);
76 static char * qualified_path(const char *cmd);
77 static char * win32_get_xlib(const char *pl, const char *xlib,
81 static void remove_dead_pseudo_process(long child);
82 static long find_pseudo_pid(int pid);
85 int _fmode = O_TEXT; /* celib do not provide _fmode, so we define it here */
88 HANDLE w32_perldll_handle = INVALID_HANDLE_VALUE;
89 char w32_module_name[MAX_PATH+1];
92 static DWORD w32_platform = (DWORD)-1;
97 return (win32_os_id() == VER_PLATFORM_WIN32_WINDOWS);
103 return (win32_os_id() == VER_PLATFORM_WIN32_NT);
109 return (win32_os_id() == VER_PLATFORM_WIN32_CE);
113 set_w32_module_name(void)
116 XCEGetModuleFileNameA((HMODULE)((w32_perldll_handle == INVALID_HANDLE_VALUE)
117 ? XCEGetModuleHandleA(NULL)
118 : w32_perldll_handle),
119 w32_module_name, sizeof(w32_module_name));
121 /* normalize to forward slashes */
122 ptr = w32_module_name;
130 /* *svp (if non-NULL) is expected to be POK (valid allocated SvPVX(*svp)) */
132 get_regstr_from(HKEY hkey, const char *valuename, SV **svp)
134 /* Retrieve a REG_SZ or REG_EXPAND_SZ from the registry */
137 const char *subkey = "Software\\Perl";
141 retval = XCERegOpenKeyExA(hkey, subkey, 0, KEY_READ, &handle);
142 if (retval == ERROR_SUCCESS) {
144 retval = XCERegQueryValueExA(handle, valuename, 0, &type, NULL, &datalen);
145 if (retval == ERROR_SUCCESS && type == REG_SZ) {
148 *svp = sv_2mortal(newSVpvn("",0));
149 SvGROW(*svp, datalen);
150 retval = XCERegQueryValueExA(handle, valuename, 0, NULL,
151 (PBYTE)SvPVX(*svp), &datalen);
152 if (retval == ERROR_SUCCESS) {
154 SvCUR_set(*svp,datalen-1);
162 /* *svp (if non-NULL) is expected to be POK (valid allocated SvPVX(*svp)) */
164 get_regstr(const char *valuename, SV **svp)
166 char *str = get_regstr_from(HKEY_CURRENT_USER, valuename, svp);
168 str = get_regstr_from(HKEY_LOCAL_MACHINE, valuename, svp);
172 /* *prev_pathp (if non-NULL) is expected to be POK (valid allocated SvPVX(sv)) */
174 get_emd_part(SV **prev_pathp, char *trailing_path, ...)
178 char mod_name[MAX_PATH+1];
182 int oldsize, newsize;
185 va_start(ap, trailing_path);
186 strip = va_arg(ap, char *);
188 sprintf(base, "%d.%d", (int)PERL_REVISION, (int)PERL_VERSION);
189 baselen = strlen(base);
191 if (!*w32_module_name) {
192 set_w32_module_name();
194 strcpy(mod_name, w32_module_name);
195 ptr = strrchr(mod_name, '/');
196 while (ptr && strip) {
197 /* look for directories to skip back */
200 ptr = strrchr(mod_name, '/');
201 /* avoid stripping component if there is no slash,
202 * or it doesn't match ... */
203 if (!ptr || stricmp(ptr+1, strip) != 0) {
204 /* ... but not if component matches m|5\.$patchlevel.*| */
205 if (!ptr || !(*strip == '5' && *(ptr+1) == '5'
206 && strncmp(strip, base, baselen) == 0
207 && strncmp(ptr+1, base, baselen) == 0))
213 strip = va_arg(ap, char *);
221 strcpy(++ptr, trailing_path);
223 /* only add directory if it exists */
224 if (XCEGetFileAttributesA(mod_name) != (DWORD) -1) {
225 /* directory exists */
228 *prev_pathp = sv_2mortal(newSVpvn("",0));
229 sv_catpvn(*prev_pathp, ";", 1);
230 sv_catpv(*prev_pathp, mod_name);
231 return SvPVX(*prev_pathp);
238 win32_get_privlib(const char *pl)
241 char *stdlib = "lib";
242 char buffer[MAX_PATH+1];
245 /* $stdlib = $HKCU{"lib-$]"} || $HKLM{"lib-$]"} || $HKCU{"lib"} || $HKLM{"lib"} || ""; */
246 sprintf(buffer, "%s-%s", stdlib, pl);
247 if (!get_regstr(buffer, &sv))
248 (void)get_regstr(stdlib, &sv);
250 /* $stdlib .= ";$EMD/../../lib" */
251 return get_emd_part(&sv, stdlib, ARCHNAME, "bin", Nullch);
255 win32_get_xlib(const char *pl, const char *xlib, const char *libname)
259 char pathstr[MAX_PATH+1];
265 /* $HKCU{"$xlib-$]"} || $HKLM{"$xlib-$]"} . ---; */
266 sprintf(regstr, "%s-%s", xlib, pl);
267 (void)get_regstr(regstr, &sv1);
270 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/$libname/$]/lib"; */
271 sprintf(pathstr, "%s/%s/lib", libname, pl);
272 (void)get_emd_part(&sv1, pathstr, ARCHNAME, "bin", pl, Nullch);
274 /* $HKCU{$xlib} || $HKLM{$xlib} . ---; */
275 (void)get_regstr(xlib, &sv2);
278 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/$libname/lib"; */
279 sprintf(pathstr, "%s/lib", libname);
280 (void)get_emd_part(&sv2, pathstr, ARCHNAME, "bin", pl, Nullch);
289 sv_catpvn(sv1, ";", 1);
296 win32_get_sitelib(const char *pl)
298 return win32_get_xlib(pl, "sitelib", "site");
301 #ifndef PERL_VENDORLIB_NAME
302 # define PERL_VENDORLIB_NAME "vendor"
306 win32_get_vendorlib(const char *pl)
308 return win32_get_xlib(pl, "vendorlib", PERL_VENDORLIB_NAME);
312 has_shell_metachars(char *ptr)
318 * Scan string looking for redirection (< or >) or pipe
319 * characters (|) that are not in a quoted string.
320 * Shell variable interpolation (%VAR%) can also happen inside strings.
352 #if !defined(PERL_IMPLICIT_SYS)
353 /* since the current process environment is being updated in util.c
354 * the library functions will get the correct environment
357 Perl_my_popen(pTHX_ char *cmd, char *mode)
359 printf("popen(%s)\n", cmd);
361 Perl_croak(aTHX_ PL_no_func, "popen");
366 Perl_my_pclose(pTHX_ PerlIO *fp)
368 Perl_croak(aTHX_ PL_no_func, "pclose");
373 DllExport unsigned long
376 static OSVERSIONINFOA osver;
378 if (osver.dwPlatformId != w32_platform) {
379 memset(&osver, 0, sizeof(OSVERSIONINFOA));
380 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOA);
381 XCEGetVersionExA(&osver);
382 w32_platform = osver.dwPlatformId;
384 return (unsigned long)w32_platform;
394 return -((int)w32_pseudo_id);
400 /* Tokenize a string. Words are null-separated, and the list
401 * ends with a doubled null. Any character (except null and
402 * including backslash) may be escaped by preceding it with a
403 * backslash (the backslash will be stripped).
404 * Returns number of words in result buffer.
407 tokenize(const char *str, char **dest, char ***destv)
409 char *retstart = Nullch;
410 char **retvstart = 0;
414 int slen = strlen(str);
416 register char **retv;
417 New(1307, ret, slen+2, char);
418 New(1308, retv, (slen+3)/2, char*);
426 if (*ret == '\\' && *str)
428 else if (*ret == ' ') {
444 retvstart[items] = Nullch;
454 win32_pipe(int *pfd, unsigned int size, int mode)
457 Perl_croak(aTHX_ PL_no_func, "pipe");
462 win32_times(struct tms *timebuf)
465 Perl_croak(aTHX_ PL_no_func, "times");
471 win32_signal(int sig, Sighandler_t subcode)
474 Perl_croak_nocontext("signal() TBD on this platform");
482 if (!w32_perlshell_tokens) {
483 /* we don't use COMSPEC here for two reasons:
484 * 1. the same reason perl on UNIX doesn't use SHELL--rampant and
485 * uncontrolled unportability of the ensuing scripts.
486 * 2. PERL5SHELL could be set to a shell that may not be fit for
487 * interactive use (which is what most programs look in COMSPEC
490 const char* defaultshell = (IsWinNT()
491 ? "cmd.exe /x/d/c" : "command.com /c");
492 const char *usershell = PerlEnv_getenv("PERL5SHELL");
493 w32_perlshell_items = tokenize(usershell ? usershell : defaultshell,
494 &w32_perlshell_tokens,
500 Perl_do_aspawn(pTHX_ SV *really, SV **mark, SV **sp)
502 Perl_croak(aTHX_ PL_no_func, "aspawn");
506 /* returns pointer to the next unquoted space or the end of the string */
508 find_next_space(const char *s)
510 bool in_quotes = FALSE;
512 /* ignore doubled backslashes, or backslash+quote */
513 if (*s == '\\' && (s[1] == '\\' || s[1] == '"')) {
516 /* keep track of when we're within quotes */
517 else if (*s == '"') {
519 in_quotes = !in_quotes;
521 /* break it up only at spaces that aren't in quotes */
522 else if (!in_quotes && isSPACE(*s))
532 do_spawn2(pTHX_ char *cmd, int exectype)
538 BOOL needToTry = TRUE;
541 /* Save an extra exec if possible. See if there are shell
542 * metacharacters in it */
543 if (!has_shell_metachars(cmd)) {
544 New(1301,argv, strlen(cmd) / 2 + 2, char*);
545 New(1302,cmd2, strlen(cmd) + 1, char);
548 for (s = cmd2; *s;) {
549 while (*s && isSPACE(*s))
553 s = find_next_space(s);
561 status = win32_spawnvp(P_WAIT, argv[0],
562 (const char* const*)argv);
564 case EXECF_SPAWN_NOWAIT:
565 status = win32_spawnvp(P_NOWAIT, argv[0],
566 (const char* const*)argv);
569 status = win32_execvp(argv[0], (const char* const*)argv);
572 if (status != -1 || errno == 0)
582 New(1306, argv, w32_perlshell_items + 2, char*);
583 while (++i < w32_perlshell_items)
584 argv[i] = w32_perlshell_vec[i];
589 status = win32_spawnvp(P_WAIT, argv[0],
590 (const char* const*)argv);
592 case EXECF_SPAWN_NOWAIT:
593 status = win32_spawnvp(P_NOWAIT, argv[0],
594 (const char* const*)argv);
597 status = win32_execvp(argv[0], (const char* const*)argv);
603 if (exectype == EXECF_SPAWN_NOWAIT) {
605 PL_statusvalue = -1; /* >16bits hint for pp_system() */
609 if (ckWARN(WARN_EXEC))
610 Perl_warner(aTHX_ packWARN(WARN_EXEC), "Can't %s \"%s\": %s",
611 (exectype == EXECF_EXEC ? "exec" : "spawn"),
612 cmd, strerror(errno));
617 PL_statusvalue = status;
623 Perl_do_spawn(pTHX_ char *cmd)
625 return do_spawn2(aTHX_ cmd, EXECF_SPAWN);
629 Perl_do_spawn_nowait(pTHX_ char *cmd)
631 return do_spawn2(aTHX_ cmd, EXECF_SPAWN_NOWAIT);
635 Perl_do_exec(pTHX_ char *cmd)
637 do_spawn2(aTHX_ cmd, EXECF_EXEC);
641 /* The idea here is to read all the directory names into a string table
642 * (separated by nulls) and when one of the other dir functions is called
643 * return the pointer to the current file name.
646 win32_opendir(char *filename)
652 char scanname[MAX_PATH+3];
654 WIN32_FIND_DATAA aFindData;
655 WIN32_FIND_DATAW wFindData;
657 char buffer[MAX_PATH*2];
658 WCHAR wbuffer[MAX_PATH+1];
661 len = strlen(filename);
665 /* check to see if filename is a directory */
666 if (win32_stat(filename, &sbuf) < 0 || !S_ISDIR(sbuf.st_mode))
669 /* Get us a DIR structure */
670 Newz(1303, dirp, 1, DIR);
672 /* Create the search pattern */
673 strcpy(scanname, filename);
675 /* bare drive name means look in cwd for drive */
676 if (len == 2 && isALPHA(scanname[0]) && scanname[1] == ':') {
677 scanname[len++] = '.';
678 scanname[len++] = '/';
680 else if (scanname[len-1] != '/' && scanname[len-1] != '\\') {
681 scanname[len++] = '/';
683 scanname[len++] = '*';
684 scanname[len] = '\0';
686 /* do the FindFirstFile call */
687 fh = FindFirstFile(PerlDir_mapA(scanname), &aFindData);
689 if (fh == INVALID_HANDLE_VALUE) {
690 DWORD err = GetLastError();
691 /* FindFirstFile() fails on empty drives! */
693 case ERROR_FILE_NOT_FOUND:
695 case ERROR_NO_MORE_FILES:
696 case ERROR_PATH_NOT_FOUND:
699 case ERROR_NOT_ENOUGH_MEMORY:
710 /* now allocate the first part of the string table for
711 * the filenames that we find.
713 ptr = aFindData.cFileName;
719 New(1304, dirp->start, dirp->size, char);
720 strcpy(dirp->start, ptr);
722 dirp->end = dirp->curr = dirp->start;
728 /* Readdir just returns the current string pointer and bumps the
729 * string pointer to the nDllExport entry.
731 DllExport struct direct *
732 win32_readdir(DIR *dirp)
737 /* first set up the structure to return */
738 len = strlen(dirp->curr);
739 strcpy(dirp->dirstr.d_name, dirp->curr);
740 dirp->dirstr.d_namlen = len;
743 dirp->dirstr.d_ino = dirp->curr - dirp->start;
745 /* Now set up for the next call to readdir */
746 dirp->curr += len + 1;
747 if (dirp->curr >= dirp->end) {
751 WIN32_FIND_DATAW wFindData;
752 WIN32_FIND_DATAA aFindData;
753 char buffer[MAX_PATH*2];
755 /* finding the next file that matches the wildcard
756 * (which should be all of them in this directory!).
758 res = FindNextFile(dirp->handle, &aFindData);
760 ptr = aFindData.cFileName;
762 long endpos = dirp->end - dirp->start;
763 long newsize = endpos + strlen(ptr) + 1;
764 /* bump the string table size by enough for the
765 * new name and its null terminator */
766 while (newsize > dirp->size) {
767 long curpos = dirp->curr - dirp->start;
769 Renew(dirp->start, dirp->size, char);
770 dirp->curr = dirp->start + curpos;
772 strcpy(dirp->start + endpos, ptr);
773 dirp->end = dirp->start + newsize;
779 return &(dirp->dirstr);
785 /* Telldir returns the current string pointer position */
787 win32_telldir(DIR *dirp)
789 return (dirp->curr - dirp->start);
793 /* Seekdir moves the string pointer to a previously saved position
794 * (returned by telldir).
797 win32_seekdir(DIR *dirp, long loc)
799 dirp->curr = dirp->start + loc;
802 /* Rewinddir resets the string pointer to the start */
804 win32_rewinddir(DIR *dirp)
806 dirp->curr = dirp->start;
809 /* free the memory allocated by opendir */
811 win32_closedir(DIR *dirp)
814 if (dirp->handle != INVALID_HANDLE_VALUE)
815 FindClose(dirp->handle);
816 Safefree(dirp->start);
822 /////!!!!!!!!!!! return here and do right stuff!!!!
825 win32_opendir(char *filename)
827 return opendir(filename);
830 DllExport struct direct *
831 win32_readdir(DIR *dirp)
833 return readdir(dirp);
837 win32_telldir(DIR *dirp)
840 Perl_croak(aTHX_ PL_no_func, "telldir");
845 win32_seekdir(DIR *dirp, long loc)
848 Perl_croak(aTHX_ PL_no_func, "seekdir");
852 win32_rewinddir(DIR *dirp)
855 Perl_croak(aTHX_ PL_no_func, "rewinddir");
859 win32_closedir(DIR *dirp)
867 win32_kill(int pid, int sig)
870 Perl_croak(aTHX_ PL_no_func, "kill");
875 win32_stat(const char *path, struct stat *sbuf)
877 return xcestat(path, sbuf);
881 win32_longpath(char *path)
886 #ifndef USE_WIN32_RTL_ENV
889 win32_getenv(const char *name)
891 return xcegetenv(name);
895 win32_putenv(const char *name)
897 return xceputenv(name);
903 filetime_to_clock(PFILETIME ft)
905 __int64 qw = ft->dwHighDateTime;
907 qw |= ft->dwLowDateTime;
908 qw /= 10000; /* File time ticks at 0.1uS, clock at 1mS */
912 /* fix utime() so it works on directories in NT */
914 filetime_from_time(PFILETIME pFileTime, time_t Time)
916 struct tm *pTM = localtime(&Time);
917 SYSTEMTIME SystemTime;
923 SystemTime.wYear = pTM->tm_year + 1900;
924 SystemTime.wMonth = pTM->tm_mon + 1;
925 SystemTime.wDay = pTM->tm_mday;
926 SystemTime.wHour = pTM->tm_hour;
927 SystemTime.wMinute = pTM->tm_min;
928 SystemTime.wSecond = pTM->tm_sec;
929 SystemTime.wMilliseconds = 0;
931 return SystemTimeToFileTime(&SystemTime, &LocalTime) &&
932 LocalFileTimeToFileTime(&LocalTime, pFileTime);
936 win32_unlink(const char *filename)
938 return xceunlink(filename);
942 win32_utime(const char *filename, struct utimbuf *times)
944 return xceutime(filename, (struct _utimbuf *) times);
948 win32_gettimeofday(struct timeval *tp, void *not_used)
950 return xcegettimeofday(tp,not_used);
954 win32_uname(struct utsname *name)
957 STRLEN nodemax = sizeof(name->nodename)-1;
958 OSVERSIONINFOA osver;
960 memset(&osver, 0, sizeof(OSVERSIONINFOA));
961 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOA);
962 if (XCEGetVersionExA(&osver)) {
964 switch (osver.dwPlatformId) {
965 case VER_PLATFORM_WIN32_CE:
966 strcpy(name->sysname, "Windows CE");
968 case VER_PLATFORM_WIN32_WINDOWS:
969 strcpy(name->sysname, "Windows");
971 case VER_PLATFORM_WIN32_NT:
972 strcpy(name->sysname, "Windows NT");
974 case VER_PLATFORM_WIN32s:
975 strcpy(name->sysname, "Win32s");
978 strcpy(name->sysname, "Win32 Unknown");
983 sprintf(name->release, "%d.%d",
984 osver.dwMajorVersion, osver.dwMinorVersion);
987 sprintf(name->version, "Build %d",
988 osver.dwPlatformId == VER_PLATFORM_WIN32_NT
989 ? osver.dwBuildNumber : (osver.dwBuildNumber & 0xffff));
990 if (osver.szCSDVersion[0]) {
991 char *buf = name->version + strlen(name->version);
992 sprintf(buf, " (%s)", osver.szCSDVersion);
996 *name->sysname = '\0';
997 *name->version = '\0';
998 *name->release = '\0';
1002 hep = win32_gethostbyname("localhost");
1004 STRLEN len = strlen(hep->h_name);
1005 if (len <= nodemax) {
1006 strcpy(name->nodename, hep->h_name);
1009 strncpy(name->nodename, hep->h_name, nodemax);
1010 name->nodename[nodemax] = '\0';
1015 if (!XCEGetComputerNameA(name->nodename, &sz))
1016 *name->nodename = '\0';
1019 /* machine (architecture) */
1023 GetSystemInfo(&info);
1025 switch (info.wProcessorArchitecture) {
1026 case PROCESSOR_ARCHITECTURE_INTEL:
1027 arch = "x86"; break;
1028 case PROCESSOR_ARCHITECTURE_MIPS:
1029 arch = "mips"; break;
1030 case PROCESSOR_ARCHITECTURE_ALPHA:
1031 arch = "alpha"; break;
1032 case PROCESSOR_ARCHITECTURE_PPC:
1033 arch = "ppc"; break;
1034 case PROCESSOR_ARCHITECTURE_ARM:
1035 arch = "arm"; break;
1036 case PROCESSOR_HITACHI_SH3:
1037 arch = "sh3"; break;
1038 case PROCESSOR_SHx_SH3:
1039 arch = "sh3"; break;
1042 arch = "unknown"; break;
1044 strcpy(name->machine, arch);
1049 /* Timing related stuff */
1052 do_raise(pTHX_ int sig)
1054 if (sig < SIG_SIZE) {
1055 Sighandler_t handler = w32_sighandler[sig];
1056 if (handler == SIG_IGN) {
1059 else if (handler != SIG_DFL) {
1064 /* Choose correct default behaviour */
1080 /* Tell caller to exit thread/process as approriate */
1085 sig_terminate(pTHX_ int sig)
1087 Perl_warn(aTHX_ "Terminating on signal SIG%s(%d)\n",PL_sig_name[sig], sig);
1088 /* exit() seems to be safe, my_exit() or die() is a problem in ^C
1095 win32_async_check(pTHX)
1099 /* Passing PeekMessage -1 as HWND (2nd arg) only get PostThreadMessage() messages
1100 * and ignores window messages - should co-exist better with windows apps e.g. Tk
1102 while (PeekMessage(&msg, (HWND)-1, 0, 0, PM_REMOVE|PM_NOYIELD)) {
1104 switch(msg.message) {
1107 /* Perhaps some other messages could map to signals ? ... */
1110 /* Treat WM_QUIT like SIGHUP? */
1116 /* We use WM_USER to fake kill() with other signals */
1120 if (do_raise(aTHX_ sig)) {
1121 sig_terminate(aTHX_ sig);
1127 /* alarm() is a one-shot but SetTimer() repeats so kill it */
1129 KillTimer(NULL,w32_timerid);
1132 /* Now fake a call to signal handler */
1133 if (do_raise(aTHX_ 14)) {
1134 sig_terminate(aTHX_ 14);
1139 /* Otherwise do normal Win32 thing - in case it is useful */
1141 TranslateMessage(&msg);
1142 DispatchMessage(&msg);
1149 /* Above or other stuff may have set a signal flag */
1150 if (PL_sig_pending) {
1156 /* This function will not return until the timeout has elapsed, or until
1157 * one of the handles is ready. */
1159 win32_msgwait(pTHX_ DWORD count, LPHANDLE handles, DWORD timeout, LPDWORD resultp)
1161 /* We may need several goes at this - so compute when we stop */
1163 if (timeout != INFINITE) {
1164 ticks = GetTickCount();
1168 DWORD result = MsgWaitForMultipleObjects(count,handles,FALSE,timeout-ticks, QS_ALLEVENTS);
1171 if (result == WAIT_TIMEOUT) {
1172 /* Ran out of time - explicit return of zero to avoid -ve if we
1173 have scheduling issues
1177 if (timeout != INFINITE) {
1178 ticks = GetTickCount();
1180 if (result == WAIT_OBJECT_0 + count) {
1181 /* Message has arrived - check it */
1182 (void)win32_async_check(aTHX);
1185 /* Not timeout or message - one of handles is ready */
1189 /* compute time left to wait */
1190 ticks = timeout - ticks;
1191 /* If we are past the end say zero */
1192 return (ticks > 0) ? ticks : 0;
1195 static UINT timerid = 0;
1197 static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
1200 KillTimer(NULL,timerid);
1205 DllExport unsigned int
1206 win32_sleep(unsigned int t)
1211 DllExport unsigned int
1212 win32_alarm(unsigned int sec)
1215 * the 'obvious' implentation is SetTimer() with a callback
1216 * which does whatever receiving SIGALRM would do
1217 * we cannot use SIGALRM even via raise() as it is not
1218 * one of the supported codes in <signal.h>
1220 * Snag is unless something is looking at the message queue
1221 * nothing happens :-(
1226 timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
1228 Perl_croak_nocontext("Cannot set timer");
1234 KillTimer(NULL,timerid);
1241 #ifdef HAVE_DES_FCRYPT
1242 extern char * des_fcrypt(const char *txt, const char *salt, char *cbuf);
1246 win32_crypt(const char *txt, const char *salt)
1249 #ifdef HAVE_DES_FCRYPT
1251 return des_fcrypt(txt, salt, w32_crypt_buffer);
1253 Perl_croak(aTHX_ "The crypt() function is unimplemented due to excessive paranoia.");
1260 * redirected io subsystem for all XS modules
1273 return (&(environ));
1276 /* the rest are the remapped stdio routines */
1283 char *g_getlogin() {
1284 return "no-getlogin";
1300 win32_ferror(FILE *fp)
1302 return (ferror(fp));
1307 win32_feof(FILE *fp)
1313 * Since the errors returned by the socket error function
1314 * WSAGetLastError() are not known by the library routine strerror
1315 * we have to roll our own.
1319 win32_strerror(int e)
1321 return xcestrerror(e);
1325 win32_str_os_error(void *sv, DWORD dwErr)
1329 sv_setpvn((SV*)sv, "Error", 5);
1334 win32_fprintf(FILE *fp, const char *format, ...)
1337 va_start(marker, format); /* Initialize variable arguments. */
1339 return (vfprintf(fp, format, marker));
1343 win32_printf(const char *format, ...)
1346 va_start(marker, format); /* Initialize variable arguments. */
1348 return (vprintf(format, marker));
1352 win32_vfprintf(FILE *fp, const char *format, va_list args)
1354 return (vfprintf(fp, format, args));
1358 win32_vprintf(const char *format, va_list args)
1360 return (vprintf(format, args));
1364 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
1366 return fread(buf, size, count, fp);
1370 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
1372 return fwrite(buf, size, count, fp);
1376 win32_fopen(const char *filename, const char *mode)
1378 return xcefopen(filename, mode);
1382 win32_fdopen(int handle, const char *mode)
1384 return palm_fdopen(handle, mode);
1388 win32_freopen(const char *path, const char *mode, FILE *stream)
1390 return xcefreopen(path, mode, stream);
1394 win32_fclose(FILE *pf)
1396 return xcefclose(pf);
1400 win32_fputs(const char *s,FILE *pf)
1402 return fputs(s, pf);
1406 win32_fputc(int c,FILE *pf)
1412 win32_ungetc(int c,FILE *pf)
1414 return ungetc(c,pf);
1418 win32_getc(FILE *pf)
1424 win32_fileno(FILE *pf)
1426 return palm_fileno(pf);
1430 win32_clearerr(FILE *pf)
1437 win32_fflush(FILE *pf)
1443 win32_ftell(FILE *pf)
1449 win32_fseek(FILE *pf, Off_t offset,int origin)
1451 return fseek(pf, offset, origin);
1454 /* fpos_t seems to be int64 on hpc pro! Really stupid. */
1455 /* But maybe someday there will be such large disks in a hpc... */
1457 win32_fgetpos(FILE *pf, fpos_t *p)
1459 return fgetpos(pf, p);
1463 win32_fsetpos(FILE *pf, const fpos_t *p)
1465 return fsetpos(pf, p);
1469 win32_rewind(FILE *pf)
1471 fseek(pf, 0, SEEK_SET);
1479 char prefix[MAX_PATH+1];
1480 char filename[MAX_PATH+1];
1481 DWORD len = GetTempPath(MAX_PATH, prefix);
1482 if (len && len < MAX_PATH) {
1483 if (GetTempFileName(prefix, "plx", 0, filename)) {
1484 HANDLE fh = CreateFile(filename,
1485 DELETE | GENERIC_READ | GENERIC_WRITE,
1489 FILE_ATTRIBUTE_NORMAL
1490 | FILE_FLAG_DELETE_ON_CLOSE,
1492 if (fh != INVALID_HANDLE_VALUE) {
1493 int fd = win32_open_osfhandle((intptr_t)fh, 0);
1495 #if defined(__BORLANDC__)
1496 setmode(fd,O_BINARY);
1498 DEBUG_p(PerlIO_printf(Perl_debug_log,
1499 "Created tmpfile=%s\n",filename));
1511 int fd = win32_tmpfd();
1513 return win32_fdopen(fd, "w+b");
1526 win32_fstat(int fd, struct stat *sbufptr)
1528 return xcefstat(fd, sbufptr);
1532 win32_link(const char *oldname, const char *newname)
1535 Perl_croak(aTHX_ PL_no_func, "link");
1541 win32_rename(const char *oname, const char *newname)
1543 return xcerename(oname, newname);
1547 win32_setmode(int fd, int mode)
1549 /* currently 'celib' seem to have this function in src, but not
1550 * exported. When it will be, we'll uncomment following line.
1552 /* return xcesetmode(fd, mode); */
1557 win32_chsize(int fd, Off_t size)
1559 return chsize(fd, size);
1563 win32_lseek(int fd, Off_t offset, int origin)
1565 return xcelseek(fd, offset, origin);
1571 return xcelseek(fd, 0, SEEK_CUR);
1575 win32_open(const char *path, int flag, ...)
1581 pmode = va_arg(ap, int);
1584 return xceopen(path, flag, pmode);
1590 return xceclose(fd);
1597 Perl_croak(aTHX_ PL_no_func, "eof");
1604 return xcedup(fd); /* from celib/ceio.c; requires some more work on it */
1608 win32_dup2(int fd1,int fd2)
1610 return xcedup2(fd1,fd2);
1614 win32_read(int fd, void *buf, unsigned int cnt)
1616 return xceread(fd, buf, cnt);
1620 win32_write(int fd, const void *buf, unsigned int cnt)
1622 return xcewrite(fd, (void *) buf, cnt);
1626 win32_mkdir(const char *dir, int mode)
1628 return xcemkdir(dir);
1632 win32_rmdir(const char *dir)
1634 return xcermdir(dir);
1638 win32_chdir(const char *dir)
1640 return xcechdir(dir);
1644 win32_access(const char *path, int mode)
1646 return xceaccess(path, mode);
1650 win32_chmod(const char *path, int mode)
1652 return xcechmod(path, mode);
1656 create_command_line(char *cname, STRLEN clen, const char * const *args)
1663 bool bat_file = FALSE;
1664 bool cmd_shell = FALSE;
1665 bool dumb_shell = FALSE;
1666 bool extra_quotes = FALSE;
1667 bool quote_next = FALSE;
1670 cname = (char*)args[0];
1672 /* The NT cmd.exe shell has the following peculiarity that needs to be
1673 * worked around. It strips a leading and trailing dquote when any
1674 * of the following is true:
1675 * 1. the /S switch was used
1676 * 2. there are more than two dquotes
1677 * 3. there is a special character from this set: &<>()@^|
1678 * 4. no whitespace characters within the two dquotes
1679 * 5. string between two dquotes isn't an executable file
1680 * To work around this, we always add a leading and trailing dquote
1681 * to the string, if the first argument is either "cmd.exe" or "cmd",
1682 * and there were at least two or more arguments passed to cmd.exe
1683 * (not including switches).
1684 * XXX the above rules (from "cmd /?") don't seem to be applied
1685 * always, making for the convolutions below :-(
1689 clen = strlen(cname);
1692 && (stricmp(&cname[clen-4], ".bat") == 0
1693 || (IsWinNT() && stricmp(&cname[clen-4], ".cmd") == 0)))
1699 char *exe = strrchr(cname, '/');
1700 char *exe2 = strrchr(cname, '\\');
1707 if (stricmp(exe, "cmd.exe") == 0 || stricmp(exe, "cmd") == 0) {
1711 else if (stricmp(exe, "command.com") == 0
1712 || stricmp(exe, "command") == 0)
1719 DEBUG_p(PerlIO_printf(Perl_debug_log, "Args "));
1720 for (index = 0; (arg = (char*)args[index]) != NULL; ++index) {
1721 STRLEN curlen = strlen(arg);
1722 if (!(arg[0] == '"' && arg[curlen-1] == '"'))
1723 len += 2; /* assume quoting needed (worst case) */
1725 DEBUG_p(PerlIO_printf(Perl_debug_log, "[%s]",arg));
1727 DEBUG_p(PerlIO_printf(Perl_debug_log, "\n"));
1730 New(1310, cmd, len, char);
1735 extra_quotes = TRUE;
1738 for (index = 0; (arg = (char*)args[index]) != NULL; ++index) {
1740 STRLEN curlen = strlen(arg);
1742 /* we want to protect empty arguments and ones with spaces with
1743 * dquotes, but only if they aren't already there */
1748 else if (quote_next) {
1749 /* see if it really is multiple arguments pretending to
1750 * be one and force a set of quotes around it */
1751 if (*find_next_space(arg))
1754 else if (!(arg[0] == '"' && curlen > 1 && arg[curlen-1] == '"')) {
1756 while (i < curlen) {
1757 if (isSPACE(arg[i])) {
1760 else if (arg[i] == '"') {
1784 && *arg == '/' /* see if arg is "/c", "/x/c", "/x/d/c" etc. */
1785 && stricmp(arg+curlen-2, "/c") == 0)
1787 /* is there a next argument? */
1788 if (args[index+1]) {
1789 /* are there two or more next arguments? */
1790 if (args[index+2]) {
1792 extra_quotes = TRUE;
1795 /* single argument, force quoting if it has spaces */
1811 qualified_path(const char *cmd)
1815 char *fullcmd, *curfullcmd;
1821 fullcmd = (char*)cmd;
1823 if (*fullcmd == '/' || *fullcmd == '\\')
1830 pathstr = PerlEnv_getenv("PATH");
1831 New(0, fullcmd, MAX_PATH+1, char);
1832 curfullcmd = fullcmd;
1837 /* start by appending the name to the current prefix */
1838 strcpy(curfullcmd, cmd);
1839 curfullcmd += cmdlen;
1841 /* if it doesn't end with '.', or has no extension, try adding
1842 * a trailing .exe first */
1843 if (cmd[cmdlen-1] != '.'
1844 && (cmdlen < 4 || cmd[cmdlen-4] != '.'))
1846 strcpy(curfullcmd, ".exe");
1847 res = GetFileAttributes(fullcmd);
1848 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
1853 /* that failed, try the bare name */
1854 res = GetFileAttributes(fullcmd);
1855 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
1858 /* quit if no other path exists, or if cmd already has path */
1859 if (!pathstr || !*pathstr || has_slash)
1862 /* skip leading semis */
1863 while (*pathstr == ';')
1866 /* build a new prefix from scratch */
1867 curfullcmd = fullcmd;
1868 while (*pathstr && *pathstr != ';') {
1869 if (*pathstr == '"') { /* foo;"baz;etc";bar */
1870 pathstr++; /* skip initial '"' */
1871 while (*pathstr && *pathstr != '"') {
1872 if ((STRLEN)(curfullcmd-fullcmd) < MAX_PATH-cmdlen-5)
1873 *curfullcmd++ = *pathstr;
1877 pathstr++; /* skip trailing '"' */
1880 if ((STRLEN)(curfullcmd-fullcmd) < MAX_PATH-cmdlen-5)
1881 *curfullcmd++ = *pathstr;
1886 pathstr++; /* skip trailing semi */
1887 if (curfullcmd > fullcmd /* append a dir separator */
1888 && curfullcmd[-1] != '/' && curfullcmd[-1] != '\\')
1890 *curfullcmd++ = '\\';
1898 /* The following are just place holders.
1899 * Some hosts may provide and environment that the OS is
1900 * not tracking, therefore, these host must provide that
1901 * environment and the current directory to CreateProcess
1905 win32_get_childenv(void)
1911 win32_free_childenv(void* d)
1916 win32_clearenv(void)
1918 char *envv = GetEnvironmentStrings();
1922 char *end = strchr(cur,'=');
1923 if (end && end != cur) {
1925 xcesetenv(cur, "", 0);
1927 cur = end + strlen(end+1)+2;
1929 else if ((len = strlen(cur)))
1932 FreeEnvironmentStrings(envv);
1936 win32_get_childdir(void)
1940 char szfilename[(MAX_PATH+1)*2];
1942 WCHAR wfilename[MAX_PATH+1];
1943 GetCurrentDirectoryW(MAX_PATH+1, wfilename);
1944 W2AHELPER(wfilename, szfilename, sizeof(szfilename));
1947 GetCurrentDirectoryA(MAX_PATH+1, szfilename);
1950 New(0, ptr, strlen(szfilename)+1, char);
1951 strcpy(ptr, szfilename);
1956 win32_free_childdir(char* d)
1962 /* XXX this needs to be made more compatible with the spawnvp()
1963 * provided by the various RTLs. In particular, searching for
1964 * *.{com,bat,cmd} files (as done by the RTLs) is unimplemented.
1965 * This doesn't significantly affect perl itself, because we
1966 * always invoke things using PERL5SHELL if a direct attempt to
1967 * spawn the executable fails.
1969 * XXX splitting and rejoining the commandline between do_aspawn()
1970 * and win32_spawnvp() could also be avoided.
1974 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
1976 #ifdef USE_RTL_SPAWNVP
1977 return spawnvp(mode, cmdname, (char * const *)argv);
1984 STARTUPINFO StartupInfo;
1985 PROCESS_INFORMATION ProcessInformation;
1988 char *fullcmd = Nullch;
1989 char *cname = (char *)cmdname;
1993 clen = strlen(cname);
1994 /* if command name contains dquotes, must remove them */
1995 if (strchr(cname, '"')) {
1997 New(0,cname,clen+1,char);
2010 cmd = create_command_line(cname, clen, argv);
2012 env = PerlEnv_get_childenv();
2013 dir = PerlEnv_get_childdir();
2016 case P_NOWAIT: /* asynch + remember result */
2017 if (w32_num_children >= MAXIMUM_WAIT_OBJECTS) {
2022 /* Create a new process group so we can use GenerateConsoleCtrlEvent()
2025 /* not supported on CE create |= CREATE_NEW_PROCESS_GROUP; */
2028 case P_WAIT: /* synchronous execution */
2030 default: /* invalid mode */
2035 memset(&StartupInfo,0,sizeof(StartupInfo));
2036 StartupInfo.cb = sizeof(StartupInfo);
2037 memset(&tbl,0,sizeof(tbl));
2038 PerlEnv_get_child_IO(&tbl);
2039 StartupInfo.dwFlags = tbl.dwFlags;
2040 StartupInfo.dwX = tbl.dwX;
2041 StartupInfo.dwY = tbl.dwY;
2042 StartupInfo.dwXSize = tbl.dwXSize;
2043 StartupInfo.dwYSize = tbl.dwYSize;
2044 StartupInfo.dwXCountChars = tbl.dwXCountChars;
2045 StartupInfo.dwYCountChars = tbl.dwYCountChars;
2046 StartupInfo.dwFillAttribute = tbl.dwFillAttribute;
2047 StartupInfo.wShowWindow = tbl.wShowWindow;
2048 StartupInfo.hStdInput = tbl.childStdIn;
2049 StartupInfo.hStdOutput = tbl.childStdOut;
2050 StartupInfo.hStdError = tbl.childStdErr;
2051 if (StartupInfo.hStdInput == INVALID_HANDLE_VALUE &&
2052 StartupInfo.hStdOutput == INVALID_HANDLE_VALUE &&
2053 StartupInfo.hStdError == INVALID_HANDLE_VALUE)
2055 create |= CREATE_NEW_CONSOLE;
2058 StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
2060 if (w32_use_showwindow) {
2061 StartupInfo.dwFlags |= STARTF_USESHOWWINDOW;
2062 StartupInfo.wShowWindow = w32_showwindow;
2065 DEBUG_p(PerlIO_printf(Perl_debug_log, "Spawning [%s] with [%s]\n",
2068 if (!CreateProcess(cname, /* search PATH to find executable */
2069 cmd, /* executable, and its arguments */
2070 NULL, /* process attributes */
2071 NULL, /* thread attributes */
2072 TRUE, /* inherit handles */
2073 create, /* creation flags */
2074 (LPVOID)env, /* inherit environment */
2075 dir, /* inherit cwd */
2077 &ProcessInformation))
2079 /* initial NULL argument to CreateProcess() does a PATH
2080 * search, but it always first looks in the directory
2081 * where the current process was started, which behavior
2082 * is undesirable for backward compatibility. So we
2083 * jump through our own hoops by picking out the path
2084 * we really want it to use. */
2086 fullcmd = qualified_path(cname);
2088 if (cname != cmdname)
2091 DEBUG_p(PerlIO_printf(Perl_debug_log,
2092 "Retrying [%s] with same args\n",
2102 if (mode == P_NOWAIT) {
2103 /* asynchronous spawn -- store handle, return PID */
2104 ret = (int)ProcessInformation.dwProcessId;
2105 if (IsWin95() && ret < 0)
2108 w32_child_handles[w32_num_children] = ProcessInformation.hProcess;
2109 w32_child_pids[w32_num_children] = (DWORD)ret;
2114 win32_msgwait(aTHX_ 1, &ProcessInformation.hProcess, INFINITE, NULL);
2115 /* FIXME: if msgwait returned due to message perhaps forward the
2116 "signal" to the process
2118 GetExitCodeProcess(ProcessInformation.hProcess, &status);
2120 CloseHandle(ProcessInformation.hProcess);
2123 CloseHandle(ProcessInformation.hThread);
2126 PerlEnv_free_childenv(env);
2127 PerlEnv_free_childdir(dir);
2129 if (cname != cmdname)
2136 win32_execv(const char *cmdname, const char *const *argv)
2139 Perl_croak(aTHX_ PL_no_func, "execv");
2144 win32_execvp(const char *cmdname, const char *const *argv)
2147 Perl_croak(aTHX_ PL_no_func, "execvp");
2152 win32_perror(const char *str)
2158 win32_setbuf(FILE *pf, char *buf)
2161 Perl_croak(aTHX_ PL_no_func, "setbuf");
2165 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
2167 return setvbuf(pf, buf, type, size);
2171 win32_flushall(void)
2177 win32_fcloseall(void)
2183 win32_fgets(char *s, int n, FILE *pf)
2185 return fgets(s, n, pf);
2195 win32_fgetc(FILE *pf)
2201 win32_putc(int c, FILE *pf)
2207 win32_puts(const char *s)
2219 win32_putchar(int c)
2226 #ifndef USE_PERL_SBRK
2228 static char *committed = NULL;
2229 static char *base = NULL;
2230 static char *reserved = NULL;
2231 static char *brk = NULL;
2232 static DWORD pagesize = 0;
2233 static DWORD allocsize = 0;
2241 GetSystemInfo(&info);
2242 /* Pretend page size is larger so we don't perpetually
2243 * call the OS to commit just one page ...
2245 pagesize = info.dwPageSize << 3;
2246 allocsize = info.dwAllocationGranularity;
2248 /* This scheme fails eventually if request for contiguous
2249 * block is denied so reserve big blocks - this is only
2250 * address space not memory ...
2252 if (brk+need >= reserved)
2254 DWORD size = 64*1024*1024;
2256 if (committed && reserved && committed < reserved)
2258 /* Commit last of previous chunk cannot span allocations */
2259 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
2261 committed = reserved;
2263 /* Reserve some (more) space
2264 * Note this is a little sneaky, 1st call passes NULL as reserved
2265 * so lets system choose where we start, subsequent calls pass
2266 * the old end address so ask for a contiguous block
2268 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
2271 reserved = addr+size;
2286 if (brk > committed)
2288 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
2289 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
2304 win32_malloc(size_t size)
2306 return malloc(size);
2310 win32_calloc(size_t numitems, size_t size)
2312 return calloc(numitems,size);
2316 win32_realloc(void *block, size_t size)
2318 return realloc(block,size);
2322 win32_free(void *block)
2328 win32_open_osfhandle(intptr_t osfhandle, int flags)
2331 char fileflags=0; /* _osfile flags */
2333 Perl_croak_nocontext("win32_open_osfhandle() TBD on this platform");
2338 win32_get_osfhandle(int fd)
2341 char fileflags=0; /* _osfile flags */
2343 Perl_croak_nocontext("win32_get_osfhandle() TBD on this platform");
2348 win32_fdupopen(FILE *pf)
2353 int fileno = win32_dup(win32_fileno(pf));
2354 int fmode = palm_fgetmode(pfdup);
2356 fprintf(stderr,"DEBUG for win32_fdupopen()\n");
2358 /* open the file in the same mode */
2359 if(fmode & O_RDONLY) {
2363 else if(fmode & O_APPEND) {
2367 else if(fmode & O_RDWR) {
2373 /* it appears that the binmode is attached to the
2374 * file descriptor so binmode files will be handled
2377 pfdup = win32_fdopen(fileno, mode);
2379 /* move the file pointer to the same position */
2380 if (!fgetpos(pf, &pos)) {
2381 fsetpos(pfdup, &pos);
2387 win32_dynaload(const char* filename)
2392 hModule = XCELoadLibraryA(filename);
2397 /* this is needed by Cwd.pm... */
2404 SV *sv = sv_newmortal();
2406 xcegetcwd(buf, sizeof(buf));
2408 sv_setpv(sv, xcestrdup(buf));
2412 #ifndef INCOMPLETE_TAINTS
2413 SvTAINTED_on(ST(0));
2424 Perl_croak(aTHX_ "usage: Win32::SetCwd($cwd)");
2426 if (!xcechdir(SvPV_nolen(ST(0))))
2433 XS(w32_GetTickCount)
2436 DWORD msec = GetTickCount();
2444 XS(w32_GetOSVersion)
2447 OSVERSIONINFOA osver;
2449 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOA);
2450 if (!XCEGetVersionExA(&osver)) {
2453 XPUSHs(newSVpvn(osver.szCSDVersion, strlen(osver.szCSDVersion)));
2454 XPUSHs(newSViv(osver.dwMajorVersion));
2455 XPUSHs(newSViv(osver.dwMinorVersion));
2456 XPUSHs(newSViv(osver.dwBuildNumber));
2458 XPUSHs(newSViv(osver.dwPlatformId));
2467 XSRETURN_IV(IsWinNT());
2475 XSRETURN_IV(IsWin95());
2483 XSRETURN_IV(IsWinCE());
2493 if(SystemParametersInfoW(SPI_GETOEMINFO, sizeof(wbuf), wbuf, FALSE))
2494 WideCharToMultiByte(CP_ACP, 0, wbuf, -1, buf, sizeof(buf), 0, 0);
2496 sprintf(buf, "SystemParametersInfo failed: %d", GetLastError());
2507 Perl_croak(aTHX_ "usage: Win32::Sleep($milliseconds)");
2518 Perl_croak(aTHX_ "usage: Win32::CopyFile($from, $to, $overwrite)");
2521 char szSourceFile[MAX_PATH+1];
2522 strcpy(szSourceFile, PerlDir_mapA(SvPV_nolen(ST(0))));
2523 bResult = XCECopyFileA(szSourceFile, SvPV_nolen(ST(1)),
2540 unsigned int flags = MB_OK;
2542 txt = SvPV_nolen(ST(0));
2544 if (items < 1 || items > 2)
2545 Perl_croak(aTHX_ "usage: Win32::MessageBox($txt, [$flags])");
2548 flags = SvIV(ST(1));
2550 res = XCEMessageBoxA(NULL, txt, "Perl", flags);
2556 XS(w32_GetPowerStatus)
2560 SYSTEM_POWER_STATUS_EX sps;
2562 if(GetSystemPowerStatusEx(&sps, TRUE) == FALSE)
2567 XPUSHs(newSViv(sps.ACLineStatus));
2568 XPUSHs(newSViv(sps.BatteryFlag));
2569 XPUSHs(newSViv(sps.BatteryLifePercent));
2570 XPUSHs(newSViv(sps.BatteryLifeTime));
2571 XPUSHs(newSViv(sps.BatteryFullLifeTime));
2572 XPUSHs(newSViv(sps.BackupBatteryFlag));
2573 XPUSHs(newSViv(sps.BackupBatteryLifePercent));
2574 XPUSHs(newSViv(sps.BackupBatteryLifeTime));
2575 XPUSHs(newSViv(sps.BackupBatteryFullLifeTime));
2587 SHELLEXECUTEINFO si;
2589 wchar_t wfile[MAX_PATH];
2593 Perl_croak(aTHX_ "usage: Win32::ShellEx($file, $verb)");
2595 file = SvPV_nolen(ST(0));
2596 verb = SvPV_nolen(ST(1));
2598 memset(&si, 0, sizeof(si));
2599 si.cbSize = sizeof(si);
2600 si.fMask = SEE_MASK_FLAG_NO_UI;
2602 MultiByteToWideChar(CP_ACP, 0, verb, -1,
2603 wverb, sizeof(wverb)/2);
2604 si.lpVerb = (TCHAR *)wverb;
2606 MultiByteToWideChar(CP_ACP, 0, file, -1,
2607 wfile, sizeof(wfile)/2);
2608 si.lpFile = (TCHAR *)wfile;
2610 if(ShellExecuteEx(&si) == FALSE)
2619 Perl_init_os_extras(void)
2622 char *file = __FILE__;
2625 w32_perlshell_tokens = Nullch;
2626 w32_perlshell_items = -1;
2627 w32_fdpid = newAV(); /* XX needs to be in Perl_win32_init()? */
2628 New(1313, w32_children, 1, child_tab);
2629 w32_num_children = 0;
2631 newXS("Win32::GetCwd", w32_GetCwd, file);
2632 newXS("Win32::SetCwd", w32_SetCwd, file);
2633 newXS("Win32::GetTickCount", w32_GetTickCount, file);
2634 newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
2636 newXS("Win32::ShellEx", w32_ShellEx, file);
2638 newXS("Win32::IsWinNT", w32_IsWinNT, file);
2639 newXS("Win32::IsWin95", w32_IsWin95, file);
2640 newXS("Win32::IsWinCE", w32_IsWinCE, file);
2641 newXS("Win32::CopyFile", w32_CopyFile, file);
2642 newXS("Win32::Sleep", w32_Sleep, file);
2643 newXS("Win32::MessageBox", w32_MessageBox, file);
2644 newXS("Win32::GetPowerStatus", w32_GetPowerStatus, file);
2645 newXS("Win32::GetOemInfo", w32_GetOemInfo, file);
2654 fgets(buf, sizeof(buf), stdin);
2658 Perl_win32_init(int *argcp, char ***argvp)
2663 if((p = xcegetenv("PERLDEBUG")) && (p[0] == 'y' || p[0] == 'Y'))
2671 Perl_win32_term(void)
2678 win32_get_child_IO(child_IO_table* ptbl)
2680 ptbl->childStdIn = GetStdHandle(STD_INPUT_HANDLE);
2681 ptbl->childStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
2682 ptbl->childStdErr = GetStdHandle(STD_ERROR_HANDLE);
2685 win32_flock(int fd, int oper)
2688 Perl_croak(aTHX_ PL_no_func, "flock");
2693 win32_waitpid(int pid, int *status, int flags)
2696 Perl_croak(aTHX_ PL_no_func, "waitpid");
2701 win32_wait(int *status)
2704 Perl_croak(aTHX_ PL_no_func, "wait");
2709 wce_reopen_stdout(char *fname)
2711 if(xcefreopen(fname, "w", stdout) == NULL)
2722 printf("Hit RETURN");
2724 fgets(buf, sizeof(buf), stdin);
2728 /* //////////////////////////////////////////////////////////////////// */
2733 getcwd(char *buf, size_t size)
2735 return xcegetcwd(buf, size);
2746 win32_popenlist(const char *mode, IV narg, SV **args)
2749 Perl_croak(aTHX_ "List form of pipe open not implemented");
2754 * a popen() clone that respects PERL5SHELL
2756 * changed to return PerlIO* rather than FILE * by BKS, 11-11-2000
2760 win32_popen(const char *command, const char *mode)
2762 #ifdef USE_RTL_POPEN
2763 return _popen(command, mode);
2775 /* establish which ends read and write */
2776 if (strchr(mode,'w')) {
2777 stdfd = 0; /* stdin */
2780 nhandle = STD_INPUT_HANDLE;
2782 else if (strchr(mode,'r')) {
2783 stdfd = 1; /* stdout */
2786 nhandle = STD_OUTPUT_HANDLE;
2791 /* set the correct mode */
2792 if (strchr(mode,'b'))
2794 else if (strchr(mode,'t'))
2797 ourmode = _fmode & (O_TEXT | O_BINARY);
2799 /* the child doesn't inherit handles */
2800 ourmode |= O_NOINHERIT;
2802 if (win32_pipe(p, 512, ourmode) == -1)
2805 /* save current stdfd */
2806 if ((oldfd = win32_dup(stdfd)) == -1)
2809 /* save the old std handle (this needs to happen before the
2810 * dup2(), since that might call SetStdHandle() too) */
2813 old_h = GetStdHandle(nhandle);
2815 /* make stdfd go to child end of pipe (implicitly closes stdfd) */
2816 /* stdfd will be inherited by the child */
2817 if (win32_dup2(p[child], stdfd) == -1)
2820 /* close the child end in parent */
2821 win32_close(p[child]);
2823 /* set the new std handle (in case dup2() above didn't) */
2824 SetStdHandle(nhandle, (HANDLE)_get_osfhandle(stdfd));
2826 /* start the child */
2829 if ((childpid = do_spawn_nowait((char*)command)) == -1)
2832 /* revert stdfd to whatever it was before */
2833 if (win32_dup2(oldfd, stdfd) == -1)
2836 /* restore the old std handle (this needs to happen after the
2837 * dup2(), since that might call SetStdHandle() too */
2839 SetStdHandle(nhandle, old_h);
2844 /* close saved handle */
2848 sv_setiv(*av_fetch(w32_fdpid, p[parent], TRUE), childpid);
2851 /* set process id so that it can be returned by perl's open() */
2852 PL_forkprocess = childpid;
2855 /* we have an fd, return a file stream */
2856 return (PerlIO_fdopen(p[parent], (char *)mode));
2859 /* we don't need to check for errors here */
2863 SetStdHandle(nhandle, old_h);
2868 win32_dup2(oldfd, stdfd);
2873 #endif /* USE_RTL_POPEN */
2881 win32_pclose(PerlIO *pf)
2883 #ifdef USE_RTL_POPEN
2887 int childpid, status;
2891 sv = *av_fetch(w32_fdpid, PerlIO_fileno(pf), TRUE);
2894 childpid = SvIVX(sv);
2911 if (win32_waitpid(childpid, &status, 0) == -1)
2916 #endif /* USE_RTL_POPEN */
2919 #ifdef HAVE_INTERP_INTERN
2923 win32_csighandler(int sig)
2926 dTHXa(PERL_GET_SIG_CONTEXT);
2927 Perl_warn(aTHX_ "Got signal %d",sig);
2933 Perl_sys_intern_init(pTHX)
2936 w32_perlshell_tokens = Nullch;
2937 w32_perlshell_vec = (char**)NULL;
2938 w32_perlshell_items = 0;
2939 w32_fdpid = newAV();
2940 New(1313, w32_children, 1, child_tab);
2941 w32_num_children = 0;
2942 # ifdef USE_ITHREADS
2944 New(1313, w32_pseudo_children, 1, child_tab);
2945 w32_num_pseudo_children = 0;
2947 w32_init_socktype = 0;
2953 Perl_sys_intern_clear(pTHX)
2955 Safefree(w32_perlshell_tokens);
2956 Safefree(w32_perlshell_vec);
2957 /* NOTE: w32_fdpid is freed by sv_clean_all() */
2958 Safefree(w32_children);
2960 KillTimer(NULL,w32_timerid);
2963 # ifdef USE_ITHREADS
2964 Safefree(w32_pseudo_children);
2968 # ifdef USE_ITHREADS
2971 Perl_sys_intern_dup(pTHX_ struct interp_intern *src, struct interp_intern *dst)
2973 dst->perlshell_tokens = Nullch;
2974 dst->perlshell_vec = (char**)NULL;
2975 dst->perlshell_items = 0;
2976 dst->fdpid = newAV();
2977 Newz(1313, dst->children, 1, child_tab);
2979 Newz(1313, dst->pseudo_children, 1, child_tab);
2980 dst->thr_intern.Winit_socktype = 0;
2982 dst->poll_count = 0;
2983 Copy(src->sigtable,dst->sigtable,SIG_SIZE,Sighandler_t);
2985 # endif /* USE_ITHREADS */
2986 #endif /* HAVE_INTERP_INTERN */
2989 win32_free_argvw(pTHX_ void *ptr)
2991 char** argv = (char**)ptr;
2999 win32_argv2utf8(int argc, char** argv)
3001 /* do nothing, since we're not aware of command line arguments
3008 Perl_sys_intern_clear(pTHX)
3010 Safefree(w32_perlshell_tokens);
3011 Safefree(w32_perlshell_vec);
3012 /* NOTE: w32_fdpid is freed by sv_clean_all() */
3013 Safefree(w32_children);
3014 # ifdef USE_ITHREADS
3015 Safefree(w32_pseudo_children);
3020 // added to remove undefied symbol error in CodeWarrior compilation
3022 Perl_Ireentrant_buffer_ptr(aTHX)