3 * (c) 1995 Microsoft Corporation. All rights reserved.
4 * Developed by hip communications inc., http://info.hip.com/info/
5 * Portions (c) 1993 Intergraph Corporation. All rights reserved.
7 * You may distribute under the terms of either the GNU General Public
8 * License or the Artistic License, as specified in the README file.
11 #define WIN32_LEAN_AND_MEAN
12 #define WIN32IO_IS_STDIO
18 #ifndef __MINGW32__ /* GCC/Mingw32-2.95.2 forgot the WINAPI on CommandLineToArgvW() */
19 # include <shellapi.h>
21 LPWSTR* WINAPI CommandLineToArgvW(LPCWSTR lpCommandLine, int * pNumArgs);
26 /* #include "config.h" */
28 #define PERLIO_NOT_STDIO 0
29 #if !defined(PERLIO_IS_STDIO) && !defined(USE_SFIO)
38 #define PERL_NO_GET_CONTEXT
44 /* assert.h conflicts with #define of assert in perl.h */
51 #if defined(_MSC_VER) || defined(__MINGW32__)
52 #include <sys/utime.h>
57 /* Mingw32 defaults to globing command line
58 * So we turn it off like this:
63 #if defined(__MINGW32__)
64 /* Mingw32 is missing some prototypes */
65 FILE * _wfopen(LPCWSTR wszFileName, LPCWSTR wszMode);
66 FILE * _wfdopen(int nFd, LPCWSTR wszMode);
67 FILE * _freopen(LPCWSTR wszFileName, LPCWSTR wszMode, FILE * pOldStream);
72 #if defined(__BORLANDC__)
74 # define _utimbuf utimbuf
79 #define EXECF_SPAWN_NOWAIT 3
81 #if defined(PERL_IMPLICIT_SYS)
82 # undef win32_get_privlib
83 # define win32_get_privlib g_win32_get_privlib
84 # undef win32_get_sitelib
85 # define win32_get_sitelib g_win32_get_sitelib
86 # undef win32_get_vendorlib
87 # define win32_get_vendorlib g_win32_get_vendorlib
89 # define do_spawn g_do_spawn
91 # define getlogin g_getlogin
94 #if defined(PERL_OBJECT)
96 # define do_aspawn g_do_aspawn
98 # define Perl_do_exec g_do_exec
101 static void get_shell(void);
102 static long tokenize(const char *str, char **dest, char ***destv);
103 int do_spawn2(char *cmd, int exectype);
104 static BOOL has_shell_metachars(char *ptr);
105 static long filetime_to_clock(PFILETIME ft);
106 static BOOL filetime_from_time(PFILETIME ft, time_t t);
107 static char * get_emd_part(SV **leading, char *trailing, ...);
108 static void remove_dead_process(long deceased);
109 static long find_pid(int pid);
110 static char * qualified_path(const char *cmd);
111 static char * win32_get_xlib(const char *pl, const char *xlib,
112 const char *libname);
115 static void remove_dead_pseudo_process(long child);
116 static long find_pseudo_pid(int pid);
120 HANDLE w32_perldll_handle = INVALID_HANDLE_VALUE;
121 char w32_module_name[MAX_PATH+1];
124 static DWORD w32_platform = (DWORD)-1;
126 #define ONE_K_BUFSIZE 1024
131 return (win32_os_id() == VER_PLATFORM_WIN32_WINDOWS);
137 return (win32_os_id() == VER_PLATFORM_WIN32_NT);
141 set_w32_module_name(void)
144 GetModuleFileName((HMODULE)((w32_perldll_handle == INVALID_HANDLE_VALUE)
145 ? GetModuleHandle(NULL)
146 : w32_perldll_handle),
147 w32_module_name, sizeof(w32_module_name));
149 /* try to get full path to binary (which may be mangled when perl is
150 * run from a 16-bit app) */
151 /*PerlIO_printf(Perl_debug_log, "Before %s\n", w32_module_name);*/
152 (void)win32_longpath(w32_module_name);
153 /*PerlIO_printf(Perl_debug_log, "After %s\n", w32_module_name);*/
155 /* normalize to forward slashes */
156 ptr = w32_module_name;
164 /* *svp (if non-NULL) is expected to be POK (valid allocated SvPVX(*svp)) */
166 get_regstr_from(HKEY hkey, const char *valuename, SV **svp)
168 /* Retrieve a REG_SZ or REG_EXPAND_SZ from the registry */
171 const char *subkey = "Software\\Perl";
175 retval = RegOpenKeyEx(hkey, subkey, 0, KEY_READ, &handle);
176 if (retval == ERROR_SUCCESS) {
178 retval = RegQueryValueEx(handle, valuename, 0, &type, NULL, &datalen);
179 if (retval == ERROR_SUCCESS
180 && (type == REG_SZ || type == REG_EXPAND_SZ))
184 *svp = sv_2mortal(newSVpvn("",0));
185 SvGROW(*svp, datalen);
186 retval = RegQueryValueEx(handle, valuename, 0, NULL,
187 (PBYTE)SvPVX(*svp), &datalen);
188 if (retval == ERROR_SUCCESS) {
190 SvCUR_set(*svp,datalen-1);
198 /* *svp (if non-NULL) is expected to be POK (valid allocated SvPVX(*svp)) */
200 get_regstr(const char *valuename, SV **svp)
202 char *str = get_regstr_from(HKEY_CURRENT_USER, valuename, svp);
204 str = get_regstr_from(HKEY_LOCAL_MACHINE, valuename, svp);
208 /* *prev_pathp (if non-NULL) is expected to be POK (valid allocated SvPVX(sv)) */
210 get_emd_part(SV **prev_pathp, char *trailing_path, ...)
214 char mod_name[MAX_PATH+1];
218 int oldsize, newsize;
221 va_start(ap, trailing_path);
222 strip = va_arg(ap, char *);
224 sprintf(base, "%d.%d", (int)PERL_REVISION, (int)PERL_VERSION);
225 baselen = strlen(base);
227 if (!*w32_module_name) {
228 set_w32_module_name();
230 strcpy(mod_name, w32_module_name);
231 ptr = strrchr(mod_name, '/');
232 while (ptr && strip) {
233 /* look for directories to skip back */
236 ptr = strrchr(mod_name, '/');
237 /* avoid stripping component if there is no slash,
238 * or it doesn't match ... */
239 if (!ptr || stricmp(ptr+1, strip) != 0) {
240 /* ... but not if component matches m|5\.$patchlevel.*| */
241 if (!ptr || !(*strip == '5' && *(ptr+1) == '5'
242 && strncmp(strip, base, baselen) == 0
243 && strncmp(ptr+1, base, baselen) == 0))
249 strip = va_arg(ap, char *);
257 strcpy(++ptr, trailing_path);
259 /* only add directory if it exists */
260 if (GetFileAttributes(mod_name) != (DWORD) -1) {
261 /* directory exists */
264 *prev_pathp = sv_2mortal(newSVpvn("",0));
265 sv_catpvn(*prev_pathp, ";", 1);
266 sv_catpv(*prev_pathp, mod_name);
267 return SvPVX(*prev_pathp);
274 win32_get_privlib(const char *pl)
277 char *stdlib = "lib";
278 char buffer[MAX_PATH+1];
281 /* $stdlib = $HKCU{"lib-$]"} || $HKLM{"lib-$]"} || $HKCU{"lib"} || $HKLM{"lib"} || ""; */
282 sprintf(buffer, "%s-%s", stdlib, pl);
283 if (!get_regstr(buffer, &sv))
284 (void)get_regstr(stdlib, &sv);
286 /* $stdlib .= ";$EMD/../../lib" */
287 return get_emd_part(&sv, stdlib, ARCHNAME, "bin", Nullch);
291 win32_get_xlib(const char *pl, const char *xlib, const char *libname)
295 char pathstr[MAX_PATH+1];
301 /* $HKCU{"$xlib-$]"} || $HKLM{"$xlib-$]"} . ---; */
302 sprintf(regstr, "%s-%s", xlib, pl);
303 (void)get_regstr(regstr, &sv1);
306 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/$libname/$]/lib"; */
307 sprintf(pathstr, "%s/%s/lib", libname, pl);
308 (void)get_emd_part(&sv1, pathstr, ARCHNAME, "bin", pl, Nullch);
310 /* $HKCU{$xlib} || $HKLM{$xlib} . ---; */
311 (void)get_regstr(xlib, &sv2);
314 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/$libname/lib"; */
315 sprintf(pathstr, "%s/lib", libname);
316 (void)get_emd_part(&sv2, pathstr, ARCHNAME, "bin", pl, Nullch);
325 sv_catpvn(sv1, ";", 1);
332 win32_get_sitelib(const char *pl)
334 return win32_get_xlib(pl, "sitelib", "site");
337 #ifndef PERL_VENDORLIB_NAME
338 # define PERL_VENDORLIB_NAME "vendor"
342 win32_get_vendorlib(const char *pl)
344 return win32_get_xlib(pl, "vendorlib", PERL_VENDORLIB_NAME);
348 has_shell_metachars(char *ptr)
354 * Scan string looking for redirection (< or >) or pipe
355 * characters (|) that are not in a quoted string.
356 * Shell variable interpolation (%VAR%) can also happen inside strings.
388 #if !defined(PERL_IMPLICIT_SYS)
389 /* since the current process environment is being updated in util.c
390 * the library functions will get the correct environment
393 Perl_my_popen(pTHX_ char *cmd, char *mode)
396 #define fixcmd(x) { \
397 char *pspace = strchr((x),' '); \
400 while (p < pspace) { \
411 PERL_FLUSHALL_FOR_CHILD;
412 return win32_popen(cmd, mode);
416 Perl_my_pclose(pTHX_ PerlIO *fp)
418 return win32_pclose(fp);
422 DllExport unsigned long
425 static OSVERSIONINFO osver;
427 if (osver.dwPlatformId != w32_platform) {
428 memset(&osver, 0, sizeof(OSVERSIONINFO));
429 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
430 GetVersionEx(&osver);
431 w32_platform = osver.dwPlatformId;
433 return (unsigned long)w32_platform;
443 return -((int)w32_pseudo_id);
446 /* Windows 9x appears to always reports a pid for threads and processes
447 * that has the high bit set. So we treat the lower 31 bits as the
448 * "real" PID for Perl's purposes. */
449 if (IsWin95() && pid < 0)
454 /* Tokenize a string. Words are null-separated, and the list
455 * ends with a doubled null. Any character (except null and
456 * including backslash) may be escaped by preceding it with a
457 * backslash (the backslash will be stripped).
458 * Returns number of words in result buffer.
461 tokenize(const char *str, char **dest, char ***destv)
463 char *retstart = Nullch;
464 char **retvstart = 0;
468 int slen = strlen(str);
470 register char **retv;
471 New(1307, ret, slen+2, char);
472 New(1308, retv, (slen+3)/2, char*);
480 if (*ret == '\\' && *str)
482 else if (*ret == ' ') {
498 retvstart[items] = Nullch;
511 if (!w32_perlshell_tokens) {
512 /* we don't use COMSPEC here for two reasons:
513 * 1. the same reason perl on UNIX doesn't use SHELL--rampant and
514 * uncontrolled unportability of the ensuing scripts.
515 * 2. PERL5SHELL could be set to a shell that may not be fit for
516 * interactive use (which is what most programs look in COMSPEC
519 const char* defaultshell = (IsWinNT()
520 ? "cmd.exe /x/c" : "command.com /c");
521 const char *usershell = getenv("PERL5SHELL");
522 w32_perlshell_items = tokenize(usershell ? usershell : defaultshell,
523 &w32_perlshell_tokens,
529 do_aspawn(void *vreally, void **vmark, void **vsp)
532 SV *really = (SV*)vreally;
533 SV **mark = (SV**)vmark;
545 New(1306, argv, (sp - mark) + w32_perlshell_items + 2, char*);
547 if (SvNIOKp(*(mark+1)) && !SvPOKp(*(mark+1))) {
552 while (++mark <= sp) {
553 if (*mark && (str = SvPV_nolen(*mark)))
560 status = win32_spawnvp(flag,
561 (const char*)(really ? SvPV_nolen(really) : argv[0]),
562 (const char* const*)argv);
564 if (status < 0 && (errno == ENOEXEC || errno == ENOENT)) {
565 /* possible shell-builtin, invoke with shell */
567 sh_items = w32_perlshell_items;
569 argv[index+sh_items] = argv[index];
570 while (--sh_items >= 0)
571 argv[sh_items] = w32_perlshell_vec[sh_items];
573 status = win32_spawnvp(flag,
574 (const char*)(really ? SvPV_nolen(really) : argv[0]),
575 (const char* const*)argv);
578 if (flag == P_NOWAIT) {
580 PL_statusvalue = -1; /* >16bits hint for pp_system() */
584 if (ckWARN(WARN_EXEC))
585 Perl_warner(aTHX_ WARN_EXEC, "Can't spawn \"%s\": %s", argv[0], strerror(errno));
590 PL_statusvalue = status;
597 do_spawn2(char *cmd, int exectype)
604 BOOL needToTry = TRUE;
607 /* Save an extra exec if possible. See if there are shell
608 * metacharacters in it */
609 if (!has_shell_metachars(cmd)) {
610 New(1301,argv, strlen(cmd) / 2 + 2, char*);
611 New(1302,cmd2, strlen(cmd) + 1, char);
614 for (s = cmd2; *s;) {
615 while (*s && isSPACE(*s))
619 while (*s && !isSPACE(*s))
628 status = win32_spawnvp(P_WAIT, argv[0],
629 (const char* const*)argv);
631 case EXECF_SPAWN_NOWAIT:
632 status = win32_spawnvp(P_NOWAIT, argv[0],
633 (const char* const*)argv);
636 status = win32_execvp(argv[0], (const char* const*)argv);
639 if (status != -1 || errno == 0)
649 New(1306, argv, w32_perlshell_items + 2, char*);
650 while (++i < w32_perlshell_items)
651 argv[i] = w32_perlshell_vec[i];
656 status = win32_spawnvp(P_WAIT, argv[0],
657 (const char* const*)argv);
659 case EXECF_SPAWN_NOWAIT:
660 status = win32_spawnvp(P_NOWAIT, argv[0],
661 (const char* const*)argv);
664 status = win32_execvp(argv[0], (const char* const*)argv);
670 if (exectype == EXECF_SPAWN_NOWAIT) {
672 PL_statusvalue = -1; /* >16bits hint for pp_system() */
676 if (ckWARN(WARN_EXEC))
677 Perl_warner(aTHX_ WARN_EXEC, "Can't %s \"%s\": %s",
678 (exectype == EXECF_EXEC ? "exec" : "spawn"),
679 cmd, strerror(errno));
684 PL_statusvalue = status;
692 return do_spawn2(cmd, EXECF_SPAWN);
696 do_spawn_nowait(char *cmd)
698 return do_spawn2(cmd, EXECF_SPAWN_NOWAIT);
702 Perl_do_exec(pTHX_ char *cmd)
704 do_spawn2(cmd, EXECF_EXEC);
708 /* The idea here is to read all the directory names into a string table
709 * (separated by nulls) and when one of the other dir functions is called
710 * return the pointer to the current file name.
713 win32_opendir(char *filename)
719 char scanname[MAX_PATH+3];
721 WIN32_FIND_DATAA aFindData;
722 WIN32_FIND_DATAW wFindData;
724 char buffer[MAX_PATH*2];
725 WCHAR wbuffer[MAX_PATH+1];
728 len = strlen(filename);
732 /* check to see if filename is a directory */
733 if (win32_stat(filename, &sbuf) < 0 || !S_ISDIR(sbuf.st_mode))
736 /* Get us a DIR structure */
737 Newz(1303, dirp, 1, DIR);
739 /* Create the search pattern */
740 strcpy(scanname, filename);
742 /* bare drive name means look in cwd for drive */
743 if (len == 2 && isALPHA(scanname[0]) && scanname[1] == ':') {
744 scanname[len++] = '.';
745 scanname[len++] = '/';
747 else if (scanname[len-1] != '/' && scanname[len-1] != '\\') {
748 scanname[len++] = '/';
750 scanname[len++] = '*';
751 scanname[len] = '\0';
753 /* do the FindFirstFile call */
755 A2WHELPER(scanname, wbuffer, sizeof(wbuffer));
756 fh = FindFirstFileW(PerlDir_mapW(wbuffer), &wFindData);
759 fh = FindFirstFileA(PerlDir_mapA(scanname), &aFindData);
762 if (fh == INVALID_HANDLE_VALUE) {
763 DWORD err = GetLastError();
764 /* FindFirstFile() fails on empty drives! */
766 case ERROR_FILE_NOT_FOUND:
768 case ERROR_NO_MORE_FILES:
769 case ERROR_PATH_NOT_FOUND:
772 case ERROR_NOT_ENOUGH_MEMORY:
783 /* now allocate the first part of the string table for
784 * the filenames that we find.
787 W2AHELPER(wFindData.cFileName, buffer, sizeof(buffer));
791 ptr = aFindData.cFileName;
798 New(1304, dirp->start, dirp->size, char);
799 strcpy(dirp->start, ptr);
801 dirp->end = dirp->curr = dirp->start;
807 /* Readdir just returns the current string pointer and bumps the
808 * string pointer to the nDllExport entry.
810 DllExport struct direct *
811 win32_readdir(DIR *dirp)
816 /* first set up the structure to return */
817 len = strlen(dirp->curr);
818 strcpy(dirp->dirstr.d_name, dirp->curr);
819 dirp->dirstr.d_namlen = len;
822 dirp->dirstr.d_ino = dirp->curr - dirp->start;
824 /* Now set up for the next call to readdir */
825 dirp->curr += len + 1;
826 if (dirp->curr >= dirp->end) {
830 WIN32_FIND_DATAW wFindData;
831 WIN32_FIND_DATAA aFindData;
832 char buffer[MAX_PATH*2];
834 /* finding the next file that matches the wildcard
835 * (which should be all of them in this directory!).
838 res = FindNextFileW(dirp->handle, &wFindData);
840 W2AHELPER(wFindData.cFileName, buffer, sizeof(buffer));
845 res = FindNextFileA(dirp->handle, &aFindData);
847 ptr = aFindData.cFileName;
850 long endpos = dirp->end - dirp->start;
851 long newsize = endpos + strlen(ptr) + 1;
852 /* bump the string table size by enough for the
853 * new name and it's null terminator */
854 while (newsize > dirp->size) {
855 long curpos = dirp->curr - dirp->start;
857 Renew(dirp->start, dirp->size, char);
858 dirp->curr = dirp->start + curpos;
860 strcpy(dirp->start + endpos, ptr);
861 dirp->end = dirp->start + newsize;
867 return &(dirp->dirstr);
873 /* Telldir returns the current string pointer position */
875 win32_telldir(DIR *dirp)
877 return (dirp->curr - dirp->start);
881 /* Seekdir moves the string pointer to a previously saved position
882 * (returned by telldir).
885 win32_seekdir(DIR *dirp, long loc)
887 dirp->curr = dirp->start + loc;
890 /* Rewinddir resets the string pointer to the start */
892 win32_rewinddir(DIR *dirp)
894 dirp->curr = dirp->start;
897 /* free the memory allocated by opendir */
899 win32_closedir(DIR *dirp)
902 if (dirp->handle != INVALID_HANDLE_VALUE)
903 FindClose(dirp->handle);
904 Safefree(dirp->start);
917 * Just pretend that everyone is a superuser. NT will let us know if
918 * we don\'t really have permission to do something.
921 #define ROOT_UID ((uid_t)0)
922 #define ROOT_GID ((gid_t)0)
951 return (auid == ROOT_UID ? 0 : -1);
957 return (agid == ROOT_GID ? 0 : -1);
964 char *buf = w32_getlogin_buffer;
965 DWORD size = sizeof(w32_getlogin_buffer);
966 if (GetUserName(buf,&size))
972 chown(const char *path, uid_t owner, gid_t group)
979 * XXX this needs strengthening (for PerlIO)
982 int mkstemp(const char *path)
985 char buf[MAX_PATH+1];
989 if (i++ > 10) { /* give up */
993 if (!GetTempFileNameA((LPCSTR)path, "plr", 1, buf)) {
997 fd = PerlLIO_open3(buf, O_CREAT|O_RDWR|O_EXCL, 0600);
1007 long child = w32_num_children;
1008 while (--child >= 0) {
1009 if (w32_child_pids[child] == pid)
1016 remove_dead_process(long child)
1020 CloseHandle(w32_child_handles[child]);
1021 Move(&w32_child_handles[child+1], &w32_child_handles[child],
1022 (w32_num_children-child-1), HANDLE);
1023 Move(&w32_child_pids[child+1], &w32_child_pids[child],
1024 (w32_num_children-child-1), DWORD);
1031 find_pseudo_pid(int pid)
1034 long child = w32_num_pseudo_children;
1035 while (--child >= 0) {
1036 if (w32_pseudo_child_pids[child] == pid)
1043 remove_dead_pseudo_process(long child)
1047 CloseHandle(w32_pseudo_child_handles[child]);
1048 Move(&w32_pseudo_child_handles[child+1], &w32_pseudo_child_handles[child],
1049 (w32_num_pseudo_children-child-1), HANDLE);
1050 Move(&w32_pseudo_child_pids[child+1], &w32_pseudo_child_pids[child],
1051 (w32_num_pseudo_children-child-1), DWORD);
1052 w32_num_pseudo_children--;
1058 win32_kill(int pid, int sig)
1065 /* it is a pseudo-forked child */
1066 child = find_pseudo_pid(-pid);
1070 hProcess = w32_pseudo_child_handles[child];
1071 if (TerminateThread(hProcess, sig)) {
1072 remove_dead_pseudo_process(child);
1076 else if (IsWin95()) {
1084 child = find_pid(pid);
1088 hProcess = w32_child_handles[child];
1089 if (TerminateProcess(hProcess, sig)) {
1090 remove_dead_process(child);
1096 hProcess = OpenProcess(PROCESS_ALL_ACCESS, TRUE,
1097 (IsWin95() ? -pid : pid));
1101 if (TerminateProcess(hProcess, sig)) {
1102 CloseHandle(hProcess);
1116 DllExport unsigned int
1117 win32_sleep(unsigned int t)
1124 win32_stat(const char *path, struct stat *sbuf)
1127 char buffer[MAX_PATH+1];
1128 int l = strlen(path);
1130 WCHAR wbuffer[MAX_PATH+1];
1136 switch(path[l - 1]) {
1137 /* FindFirstFile() and stat() are buggy with a trailing
1138 * backslash, so change it to a forward slash :-( */
1140 strncpy(buffer, path, l-1);
1141 buffer[l - 1] = '/';
1145 /* FindFirstFile() is buggy with "x:", so add a dot :-( */
1147 if (l == 2 && isALPHA(path[0])) {
1148 buffer[0] = path[0];
1159 /* We *must* open & close the file once; otherwise file attribute changes */
1160 /* might not yet have propagated to "other" hard links of the same file. */
1161 /* This also gives us an opportunity to determine the number of links. */
1163 A2WHELPER(path, wbuffer, sizeof(wbuffer));
1164 pwbuffer = PerlDir_mapW(wbuffer);
1165 handle = CreateFileW(pwbuffer, 0, 0, NULL, OPEN_EXISTING, 0, NULL);
1168 path = PerlDir_mapA(path);
1170 handle = CreateFileA(path, 0, 0, NULL, OPEN_EXISTING, 0, NULL);
1172 if (handle != INVALID_HANDLE_VALUE) {
1173 BY_HANDLE_FILE_INFORMATION bhi;
1174 if (GetFileInformationByHandle(handle, &bhi))
1175 nlink = bhi.nNumberOfLinks;
1176 CloseHandle(handle);
1179 /* pwbuffer or path will be mapped correctly above */
1181 res = _wstat(pwbuffer, (struct _stat *)sbuf);
1184 res = stat(path, sbuf);
1186 sbuf->st_nlink = nlink;
1189 /* CRT is buggy on sharenames, so make sure it really isn't.
1190 * XXX using GetFileAttributesEx() will enable us to set
1191 * sbuf->st_*time (but note that's not available on the
1192 * Windows of 1995) */
1195 r = GetFileAttributesW(pwbuffer);
1198 r = GetFileAttributesA(path);
1200 if (r != 0xffffffff && (r & FILE_ATTRIBUTE_DIRECTORY)) {
1201 /* sbuf may still contain old garbage since stat() failed */
1202 Zero(sbuf, 1, struct stat);
1203 sbuf->st_mode = S_IFDIR | S_IREAD;
1205 if (!(r & FILE_ATTRIBUTE_READONLY))
1206 sbuf->st_mode |= S_IWRITE | S_IEXEC;
1211 if (l == 3 && isALPHA(path[0]) && path[1] == ':'
1212 && (path[2] == '\\' || path[2] == '/'))
1214 /* The drive can be inaccessible, some _stat()s are buggy */
1216 ? !GetVolumeInformationW(pwbuffer,NULL,0,NULL,NULL,NULL,NULL,0)
1217 : !GetVolumeInformationA(path,NULL,0,NULL,NULL,NULL,NULL,0)) {
1223 if (S_ISDIR(sbuf->st_mode))
1224 sbuf->st_mode |= S_IWRITE | S_IEXEC;
1225 else if (S_ISREG(sbuf->st_mode)) {
1227 if (l >= 4 && path[l-4] == '.') {
1228 const char *e = path + l - 3;
1229 if (strnicmp(e,"exe",3)
1230 && strnicmp(e,"bat",3)
1231 && strnicmp(e,"com",3)
1232 && (IsWin95() || strnicmp(e,"cmd",3)))
1233 sbuf->st_mode &= ~S_IEXEC;
1235 sbuf->st_mode |= S_IEXEC;
1238 sbuf->st_mode &= ~S_IEXEC;
1239 /* Propagate permissions to _group_ and _others_ */
1240 perms = sbuf->st_mode & (S_IREAD|S_IWRITE|S_IEXEC);
1241 sbuf->st_mode |= (perms>>3) | (perms>>6);
1248 /* Find the longname of a given path. path is destructively modified.
1249 * It should have space for at least MAX_PATH characters. */
1251 win32_longpath(char *path)
1253 WIN32_FIND_DATA fdata;
1255 char tmpbuf[MAX_PATH+1];
1256 char *tmpstart = tmpbuf;
1263 if (isALPHA(path[0]) && path[1] == ':' &&
1264 (path[2] == '/' || path[2] == '\\'))
1267 *tmpstart++ = path[0];
1271 else if ((path[0] == '/' || path[0] == '\\') &&
1272 (path[1] == '/' || path[1] == '\\'))
1275 *tmpstart++ = path[0];
1276 *tmpstart++ = path[1];
1277 /* copy machine name */
1278 while (*start && *start != '/' && *start != '\\')
1279 *tmpstart++ = *start++;
1281 *tmpstart++ = *start;
1283 /* copy share name */
1284 while (*start && *start != '/' && *start != '\\')
1285 *tmpstart++ = *start++;
1289 if (sep == '/' || sep == '\\')
1293 /* walk up to slash */
1294 while (*start && *start != '/' && *start != '\\')
1297 /* discard doubled slashes */
1298 while (*start && (start[1] == '/' || start[1] == '\\'))
1302 /* stop and find full name of component */
1304 fhand = FindFirstFile(path,&fdata);
1305 if (fhand != INVALID_HANDLE_VALUE) {
1306 strcpy(tmpstart, fdata.cFileName);
1307 tmpstart += strlen(fdata.cFileName);
1315 /* failed a step, just return without side effects */
1316 /*PerlIO_printf(Perl_debug_log, "Failed to find %s\n", path);*/
1321 strcpy(path,tmpbuf);
1326 win32_getenv(const char *name)
1329 WCHAR wBuffer[MAX_PATH+1];
1331 SV *curitem = Nullsv;
1334 A2WHELPER(name, wBuffer, sizeof(wBuffer));
1335 needlen = GetEnvironmentVariableW(wBuffer, NULL, 0);
1338 needlen = GetEnvironmentVariableA(name,NULL,0);
1340 curitem = sv_2mortal(newSVpvn("", 0));
1344 SvGROW(curitem, (needlen+1)*sizeof(WCHAR));
1345 needlen = GetEnvironmentVariableW(wBuffer,
1346 (WCHAR*)SvPVX(curitem),
1348 } while (needlen >= SvLEN(curitem)/sizeof(WCHAR));
1349 SvCUR_set(curitem, (needlen*sizeof(WCHAR))+1);
1350 acuritem = sv_2mortal(newSVsv(curitem));
1351 W2AHELPER((WCHAR*)SvPVX(acuritem), SvPVX(curitem), SvCUR(curitem));
1355 SvGROW(curitem, needlen+1);
1356 needlen = GetEnvironmentVariableA(name,SvPVX(curitem),
1358 } while (needlen >= SvLEN(curitem));
1359 SvCUR_set(curitem, needlen);
1363 /* allow any environment variables that begin with 'PERL'
1364 to be stored in the registry */
1365 if (strncmp(name, "PERL", 4) == 0)
1366 (void)get_regstr(name, &curitem);
1368 if (curitem && SvCUR(curitem))
1369 return SvPVX(curitem);
1375 win32_putenv(const char *name)
1382 int length, relval = -1;
1386 length = strlen(name)+1;
1387 New(1309,wCuritem,length,WCHAR);
1388 A2WHELPER(name, wCuritem, length*sizeof(WCHAR));
1389 wVal = wcschr(wCuritem, '=');
1392 if (SetEnvironmentVariableW(wCuritem, *wVal ? wVal : NULL))
1398 New(1309,curitem,strlen(name)+1,char);
1399 strcpy(curitem, name);
1400 val = strchr(curitem, '=');
1402 /* The sane way to deal with the environment.
1403 * Has these advantages over putenv() & co.:
1404 * * enables us to store a truly empty value in the
1405 * environment (like in UNIX).
1406 * * we don't have to deal with RTL globals, bugs and leaks.
1408 * Why you may want to enable USE_WIN32_RTL_ENV:
1409 * * environ[] and RTL functions will not reflect changes,
1410 * which might be an issue if extensions want to access
1411 * the env. via RTL. This cuts both ways, since RTL will
1412 * not see changes made by extensions that call the Win32
1413 * functions directly, either.
1417 if (SetEnvironmentVariableA(curitem, *val ? val : NULL))
1427 filetime_to_clock(PFILETIME ft)
1429 __int64 qw = ft->dwHighDateTime;
1431 qw |= ft->dwLowDateTime;
1432 qw /= 10000; /* File time ticks at 0.1uS, clock at 1mS */
1437 win32_times(struct tms *timebuf)
1442 if (GetProcessTimes(GetCurrentProcess(), &dummy, &dummy,
1444 timebuf->tms_utime = filetime_to_clock(&user);
1445 timebuf->tms_stime = filetime_to_clock(&kernel);
1446 timebuf->tms_cutime = 0;
1447 timebuf->tms_cstime = 0;
1450 /* That failed - e.g. Win95 fallback to clock() */
1451 clock_t t = clock();
1452 timebuf->tms_utime = t;
1453 timebuf->tms_stime = 0;
1454 timebuf->tms_cutime = 0;
1455 timebuf->tms_cstime = 0;
1460 /* fix utime() so it works on directories in NT */
1462 filetime_from_time(PFILETIME pFileTime, time_t Time)
1464 struct tm *pTM = localtime(&Time);
1465 SYSTEMTIME SystemTime;
1471 SystemTime.wYear = pTM->tm_year + 1900;
1472 SystemTime.wMonth = pTM->tm_mon + 1;
1473 SystemTime.wDay = pTM->tm_mday;
1474 SystemTime.wHour = pTM->tm_hour;
1475 SystemTime.wMinute = pTM->tm_min;
1476 SystemTime.wSecond = pTM->tm_sec;
1477 SystemTime.wMilliseconds = 0;
1479 return SystemTimeToFileTime(&SystemTime, &LocalTime) &&
1480 LocalFileTimeToFileTime(&LocalTime, pFileTime);
1484 win32_unlink(const char *filename)
1491 WCHAR wBuffer[MAX_PATH+1];
1494 A2WHELPER(filename, wBuffer, sizeof(wBuffer));
1495 pwBuffer = PerlDir_mapW(wBuffer);
1496 attrs = GetFileAttributesW(pwBuffer);
1497 if (attrs == 0xFFFFFFFF)
1499 if (attrs & FILE_ATTRIBUTE_READONLY) {
1500 (void)SetFileAttributesW(pwBuffer, attrs & ~FILE_ATTRIBUTE_READONLY);
1501 ret = _wunlink(pwBuffer);
1503 (void)SetFileAttributesW(pwBuffer, attrs);
1506 ret = _wunlink(pwBuffer);
1509 filename = PerlDir_mapA(filename);
1510 attrs = GetFileAttributesA(filename);
1511 if (attrs == 0xFFFFFFFF)
1513 if (attrs & FILE_ATTRIBUTE_READONLY) {
1514 (void)SetFileAttributesA(filename, attrs & ~FILE_ATTRIBUTE_READONLY);
1515 ret = unlink(filename);
1517 (void)SetFileAttributesA(filename, attrs);
1520 ret = unlink(filename);
1529 win32_utime(const char *filename, struct utimbuf *times)
1536 struct utimbuf TimeBuffer;
1537 WCHAR wbuffer[MAX_PATH+1];
1542 A2WHELPER(filename, wbuffer, sizeof(wbuffer));
1543 pwbuffer = PerlDir_mapW(wbuffer);
1544 rc = _wutime(pwbuffer, (struct _utimbuf*)times);
1547 filename = PerlDir_mapA(filename);
1548 rc = utime(filename, times);
1550 /* EACCES: path specifies directory or readonly file */
1551 if (rc == 0 || errno != EACCES /* || !IsWinNT() */)
1554 if (times == NULL) {
1555 times = &TimeBuffer;
1556 time(×->actime);
1557 times->modtime = times->actime;
1560 /* This will (and should) still fail on readonly files */
1562 handle = CreateFileW(pwbuffer, GENERIC_READ | GENERIC_WRITE,
1563 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1564 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1567 handle = CreateFileA(filename, GENERIC_READ | GENERIC_WRITE,
1568 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1569 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1571 if (handle == INVALID_HANDLE_VALUE)
1574 if (GetFileTime(handle, &ftCreate, &ftAccess, &ftWrite) &&
1575 filetime_from_time(&ftAccess, times->actime) &&
1576 filetime_from_time(&ftWrite, times->modtime) &&
1577 SetFileTime(handle, &ftCreate, &ftAccess, &ftWrite))
1582 CloseHandle(handle);
1587 win32_uname(struct utsname *name)
1589 struct hostent *hep;
1590 STRLEN nodemax = sizeof(name->nodename)-1;
1591 OSVERSIONINFO osver;
1593 memset(&osver, 0, sizeof(OSVERSIONINFO));
1594 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1595 if (GetVersionEx(&osver)) {
1597 switch (osver.dwPlatformId) {
1598 case VER_PLATFORM_WIN32_WINDOWS:
1599 strcpy(name->sysname, "Windows");
1601 case VER_PLATFORM_WIN32_NT:
1602 strcpy(name->sysname, "Windows NT");
1604 case VER_PLATFORM_WIN32s:
1605 strcpy(name->sysname, "Win32s");
1608 strcpy(name->sysname, "Win32 Unknown");
1613 sprintf(name->release, "%d.%d",
1614 osver.dwMajorVersion, osver.dwMinorVersion);
1617 sprintf(name->version, "Build %d",
1618 osver.dwPlatformId == VER_PLATFORM_WIN32_NT
1619 ? osver.dwBuildNumber : (osver.dwBuildNumber & 0xffff));
1620 if (osver.szCSDVersion[0]) {
1621 char *buf = name->version + strlen(name->version);
1622 sprintf(buf, " (%s)", osver.szCSDVersion);
1626 *name->sysname = '\0';
1627 *name->version = '\0';
1628 *name->release = '\0';
1632 hep = win32_gethostbyname("localhost");
1634 STRLEN len = strlen(hep->h_name);
1635 if (len <= nodemax) {
1636 strcpy(name->nodename, hep->h_name);
1639 strncpy(name->nodename, hep->h_name, nodemax);
1640 name->nodename[nodemax] = '\0';
1645 if (!GetComputerName(name->nodename, &sz))
1646 *name->nodename = '\0';
1649 /* machine (architecture) */
1653 GetSystemInfo(&info);
1655 #if (defined(__BORLANDC__)&&(__BORLANDC__<=0x520)) || defined(__MINGW32__)
1656 switch (info.u.s.wProcessorArchitecture) {
1658 switch (info.wProcessorArchitecture) {
1660 case PROCESSOR_ARCHITECTURE_INTEL:
1661 arch = "x86"; break;
1662 case PROCESSOR_ARCHITECTURE_MIPS:
1663 arch = "mips"; break;
1664 case PROCESSOR_ARCHITECTURE_ALPHA:
1665 arch = "alpha"; break;
1666 case PROCESSOR_ARCHITECTURE_PPC:
1667 arch = "ppc"; break;
1669 arch = "unknown"; break;
1671 strcpy(name->machine, arch);
1677 win32_waitpid(int pid, int *status, int flags)
1680 DWORD timeout = (flags & WNOHANG) ? 0 : INFINITE;
1683 if (pid == -1) /* XXX threadid == 1 ? */
1684 return win32_wait(status);
1687 child = find_pseudo_pid(-pid);
1689 HANDLE hThread = w32_pseudo_child_handles[child];
1690 DWORD waitcode = WaitForSingleObject(hThread, timeout);
1691 if (waitcode == WAIT_TIMEOUT) {
1694 else if (waitcode != WAIT_FAILED) {
1695 if (GetExitCodeThread(hThread, &waitcode)) {
1696 *status = (int)((waitcode & 0xff) << 8);
1697 retval = (int)w32_pseudo_child_pids[child];
1698 remove_dead_pseudo_process(child);
1705 else if (IsWin95()) {
1714 child = find_pid(pid);
1716 hProcess = w32_child_handles[child];
1717 waitcode = WaitForSingleObject(hProcess, timeout);
1718 if (waitcode == WAIT_TIMEOUT) {
1721 else if (waitcode != WAIT_FAILED) {
1722 if (GetExitCodeProcess(hProcess, &waitcode)) {
1723 *status = (int)((waitcode & 0xff) << 8);
1724 retval = (int)w32_child_pids[child];
1725 remove_dead_process(child);
1734 hProcess = OpenProcess(PROCESS_ALL_ACCESS, TRUE,
1735 (IsWin95() ? -pid : pid));
1737 waitcode = WaitForSingleObject(hProcess, timeout);
1738 if (waitcode == WAIT_TIMEOUT) {
1741 else if (waitcode != WAIT_FAILED) {
1742 if (GetExitCodeProcess(hProcess, &waitcode)) {
1743 *status = (int)((waitcode & 0xff) << 8);
1744 CloseHandle(hProcess);
1748 CloseHandle(hProcess);
1754 return retval >= 0 ? pid : retval;
1758 win32_wait(int *status)
1760 /* XXX this wait emulation only knows about processes
1761 * spawned via win32_spawnvp(P_NOWAIT, ...).
1765 DWORD exitcode, waitcode;
1768 if (w32_num_pseudo_children) {
1769 waitcode = WaitForMultipleObjects(w32_num_pseudo_children,
1770 w32_pseudo_child_handles,
1773 if (waitcode != WAIT_FAILED) {
1774 if (waitcode >= WAIT_ABANDONED_0
1775 && waitcode < WAIT_ABANDONED_0 + w32_num_pseudo_children)
1776 i = waitcode - WAIT_ABANDONED_0;
1778 i = waitcode - WAIT_OBJECT_0;
1779 if (GetExitCodeThread(w32_pseudo_child_handles[i], &exitcode)) {
1780 *status = (int)((exitcode & 0xff) << 8);
1781 retval = (int)w32_pseudo_child_pids[i];
1782 remove_dead_pseudo_process(i);
1789 if (!w32_num_children) {
1794 /* if a child exists, wait for it to die */
1795 waitcode = WaitForMultipleObjects(w32_num_children,
1799 if (waitcode != WAIT_FAILED) {
1800 if (waitcode >= WAIT_ABANDONED_0
1801 && waitcode < WAIT_ABANDONED_0 + w32_num_children)
1802 i = waitcode - WAIT_ABANDONED_0;
1804 i = waitcode - WAIT_OBJECT_0;
1805 if (GetExitCodeProcess(w32_child_handles[i], &exitcode) ) {
1806 *status = (int)((exitcode & 0xff) << 8);
1807 retval = (int)w32_child_pids[i];
1808 remove_dead_process(i);
1814 errno = GetLastError();
1820 static UINT timerid = 0;
1822 static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
1825 KillTimer(NULL,timerid);
1827 CALL_FPTR(PL_sighandlerp)(14);
1829 #endif /* !PERL_OBJECT */
1831 DllExport unsigned int
1832 win32_alarm(unsigned int sec)
1836 * the 'obvious' implentation is SetTimer() with a callback
1837 * which does whatever receiving SIGALRM would do
1838 * we cannot use SIGALRM even via raise() as it is not
1839 * one of the supported codes in <signal.h>
1841 * Snag is unless something is looking at the message queue
1842 * nothing happens :-(
1847 timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
1849 Perl_croak_nocontext("Cannot set timer");
1855 KillTimer(NULL,timerid);
1859 #endif /* !PERL_OBJECT */
1863 #ifdef HAVE_DES_FCRYPT
1864 extern char * des_fcrypt(const char *txt, const char *salt, char *cbuf);
1868 win32_crypt(const char *txt, const char *salt)
1871 #ifdef HAVE_DES_FCRYPT
1872 return des_fcrypt(txt, salt, w32_crypt_buffer);
1874 Perl_croak(aTHX_ "The crypt() function is unimplemented due to excessive paranoia.");
1879 #ifdef USE_FIXED_OSFHANDLE
1881 #define FOPEN 0x01 /* file handle open */
1882 #define FNOINHERIT 0x10 /* file handle opened O_NOINHERIT */
1883 #define FAPPEND 0x20 /* file handle opened O_APPEND */
1884 #define FDEV 0x40 /* file handle refers to device */
1885 #define FTEXT 0x80 /* file handle is in text mode */
1888 *int my_open_osfhandle(long osfhandle, int flags) - open C Runtime file handle
1891 * This function allocates a free C Runtime file handle and associates
1892 * it with the Win32 HANDLE specified by the first parameter. This is a
1893 * temperary fix for WIN95's brain damage GetFileType() error on socket
1894 * we just bypass that call for socket
1896 * This works with MSVC++ 4.0+ or GCC/Mingw32
1899 * long osfhandle - Win32 HANDLE to associate with C Runtime file handle.
1900 * int flags - flags to associate with C Runtime file handle.
1903 * returns index of entry in fh, if successful
1904 * return -1, if no free entry is found
1908 *******************************************************************************/
1911 * we fake up some parts of the CRT that aren't exported by MSVCRT.dll
1912 * this lets sockets work on Win9X with GCC and should fix the problems
1917 /* create an ioinfo entry, kill its handle, and steal the entry */
1922 HANDLE hF = CreateFile("NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
1923 int fh = _open_osfhandle((long)hF, 0);
1927 EnterCriticalSection(&(_pioinfo(fh)->lock));
1932 my_open_osfhandle(long osfhandle, int flags)
1935 char fileflags; /* _osfile flags */
1937 /* copy relevant flags from second parameter */
1940 if (flags & O_APPEND)
1941 fileflags |= FAPPEND;
1946 if (flags & O_NOINHERIT)
1947 fileflags |= FNOINHERIT;
1949 /* attempt to allocate a C Runtime file handle */
1950 if ((fh = _alloc_osfhnd()) == -1) {
1951 errno = EMFILE; /* too many open files */
1952 _doserrno = 0L; /* not an OS error */
1953 return -1; /* return error to caller */
1956 /* the file is open. now, set the info in _osfhnd array */
1957 _set_osfhnd(fh, osfhandle);
1959 fileflags |= FOPEN; /* mark as open */
1961 _osfile(fh) = fileflags; /* set osfile entry */
1962 LeaveCriticalSection(&_pioinfo(fh)->lock);
1964 return fh; /* return handle */
1967 #endif /* USE_FIXED_OSFHANDLE */
1969 /* simulate flock by locking a range on the file */
1971 #define LK_ERR(f,i) ((f) ? (i = 0) : (errno = GetLastError()))
1972 #define LK_LEN 0xffff0000
1975 win32_flock(int fd, int oper)
1983 Perl_croak_nocontext("flock() unimplemented on this platform");
1986 fh = (HANDLE)_get_osfhandle(fd);
1987 memset(&o, 0, sizeof(o));
1990 case LOCK_SH: /* shared lock */
1991 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
1993 case LOCK_EX: /* exclusive lock */
1994 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
1996 case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
1997 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
1999 case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
2000 LK_ERR(LockFileEx(fh,
2001 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
2002 0, LK_LEN, 0, &o),i);
2004 case LOCK_UN: /* unlock lock */
2005 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, 0, &o),i);
2007 default: /* unknown */
2018 * redirected io subsystem for all XS modules
2031 return (&(_environ));
2034 /* the rest are the remapped stdio routines */
2054 win32_ferror(FILE *fp)
2056 return (ferror(fp));
2061 win32_feof(FILE *fp)
2067 * Since the errors returned by the socket error function
2068 * WSAGetLastError() are not known by the library routine strerror
2069 * we have to roll our own.
2073 win32_strerror(int e)
2075 #ifndef __BORLANDC__ /* Borland intolerance */
2076 extern int sys_nerr;
2080 if (e < 0 || e > sys_nerr) {
2085 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
2086 w32_strerror_buffer,
2087 sizeof(w32_strerror_buffer), NULL) == 0)
2088 strcpy(w32_strerror_buffer, "Unknown Error");
2090 return w32_strerror_buffer;
2096 win32_str_os_error(void *sv, DWORD dwErr)
2100 dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
2101 |FORMAT_MESSAGE_IGNORE_INSERTS
2102 |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
2103 dwErr, 0, (char *)&sMsg, 1, NULL);
2104 /* strip trailing whitespace and period */
2107 --dwLen; /* dwLen doesn't include trailing null */
2108 } while (0 < dwLen && isSPACE(sMsg[dwLen]));
2109 if ('.' != sMsg[dwLen])
2114 sMsg = (char*)LocalAlloc(0, 64/**sizeof(TCHAR)*/);
2116 dwLen = sprintf(sMsg,
2117 "Unknown error #0x%lX (lookup 0x%lX)",
2118 dwErr, GetLastError());
2122 sv_setpvn((SV*)sv, sMsg, dwLen);
2128 win32_fprintf(FILE *fp, const char *format, ...)
2131 va_start(marker, format); /* Initialize variable arguments. */
2133 return (vfprintf(fp, format, marker));
2137 win32_printf(const char *format, ...)
2140 va_start(marker, format); /* Initialize variable arguments. */
2142 return (vprintf(format, marker));
2146 win32_vfprintf(FILE *fp, const char *format, va_list args)
2148 return (vfprintf(fp, format, args));
2152 win32_vprintf(const char *format, va_list args)
2154 return (vprintf(format, args));
2158 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
2160 return fread(buf, size, count, fp);
2164 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
2166 return fwrite(buf, size, count, fp);
2169 #define MODE_SIZE 10
2172 win32_fopen(const char *filename, const char *mode)
2175 WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH+1];
2181 if (stricmp(filename, "/dev/null")==0)
2185 A2WHELPER(mode, wMode, sizeof(wMode));
2186 A2WHELPER(filename, wBuffer, sizeof(wBuffer));
2187 f = _wfopen(PerlDir_mapW(wBuffer), wMode);
2190 f = fopen(PerlDir_mapA(filename), mode);
2191 /* avoid buffering headaches for child processes */
2192 if (f && *mode == 'a')
2193 win32_fseek(f, 0, SEEK_END);
2197 #ifndef USE_SOCKETS_AS_HANDLES
2199 #define fdopen my_fdopen
2203 win32_fdopen(int handle, const char *mode)
2206 WCHAR wMode[MODE_SIZE];
2209 A2WHELPER(mode, wMode, sizeof(wMode));
2210 f = _wfdopen(handle, wMode);
2213 f = fdopen(handle, (char *) mode);
2214 /* avoid buffering headaches for child processes */
2215 if (f && *mode == 'a')
2216 win32_fseek(f, 0, SEEK_END);
2221 win32_freopen(const char *path, const char *mode, FILE *stream)
2224 WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH+1];
2225 if (stricmp(path, "/dev/null")==0)
2229 A2WHELPER(mode, wMode, sizeof(wMode));
2230 A2WHELPER(path, wBuffer, sizeof(wBuffer));
2231 return _wfreopen(PerlDir_mapW(wBuffer), wMode, stream);
2233 return freopen(PerlDir_mapA(path), mode, stream);
2237 win32_fclose(FILE *pf)
2239 return my_fclose(pf); /* defined in win32sck.c */
2243 win32_fputs(const char *s,FILE *pf)
2245 return fputs(s, pf);
2249 win32_fputc(int c,FILE *pf)
2255 win32_ungetc(int c,FILE *pf)
2257 return ungetc(c,pf);
2261 win32_getc(FILE *pf)
2267 win32_fileno(FILE *pf)
2273 win32_clearerr(FILE *pf)
2280 win32_fflush(FILE *pf)
2286 win32_ftell(FILE *pf)
2292 win32_fseek(FILE *pf,long offset,int origin)
2294 return fseek(pf, offset, origin);
2298 win32_fgetpos(FILE *pf,fpos_t *p)
2300 return fgetpos(pf, p);
2304 win32_fsetpos(FILE *pf,const fpos_t *p)
2306 return fsetpos(pf, p);
2310 win32_rewind(FILE *pf)
2330 win32_fstat(int fd,struct stat *sbufptr)
2333 /* A file designated by filehandle is not shown as accessible
2334 * for write operations, probably because it is opened for reading.
2337 int rc = fstat(fd,sbufptr);
2338 BY_HANDLE_FILE_INFORMATION bhfi;
2339 if (GetFileInformationByHandle((HANDLE)_get_osfhandle(fd), &bhfi)) {
2340 sbufptr->st_mode &= 0xFE00;
2341 if (bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
2342 sbufptr->st_mode |= (S_IREAD + (S_IREAD >> 3) + (S_IREAD >> 6));
2344 sbufptr->st_mode |= ((S_IREAD|S_IWRITE) + ((S_IREAD|S_IWRITE) >> 3)
2345 + ((S_IREAD|S_IWRITE) >> 6));
2349 return my_fstat(fd,sbufptr);
2354 win32_pipe(int *pfd, unsigned int size, int mode)
2356 return _pipe(pfd, size, mode);
2360 win32_popenlist(const char *mode, IV narg, SV **args)
2363 Perl_croak(aTHX_ "List form of pipe open not implemented");
2368 * a popen() clone that respects PERL5SHELL
2370 * changed to return PerlIO* rather than FILE * by BKS, 11-11-2000
2374 win32_popen(const char *command, const char *mode)
2376 #ifdef USE_RTL_POPEN
2377 return _popen(command, mode);
2385 /* establish which ends read and write */
2386 if (strchr(mode,'w')) {
2387 stdfd = 0; /* stdin */
2391 else if (strchr(mode,'r')) {
2392 stdfd = 1; /* stdout */
2399 /* set the correct mode */
2400 if (strchr(mode,'b'))
2402 else if (strchr(mode,'t'))
2405 ourmode = _fmode & (O_TEXT | O_BINARY);
2407 /* the child doesn't inherit handles */
2408 ourmode |= O_NOINHERIT;
2410 if (win32_pipe( p, 512, ourmode) == -1)
2413 /* save current stdfd */
2414 if ((oldfd = win32_dup(stdfd)) == -1)
2417 /* make stdfd go to child end of pipe (implicitly closes stdfd) */
2418 /* stdfd will be inherited by the child */
2419 if (win32_dup2(p[child], stdfd) == -1)
2422 /* close the child end in parent */
2423 win32_close(p[child]);
2425 /* start the child */
2428 if ((childpid = do_spawn_nowait((char*)command)) == -1)
2431 /* revert stdfd to whatever it was before */
2432 if (win32_dup2(oldfd, stdfd) == -1)
2435 /* close saved handle */
2439 sv_setiv(*av_fetch(w32_fdpid, p[parent], TRUE), childpid);
2442 /* set process id so that it can be returned by perl's open() */
2443 PL_forkprocess = childpid;
2446 /* we have an fd, return a file stream */
2447 return (PerlIO_fdopen(p[parent], (char *)mode));
2450 /* we don't need to check for errors here */
2454 win32_dup2(oldfd, stdfd);
2459 #endif /* USE_RTL_POPEN */
2467 win32_pclose(PerlIO *pf)
2469 #ifdef USE_RTL_POPEN
2473 int childpid, status;
2477 sv = *av_fetch(w32_fdpid, PerlIO_fileno(pf), TRUE);
2480 childpid = SvIVX(sv);
2497 if (win32_waitpid(childpid, &status, 0) == -1)
2502 #endif /* USE_RTL_POPEN */
2508 LPCWSTR lpExistingFileName,
2509 LPSECURITY_ATTRIBUTES lpSecurityAttributes)
2512 WCHAR wFullName[MAX_PATH+1];
2513 LPVOID lpContext = NULL;
2514 WIN32_STREAM_ID StreamId;
2515 DWORD dwSize = (char*)&StreamId.cStreamName - (char*)&StreamId;
2520 BOOL (__stdcall *pfnBackupWrite)(HANDLE, LPBYTE, DWORD, LPDWORD,
2521 BOOL, BOOL, LPVOID*) =
2522 (BOOL (__stdcall *)(HANDLE, LPBYTE, DWORD, LPDWORD,
2523 BOOL, BOOL, LPVOID*))
2524 GetProcAddress(GetModuleHandle("kernel32.dll"), "BackupWrite");
2525 if (pfnBackupWrite == NULL)
2528 dwLen = GetFullPathNameW(lpFileName, MAX_PATH, wFullName, NULL);
2531 dwLen = (dwLen+1)*sizeof(WCHAR);
2533 handle = CreateFileW(lpExistingFileName, FILE_WRITE_ATTRIBUTES,
2534 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
2535 NULL, OPEN_EXISTING, 0, NULL);
2536 if (handle == INVALID_HANDLE_VALUE)
2539 StreamId.dwStreamId = BACKUP_LINK;
2540 StreamId.dwStreamAttributes = 0;
2541 StreamId.dwStreamNameSize = 0;
2542 #if defined(__BORLANDC__) || defined(__MINGW32__)
2543 StreamId.Size.u.HighPart = 0;
2544 StreamId.Size.u.LowPart = dwLen;
2546 StreamId.Size.HighPart = 0;
2547 StreamId.Size.LowPart = dwLen;
2550 bSuccess = pfnBackupWrite(handle, (LPBYTE)&StreamId, dwSize, &dwWritten,
2551 FALSE, FALSE, &lpContext);
2553 bSuccess = pfnBackupWrite(handle, (LPBYTE)wFullName, dwLen, &dwWritten,
2554 FALSE, FALSE, &lpContext);
2555 pfnBackupWrite(handle, NULL, 0, &dwWritten, TRUE, FALSE, &lpContext);
2558 CloseHandle(handle);
2563 win32_link(const char *oldname, const char *newname)
2566 BOOL (__stdcall *pfnCreateHardLinkW)(LPCWSTR,LPCWSTR,LPSECURITY_ATTRIBUTES);
2567 WCHAR wOldName[MAX_PATH+1];
2568 WCHAR wNewName[MAX_PATH+1];
2571 Perl_croak(aTHX_ PL_no_func, "link");
2573 pfnCreateHardLinkW =
2574 (BOOL (__stdcall *)(LPCWSTR, LPCWSTR, LPSECURITY_ATTRIBUTES))
2575 GetProcAddress(GetModuleHandle("kernel32.dll"), "CreateHardLinkW");
2576 if (pfnCreateHardLinkW == NULL)
2577 pfnCreateHardLinkW = Nt4CreateHardLinkW;
2579 if ((A2WHELPER(oldname, wOldName, sizeof(wOldName))) &&
2580 (A2WHELPER(newname, wNewName, sizeof(wNewName))) &&
2581 (wcscpy(wOldName, PerlDir_mapW(wOldName)),
2582 pfnCreateHardLinkW(PerlDir_mapW(wNewName), wOldName, NULL)))
2586 errno = (GetLastError() == ERROR_FILE_NOT_FOUND) ? ENOENT : EINVAL;
2591 win32_rename(const char *oname, const char *newname)
2593 WCHAR wOldName[MAX_PATH+1];
2594 WCHAR wNewName[MAX_PATH+1];
2595 char szOldName[MAX_PATH+1];
2596 char szNewName[MAX_PATH+1];
2600 /* XXX despite what the documentation says about MoveFileEx(),
2601 * it doesn't work under Windows95!
2604 DWORD dwFlags = MOVEFILE_COPY_ALLOWED;
2606 A2WHELPER(oname, wOldName, sizeof(wOldName));
2607 A2WHELPER(newname, wNewName, sizeof(wNewName));
2608 if (wcsicmp(wNewName, wOldName))
2609 dwFlags |= MOVEFILE_REPLACE_EXISTING;
2610 wcscpy(wOldName, PerlDir_mapW(wOldName));
2611 bResult = MoveFileExW(wOldName,PerlDir_mapW(wNewName), dwFlags);
2614 if (stricmp(newname, oname))
2615 dwFlags |= MOVEFILE_REPLACE_EXISTING;
2616 strcpy(szOldName, PerlDir_mapA(oname));
2617 bResult = MoveFileExA(szOldName,PerlDir_mapA(newname), dwFlags);
2620 DWORD err = GetLastError();
2622 case ERROR_BAD_NET_NAME:
2623 case ERROR_BAD_NETPATH:
2624 case ERROR_BAD_PATHNAME:
2625 case ERROR_FILE_NOT_FOUND:
2626 case ERROR_FILENAME_EXCED_RANGE:
2627 case ERROR_INVALID_DRIVE:
2628 case ERROR_NO_MORE_FILES:
2629 case ERROR_PATH_NOT_FOUND:
2642 char szTmpName[MAX_PATH+1];
2643 char dname[MAX_PATH+1];
2644 char *endname = Nullch;
2646 DWORD from_attr, to_attr;
2648 strcpy(szOldName, PerlDir_mapA(oname));
2649 strcpy(szNewName, PerlDir_mapA(newname));
2651 /* if oname doesn't exist, do nothing */
2652 from_attr = GetFileAttributes(szOldName);
2653 if (from_attr == 0xFFFFFFFF) {
2658 /* if newname exists, rename it to a temporary name so that we
2659 * don't delete it in case oname happens to be the same file
2660 * (but perhaps accessed via a different path)
2662 to_attr = GetFileAttributes(szNewName);
2663 if (to_attr != 0xFFFFFFFF) {
2664 /* if newname is a directory, we fail
2665 * XXX could overcome this with yet more convoluted logic */
2666 if (to_attr & FILE_ATTRIBUTE_DIRECTORY) {
2670 tmplen = strlen(szNewName);
2671 strcpy(szTmpName,szNewName);
2672 endname = szTmpName+tmplen;
2673 for (; endname > szTmpName ; --endname) {
2674 if (*endname == '/' || *endname == '\\') {
2679 if (endname > szTmpName)
2680 endname = strcpy(dname,szTmpName);
2684 /* get a temporary filename in same directory
2685 * XXX is this really the best we can do? */
2686 if (!GetTempFileName((LPCTSTR)endname, "plr", 0, szTmpName)) {
2690 DeleteFile(szTmpName);
2692 retval = rename(szNewName, szTmpName);
2699 /* rename oname to newname */
2700 retval = rename(szOldName, szNewName);
2702 /* if we created a temporary file before ... */
2703 if (endname != Nullch) {
2704 /* ...and rename succeeded, delete temporary file/directory */
2706 DeleteFile(szTmpName);
2707 /* else restore it to what it was */
2709 (void)rename(szTmpName, szNewName);
2716 win32_setmode(int fd, int mode)
2718 return setmode(fd, mode);
2722 win32_lseek(int fd, long offset, int origin)
2724 return lseek(fd, offset, origin);
2734 win32_open(const char *path, int flag, ...)
2739 WCHAR wBuffer[MAX_PATH+1];
2742 pmode = va_arg(ap, int);
2745 if (stricmp(path, "/dev/null")==0)
2749 A2WHELPER(path, wBuffer, sizeof(wBuffer));
2750 return _wopen(PerlDir_mapW(wBuffer), flag, pmode);
2752 return open(PerlDir_mapA(path), flag, pmode);
2755 /* close() that understands socket */
2756 extern int my_close(int); /* in win32sck.c */
2761 return my_close(fd);
2777 win32_dup2(int fd1,int fd2)
2779 return dup2(fd1,fd2);
2782 #ifdef PERL_MSVCRT_READFIX
2784 #define LF 10 /* line feed */
2785 #define CR 13 /* carriage return */
2786 #define CTRLZ 26 /* ctrl-z means eof for text */
2787 #define FOPEN 0x01 /* file handle open */
2788 #define FEOFLAG 0x02 /* end of file has been encountered */
2789 #define FCRLF 0x04 /* CR-LF across read buffer (in text mode) */
2790 #define FPIPE 0x08 /* file handle refers to a pipe */
2791 #define FAPPEND 0x20 /* file handle opened O_APPEND */
2792 #define FDEV 0x40 /* file handle refers to device */
2793 #define FTEXT 0x80 /* file handle is in text mode */
2794 #define MAX_DESCRIPTOR_COUNT (64*32) /* this is the maximun that MSVCRT can handle */
2797 _fixed_read(int fh, void *buf, unsigned cnt)
2799 int bytes_read; /* number of bytes read */
2800 char *buffer; /* buffer to read to */
2801 int os_read; /* bytes read on OS call */
2802 char *p, *q; /* pointers into buffer */
2803 char peekchr; /* peek-ahead character */
2804 ULONG filepos; /* file position after seek */
2805 ULONG dosretval; /* o.s. return value */
2807 /* validate handle */
2808 if (((unsigned)fh >= (unsigned)MAX_DESCRIPTOR_COUNT) ||
2809 !(_osfile(fh) & FOPEN))
2811 /* out of range -- return error */
2813 _doserrno = 0; /* not o.s. error */
2818 * If lockinitflag is FALSE, assume fd is device
2819 * lockinitflag is set to TRUE by open.
2821 if (_pioinfo(fh)->lockinitflag)
2822 EnterCriticalSection(&(_pioinfo(fh)->lock)); /* lock file */
2824 bytes_read = 0; /* nothing read yet */
2825 buffer = (char*)buf;
2827 if (cnt == 0 || (_osfile(fh) & FEOFLAG)) {
2828 /* nothing to read or at EOF, so return 0 read */
2832 if ((_osfile(fh) & (FPIPE|FDEV)) && _pipech(fh) != LF) {
2833 /* a pipe/device and pipe lookahead non-empty: read the lookahead
2835 *buffer++ = _pipech(fh);
2838 _pipech(fh) = LF; /* mark as empty */
2843 if (!ReadFile((HANDLE)_osfhnd(fh), buffer, cnt, (LPDWORD)&os_read, NULL))
2845 /* ReadFile has reported an error. recognize two special cases.
2847 * 1. map ERROR_ACCESS_DENIED to EBADF
2849 * 2. just return 0 if ERROR_BROKEN_PIPE has occurred. it
2850 * means the handle is a read-handle on a pipe for which
2851 * all write-handles have been closed and all data has been
2854 if ((dosretval = GetLastError()) == ERROR_ACCESS_DENIED) {
2855 /* wrong read/write mode should return EBADF, not EACCES */
2857 _doserrno = dosretval;
2861 else if (dosretval == ERROR_BROKEN_PIPE) {
2871 bytes_read += os_read; /* update bytes read */
2873 if (_osfile(fh) & FTEXT) {
2874 /* now must translate CR-LFs to LFs in the buffer */
2876 /* set CRLF flag to indicate LF at beginning of buffer */
2877 /* if ((os_read != 0) && (*(char *)buf == LF)) */
2878 /* _osfile(fh) |= FCRLF; */
2880 /* _osfile(fh) &= ~FCRLF; */
2882 _osfile(fh) &= ~FCRLF;
2884 /* convert chars in the buffer: p is src, q is dest */
2886 while (p < (char *)buf + bytes_read) {
2888 /* if fh is not a device, set ctrl-z flag */
2889 if (!(_osfile(fh) & FDEV))
2890 _osfile(fh) |= FEOFLAG;
2891 break; /* stop translating */
2896 /* *p is CR, so must check next char for LF */
2897 if (p < (char *)buf + bytes_read - 1) {
2900 *q++ = LF; /* convert CR-LF to LF */
2903 *q++ = *p++; /* store char normally */
2906 /* This is the hard part. We found a CR at end of
2907 buffer. We must peek ahead to see if next char
2912 if (!ReadFile((HANDLE)_osfhnd(fh), &peekchr, 1,
2913 (LPDWORD)&os_read, NULL))
2914 dosretval = GetLastError();
2916 if (dosretval != 0 || os_read == 0) {
2917 /* couldn't read ahead, store CR */
2921 /* peekchr now has the extra character -- we now
2922 have several possibilities:
2923 1. disk file and char is not LF; just seek back
2925 2. disk file and char is LF; store LF, don't seek back
2926 3. pipe/device and char is LF; store LF.
2927 4. pipe/device and char isn't LF, store CR and
2928 put char in pipe lookahead buffer. */
2929 if (_osfile(fh) & (FDEV|FPIPE)) {
2930 /* non-seekable device */
2935 _pipech(fh) = peekchr;
2940 if (peekchr == LF) {
2941 /* nothing read yet; must make some
2944 /* turn on this flag for tell routine */
2945 _osfile(fh) |= FCRLF;
2948 HANDLE osHandle; /* o.s. handle value */
2950 if ((osHandle = (HANDLE)_get_osfhandle(fh)) != (HANDLE)-1)
2952 if ((filepos = SetFilePointer(osHandle, -1, NULL, FILE_CURRENT)) == -1)
2953 dosretval = GetLastError();
2964 /* we now change bytes_read to reflect the true number of chars
2966 bytes_read = q - (char *)buf;
2970 if (_pioinfo(fh)->lockinitflag)
2971 LeaveCriticalSection(&(_pioinfo(fh)->lock)); /* unlock file */
2976 #endif /* PERL_MSVCRT_READFIX */
2979 win32_read(int fd, void *buf, unsigned int cnt)
2981 #ifdef PERL_MSVCRT_READFIX
2982 return _fixed_read(fd, buf, cnt);
2984 return read(fd, buf, cnt);
2989 win32_write(int fd, const void *buf, unsigned int cnt)
2991 return write(fd, buf, cnt);
2995 win32_mkdir(const char *dir, int mode)
2999 WCHAR wBuffer[MAX_PATH+1];
3000 A2WHELPER(dir, wBuffer, sizeof(wBuffer));
3001 return _wmkdir(PerlDir_mapW(wBuffer));
3003 return mkdir(PerlDir_mapA(dir)); /* just ignore mode */
3007 win32_rmdir(const char *dir)
3011 WCHAR wBuffer[MAX_PATH+1];
3012 A2WHELPER(dir, wBuffer, sizeof(wBuffer));
3013 return _wrmdir(PerlDir_mapW(wBuffer));
3015 return rmdir(PerlDir_mapA(dir));
3019 win32_chdir(const char *dir)
3023 WCHAR wBuffer[MAX_PATH+1];
3024 A2WHELPER(dir, wBuffer, sizeof(wBuffer));
3025 return _wchdir(wBuffer);
3031 win32_access(const char *path, int mode)
3035 WCHAR wBuffer[MAX_PATH+1];
3036 A2WHELPER(path, wBuffer, sizeof(wBuffer));
3037 return _waccess(PerlDir_mapW(wBuffer), mode);
3039 return access(PerlDir_mapA(path), mode);
3043 win32_chmod(const char *path, int mode)
3047 WCHAR wBuffer[MAX_PATH+1];
3048 A2WHELPER(path, wBuffer, sizeof(wBuffer));
3049 return _wchmod(PerlDir_mapW(wBuffer), mode);
3051 return chmod(PerlDir_mapA(path), mode);
3056 create_command_line(const char* command, const char * const *args)
3060 char *cmd, *ptr, *arg;
3061 STRLEN len = strlen(command) + 1;
3063 for (index = 0; (ptr = (char*)args[index]) != NULL; ++index)
3064 len += strlen(ptr) + 1;
3066 New(1310, cmd, len, char);
3068 strcpy(ptr, command);
3070 for (index = 0; (arg = (char*)args[index]) != NULL; ++index) {
3080 qualified_path(const char *cmd)
3084 char *fullcmd, *curfullcmd;
3090 fullcmd = (char*)cmd;
3092 if (*fullcmd == '/' || *fullcmd == '\\')
3099 pathstr = win32_getenv("PATH");
3100 New(0, fullcmd, MAX_PATH+1, char);
3101 curfullcmd = fullcmd;
3106 /* start by appending the name to the current prefix */
3107 strcpy(curfullcmd, cmd);
3108 curfullcmd += cmdlen;
3110 /* if it doesn't end with '.', or has no extension, try adding
3111 * a trailing .exe first */
3112 if (cmd[cmdlen-1] != '.'
3113 && (cmdlen < 4 || cmd[cmdlen-4] != '.'))
3115 strcpy(curfullcmd, ".exe");
3116 res = GetFileAttributes(fullcmd);
3117 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
3122 /* that failed, try the bare name */
3123 res = GetFileAttributes(fullcmd);
3124 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
3127 /* quit if no other path exists, or if cmd already has path */
3128 if (!pathstr || !*pathstr || has_slash)
3131 /* skip leading semis */
3132 while (*pathstr == ';')
3135 /* build a new prefix from scratch */
3136 curfullcmd = fullcmd;
3137 while (*pathstr && *pathstr != ';') {
3138 if (*pathstr == '"') { /* foo;"baz;etc";bar */
3139 pathstr++; /* skip initial '"' */
3140 while (*pathstr && *pathstr != '"') {
3141 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
3142 *curfullcmd++ = *pathstr;
3146 pathstr++; /* skip trailing '"' */
3149 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
3150 *curfullcmd++ = *pathstr;
3155 pathstr++; /* skip trailing semi */
3156 if (curfullcmd > fullcmd /* append a dir separator */
3157 && curfullcmd[-1] != '/' && curfullcmd[-1] != '\\')
3159 *curfullcmd++ = '\\';
3167 /* The following are just place holders.
3168 * Some hosts may provide and environment that the OS is
3169 * not tracking, therefore, these host must provide that
3170 * environment and the current directory to CreateProcess
3180 free_childenv(void* d)
3189 char szfilename[(MAX_PATH+1)*2];
3191 WCHAR wfilename[MAX_PATH+1];
3192 GetCurrentDirectoryW(MAX_PATH+1, wfilename);
3193 W2AHELPER(wfilename, szfilename, sizeof(szfilename));
3196 GetCurrentDirectoryA(MAX_PATH+1, szfilename);
3199 New(0, ptr, strlen(szfilename)+1, char);
3200 strcpy(ptr, szfilename);
3205 free_childdir(char* d)
3212 /* XXX this needs to be made more compatible with the spawnvp()
3213 * provided by the various RTLs. In particular, searching for
3214 * *.{com,bat,cmd} files (as done by the RTLs) is unimplemented.
3215 * This doesn't significantly affect perl itself, because we
3216 * always invoke things using PERL5SHELL if a direct attempt to
3217 * spawn the executable fails.
3219 * XXX splitting and rejoining the commandline between do_aspawn()
3220 * and win32_spawnvp() could also be avoided.
3224 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
3226 #ifdef USE_RTL_SPAWNVP
3227 return spawnvp(mode, cmdname, (char * const *)argv);
3234 STARTUPINFO StartupInfo;
3235 PROCESS_INFORMATION ProcessInformation;
3238 char *cmd = create_command_line(cmdname, strcmp(cmdname, argv[0]) == 0
3240 char *fullcmd = Nullch;
3242 env = PerlEnv_get_childenv();
3243 dir = PerlEnv_get_childdir();
3246 case P_NOWAIT: /* asynch + remember result */
3247 if (w32_num_children >= MAXIMUM_WAIT_OBJECTS) {
3253 case P_WAIT: /* synchronous execution */
3255 default: /* invalid mode */
3260 memset(&StartupInfo,0,sizeof(StartupInfo));
3261 StartupInfo.cb = sizeof(StartupInfo);
3262 memset(&tbl,0,sizeof(tbl));
3263 PerlEnv_get_child_IO(&tbl);
3264 StartupInfo.dwFlags = tbl.dwFlags;
3265 StartupInfo.dwX = tbl.dwX;
3266 StartupInfo.dwY = tbl.dwY;
3267 StartupInfo.dwXSize = tbl.dwXSize;
3268 StartupInfo.dwYSize = tbl.dwYSize;
3269 StartupInfo.dwXCountChars = tbl.dwXCountChars;
3270 StartupInfo.dwYCountChars = tbl.dwYCountChars;
3271 StartupInfo.dwFillAttribute = tbl.dwFillAttribute;
3272 StartupInfo.wShowWindow = tbl.wShowWindow;
3273 StartupInfo.hStdInput = tbl.childStdIn;
3274 StartupInfo.hStdOutput = tbl.childStdOut;
3275 StartupInfo.hStdError = tbl.childStdErr;
3276 if (StartupInfo.hStdInput != INVALID_HANDLE_VALUE &&
3277 StartupInfo.hStdOutput != INVALID_HANDLE_VALUE &&
3278 StartupInfo.hStdError != INVALID_HANDLE_VALUE)
3280 StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
3283 create |= CREATE_NEW_CONSOLE;
3287 if (!CreateProcess(cmdname, /* search PATH to find executable */
3288 cmd, /* executable, and its arguments */
3289 NULL, /* process attributes */
3290 NULL, /* thread attributes */
3291 TRUE, /* inherit handles */
3292 create, /* creation flags */
3293 (LPVOID)env, /* inherit environment */
3294 dir, /* inherit cwd */
3296 &ProcessInformation))
3298 /* initial NULL argument to CreateProcess() does a PATH
3299 * search, but it always first looks in the directory
3300 * where the current process was started, which behavior
3301 * is undesirable for backward compatibility. So we
3302 * jump through our own hoops by picking out the path
3303 * we really want it to use. */
3305 fullcmd = qualified_path(cmdname);
3316 if (mode == P_NOWAIT) {
3317 /* asynchronous spawn -- store handle, return PID */
3318 ret = (int)ProcessInformation.dwProcessId;
3319 if (IsWin95() && ret < 0)
3322 w32_child_handles[w32_num_children] = ProcessInformation.hProcess;
3323 w32_child_pids[w32_num_children] = (DWORD)ret;
3328 WaitForSingleObject(ProcessInformation.hProcess, INFINITE);
3329 GetExitCodeProcess(ProcessInformation.hProcess, &status);
3331 CloseHandle(ProcessInformation.hProcess);
3334 CloseHandle(ProcessInformation.hThread);
3337 PerlEnv_free_childenv(env);
3338 PerlEnv_free_childdir(dir);
3346 win32_execv(const char *cmdname, const char *const *argv)
3350 /* if this is a pseudo-forked child, we just want to spawn
3351 * the new program, and return */
3353 return spawnv(P_WAIT, cmdname, (char *const *)argv);
3355 return execv(cmdname, (char *const *)argv);
3359 win32_execvp(const char *cmdname, const char *const *argv)
3363 /* if this is a pseudo-forked child, we just want to spawn
3364 * the new program, and return */
3366 return win32_spawnvp(P_WAIT, cmdname, (char *const *)argv);
3368 return execvp(cmdname, (char *const *)argv);
3372 win32_perror(const char *str)
3378 win32_setbuf(FILE *pf, char *buf)
3384 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
3386 return setvbuf(pf, buf, type, size);
3390 win32_flushall(void)
3396 win32_fcloseall(void)
3402 win32_fgets(char *s, int n, FILE *pf)
3404 return fgets(s, n, pf);
3414 win32_fgetc(FILE *pf)
3420 win32_putc(int c, FILE *pf)
3426 win32_puts(const char *s)
3438 win32_putchar(int c)
3445 #ifndef USE_PERL_SBRK
3447 static char *committed = NULL;
3448 static char *base = NULL;
3449 static char *reserved = NULL;
3450 static char *brk = NULL;
3451 static DWORD pagesize = 0;
3452 static DWORD allocsize = 0;
3460 GetSystemInfo(&info);
3461 /* Pretend page size is larger so we don't perpetually
3462 * call the OS to commit just one page ...
3464 pagesize = info.dwPageSize << 3;
3465 allocsize = info.dwAllocationGranularity;
3467 /* This scheme fails eventually if request for contiguous
3468 * block is denied so reserve big blocks - this is only
3469 * address space not memory ...
3471 if (brk+need >= reserved)
3473 DWORD size = 64*1024*1024;
3475 if (committed && reserved && committed < reserved)
3477 /* Commit last of previous chunk cannot span allocations */
3478 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
3480 committed = reserved;
3482 /* Reserve some (more) space
3483 * Note this is a little sneaky, 1st call passes NULL as reserved
3484 * so lets system choose where we start, subsequent calls pass
3485 * the old end address so ask for a contiguous block
3487 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
3490 reserved = addr+size;
3505 if (brk > committed)
3507 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
3508 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
3523 win32_malloc(size_t size)
3525 return malloc(size);
3529 win32_calloc(size_t numitems, size_t size)
3531 return calloc(numitems,size);
3535 win32_realloc(void *block, size_t size)
3537 return realloc(block,size);
3541 win32_free(void *block)
3548 win32_open_osfhandle(long handle, int flags)
3550 #ifdef USE_FIXED_OSFHANDLE
3552 return my_open_osfhandle(handle, flags);
3554 return _open_osfhandle(handle, flags);
3558 win32_get_osfhandle(int fd)
3560 return _get_osfhandle(fd);
3564 win32_dynaload(const char* filename)
3568 char buf[MAX_PATH+1];
3571 /* LoadLibrary() doesn't recognize forward slashes correctly,
3572 * so turn 'em back. */
3573 first = strchr(filename, '/');
3575 STRLEN len = strlen(filename);
3576 if (len <= MAX_PATH) {
3577 strcpy(buf, filename);
3578 filename = &buf[first - filename];
3580 if (*filename == '/')
3581 *(char*)filename = '\\';
3588 WCHAR wfilename[MAX_PATH+1];
3589 A2WHELPER(filename, wfilename, sizeof(wfilename));
3590 hModule = LoadLibraryExW(PerlDir_mapW(wfilename), NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
3593 hModule = LoadLibraryExA(PerlDir_mapA(filename), NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
3606 /* Make the host for current directory */
3607 char* ptr = PerlEnv_get_childdir();
3610 * then it worked, set PV valid,
3611 * else return 'undef'
3614 SV *sv = sv_newmortal();
3616 PerlEnv_free_childdir(ptr);
3631 Perl_croak(aTHX_ "usage: Win32::SetCurrentDirectory($cwd)");
3632 if (!PerlDir_chdir(SvPV_nolen(ST(0))))
3639 XS(w32_GetNextAvailDrive)
3643 char root[] = "_:\\";
3648 if (GetDriveType(root) == 1) {
3657 XS(w32_GetLastError)
3661 XSRETURN_IV(GetLastError());
3665 XS(w32_SetLastError)
3669 Perl_croak(aTHX_ "usage: Win32::SetLastError($error)");
3670 SetLastError(SvIV(ST(0)));
3678 char *name = w32_getlogin_buffer;
3679 DWORD size = sizeof(w32_getlogin_buffer);
3681 if (GetUserName(name,&size)) {
3682 /* size includes NULL */
3683 ST(0) = sv_2mortal(newSVpvn(name,size-1));
3693 char name[MAX_COMPUTERNAME_LENGTH+1];
3694 DWORD size = sizeof(name);
3696 if (GetComputerName(name,&size)) {
3697 /* size does NOT include NULL :-( */
3698 ST(0) = sv_2mortal(newSVpvn(name,size));
3709 HINSTANCE hNetApi32 = LoadLibrary("netapi32.dll");
3710 DWORD (__stdcall *pfnNetApiBufferFree)(LPVOID Buffer);
3711 DWORD (__stdcall *pfnNetWkstaGetInfo)(LPWSTR servername, DWORD level,
3715 pfnNetApiBufferFree = (DWORD (__stdcall *)(void *))
3716 GetProcAddress(hNetApi32, "NetApiBufferFree");
3717 pfnNetWkstaGetInfo = (DWORD (__stdcall *)(LPWSTR, DWORD, void *))
3718 GetProcAddress(hNetApi32, "NetWkstaGetInfo");
3721 if (hNetApi32 && pfnNetWkstaGetInfo && pfnNetApiBufferFree) {
3722 /* this way is more reliable, in case user has a local account. */
3724 DWORD dnamelen = sizeof(dname);
3726 DWORD wki100_platform_id;
3727 LPWSTR wki100_computername;
3728 LPWSTR wki100_langroup;
3729 DWORD wki100_ver_major;
3730 DWORD wki100_ver_minor;
3732 /* NERR_Success *is* 0*/
3733 if (0 == pfnNetWkstaGetInfo(NULL, 100, &pwi)) {
3734 if (pwi->wki100_langroup && *(pwi->wki100_langroup)) {
3735 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_langroup,
3736 -1, (LPSTR)dname, dnamelen, NULL, NULL);
3739 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_computername,
3740 -1, (LPSTR)dname, dnamelen, NULL, NULL);
3742 pfnNetApiBufferFree(pwi);
3743 FreeLibrary(hNetApi32);
3746 FreeLibrary(hNetApi32);
3749 /* Win95 doesn't have NetWksta*(), so do it the old way */
3751 DWORD size = sizeof(name);
3753 FreeLibrary(hNetApi32);
3754 if (GetUserName(name,&size)) {
3755 char sid[ONE_K_BUFSIZE];
3756 DWORD sidlen = sizeof(sid);
3758 DWORD dnamelen = sizeof(dname);
3760 if (LookupAccountName(NULL, name, (PSID)&sid, &sidlen,
3761 dname, &dnamelen, &snu)) {
3762 XSRETURN_PV(dname); /* all that for this */
3774 DWORD flags, filecomplen;
3775 if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
3776 &flags, fsname, sizeof(fsname))) {
3777 if (GIMME_V == G_ARRAY) {
3778 XPUSHs(sv_2mortal(newSVpvn(fsname,strlen(fsname))));
3779 XPUSHs(sv_2mortal(newSViv(flags)));
3780 XPUSHs(sv_2mortal(newSViv(filecomplen)));
3785 XSRETURN_PV(fsname);
3791 XS(w32_GetOSVersion)
3794 OSVERSIONINFOA osver;
3797 OSVERSIONINFOW osverw;
3798 char szCSDVersion[sizeof(osverw.szCSDVersion)];
3799 osverw.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
3800 if (!GetVersionExW(&osverw)) {
3803 W2AHELPER(osverw.szCSDVersion, szCSDVersion, sizeof(szCSDVersion));
3804 XPUSHs(newSVpvn(szCSDVersion, strlen(szCSDVersion)));
3805 osver.dwMajorVersion = osverw.dwMajorVersion;
3806 osver.dwMinorVersion = osverw.dwMinorVersion;
3807 osver.dwBuildNumber = osverw.dwBuildNumber;
3808 osver.dwPlatformId = osverw.dwPlatformId;
3811 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOA);
3812 if (!GetVersionExA(&osver)) {
3815 XPUSHs(newSVpvn(osver.szCSDVersion, strlen(osver.szCSDVersion)));
3817 XPUSHs(newSViv(osver.dwMajorVersion));
3818 XPUSHs(newSViv(osver.dwMinorVersion));
3819 XPUSHs(newSViv(osver.dwBuildNumber));
3820 XPUSHs(newSViv(osver.dwPlatformId));
3829 XSRETURN_IV(IsWinNT());
3837 XSRETURN_IV(IsWin95());
3841 XS(w32_FormatMessage)
3845 char msgbuf[ONE_K_BUFSIZE];
3848 Perl_croak(aTHX_ "usage: Win32::FormatMessage($errno)");
3851 WCHAR wmsgbuf[ONE_K_BUFSIZE];
3852 if (FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM,
3853 &source, SvIV(ST(0)), 0,
3854 wmsgbuf, ONE_K_BUFSIZE-1, NULL))
3856 W2AHELPER(wmsgbuf, msgbuf, sizeof(msgbuf));
3857 XSRETURN_PV(msgbuf);
3861 if (FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM,
3862 &source, SvIV(ST(0)), 0,
3863 msgbuf, sizeof(msgbuf)-1, NULL))
3864 XSRETURN_PV(msgbuf);
3877 PROCESS_INFORMATION stProcInfo;
3878 STARTUPINFO stStartInfo;
3879 BOOL bSuccess = FALSE;
3882 Perl_croak(aTHX_ "usage: Win32::Spawn($cmdName, $args, $PID)");
3884 cmd = SvPV_nolen(ST(0));
3885 args = SvPV_nolen(ST(1));
3887 env = PerlEnv_get_childenv();
3888 dir = PerlEnv_get_childdir();
3890 memset(&stStartInfo, 0, sizeof(stStartInfo)); /* Clear the block */
3891 stStartInfo.cb = sizeof(stStartInfo); /* Set the structure size */
3892 stStartInfo.dwFlags = STARTF_USESHOWWINDOW; /* Enable wShowWindow control */
3893 stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE; /* Start min (normal) */
3896 cmd, /* Image path */
3897 args, /* Arguments for command line */
3898 NULL, /* Default process security */
3899 NULL, /* Default thread security */
3900 FALSE, /* Must be TRUE to use std handles */
3901 NORMAL_PRIORITY_CLASS, /* No special scheduling */
3902 env, /* Inherit our environment block */
3903 dir, /* Inherit our currrent directory */
3904 &stStartInfo, /* -> Startup info */
3905 &stProcInfo)) /* <- Process info (if OK) */
3907 int pid = (int)stProcInfo.dwProcessId;
3908 if (IsWin95() && pid < 0)
3910 sv_setiv(ST(2), pid);
3911 CloseHandle(stProcInfo.hThread);/* library source code does this. */
3914 PerlEnv_free_childenv(env);
3915 PerlEnv_free_childdir(dir);
3916 XSRETURN_IV(bSuccess);
3920 XS(w32_GetTickCount)
3923 DWORD msec = GetTickCount();
3931 XS(w32_GetShortPathName)
3938 Perl_croak(aTHX_ "usage: Win32::GetShortPathName($longPathName)");
3940 shortpath = sv_mortalcopy(ST(0));
3941 SvUPGRADE(shortpath, SVt_PV);
3942 if (!SvPVX(shortpath) || !SvLEN(shortpath))
3945 /* src == target is allowed */
3947 len = GetShortPathName(SvPVX(shortpath),
3950 } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
3952 SvCUR_set(shortpath,len);
3960 XS(w32_GetFullPathName)
3969 Perl_croak(aTHX_ "usage: Win32::GetFullPathName($filename)");
3972 fullpath = sv_mortalcopy(filename);
3973 SvUPGRADE(fullpath, SVt_PV);
3974 if (!SvPVX(fullpath) || !SvLEN(fullpath))
3978 len = GetFullPathName(SvPVX(filename),
3982 } while (len >= SvLEN(fullpath) && sv_grow(fullpath,len+1));
3984 if (GIMME_V == G_ARRAY) {
3986 XST_mPV(1,filepart);
3987 len = filepart - SvPVX(fullpath);
3990 SvCUR_set(fullpath,len);
3998 XS(w32_GetLongPathName)
4002 char tmpbuf[MAX_PATH+1];
4007 Perl_croak(aTHX_ "usage: Win32::GetLongPathName($pathname)");
4010 pathstr = SvPV(path,len);
4011 strcpy(tmpbuf, pathstr);
4012 pathstr = win32_longpath(tmpbuf);
4014 ST(0) = sv_2mortal(newSVpvn(pathstr, strlen(pathstr)));
4025 Perl_croak(aTHX_ "usage: Win32::Sleep($milliseconds)");
4036 Perl_croak(aTHX_ "usage: Win32::CopyFile($from, $to, $overwrite)");
4038 WCHAR wSourceFile[MAX_PATH+1];
4039 WCHAR wDestFile[MAX_PATH+1];
4040 A2WHELPER(SvPV_nolen(ST(0)), wSourceFile, sizeof(wSourceFile));
4041 wcscpy(wSourceFile, PerlDir_mapW(wSourceFile));
4042 A2WHELPER(SvPV_nolen(ST(1)), wDestFile, sizeof(wDestFile));
4043 bResult = CopyFileW(wSourceFile, PerlDir_mapW(wDestFile), !SvTRUE(ST(2)));
4046 char szSourceFile[MAX_PATH+1];
4047 strcpy(szSourceFile, PerlDir_mapA(SvPV_nolen(ST(0))));
4048 bResult = CopyFileA(szSourceFile, PerlDir_mapA(SvPV_nolen(ST(1))), !SvTRUE(ST(2)));
4057 Perl_init_os_extras(void)
4060 char *file = __FILE__;
4063 /* these names are Activeware compatible */
4064 newXS("Win32::GetCwd", w32_GetCwd, file);
4065 newXS("Win32::SetCwd", w32_SetCwd, file);
4066 newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
4067 newXS("Win32::GetLastError", w32_GetLastError, file);
4068 newXS("Win32::SetLastError", w32_SetLastError, file);
4069 newXS("Win32::LoginName", w32_LoginName, file);
4070 newXS("Win32::NodeName", w32_NodeName, file);
4071 newXS("Win32::DomainName", w32_DomainName, file);
4072 newXS("Win32::FsType", w32_FsType, file);
4073 newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
4074 newXS("Win32::IsWinNT", w32_IsWinNT, file);
4075 newXS("Win32::IsWin95", w32_IsWin95, file);
4076 newXS("Win32::FormatMessage", w32_FormatMessage, file);
4077 newXS("Win32::Spawn", w32_Spawn, file);
4078 newXS("Win32::GetTickCount", w32_GetTickCount, file);
4079 newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
4080 newXS("Win32::GetFullPathName", w32_GetFullPathName, file);
4081 newXS("Win32::GetLongPathName", w32_GetLongPathName, file);
4082 newXS("Win32::CopyFile", w32_CopyFile, file);
4083 newXS("Win32::Sleep", w32_Sleep, file);
4085 /* XXX Bloat Alert! The following Activeware preloads really
4086 * ought to be part of Win32::Sys::*, so they're not included
4089 /* LookupAccountName
4091 * InitiateSystemShutdown
4092 * AbortSystemShutdown
4093 * ExpandEnvrironmentStrings
4098 Perl_win32_init(int *argcp, char ***argvp)
4100 /* Disable floating point errors, Perl will trap the ones we
4101 * care about. VC++ RTL defaults to switching these off
4102 * already, but the Borland RTL doesn't. Since we don't
4103 * want to be at the vendor's whim on the default, we set
4104 * it explicitly here.
4106 #if !defined(_ALPHA_) && !defined(__GNUC__)
4107 _control87(MCW_EM, MCW_EM);
4113 win32_get_child_IO(child_IO_table* ptbl)
4115 ptbl->childStdIn = GetStdHandle(STD_INPUT_HANDLE);
4116 ptbl->childStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
4117 ptbl->childStdErr = GetStdHandle(STD_ERROR_HANDLE);
4120 #ifdef HAVE_INTERP_INTERN
4123 # undef Perl_sys_intern_init
4124 # define Perl_sys_intern_init CPerlObj::Perl_sys_intern_init
4125 # undef Perl_sys_intern_dup
4126 # define Perl_sys_intern_dup CPerlObj::Perl_sys_intern_dup
4127 # undef Perl_sys_intern_clear
4128 # define Perl_sys_intern_clear CPerlObj::Perl_sys_intern_clear
4133 Perl_sys_intern_init(pTHX)
4135 w32_perlshell_tokens = Nullch;
4136 w32_perlshell_vec = (char**)NULL;
4137 w32_perlshell_items = 0;
4138 w32_fdpid = newAV();
4139 New(1313, w32_children, 1, child_tab);
4140 w32_num_children = 0;
4141 # ifdef USE_ITHREADS
4143 New(1313, w32_pseudo_children, 1, child_tab);
4144 w32_num_pseudo_children = 0;
4146 w32_init_socktype = 0;
4150 Perl_sys_intern_clear(pTHX)
4152 Safefree(w32_perlshell_tokens);
4153 Safefree(w32_perlshell_vec);
4154 /* NOTE: w32_fdpid is freed by sv_clean_all() */
4155 Safefree(w32_children);
4156 # ifdef USE_ITHREADS
4157 Safefree(w32_pseudo_children);
4161 # ifdef USE_ITHREADS
4164 Perl_sys_intern_dup(pTHX_ struct interp_intern *src, struct interp_intern *dst)
4166 dst->perlshell_tokens = Nullch;
4167 dst->perlshell_vec = (char**)NULL;
4168 dst->perlshell_items = 0;
4169 dst->fdpid = newAV();
4170 Newz(1313, dst->children, 1, child_tab);
4172 Newz(1313, dst->pseudo_children, 1, child_tab);
4173 dst->thr_intern.Winit_socktype = 0;
4175 # endif /* USE_ITHREADS */
4176 #endif /* HAVE_INTERP_INTERN */
4184 win32_free_argvw(pTHXo_ void *ptr)
4186 char** argv = (char**)ptr;
4194 win32_argv2utf8(int argc, char** argv)
4199 LPWSTR* lpwStr = CommandLineToArgvW(GetCommandLineW(), &wargc);
4200 if (lpwStr && argc) {
4202 length = WideCharToMultiByte(CP_UTF8, 0, lpwStr[--wargc], -1, NULL, 0, NULL, NULL);
4203 Newz(0, psz, length, char);
4204 WideCharToMultiByte(CP_UTF8, 0, lpwStr[wargc], -1, psz, length, NULL, NULL);
4207 call_atexit(win32_free_argvw, argv);
4209 GlobalFree((HGLOBAL)lpwStr);