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() */
585 if (ckWARN(WARN_EXEC))
586 Perl_warner(aTHX_ WARN_EXEC, "Can't spawn \"%s\": %s", argv[0], strerror(errno));
591 PL_statusvalue = status;
598 do_spawn2(char *cmd, int exectype)
605 BOOL needToTry = TRUE;
608 /* Save an extra exec if possible. See if there are shell
609 * metacharacters in it */
610 if (!has_shell_metachars(cmd)) {
611 New(1301,argv, strlen(cmd) / 2 + 2, char*);
612 New(1302,cmd2, strlen(cmd) + 1, char);
615 for (s = cmd2; *s;) {
616 while (*s && isSPACE(*s))
620 while (*s && !isSPACE(*s))
629 status = win32_spawnvp(P_WAIT, argv[0],
630 (const char* const*)argv);
632 case EXECF_SPAWN_NOWAIT:
633 status = win32_spawnvp(P_NOWAIT, argv[0],
634 (const char* const*)argv);
637 status = win32_execvp(argv[0], (const char* const*)argv);
640 if (status != -1 || errno == 0)
650 New(1306, argv, w32_perlshell_items + 2, char*);
651 while (++i < w32_perlshell_items)
652 argv[i] = w32_perlshell_vec[i];
657 status = win32_spawnvp(P_WAIT, argv[0],
658 (const char* const*)argv);
660 case EXECF_SPAWN_NOWAIT:
661 status = win32_spawnvp(P_NOWAIT, argv[0],
662 (const char* const*)argv);
665 status = win32_execvp(argv[0], (const char* const*)argv);
671 if (exectype == EXECF_SPAWN_NOWAIT) {
673 PL_statusvalue = -1; /* >16bits hint for pp_system() */
678 if (ckWARN(WARN_EXEC))
679 Perl_warner(aTHX_ WARN_EXEC, "Can't %s \"%s\": %s",
680 (exectype == EXECF_EXEC ? "exec" : "spawn"),
681 cmd, strerror(errno));
686 PL_statusvalue = status;
694 return do_spawn2(cmd, EXECF_SPAWN);
698 do_spawn_nowait(char *cmd)
700 return do_spawn2(cmd, EXECF_SPAWN_NOWAIT);
704 Perl_do_exec(pTHX_ char *cmd)
706 do_spawn2(cmd, EXECF_EXEC);
710 /* The idea here is to read all the directory names into a string table
711 * (separated by nulls) and when one of the other dir functions is called
712 * return the pointer to the current file name.
715 win32_opendir(char *filename)
721 char scanname[MAX_PATH+3];
723 WIN32_FIND_DATAA aFindData;
724 WIN32_FIND_DATAW wFindData;
726 char buffer[MAX_PATH*2];
727 WCHAR wbuffer[MAX_PATH+1];
730 len = strlen(filename);
734 /* check to see if filename is a directory */
735 if (win32_stat(filename, &sbuf) < 0 || !S_ISDIR(sbuf.st_mode))
738 /* Get us a DIR structure */
739 Newz(1303, dirp, 1, DIR);
741 /* Create the search pattern */
742 strcpy(scanname, filename);
744 /* bare drive name means look in cwd for drive */
745 if (len == 2 && isALPHA(scanname[0]) && scanname[1] == ':') {
746 scanname[len++] = '.';
747 scanname[len++] = '/';
749 else if (scanname[len-1] != '/' && scanname[len-1] != '\\') {
750 scanname[len++] = '/';
752 scanname[len++] = '*';
753 scanname[len] = '\0';
755 /* do the FindFirstFile call */
757 A2WHELPER(scanname, wbuffer, sizeof(wbuffer));
758 fh = FindFirstFileW(PerlDir_mapW(wbuffer), &wFindData);
761 fh = FindFirstFileA(PerlDir_mapA(scanname), &aFindData);
764 if (fh == INVALID_HANDLE_VALUE) {
765 DWORD err = GetLastError();
766 /* FindFirstFile() fails on empty drives! */
768 case ERROR_FILE_NOT_FOUND:
770 case ERROR_NO_MORE_FILES:
771 case ERROR_PATH_NOT_FOUND:
774 case ERROR_NOT_ENOUGH_MEMORY:
785 /* now allocate the first part of the string table for
786 * the filenames that we find.
789 W2AHELPER(wFindData.cFileName, buffer, sizeof(buffer));
793 ptr = aFindData.cFileName;
800 New(1304, dirp->start, dirp->size, char);
801 strcpy(dirp->start, ptr);
803 dirp->end = dirp->curr = dirp->start;
809 /* Readdir just returns the current string pointer and bumps the
810 * string pointer to the nDllExport entry.
812 DllExport struct direct *
813 win32_readdir(DIR *dirp)
818 /* first set up the structure to return */
819 len = strlen(dirp->curr);
820 strcpy(dirp->dirstr.d_name, dirp->curr);
821 dirp->dirstr.d_namlen = len;
824 dirp->dirstr.d_ino = dirp->curr - dirp->start;
826 /* Now set up for the next call to readdir */
827 dirp->curr += len + 1;
828 if (dirp->curr >= dirp->end) {
832 WIN32_FIND_DATAW wFindData;
833 WIN32_FIND_DATAA aFindData;
834 char buffer[MAX_PATH*2];
836 /* finding the next file that matches the wildcard
837 * (which should be all of them in this directory!).
840 res = FindNextFileW(dirp->handle, &wFindData);
842 W2AHELPER(wFindData.cFileName, buffer, sizeof(buffer));
847 res = FindNextFileA(dirp->handle, &aFindData);
849 ptr = aFindData.cFileName;
852 long endpos = dirp->end - dirp->start;
853 long newsize = endpos + strlen(ptr) + 1;
854 /* bump the string table size by enough for the
855 * new name and it's null terminator */
856 while (newsize > dirp->size) {
857 long curpos = dirp->curr - dirp->start;
859 Renew(dirp->start, dirp->size, char);
860 dirp->curr = dirp->start + curpos;
862 strcpy(dirp->start + endpos, ptr);
863 dirp->end = dirp->start + newsize;
869 return &(dirp->dirstr);
875 /* Telldir returns the current string pointer position */
877 win32_telldir(DIR *dirp)
879 return (dirp->curr - dirp->start);
883 /* Seekdir moves the string pointer to a previously saved position
884 * (returned by telldir).
887 win32_seekdir(DIR *dirp, long loc)
889 dirp->curr = dirp->start + loc;
892 /* Rewinddir resets the string pointer to the start */
894 win32_rewinddir(DIR *dirp)
896 dirp->curr = dirp->start;
899 /* free the memory allocated by opendir */
901 win32_closedir(DIR *dirp)
904 if (dirp->handle != INVALID_HANDLE_VALUE)
905 FindClose(dirp->handle);
906 Safefree(dirp->start);
919 * Just pretend that everyone is a superuser. NT will let us know if
920 * we don\'t really have permission to do something.
923 #define ROOT_UID ((uid_t)0)
924 #define ROOT_GID ((gid_t)0)
953 return (auid == ROOT_UID ? 0 : -1);
959 return (agid == ROOT_GID ? 0 : -1);
966 char *buf = w32_getlogin_buffer;
967 DWORD size = sizeof(w32_getlogin_buffer);
968 if (GetUserName(buf,&size))
974 chown(const char *path, uid_t owner, gid_t group)
984 long child = w32_num_children;
985 while (--child >= 0) {
986 if (w32_child_pids[child] == pid)
993 remove_dead_process(long child)
997 CloseHandle(w32_child_handles[child]);
998 Move(&w32_child_handles[child+1], &w32_child_handles[child],
999 (w32_num_children-child-1), HANDLE);
1000 Move(&w32_child_pids[child+1], &w32_child_pids[child],
1001 (w32_num_children-child-1), DWORD);
1008 find_pseudo_pid(int pid)
1011 long child = w32_num_pseudo_children;
1012 while (--child >= 0) {
1013 if (w32_pseudo_child_pids[child] == pid)
1020 remove_dead_pseudo_process(long child)
1024 CloseHandle(w32_pseudo_child_handles[child]);
1025 Move(&w32_pseudo_child_handles[child+1], &w32_pseudo_child_handles[child],
1026 (w32_num_pseudo_children-child-1), HANDLE);
1027 Move(&w32_pseudo_child_pids[child+1], &w32_pseudo_child_pids[child],
1028 (w32_num_pseudo_children-child-1), DWORD);
1029 w32_num_pseudo_children--;
1035 win32_kill(int pid, int sig)
1042 /* it is a pseudo-forked child */
1043 child = find_pseudo_pid(-pid);
1047 hProcess = w32_pseudo_child_handles[child];
1048 if (TerminateThread(hProcess, sig)) {
1049 remove_dead_pseudo_process(child);
1053 else if (IsWin95()) {
1061 child = find_pid(pid);
1065 hProcess = w32_child_handles[child];
1066 if (TerminateProcess(hProcess, sig)) {
1067 remove_dead_process(child);
1073 hProcess = OpenProcess(PROCESS_ALL_ACCESS, TRUE,
1074 (IsWin95() ? -pid : pid));
1078 if (TerminateProcess(hProcess, sig)) {
1079 CloseHandle(hProcess);
1093 DllExport unsigned int
1094 win32_sleep(unsigned int t)
1101 win32_stat(const char *path, struct stat *sbuf)
1104 char buffer[MAX_PATH+1];
1105 int l = strlen(path);
1107 WCHAR wbuffer[MAX_PATH+1];
1113 switch(path[l - 1]) {
1114 /* FindFirstFile() and stat() are buggy with a trailing
1115 * backslash, so change it to a forward slash :-( */
1117 strncpy(buffer, path, l-1);
1118 buffer[l - 1] = '/';
1122 /* FindFirstFile() is buggy with "x:", so add a dot :-( */
1124 if (l == 2 && isALPHA(path[0])) {
1125 buffer[0] = path[0];
1136 /* We *must* open & close the file once; otherwise file attribute changes */
1137 /* might not yet have propagated to "other" hard links of the same file. */
1138 /* This also gives us an opportunity to determine the number of links. */
1140 A2WHELPER(path, wbuffer, sizeof(wbuffer));
1141 pwbuffer = PerlDir_mapW(wbuffer);
1142 handle = CreateFileW(pwbuffer, 0, 0, NULL, OPEN_EXISTING, 0, NULL);
1145 path = PerlDir_mapA(path);
1147 handle = CreateFileA(path, 0, 0, NULL, OPEN_EXISTING, 0, NULL);
1149 if (handle != INVALID_HANDLE_VALUE) {
1150 BY_HANDLE_FILE_INFORMATION bhi;
1151 if (GetFileInformationByHandle(handle, &bhi))
1152 nlink = bhi.nNumberOfLinks;
1153 CloseHandle(handle);
1156 /* pwbuffer or path will be mapped correctly above */
1158 res = _wstat(pwbuffer, (struct _stat *)sbuf);
1161 res = stat(path, sbuf);
1163 sbuf->st_nlink = nlink;
1166 /* CRT is buggy on sharenames, so make sure it really isn't.
1167 * XXX using GetFileAttributesEx() will enable us to set
1168 * sbuf->st_*time (but note that's not available on the
1169 * Windows of 1995) */
1172 r = GetFileAttributesW(pwbuffer);
1175 r = GetFileAttributesA(path);
1177 if (r != 0xffffffff && (r & FILE_ATTRIBUTE_DIRECTORY)) {
1178 /* sbuf may still contain old garbage since stat() failed */
1179 Zero(sbuf, 1, struct stat);
1180 sbuf->st_mode = S_IFDIR | S_IREAD;
1182 if (!(r & FILE_ATTRIBUTE_READONLY))
1183 sbuf->st_mode |= S_IWRITE | S_IEXEC;
1188 if (l == 3 && isALPHA(path[0]) && path[1] == ':'
1189 && (path[2] == '\\' || path[2] == '/'))
1191 /* The drive can be inaccessible, some _stat()s are buggy */
1193 ? !GetVolumeInformationW(pwbuffer,NULL,0,NULL,NULL,NULL,NULL,0)
1194 : !GetVolumeInformationA(path,NULL,0,NULL,NULL,NULL,NULL,0)) {
1200 if (S_ISDIR(sbuf->st_mode))
1201 sbuf->st_mode |= S_IWRITE | S_IEXEC;
1202 else if (S_ISREG(sbuf->st_mode)) {
1204 if (l >= 4 && path[l-4] == '.') {
1205 const char *e = path + l - 3;
1206 if (strnicmp(e,"exe",3)
1207 && strnicmp(e,"bat",3)
1208 && strnicmp(e,"com",3)
1209 && (IsWin95() || strnicmp(e,"cmd",3)))
1210 sbuf->st_mode &= ~S_IEXEC;
1212 sbuf->st_mode |= S_IEXEC;
1215 sbuf->st_mode &= ~S_IEXEC;
1216 /* Propagate permissions to _group_ and _others_ */
1217 perms = sbuf->st_mode & (S_IREAD|S_IWRITE|S_IEXEC);
1218 sbuf->st_mode |= (perms>>3) | (perms>>6);
1225 /* Find the longname of a given path. path is destructively modified.
1226 * It should have space for at least MAX_PATH characters. */
1228 win32_longpath(char *path)
1230 WIN32_FIND_DATA fdata;
1232 char tmpbuf[MAX_PATH+1];
1233 char *tmpstart = tmpbuf;
1240 if (isALPHA(path[0]) && path[1] == ':' &&
1241 (path[2] == '/' || path[2] == '\\'))
1244 *tmpstart++ = path[0];
1248 else if ((path[0] == '/' || path[0] == '\\') &&
1249 (path[1] == '/' || path[1] == '\\'))
1252 *tmpstart++ = path[0];
1253 *tmpstart++ = path[1];
1254 /* copy machine name */
1255 while (*start && *start != '/' && *start != '\\')
1256 *tmpstart++ = *start++;
1258 *tmpstart++ = *start;
1260 /* copy share name */
1261 while (*start && *start != '/' && *start != '\\')
1262 *tmpstart++ = *start++;
1266 if (sep == '/' || sep == '\\')
1270 /* walk up to slash */
1271 while (*start && *start != '/' && *start != '\\')
1274 /* discard doubled slashes */
1275 while (*start && (start[1] == '/' || start[1] == '\\'))
1279 /* stop and find full name of component */
1281 fhand = FindFirstFile(path,&fdata);
1282 if (fhand != INVALID_HANDLE_VALUE) {
1283 strcpy(tmpstart, fdata.cFileName);
1284 tmpstart += strlen(fdata.cFileName);
1292 /* failed a step, just return without side effects */
1293 /*PerlIO_printf(Perl_debug_log, "Failed to find %s\n", path);*/
1298 strcpy(path,tmpbuf);
1302 #ifndef USE_WIN32_RTL_ENV
1305 win32_getenv(const char *name)
1308 WCHAR wBuffer[MAX_PATH+1];
1310 SV *curitem = Nullsv;
1313 A2WHELPER(name, wBuffer, sizeof(wBuffer));
1314 needlen = GetEnvironmentVariableW(wBuffer, NULL, 0);
1317 needlen = GetEnvironmentVariableA(name,NULL,0);
1319 curitem = sv_2mortal(newSVpvn("", 0));
1323 SvGROW(curitem, (needlen+1)*sizeof(WCHAR));
1324 needlen = GetEnvironmentVariableW(wBuffer,
1325 (WCHAR*)SvPVX(curitem),
1327 } while (needlen >= SvLEN(curitem)/sizeof(WCHAR));
1328 SvCUR_set(curitem, (needlen*sizeof(WCHAR))+1);
1329 acuritem = sv_2mortal(newSVsv(curitem));
1330 W2AHELPER((WCHAR*)SvPVX(acuritem), SvPVX(curitem), SvCUR(curitem));
1334 SvGROW(curitem, needlen+1);
1335 needlen = GetEnvironmentVariableA(name,SvPVX(curitem),
1337 } while (needlen >= SvLEN(curitem));
1338 SvCUR_set(curitem, needlen);
1342 /* allow any environment variables that begin with 'PERL'
1343 to be stored in the registry */
1344 if (strncmp(name, "PERL", 4) == 0)
1345 (void)get_regstr(name, &curitem);
1347 if (curitem && SvCUR(curitem))
1348 return SvPVX(curitem);
1354 win32_putenv(const char *name)
1361 int length, relval = -1;
1365 length = strlen(name)+1;
1366 New(1309,wCuritem,length,WCHAR);
1367 A2WHELPER(name, wCuritem, length*sizeof(WCHAR));
1368 wVal = wcschr(wCuritem, '=');
1371 if (SetEnvironmentVariableW(wCuritem, *wVal ? wVal : NULL))
1377 New(1309,curitem,strlen(name)+1,char);
1378 strcpy(curitem, name);
1379 val = strchr(curitem, '=');
1381 /* The sane way to deal with the environment.
1382 * Has these advantages over putenv() & co.:
1383 * * enables us to store a truly empty value in the
1384 * environment (like in UNIX).
1385 * * we don't have to deal with RTL globals, bugs and leaks.
1387 * Why you may want to enable USE_WIN32_RTL_ENV:
1388 * * environ[] and RTL functions will not reflect changes,
1389 * which might be an issue if extensions want to access
1390 * the env. via RTL. This cuts both ways, since RTL will
1391 * not see changes made by extensions that call the Win32
1392 * functions directly, either.
1396 if (SetEnvironmentVariableA(curitem, *val ? val : NULL))
1408 filetime_to_clock(PFILETIME ft)
1410 __int64 qw = ft->dwHighDateTime;
1412 qw |= ft->dwLowDateTime;
1413 qw /= 10000; /* File time ticks at 0.1uS, clock at 1mS */
1418 win32_times(struct tms *timebuf)
1423 if (GetProcessTimes(GetCurrentProcess(), &dummy, &dummy,
1425 timebuf->tms_utime = filetime_to_clock(&user);
1426 timebuf->tms_stime = filetime_to_clock(&kernel);
1427 timebuf->tms_cutime = 0;
1428 timebuf->tms_cstime = 0;
1431 /* That failed - e.g. Win95 fallback to clock() */
1432 clock_t t = clock();
1433 timebuf->tms_utime = t;
1434 timebuf->tms_stime = 0;
1435 timebuf->tms_cutime = 0;
1436 timebuf->tms_cstime = 0;
1441 /* fix utime() so it works on directories in NT */
1443 filetime_from_time(PFILETIME pFileTime, time_t Time)
1445 struct tm *pTM = localtime(&Time);
1446 SYSTEMTIME SystemTime;
1452 SystemTime.wYear = pTM->tm_year + 1900;
1453 SystemTime.wMonth = pTM->tm_mon + 1;
1454 SystemTime.wDay = pTM->tm_mday;
1455 SystemTime.wHour = pTM->tm_hour;
1456 SystemTime.wMinute = pTM->tm_min;
1457 SystemTime.wSecond = pTM->tm_sec;
1458 SystemTime.wMilliseconds = 0;
1460 return SystemTimeToFileTime(&SystemTime, &LocalTime) &&
1461 LocalFileTimeToFileTime(&LocalTime, pFileTime);
1465 win32_unlink(const char *filename)
1472 WCHAR wBuffer[MAX_PATH+1];
1475 A2WHELPER(filename, wBuffer, sizeof(wBuffer));
1476 pwBuffer = PerlDir_mapW(wBuffer);
1477 attrs = GetFileAttributesW(pwBuffer);
1478 if (attrs == 0xFFFFFFFF)
1480 if (attrs & FILE_ATTRIBUTE_READONLY) {
1481 (void)SetFileAttributesW(pwBuffer, attrs & ~FILE_ATTRIBUTE_READONLY);
1482 ret = _wunlink(pwBuffer);
1484 (void)SetFileAttributesW(pwBuffer, attrs);
1487 ret = _wunlink(pwBuffer);
1490 filename = PerlDir_mapA(filename);
1491 attrs = GetFileAttributesA(filename);
1492 if (attrs == 0xFFFFFFFF)
1494 if (attrs & FILE_ATTRIBUTE_READONLY) {
1495 (void)SetFileAttributesA(filename, attrs & ~FILE_ATTRIBUTE_READONLY);
1496 ret = unlink(filename);
1498 (void)SetFileAttributesA(filename, attrs);
1501 ret = unlink(filename);
1510 win32_utime(const char *filename, struct utimbuf *times)
1517 struct utimbuf TimeBuffer;
1518 WCHAR wbuffer[MAX_PATH+1];
1523 A2WHELPER(filename, wbuffer, sizeof(wbuffer));
1524 pwbuffer = PerlDir_mapW(wbuffer);
1525 rc = _wutime(pwbuffer, (struct _utimbuf*)times);
1528 filename = PerlDir_mapA(filename);
1529 rc = utime(filename, times);
1531 /* EACCES: path specifies directory or readonly file */
1532 if (rc == 0 || errno != EACCES /* || !IsWinNT() */)
1535 if (times == NULL) {
1536 times = &TimeBuffer;
1537 time(×->actime);
1538 times->modtime = times->actime;
1541 /* This will (and should) still fail on readonly files */
1543 handle = CreateFileW(pwbuffer, GENERIC_READ | GENERIC_WRITE,
1544 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1545 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1548 handle = CreateFileA(filename, GENERIC_READ | GENERIC_WRITE,
1549 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1550 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1552 if (handle == INVALID_HANDLE_VALUE)
1555 if (GetFileTime(handle, &ftCreate, &ftAccess, &ftWrite) &&
1556 filetime_from_time(&ftAccess, times->actime) &&
1557 filetime_from_time(&ftWrite, times->modtime) &&
1558 SetFileTime(handle, &ftCreate, &ftAccess, &ftWrite))
1563 CloseHandle(handle);
1568 win32_uname(struct utsname *name)
1570 struct hostent *hep;
1571 STRLEN nodemax = sizeof(name->nodename)-1;
1572 OSVERSIONINFO osver;
1574 memset(&osver, 0, sizeof(OSVERSIONINFO));
1575 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1576 if (GetVersionEx(&osver)) {
1578 switch (osver.dwPlatformId) {
1579 case VER_PLATFORM_WIN32_WINDOWS:
1580 strcpy(name->sysname, "Windows");
1582 case VER_PLATFORM_WIN32_NT:
1583 strcpy(name->sysname, "Windows NT");
1585 case VER_PLATFORM_WIN32s:
1586 strcpy(name->sysname, "Win32s");
1589 strcpy(name->sysname, "Win32 Unknown");
1594 sprintf(name->release, "%d.%d",
1595 osver.dwMajorVersion, osver.dwMinorVersion);
1598 sprintf(name->version, "Build %d",
1599 osver.dwPlatformId == VER_PLATFORM_WIN32_NT
1600 ? osver.dwBuildNumber : (osver.dwBuildNumber & 0xffff));
1601 if (osver.szCSDVersion[0]) {
1602 char *buf = name->version + strlen(name->version);
1603 sprintf(buf, " (%s)", osver.szCSDVersion);
1607 *name->sysname = '\0';
1608 *name->version = '\0';
1609 *name->release = '\0';
1613 hep = win32_gethostbyname("localhost");
1615 STRLEN len = strlen(hep->h_name);
1616 if (len <= nodemax) {
1617 strcpy(name->nodename, hep->h_name);
1620 strncpy(name->nodename, hep->h_name, nodemax);
1621 name->nodename[nodemax] = '\0';
1626 if (!GetComputerName(name->nodename, &sz))
1627 *name->nodename = '\0';
1630 /* machine (architecture) */
1634 GetSystemInfo(&info);
1636 #if (defined(__BORLANDC__)&&(__BORLANDC__<=0x520)) || defined(__MINGW32__)
1637 switch (info.u.s.wProcessorArchitecture) {
1639 switch (info.wProcessorArchitecture) {
1641 case PROCESSOR_ARCHITECTURE_INTEL:
1642 arch = "x86"; break;
1643 case PROCESSOR_ARCHITECTURE_MIPS:
1644 arch = "mips"; break;
1645 case PROCESSOR_ARCHITECTURE_ALPHA:
1646 arch = "alpha"; break;
1647 case PROCESSOR_ARCHITECTURE_PPC:
1648 arch = "ppc"; break;
1650 arch = "unknown"; break;
1652 strcpy(name->machine, arch);
1658 win32_waitpid(int pid, int *status, int flags)
1661 DWORD timeout = (flags & WNOHANG) ? 0 : INFINITE;
1664 if (pid == -1) /* XXX threadid == 1 ? */
1665 return win32_wait(status);
1668 child = find_pseudo_pid(-pid);
1670 HANDLE hThread = w32_pseudo_child_handles[child];
1671 DWORD waitcode = WaitForSingleObject(hThread, timeout);
1672 if (waitcode == WAIT_TIMEOUT) {
1675 else if (waitcode != WAIT_FAILED) {
1676 if (GetExitCodeThread(hThread, &waitcode)) {
1677 *status = (int)((waitcode & 0xff) << 8);
1678 retval = (int)w32_pseudo_child_pids[child];
1679 remove_dead_pseudo_process(child);
1686 else if (IsWin95()) {
1695 child = find_pid(pid);
1697 hProcess = w32_child_handles[child];
1698 waitcode = WaitForSingleObject(hProcess, timeout);
1699 if (waitcode == WAIT_TIMEOUT) {
1702 else if (waitcode != WAIT_FAILED) {
1703 if (GetExitCodeProcess(hProcess, &waitcode)) {
1704 *status = (int)((waitcode & 0xff) << 8);
1705 retval = (int)w32_child_pids[child];
1706 remove_dead_process(child);
1715 hProcess = OpenProcess(PROCESS_ALL_ACCESS, TRUE,
1716 (IsWin95() ? -pid : pid));
1718 waitcode = WaitForSingleObject(hProcess, timeout);
1719 if (waitcode == WAIT_TIMEOUT) {
1722 else if (waitcode != WAIT_FAILED) {
1723 if (GetExitCodeProcess(hProcess, &waitcode)) {
1724 *status = (int)((waitcode & 0xff) << 8);
1725 CloseHandle(hProcess);
1729 CloseHandle(hProcess);
1735 return retval >= 0 ? pid : retval;
1739 win32_wait(int *status)
1741 /* XXX this wait emulation only knows about processes
1742 * spawned via win32_spawnvp(P_NOWAIT, ...).
1746 DWORD exitcode, waitcode;
1749 if (w32_num_pseudo_children) {
1750 waitcode = WaitForMultipleObjects(w32_num_pseudo_children,
1751 w32_pseudo_child_handles,
1754 if (waitcode != WAIT_FAILED) {
1755 if (waitcode >= WAIT_ABANDONED_0
1756 && waitcode < WAIT_ABANDONED_0 + w32_num_pseudo_children)
1757 i = waitcode - WAIT_ABANDONED_0;
1759 i = waitcode - WAIT_OBJECT_0;
1760 if (GetExitCodeThread(w32_pseudo_child_handles[i], &exitcode)) {
1761 *status = (int)((exitcode & 0xff) << 8);
1762 retval = (int)w32_pseudo_child_pids[i];
1763 remove_dead_pseudo_process(i);
1770 if (!w32_num_children) {
1775 /* if a child exists, wait for it to die */
1776 waitcode = WaitForMultipleObjects(w32_num_children,
1780 if (waitcode != WAIT_FAILED) {
1781 if (waitcode >= WAIT_ABANDONED_0
1782 && waitcode < WAIT_ABANDONED_0 + w32_num_children)
1783 i = waitcode - WAIT_ABANDONED_0;
1785 i = waitcode - WAIT_OBJECT_0;
1786 if (GetExitCodeProcess(w32_child_handles[i], &exitcode) ) {
1787 *status = (int)((exitcode & 0xff) << 8);
1788 retval = (int)w32_child_pids[i];
1789 remove_dead_process(i);
1795 errno = GetLastError();
1801 static UINT timerid = 0;
1803 static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
1806 KillTimer(NULL,timerid);
1808 CALL_FPTR(PL_sighandlerp)(14);
1810 #endif /* !PERL_OBJECT */
1812 DllExport unsigned int
1813 win32_alarm(unsigned int sec)
1817 * the 'obvious' implentation is SetTimer() with a callback
1818 * which does whatever receiving SIGALRM would do
1819 * we cannot use SIGALRM even via raise() as it is not
1820 * one of the supported codes in <signal.h>
1822 * Snag is unless something is looking at the message queue
1823 * nothing happens :-(
1828 timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
1830 Perl_croak_nocontext("Cannot set timer");
1836 KillTimer(NULL,timerid);
1840 #endif /* !PERL_OBJECT */
1844 #ifdef HAVE_DES_FCRYPT
1845 extern char * des_fcrypt(const char *txt, const char *salt, char *cbuf);
1849 win32_crypt(const char *txt, const char *salt)
1852 #ifdef HAVE_DES_FCRYPT
1854 return des_fcrypt(txt, salt, w32_crypt_buffer);
1856 Perl_croak(aTHX_ "The crypt() function is unimplemented due to excessive paranoia.");
1861 /* C doesn't like repeat struct definitions */
1863 #if defined(USE_FIXED_OSFHANDLE) || defined(PERL_MSVCRT_READFIX)
1866 #define _CRTIMP __declspec(dllimport)
1870 * Control structure for lowio file handles
1873 long osfhnd; /* underlying OS file HANDLE */
1874 char osfile; /* attributes of file (e.g., open in text mode?) */
1875 char pipech; /* one char buffer for handles opened on pipes */
1877 CRITICAL_SECTION lock;
1882 * Array of arrays of control structures for lowio files.
1884 EXTERN_C _CRTIMP ioinfo* __pioinfo[];
1887 * Definition of IOINFO_L2E, the log base 2 of the number of elements in each
1888 * array of ioinfo structs.
1890 #define IOINFO_L2E 5
1893 * Definition of IOINFO_ARRAY_ELTS, the number of elements in ioinfo array
1895 #define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
1898 * Access macros for getting at an ioinfo struct and its fields from a
1901 #define _pioinfo(i) (__pioinfo[(i) >> IOINFO_L2E] + ((i) & (IOINFO_ARRAY_ELTS - 1)))
1902 #define _osfhnd(i) (_pioinfo(i)->osfhnd)
1903 #define _osfile(i) (_pioinfo(i)->osfile)
1904 #define _pipech(i) (_pioinfo(i)->pipech)
1908 #ifdef USE_FIXED_OSFHANDLE
1910 #define FOPEN 0x01 /* file handle open */
1911 #define FNOINHERIT 0x10 /* file handle opened O_NOINHERIT */
1912 #define FAPPEND 0x20 /* file handle opened O_APPEND */
1913 #define FDEV 0x40 /* file handle refers to device */
1914 #define FTEXT 0x80 /* file handle is in text mode */
1917 *int my_open_osfhandle(long osfhandle, int flags) - open C Runtime file handle
1920 * This function allocates a free C Runtime file handle and associates
1921 * it with the Win32 HANDLE specified by the first parameter. This is a
1922 * temperary fix for WIN95's brain damage GetFileType() error on socket
1923 * we just bypass that call for socket
1925 * This works with MSVC++ 4.0+ or GCC/Mingw32
1928 * long osfhandle - Win32 HANDLE to associate with C Runtime file handle.
1929 * int flags - flags to associate with C Runtime file handle.
1932 * returns index of entry in fh, if successful
1933 * return -1, if no free entry is found
1937 *******************************************************************************/
1940 * we fake up some parts of the CRT that aren't exported by MSVCRT.dll
1941 * this lets sockets work on Win9X with GCC and should fix the problems
1946 /* since we are not doing a dup2(), this works fine */
1948 #define _set_osfhnd(fh, osfh) (void)(_osfhnd(fh) = osfh)
1950 /* create an ioinfo entry, kill its handle, and steal the entry */
1955 HANDLE hF = CreateFile("NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
1956 int fh = _open_osfhandle((long)hF, 0);
1960 EnterCriticalSection(&(_pioinfo(fh)->lock));
1965 my_open_osfhandle(long osfhandle, int flags)
1968 char fileflags; /* _osfile flags */
1970 /* copy relevant flags from second parameter */
1973 if (flags & O_APPEND)
1974 fileflags |= FAPPEND;
1979 if (flags & O_NOINHERIT)
1980 fileflags |= FNOINHERIT;
1982 /* attempt to allocate a C Runtime file handle */
1983 if ((fh = _alloc_osfhnd()) == -1) {
1984 errno = EMFILE; /* too many open files */
1985 _doserrno = 0L; /* not an OS error */
1986 return -1; /* return error to caller */
1989 /* the file is open. now, set the info in _osfhnd array */
1990 _set_osfhnd(fh, osfhandle);
1992 fileflags |= FOPEN; /* mark as open */
1994 _osfile(fh) = fileflags; /* set osfile entry */
1995 LeaveCriticalSection(&_pioinfo(fh)->lock);
1997 return fh; /* return handle */
2000 #endif /* USE_FIXED_OSFHANDLE */
2002 /* simulate flock by locking a range on the file */
2004 #define LK_ERR(f,i) ((f) ? (i = 0) : (errno = GetLastError()))
2005 #define LK_LEN 0xffff0000
2008 win32_flock(int fd, int oper)
2016 Perl_croak_nocontext("flock() unimplemented on this platform");
2019 fh = (HANDLE)_get_osfhandle(fd);
2020 memset(&o, 0, sizeof(o));
2023 case LOCK_SH: /* shared lock */
2024 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
2026 case LOCK_EX: /* exclusive lock */
2027 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
2029 case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
2030 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
2032 case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
2033 LK_ERR(LockFileEx(fh,
2034 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
2035 0, LK_LEN, 0, &o),i);
2037 case LOCK_UN: /* unlock lock */
2038 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, 0, &o),i);
2040 default: /* unknown */
2051 * redirected io subsystem for all XS modules
2064 return (&(_environ));
2067 /* the rest are the remapped stdio routines */
2087 win32_ferror(FILE *fp)
2089 return (ferror(fp));
2094 win32_feof(FILE *fp)
2100 * Since the errors returned by the socket error function
2101 * WSAGetLastError() are not known by the library routine strerror
2102 * we have to roll our own.
2106 win32_strerror(int e)
2108 #ifndef __BORLANDC__ /* Borland intolerance */
2109 extern int sys_nerr;
2113 if (e < 0 || e > sys_nerr) {
2118 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
2119 w32_strerror_buffer,
2120 sizeof(w32_strerror_buffer), NULL) == 0)
2121 strcpy(w32_strerror_buffer, "Unknown Error");
2123 return w32_strerror_buffer;
2129 win32_str_os_error(void *sv, DWORD dwErr)
2133 dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
2134 |FORMAT_MESSAGE_IGNORE_INSERTS
2135 |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
2136 dwErr, 0, (char *)&sMsg, 1, NULL);
2137 /* strip trailing whitespace and period */
2140 --dwLen; /* dwLen doesn't include trailing null */
2141 } while (0 < dwLen && isSPACE(sMsg[dwLen]));
2142 if ('.' != sMsg[dwLen])
2147 sMsg = (char*)LocalAlloc(0, 64/**sizeof(TCHAR)*/);
2149 dwLen = sprintf(sMsg,
2150 "Unknown error #0x%lX (lookup 0x%lX)",
2151 dwErr, GetLastError());
2155 sv_setpvn((SV*)sv, sMsg, dwLen);
2162 win32_fprintf(FILE *fp, const char *format, ...)
2165 va_start(marker, format); /* Initialize variable arguments. */
2167 return (vfprintf(fp, format, marker));
2171 win32_printf(const char *format, ...)
2174 va_start(marker, format); /* Initialize variable arguments. */
2176 return (vprintf(format, marker));
2180 win32_vfprintf(FILE *fp, const char *format, va_list args)
2182 return (vfprintf(fp, format, args));
2186 win32_vprintf(const char *format, va_list args)
2188 return (vprintf(format, args));
2192 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
2194 return fread(buf, size, count, fp);
2198 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
2200 return fwrite(buf, size, count, fp);
2203 #define MODE_SIZE 10
2206 win32_fopen(const char *filename, const char *mode)
2209 WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH+1];
2215 if (stricmp(filename, "/dev/null")==0)
2219 A2WHELPER(mode, wMode, sizeof(wMode));
2220 A2WHELPER(filename, wBuffer, sizeof(wBuffer));
2221 f = _wfopen(PerlDir_mapW(wBuffer), wMode);
2224 f = fopen(PerlDir_mapA(filename), mode);
2225 /* avoid buffering headaches for child processes */
2226 if (f && *mode == 'a')
2227 win32_fseek(f, 0, SEEK_END);
2231 #ifndef USE_SOCKETS_AS_HANDLES
2233 #define fdopen my_fdopen
2237 win32_fdopen(int handle, const char *mode)
2240 WCHAR wMode[MODE_SIZE];
2243 A2WHELPER(mode, wMode, sizeof(wMode));
2244 f = _wfdopen(handle, wMode);
2247 f = fdopen(handle, (char *) mode);
2248 /* avoid buffering headaches for child processes */
2249 if (f && *mode == 'a')
2250 win32_fseek(f, 0, SEEK_END);
2255 win32_freopen(const char *path, const char *mode, FILE *stream)
2258 WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH+1];
2259 if (stricmp(path, "/dev/null")==0)
2263 A2WHELPER(mode, wMode, sizeof(wMode));
2264 A2WHELPER(path, wBuffer, sizeof(wBuffer));
2265 return _wfreopen(PerlDir_mapW(wBuffer), wMode, stream);
2267 return freopen(PerlDir_mapA(path), mode, stream);
2271 win32_fclose(FILE *pf)
2273 return my_fclose(pf); /* defined in win32sck.c */
2277 win32_fputs(const char *s,FILE *pf)
2279 return fputs(s, pf);
2283 win32_fputc(int c,FILE *pf)
2289 win32_ungetc(int c,FILE *pf)
2291 return ungetc(c,pf);
2295 win32_getc(FILE *pf)
2301 win32_fileno(FILE *pf)
2307 win32_clearerr(FILE *pf)
2314 win32_fflush(FILE *pf)
2320 win32_ftell(FILE *pf)
2326 win32_fseek(FILE *pf,long offset,int origin)
2328 return fseek(pf, offset, origin);
2332 win32_fgetpos(FILE *pf,fpos_t *p)
2334 return fgetpos(pf, p);
2338 win32_fsetpos(FILE *pf,const fpos_t *p)
2340 return fsetpos(pf, p);
2344 win32_rewind(FILE *pf)
2364 win32_fstat(int fd,struct stat *sbufptr)
2366 return fstat(fd,sbufptr);
2370 win32_pipe(int *pfd, unsigned int size, int mode)
2372 return _pipe(pfd, size, mode);
2376 * a popen() clone that respects PERL5SHELL
2380 win32_popen(const char *command, const char *mode)
2382 #ifdef USE_RTL_POPEN
2383 return _popen(command, mode);
2391 /* establish which ends read and write */
2392 if (strchr(mode,'w')) {
2393 stdfd = 0; /* stdin */
2397 else if (strchr(mode,'r')) {
2398 stdfd = 1; /* stdout */
2405 /* set the correct mode */
2406 if (strchr(mode,'b'))
2408 else if (strchr(mode,'t'))
2411 ourmode = _fmode & (O_TEXT | O_BINARY);
2413 /* the child doesn't inherit handles */
2414 ourmode |= O_NOINHERIT;
2416 if (win32_pipe( p, 512, ourmode) == -1)
2419 /* save current stdfd */
2420 if ((oldfd = win32_dup(stdfd)) == -1)
2423 /* make stdfd go to child end of pipe (implicitly closes stdfd) */
2424 /* stdfd will be inherited by the child */
2425 if (win32_dup2(p[child], stdfd) == -1)
2428 /* close the child end in parent */
2429 win32_close(p[child]);
2431 /* start the child */
2434 if ((childpid = do_spawn_nowait((char*)command)) == -1)
2437 /* revert stdfd to whatever it was before */
2438 if (win32_dup2(oldfd, stdfd) == -1)
2441 /* close saved handle */
2445 sv_setiv(*av_fetch(w32_fdpid, p[parent], TRUE), childpid);
2448 /* set process id so that it can be returned by perl's open() */
2449 PL_forkprocess = childpid;
2452 /* we have an fd, return a file stream */
2453 return (win32_fdopen(p[parent], (char *)mode));
2456 /* we don't need to check for errors here */
2460 win32_dup2(oldfd, stdfd);
2465 #endif /* USE_RTL_POPEN */
2473 win32_pclose(FILE *pf)
2475 #ifdef USE_RTL_POPEN
2479 int childpid, status;
2483 sv = *av_fetch(w32_fdpid, win32_fileno(pf), TRUE);
2486 childpid = SvIVX(sv);
2499 if (win32_waitpid(childpid, &status, 0) == -1)
2504 #endif /* USE_RTL_POPEN */
2510 LPCWSTR lpExistingFileName,
2511 LPSECURITY_ATTRIBUTES lpSecurityAttributes)
2514 WCHAR wFullName[MAX_PATH+1];
2515 LPVOID lpContext = NULL;
2516 WIN32_STREAM_ID StreamId;
2517 DWORD dwSize = (char*)&StreamId.cStreamName - (char*)&StreamId;
2522 BOOL (__stdcall *pfnBackupWrite)(HANDLE, LPBYTE, DWORD, LPDWORD,
2523 BOOL, BOOL, LPVOID*) =
2524 (BOOL (__stdcall *)(HANDLE, LPBYTE, DWORD, LPDWORD,
2525 BOOL, BOOL, LPVOID*))
2526 GetProcAddress(GetModuleHandle("kernel32.dll"), "BackupWrite");
2527 if (pfnBackupWrite == NULL)
2530 dwLen = GetFullPathNameW(lpFileName, MAX_PATH, wFullName, NULL);
2533 dwLen = (dwLen+1)*sizeof(WCHAR);
2535 handle = CreateFileW(lpExistingFileName, FILE_WRITE_ATTRIBUTES,
2536 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
2537 NULL, OPEN_EXISTING, 0, NULL);
2538 if (handle == INVALID_HANDLE_VALUE)
2541 StreamId.dwStreamId = BACKUP_LINK;
2542 StreamId.dwStreamAttributes = 0;
2543 StreamId.dwStreamNameSize = 0;
2544 #if defined(__BORLANDC__) || defined(__MINGW32__)
2545 StreamId.Size.u.HighPart = 0;
2546 StreamId.Size.u.LowPart = dwLen;
2548 StreamId.Size.HighPart = 0;
2549 StreamId.Size.LowPart = dwLen;
2552 bSuccess = pfnBackupWrite(handle, (LPBYTE)&StreamId, dwSize, &dwWritten,
2553 FALSE, FALSE, &lpContext);
2555 bSuccess = pfnBackupWrite(handle, (LPBYTE)wFullName, dwLen, &dwWritten,
2556 FALSE, FALSE, &lpContext);
2557 pfnBackupWrite(handle, NULL, 0, &dwWritten, TRUE, FALSE, &lpContext);
2560 CloseHandle(handle);
2565 win32_link(const char *oldname, const char *newname)
2568 BOOL (__stdcall *pfnCreateHardLinkW)(LPCWSTR,LPCWSTR,LPSECURITY_ATTRIBUTES);
2569 WCHAR wOldName[MAX_PATH+1];
2570 WCHAR wNewName[MAX_PATH+1];
2573 Perl_croak(aTHX_ PL_no_func, "link");
2575 pfnCreateHardLinkW =
2576 (BOOL (__stdcall *)(LPCWSTR, LPCWSTR, LPSECURITY_ATTRIBUTES))
2577 GetProcAddress(GetModuleHandle("kernel32.dll"), "CreateHardLinkW");
2578 if (pfnCreateHardLinkW == NULL)
2579 pfnCreateHardLinkW = Nt4CreateHardLinkW;
2581 if ((A2WHELPER(oldname, wOldName, sizeof(wOldName))) &&
2582 (A2WHELPER(newname, wNewName, sizeof(wNewName))) &&
2583 (wcscpy(wOldName, PerlDir_mapW(wOldName)),
2584 pfnCreateHardLinkW(PerlDir_mapW(wNewName), wOldName, NULL)))
2588 errno = (GetLastError() == ERROR_FILE_NOT_FOUND) ? ENOENT : EINVAL;
2593 win32_rename(const char *oname, const char *newname)
2595 WCHAR wOldName[MAX_PATH+1];
2596 WCHAR wNewName[MAX_PATH+1];
2597 char szOldName[MAX_PATH+1];
2598 char szNewName[MAX_PATH+1];
2602 /* XXX despite what the documentation says about MoveFileEx(),
2603 * it doesn't work under Windows95!
2606 DWORD dwFlags = MOVEFILE_COPY_ALLOWED;
2608 A2WHELPER(oname, wOldName, sizeof(wOldName));
2609 A2WHELPER(newname, wNewName, sizeof(wNewName));
2610 if (wcsicmp(wNewName, wOldName))
2611 dwFlags |= MOVEFILE_REPLACE_EXISTING;
2612 wcscpy(wOldName, PerlDir_mapW(wOldName));
2613 bResult = MoveFileExW(wOldName,PerlDir_mapW(wNewName), dwFlags);
2616 if (stricmp(newname, oname))
2617 dwFlags |= MOVEFILE_REPLACE_EXISTING;
2618 strcpy(szOldName, PerlDir_mapA(oname));
2619 bResult = MoveFileExA(szOldName,PerlDir_mapA(newname), dwFlags);
2622 DWORD err = GetLastError();
2624 case ERROR_BAD_NET_NAME:
2625 case ERROR_BAD_NETPATH:
2626 case ERROR_BAD_PATHNAME:
2627 case ERROR_FILE_NOT_FOUND:
2628 case ERROR_FILENAME_EXCED_RANGE:
2629 case ERROR_INVALID_DRIVE:
2630 case ERROR_NO_MORE_FILES:
2631 case ERROR_PATH_NOT_FOUND:
2644 char szTmpName[MAX_PATH+1];
2645 char dname[MAX_PATH+1];
2646 char *endname = Nullch;
2648 DWORD from_attr, to_attr;
2650 strcpy(szOldName, PerlDir_mapA(oname));
2651 strcpy(szNewName, PerlDir_mapA(newname));
2653 /* if oname doesn't exist, do nothing */
2654 from_attr = GetFileAttributes(szOldName);
2655 if (from_attr == 0xFFFFFFFF) {
2660 /* if newname exists, rename it to a temporary name so that we
2661 * don't delete it in case oname happens to be the same file
2662 * (but perhaps accessed via a different path)
2664 to_attr = GetFileAttributes(szNewName);
2665 if (to_attr != 0xFFFFFFFF) {
2666 /* if newname is a directory, we fail
2667 * XXX could overcome this with yet more convoluted logic */
2668 if (to_attr & FILE_ATTRIBUTE_DIRECTORY) {
2672 tmplen = strlen(szNewName);
2673 strcpy(szTmpName,szNewName);
2674 endname = szTmpName+tmplen;
2675 for (; endname > szTmpName ; --endname) {
2676 if (*endname == '/' || *endname == '\\') {
2681 if (endname > szTmpName)
2682 endname = strcpy(dname,szTmpName);
2686 /* get a temporary filename in same directory
2687 * XXX is this really the best we can do? */
2688 if (!GetTempFileName((LPCTSTR)endname, "plr", 0, szTmpName)) {
2692 DeleteFile(szTmpName);
2694 retval = rename(szNewName, szTmpName);
2701 /* rename oname to newname */
2702 retval = rename(szOldName, szNewName);
2704 /* if we created a temporary file before ... */
2705 if (endname != Nullch) {
2706 /* ...and rename succeeded, delete temporary file/directory */
2708 DeleteFile(szTmpName);
2709 /* else restore it to what it was */
2711 (void)rename(szTmpName, szNewName);
2718 win32_setmode(int fd, int mode)
2720 return setmode(fd, mode);
2724 win32_lseek(int fd, long offset, int origin)
2726 return lseek(fd, offset, origin);
2736 win32_open(const char *path, int flag, ...)
2741 WCHAR wBuffer[MAX_PATH+1];
2744 pmode = va_arg(ap, int);
2747 if (stricmp(path, "/dev/null")==0)
2751 A2WHELPER(path, wBuffer, sizeof(wBuffer));
2752 return _wopen(PerlDir_mapW(wBuffer), flag, pmode);
2754 return open(PerlDir_mapA(path), flag, pmode);
2776 win32_dup2(int fd1,int fd2)
2778 return dup2(fd1,fd2);
2781 #ifdef PERL_MSVCRT_READFIX
2783 #define LF 10 /* line feed */
2784 #define CR 13 /* carriage return */
2785 #define CTRLZ 26 /* ctrl-z means eof for text */
2786 #define FOPEN 0x01 /* file handle open */
2787 #define FEOFLAG 0x02 /* end of file has been encountered */
2788 #define FCRLF 0x04 /* CR-LF across read buffer (in text mode) */
2789 #define FPIPE 0x08 /* file handle refers to a pipe */
2790 #define FAPPEND 0x20 /* file handle opened O_APPEND */
2791 #define FDEV 0x40 /* file handle refers to device */
2792 #define FTEXT 0x80 /* file handle is in text mode */
2793 #define MAX_DESCRIPTOR_COUNT (64*32) /* this is the maximun that MSVCRT can handle */
2796 _fixed_read(int fh, void *buf, unsigned cnt)
2798 int bytes_read; /* number of bytes read */
2799 char *buffer; /* buffer to read to */
2800 int os_read; /* bytes read on OS call */
2801 char *p, *q; /* pointers into buffer */
2802 char peekchr; /* peek-ahead character */
2803 ULONG filepos; /* file position after seek */
2804 ULONG dosretval; /* o.s. return value */
2806 /* validate handle */
2807 if (((unsigned)fh >= (unsigned)MAX_DESCRIPTOR_COUNT) ||
2808 !(_osfile(fh) & FOPEN))
2810 /* out of range -- return error */
2812 _doserrno = 0; /* not o.s. error */
2817 * If lockinitflag is FALSE, assume fd is device
2818 * lockinitflag is set to TRUE by open.
2820 if (_pioinfo(fh)->lockinitflag)
2821 EnterCriticalSection(&(_pioinfo(fh)->lock)); /* lock file */
2823 bytes_read = 0; /* nothing read yet */
2824 buffer = (char*)buf;
2826 if (cnt == 0 || (_osfile(fh) & FEOFLAG)) {
2827 /* nothing to read or at EOF, so return 0 read */
2831 if ((_osfile(fh) & (FPIPE|FDEV)) && _pipech(fh) != LF) {
2832 /* a pipe/device and pipe lookahead non-empty: read the lookahead
2834 *buffer++ = _pipech(fh);
2837 _pipech(fh) = LF; /* mark as empty */
2842 if (!ReadFile((HANDLE)_osfhnd(fh), buffer, cnt, (LPDWORD)&os_read, NULL))
2844 /* ReadFile has reported an error. recognize two special cases.
2846 * 1. map ERROR_ACCESS_DENIED to EBADF
2848 * 2. just return 0 if ERROR_BROKEN_PIPE has occurred. it
2849 * means the handle is a read-handle on a pipe for which
2850 * all write-handles have been closed and all data has been
2853 if ((dosretval = GetLastError()) == ERROR_ACCESS_DENIED) {
2854 /* wrong read/write mode should return EBADF, not EACCES */
2856 _doserrno = dosretval;
2860 else if (dosretval == ERROR_BROKEN_PIPE) {
2870 bytes_read += os_read; /* update bytes read */
2872 if (_osfile(fh) & FTEXT) {
2873 /* now must translate CR-LFs to LFs in the buffer */
2875 /* set CRLF flag to indicate LF at beginning of buffer */
2876 /* if ((os_read != 0) && (*(char *)buf == LF)) */
2877 /* _osfile(fh) |= FCRLF; */
2879 /* _osfile(fh) &= ~FCRLF; */
2881 _osfile(fh) &= ~FCRLF;
2883 /* convert chars in the buffer: p is src, q is dest */
2885 while (p < (char *)buf + bytes_read) {
2887 /* if fh is not a device, set ctrl-z flag */
2888 if (!(_osfile(fh) & FDEV))
2889 _osfile(fh) |= FEOFLAG;
2890 break; /* stop translating */
2895 /* *p is CR, so must check next char for LF */
2896 if (p < (char *)buf + bytes_read - 1) {
2899 *q++ = LF; /* convert CR-LF to LF */
2902 *q++ = *p++; /* store char normally */
2905 /* This is the hard part. We found a CR at end of
2906 buffer. We must peek ahead to see if next char
2911 if (!ReadFile((HANDLE)_osfhnd(fh), &peekchr, 1,
2912 (LPDWORD)&os_read, NULL))
2913 dosretval = GetLastError();
2915 if (dosretval != 0 || os_read == 0) {
2916 /* couldn't read ahead, store CR */
2920 /* peekchr now has the extra character -- we now
2921 have several possibilities:
2922 1. disk file and char is not LF; just seek back
2924 2. disk file and char is LF; store LF, don't seek back
2925 3. pipe/device and char is LF; store LF.
2926 4. pipe/device and char isn't LF, store CR and
2927 put char in pipe lookahead buffer. */
2928 if (_osfile(fh) & (FDEV|FPIPE)) {
2929 /* non-seekable device */
2934 _pipech(fh) = peekchr;
2939 if (peekchr == LF) {
2940 /* nothing read yet; must make some
2943 /* turn on this flag for tell routine */
2944 _osfile(fh) |= FCRLF;
2947 HANDLE osHandle; /* o.s. handle value */
2949 if ((osHandle = (HANDLE)_get_osfhandle(fh)) != (HANDLE)-1)
2951 if ((filepos = SetFilePointer(osHandle, -1, NULL, FILE_CURRENT)) == -1)
2952 dosretval = GetLastError();
2963 /* we now change bytes_read to reflect the true number of chars
2965 bytes_read = q - (char *)buf;
2969 if (_pioinfo(fh)->lockinitflag)
2970 LeaveCriticalSection(&(_pioinfo(fh)->lock)); /* unlock file */
2975 #endif /* PERL_MSVCRT_READFIX */
2978 win32_read(int fd, void *buf, unsigned int cnt)
2980 #ifdef PERL_MSVCRT_READFIX
2981 return _fixed_read(fd, buf, cnt);
2983 return read(fd, buf, cnt);
2988 win32_write(int fd, const void *buf, unsigned int cnt)
2990 return write(fd, buf, cnt);
2994 win32_mkdir(const char *dir, int mode)
2998 WCHAR wBuffer[MAX_PATH+1];
2999 A2WHELPER(dir, wBuffer, sizeof(wBuffer));
3000 return _wmkdir(PerlDir_mapW(wBuffer));
3002 return mkdir(PerlDir_mapA(dir)); /* just ignore mode */
3006 win32_rmdir(const char *dir)
3010 WCHAR wBuffer[MAX_PATH+1];
3011 A2WHELPER(dir, wBuffer, sizeof(wBuffer));
3012 return _wrmdir(PerlDir_mapW(wBuffer));
3014 return rmdir(PerlDir_mapA(dir));
3018 win32_chdir(const char *dir)
3022 WCHAR wBuffer[MAX_PATH+1];
3023 A2WHELPER(dir, wBuffer, sizeof(wBuffer));
3024 return _wchdir(wBuffer);
3030 win32_access(const char *path, int mode)
3034 WCHAR wBuffer[MAX_PATH+1];
3035 A2WHELPER(path, wBuffer, sizeof(wBuffer));
3036 return _waccess(PerlDir_mapW(wBuffer), mode);
3038 return access(PerlDir_mapA(path), mode);
3042 win32_chmod(const char *path, int mode)
3046 WCHAR wBuffer[MAX_PATH+1];
3047 A2WHELPER(path, wBuffer, sizeof(wBuffer));
3048 return _wchmod(PerlDir_mapW(wBuffer), mode);
3050 return chmod(PerlDir_mapA(path), mode);
3055 create_command_line(const char* command, const char * const *args)
3059 char *cmd, *ptr, *arg;
3060 STRLEN len = strlen(command) + 1;
3062 for (index = 0; (ptr = (char*)args[index]) != NULL; ++index)
3063 len += strlen(ptr) + 1;
3065 New(1310, cmd, len, char);
3067 strcpy(ptr, command);
3069 for (index = 0; (arg = (char*)args[index]) != NULL; ++index) {
3079 qualified_path(const char *cmd)
3083 char *fullcmd, *curfullcmd;
3089 fullcmd = (char*)cmd;
3091 if (*fullcmd == '/' || *fullcmd == '\\')
3098 pathstr = win32_getenv("PATH");
3099 New(0, fullcmd, MAX_PATH+1, char);
3100 curfullcmd = fullcmd;
3105 /* start by appending the name to the current prefix */
3106 strcpy(curfullcmd, cmd);
3107 curfullcmd += cmdlen;
3109 /* if it doesn't end with '.', or has no extension, try adding
3110 * a trailing .exe first */
3111 if (cmd[cmdlen-1] != '.'
3112 && (cmdlen < 4 || cmd[cmdlen-4] != '.'))
3114 strcpy(curfullcmd, ".exe");
3115 res = GetFileAttributes(fullcmd);
3116 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
3121 /* that failed, try the bare name */
3122 res = GetFileAttributes(fullcmd);
3123 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
3126 /* quit if no other path exists, or if cmd already has path */
3127 if (!pathstr || !*pathstr || has_slash)
3130 /* skip leading semis */
3131 while (*pathstr == ';')
3134 /* build a new prefix from scratch */
3135 curfullcmd = fullcmd;
3136 while (*pathstr && *pathstr != ';') {
3137 if (*pathstr == '"') { /* foo;"baz;etc";bar */
3138 pathstr++; /* skip initial '"' */
3139 while (*pathstr && *pathstr != '"') {
3140 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
3141 *curfullcmd++ = *pathstr;
3145 pathstr++; /* skip trailing '"' */
3148 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
3149 *curfullcmd++ = *pathstr;
3154 pathstr++; /* skip trailing semi */
3155 if (curfullcmd > fullcmd /* append a dir separator */
3156 && curfullcmd[-1] != '/' && curfullcmd[-1] != '\\')
3158 *curfullcmd++ = '\\';
3166 /* The following are just place holders.
3167 * Some hosts may provide and environment that the OS is
3168 * not tracking, therefore, these host must provide that
3169 * environment and the current directory to CreateProcess
3179 free_childenv(void* d)
3188 char szfilename[(MAX_PATH+1)*2];
3190 WCHAR wfilename[MAX_PATH+1];
3191 GetCurrentDirectoryW(MAX_PATH+1, wfilename);
3192 W2AHELPER(wfilename, szfilename, sizeof(szfilename));
3195 GetCurrentDirectoryA(MAX_PATH+1, szfilename);
3198 New(0, ptr, strlen(szfilename)+1, char);
3199 strcpy(ptr, szfilename);
3204 free_childdir(char* d)
3211 /* XXX this needs to be made more compatible with the spawnvp()
3212 * provided by the various RTLs. In particular, searching for
3213 * *.{com,bat,cmd} files (as done by the RTLs) is unimplemented.
3214 * This doesn't significantly affect perl itself, because we
3215 * always invoke things using PERL5SHELL if a direct attempt to
3216 * spawn the executable fails.
3218 * XXX splitting and rejoining the commandline between do_aspawn()
3219 * and win32_spawnvp() could also be avoided.
3223 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
3225 #ifdef USE_RTL_SPAWNVP
3226 return spawnvp(mode, cmdname, (char * const *)argv);
3233 STARTUPINFO StartupInfo;
3234 PROCESS_INFORMATION ProcessInformation;
3237 char *cmd = create_command_line(cmdname, strcmp(cmdname, argv[0]) == 0
3239 char *fullcmd = Nullch;
3241 env = PerlEnv_get_childenv();
3242 dir = PerlEnv_get_childdir();
3245 case P_NOWAIT: /* asynch + remember result */
3246 if (w32_num_children >= MAXIMUM_WAIT_OBJECTS) {
3252 case P_WAIT: /* synchronous execution */
3254 default: /* invalid mode */
3259 memset(&StartupInfo,0,sizeof(StartupInfo));
3260 StartupInfo.cb = sizeof(StartupInfo);
3261 memset(&tbl,0,sizeof(tbl));
3262 PerlEnv_get_child_IO(&tbl);
3263 StartupInfo.dwFlags = tbl.dwFlags;
3264 StartupInfo.dwX = tbl.dwX;
3265 StartupInfo.dwY = tbl.dwY;
3266 StartupInfo.dwXSize = tbl.dwXSize;
3267 StartupInfo.dwYSize = tbl.dwYSize;
3268 StartupInfo.dwXCountChars = tbl.dwXCountChars;
3269 StartupInfo.dwYCountChars = tbl.dwYCountChars;
3270 StartupInfo.dwFillAttribute = tbl.dwFillAttribute;
3271 StartupInfo.wShowWindow = tbl.wShowWindow;
3272 StartupInfo.hStdInput = tbl.childStdIn;
3273 StartupInfo.hStdOutput = tbl.childStdOut;
3274 StartupInfo.hStdError = tbl.childStdErr;
3275 if (StartupInfo.hStdInput != INVALID_HANDLE_VALUE &&
3276 StartupInfo.hStdOutput != INVALID_HANDLE_VALUE &&
3277 StartupInfo.hStdError != INVALID_HANDLE_VALUE)
3279 StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
3282 create |= CREATE_NEW_CONSOLE;
3286 if (!CreateProcess(cmdname, /* search PATH to find executable */
3287 cmd, /* executable, and its arguments */
3288 NULL, /* process attributes */
3289 NULL, /* thread attributes */
3290 TRUE, /* inherit handles */
3291 create, /* creation flags */
3292 (LPVOID)env, /* inherit environment */
3293 dir, /* inherit cwd */
3295 &ProcessInformation))
3297 /* initial NULL argument to CreateProcess() does a PATH
3298 * search, but it always first looks in the directory
3299 * where the current process was started, which behavior
3300 * is undesirable for backward compatibility. So we
3301 * jump through our own hoops by picking out the path
3302 * we really want it to use. */
3304 fullcmd = qualified_path(cmdname);
3315 if (mode == P_NOWAIT) {
3316 /* asynchronous spawn -- store handle, return PID */
3317 ret = (int)ProcessInformation.dwProcessId;
3318 if (IsWin95() && ret < 0)
3321 w32_child_handles[w32_num_children] = ProcessInformation.hProcess;
3322 w32_child_pids[w32_num_children] = (DWORD)ret;
3327 WaitForSingleObject(ProcessInformation.hProcess, INFINITE);
3328 GetExitCodeProcess(ProcessInformation.hProcess, &status);
3330 CloseHandle(ProcessInformation.hProcess);
3333 CloseHandle(ProcessInformation.hThread);
3336 PerlEnv_free_childenv(env);
3337 PerlEnv_free_childdir(dir);
3345 win32_execv(const char *cmdname, const char *const *argv)
3349 /* if this is a pseudo-forked child, we just want to spawn
3350 * the new program, and return */
3352 return spawnv(P_WAIT, cmdname, (char *const *)argv);
3354 return execv(cmdname, (char *const *)argv);
3358 win32_execvp(const char *cmdname, const char *const *argv)
3362 /* if this is a pseudo-forked child, we just want to spawn
3363 * the new program, and return */
3365 return win32_spawnvp(P_WAIT, cmdname, (char *const *)argv);
3367 return execvp(cmdname, (char *const *)argv);
3371 win32_perror(const char *str)
3377 win32_setbuf(FILE *pf, char *buf)
3383 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
3385 return setvbuf(pf, buf, type, size);
3389 win32_flushall(void)
3395 win32_fcloseall(void)
3401 win32_fgets(char *s, int n, FILE *pf)
3403 return fgets(s, n, pf);
3413 win32_fgetc(FILE *pf)
3419 win32_putc(int c, FILE *pf)
3425 win32_puts(const char *s)
3437 win32_putchar(int c)
3444 #ifndef USE_PERL_SBRK
3446 static char *committed = NULL;
3447 static char *base = NULL;
3448 static char *reserved = NULL;
3449 static char *brk = NULL;
3450 static DWORD pagesize = 0;
3451 static DWORD allocsize = 0;
3459 GetSystemInfo(&info);
3460 /* Pretend page size is larger so we don't perpetually
3461 * call the OS to commit just one page ...
3463 pagesize = info.dwPageSize << 3;
3464 allocsize = info.dwAllocationGranularity;
3466 /* This scheme fails eventually if request for contiguous
3467 * block is denied so reserve big blocks - this is only
3468 * address space not memory ...
3470 if (brk+need >= reserved)
3472 DWORD size = 64*1024*1024;
3474 if (committed && reserved && committed < reserved)
3476 /* Commit last of previous chunk cannot span allocations */
3477 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
3479 committed = reserved;
3481 /* Reserve some (more) space
3482 * Note this is a little sneaky, 1st call passes NULL as reserved
3483 * so lets system choose where we start, subsequent calls pass
3484 * the old end address so ask for a contiguous block
3486 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
3489 reserved = addr+size;
3504 if (brk > committed)
3506 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
3507 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
3522 win32_malloc(size_t size)
3524 return malloc(size);
3528 win32_calloc(size_t numitems, size_t size)
3530 return calloc(numitems,size);
3534 win32_realloc(void *block, size_t size)
3536 return realloc(block,size);
3540 win32_free(void *block)
3547 win32_open_osfhandle(long handle, int flags)
3549 #ifdef USE_FIXED_OSFHANDLE
3551 return my_open_osfhandle(handle, flags);
3553 return _open_osfhandle(handle, flags);
3557 win32_get_osfhandle(int fd)
3559 return _get_osfhandle(fd);
3563 win32_dynaload(const char* filename)
3567 char buf[MAX_PATH+1];
3570 /* LoadLibrary() doesn't recognize forward slashes correctly,
3571 * so turn 'em back. */
3572 first = strchr(filename, '/');
3574 STRLEN len = strlen(filename);
3575 if (len <= MAX_PATH) {
3576 strcpy(buf, filename);
3577 filename = &buf[first - filename];
3579 if (*filename == '/')
3580 *(char*)filename = '\\';
3587 WCHAR wfilename[MAX_PATH+1];
3588 A2WHELPER(filename, wfilename, sizeof(wfilename));
3589 hModule = LoadLibraryExW(PerlDir_mapW(wfilename), NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
3592 hModule = LoadLibraryExA(PerlDir_mapA(filename), NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
3605 /* Make the host for current directory */
3606 char* ptr = PerlEnv_get_childdir();
3609 * then it worked, set PV valid,
3610 * else return 'undef'
3613 SV *sv = sv_newmortal();
3615 PerlEnv_free_childdir(ptr);
3630 Perl_croak(aTHX_ "usage: Win32::SetCurrentDirectory($cwd)");
3631 if (!PerlDir_chdir(SvPV_nolen(ST(0))))
3638 XS(w32_GetNextAvailDrive)
3642 char root[] = "_:\\";
3647 if (GetDriveType(root) == 1) {
3656 XS(w32_GetLastError)
3660 XSRETURN_IV(GetLastError());
3664 XS(w32_SetLastError)
3668 Perl_croak(aTHX_ "usage: Win32::SetLastError($error)");
3669 SetLastError(SvIV(ST(0)));
3677 char *name = w32_getlogin_buffer;
3678 DWORD size = sizeof(w32_getlogin_buffer);
3680 if (GetUserName(name,&size)) {
3681 /* size includes NULL */
3682 ST(0) = sv_2mortal(newSVpvn(name,size-1));
3692 char name[MAX_COMPUTERNAME_LENGTH+1];
3693 DWORD size = sizeof(name);
3695 if (GetComputerName(name,&size)) {
3696 /* size does NOT include NULL :-( */
3697 ST(0) = sv_2mortal(newSVpvn(name,size));
3708 HINSTANCE hNetApi32 = LoadLibrary("netapi32.dll");
3709 DWORD (__stdcall *pfnNetApiBufferFree)(LPVOID Buffer);
3710 DWORD (__stdcall *pfnNetWkstaGetInfo)(LPWSTR servername, DWORD level,
3714 pfnNetApiBufferFree = (DWORD (__stdcall *)(void *))
3715 GetProcAddress(hNetApi32, "NetApiBufferFree");
3716 pfnNetWkstaGetInfo = (DWORD (__stdcall *)(LPWSTR, DWORD, void *))
3717 GetProcAddress(hNetApi32, "NetWkstaGetInfo");
3720 if (hNetApi32 && pfnNetWkstaGetInfo && pfnNetApiBufferFree) {
3721 /* this way is more reliable, in case user has a local account. */
3723 DWORD dnamelen = sizeof(dname);
3725 DWORD wki100_platform_id;
3726 LPWSTR wki100_computername;
3727 LPWSTR wki100_langroup;
3728 DWORD wki100_ver_major;
3729 DWORD wki100_ver_minor;
3731 /* NERR_Success *is* 0*/
3732 if (0 == pfnNetWkstaGetInfo(NULL, 100, &pwi)) {
3733 if (pwi->wki100_langroup && *(pwi->wki100_langroup)) {
3734 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_langroup,
3735 -1, (LPSTR)dname, dnamelen, NULL, NULL);
3738 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_computername,
3739 -1, (LPSTR)dname, dnamelen, NULL, NULL);
3741 pfnNetApiBufferFree(pwi);
3742 FreeLibrary(hNetApi32);
3745 FreeLibrary(hNetApi32);
3748 /* Win95 doesn't have NetWksta*(), so do it the old way */
3750 DWORD size = sizeof(name);
3752 FreeLibrary(hNetApi32);
3753 if (GetUserName(name,&size)) {
3754 char sid[ONE_K_BUFSIZE];
3755 DWORD sidlen = sizeof(sid);
3757 DWORD dnamelen = sizeof(dname);
3759 if (LookupAccountName(NULL, name, (PSID)&sid, &sidlen,
3760 dname, &dnamelen, &snu)) {
3761 XSRETURN_PV(dname); /* all that for this */
3773 DWORD flags, filecomplen;
3774 if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
3775 &flags, fsname, sizeof(fsname))) {
3776 if (GIMME_V == G_ARRAY) {
3777 XPUSHs(sv_2mortal(newSVpvn(fsname,strlen(fsname))));
3778 XPUSHs(sv_2mortal(newSViv(flags)));
3779 XPUSHs(sv_2mortal(newSViv(filecomplen)));
3784 XSRETURN_PV(fsname);
3790 XS(w32_GetOSVersion)
3793 OSVERSIONINFOA osver;
3796 OSVERSIONINFOW osverw;
3797 char szCSDVersion[sizeof(osverw.szCSDVersion)];
3798 osverw.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
3799 if (!GetVersionExW(&osverw)) {
3802 W2AHELPER(osverw.szCSDVersion, szCSDVersion, sizeof(szCSDVersion));
3803 XPUSHs(newSVpvn(szCSDVersion, strlen(szCSDVersion)));
3804 osver.dwMajorVersion = osverw.dwMajorVersion;
3805 osver.dwMinorVersion = osverw.dwMinorVersion;
3806 osver.dwBuildNumber = osverw.dwBuildNumber;
3807 osver.dwPlatformId = osverw.dwPlatformId;
3810 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOA);
3811 if (!GetVersionExA(&osver)) {
3814 XPUSHs(newSVpvn(osver.szCSDVersion, strlen(osver.szCSDVersion)));
3816 XPUSHs(newSViv(osver.dwMajorVersion));
3817 XPUSHs(newSViv(osver.dwMinorVersion));
3818 XPUSHs(newSViv(osver.dwBuildNumber));
3819 XPUSHs(newSViv(osver.dwPlatformId));
3828 XSRETURN_IV(IsWinNT());
3836 XSRETURN_IV(IsWin95());
3840 XS(w32_FormatMessage)
3844 char msgbuf[ONE_K_BUFSIZE];
3847 Perl_croak(aTHX_ "usage: Win32::FormatMessage($errno)");
3850 WCHAR wmsgbuf[ONE_K_BUFSIZE];
3851 if (FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM,
3852 &source, SvIV(ST(0)), 0,
3853 wmsgbuf, ONE_K_BUFSIZE-1, NULL))
3855 W2AHELPER(wmsgbuf, msgbuf, sizeof(msgbuf));
3856 XSRETURN_PV(msgbuf);
3860 if (FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM,
3861 &source, SvIV(ST(0)), 0,
3862 msgbuf, sizeof(msgbuf)-1, NULL))
3863 XSRETURN_PV(msgbuf);
3874 PROCESS_INFORMATION stProcInfo;
3875 STARTUPINFO stStartInfo;
3876 BOOL bSuccess = FALSE;
3879 Perl_croak(aTHX_ "usage: Win32::Spawn($cmdName, $args, $PID)");
3881 cmd = SvPV_nolen(ST(0));
3882 args = SvPV_nolen(ST(1));
3884 memset(&stStartInfo, 0, sizeof(stStartInfo)); /* Clear the block */
3885 stStartInfo.cb = sizeof(stStartInfo); /* Set the structure size */
3886 stStartInfo.dwFlags = STARTF_USESHOWWINDOW; /* Enable wShowWindow control */
3887 stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE; /* Start min (normal) */
3890 cmd, /* Image path */
3891 args, /* Arguments for command line */
3892 NULL, /* Default process security */
3893 NULL, /* Default thread security */
3894 FALSE, /* Must be TRUE to use std handles */
3895 NORMAL_PRIORITY_CLASS, /* No special scheduling */
3896 NULL, /* Inherit our environment block */
3897 NULL, /* Inherit our currrent directory */
3898 &stStartInfo, /* -> Startup info */
3899 &stProcInfo)) /* <- Process info (if OK) */
3901 int pid = (int)stProcInfo.dwProcessId;
3902 if (IsWin95() && pid < 0)
3904 sv_setiv(ST(2), pid);
3905 CloseHandle(stProcInfo.hThread);/* library source code does this. */
3908 XSRETURN_IV(bSuccess);
3912 XS(w32_GetTickCount)
3915 DWORD msec = GetTickCount();
3923 XS(w32_GetShortPathName)
3930 Perl_croak(aTHX_ "usage: Win32::GetShortPathName($longPathName)");
3932 shortpath = sv_mortalcopy(ST(0));
3933 SvUPGRADE(shortpath, SVt_PV);
3934 if (!SvPVX(shortpath) || !SvLEN(shortpath))
3937 /* src == target is allowed */
3939 len = GetShortPathName(SvPVX(shortpath),
3942 } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
3944 SvCUR_set(shortpath,len);
3952 XS(w32_GetFullPathName)
3961 Perl_croak(aTHX_ "usage: Win32::GetFullPathName($filename)");
3964 fullpath = sv_mortalcopy(filename);
3965 SvUPGRADE(fullpath, SVt_PV);
3966 if (!SvPVX(fullpath) || !SvLEN(fullpath))
3970 len = GetFullPathName(SvPVX(filename),
3974 } while (len >= SvLEN(fullpath) && sv_grow(fullpath,len+1));
3976 if (GIMME_V == G_ARRAY) {
3978 XST_mPV(1,filepart);
3979 len = filepart - SvPVX(fullpath);
3982 SvCUR_set(fullpath,len);
3990 XS(w32_GetLongPathName)
3994 char tmpbuf[MAX_PATH+1];
3999 Perl_croak(aTHX_ "usage: Win32::GetLongPathName($pathname)");
4002 pathstr = SvPV(path,len);
4003 strcpy(tmpbuf, pathstr);
4004 pathstr = win32_longpath(tmpbuf);
4006 ST(0) = sv_2mortal(newSVpvn(pathstr, strlen(pathstr)));
4017 Perl_croak(aTHX_ "usage: Win32::Sleep($milliseconds)");
4028 Perl_croak(aTHX_ "usage: Win32::CopyFile($from, $to, $overwrite)");
4030 WCHAR wSourceFile[MAX_PATH+1];
4031 WCHAR wDestFile[MAX_PATH+1];
4032 A2WHELPER(SvPV_nolen(ST(0)), wSourceFile, sizeof(wSourceFile));
4033 wcscpy(wSourceFile, PerlDir_mapW(wSourceFile));
4034 A2WHELPER(SvPV_nolen(ST(1)), wDestFile, sizeof(wDestFile));
4035 bResult = CopyFileW(wSourceFile, PerlDir_mapW(wDestFile), !SvTRUE(ST(2)));
4038 char szSourceFile[MAX_PATH+1];
4039 strcpy(szSourceFile, PerlDir_mapA(SvPV_nolen(ST(0))));
4040 bResult = CopyFileA(szSourceFile, PerlDir_mapA(SvPV_nolen(ST(1))), !SvTRUE(ST(2)));
4049 Perl_init_os_extras(void)
4052 char *file = __FILE__;
4055 /* these names are Activeware compatible */
4056 newXS("Win32::GetCwd", w32_GetCwd, file);
4057 newXS("Win32::SetCwd", w32_SetCwd, file);
4058 newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
4059 newXS("Win32::GetLastError", w32_GetLastError, file);
4060 newXS("Win32::SetLastError", w32_SetLastError, file);
4061 newXS("Win32::LoginName", w32_LoginName, file);
4062 newXS("Win32::NodeName", w32_NodeName, file);
4063 newXS("Win32::DomainName", w32_DomainName, file);
4064 newXS("Win32::FsType", w32_FsType, file);
4065 newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
4066 newXS("Win32::IsWinNT", w32_IsWinNT, file);
4067 newXS("Win32::IsWin95", w32_IsWin95, file);
4068 newXS("Win32::FormatMessage", w32_FormatMessage, file);
4069 newXS("Win32::Spawn", w32_Spawn, file);
4070 newXS("Win32::GetTickCount", w32_GetTickCount, file);
4071 newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
4072 newXS("Win32::GetFullPathName", w32_GetFullPathName, file);
4073 newXS("Win32::GetLongPathName", w32_GetLongPathName, file);
4074 newXS("Win32::CopyFile", w32_CopyFile, file);
4075 newXS("Win32::Sleep", w32_Sleep, file);
4077 /* XXX Bloat Alert! The following Activeware preloads really
4078 * ought to be part of Win32::Sys::*, so they're not included
4081 /* LookupAccountName
4083 * InitiateSystemShutdown
4084 * AbortSystemShutdown
4085 * ExpandEnvrironmentStrings
4090 Perl_win32_init(int *argcp, char ***argvp)
4092 /* Disable floating point errors, Perl will trap the ones we
4093 * care about. VC++ RTL defaults to switching these off
4094 * already, but the Borland RTL doesn't. Since we don't
4095 * want to be at the vendor's whim on the default, we set
4096 * it explicitly here.
4098 #if !defined(_ALPHA_) && !defined(__GNUC__)
4099 _control87(MCW_EM, MCW_EM);
4105 win32_get_child_IO(child_IO_table* ptbl)
4107 ptbl->childStdIn = GetStdHandle(STD_INPUT_HANDLE);
4108 ptbl->childStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
4109 ptbl->childStdErr = GetStdHandle(STD_ERROR_HANDLE);
4112 #ifdef HAVE_INTERP_INTERN
4115 # undef Perl_sys_intern_init
4116 # define Perl_sys_intern_init CPerlObj::Perl_sys_intern_init
4117 # undef Perl_sys_intern_dup
4118 # define Perl_sys_intern_dup CPerlObj::Perl_sys_intern_dup
4119 # undef Perl_sys_intern_clear
4120 # define Perl_sys_intern_clear CPerlObj::Perl_sys_intern_clear
4125 Perl_sys_intern_init(pTHX)
4127 w32_perlshell_tokens = Nullch;
4128 w32_perlshell_vec = (char**)NULL;
4129 w32_perlshell_items = 0;
4130 w32_fdpid = newAV();
4131 New(1313, w32_children, 1, child_tab);
4132 w32_num_children = 0;
4133 # ifdef USE_ITHREADS
4135 New(1313, w32_pseudo_children, 1, child_tab);
4136 w32_num_pseudo_children = 0;
4138 w32_init_socktype = 0;
4142 Perl_sys_intern_clear(pTHX)
4144 Safefree(w32_perlshell_tokens);
4145 Safefree(w32_perlshell_vec);
4146 /* NOTE: w32_fdpid is freed by sv_clean_all() */
4147 Safefree(w32_children);
4148 # ifdef USE_ITHREADS
4149 Safefree(w32_pseudo_children);
4153 # ifdef USE_ITHREADS
4156 Perl_sys_intern_dup(pTHX_ struct interp_intern *src, struct interp_intern *dst)
4158 dst->perlshell_tokens = Nullch;
4159 dst->perlshell_vec = (char**)NULL;
4160 dst->perlshell_items = 0;
4161 dst->fdpid = newAV();
4162 Newz(1313, dst->children, 1, child_tab);
4164 Newz(1313, dst->pseudo_children, 1, child_tab);
4165 dst->thr_intern.Winit_socktype = 0;
4167 # endif /* USE_ITHREADS */
4168 #endif /* HAVE_INTERP_INTERN */
4176 win32_free_argvw(pTHXo_ void *ptr)
4178 char** argv = (char**)ptr;
4186 win32_argv2utf8(int argc, char** argv)
4191 LPWSTR* lpwStr = CommandLineToArgvW(GetCommandLineW(), &wargc);
4192 if (lpwStr && argc) {
4194 length = WideCharToMultiByte(CP_UTF8, 0, lpwStr[--wargc], -1, NULL, 0, NULL, NULL);
4195 Newz(0, psz, length, char);
4196 WideCharToMultiByte(CP_UTF8, 0, lpwStr[wargc], -1, psz, length, NULL, NULL);
4199 call_atexit(win32_free_argvw, argv);
4201 GlobalFree((HGLOBAL)lpwStr);