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 static void get_shell(void);
95 static long tokenize(const char *str, char **dest, char ***destv);
96 int do_spawn2(char *cmd, int exectype);
97 static BOOL has_shell_metachars(char *ptr);
98 static long filetime_to_clock(PFILETIME ft);
99 static BOOL filetime_from_time(PFILETIME ft, time_t t);
100 static char * get_emd_part(SV **leading, char *trailing, ...);
101 static void remove_dead_process(long deceased);
102 static long find_pid(int pid);
103 static char * qualified_path(const char *cmd);
104 static char * win32_get_xlib(const char *pl, const char *xlib,
105 const char *libname);
108 static void remove_dead_pseudo_process(long child);
109 static long find_pseudo_pid(int pid);
113 HANDLE w32_perldll_handle = INVALID_HANDLE_VALUE;
114 char w32_module_name[MAX_PATH+1];
117 static DWORD w32_platform = (DWORD)-1;
119 #define ONE_K_BUFSIZE 1024
124 return (win32_os_id() == VER_PLATFORM_WIN32_WINDOWS);
130 return (win32_os_id() == VER_PLATFORM_WIN32_NT);
134 set_w32_module_name(void)
137 GetModuleFileName((HMODULE)((w32_perldll_handle == INVALID_HANDLE_VALUE)
138 ? GetModuleHandle(NULL)
139 : w32_perldll_handle),
140 w32_module_name, sizeof(w32_module_name));
142 /* try to get full path to binary (which may be mangled when perl is
143 * run from a 16-bit app) */
144 /*PerlIO_printf(Perl_debug_log, "Before %s\n", w32_module_name);*/
145 (void)win32_longpath(w32_module_name);
146 /*PerlIO_printf(Perl_debug_log, "After %s\n", w32_module_name);*/
148 /* normalize to forward slashes */
149 ptr = w32_module_name;
157 /* *svp (if non-NULL) is expected to be POK (valid allocated SvPVX(*svp)) */
159 get_regstr_from(HKEY hkey, const char *valuename, SV **svp)
161 /* Retrieve a REG_SZ or REG_EXPAND_SZ from the registry */
164 const char *subkey = "Software\\Perl";
168 retval = RegOpenKeyEx(hkey, subkey, 0, KEY_READ, &handle);
169 if (retval == ERROR_SUCCESS) {
171 retval = RegQueryValueEx(handle, valuename, 0, &type, NULL, &datalen);
172 if (retval == ERROR_SUCCESS
173 && (type == REG_SZ || type == REG_EXPAND_SZ))
177 *svp = sv_2mortal(newSVpvn("",0));
178 SvGROW(*svp, datalen);
179 retval = RegQueryValueEx(handle, valuename, 0, NULL,
180 (PBYTE)SvPVX(*svp), &datalen);
181 if (retval == ERROR_SUCCESS) {
183 SvCUR_set(*svp,datalen-1);
191 /* *svp (if non-NULL) is expected to be POK (valid allocated SvPVX(*svp)) */
193 get_regstr(const char *valuename, SV **svp)
195 char *str = get_regstr_from(HKEY_CURRENT_USER, valuename, svp);
197 str = get_regstr_from(HKEY_LOCAL_MACHINE, valuename, svp);
201 /* *prev_pathp (if non-NULL) is expected to be POK (valid allocated SvPVX(sv)) */
203 get_emd_part(SV **prev_pathp, char *trailing_path, ...)
207 char mod_name[MAX_PATH+1];
211 int oldsize, newsize;
214 va_start(ap, trailing_path);
215 strip = va_arg(ap, char *);
217 sprintf(base, "%d.%d", (int)PERL_REVISION, (int)PERL_VERSION);
218 baselen = strlen(base);
220 if (!*w32_module_name) {
221 set_w32_module_name();
223 strcpy(mod_name, w32_module_name);
224 ptr = strrchr(mod_name, '/');
225 while (ptr && strip) {
226 /* look for directories to skip back */
229 ptr = strrchr(mod_name, '/');
230 /* avoid stripping component if there is no slash,
231 * or it doesn't match ... */
232 if (!ptr || stricmp(ptr+1, strip) != 0) {
233 /* ... but not if component matches m|5\.$patchlevel.*| */
234 if (!ptr || !(*strip == '5' && *(ptr+1) == '5'
235 && strncmp(strip, base, baselen) == 0
236 && strncmp(ptr+1, base, baselen) == 0))
242 strip = va_arg(ap, char *);
250 strcpy(++ptr, trailing_path);
252 /* only add directory if it exists */
253 if (GetFileAttributes(mod_name) != (DWORD) -1) {
254 /* directory exists */
257 *prev_pathp = sv_2mortal(newSVpvn("",0));
258 sv_catpvn(*prev_pathp, ";", 1);
259 sv_catpv(*prev_pathp, mod_name);
260 return SvPVX(*prev_pathp);
267 win32_get_privlib(const char *pl)
270 char *stdlib = "lib";
271 char buffer[MAX_PATH+1];
274 /* $stdlib = $HKCU{"lib-$]"} || $HKLM{"lib-$]"} || $HKCU{"lib"} || $HKLM{"lib"} || ""; */
275 sprintf(buffer, "%s-%s", stdlib, pl);
276 if (!get_regstr(buffer, &sv))
277 (void)get_regstr(stdlib, &sv);
279 /* $stdlib .= ";$EMD/../../lib" */
280 return get_emd_part(&sv, stdlib, ARCHNAME, "bin", Nullch);
284 win32_get_xlib(const char *pl, const char *xlib, const char *libname)
288 char pathstr[MAX_PATH+1];
294 /* $HKCU{"$xlib-$]"} || $HKLM{"$xlib-$]"} . ---; */
295 sprintf(regstr, "%s-%s", xlib, pl);
296 (void)get_regstr(regstr, &sv1);
299 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/$libname/$]/lib"; */
300 sprintf(pathstr, "%s/%s/lib", libname, pl);
301 (void)get_emd_part(&sv1, pathstr, ARCHNAME, "bin", pl, Nullch);
303 /* $HKCU{$xlib} || $HKLM{$xlib} . ---; */
304 (void)get_regstr(xlib, &sv2);
307 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/$libname/lib"; */
308 sprintf(pathstr, "%s/lib", libname);
309 (void)get_emd_part(&sv2, pathstr, ARCHNAME, "bin", pl, Nullch);
318 sv_catpvn(sv1, ";", 1);
325 win32_get_sitelib(const char *pl)
327 return win32_get_xlib(pl, "sitelib", "site");
330 #ifndef PERL_VENDORLIB_NAME
331 # define PERL_VENDORLIB_NAME "vendor"
335 win32_get_vendorlib(const char *pl)
337 return win32_get_xlib(pl, "vendorlib", PERL_VENDORLIB_NAME);
341 has_shell_metachars(char *ptr)
347 * Scan string looking for redirection (< or >) or pipe
348 * characters (|) that are not in a quoted string.
349 * Shell variable interpolation (%VAR%) can also happen inside strings.
381 #if !defined(PERL_IMPLICIT_SYS)
382 /* since the current process environment is being updated in util.c
383 * the library functions will get the correct environment
386 Perl_my_popen(pTHX_ char *cmd, char *mode)
389 #define fixcmd(x) { \
390 char *pspace = strchr((x),' '); \
393 while (p < pspace) { \
404 PERL_FLUSHALL_FOR_CHILD;
405 return win32_popen(cmd, mode);
409 Perl_my_pclose(pTHX_ PerlIO *fp)
411 return win32_pclose(fp);
415 DllExport unsigned long
418 static OSVERSIONINFO osver;
420 if (osver.dwPlatformId != w32_platform) {
421 memset(&osver, 0, sizeof(OSVERSIONINFO));
422 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
423 GetVersionEx(&osver);
424 w32_platform = osver.dwPlatformId;
426 return (unsigned long)w32_platform;
436 return -((int)w32_pseudo_id);
439 /* Windows 9x appears to always reports a pid for threads and processes
440 * that has the high bit set. So we treat the lower 31 bits as the
441 * "real" PID for Perl's purposes. */
442 if (IsWin95() && pid < 0)
447 /* Tokenize a string. Words are null-separated, and the list
448 * ends with a doubled null. Any character (except null and
449 * including backslash) may be escaped by preceding it with a
450 * backslash (the backslash will be stripped).
451 * Returns number of words in result buffer.
454 tokenize(const char *str, char **dest, char ***destv)
456 char *retstart = Nullch;
457 char **retvstart = 0;
461 int slen = strlen(str);
463 register char **retv;
464 New(1307, ret, slen+2, char);
465 New(1308, retv, (slen+3)/2, char*);
473 if (*ret == '\\' && *str)
475 else if (*ret == ' ') {
491 retvstart[items] = Nullch;
504 if (!w32_perlshell_tokens) {
505 /* we don't use COMSPEC here for two reasons:
506 * 1. the same reason perl on UNIX doesn't use SHELL--rampant and
507 * uncontrolled unportability of the ensuing scripts.
508 * 2. PERL5SHELL could be set to a shell that may not be fit for
509 * interactive use (which is what most programs look in COMSPEC
512 const char* defaultshell = (IsWinNT()
513 ? "cmd.exe /x/c" : "command.com /c");
514 const char *usershell = PerlEnv_getenv("PERL5SHELL");
515 w32_perlshell_items = tokenize(usershell ? usershell : defaultshell,
516 &w32_perlshell_tokens,
522 do_aspawn(void *vreally, void **vmark, void **vsp)
525 SV *really = (SV*)vreally;
526 SV **mark = (SV**)vmark;
538 New(1306, argv, (sp - mark) + w32_perlshell_items + 2, char*);
540 if (SvNIOKp(*(mark+1)) && !SvPOKp(*(mark+1))) {
545 while (++mark <= sp) {
546 if (*mark && (str = SvPV_nolen(*mark)))
553 status = win32_spawnvp(flag,
554 (const char*)(really ? SvPV_nolen(really) : argv[0]),
555 (const char* const*)argv);
557 if (status < 0 && (errno == ENOEXEC || errno == ENOENT)) {
558 /* possible shell-builtin, invoke with shell */
560 sh_items = w32_perlshell_items;
562 argv[index+sh_items] = argv[index];
563 while (--sh_items >= 0)
564 argv[sh_items] = w32_perlshell_vec[sh_items];
566 status = win32_spawnvp(flag,
567 (const char*)(really ? SvPV_nolen(really) : argv[0]),
568 (const char* const*)argv);
571 if (flag == P_NOWAIT) {
573 PL_statusvalue = -1; /* >16bits hint for pp_system() */
577 if (ckWARN(WARN_EXEC))
578 Perl_warner(aTHX_ WARN_EXEC, "Can't spawn \"%s\": %s", argv[0], strerror(errno));
583 PL_statusvalue = status;
590 do_spawn2(char *cmd, int exectype)
597 BOOL needToTry = TRUE;
600 /* Save an extra exec if possible. See if there are shell
601 * metacharacters in it */
602 if (!has_shell_metachars(cmd)) {
603 New(1301,argv, strlen(cmd) / 2 + 2, char*);
604 New(1302,cmd2, strlen(cmd) + 1, char);
607 for (s = cmd2; *s;) {
608 while (*s && isSPACE(*s))
612 while (*s && !isSPACE(*s))
621 status = win32_spawnvp(P_WAIT, argv[0],
622 (const char* const*)argv);
624 case EXECF_SPAWN_NOWAIT:
625 status = win32_spawnvp(P_NOWAIT, argv[0],
626 (const char* const*)argv);
629 status = win32_execvp(argv[0], (const char* const*)argv);
632 if (status != -1 || errno == 0)
642 New(1306, argv, w32_perlshell_items + 2, char*);
643 while (++i < w32_perlshell_items)
644 argv[i] = w32_perlshell_vec[i];
649 status = win32_spawnvp(P_WAIT, argv[0],
650 (const char* const*)argv);
652 case EXECF_SPAWN_NOWAIT:
653 status = win32_spawnvp(P_NOWAIT, argv[0],
654 (const char* const*)argv);
657 status = win32_execvp(argv[0], (const char* const*)argv);
663 if (exectype == EXECF_SPAWN_NOWAIT) {
665 PL_statusvalue = -1; /* >16bits hint for pp_system() */
669 if (ckWARN(WARN_EXEC))
670 Perl_warner(aTHX_ WARN_EXEC, "Can't %s \"%s\": %s",
671 (exectype == EXECF_EXEC ? "exec" : "spawn"),
672 cmd, strerror(errno));
677 PL_statusvalue = status;
685 return do_spawn2(cmd, EXECF_SPAWN);
689 do_spawn_nowait(char *cmd)
691 return do_spawn2(cmd, EXECF_SPAWN_NOWAIT);
695 Perl_do_exec(pTHX_ char *cmd)
697 do_spawn2(cmd, EXECF_EXEC);
701 /* The idea here is to read all the directory names into a string table
702 * (separated by nulls) and when one of the other dir functions is called
703 * return the pointer to the current file name.
706 win32_opendir(char *filename)
712 char scanname[MAX_PATH+3];
714 WIN32_FIND_DATAA aFindData;
715 WIN32_FIND_DATAW wFindData;
717 char buffer[MAX_PATH*2];
718 WCHAR wbuffer[MAX_PATH+1];
721 len = strlen(filename);
725 /* check to see if filename is a directory */
726 if (win32_stat(filename, &sbuf) < 0 || !S_ISDIR(sbuf.st_mode))
729 /* Get us a DIR structure */
730 Newz(1303, dirp, 1, DIR);
732 /* Create the search pattern */
733 strcpy(scanname, filename);
735 /* bare drive name means look in cwd for drive */
736 if (len == 2 && isALPHA(scanname[0]) && scanname[1] == ':') {
737 scanname[len++] = '.';
738 scanname[len++] = '/';
740 else if (scanname[len-1] != '/' && scanname[len-1] != '\\') {
741 scanname[len++] = '/';
743 scanname[len++] = '*';
744 scanname[len] = '\0';
746 /* do the FindFirstFile call */
748 A2WHELPER(scanname, wbuffer, sizeof(wbuffer));
749 fh = FindFirstFileW(PerlDir_mapW(wbuffer), &wFindData);
752 fh = FindFirstFileA(PerlDir_mapA(scanname), &aFindData);
755 if (fh == INVALID_HANDLE_VALUE) {
756 DWORD err = GetLastError();
757 /* FindFirstFile() fails on empty drives! */
759 case ERROR_FILE_NOT_FOUND:
761 case ERROR_NO_MORE_FILES:
762 case ERROR_PATH_NOT_FOUND:
765 case ERROR_NOT_ENOUGH_MEMORY:
776 /* now allocate the first part of the string table for
777 * the filenames that we find.
780 W2AHELPER(wFindData.cFileName, buffer, sizeof(buffer));
784 ptr = aFindData.cFileName;
791 New(1304, dirp->start, dirp->size, char);
792 strcpy(dirp->start, ptr);
794 dirp->end = dirp->curr = dirp->start;
800 /* Readdir just returns the current string pointer and bumps the
801 * string pointer to the nDllExport entry.
803 DllExport struct direct *
804 win32_readdir(DIR *dirp)
809 /* first set up the structure to return */
810 len = strlen(dirp->curr);
811 strcpy(dirp->dirstr.d_name, dirp->curr);
812 dirp->dirstr.d_namlen = len;
815 dirp->dirstr.d_ino = dirp->curr - dirp->start;
817 /* Now set up for the next call to readdir */
818 dirp->curr += len + 1;
819 if (dirp->curr >= dirp->end) {
823 WIN32_FIND_DATAW wFindData;
824 WIN32_FIND_DATAA aFindData;
825 char buffer[MAX_PATH*2];
827 /* finding the next file that matches the wildcard
828 * (which should be all of them in this directory!).
831 res = FindNextFileW(dirp->handle, &wFindData);
833 W2AHELPER(wFindData.cFileName, buffer, sizeof(buffer));
838 res = FindNextFileA(dirp->handle, &aFindData);
840 ptr = aFindData.cFileName;
843 long endpos = dirp->end - dirp->start;
844 long newsize = endpos + strlen(ptr) + 1;
845 /* bump the string table size by enough for the
846 * new name and its null terminator */
847 while (newsize > dirp->size) {
848 long curpos = dirp->curr - dirp->start;
850 Renew(dirp->start, dirp->size, char);
851 dirp->curr = dirp->start + curpos;
853 strcpy(dirp->start + endpos, ptr);
854 dirp->end = dirp->start + newsize;
860 return &(dirp->dirstr);
866 /* Telldir returns the current string pointer position */
868 win32_telldir(DIR *dirp)
870 return (dirp->curr - dirp->start);
874 /* Seekdir moves the string pointer to a previously saved position
875 * (returned by telldir).
878 win32_seekdir(DIR *dirp, long loc)
880 dirp->curr = dirp->start + loc;
883 /* Rewinddir resets the string pointer to the start */
885 win32_rewinddir(DIR *dirp)
887 dirp->curr = dirp->start;
890 /* free the memory allocated by opendir */
892 win32_closedir(DIR *dirp)
895 if (dirp->handle != INVALID_HANDLE_VALUE)
896 FindClose(dirp->handle);
897 Safefree(dirp->start);
910 * Just pretend that everyone is a superuser. NT will let us know if
911 * we don\'t really have permission to do something.
914 #define ROOT_UID ((uid_t)0)
915 #define ROOT_GID ((gid_t)0)
944 return (auid == ROOT_UID ? 0 : -1);
950 return (agid == ROOT_GID ? 0 : -1);
957 char *buf = w32_getlogin_buffer;
958 DWORD size = sizeof(w32_getlogin_buffer);
959 if (GetUserName(buf,&size))
965 chown(const char *path, uid_t owner, gid_t group)
972 * XXX this needs strengthening (for PerlIO)
975 int mkstemp(const char *path)
978 char buf[MAX_PATH+1];
982 if (i++ > 10) { /* give up */
986 if (!GetTempFileNameA((LPCSTR)path, "plr", 1, buf)) {
990 fd = PerlLIO_open3(buf, O_CREAT|O_RDWR|O_EXCL, 0600);
1000 long child = w32_num_children;
1001 while (--child >= 0) {
1002 if (w32_child_pids[child] == pid)
1009 remove_dead_process(long child)
1013 CloseHandle(w32_child_handles[child]);
1014 Move(&w32_child_handles[child+1], &w32_child_handles[child],
1015 (w32_num_children-child-1), HANDLE);
1016 Move(&w32_child_pids[child+1], &w32_child_pids[child],
1017 (w32_num_children-child-1), DWORD);
1024 find_pseudo_pid(int pid)
1027 long child = w32_num_pseudo_children;
1028 while (--child >= 0) {
1029 if (w32_pseudo_child_pids[child] == pid)
1036 remove_dead_pseudo_process(long child)
1040 CloseHandle(w32_pseudo_child_handles[child]);
1041 Move(&w32_pseudo_child_handles[child+1], &w32_pseudo_child_handles[child],
1042 (w32_num_pseudo_children-child-1), HANDLE);
1043 Move(&w32_pseudo_child_pids[child+1], &w32_pseudo_child_pids[child],
1044 (w32_num_pseudo_children-child-1), DWORD);
1045 w32_num_pseudo_children--;
1051 win32_kill(int pid, int sig)
1058 /* it is a pseudo-forked child */
1059 child = find_pseudo_pid(-pid);
1063 hProcess = w32_pseudo_child_handles[child];
1064 if (TerminateThread(hProcess, sig)) {
1065 remove_dead_pseudo_process(child);
1069 else if (IsWin95()) {
1077 child = find_pid(pid);
1081 hProcess = w32_child_handles[child];
1082 if (TerminateProcess(hProcess, sig)) {
1083 remove_dead_process(child);
1089 hProcess = OpenProcess(PROCESS_ALL_ACCESS, TRUE,
1090 (IsWin95() ? -pid : pid));
1094 if (TerminateProcess(hProcess, sig)) {
1095 CloseHandle(hProcess);
1109 DllExport unsigned int
1110 win32_sleep(unsigned int t)
1117 win32_stat(const char *path, struct stat *sbuf)
1120 char buffer[MAX_PATH+1];
1121 int l = strlen(path);
1123 WCHAR wbuffer[MAX_PATH+1];
1129 switch(path[l - 1]) {
1130 /* FindFirstFile() and stat() are buggy with a trailing
1131 * backslash, so change it to a forward slash :-( */
1133 strncpy(buffer, path, l-1);
1134 buffer[l - 1] = '/';
1138 /* FindFirstFile() is buggy with "x:", so add a dot :-( */
1140 if (l == 2 && isALPHA(path[0])) {
1141 buffer[0] = path[0];
1152 /* We *must* open & close the file once; otherwise file attribute changes */
1153 /* might not yet have propagated to "other" hard links of the same file. */
1154 /* This also gives us an opportunity to determine the number of links. */
1156 A2WHELPER(path, wbuffer, sizeof(wbuffer));
1157 pwbuffer = PerlDir_mapW(wbuffer);
1158 handle = CreateFileW(pwbuffer, 0, 0, NULL, OPEN_EXISTING, 0, NULL);
1161 path = PerlDir_mapA(path);
1163 handle = CreateFileA(path, 0, 0, NULL, OPEN_EXISTING, 0, NULL);
1165 if (handle != INVALID_HANDLE_VALUE) {
1166 BY_HANDLE_FILE_INFORMATION bhi;
1167 if (GetFileInformationByHandle(handle, &bhi))
1168 nlink = bhi.nNumberOfLinks;
1169 CloseHandle(handle);
1172 /* pwbuffer or path will be mapped correctly above */
1174 res = _wstat(pwbuffer, (struct _stat *)sbuf);
1177 res = stat(path, sbuf);
1179 sbuf->st_nlink = nlink;
1182 /* CRT is buggy on sharenames, so make sure it really isn't.
1183 * XXX using GetFileAttributesEx() will enable us to set
1184 * sbuf->st_*time (but note that's not available on the
1185 * Windows of 1995) */
1188 r = GetFileAttributesW(pwbuffer);
1191 r = GetFileAttributesA(path);
1193 if (r != 0xffffffff && (r & FILE_ATTRIBUTE_DIRECTORY)) {
1194 /* sbuf may still contain old garbage since stat() failed */
1195 Zero(sbuf, 1, struct stat);
1196 sbuf->st_mode = S_IFDIR | S_IREAD;
1198 if (!(r & FILE_ATTRIBUTE_READONLY))
1199 sbuf->st_mode |= S_IWRITE | S_IEXEC;
1204 if (l == 3 && isALPHA(path[0]) && path[1] == ':'
1205 && (path[2] == '\\' || path[2] == '/'))
1207 /* The drive can be inaccessible, some _stat()s are buggy */
1209 ? !GetVolumeInformationW(pwbuffer,NULL,0,NULL,NULL,NULL,NULL,0)
1210 : !GetVolumeInformationA(path,NULL,0,NULL,NULL,NULL,NULL,0)) {
1216 if (S_ISDIR(sbuf->st_mode))
1217 sbuf->st_mode |= S_IWRITE | S_IEXEC;
1218 else if (S_ISREG(sbuf->st_mode)) {
1220 if (l >= 4 && path[l-4] == '.') {
1221 const char *e = path + l - 3;
1222 if (strnicmp(e,"exe",3)
1223 && strnicmp(e,"bat",3)
1224 && strnicmp(e,"com",3)
1225 && (IsWin95() || strnicmp(e,"cmd",3)))
1226 sbuf->st_mode &= ~S_IEXEC;
1228 sbuf->st_mode |= S_IEXEC;
1231 sbuf->st_mode &= ~S_IEXEC;
1232 /* Propagate permissions to _group_ and _others_ */
1233 perms = sbuf->st_mode & (S_IREAD|S_IWRITE|S_IEXEC);
1234 sbuf->st_mode |= (perms>>3) | (perms>>6);
1241 /* Find the longname of a given path. path is destructively modified.
1242 * It should have space for at least MAX_PATH characters. */
1244 win32_longpath(char *path)
1246 WIN32_FIND_DATA fdata;
1248 char tmpbuf[MAX_PATH+1];
1249 char *tmpstart = tmpbuf;
1256 if (isALPHA(path[0]) && path[1] == ':' &&
1257 (path[2] == '/' || path[2] == '\\'))
1260 *tmpstart++ = path[0];
1264 else if ((path[0] == '/' || path[0] == '\\') &&
1265 (path[1] == '/' || path[1] == '\\'))
1268 *tmpstart++ = path[0];
1269 *tmpstart++ = path[1];
1270 /* copy machine name */
1271 while (*start && *start != '/' && *start != '\\')
1272 *tmpstart++ = *start++;
1274 *tmpstart++ = *start;
1276 /* copy share name */
1277 while (*start && *start != '/' && *start != '\\')
1278 *tmpstart++ = *start++;
1282 if (sep == '/' || sep == '\\')
1286 /* walk up to slash */
1287 while (*start && *start != '/' && *start != '\\')
1290 /* discard doubled slashes */
1291 while (*start && (start[1] == '/' || start[1] == '\\'))
1295 /* stop and find full name of component */
1297 fhand = FindFirstFile(path,&fdata);
1298 if (fhand != INVALID_HANDLE_VALUE) {
1299 strcpy(tmpstart, fdata.cFileName);
1300 tmpstart += strlen(fdata.cFileName);
1308 /* failed a step, just return without side effects */
1309 /*PerlIO_printf(Perl_debug_log, "Failed to find %s\n", path);*/
1314 strcpy(path,tmpbuf);
1319 win32_getenv(const char *name)
1322 WCHAR wBuffer[MAX_PATH+1];
1324 SV *curitem = Nullsv;
1327 A2WHELPER(name, wBuffer, sizeof(wBuffer));
1328 needlen = GetEnvironmentVariableW(wBuffer, NULL, 0);
1331 needlen = GetEnvironmentVariableA(name,NULL,0);
1333 curitem = sv_2mortal(newSVpvn("", 0));
1337 SvGROW(curitem, (needlen+1)*sizeof(WCHAR));
1338 needlen = GetEnvironmentVariableW(wBuffer,
1339 (WCHAR*)SvPVX(curitem),
1341 } while (needlen >= SvLEN(curitem)/sizeof(WCHAR));
1342 SvCUR_set(curitem, (needlen*sizeof(WCHAR))+1);
1343 acuritem = sv_2mortal(newSVsv(curitem));
1344 W2AHELPER((WCHAR*)SvPVX(acuritem), SvPVX(curitem), SvCUR(curitem));
1348 SvGROW(curitem, needlen+1);
1349 needlen = GetEnvironmentVariableA(name,SvPVX(curitem),
1351 } while (needlen >= SvLEN(curitem));
1352 SvCUR_set(curitem, needlen);
1356 /* allow any environment variables that begin with 'PERL'
1357 to be stored in the registry */
1358 if (strncmp(name, "PERL", 4) == 0)
1359 (void)get_regstr(name, &curitem);
1361 if (curitem && SvCUR(curitem))
1362 return SvPVX(curitem);
1368 win32_putenv(const char *name)
1375 int length, relval = -1;
1379 length = strlen(name)+1;
1380 New(1309,wCuritem,length,WCHAR);
1381 A2WHELPER(name, wCuritem, length*sizeof(WCHAR));
1382 wVal = wcschr(wCuritem, '=');
1385 if (SetEnvironmentVariableW(wCuritem, *wVal ? wVal : NULL))
1391 New(1309,curitem,strlen(name)+1,char);
1392 strcpy(curitem, name);
1393 val = strchr(curitem, '=');
1395 /* The sane way to deal with the environment.
1396 * Has these advantages over putenv() & co.:
1397 * * enables us to store a truly empty value in the
1398 * environment (like in UNIX).
1399 * * we don't have to deal with RTL globals, bugs and leaks.
1401 * Why you may want to enable USE_WIN32_RTL_ENV:
1402 * * environ[] and RTL functions will not reflect changes,
1403 * which might be an issue if extensions want to access
1404 * the env. via RTL. This cuts both ways, since RTL will
1405 * not see changes made by extensions that call the Win32
1406 * functions directly, either.
1410 if (SetEnvironmentVariableA(curitem, *val ? val : NULL))
1420 filetime_to_clock(PFILETIME ft)
1422 __int64 qw = ft->dwHighDateTime;
1424 qw |= ft->dwLowDateTime;
1425 qw /= 10000; /* File time ticks at 0.1uS, clock at 1mS */
1430 win32_times(struct tms *timebuf)
1435 if (GetProcessTimes(GetCurrentProcess(), &dummy, &dummy,
1437 timebuf->tms_utime = filetime_to_clock(&user);
1438 timebuf->tms_stime = filetime_to_clock(&kernel);
1439 timebuf->tms_cutime = 0;
1440 timebuf->tms_cstime = 0;
1443 /* That failed - e.g. Win95 fallback to clock() */
1444 clock_t t = clock();
1445 timebuf->tms_utime = t;
1446 timebuf->tms_stime = 0;
1447 timebuf->tms_cutime = 0;
1448 timebuf->tms_cstime = 0;
1453 /* fix utime() so it works on directories in NT */
1455 filetime_from_time(PFILETIME pFileTime, time_t Time)
1457 struct tm *pTM = localtime(&Time);
1458 SYSTEMTIME SystemTime;
1464 SystemTime.wYear = pTM->tm_year + 1900;
1465 SystemTime.wMonth = pTM->tm_mon + 1;
1466 SystemTime.wDay = pTM->tm_mday;
1467 SystemTime.wHour = pTM->tm_hour;
1468 SystemTime.wMinute = pTM->tm_min;
1469 SystemTime.wSecond = pTM->tm_sec;
1470 SystemTime.wMilliseconds = 0;
1472 return SystemTimeToFileTime(&SystemTime, &LocalTime) &&
1473 LocalFileTimeToFileTime(&LocalTime, pFileTime);
1477 win32_unlink(const char *filename)
1484 WCHAR wBuffer[MAX_PATH+1];
1487 A2WHELPER(filename, wBuffer, sizeof(wBuffer));
1488 pwBuffer = PerlDir_mapW(wBuffer);
1489 attrs = GetFileAttributesW(pwBuffer);
1490 if (attrs == 0xFFFFFFFF)
1492 if (attrs & FILE_ATTRIBUTE_READONLY) {
1493 (void)SetFileAttributesW(pwBuffer, attrs & ~FILE_ATTRIBUTE_READONLY);
1494 ret = _wunlink(pwBuffer);
1496 (void)SetFileAttributesW(pwBuffer, attrs);
1499 ret = _wunlink(pwBuffer);
1502 filename = PerlDir_mapA(filename);
1503 attrs = GetFileAttributesA(filename);
1504 if (attrs == 0xFFFFFFFF)
1506 if (attrs & FILE_ATTRIBUTE_READONLY) {
1507 (void)SetFileAttributesA(filename, attrs & ~FILE_ATTRIBUTE_READONLY);
1508 ret = unlink(filename);
1510 (void)SetFileAttributesA(filename, attrs);
1513 ret = unlink(filename);
1522 win32_utime(const char *filename, struct utimbuf *times)
1529 struct utimbuf TimeBuffer;
1530 WCHAR wbuffer[MAX_PATH+1];
1535 A2WHELPER(filename, wbuffer, sizeof(wbuffer));
1536 pwbuffer = PerlDir_mapW(wbuffer);
1537 rc = _wutime(pwbuffer, (struct _utimbuf*)times);
1540 filename = PerlDir_mapA(filename);
1541 rc = utime(filename, times);
1543 /* EACCES: path specifies directory or readonly file */
1544 if (rc == 0 || errno != EACCES /* || !IsWinNT() */)
1547 if (times == NULL) {
1548 times = &TimeBuffer;
1549 time(×->actime);
1550 times->modtime = times->actime;
1553 /* This will (and should) still fail on readonly files */
1555 handle = CreateFileW(pwbuffer, GENERIC_READ | GENERIC_WRITE,
1556 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1557 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1560 handle = CreateFileA(filename, GENERIC_READ | GENERIC_WRITE,
1561 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1562 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1564 if (handle == INVALID_HANDLE_VALUE)
1567 if (GetFileTime(handle, &ftCreate, &ftAccess, &ftWrite) &&
1568 filetime_from_time(&ftAccess, times->actime) &&
1569 filetime_from_time(&ftWrite, times->modtime) &&
1570 SetFileTime(handle, &ftCreate, &ftAccess, &ftWrite))
1575 CloseHandle(handle);
1580 win32_uname(struct utsname *name)
1582 struct hostent *hep;
1583 STRLEN nodemax = sizeof(name->nodename)-1;
1584 OSVERSIONINFO osver;
1586 memset(&osver, 0, sizeof(OSVERSIONINFO));
1587 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1588 if (GetVersionEx(&osver)) {
1590 switch (osver.dwPlatformId) {
1591 case VER_PLATFORM_WIN32_WINDOWS:
1592 strcpy(name->sysname, "Windows");
1594 case VER_PLATFORM_WIN32_NT:
1595 strcpy(name->sysname, "Windows NT");
1597 case VER_PLATFORM_WIN32s:
1598 strcpy(name->sysname, "Win32s");
1601 strcpy(name->sysname, "Win32 Unknown");
1606 sprintf(name->release, "%d.%d",
1607 osver.dwMajorVersion, osver.dwMinorVersion);
1610 sprintf(name->version, "Build %d",
1611 osver.dwPlatformId == VER_PLATFORM_WIN32_NT
1612 ? osver.dwBuildNumber : (osver.dwBuildNumber & 0xffff));
1613 if (osver.szCSDVersion[0]) {
1614 char *buf = name->version + strlen(name->version);
1615 sprintf(buf, " (%s)", osver.szCSDVersion);
1619 *name->sysname = '\0';
1620 *name->version = '\0';
1621 *name->release = '\0';
1625 hep = win32_gethostbyname("localhost");
1627 STRLEN len = strlen(hep->h_name);
1628 if (len <= nodemax) {
1629 strcpy(name->nodename, hep->h_name);
1632 strncpy(name->nodename, hep->h_name, nodemax);
1633 name->nodename[nodemax] = '\0';
1638 if (!GetComputerName(name->nodename, &sz))
1639 *name->nodename = '\0';
1642 /* machine (architecture) */
1646 GetSystemInfo(&info);
1648 #if (defined(__BORLANDC__)&&(__BORLANDC__<=0x520)) \
1649 || (defined(__MINGW32__) && !defined(_ANONYMOUS_UNION))
1650 switch (info.u.s.wProcessorArchitecture) {
1652 switch (info.wProcessorArchitecture) {
1654 case PROCESSOR_ARCHITECTURE_INTEL:
1655 arch = "x86"; break;
1656 case PROCESSOR_ARCHITECTURE_MIPS:
1657 arch = "mips"; break;
1658 case PROCESSOR_ARCHITECTURE_ALPHA:
1659 arch = "alpha"; break;
1660 case PROCESSOR_ARCHITECTURE_PPC:
1661 arch = "ppc"; break;
1663 arch = "unknown"; break;
1665 strcpy(name->machine, arch);
1671 win32_waitpid(int pid, int *status, int flags)
1674 DWORD timeout = (flags & WNOHANG) ? 0 : INFINITE;
1677 if (pid == -1) /* XXX threadid == 1 ? */
1678 return win32_wait(status);
1681 child = find_pseudo_pid(-pid);
1683 HANDLE hThread = w32_pseudo_child_handles[child];
1684 DWORD waitcode = WaitForSingleObject(hThread, timeout);
1685 if (waitcode == WAIT_TIMEOUT) {
1688 else if (waitcode != WAIT_FAILED) {
1689 if (GetExitCodeThread(hThread, &waitcode)) {
1690 *status = (int)((waitcode & 0xff) << 8);
1691 retval = (int)w32_pseudo_child_pids[child];
1692 remove_dead_pseudo_process(child);
1699 else if (IsWin95()) {
1708 child = find_pid(pid);
1710 hProcess = w32_child_handles[child];
1711 waitcode = WaitForSingleObject(hProcess, timeout);
1712 if (waitcode == WAIT_TIMEOUT) {
1715 else if (waitcode != WAIT_FAILED) {
1716 if (GetExitCodeProcess(hProcess, &waitcode)) {
1717 *status = (int)((waitcode & 0xff) << 8);
1718 retval = (int)w32_child_pids[child];
1719 remove_dead_process(child);
1728 hProcess = OpenProcess(PROCESS_ALL_ACCESS, TRUE,
1729 (IsWin95() ? -pid : pid));
1731 waitcode = WaitForSingleObject(hProcess, timeout);
1732 if (waitcode == WAIT_TIMEOUT) {
1735 else if (waitcode != WAIT_FAILED) {
1736 if (GetExitCodeProcess(hProcess, &waitcode)) {
1737 *status = (int)((waitcode & 0xff) << 8);
1738 CloseHandle(hProcess);
1742 CloseHandle(hProcess);
1748 return retval >= 0 ? pid : retval;
1752 win32_wait(int *status)
1754 /* XXX this wait emulation only knows about processes
1755 * spawned via win32_spawnvp(P_NOWAIT, ...).
1759 DWORD exitcode, waitcode;
1762 if (w32_num_pseudo_children) {
1763 waitcode = WaitForMultipleObjects(w32_num_pseudo_children,
1764 w32_pseudo_child_handles,
1767 if (waitcode != WAIT_FAILED) {
1768 if (waitcode >= WAIT_ABANDONED_0
1769 && waitcode < WAIT_ABANDONED_0 + w32_num_pseudo_children)
1770 i = waitcode - WAIT_ABANDONED_0;
1772 i = waitcode - WAIT_OBJECT_0;
1773 if (GetExitCodeThread(w32_pseudo_child_handles[i], &exitcode)) {
1774 *status = (int)((exitcode & 0xff) << 8);
1775 retval = (int)w32_pseudo_child_pids[i];
1776 remove_dead_pseudo_process(i);
1783 if (!w32_num_children) {
1788 /* if a child exists, wait for it to die */
1789 waitcode = WaitForMultipleObjects(w32_num_children,
1793 if (waitcode != WAIT_FAILED) {
1794 if (waitcode >= WAIT_ABANDONED_0
1795 && waitcode < WAIT_ABANDONED_0 + w32_num_children)
1796 i = waitcode - WAIT_ABANDONED_0;
1798 i = waitcode - WAIT_OBJECT_0;
1799 if (GetExitCodeProcess(w32_child_handles[i], &exitcode) ) {
1800 *status = (int)((exitcode & 0xff) << 8);
1801 retval = (int)w32_child_pids[i];
1802 remove_dead_process(i);
1808 errno = GetLastError();
1812 static UINT timerid = 0;
1814 static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
1817 KillTimer(NULL,timerid);
1819 CALL_FPTR(PL_sighandlerp)(14);
1822 DllExport unsigned int
1823 win32_alarm(unsigned int sec)
1826 * the 'obvious' implentation is SetTimer() with a callback
1827 * which does whatever receiving SIGALRM would do
1828 * we cannot use SIGALRM even via raise() as it is not
1829 * one of the supported codes in <signal.h>
1831 * Snag is unless something is looking at the message queue
1832 * nothing happens :-(
1837 timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
1839 Perl_croak_nocontext("Cannot set timer");
1845 KillTimer(NULL,timerid);
1852 #ifdef HAVE_DES_FCRYPT
1853 extern char * des_fcrypt(const char *txt, const char *salt, char *cbuf);
1857 win32_crypt(const char *txt, const char *salt)
1860 #ifdef HAVE_DES_FCRYPT
1861 return des_fcrypt(txt, salt, w32_crypt_buffer);
1863 Perl_croak(aTHX_ "The crypt() function is unimplemented due to excessive paranoia.");
1868 #ifdef USE_FIXED_OSFHANDLE
1870 #define FOPEN 0x01 /* file handle open */
1871 #define FNOINHERIT 0x10 /* file handle opened O_NOINHERIT */
1872 #define FAPPEND 0x20 /* file handle opened O_APPEND */
1873 #define FDEV 0x40 /* file handle refers to device */
1874 #define FTEXT 0x80 /* file handle is in text mode */
1877 *int my_open_osfhandle(long osfhandle, int flags) - open C Runtime file handle
1880 * This function allocates a free C Runtime file handle and associates
1881 * it with the Win32 HANDLE specified by the first parameter. This is a
1882 * temperary fix for WIN95's brain damage GetFileType() error on socket
1883 * we just bypass that call for socket
1885 * This works with MSVC++ 4.0+ or GCC/Mingw32
1888 * long osfhandle - Win32 HANDLE to associate with C Runtime file handle.
1889 * int flags - flags to associate with C Runtime file handle.
1892 * returns index of entry in fh, if successful
1893 * return -1, if no free entry is found
1897 *******************************************************************************/
1900 * we fake up some parts of the CRT that aren't exported by MSVCRT.dll
1901 * this lets sockets work on Win9X with GCC and should fix the problems
1906 /* create an ioinfo entry, kill its handle, and steal the entry */
1911 HANDLE hF = CreateFile("NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
1912 int fh = _open_osfhandle((long)hF, 0);
1916 EnterCriticalSection(&(_pioinfo(fh)->lock));
1921 my_open_osfhandle(long osfhandle, int flags)
1924 char fileflags; /* _osfile flags */
1926 /* copy relevant flags from second parameter */
1929 if (flags & O_APPEND)
1930 fileflags |= FAPPEND;
1935 if (flags & O_NOINHERIT)
1936 fileflags |= FNOINHERIT;
1938 /* attempt to allocate a C Runtime file handle */
1939 if ((fh = _alloc_osfhnd()) == -1) {
1940 errno = EMFILE; /* too many open files */
1941 _doserrno = 0L; /* not an OS error */
1942 return -1; /* return error to caller */
1945 /* the file is open. now, set the info in _osfhnd array */
1946 _set_osfhnd(fh, osfhandle);
1948 fileflags |= FOPEN; /* mark as open */
1950 _osfile(fh) = fileflags; /* set osfile entry */
1951 LeaveCriticalSection(&_pioinfo(fh)->lock);
1953 return fh; /* return handle */
1956 #endif /* USE_FIXED_OSFHANDLE */
1958 /* simulate flock by locking a range on the file */
1960 #define LK_ERR(f,i) ((f) ? (i = 0) : (errno = GetLastError()))
1961 #define LK_LEN 0xffff0000
1964 win32_flock(int fd, int oper)
1972 Perl_croak_nocontext("flock() unimplemented on this platform");
1975 fh = (HANDLE)_get_osfhandle(fd);
1976 memset(&o, 0, sizeof(o));
1979 case LOCK_SH: /* shared lock */
1980 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
1982 case LOCK_EX: /* exclusive lock */
1983 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
1985 case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
1986 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
1988 case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
1989 LK_ERR(LockFileEx(fh,
1990 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
1991 0, LK_LEN, 0, &o),i);
1993 case LOCK_UN: /* unlock lock */
1994 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, 0, &o),i);
1996 default: /* unknown */
2007 * redirected io subsystem for all XS modules
2020 return (&(_environ));
2023 /* the rest are the remapped stdio routines */
2043 win32_ferror(FILE *fp)
2045 return (ferror(fp));
2050 win32_feof(FILE *fp)
2056 * Since the errors returned by the socket error function
2057 * WSAGetLastError() are not known by the library routine strerror
2058 * we have to roll our own.
2062 win32_strerror(int e)
2064 #if !defined __BORLANDC__ && !defined __MINGW32__ /* compiler intolerance */
2065 extern int sys_nerr;
2069 if (e < 0 || e > sys_nerr) {
2074 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
2075 w32_strerror_buffer,
2076 sizeof(w32_strerror_buffer), NULL) == 0)
2077 strcpy(w32_strerror_buffer, "Unknown Error");
2079 return w32_strerror_buffer;
2085 win32_str_os_error(void *sv, DWORD dwErr)
2089 dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
2090 |FORMAT_MESSAGE_IGNORE_INSERTS
2091 |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
2092 dwErr, 0, (char *)&sMsg, 1, NULL);
2093 /* strip trailing whitespace and period */
2096 --dwLen; /* dwLen doesn't include trailing null */
2097 } while (0 < dwLen && isSPACE(sMsg[dwLen]));
2098 if ('.' != sMsg[dwLen])
2103 sMsg = (char*)LocalAlloc(0, 64/**sizeof(TCHAR)*/);
2105 dwLen = sprintf(sMsg,
2106 "Unknown error #0x%lX (lookup 0x%lX)",
2107 dwErr, GetLastError());
2111 sv_setpvn((SV*)sv, sMsg, dwLen);
2117 win32_fprintf(FILE *fp, const char *format, ...)
2120 va_start(marker, format); /* Initialize variable arguments. */
2122 return (vfprintf(fp, format, marker));
2126 win32_printf(const char *format, ...)
2129 va_start(marker, format); /* Initialize variable arguments. */
2131 return (vprintf(format, marker));
2135 win32_vfprintf(FILE *fp, const char *format, va_list args)
2137 return (vfprintf(fp, format, args));
2141 win32_vprintf(const char *format, va_list args)
2143 return (vprintf(format, args));
2147 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
2149 return fread(buf, size, count, fp);
2153 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
2155 return fwrite(buf, size, count, fp);
2158 #define MODE_SIZE 10
2161 win32_fopen(const char *filename, const char *mode)
2164 WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH+1];
2170 if (stricmp(filename, "/dev/null")==0)
2174 A2WHELPER(mode, wMode, sizeof(wMode));
2175 A2WHELPER(filename, wBuffer, sizeof(wBuffer));
2176 f = _wfopen(PerlDir_mapW(wBuffer), wMode);
2179 f = fopen(PerlDir_mapA(filename), mode);
2180 /* avoid buffering headaches for child processes */
2181 if (f && *mode == 'a')
2182 win32_fseek(f, 0, SEEK_END);
2186 #ifndef USE_SOCKETS_AS_HANDLES
2188 #define fdopen my_fdopen
2192 win32_fdopen(int handle, const char *mode)
2195 WCHAR wMode[MODE_SIZE];
2198 A2WHELPER(mode, wMode, sizeof(wMode));
2199 f = _wfdopen(handle, wMode);
2202 f = fdopen(handle, (char *) mode);
2203 /* avoid buffering headaches for child processes */
2204 if (f && *mode == 'a')
2205 win32_fseek(f, 0, SEEK_END);
2210 win32_freopen(const char *path, const char *mode, FILE *stream)
2213 WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH+1];
2214 if (stricmp(path, "/dev/null")==0)
2218 A2WHELPER(mode, wMode, sizeof(wMode));
2219 A2WHELPER(path, wBuffer, sizeof(wBuffer));
2220 return _wfreopen(PerlDir_mapW(wBuffer), wMode, stream);
2222 return freopen(PerlDir_mapA(path), mode, stream);
2226 win32_fclose(FILE *pf)
2228 return my_fclose(pf); /* defined in win32sck.c */
2232 win32_fputs(const char *s,FILE *pf)
2234 return fputs(s, pf);
2238 win32_fputc(int c,FILE *pf)
2244 win32_ungetc(int c,FILE *pf)
2246 return ungetc(c,pf);
2250 win32_getc(FILE *pf)
2256 win32_fileno(FILE *pf)
2262 win32_clearerr(FILE *pf)
2269 win32_fflush(FILE *pf)
2275 win32_ftell(FILE *pf)
2281 win32_fseek(FILE *pf,long offset,int origin)
2283 return fseek(pf, offset, origin);
2287 win32_fgetpos(FILE *pf,fpos_t *p)
2289 return fgetpos(pf, p);
2293 win32_fsetpos(FILE *pf,const fpos_t *p)
2295 return fsetpos(pf, p);
2299 win32_rewind(FILE *pf)
2319 win32_fstat(int fd,struct stat *sbufptr)
2322 /* A file designated by filehandle is not shown as accessible
2323 * for write operations, probably because it is opened for reading.
2326 int rc = fstat(fd,sbufptr);
2327 BY_HANDLE_FILE_INFORMATION bhfi;
2328 if (GetFileInformationByHandle((HANDLE)_get_osfhandle(fd), &bhfi)) {
2329 sbufptr->st_mode &= 0xFE00;
2330 if (bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
2331 sbufptr->st_mode |= (S_IREAD + (S_IREAD >> 3) + (S_IREAD >> 6));
2333 sbufptr->st_mode |= ((S_IREAD|S_IWRITE) + ((S_IREAD|S_IWRITE) >> 3)
2334 + ((S_IREAD|S_IWRITE) >> 6));
2338 return my_fstat(fd,sbufptr);
2343 win32_pipe(int *pfd, unsigned int size, int mode)
2345 return _pipe(pfd, size, mode);
2349 win32_popenlist(const char *mode, IV narg, SV **args)
2352 Perl_croak(aTHX_ "List form of pipe open not implemented");
2357 * a popen() clone that respects PERL5SHELL
2359 * changed to return PerlIO* rather than FILE * by BKS, 11-11-2000
2363 win32_popen(const char *command, const char *mode)
2365 #ifdef USE_RTL_POPEN
2366 return _popen(command, mode);
2374 /* establish which ends read and write */
2375 if (strchr(mode,'w')) {
2376 stdfd = 0; /* stdin */
2380 else if (strchr(mode,'r')) {
2381 stdfd = 1; /* stdout */
2388 /* set the correct mode */
2389 if (strchr(mode,'b'))
2391 else if (strchr(mode,'t'))
2394 ourmode = _fmode & (O_TEXT | O_BINARY);
2396 /* the child doesn't inherit handles */
2397 ourmode |= O_NOINHERIT;
2399 if (win32_pipe( p, 512, ourmode) == -1)
2402 /* save current stdfd */
2403 if ((oldfd = win32_dup(stdfd)) == -1)
2406 /* make stdfd go to child end of pipe (implicitly closes stdfd) */
2407 /* stdfd will be inherited by the child */
2408 if (win32_dup2(p[child], stdfd) == -1)
2411 /* close the child end in parent */
2412 win32_close(p[child]);
2414 /* start the child */
2417 if ((childpid = do_spawn_nowait((char*)command)) == -1)
2420 /* revert stdfd to whatever it was before */
2421 if (win32_dup2(oldfd, stdfd) == -1)
2424 /* close saved handle */
2428 sv_setiv(*av_fetch(w32_fdpid, p[parent], TRUE), childpid);
2431 /* set process id so that it can be returned by perl's open() */
2432 PL_forkprocess = childpid;
2435 /* we have an fd, return a file stream */
2436 return (PerlIO_fdopen(p[parent], (char *)mode));
2439 /* we don't need to check for errors here */
2443 win32_dup2(oldfd, stdfd);
2448 #endif /* USE_RTL_POPEN */
2456 win32_pclose(PerlIO *pf)
2458 #ifdef USE_RTL_POPEN
2462 int childpid, status;
2466 sv = *av_fetch(w32_fdpid, PerlIO_fileno(pf), TRUE);
2469 childpid = SvIVX(sv);
2486 if (win32_waitpid(childpid, &status, 0) == -1)
2491 #endif /* USE_RTL_POPEN */
2497 LPCWSTR lpExistingFileName,
2498 LPSECURITY_ATTRIBUTES lpSecurityAttributes)
2501 WCHAR wFullName[MAX_PATH+1];
2502 LPVOID lpContext = NULL;
2503 WIN32_STREAM_ID StreamId;
2504 DWORD dwSize = (char*)&StreamId.cStreamName - (char*)&StreamId;
2509 BOOL (__stdcall *pfnBackupWrite)(HANDLE, LPBYTE, DWORD, LPDWORD,
2510 BOOL, BOOL, LPVOID*) =
2511 (BOOL (__stdcall *)(HANDLE, LPBYTE, DWORD, LPDWORD,
2512 BOOL, BOOL, LPVOID*))
2513 GetProcAddress(GetModuleHandle("kernel32.dll"), "BackupWrite");
2514 if (pfnBackupWrite == NULL)
2517 dwLen = GetFullPathNameW(lpFileName, MAX_PATH, wFullName, NULL);
2520 dwLen = (dwLen+1)*sizeof(WCHAR);
2522 handle = CreateFileW(lpExistingFileName, FILE_WRITE_ATTRIBUTES,
2523 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
2524 NULL, OPEN_EXISTING, 0, NULL);
2525 if (handle == INVALID_HANDLE_VALUE)
2528 StreamId.dwStreamId = BACKUP_LINK;
2529 StreamId.dwStreamAttributes = 0;
2530 StreamId.dwStreamNameSize = 0;
2531 #if defined(__BORLANDC__) \
2532 ||(defined(__MINGW32__) && !defined(_ANONYMOUS_UNION))
2533 StreamId.Size.u.HighPart = 0;
2534 StreamId.Size.u.LowPart = dwLen;
2536 StreamId.Size.HighPart = 0;
2537 StreamId.Size.LowPart = dwLen;
2540 bSuccess = pfnBackupWrite(handle, (LPBYTE)&StreamId, dwSize, &dwWritten,
2541 FALSE, FALSE, &lpContext);
2543 bSuccess = pfnBackupWrite(handle, (LPBYTE)wFullName, dwLen, &dwWritten,
2544 FALSE, FALSE, &lpContext);
2545 pfnBackupWrite(handle, NULL, 0, &dwWritten, TRUE, FALSE, &lpContext);
2548 CloseHandle(handle);
2553 win32_link(const char *oldname, const char *newname)
2556 BOOL (__stdcall *pfnCreateHardLinkW)(LPCWSTR,LPCWSTR,LPSECURITY_ATTRIBUTES);
2557 WCHAR wOldName[MAX_PATH+1];
2558 WCHAR wNewName[MAX_PATH+1];
2561 Perl_croak(aTHX_ PL_no_func, "link");
2563 pfnCreateHardLinkW =
2564 (BOOL (__stdcall *)(LPCWSTR, LPCWSTR, LPSECURITY_ATTRIBUTES))
2565 GetProcAddress(GetModuleHandle("kernel32.dll"), "CreateHardLinkW");
2566 if (pfnCreateHardLinkW == NULL)
2567 pfnCreateHardLinkW = Nt4CreateHardLinkW;
2569 if ((A2WHELPER(oldname, wOldName, sizeof(wOldName))) &&
2570 (A2WHELPER(newname, wNewName, sizeof(wNewName))) &&
2571 (wcscpy(wOldName, PerlDir_mapW(wOldName)),
2572 pfnCreateHardLinkW(PerlDir_mapW(wNewName), wOldName, NULL)))
2576 errno = (GetLastError() == ERROR_FILE_NOT_FOUND) ? ENOENT : EINVAL;
2581 win32_rename(const char *oname, const char *newname)
2583 WCHAR wOldName[MAX_PATH+1];
2584 WCHAR wNewName[MAX_PATH+1];
2585 char szOldName[MAX_PATH+1];
2586 char szNewName[MAX_PATH+1];
2590 /* XXX despite what the documentation says about MoveFileEx(),
2591 * it doesn't work under Windows95!
2594 DWORD dwFlags = MOVEFILE_COPY_ALLOWED;
2596 A2WHELPER(oname, wOldName, sizeof(wOldName));
2597 A2WHELPER(newname, wNewName, sizeof(wNewName));
2598 if (wcsicmp(wNewName, wOldName))
2599 dwFlags |= MOVEFILE_REPLACE_EXISTING;
2600 wcscpy(wOldName, PerlDir_mapW(wOldName));
2601 bResult = MoveFileExW(wOldName,PerlDir_mapW(wNewName), dwFlags);
2604 if (stricmp(newname, oname))
2605 dwFlags |= MOVEFILE_REPLACE_EXISTING;
2606 strcpy(szOldName, PerlDir_mapA(oname));
2607 bResult = MoveFileExA(szOldName,PerlDir_mapA(newname), dwFlags);
2610 DWORD err = GetLastError();
2612 case ERROR_BAD_NET_NAME:
2613 case ERROR_BAD_NETPATH:
2614 case ERROR_BAD_PATHNAME:
2615 case ERROR_FILE_NOT_FOUND:
2616 case ERROR_FILENAME_EXCED_RANGE:
2617 case ERROR_INVALID_DRIVE:
2618 case ERROR_NO_MORE_FILES:
2619 case ERROR_PATH_NOT_FOUND:
2632 char szTmpName[MAX_PATH+1];
2633 char dname[MAX_PATH+1];
2634 char *endname = Nullch;
2636 DWORD from_attr, to_attr;
2638 strcpy(szOldName, PerlDir_mapA(oname));
2639 strcpy(szNewName, PerlDir_mapA(newname));
2641 /* if oname doesn't exist, do nothing */
2642 from_attr = GetFileAttributes(szOldName);
2643 if (from_attr == 0xFFFFFFFF) {
2648 /* if newname exists, rename it to a temporary name so that we
2649 * don't delete it in case oname happens to be the same file
2650 * (but perhaps accessed via a different path)
2652 to_attr = GetFileAttributes(szNewName);
2653 if (to_attr != 0xFFFFFFFF) {
2654 /* if newname is a directory, we fail
2655 * XXX could overcome this with yet more convoluted logic */
2656 if (to_attr & FILE_ATTRIBUTE_DIRECTORY) {
2660 tmplen = strlen(szNewName);
2661 strcpy(szTmpName,szNewName);
2662 endname = szTmpName+tmplen;
2663 for (; endname > szTmpName ; --endname) {
2664 if (*endname == '/' || *endname == '\\') {
2669 if (endname > szTmpName)
2670 endname = strcpy(dname,szTmpName);
2674 /* get a temporary filename in same directory
2675 * XXX is this really the best we can do? */
2676 if (!GetTempFileName((LPCTSTR)endname, "plr", 0, szTmpName)) {
2680 DeleteFile(szTmpName);
2682 retval = rename(szNewName, szTmpName);
2689 /* rename oname to newname */
2690 retval = rename(szOldName, szNewName);
2692 /* if we created a temporary file before ... */
2693 if (endname != Nullch) {
2694 /* ...and rename succeeded, delete temporary file/directory */
2696 DeleteFile(szTmpName);
2697 /* else restore it to what it was */
2699 (void)rename(szTmpName, szNewName);
2706 win32_setmode(int fd, int mode)
2708 return setmode(fd, mode);
2712 win32_lseek(int fd, long offset, int origin)
2714 return lseek(fd, offset, origin);
2724 win32_open(const char *path, int flag, ...)
2729 WCHAR wBuffer[MAX_PATH+1];
2732 pmode = va_arg(ap, int);
2735 if (stricmp(path, "/dev/null")==0)
2739 A2WHELPER(path, wBuffer, sizeof(wBuffer));
2740 return _wopen(PerlDir_mapW(wBuffer), flag, pmode);
2742 return open(PerlDir_mapA(path), flag, pmode);
2745 /* close() that understands socket */
2746 extern int my_close(int); /* in win32sck.c */
2751 return my_close(fd);
2767 win32_dup2(int fd1,int fd2)
2769 return dup2(fd1,fd2);
2772 #ifdef PERL_MSVCRT_READFIX
2774 #define LF 10 /* line feed */
2775 #define CR 13 /* carriage return */
2776 #define CTRLZ 26 /* ctrl-z means eof for text */
2777 #define FOPEN 0x01 /* file handle open */
2778 #define FEOFLAG 0x02 /* end of file has been encountered */
2779 #define FCRLF 0x04 /* CR-LF across read buffer (in text mode) */
2780 #define FPIPE 0x08 /* file handle refers to a pipe */
2781 #define FAPPEND 0x20 /* file handle opened O_APPEND */
2782 #define FDEV 0x40 /* file handle refers to device */
2783 #define FTEXT 0x80 /* file handle is in text mode */
2784 #define MAX_DESCRIPTOR_COUNT (64*32) /* this is the maximun that MSVCRT can handle */
2787 _fixed_read(int fh, void *buf, unsigned cnt)
2789 int bytes_read; /* number of bytes read */
2790 char *buffer; /* buffer to read to */
2791 int os_read; /* bytes read on OS call */
2792 char *p, *q; /* pointers into buffer */
2793 char peekchr; /* peek-ahead character */
2794 ULONG filepos; /* file position after seek */
2795 ULONG dosretval; /* o.s. return value */
2797 /* validate handle */
2798 if (((unsigned)fh >= (unsigned)MAX_DESCRIPTOR_COUNT) ||
2799 !(_osfile(fh) & FOPEN))
2801 /* out of range -- return error */
2803 _doserrno = 0; /* not o.s. error */
2808 * If lockinitflag is FALSE, assume fd is device
2809 * lockinitflag is set to TRUE by open.
2811 if (_pioinfo(fh)->lockinitflag)
2812 EnterCriticalSection(&(_pioinfo(fh)->lock)); /* lock file */
2814 bytes_read = 0; /* nothing read yet */
2815 buffer = (char*)buf;
2817 if (cnt == 0 || (_osfile(fh) & FEOFLAG)) {
2818 /* nothing to read or at EOF, so return 0 read */
2822 if ((_osfile(fh) & (FPIPE|FDEV)) && _pipech(fh) != LF) {
2823 /* a pipe/device and pipe lookahead non-empty: read the lookahead
2825 *buffer++ = _pipech(fh);
2828 _pipech(fh) = LF; /* mark as empty */
2833 if (!ReadFile((HANDLE)_osfhnd(fh), buffer, cnt, (LPDWORD)&os_read, NULL))
2835 /* ReadFile has reported an error. recognize two special cases.
2837 * 1. map ERROR_ACCESS_DENIED to EBADF
2839 * 2. just return 0 if ERROR_BROKEN_PIPE has occurred. it
2840 * means the handle is a read-handle on a pipe for which
2841 * all write-handles have been closed and all data has been
2844 if ((dosretval = GetLastError()) == ERROR_ACCESS_DENIED) {
2845 /* wrong read/write mode should return EBADF, not EACCES */
2847 _doserrno = dosretval;
2851 else if (dosretval == ERROR_BROKEN_PIPE) {
2861 bytes_read += os_read; /* update bytes read */
2863 if (_osfile(fh) & FTEXT) {
2864 /* now must translate CR-LFs to LFs in the buffer */
2866 /* set CRLF flag to indicate LF at beginning of buffer */
2867 /* if ((os_read != 0) && (*(char *)buf == LF)) */
2868 /* _osfile(fh) |= FCRLF; */
2870 /* _osfile(fh) &= ~FCRLF; */
2872 _osfile(fh) &= ~FCRLF;
2874 /* convert chars in the buffer: p is src, q is dest */
2876 while (p < (char *)buf + bytes_read) {
2878 /* if fh is not a device, set ctrl-z flag */
2879 if (!(_osfile(fh) & FDEV))
2880 _osfile(fh) |= FEOFLAG;
2881 break; /* stop translating */
2886 /* *p is CR, so must check next char for LF */
2887 if (p < (char *)buf + bytes_read - 1) {
2890 *q++ = LF; /* convert CR-LF to LF */
2893 *q++ = *p++; /* store char normally */
2896 /* This is the hard part. We found a CR at end of
2897 buffer. We must peek ahead to see if next char
2902 if (!ReadFile((HANDLE)_osfhnd(fh), &peekchr, 1,
2903 (LPDWORD)&os_read, NULL))
2904 dosretval = GetLastError();
2906 if (dosretval != 0 || os_read == 0) {
2907 /* couldn't read ahead, store CR */
2911 /* peekchr now has the extra character -- we now
2912 have several possibilities:
2913 1. disk file and char is not LF; just seek back
2915 2. disk file and char is LF; store LF, don't seek back
2916 3. pipe/device and char is LF; store LF.
2917 4. pipe/device and char isn't LF, store CR and
2918 put char in pipe lookahead buffer. */
2919 if (_osfile(fh) & (FDEV|FPIPE)) {
2920 /* non-seekable device */
2925 _pipech(fh) = peekchr;
2930 if (peekchr == LF) {
2931 /* nothing read yet; must make some
2934 /* turn on this flag for tell routine */
2935 _osfile(fh) |= FCRLF;
2938 HANDLE osHandle; /* o.s. handle value */
2940 if ((osHandle = (HANDLE)_get_osfhandle(fh)) != (HANDLE)-1)
2942 if ((filepos = SetFilePointer(osHandle, -1, NULL, FILE_CURRENT)) == -1)
2943 dosretval = GetLastError();
2954 /* we now change bytes_read to reflect the true number of chars
2956 bytes_read = q - (char *)buf;
2960 if (_pioinfo(fh)->lockinitflag)
2961 LeaveCriticalSection(&(_pioinfo(fh)->lock)); /* unlock file */
2966 #endif /* PERL_MSVCRT_READFIX */
2969 win32_read(int fd, void *buf, unsigned int cnt)
2971 #ifdef PERL_MSVCRT_READFIX
2972 return _fixed_read(fd, buf, cnt);
2974 return read(fd, buf, cnt);
2979 win32_write(int fd, const void *buf, unsigned int cnt)
2981 return write(fd, buf, cnt);
2985 win32_mkdir(const char *dir, int mode)
2989 WCHAR wBuffer[MAX_PATH+1];
2990 A2WHELPER(dir, wBuffer, sizeof(wBuffer));
2991 return _wmkdir(PerlDir_mapW(wBuffer));
2993 return mkdir(PerlDir_mapA(dir)); /* just ignore mode */
2997 win32_rmdir(const char *dir)
3001 WCHAR wBuffer[MAX_PATH+1];
3002 A2WHELPER(dir, wBuffer, sizeof(wBuffer));
3003 return _wrmdir(PerlDir_mapW(wBuffer));
3005 return rmdir(PerlDir_mapA(dir));
3009 win32_chdir(const char *dir)
3013 WCHAR wBuffer[MAX_PATH+1];
3014 A2WHELPER(dir, wBuffer, sizeof(wBuffer));
3015 return _wchdir(wBuffer);
3021 win32_access(const char *path, int mode)
3025 WCHAR wBuffer[MAX_PATH+1];
3026 A2WHELPER(path, wBuffer, sizeof(wBuffer));
3027 return _waccess(PerlDir_mapW(wBuffer), mode);
3029 return access(PerlDir_mapA(path), mode);
3033 win32_chmod(const char *path, int mode)
3037 WCHAR wBuffer[MAX_PATH+1];
3038 A2WHELPER(path, wBuffer, sizeof(wBuffer));
3039 return _wchmod(PerlDir_mapW(wBuffer), mode);
3041 return chmod(PerlDir_mapA(path), mode);
3046 create_command_line(const char* command, const char * const *args)
3050 char *cmd, *ptr, *arg;
3051 STRLEN len = strlen(command) + 1;
3053 for (index = 0; (ptr = (char*)args[index]) != NULL; ++index)
3054 len += strlen(ptr) + 1;
3056 New(1310, cmd, len, char);
3058 strcpy(ptr, command);
3060 for (index = 0; (arg = (char*)args[index]) != NULL; ++index) {
3070 qualified_path(const char *cmd)
3074 char *fullcmd, *curfullcmd;
3080 fullcmd = (char*)cmd;
3082 if (*fullcmd == '/' || *fullcmd == '\\')
3089 pathstr = PerlEnv_getenv("PATH");
3090 New(0, fullcmd, MAX_PATH+1, char);
3091 curfullcmd = fullcmd;
3096 /* start by appending the name to the current prefix */
3097 strcpy(curfullcmd, cmd);
3098 curfullcmd += cmdlen;
3100 /* if it doesn't end with '.', or has no extension, try adding
3101 * a trailing .exe first */
3102 if (cmd[cmdlen-1] != '.'
3103 && (cmdlen < 4 || cmd[cmdlen-4] != '.'))
3105 strcpy(curfullcmd, ".exe");
3106 res = GetFileAttributes(fullcmd);
3107 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
3112 /* that failed, try the bare name */
3113 res = GetFileAttributes(fullcmd);
3114 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
3117 /* quit if no other path exists, or if cmd already has path */
3118 if (!pathstr || !*pathstr || has_slash)
3121 /* skip leading semis */
3122 while (*pathstr == ';')
3125 /* build a new prefix from scratch */
3126 curfullcmd = fullcmd;
3127 while (*pathstr && *pathstr != ';') {
3128 if (*pathstr == '"') { /* foo;"baz;etc";bar */
3129 pathstr++; /* skip initial '"' */
3130 while (*pathstr && *pathstr != '"') {
3131 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
3132 *curfullcmd++ = *pathstr;
3136 pathstr++; /* skip trailing '"' */
3139 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
3140 *curfullcmd++ = *pathstr;
3145 pathstr++; /* skip trailing semi */
3146 if (curfullcmd > fullcmd /* append a dir separator */
3147 && curfullcmd[-1] != '/' && curfullcmd[-1] != '\\')
3149 *curfullcmd++ = '\\';
3157 /* The following are just place holders.
3158 * Some hosts may provide and environment that the OS is
3159 * not tracking, therefore, these host must provide that
3160 * environment and the current directory to CreateProcess
3170 free_childenv(void* d)
3179 char szfilename[(MAX_PATH+1)*2];
3181 WCHAR wfilename[MAX_PATH+1];
3182 GetCurrentDirectoryW(MAX_PATH+1, wfilename);
3183 W2AHELPER(wfilename, szfilename, sizeof(szfilename));
3186 GetCurrentDirectoryA(MAX_PATH+1, szfilename);
3189 New(0, ptr, strlen(szfilename)+1, char);
3190 strcpy(ptr, szfilename);
3195 free_childdir(char* d)
3202 /* XXX this needs to be made more compatible with the spawnvp()
3203 * provided by the various RTLs. In particular, searching for
3204 * *.{com,bat,cmd} files (as done by the RTLs) is unimplemented.
3205 * This doesn't significantly affect perl itself, because we
3206 * always invoke things using PERL5SHELL if a direct attempt to
3207 * spawn the executable fails.
3209 * XXX splitting and rejoining the commandline between do_aspawn()
3210 * and win32_spawnvp() could also be avoided.
3214 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
3216 #ifdef USE_RTL_SPAWNVP
3217 return spawnvp(mode, cmdname, (char * const *)argv);
3224 STARTUPINFO StartupInfo;
3225 PROCESS_INFORMATION ProcessInformation;
3228 char *cmd = create_command_line(cmdname, strcmp(cmdname, argv[0]) == 0
3230 char *fullcmd = Nullch;
3232 env = PerlEnv_get_childenv();
3233 dir = PerlEnv_get_childdir();
3236 case P_NOWAIT: /* asynch + remember result */
3237 if (w32_num_children >= MAXIMUM_WAIT_OBJECTS) {
3243 case P_WAIT: /* synchronous execution */
3245 default: /* invalid mode */
3250 memset(&StartupInfo,0,sizeof(StartupInfo));
3251 StartupInfo.cb = sizeof(StartupInfo);
3252 memset(&tbl,0,sizeof(tbl));
3253 PerlEnv_get_child_IO(&tbl);
3254 StartupInfo.dwFlags = tbl.dwFlags;
3255 StartupInfo.dwX = tbl.dwX;
3256 StartupInfo.dwY = tbl.dwY;
3257 StartupInfo.dwXSize = tbl.dwXSize;
3258 StartupInfo.dwYSize = tbl.dwYSize;
3259 StartupInfo.dwXCountChars = tbl.dwXCountChars;
3260 StartupInfo.dwYCountChars = tbl.dwYCountChars;
3261 StartupInfo.dwFillAttribute = tbl.dwFillAttribute;
3262 StartupInfo.wShowWindow = tbl.wShowWindow;
3263 StartupInfo.hStdInput = tbl.childStdIn;
3264 StartupInfo.hStdOutput = tbl.childStdOut;
3265 StartupInfo.hStdError = tbl.childStdErr;
3266 if (StartupInfo.hStdInput != INVALID_HANDLE_VALUE &&
3267 StartupInfo.hStdOutput != INVALID_HANDLE_VALUE &&
3268 StartupInfo.hStdError != INVALID_HANDLE_VALUE)
3270 StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
3273 create |= CREATE_NEW_CONSOLE;
3277 if (!CreateProcess(cmdname, /* search PATH to find executable */
3278 cmd, /* executable, and its arguments */
3279 NULL, /* process attributes */
3280 NULL, /* thread attributes */
3281 TRUE, /* inherit handles */
3282 create, /* creation flags */
3283 (LPVOID)env, /* inherit environment */
3284 dir, /* inherit cwd */
3286 &ProcessInformation))
3288 /* initial NULL argument to CreateProcess() does a PATH
3289 * search, but it always first looks in the directory
3290 * where the current process was started, which behavior
3291 * is undesirable for backward compatibility. So we
3292 * jump through our own hoops by picking out the path
3293 * we really want it to use. */
3295 fullcmd = qualified_path(cmdname);
3306 if (mode == P_NOWAIT) {
3307 /* asynchronous spawn -- store handle, return PID */
3308 ret = (int)ProcessInformation.dwProcessId;
3309 if (IsWin95() && ret < 0)
3312 w32_child_handles[w32_num_children] = ProcessInformation.hProcess;
3313 w32_child_pids[w32_num_children] = (DWORD)ret;
3318 WaitForSingleObject(ProcessInformation.hProcess, INFINITE);
3319 GetExitCodeProcess(ProcessInformation.hProcess, &status);
3321 CloseHandle(ProcessInformation.hProcess);
3324 CloseHandle(ProcessInformation.hThread);
3327 PerlEnv_free_childenv(env);
3328 PerlEnv_free_childdir(dir);
3336 win32_execv(const char *cmdname, const char *const *argv)
3340 /* if this is a pseudo-forked child, we just want to spawn
3341 * the new program, and return */
3343 return spawnv(P_WAIT, cmdname, (char *const *)argv);
3345 return execv(cmdname, (char *const *)argv);
3349 win32_execvp(const char *cmdname, const char *const *argv)
3353 /* if this is a pseudo-forked child, we just want to spawn
3354 * the new program, and return */
3355 if (w32_pseudo_id) {
3356 int status = win32_spawnvp(P_WAIT, cmdname, (char *const *)argv);
3365 return execvp(cmdname, (char *const *)argv);
3369 win32_perror(const char *str)
3375 win32_setbuf(FILE *pf, char *buf)
3381 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
3383 return setvbuf(pf, buf, type, size);
3387 win32_flushall(void)
3393 win32_fcloseall(void)
3399 win32_fgets(char *s, int n, FILE *pf)
3401 return fgets(s, n, pf);
3411 win32_fgetc(FILE *pf)
3417 win32_putc(int c, FILE *pf)
3423 win32_puts(const char *s)
3435 win32_putchar(int c)
3442 #ifndef USE_PERL_SBRK
3444 static char *committed = NULL;
3445 static char *base = NULL;
3446 static char *reserved = NULL;
3447 static char *brk = NULL;
3448 static DWORD pagesize = 0;
3449 static DWORD allocsize = 0;
3457 GetSystemInfo(&info);
3458 /* Pretend page size is larger so we don't perpetually
3459 * call the OS to commit just one page ...
3461 pagesize = info.dwPageSize << 3;
3462 allocsize = info.dwAllocationGranularity;
3464 /* This scheme fails eventually if request for contiguous
3465 * block is denied so reserve big blocks - this is only
3466 * address space not memory ...
3468 if (brk+need >= reserved)
3470 DWORD size = 64*1024*1024;
3472 if (committed && reserved && committed < reserved)
3474 /* Commit last of previous chunk cannot span allocations */
3475 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
3477 committed = reserved;
3479 /* Reserve some (more) space
3480 * Note this is a little sneaky, 1st call passes NULL as reserved
3481 * so lets system choose where we start, subsequent calls pass
3482 * the old end address so ask for a contiguous block
3484 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
3487 reserved = addr+size;
3502 if (brk > committed)
3504 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
3505 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
3520 win32_malloc(size_t size)
3522 return malloc(size);
3526 win32_calloc(size_t numitems, size_t size)
3528 return calloc(numitems,size);
3532 win32_realloc(void *block, size_t size)
3534 return realloc(block,size);
3538 win32_free(void *block)
3545 win32_open_osfhandle(long handle, int flags)
3547 #ifdef USE_FIXED_OSFHANDLE
3549 return my_open_osfhandle(handle, flags);
3551 return _open_osfhandle(handle, flags);
3555 win32_get_osfhandle(int fd)
3557 return _get_osfhandle(fd);
3561 win32_dynaload(const char* filename)
3565 char buf[MAX_PATH+1];
3568 /* LoadLibrary() doesn't recognize forward slashes correctly,
3569 * so turn 'em back. */
3570 first = strchr(filename, '/');
3572 STRLEN len = strlen(filename);
3573 if (len <= MAX_PATH) {
3574 strcpy(buf, filename);
3575 filename = &buf[first - filename];
3577 if (*filename == '/')
3578 *(char*)filename = '\\';
3585 WCHAR wfilename[MAX_PATH+1];
3586 A2WHELPER(filename, wfilename, sizeof(wfilename));
3587 hModule = LoadLibraryExW(PerlDir_mapW(wfilename), NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
3590 hModule = LoadLibraryExA(PerlDir_mapA(filename), NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
3603 /* Make the host for current directory */
3604 char* ptr = PerlEnv_get_childdir();
3607 * then it worked, set PV valid,
3608 * else return 'undef'
3611 SV *sv = sv_newmortal();
3613 PerlEnv_free_childdir(ptr);
3628 Perl_croak(aTHX_ "usage: Win32::SetCurrentDirectory($cwd)");
3629 if (!PerlDir_chdir(SvPV_nolen(ST(0))))
3636 XS(w32_GetNextAvailDrive)
3640 char root[] = "_:\\";
3645 if (GetDriveType(root) == 1) {
3654 XS(w32_GetLastError)
3658 XSRETURN_IV(GetLastError());
3662 XS(w32_SetLastError)
3666 Perl_croak(aTHX_ "usage: Win32::SetLastError($error)");
3667 SetLastError(SvIV(ST(0)));
3675 char *name = w32_getlogin_buffer;
3676 DWORD size = sizeof(w32_getlogin_buffer);
3678 if (GetUserName(name,&size)) {
3679 /* size includes NULL */
3680 ST(0) = sv_2mortal(newSVpvn(name,size-1));
3690 char name[MAX_COMPUTERNAME_LENGTH+1];
3691 DWORD size = sizeof(name);
3693 if (GetComputerName(name,&size)) {
3694 /* size does NOT include NULL :-( */
3695 ST(0) = sv_2mortal(newSVpvn(name,size));
3706 HINSTANCE hNetApi32 = LoadLibrary("netapi32.dll");
3707 DWORD (__stdcall *pfnNetApiBufferFree)(LPVOID Buffer);
3708 DWORD (__stdcall *pfnNetWkstaGetInfo)(LPWSTR servername, DWORD level,
3712 pfnNetApiBufferFree = (DWORD (__stdcall *)(void *))
3713 GetProcAddress(hNetApi32, "NetApiBufferFree");
3714 pfnNetWkstaGetInfo = (DWORD (__stdcall *)(LPWSTR, DWORD, void *))
3715 GetProcAddress(hNetApi32, "NetWkstaGetInfo");
3718 if (hNetApi32 && pfnNetWkstaGetInfo && pfnNetApiBufferFree) {
3719 /* this way is more reliable, in case user has a local account. */
3721 DWORD dnamelen = sizeof(dname);
3723 DWORD wki100_platform_id;
3724 LPWSTR wki100_computername;
3725 LPWSTR wki100_langroup;
3726 DWORD wki100_ver_major;
3727 DWORD wki100_ver_minor;
3729 /* NERR_Success *is* 0*/
3730 if (0 == pfnNetWkstaGetInfo(NULL, 100, &pwi)) {
3731 if (pwi->wki100_langroup && *(pwi->wki100_langroup)) {
3732 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_langroup,
3733 -1, (LPSTR)dname, dnamelen, NULL, NULL);
3736 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_computername,
3737 -1, (LPSTR)dname, dnamelen, NULL, NULL);
3739 pfnNetApiBufferFree(pwi);
3740 FreeLibrary(hNetApi32);
3743 FreeLibrary(hNetApi32);
3746 /* Win95 doesn't have NetWksta*(), so do it the old way */
3748 DWORD size = sizeof(name);
3750 FreeLibrary(hNetApi32);
3751 if (GetUserName(name,&size)) {
3752 char sid[ONE_K_BUFSIZE];
3753 DWORD sidlen = sizeof(sid);
3755 DWORD dnamelen = sizeof(dname);
3757 if (LookupAccountName(NULL, name, (PSID)&sid, &sidlen,
3758 dname, &dnamelen, &snu)) {
3759 XSRETURN_PV(dname); /* all that for this */
3771 DWORD flags, filecomplen;
3772 if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
3773 &flags, fsname, sizeof(fsname))) {
3774 if (GIMME_V == G_ARRAY) {
3775 XPUSHs(sv_2mortal(newSVpvn(fsname,strlen(fsname))));
3776 XPUSHs(sv_2mortal(newSViv(flags)));
3777 XPUSHs(sv_2mortal(newSViv(filecomplen)));
3782 XSRETURN_PV(fsname);
3788 XS(w32_GetOSVersion)
3791 OSVERSIONINFOA osver;
3794 OSVERSIONINFOW osverw;
3795 char szCSDVersion[sizeof(osverw.szCSDVersion)];
3796 osverw.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
3797 if (!GetVersionExW(&osverw)) {
3800 W2AHELPER(osverw.szCSDVersion, szCSDVersion, sizeof(szCSDVersion));
3801 XPUSHs(newSVpvn(szCSDVersion, strlen(szCSDVersion)));
3802 osver.dwMajorVersion = osverw.dwMajorVersion;
3803 osver.dwMinorVersion = osverw.dwMinorVersion;
3804 osver.dwBuildNumber = osverw.dwBuildNumber;
3805 osver.dwPlatformId = osverw.dwPlatformId;
3808 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOA);
3809 if (!GetVersionExA(&osver)) {
3812 XPUSHs(newSVpvn(osver.szCSDVersion, strlen(osver.szCSDVersion)));
3814 XPUSHs(newSViv(osver.dwMajorVersion));
3815 XPUSHs(newSViv(osver.dwMinorVersion));
3816 XPUSHs(newSViv(osver.dwBuildNumber));
3817 XPUSHs(newSViv(osver.dwPlatformId));
3826 XSRETURN_IV(IsWinNT());
3834 XSRETURN_IV(IsWin95());
3838 XS(w32_FormatMessage)
3842 char msgbuf[ONE_K_BUFSIZE];
3845 Perl_croak(aTHX_ "usage: Win32::FormatMessage($errno)");
3848 WCHAR wmsgbuf[ONE_K_BUFSIZE];
3849 if (FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM,
3850 &source, SvIV(ST(0)), 0,
3851 wmsgbuf, ONE_K_BUFSIZE-1, NULL))
3853 W2AHELPER(wmsgbuf, msgbuf, sizeof(msgbuf));
3854 XSRETURN_PV(msgbuf);
3858 if (FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM,
3859 &source, SvIV(ST(0)), 0,
3860 msgbuf, sizeof(msgbuf)-1, NULL))
3861 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 env = PerlEnv_get_childenv();
3885 dir = PerlEnv_get_childdir();
3887 memset(&stStartInfo, 0, sizeof(stStartInfo)); /* Clear the block */
3888 stStartInfo.cb = sizeof(stStartInfo); /* Set the structure size */
3889 stStartInfo.dwFlags = STARTF_USESHOWWINDOW; /* Enable wShowWindow control */
3890 stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE; /* Start min (normal) */
3893 cmd, /* Image path */
3894 args, /* Arguments for command line */
3895 NULL, /* Default process security */
3896 NULL, /* Default thread security */
3897 FALSE, /* Must be TRUE to use std handles */
3898 NORMAL_PRIORITY_CLASS, /* No special scheduling */
3899 env, /* Inherit our environment block */
3900 dir, /* Inherit our currrent directory */
3901 &stStartInfo, /* -> Startup info */
3902 &stProcInfo)) /* <- Process info (if OK) */
3904 int pid = (int)stProcInfo.dwProcessId;
3905 if (IsWin95() && pid < 0)
3907 sv_setiv(ST(2), pid);
3908 CloseHandle(stProcInfo.hThread);/* library source code does this. */
3911 PerlEnv_free_childenv(env);
3912 PerlEnv_free_childdir(dir);
3913 XSRETURN_IV(bSuccess);
3917 XS(w32_GetTickCount)
3920 DWORD msec = GetTickCount();
3928 XS(w32_GetShortPathName)
3935 Perl_croak(aTHX_ "usage: Win32::GetShortPathName($longPathName)");
3937 shortpath = sv_mortalcopy(ST(0));
3938 SvUPGRADE(shortpath, SVt_PV);
3939 if (!SvPVX(shortpath) || !SvLEN(shortpath))
3942 /* src == target is allowed */
3944 len = GetShortPathName(SvPVX(shortpath),
3947 } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
3949 SvCUR_set(shortpath,len);
3957 XS(w32_GetFullPathName)
3966 Perl_croak(aTHX_ "usage: Win32::GetFullPathName($filename)");
3969 fullpath = sv_mortalcopy(filename);
3970 SvUPGRADE(fullpath, SVt_PV);
3971 if (!SvPVX(fullpath) || !SvLEN(fullpath))
3975 len = GetFullPathName(SvPVX(filename),
3979 } while (len >= SvLEN(fullpath) && sv_grow(fullpath,len+1));
3981 if (GIMME_V == G_ARRAY) {
3983 XST_mPV(1,filepart);
3984 len = filepart - SvPVX(fullpath);
3987 SvCUR_set(fullpath,len);
3995 XS(w32_GetLongPathName)
3999 char tmpbuf[MAX_PATH+1];
4004 Perl_croak(aTHX_ "usage: Win32::GetLongPathName($pathname)");
4007 pathstr = SvPV(path,len);
4008 strcpy(tmpbuf, pathstr);
4009 pathstr = win32_longpath(tmpbuf);
4011 ST(0) = sv_2mortal(newSVpvn(pathstr, strlen(pathstr)));
4022 Perl_croak(aTHX_ "usage: Win32::Sleep($milliseconds)");
4033 Perl_croak(aTHX_ "usage: Win32::CopyFile($from, $to, $overwrite)");
4035 WCHAR wSourceFile[MAX_PATH+1];
4036 WCHAR wDestFile[MAX_PATH+1];
4037 A2WHELPER(SvPV_nolen(ST(0)), wSourceFile, sizeof(wSourceFile));
4038 wcscpy(wSourceFile, PerlDir_mapW(wSourceFile));
4039 A2WHELPER(SvPV_nolen(ST(1)), wDestFile, sizeof(wDestFile));
4040 bResult = CopyFileW(wSourceFile, PerlDir_mapW(wDestFile), !SvTRUE(ST(2)));
4043 char szSourceFile[MAX_PATH+1];
4044 strcpy(szSourceFile, PerlDir_mapA(SvPV_nolen(ST(0))));
4045 bResult = CopyFileA(szSourceFile, PerlDir_mapA(SvPV_nolen(ST(1))), !SvTRUE(ST(2)));
4054 Perl_init_os_extras(void)
4057 char *file = __FILE__;
4060 /* these names are Activeware compatible */
4061 newXS("Win32::GetCwd", w32_GetCwd, file);
4062 newXS("Win32::SetCwd", w32_SetCwd, file);
4063 newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
4064 newXS("Win32::GetLastError", w32_GetLastError, file);
4065 newXS("Win32::SetLastError", w32_SetLastError, file);
4066 newXS("Win32::LoginName", w32_LoginName, file);
4067 newXS("Win32::NodeName", w32_NodeName, file);
4068 newXS("Win32::DomainName", w32_DomainName, file);
4069 newXS("Win32::FsType", w32_FsType, file);
4070 newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
4071 newXS("Win32::IsWinNT", w32_IsWinNT, file);
4072 newXS("Win32::IsWin95", w32_IsWin95, file);
4073 newXS("Win32::FormatMessage", w32_FormatMessage, file);
4074 newXS("Win32::Spawn", w32_Spawn, file);
4075 newXS("Win32::GetTickCount", w32_GetTickCount, file);
4076 newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
4077 newXS("Win32::GetFullPathName", w32_GetFullPathName, file);
4078 newXS("Win32::GetLongPathName", w32_GetLongPathName, file);
4079 newXS("Win32::CopyFile", w32_CopyFile, file);
4080 newXS("Win32::Sleep", w32_Sleep, file);
4082 /* XXX Bloat Alert! The following Activeware preloads really
4083 * ought to be part of Win32::Sys::*, so they're not included
4086 /* LookupAccountName
4088 * InitiateSystemShutdown
4089 * AbortSystemShutdown
4090 * ExpandEnvrironmentStrings
4095 Perl_win32_init(int *argcp, char ***argvp)
4097 /* Disable floating point errors, Perl will trap the ones we
4098 * care about. VC++ RTL defaults to switching these off
4099 * already, but the Borland RTL doesn't. Since we don't
4100 * want to be at the vendor's whim on the default, we set
4101 * it explicitly here.
4103 #if !defined(_ALPHA_) && !defined(__GNUC__)
4104 _control87(MCW_EM, MCW_EM);
4110 win32_get_child_IO(child_IO_table* ptbl)
4112 ptbl->childStdIn = GetStdHandle(STD_INPUT_HANDLE);
4113 ptbl->childStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
4114 ptbl->childStdErr = GetStdHandle(STD_ERROR_HANDLE);
4117 #ifdef HAVE_INTERP_INTERN
4120 Perl_sys_intern_init(pTHX)
4122 w32_perlshell_tokens = Nullch;
4123 w32_perlshell_vec = (char**)NULL;
4124 w32_perlshell_items = 0;
4125 w32_fdpid = newAV();
4126 New(1313, w32_children, 1, child_tab);
4127 w32_num_children = 0;
4128 # ifdef USE_ITHREADS
4130 New(1313, w32_pseudo_children, 1, child_tab);
4131 w32_num_pseudo_children = 0;
4133 w32_init_socktype = 0;
4137 Perl_sys_intern_clear(pTHX)
4139 Safefree(w32_perlshell_tokens);
4140 Safefree(w32_perlshell_vec);
4141 /* NOTE: w32_fdpid is freed by sv_clean_all() */
4142 Safefree(w32_children);
4143 # ifdef USE_ITHREADS
4144 Safefree(w32_pseudo_children);
4148 # ifdef USE_ITHREADS
4151 Perl_sys_intern_dup(pTHX_ struct interp_intern *src, struct interp_intern *dst)
4153 dst->perlshell_tokens = Nullch;
4154 dst->perlshell_vec = (char**)NULL;
4155 dst->perlshell_items = 0;
4156 dst->fdpid = newAV();
4157 Newz(1313, dst->children, 1, child_tab);
4159 Newz(1313, dst->pseudo_children, 1, child_tab);
4160 dst->thr_intern.Winit_socktype = 0;
4162 # endif /* USE_ITHREADS */
4163 #endif /* HAVE_INTERP_INTERN */
4166 win32_free_argvw(pTHX_ void *ptr)
4168 char** argv = (char**)ptr;
4176 win32_argv2utf8(int argc, char** argv)
4181 LPWSTR* lpwStr = CommandLineToArgvW(GetCommandLineW(), &wargc);
4182 if (lpwStr && argc) {
4184 length = WideCharToMultiByte(CP_UTF8, 0, lpwStr[--wargc], -1, NULL, 0, NULL, NULL);
4185 Newz(0, psz, length, char);
4186 WideCharToMultiByte(CP_UTF8, 0, lpwStr[wargc], -1, psz, length, NULL, NULL);
4189 call_atexit(win32_free_argvw, argv);
4191 GlobalFree((HGLOBAL)lpwStr);