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;
442 return -((int)w32_pseudo_id);
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 = 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) {
574 if (ckWARN(WARN_EXEC))
575 Perl_warner(aTHX_ WARN_EXEC, "Can't spawn \"%s\": %s", argv[0], strerror(errno));
580 PL_statusvalue = status;
587 do_spawn2(char *cmd, int exectype)
594 BOOL needToTry = TRUE;
597 /* Save an extra exec if possible. See if there are shell
598 * metacharacters in it */
599 if (!has_shell_metachars(cmd)) {
600 New(1301,argv, strlen(cmd) / 2 + 2, char*);
601 New(1302,cmd2, strlen(cmd) + 1, char);
604 for (s = cmd2; *s;) {
605 while (*s && isSPACE(*s))
609 while (*s && !isSPACE(*s))
618 status = win32_spawnvp(P_WAIT, argv[0],
619 (const char* const*)argv);
621 case EXECF_SPAWN_NOWAIT:
622 status = win32_spawnvp(P_NOWAIT, argv[0],
623 (const char* const*)argv);
626 status = win32_execvp(argv[0], (const char* const*)argv);
629 if (status != -1 || errno == 0)
639 New(1306, argv, w32_perlshell_items + 2, char*);
640 while (++i < w32_perlshell_items)
641 argv[i] = w32_perlshell_vec[i];
646 status = win32_spawnvp(P_WAIT, argv[0],
647 (const char* const*)argv);
649 case EXECF_SPAWN_NOWAIT:
650 status = win32_spawnvp(P_NOWAIT, argv[0],
651 (const char* const*)argv);
654 status = win32_execvp(argv[0], (const char* const*)argv);
660 if (exectype != EXECF_SPAWN_NOWAIT) {
663 if (ckWARN(WARN_EXEC))
664 Perl_warner(aTHX_ WARN_EXEC, "Can't %s \"%s\": %s",
665 (exectype == EXECF_EXEC ? "exec" : "spawn"),
666 cmd, strerror(errno));
671 PL_statusvalue = status;
679 return do_spawn2(cmd, EXECF_SPAWN);
683 do_spawn_nowait(char *cmd)
685 return do_spawn2(cmd, EXECF_SPAWN_NOWAIT);
689 Perl_do_exec(pTHX_ char *cmd)
691 do_spawn2(cmd, EXECF_EXEC);
695 /* The idea here is to read all the directory names into a string table
696 * (separated by nulls) and when one of the other dir functions is called
697 * return the pointer to the current file name.
700 win32_opendir(char *filename)
706 char scanname[MAX_PATH+3];
708 WIN32_FIND_DATAA aFindData;
709 WIN32_FIND_DATAW wFindData;
711 char buffer[MAX_PATH*2];
712 WCHAR wbuffer[MAX_PATH+1];
715 len = strlen(filename);
719 /* check to see if filename is a directory */
720 if (win32_stat(filename, &sbuf) < 0 || !S_ISDIR(sbuf.st_mode))
723 /* Get us a DIR structure */
724 Newz(1303, dirp, 1, DIR);
726 /* Create the search pattern */
727 strcpy(scanname, filename);
729 /* bare drive name means look in cwd for drive */
730 if (len == 2 && isALPHA(scanname[0]) && scanname[1] == ':') {
731 scanname[len++] = '.';
732 scanname[len++] = '/';
734 else if (scanname[len-1] != '/' && scanname[len-1] != '\\') {
735 scanname[len++] = '/';
737 scanname[len++] = '*';
738 scanname[len] = '\0';
740 /* do the FindFirstFile call */
742 A2WHELPER(scanname, wbuffer, sizeof(wbuffer));
743 fh = FindFirstFileW(PerlDir_mapW(wbuffer), &wFindData);
746 fh = FindFirstFileA(PerlDir_mapA(scanname), &aFindData);
749 if (fh == INVALID_HANDLE_VALUE) {
750 DWORD err = GetLastError();
751 /* FindFirstFile() fails on empty drives! */
753 case ERROR_FILE_NOT_FOUND:
755 case ERROR_NO_MORE_FILES:
756 case ERROR_PATH_NOT_FOUND:
759 case ERROR_NOT_ENOUGH_MEMORY:
770 /* now allocate the first part of the string table for
771 * the filenames that we find.
774 W2AHELPER(wFindData.cFileName, buffer, sizeof(buffer));
778 ptr = aFindData.cFileName;
785 New(1304, dirp->start, dirp->size, char);
786 strcpy(dirp->start, ptr);
788 dirp->end = dirp->curr = dirp->start;
794 /* Readdir just returns the current string pointer and bumps the
795 * string pointer to the nDllExport entry.
797 DllExport struct direct *
798 win32_readdir(DIR *dirp)
803 /* first set up the structure to return */
804 len = strlen(dirp->curr);
805 strcpy(dirp->dirstr.d_name, dirp->curr);
806 dirp->dirstr.d_namlen = len;
809 dirp->dirstr.d_ino = dirp->curr - dirp->start;
811 /* Now set up for the next call to readdir */
812 dirp->curr += len + 1;
813 if (dirp->curr >= dirp->end) {
817 WIN32_FIND_DATAW wFindData;
818 WIN32_FIND_DATAA aFindData;
819 char buffer[MAX_PATH*2];
821 /* finding the next file that matches the wildcard
822 * (which should be all of them in this directory!).
825 res = FindNextFileW(dirp->handle, &wFindData);
827 W2AHELPER(wFindData.cFileName, buffer, sizeof(buffer));
832 res = FindNextFileA(dirp->handle, &aFindData);
834 ptr = aFindData.cFileName;
837 long endpos = dirp->end - dirp->start;
838 long newsize = endpos + strlen(ptr) + 1;
839 /* bump the string table size by enough for the
840 * new name and it's null terminator */
841 while (newsize > dirp->size) {
842 long curpos = dirp->curr - dirp->start;
844 Renew(dirp->start, dirp->size, char);
845 dirp->curr = dirp->start + curpos;
847 strcpy(dirp->start + endpos, ptr);
848 dirp->end = dirp->start + newsize;
854 return &(dirp->dirstr);
860 /* Telldir returns the current string pointer position */
862 win32_telldir(DIR *dirp)
864 return (dirp->curr - dirp->start);
868 /* Seekdir moves the string pointer to a previously saved position
869 * (returned by telldir).
872 win32_seekdir(DIR *dirp, long loc)
874 dirp->curr = dirp->start + loc;
877 /* Rewinddir resets the string pointer to the start */
879 win32_rewinddir(DIR *dirp)
881 dirp->curr = dirp->start;
884 /* free the memory allocated by opendir */
886 win32_closedir(DIR *dirp)
889 if (dirp->handle != INVALID_HANDLE_VALUE)
890 FindClose(dirp->handle);
891 Safefree(dirp->start);
904 * Just pretend that everyone is a superuser. NT will let us know if
905 * we don\'t really have permission to do something.
908 #define ROOT_UID ((uid_t)0)
909 #define ROOT_GID ((gid_t)0)
938 return (auid == ROOT_UID ? 0 : -1);
944 return (agid == ROOT_GID ? 0 : -1);
951 char *buf = w32_getlogin_buffer;
952 DWORD size = sizeof(w32_getlogin_buffer);
953 if (GetUserName(buf,&size))
959 chown(const char *path, uid_t owner, gid_t group)
969 long child = w32_num_children;
970 while (--child >= 0) {
971 if (w32_child_pids[child] == pid)
978 remove_dead_process(long child)
982 CloseHandle(w32_child_handles[child]);
983 Move(&w32_child_handles[child+1], &w32_child_handles[child],
984 (w32_num_children-child-1), HANDLE);
985 Move(&w32_child_pids[child+1], &w32_child_pids[child],
986 (w32_num_children-child-1), DWORD);
993 find_pseudo_pid(int pid)
996 long child = w32_num_pseudo_children;
997 while (--child >= 0) {
998 if (w32_pseudo_child_pids[child] == pid)
1005 remove_dead_pseudo_process(long child)
1009 CloseHandle(w32_pseudo_child_handles[child]);
1010 Move(&w32_pseudo_child_handles[child+1], &w32_pseudo_child_handles[child],
1011 (w32_num_pseudo_children-child-1), HANDLE);
1012 Move(&w32_pseudo_child_pids[child+1], &w32_pseudo_child_pids[child],
1013 (w32_num_pseudo_children-child-1), DWORD);
1014 w32_num_pseudo_children--;
1020 win32_kill(int pid, int sig)
1026 /* it is a pseudo-forked child */
1027 long child = find_pseudo_pid(-pid);
1031 hProcess = w32_pseudo_child_handles[child];
1032 if (TerminateThread(hProcess, sig)) {
1033 remove_dead_pseudo_process(child);
1041 long child = find_pid(pid);
1045 hProcess = w32_child_handles[child];
1046 if (TerminateProcess(hProcess, sig)) {
1047 remove_dead_process(child);
1052 hProcess = OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid);
1056 if (TerminateProcess(hProcess, sig)) {
1057 CloseHandle(hProcess);
1071 DllExport unsigned int
1072 win32_sleep(unsigned int t)
1079 win32_stat(const char *path, struct stat *sbuf)
1082 char buffer[MAX_PATH+1];
1083 int l = strlen(path);
1085 WCHAR wbuffer[MAX_PATH+1];
1091 switch(path[l - 1]) {
1092 /* FindFirstFile() and stat() are buggy with a trailing
1093 * backslash, so change it to a forward slash :-( */
1095 strncpy(buffer, path, l-1);
1096 buffer[l - 1] = '/';
1100 /* FindFirstFile() is buggy with "x:", so add a dot :-( */
1102 if (l == 2 && isALPHA(path[0])) {
1103 buffer[0] = path[0];
1114 /* We *must* open & close the file once; otherwise file attribute changes */
1115 /* might not yet have propagated to "other" hard links of the same file. */
1116 /* This also gives us an opportunity to determine the number of links. */
1118 A2WHELPER(path, wbuffer, sizeof(wbuffer));
1119 pwbuffer = PerlDir_mapW(wbuffer);
1120 handle = CreateFileW(pwbuffer, 0, 0, NULL, OPEN_EXISTING, 0, NULL);
1123 path = PerlDir_mapA(path);
1125 handle = CreateFileA(path, 0, 0, NULL, OPEN_EXISTING, 0, NULL);
1127 if (handle != INVALID_HANDLE_VALUE) {
1128 BY_HANDLE_FILE_INFORMATION bhi;
1129 if (GetFileInformationByHandle(handle, &bhi))
1130 nlink = bhi.nNumberOfLinks;
1131 CloseHandle(handle);
1134 /* pwbuffer or path will be mapped correctly above */
1136 res = _wstat(pwbuffer, (struct _stat *)sbuf);
1139 res = stat(path, sbuf);
1141 sbuf->st_nlink = nlink;
1144 /* CRT is buggy on sharenames, so make sure it really isn't.
1145 * XXX using GetFileAttributesEx() will enable us to set
1146 * sbuf->st_*time (but note that's not available on the
1147 * Windows of 1995) */
1150 r = GetFileAttributesW(pwbuffer);
1153 r = GetFileAttributesA(path);
1155 if (r != 0xffffffff && (r & FILE_ATTRIBUTE_DIRECTORY)) {
1156 /* sbuf may still contain old garbage since stat() failed */
1157 Zero(sbuf, 1, struct stat);
1158 sbuf->st_mode = S_IFDIR | S_IREAD;
1160 if (!(r & FILE_ATTRIBUTE_READONLY))
1161 sbuf->st_mode |= S_IWRITE | S_IEXEC;
1166 if (l == 3 && isALPHA(path[0]) && path[1] == ':'
1167 && (path[2] == '\\' || path[2] == '/'))
1169 /* The drive can be inaccessible, some _stat()s are buggy */
1171 ? !GetVolumeInformationW(pwbuffer,NULL,0,NULL,NULL,NULL,NULL,0)
1172 : !GetVolumeInformationA(path,NULL,0,NULL,NULL,NULL,NULL,0)) {
1178 if (S_ISDIR(sbuf->st_mode))
1179 sbuf->st_mode |= S_IWRITE | S_IEXEC;
1180 else if (S_ISREG(sbuf->st_mode)) {
1182 if (l >= 4 && path[l-4] == '.') {
1183 const char *e = path + l - 3;
1184 if (strnicmp(e,"exe",3)
1185 && strnicmp(e,"bat",3)
1186 && strnicmp(e,"com",3)
1187 && (IsWin95() || strnicmp(e,"cmd",3)))
1188 sbuf->st_mode &= ~S_IEXEC;
1190 sbuf->st_mode |= S_IEXEC;
1193 sbuf->st_mode &= ~S_IEXEC;
1194 /* Propagate permissions to _group_ and _others_ */
1195 perms = sbuf->st_mode & (S_IREAD|S_IWRITE|S_IEXEC);
1196 sbuf->st_mode |= (perms>>3) | (perms>>6);
1203 /* Find the longname of a given path. path is destructively modified.
1204 * It should have space for at least MAX_PATH characters. */
1206 win32_longpath(char *path)
1208 WIN32_FIND_DATA fdata;
1210 char tmpbuf[MAX_PATH+1];
1211 char *tmpstart = tmpbuf;
1218 if (isALPHA(path[0]) && path[1] == ':' &&
1219 (path[2] == '/' || path[2] == '\\'))
1222 *tmpstart++ = path[0];
1226 else if ((path[0] == '/' || path[0] == '\\') &&
1227 (path[1] == '/' || path[1] == '\\'))
1230 *tmpstart++ = path[0];
1231 *tmpstart++ = path[1];
1232 /* copy machine name */
1233 while (*start && *start != '/' && *start != '\\')
1234 *tmpstart++ = *start++;
1236 *tmpstart++ = *start;
1238 /* copy share name */
1239 while (*start && *start != '/' && *start != '\\')
1240 *tmpstart++ = *start++;
1244 if (sep == '/' || sep == '\\')
1248 /* walk up to slash */
1249 while (*start && *start != '/' && *start != '\\')
1252 /* discard doubled slashes */
1253 while (*start && (start[1] == '/' || start[1] == '\\'))
1257 /* stop and find full name of component */
1259 fhand = FindFirstFile(path,&fdata);
1260 if (fhand != INVALID_HANDLE_VALUE) {
1261 strcpy(tmpstart, fdata.cFileName);
1262 tmpstart += strlen(fdata.cFileName);
1270 /* failed a step, just return without side effects */
1271 /*PerlIO_printf(Perl_debug_log, "Failed to find %s\n", path);*/
1276 strcpy(path,tmpbuf);
1280 #ifndef USE_WIN32_RTL_ENV
1283 win32_getenv(const char *name)
1286 WCHAR wBuffer[MAX_PATH+1];
1288 SV *curitem = Nullsv;
1291 A2WHELPER(name, wBuffer, sizeof(wBuffer));
1292 needlen = GetEnvironmentVariableW(wBuffer, NULL, 0);
1295 needlen = GetEnvironmentVariableA(name,NULL,0);
1297 curitem = sv_2mortal(newSVpvn("", 0));
1301 SvGROW(curitem, (needlen+1)*sizeof(WCHAR));
1302 needlen = GetEnvironmentVariableW(wBuffer,
1303 (WCHAR*)SvPVX(curitem),
1305 } while (needlen >= SvLEN(curitem)/sizeof(WCHAR));
1306 SvCUR_set(curitem, (needlen*sizeof(WCHAR))+1);
1307 acuritem = sv_2mortal(newSVsv(curitem));
1308 W2AHELPER((WCHAR*)SvPVX(acuritem), SvPVX(curitem), SvCUR(curitem));
1312 SvGROW(curitem, needlen+1);
1313 needlen = GetEnvironmentVariableA(name,SvPVX(curitem),
1315 } while (needlen >= SvLEN(curitem));
1316 SvCUR_set(curitem, needlen);
1320 /* allow any environment variables that begin with 'PERL'
1321 to be stored in the registry */
1322 if (strncmp(name, "PERL", 4) == 0)
1323 (void)get_regstr(name, &curitem);
1325 if (curitem && SvCUR(curitem))
1326 return SvPVX(curitem);
1332 win32_putenv(const char *name)
1339 int length, relval = -1;
1343 length = strlen(name)+1;
1344 New(1309,wCuritem,length,WCHAR);
1345 A2WHELPER(name, wCuritem, length*sizeof(WCHAR));
1346 wVal = wcschr(wCuritem, '=');
1349 if (SetEnvironmentVariableW(wCuritem, *wVal ? wVal : NULL))
1355 New(1309,curitem,strlen(name)+1,char);
1356 strcpy(curitem, name);
1357 val = strchr(curitem, '=');
1359 /* The sane way to deal with the environment.
1360 * Has these advantages over putenv() & co.:
1361 * * enables us to store a truly empty value in the
1362 * environment (like in UNIX).
1363 * * we don't have to deal with RTL globals, bugs and leaks.
1365 * Why you may want to enable USE_WIN32_RTL_ENV:
1366 * * environ[] and RTL functions will not reflect changes,
1367 * which might be an issue if extensions want to access
1368 * the env. via RTL. This cuts both ways, since RTL will
1369 * not see changes made by extensions that call the Win32
1370 * functions directly, either.
1374 if (SetEnvironmentVariableA(curitem, *val ? val : NULL))
1386 filetime_to_clock(PFILETIME ft)
1388 __int64 qw = ft->dwHighDateTime;
1390 qw |= ft->dwLowDateTime;
1391 qw /= 10000; /* File time ticks at 0.1uS, clock at 1mS */
1396 win32_times(struct tms *timebuf)
1401 if (GetProcessTimes(GetCurrentProcess(), &dummy, &dummy,
1403 timebuf->tms_utime = filetime_to_clock(&user);
1404 timebuf->tms_stime = filetime_to_clock(&kernel);
1405 timebuf->tms_cutime = 0;
1406 timebuf->tms_cstime = 0;
1409 /* That failed - e.g. Win95 fallback to clock() */
1410 clock_t t = clock();
1411 timebuf->tms_utime = t;
1412 timebuf->tms_stime = 0;
1413 timebuf->tms_cutime = 0;
1414 timebuf->tms_cstime = 0;
1419 /* fix utime() so it works on directories in NT */
1421 filetime_from_time(PFILETIME pFileTime, time_t Time)
1423 struct tm *pTM = localtime(&Time);
1424 SYSTEMTIME SystemTime;
1430 SystemTime.wYear = pTM->tm_year + 1900;
1431 SystemTime.wMonth = pTM->tm_mon + 1;
1432 SystemTime.wDay = pTM->tm_mday;
1433 SystemTime.wHour = pTM->tm_hour;
1434 SystemTime.wMinute = pTM->tm_min;
1435 SystemTime.wSecond = pTM->tm_sec;
1436 SystemTime.wMilliseconds = 0;
1438 return SystemTimeToFileTime(&SystemTime, &LocalTime) &&
1439 LocalFileTimeToFileTime(&LocalTime, pFileTime);
1443 win32_unlink(const char *filename)
1450 WCHAR wBuffer[MAX_PATH+1];
1453 A2WHELPER(filename, wBuffer, sizeof(wBuffer));
1454 pwBuffer = PerlDir_mapW(wBuffer);
1455 attrs = GetFileAttributesW(pwBuffer);
1456 if (attrs == 0xFFFFFFFF)
1458 if (attrs & FILE_ATTRIBUTE_READONLY) {
1459 (void)SetFileAttributesW(pwBuffer, attrs & ~FILE_ATTRIBUTE_READONLY);
1460 ret = _wunlink(pwBuffer);
1462 (void)SetFileAttributesW(pwBuffer, attrs);
1465 ret = _wunlink(pwBuffer);
1468 filename = PerlDir_mapA(filename);
1469 attrs = GetFileAttributesA(filename);
1470 if (attrs == 0xFFFFFFFF)
1472 if (attrs & FILE_ATTRIBUTE_READONLY) {
1473 (void)SetFileAttributesA(filename, attrs & ~FILE_ATTRIBUTE_READONLY);
1474 ret = unlink(filename);
1476 (void)SetFileAttributesA(filename, attrs);
1479 ret = unlink(filename);
1488 win32_utime(const char *filename, struct utimbuf *times)
1495 struct utimbuf TimeBuffer;
1496 WCHAR wbuffer[MAX_PATH+1];
1501 A2WHELPER(filename, wbuffer, sizeof(wbuffer));
1502 pwbuffer = PerlDir_mapW(wbuffer);
1503 rc = _wutime(pwbuffer, (struct _utimbuf*)times);
1506 filename = PerlDir_mapA(filename);
1507 rc = utime(filename, times);
1509 /* EACCES: path specifies directory or readonly file */
1510 if (rc == 0 || errno != EACCES /* || !IsWinNT() */)
1513 if (times == NULL) {
1514 times = &TimeBuffer;
1515 time(×->actime);
1516 times->modtime = times->actime;
1519 /* This will (and should) still fail on readonly files */
1521 handle = CreateFileW(pwbuffer, GENERIC_READ | GENERIC_WRITE,
1522 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1523 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1526 handle = CreateFileA(filename, GENERIC_READ | GENERIC_WRITE,
1527 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1528 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1530 if (handle == INVALID_HANDLE_VALUE)
1533 if (GetFileTime(handle, &ftCreate, &ftAccess, &ftWrite) &&
1534 filetime_from_time(&ftAccess, times->actime) &&
1535 filetime_from_time(&ftWrite, times->modtime) &&
1536 SetFileTime(handle, &ftCreate, &ftAccess, &ftWrite))
1541 CloseHandle(handle);
1546 win32_uname(struct utsname *name)
1548 struct hostent *hep;
1549 STRLEN nodemax = sizeof(name->nodename)-1;
1550 OSVERSIONINFO osver;
1552 memset(&osver, 0, sizeof(OSVERSIONINFO));
1553 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1554 if (GetVersionEx(&osver)) {
1556 switch (osver.dwPlatformId) {
1557 case VER_PLATFORM_WIN32_WINDOWS:
1558 strcpy(name->sysname, "Windows");
1560 case VER_PLATFORM_WIN32_NT:
1561 strcpy(name->sysname, "Windows NT");
1563 case VER_PLATFORM_WIN32s:
1564 strcpy(name->sysname, "Win32s");
1567 strcpy(name->sysname, "Win32 Unknown");
1572 sprintf(name->release, "%d.%d",
1573 osver.dwMajorVersion, osver.dwMinorVersion);
1576 sprintf(name->version, "Build %d",
1577 osver.dwPlatformId == VER_PLATFORM_WIN32_NT
1578 ? osver.dwBuildNumber : (osver.dwBuildNumber & 0xffff));
1579 if (osver.szCSDVersion[0]) {
1580 char *buf = name->version + strlen(name->version);
1581 sprintf(buf, " (%s)", osver.szCSDVersion);
1585 *name->sysname = '\0';
1586 *name->version = '\0';
1587 *name->release = '\0';
1591 hep = win32_gethostbyname("localhost");
1593 STRLEN len = strlen(hep->h_name);
1594 if (len <= nodemax) {
1595 strcpy(name->nodename, hep->h_name);
1598 strncpy(name->nodename, hep->h_name, nodemax);
1599 name->nodename[nodemax] = '\0';
1604 if (!GetComputerName(name->nodename, &sz))
1605 *name->nodename = '\0';
1608 /* machine (architecture) */
1612 GetSystemInfo(&info);
1614 #if defined(__BORLANDC__) || defined(__MINGW32__)
1615 switch (info.u.s.wProcessorArchitecture) {
1617 switch (info.wProcessorArchitecture) {
1619 case PROCESSOR_ARCHITECTURE_INTEL:
1620 arch = "x86"; break;
1621 case PROCESSOR_ARCHITECTURE_MIPS:
1622 arch = "mips"; break;
1623 case PROCESSOR_ARCHITECTURE_ALPHA:
1624 arch = "alpha"; break;
1625 case PROCESSOR_ARCHITECTURE_PPC:
1626 arch = "ppc"; break;
1628 arch = "unknown"; break;
1630 strcpy(name->machine, arch);
1636 win32_waitpid(int pid, int *status, int flags)
1640 if (pid == -1) /* XXX threadid == 1 ? */
1641 return win32_wait(status);
1644 long child = find_pseudo_pid(-pid);
1646 HANDLE hThread = w32_pseudo_child_handles[child];
1647 DWORD timeout = (flags & WNOHANG) ? 0 : INFINITE;
1648 DWORD waitcode = WaitForSingleObject(hThread, timeout);
1649 if (waitcode == WAIT_TIMEOUT) {
1652 else if (waitcode != WAIT_FAILED) {
1653 if (GetExitCodeThread(hThread, &waitcode)) {
1654 *status = (int)((waitcode & 0xff) << 8);
1655 retval = (int)w32_pseudo_child_pids[child];
1656 remove_dead_pseudo_process(child);
1666 long child = find_pid(pid);
1668 HANDLE hProcess = w32_child_handles[child];
1669 DWORD timeout = (flags & WNOHANG) ? 0 : INFINITE;
1670 DWORD waitcode = WaitForSingleObject(hProcess, timeout);
1671 if (waitcode == WAIT_TIMEOUT) {
1674 else if (waitcode != WAIT_FAILED) {
1675 if (GetExitCodeProcess(hProcess, &waitcode)) {
1676 *status = (int)((waitcode & 0xff) << 8);
1677 retval = (int)w32_child_pids[child];
1678 remove_dead_process(child);
1686 retval = cwait(status, pid, WAIT_CHILD);
1687 /* cwait() returns "correctly" on Borland */
1688 #ifndef __BORLANDC__
1694 return retval >= 0 ? pid : retval;
1698 win32_wait(int *status)
1700 /* XXX this wait emulation only knows about processes
1701 * spawned via win32_spawnvp(P_NOWAIT, ...).
1705 DWORD exitcode, waitcode;
1708 if (w32_num_pseudo_children) {
1709 waitcode = WaitForMultipleObjects(w32_num_pseudo_children,
1710 w32_pseudo_child_handles,
1713 if (waitcode != WAIT_FAILED) {
1714 if (waitcode >= WAIT_ABANDONED_0
1715 && waitcode < WAIT_ABANDONED_0 + w32_num_pseudo_children)
1716 i = waitcode - WAIT_ABANDONED_0;
1718 i = waitcode - WAIT_OBJECT_0;
1719 if (GetExitCodeThread(w32_pseudo_child_handles[i], &exitcode)) {
1720 *status = (int)((exitcode & 0xff) << 8);
1721 retval = (int)w32_pseudo_child_pids[i];
1722 remove_dead_pseudo_process(i);
1729 if (!w32_num_children) {
1734 /* if a child exists, wait for it to die */
1735 waitcode = WaitForMultipleObjects(w32_num_children,
1739 if (waitcode != WAIT_FAILED) {
1740 if (waitcode >= WAIT_ABANDONED_0
1741 && waitcode < WAIT_ABANDONED_0 + w32_num_children)
1742 i = waitcode - WAIT_ABANDONED_0;
1744 i = waitcode - WAIT_OBJECT_0;
1745 if (GetExitCodeProcess(w32_child_handles[i], &exitcode) ) {
1746 *status = (int)((exitcode & 0xff) << 8);
1747 retval = (int)w32_child_pids[i];
1748 remove_dead_process(i);
1754 errno = GetLastError();
1760 static UINT timerid = 0;
1762 static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
1765 KillTimer(NULL,timerid);
1767 CALL_FPTR(PL_sighandlerp)(14);
1769 #endif /* !PERL_OBJECT */
1771 DllExport unsigned int
1772 win32_alarm(unsigned int sec)
1776 * the 'obvious' implentation is SetTimer() with a callback
1777 * which does whatever receiving SIGALRM would do
1778 * we cannot use SIGALRM even via raise() as it is not
1779 * one of the supported codes in <signal.h>
1781 * Snag is unless something is looking at the message queue
1782 * nothing happens :-(
1787 timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
1789 Perl_croak_nocontext("Cannot set timer");
1795 KillTimer(NULL,timerid);
1799 #endif /* !PERL_OBJECT */
1803 #ifdef HAVE_DES_FCRYPT
1804 extern char * des_fcrypt(const char *txt, const char *salt, char *cbuf);
1808 win32_crypt(const char *txt, const char *salt)
1811 #ifdef HAVE_DES_FCRYPT
1813 return des_fcrypt(txt, salt, w32_crypt_buffer);
1815 Perl_croak(aTHX_ "The crypt() function is unimplemented due to excessive paranoia.");
1820 /* C doesn't like repeat struct definitions */
1822 #if defined(USE_FIXED_OSFHANDLE) || defined(PERL_MSVCRT_READFIX)
1825 #define _CRTIMP __declspec(dllimport)
1829 * Control structure for lowio file handles
1832 long osfhnd; /* underlying OS file HANDLE */
1833 char osfile; /* attributes of file (e.g., open in text mode?) */
1834 char pipech; /* one char buffer for handles opened on pipes */
1836 CRITICAL_SECTION lock;
1841 * Array of arrays of control structures for lowio files.
1843 EXTERN_C _CRTIMP ioinfo* __pioinfo[];
1846 * Definition of IOINFO_L2E, the log base 2 of the number of elements in each
1847 * array of ioinfo structs.
1849 #define IOINFO_L2E 5
1852 * Definition of IOINFO_ARRAY_ELTS, the number of elements in ioinfo array
1854 #define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
1857 * Access macros for getting at an ioinfo struct and its fields from a
1860 #define _pioinfo(i) (__pioinfo[(i) >> IOINFO_L2E] + ((i) & (IOINFO_ARRAY_ELTS - 1)))
1861 #define _osfhnd(i) (_pioinfo(i)->osfhnd)
1862 #define _osfile(i) (_pioinfo(i)->osfile)
1863 #define _pipech(i) (_pioinfo(i)->pipech)
1867 #ifdef USE_FIXED_OSFHANDLE
1869 #define FOPEN 0x01 /* file handle open */
1870 #define FNOINHERIT 0x10 /* file handle opened O_NOINHERIT */
1871 #define FAPPEND 0x20 /* file handle opened O_APPEND */
1872 #define FDEV 0x40 /* file handle refers to device */
1873 #define FTEXT 0x80 /* file handle is in text mode */
1876 *int my_open_osfhandle(long osfhandle, int flags) - open C Runtime file handle
1879 * This function allocates a free C Runtime file handle and associates
1880 * it with the Win32 HANDLE specified by the first parameter. This is a
1881 * temperary fix for WIN95's brain damage GetFileType() error on socket
1882 * we just bypass that call for socket
1884 * This works with MSVC++ 4.0+ or GCC/Mingw32
1887 * long osfhandle - Win32 HANDLE to associate with C Runtime file handle.
1888 * int flags - flags to associate with C Runtime file handle.
1891 * returns index of entry in fh, if successful
1892 * return -1, if no free entry is found
1896 *******************************************************************************/
1899 * we fake up some parts of the CRT that aren't exported by MSVCRT.dll
1900 * this lets sockets work on Win9X with GCC and should fix the problems
1905 /* since we are not doing a dup2(), this works fine */
1907 #define _set_osfhnd(fh, osfh) (void)(_osfhnd(fh) = osfh)
1909 /* create an ioinfo entry, kill its handle, and steal the entry */
1914 HANDLE hF = CreateFile("NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
1915 int fh = _open_osfhandle((long)hF, 0);
1919 EnterCriticalSection(&(_pioinfo(fh)->lock));
1924 my_open_osfhandle(long osfhandle, int flags)
1927 char fileflags; /* _osfile flags */
1929 /* copy relevant flags from second parameter */
1932 if (flags & O_APPEND)
1933 fileflags |= FAPPEND;
1938 if (flags & O_NOINHERIT)
1939 fileflags |= FNOINHERIT;
1941 /* attempt to allocate a C Runtime file handle */
1942 if ((fh = _alloc_osfhnd()) == -1) {
1943 errno = EMFILE; /* too many open files */
1944 _doserrno = 0L; /* not an OS error */
1945 return -1; /* return error to caller */
1948 /* the file is open. now, set the info in _osfhnd array */
1949 _set_osfhnd(fh, osfhandle);
1951 fileflags |= FOPEN; /* mark as open */
1953 _osfile(fh) = fileflags; /* set osfile entry */
1954 LeaveCriticalSection(&_pioinfo(fh)->lock);
1956 return fh; /* return handle */
1959 #endif /* USE_FIXED_OSFHANDLE */
1961 /* simulate flock by locking a range on the file */
1963 #define LK_ERR(f,i) ((f) ? (i = 0) : (errno = GetLastError()))
1964 #define LK_LEN 0xffff0000
1967 win32_flock(int fd, int oper)
1975 Perl_croak_nocontext("flock() unimplemented on this platform");
1978 fh = (HANDLE)_get_osfhandle(fd);
1979 memset(&o, 0, sizeof(o));
1982 case LOCK_SH: /* shared lock */
1983 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
1985 case LOCK_EX: /* exclusive lock */
1986 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
1988 case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
1989 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
1991 case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
1992 LK_ERR(LockFileEx(fh,
1993 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
1994 0, LK_LEN, 0, &o),i);
1996 case LOCK_UN: /* unlock lock */
1997 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, 0, &o),i);
1999 default: /* unknown */
2010 * redirected io subsystem for all XS modules
2023 return (&(_environ));
2026 /* the rest are the remapped stdio routines */
2046 win32_ferror(FILE *fp)
2048 return (ferror(fp));
2053 win32_feof(FILE *fp)
2059 * Since the errors returned by the socket error function
2060 * WSAGetLastError() are not known by the library routine strerror
2061 * we have to roll our own.
2065 win32_strerror(int e)
2067 #ifndef __BORLANDC__ /* Borland intolerance */
2068 extern int sys_nerr;
2072 if (e < 0 || e > sys_nerr) {
2077 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
2078 w32_strerror_buffer,
2079 sizeof(w32_strerror_buffer), NULL) == 0)
2080 strcpy(w32_strerror_buffer, "Unknown Error");
2082 return w32_strerror_buffer;
2088 win32_str_os_error(void *sv, DWORD dwErr)
2092 dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
2093 |FORMAT_MESSAGE_IGNORE_INSERTS
2094 |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
2095 dwErr, 0, (char *)&sMsg, 1, NULL);
2096 /* strip trailing whitespace and period */
2099 --dwLen; /* dwLen doesn't include trailing null */
2100 } while (0 < dwLen && isSPACE(sMsg[dwLen]));
2101 if ('.' != sMsg[dwLen])
2106 sMsg = (char*)LocalAlloc(0, 64/**sizeof(TCHAR)*/);
2108 dwLen = sprintf(sMsg,
2109 "Unknown error #0x%lX (lookup 0x%lX)",
2110 dwErr, GetLastError());
2114 sv_setpvn((SV*)sv, sMsg, dwLen);
2121 win32_fprintf(FILE *fp, const char *format, ...)
2124 va_start(marker, format); /* Initialize variable arguments. */
2126 return (vfprintf(fp, format, marker));
2130 win32_printf(const char *format, ...)
2133 va_start(marker, format); /* Initialize variable arguments. */
2135 return (vprintf(format, marker));
2139 win32_vfprintf(FILE *fp, const char *format, va_list args)
2141 return (vfprintf(fp, format, args));
2145 win32_vprintf(const char *format, va_list args)
2147 return (vprintf(format, args));
2151 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
2153 return fread(buf, size, count, fp);
2157 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
2159 return fwrite(buf, size, count, fp);
2162 #define MODE_SIZE 10
2165 win32_fopen(const char *filename, const char *mode)
2168 WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH+1];
2174 if (stricmp(filename, "/dev/null")==0)
2178 A2WHELPER(mode, wMode, sizeof(wMode));
2179 A2WHELPER(filename, wBuffer, sizeof(wBuffer));
2180 f = _wfopen(PerlDir_mapW(wBuffer), wMode);
2183 f = fopen(PerlDir_mapA(filename), mode);
2184 /* avoid buffering headaches for child processes */
2185 if (f && *mode == 'a')
2186 win32_fseek(f, 0, SEEK_END);
2190 #ifndef USE_SOCKETS_AS_HANDLES
2192 #define fdopen my_fdopen
2196 win32_fdopen(int handle, const char *mode)
2199 WCHAR wMode[MODE_SIZE];
2202 A2WHELPER(mode, wMode, sizeof(wMode));
2203 f = _wfdopen(handle, wMode);
2206 f = fdopen(handle, (char *) mode);
2207 /* avoid buffering headaches for child processes */
2208 if (f && *mode == 'a')
2209 win32_fseek(f, 0, SEEK_END);
2214 win32_freopen(const char *path, const char *mode, FILE *stream)
2217 WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH+1];
2218 if (stricmp(path, "/dev/null")==0)
2222 A2WHELPER(mode, wMode, sizeof(wMode));
2223 A2WHELPER(path, wBuffer, sizeof(wBuffer));
2224 return _wfreopen(PerlDir_mapW(wBuffer), wMode, stream);
2226 return freopen(PerlDir_mapA(path), mode, stream);
2230 win32_fclose(FILE *pf)
2232 return my_fclose(pf); /* defined in win32sck.c */
2236 win32_fputs(const char *s,FILE *pf)
2238 return fputs(s, pf);
2242 win32_fputc(int c,FILE *pf)
2248 win32_ungetc(int c,FILE *pf)
2250 return ungetc(c,pf);
2254 win32_getc(FILE *pf)
2260 win32_fileno(FILE *pf)
2266 win32_clearerr(FILE *pf)
2273 win32_fflush(FILE *pf)
2279 win32_ftell(FILE *pf)
2285 win32_fseek(FILE *pf,long offset,int origin)
2287 return fseek(pf, offset, origin);
2291 win32_fgetpos(FILE *pf,fpos_t *p)
2293 return fgetpos(pf, p);
2297 win32_fsetpos(FILE *pf,const fpos_t *p)
2299 return fsetpos(pf, p);
2303 win32_rewind(FILE *pf)
2323 win32_fstat(int fd,struct stat *sbufptr)
2325 return fstat(fd,sbufptr);
2329 win32_pipe(int *pfd, unsigned int size, int mode)
2331 return _pipe(pfd, size, mode);
2335 * a popen() clone that respects PERL5SHELL
2339 win32_popen(const char *command, const char *mode)
2341 #ifdef USE_RTL_POPEN
2342 return _popen(command, mode);
2350 /* establish which ends read and write */
2351 if (strchr(mode,'w')) {
2352 stdfd = 0; /* stdin */
2356 else if (strchr(mode,'r')) {
2357 stdfd = 1; /* stdout */
2364 /* set the correct mode */
2365 if (strchr(mode,'b'))
2367 else if (strchr(mode,'t'))
2370 ourmode = _fmode & (O_TEXT | O_BINARY);
2372 /* the child doesn't inherit handles */
2373 ourmode |= O_NOINHERIT;
2375 if (win32_pipe( p, 512, ourmode) == -1)
2378 /* save current stdfd */
2379 if ((oldfd = win32_dup(stdfd)) == -1)
2382 /* make stdfd go to child end of pipe (implicitly closes stdfd) */
2383 /* stdfd will be inherited by the child */
2384 if (win32_dup2(p[child], stdfd) == -1)
2387 /* close the child end in parent */
2388 win32_close(p[child]);
2390 /* start the child */
2393 if ((childpid = do_spawn_nowait((char*)command)) == -1)
2396 /* revert stdfd to whatever it was before */
2397 if (win32_dup2(oldfd, stdfd) == -1)
2400 /* close saved handle */
2404 sv_setiv(*av_fetch(w32_fdpid, p[parent], TRUE), childpid);
2407 /* set process id so that it can be returned by perl's open() */
2408 PL_forkprocess = childpid;
2411 /* we have an fd, return a file stream */
2412 return (win32_fdopen(p[parent], (char *)mode));
2415 /* we don't need to check for errors here */
2419 win32_dup2(oldfd, stdfd);
2424 #endif /* USE_RTL_POPEN */
2432 win32_pclose(FILE *pf)
2434 #ifdef USE_RTL_POPEN
2438 int childpid, status;
2442 sv = *av_fetch(w32_fdpid, win32_fileno(pf), TRUE);
2445 childpid = SvIVX(sv);
2458 if (win32_waitpid(childpid, &status, 0) == -1)
2463 #endif /* USE_RTL_POPEN */
2469 LPCWSTR lpExistingFileName,
2470 LPSECURITY_ATTRIBUTES lpSecurityAttributes)
2473 WCHAR wFullName[MAX_PATH+1];
2474 LPVOID lpContext = NULL;
2475 WIN32_STREAM_ID StreamId;
2476 DWORD dwSize = (char*)&StreamId.cStreamName - (char*)&StreamId;
2481 BOOL (__stdcall *pfnBackupWrite)(HANDLE, LPBYTE, DWORD, LPDWORD,
2482 BOOL, BOOL, LPVOID*) =
2483 (BOOL (__stdcall *)(HANDLE, LPBYTE, DWORD, LPDWORD,
2484 BOOL, BOOL, LPVOID*))
2485 GetProcAddress(GetModuleHandle("kernel32.dll"), "BackupWrite");
2486 if (pfnBackupWrite == NULL)
2489 dwLen = GetFullPathNameW(lpFileName, MAX_PATH, wFullName, NULL);
2492 dwLen = (dwLen+1)*sizeof(WCHAR);
2494 handle = CreateFileW(lpExistingFileName, FILE_WRITE_ATTRIBUTES,
2495 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
2496 NULL, OPEN_EXISTING, 0, NULL);
2497 if (handle == INVALID_HANDLE_VALUE)
2500 StreamId.dwStreamId = BACKUP_LINK;
2501 StreamId.dwStreamAttributes = 0;
2502 StreamId.dwStreamNameSize = 0;
2503 #if defined(__BORLANDC__) || defined(__MINGW32__)
2504 StreamId.Size.u.HighPart = 0;
2505 StreamId.Size.u.LowPart = dwLen;
2507 StreamId.Size.HighPart = 0;
2508 StreamId.Size.LowPart = dwLen;
2511 bSuccess = pfnBackupWrite(handle, (LPBYTE)&StreamId, dwSize, &dwWritten,
2512 FALSE, FALSE, &lpContext);
2514 bSuccess = pfnBackupWrite(handle, (LPBYTE)wFullName, dwLen, &dwWritten,
2515 FALSE, FALSE, &lpContext);
2516 pfnBackupWrite(handle, NULL, 0, &dwWritten, TRUE, FALSE, &lpContext);
2519 CloseHandle(handle);
2524 win32_link(const char *oldname, const char *newname)
2527 BOOL (__stdcall *pfnCreateHardLinkW)(LPCWSTR,LPCWSTR,LPSECURITY_ATTRIBUTES);
2528 WCHAR wOldName[MAX_PATH+1];
2529 WCHAR wNewName[MAX_PATH+1];
2532 Perl_croak(aTHX_ PL_no_func, "link");
2534 pfnCreateHardLinkW =
2535 (BOOL (__stdcall *)(LPCWSTR, LPCWSTR, LPSECURITY_ATTRIBUTES))
2536 GetProcAddress(GetModuleHandle("kernel32.dll"), "CreateHardLinkW");
2537 if (pfnCreateHardLinkW == NULL)
2538 pfnCreateHardLinkW = Nt4CreateHardLinkW;
2540 if ((A2WHELPER(oldname, wOldName, sizeof(wOldName))) &&
2541 (A2WHELPER(newname, wNewName, sizeof(wNewName))) &&
2542 (wcscpy(wOldName, PerlDir_mapW(wOldName)),
2543 pfnCreateHardLinkW(PerlDir_mapW(wNewName), wOldName, NULL)))
2547 errno = (GetLastError() == ERROR_FILE_NOT_FOUND) ? ENOENT : EINVAL;
2552 win32_rename(const char *oname, const char *newname)
2554 WCHAR wOldName[MAX_PATH+1];
2555 WCHAR wNewName[MAX_PATH+1];
2556 char szOldName[MAX_PATH+1];
2557 char szNewName[MAX_PATH+1];
2561 /* XXX despite what the documentation says about MoveFileEx(),
2562 * it doesn't work under Windows95!
2565 DWORD dwFlags = MOVEFILE_COPY_ALLOWED;
2567 A2WHELPER(oname, wOldName, sizeof(wOldName));
2568 A2WHELPER(newname, wNewName, sizeof(wNewName));
2569 if (wcsicmp(wNewName, wOldName))
2570 dwFlags |= MOVEFILE_REPLACE_EXISTING;
2571 wcscpy(wOldName, PerlDir_mapW(wOldName));
2572 bResult = MoveFileExW(wOldName,PerlDir_mapW(wNewName), dwFlags);
2575 if (stricmp(newname, oname))
2576 dwFlags |= MOVEFILE_REPLACE_EXISTING;
2577 strcpy(szOldName, PerlDir_mapA(oname));
2578 bResult = MoveFileExA(szOldName,PerlDir_mapA(newname), dwFlags);
2581 DWORD err = GetLastError();
2583 case ERROR_BAD_NET_NAME:
2584 case ERROR_BAD_NETPATH:
2585 case ERROR_BAD_PATHNAME:
2586 case ERROR_FILE_NOT_FOUND:
2587 case ERROR_FILENAME_EXCED_RANGE:
2588 case ERROR_INVALID_DRIVE:
2589 case ERROR_NO_MORE_FILES:
2590 case ERROR_PATH_NOT_FOUND:
2603 char szTmpName[MAX_PATH+1];
2604 char dname[MAX_PATH+1];
2605 char *endname = Nullch;
2607 DWORD from_attr, to_attr;
2609 strcpy(szOldName, PerlDir_mapA(oname));
2610 strcpy(szNewName, PerlDir_mapA(newname));
2612 /* if oname doesn't exist, do nothing */
2613 from_attr = GetFileAttributes(szOldName);
2614 if (from_attr == 0xFFFFFFFF) {
2619 /* if newname exists, rename it to a temporary name so that we
2620 * don't delete it in case oname happens to be the same file
2621 * (but perhaps accessed via a different path)
2623 to_attr = GetFileAttributes(szNewName);
2624 if (to_attr != 0xFFFFFFFF) {
2625 /* if newname is a directory, we fail
2626 * XXX could overcome this with yet more convoluted logic */
2627 if (to_attr & FILE_ATTRIBUTE_DIRECTORY) {
2631 tmplen = strlen(szNewName);
2632 strcpy(szTmpName,szNewName);
2633 endname = szTmpName+tmplen;
2634 for (; endname > szTmpName ; --endname) {
2635 if (*endname == '/' || *endname == '\\') {
2640 if (endname > szTmpName)
2641 endname = strcpy(dname,szTmpName);
2645 /* get a temporary filename in same directory
2646 * XXX is this really the best we can do? */
2647 if (!GetTempFileName((LPCTSTR)endname, "plr", 0, szTmpName)) {
2651 DeleteFile(szTmpName);
2653 retval = rename(szNewName, szTmpName);
2660 /* rename oname to newname */
2661 retval = rename(szOldName, szNewName);
2663 /* if we created a temporary file before ... */
2664 if (endname != Nullch) {
2665 /* ...and rename succeeded, delete temporary file/directory */
2667 DeleteFile(szTmpName);
2668 /* else restore it to what it was */
2670 (void)rename(szTmpName, szNewName);
2677 win32_setmode(int fd, int mode)
2679 return setmode(fd, mode);
2683 win32_lseek(int fd, long offset, int origin)
2685 return lseek(fd, offset, origin);
2695 win32_open(const char *path, int flag, ...)
2700 WCHAR wBuffer[MAX_PATH+1];
2703 pmode = va_arg(ap, int);
2706 if (stricmp(path, "/dev/null")==0)
2710 A2WHELPER(path, wBuffer, sizeof(wBuffer));
2711 return _wopen(PerlDir_mapW(wBuffer), flag, pmode);
2713 return open(PerlDir_mapA(path), flag, pmode);
2735 win32_dup2(int fd1,int fd2)
2737 return dup2(fd1,fd2);
2740 #ifdef PERL_MSVCRT_READFIX
2742 #define LF 10 /* line feed */
2743 #define CR 13 /* carriage return */
2744 #define CTRLZ 26 /* ctrl-z means eof for text */
2745 #define FOPEN 0x01 /* file handle open */
2746 #define FEOFLAG 0x02 /* end of file has been encountered */
2747 #define FCRLF 0x04 /* CR-LF across read buffer (in text mode) */
2748 #define FPIPE 0x08 /* file handle refers to a pipe */
2749 #define FAPPEND 0x20 /* file handle opened O_APPEND */
2750 #define FDEV 0x40 /* file handle refers to device */
2751 #define FTEXT 0x80 /* file handle is in text mode */
2752 #define MAX_DESCRIPTOR_COUNT (64*32) /* this is the maximun that MSVCRT can handle */
2755 _fixed_read(int fh, void *buf, unsigned cnt)
2757 int bytes_read; /* number of bytes read */
2758 char *buffer; /* buffer to read to */
2759 int os_read; /* bytes read on OS call */
2760 char *p, *q; /* pointers into buffer */
2761 char peekchr; /* peek-ahead character */
2762 ULONG filepos; /* file position after seek */
2763 ULONG dosretval; /* o.s. return value */
2765 /* validate handle */
2766 if (((unsigned)fh >= (unsigned)MAX_DESCRIPTOR_COUNT) ||
2767 !(_osfile(fh) & FOPEN))
2769 /* out of range -- return error */
2771 _doserrno = 0; /* not o.s. error */
2776 * If lockinitflag is FALSE, assume fd is device
2777 * lockinitflag is set to TRUE by open.
2779 if (_pioinfo(fh)->lockinitflag)
2780 EnterCriticalSection(&(_pioinfo(fh)->lock)); /* lock file */
2782 bytes_read = 0; /* nothing read yet */
2783 buffer = (char*)buf;
2785 if (cnt == 0 || (_osfile(fh) & FEOFLAG)) {
2786 /* nothing to read or at EOF, so return 0 read */
2790 if ((_osfile(fh) & (FPIPE|FDEV)) && _pipech(fh) != LF) {
2791 /* a pipe/device and pipe lookahead non-empty: read the lookahead
2793 *buffer++ = _pipech(fh);
2796 _pipech(fh) = LF; /* mark as empty */
2801 if (!ReadFile((HANDLE)_osfhnd(fh), buffer, cnt, (LPDWORD)&os_read, NULL))
2803 /* ReadFile has reported an error. recognize two special cases.
2805 * 1. map ERROR_ACCESS_DENIED to EBADF
2807 * 2. just return 0 if ERROR_BROKEN_PIPE has occurred. it
2808 * means the handle is a read-handle on a pipe for which
2809 * all write-handles have been closed and all data has been
2812 if ((dosretval = GetLastError()) == ERROR_ACCESS_DENIED) {
2813 /* wrong read/write mode should return EBADF, not EACCES */
2815 _doserrno = dosretval;
2819 else if (dosretval == ERROR_BROKEN_PIPE) {
2829 bytes_read += os_read; /* update bytes read */
2831 if (_osfile(fh) & FTEXT) {
2832 /* now must translate CR-LFs to LFs in the buffer */
2834 /* set CRLF flag to indicate LF at beginning of buffer */
2835 /* if ((os_read != 0) && (*(char *)buf == LF)) */
2836 /* _osfile(fh) |= FCRLF; */
2838 /* _osfile(fh) &= ~FCRLF; */
2840 _osfile(fh) &= ~FCRLF;
2842 /* convert chars in the buffer: p is src, q is dest */
2844 while (p < (char *)buf + bytes_read) {
2846 /* if fh is not a device, set ctrl-z flag */
2847 if (!(_osfile(fh) & FDEV))
2848 _osfile(fh) |= FEOFLAG;
2849 break; /* stop translating */
2854 /* *p is CR, so must check next char for LF */
2855 if (p < (char *)buf + bytes_read - 1) {
2858 *q++ = LF; /* convert CR-LF to LF */
2861 *q++ = *p++; /* store char normally */
2864 /* This is the hard part. We found a CR at end of
2865 buffer. We must peek ahead to see if next char
2870 if (!ReadFile((HANDLE)_osfhnd(fh), &peekchr, 1,
2871 (LPDWORD)&os_read, NULL))
2872 dosretval = GetLastError();
2874 if (dosretval != 0 || os_read == 0) {
2875 /* couldn't read ahead, store CR */
2879 /* peekchr now has the extra character -- we now
2880 have several possibilities:
2881 1. disk file and char is not LF; just seek back
2883 2. disk file and char is LF; store LF, don't seek back
2884 3. pipe/device and char is LF; store LF.
2885 4. pipe/device and char isn't LF, store CR and
2886 put char in pipe lookahead buffer. */
2887 if (_osfile(fh) & (FDEV|FPIPE)) {
2888 /* non-seekable device */
2893 _pipech(fh) = peekchr;
2898 if (peekchr == LF) {
2899 /* nothing read yet; must make some
2902 /* turn on this flag for tell routine */
2903 _osfile(fh) |= FCRLF;
2906 HANDLE osHandle; /* o.s. handle value */
2908 if ((osHandle = (HANDLE)_get_osfhandle(fh)) != (HANDLE)-1)
2910 if ((filepos = SetFilePointer(osHandle, -1, NULL, FILE_CURRENT)) == -1)
2911 dosretval = GetLastError();
2922 /* we now change bytes_read to reflect the true number of chars
2924 bytes_read = q - (char *)buf;
2928 if (_pioinfo(fh)->lockinitflag)
2929 LeaveCriticalSection(&(_pioinfo(fh)->lock)); /* unlock file */
2934 #endif /* PERL_MSVCRT_READFIX */
2937 win32_read(int fd, void *buf, unsigned int cnt)
2939 #ifdef PERL_MSVCRT_READFIX
2940 return _fixed_read(fd, buf, cnt);
2942 return read(fd, buf, cnt);
2947 win32_write(int fd, const void *buf, unsigned int cnt)
2949 return write(fd, buf, cnt);
2953 win32_mkdir(const char *dir, int mode)
2957 WCHAR wBuffer[MAX_PATH+1];
2958 A2WHELPER(dir, wBuffer, sizeof(wBuffer));
2959 return _wmkdir(PerlDir_mapW(wBuffer));
2961 return mkdir(PerlDir_mapA(dir)); /* just ignore mode */
2965 win32_rmdir(const char *dir)
2969 WCHAR wBuffer[MAX_PATH+1];
2970 A2WHELPER(dir, wBuffer, sizeof(wBuffer));
2971 return _wrmdir(PerlDir_mapW(wBuffer));
2973 return rmdir(PerlDir_mapA(dir));
2977 win32_chdir(const char *dir)
2981 WCHAR wBuffer[MAX_PATH+1];
2982 A2WHELPER(dir, wBuffer, sizeof(wBuffer));
2983 return _wchdir(wBuffer);
2989 win32_access(const char *path, int mode)
2993 WCHAR wBuffer[MAX_PATH+1];
2994 A2WHELPER(path, wBuffer, sizeof(wBuffer));
2995 return _waccess(PerlDir_mapW(wBuffer), mode);
2997 return access(PerlDir_mapA(path), mode);
3001 win32_chmod(const char *path, int mode)
3005 WCHAR wBuffer[MAX_PATH+1];
3006 A2WHELPER(path, wBuffer, sizeof(wBuffer));
3007 return _wchmod(PerlDir_mapW(wBuffer), mode);
3009 return chmod(PerlDir_mapA(path), mode);
3014 create_command_line(const char* command, const char * const *args)
3018 char *cmd, *ptr, *arg;
3019 STRLEN len = strlen(command) + 1;
3021 for (index = 0; (ptr = (char*)args[index]) != NULL; ++index)
3022 len += strlen(ptr) + 1;
3024 New(1310, cmd, len, char);
3026 strcpy(ptr, command);
3028 for (index = 0; (arg = (char*)args[index]) != NULL; ++index) {
3038 qualified_path(const char *cmd)
3042 char *fullcmd, *curfullcmd;
3048 fullcmd = (char*)cmd;
3050 if (*fullcmd == '/' || *fullcmd == '\\')
3057 pathstr = win32_getenv("PATH");
3058 New(0, fullcmd, MAX_PATH+1, char);
3059 curfullcmd = fullcmd;
3064 /* start by appending the name to the current prefix */
3065 strcpy(curfullcmd, cmd);
3066 curfullcmd += cmdlen;
3068 /* if it doesn't end with '.', or has no extension, try adding
3069 * a trailing .exe first */
3070 if (cmd[cmdlen-1] != '.'
3071 && (cmdlen < 4 || cmd[cmdlen-4] != '.'))
3073 strcpy(curfullcmd, ".exe");
3074 res = GetFileAttributes(fullcmd);
3075 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
3080 /* that failed, try the bare name */
3081 res = GetFileAttributes(fullcmd);
3082 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
3085 /* quit if no other path exists, or if cmd already has path */
3086 if (!pathstr || !*pathstr || has_slash)
3089 /* skip leading semis */
3090 while (*pathstr == ';')
3093 /* build a new prefix from scratch */
3094 curfullcmd = fullcmd;
3095 while (*pathstr && *pathstr != ';') {
3096 if (*pathstr == '"') { /* foo;"baz;etc";bar */
3097 pathstr++; /* skip initial '"' */
3098 while (*pathstr && *pathstr != '"') {
3099 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
3100 *curfullcmd++ = *pathstr;
3104 pathstr++; /* skip trailing '"' */
3107 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
3108 *curfullcmd++ = *pathstr;
3113 pathstr++; /* skip trailing semi */
3114 if (curfullcmd > fullcmd /* append a dir separator */
3115 && curfullcmd[-1] != '/' && curfullcmd[-1] != '\\')
3117 *curfullcmd++ = '\\';
3125 /* The following are just place holders.
3126 * Some hosts may provide and environment that the OS is
3127 * not tracking, therefore, these host must provide that
3128 * environment and the current directory to CreateProcess
3138 free_childenv(void* d)
3147 char szfilename[(MAX_PATH+1)*2];
3149 WCHAR wfilename[MAX_PATH+1];
3150 GetCurrentDirectoryW(MAX_PATH+1, wfilename);
3151 W2AHELPER(wfilename, szfilename, sizeof(szfilename));
3154 GetCurrentDirectoryA(MAX_PATH+1, szfilename);
3157 New(0, ptr, strlen(szfilename)+1, char);
3158 strcpy(ptr, szfilename);
3163 free_childdir(char* d)
3170 /* XXX this needs to be made more compatible with the spawnvp()
3171 * provided by the various RTLs. In particular, searching for
3172 * *.{com,bat,cmd} files (as done by the RTLs) is unimplemented.
3173 * This doesn't significantly affect perl itself, because we
3174 * always invoke things using PERL5SHELL if a direct attempt to
3175 * spawn the executable fails.
3177 * XXX splitting and rejoining the commandline between do_aspawn()
3178 * and win32_spawnvp() could also be avoided.
3182 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
3184 #ifdef USE_RTL_SPAWNVP
3185 return spawnvp(mode, cmdname, (char * const *)argv);
3192 STARTUPINFO StartupInfo;
3193 PROCESS_INFORMATION ProcessInformation;
3196 char *cmd = create_command_line(cmdname, strcmp(cmdname, argv[0]) == 0
3198 char *fullcmd = Nullch;
3200 env = PerlEnv_get_childenv();
3201 dir = PerlEnv_get_childdir();
3204 case P_NOWAIT: /* asynch + remember result */
3205 if (w32_num_children >= MAXIMUM_WAIT_OBJECTS) {
3211 case P_WAIT: /* synchronous execution */
3213 default: /* invalid mode */
3218 memset(&StartupInfo,0,sizeof(StartupInfo));
3219 StartupInfo.cb = sizeof(StartupInfo);
3220 memset(&tbl,0,sizeof(tbl));
3221 PerlEnv_get_child_IO(&tbl);
3222 StartupInfo.dwFlags = tbl.dwFlags;
3223 StartupInfo.dwX = tbl.dwX;
3224 StartupInfo.dwY = tbl.dwY;
3225 StartupInfo.dwXSize = tbl.dwXSize;
3226 StartupInfo.dwYSize = tbl.dwYSize;
3227 StartupInfo.dwXCountChars = tbl.dwXCountChars;
3228 StartupInfo.dwYCountChars = tbl.dwYCountChars;
3229 StartupInfo.dwFillAttribute = tbl.dwFillAttribute;
3230 StartupInfo.wShowWindow = tbl.wShowWindow;
3231 StartupInfo.hStdInput = tbl.childStdIn;
3232 StartupInfo.hStdOutput = tbl.childStdOut;
3233 StartupInfo.hStdError = tbl.childStdErr;
3234 if (StartupInfo.hStdInput != INVALID_HANDLE_VALUE &&
3235 StartupInfo.hStdOutput != INVALID_HANDLE_VALUE &&
3236 StartupInfo.hStdError != INVALID_HANDLE_VALUE)
3238 StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
3241 create |= CREATE_NEW_CONSOLE;
3245 if (!CreateProcess(cmdname, /* search PATH to find executable */
3246 cmd, /* executable, and its arguments */
3247 NULL, /* process attributes */
3248 NULL, /* thread attributes */
3249 TRUE, /* inherit handles */
3250 create, /* creation flags */
3251 (LPVOID)env, /* inherit environment */
3252 dir, /* inherit cwd */
3254 &ProcessInformation))
3256 /* initial NULL argument to CreateProcess() does a PATH
3257 * search, but it always first looks in the directory
3258 * where the current process was started, which behavior
3259 * is undesirable for backward compatibility. So we
3260 * jump through our own hoops by picking out the path
3261 * we really want it to use. */
3263 fullcmd = qualified_path(cmdname);
3274 if (mode == P_NOWAIT) {
3275 /* asynchronous spawn -- store handle, return PID */
3276 w32_child_handles[w32_num_children] = ProcessInformation.hProcess;
3277 w32_child_pids[w32_num_children] = ProcessInformation.dwProcessId;
3278 ret = (int)ProcessInformation.dwProcessId;
3283 WaitForSingleObject(ProcessInformation.hProcess, INFINITE);
3284 GetExitCodeProcess(ProcessInformation.hProcess, &status);
3286 CloseHandle(ProcessInformation.hProcess);
3289 CloseHandle(ProcessInformation.hThread);
3292 PerlEnv_free_childenv(env);
3293 PerlEnv_free_childdir(dir);
3301 win32_execv(const char *cmdname, const char *const *argv)
3305 /* if this is a pseudo-forked child, we just want to spawn
3306 * the new program, and return */
3308 return spawnv(P_WAIT, cmdname, (char *const *)argv);
3310 return execv(cmdname, (char *const *)argv);
3314 win32_execvp(const char *cmdname, const char *const *argv)
3318 /* if this is a pseudo-forked child, we just want to spawn
3319 * the new program, and return */
3321 return win32_spawnvp(P_WAIT, cmdname, (char *const *)argv);
3323 return execvp(cmdname, (char *const *)argv);
3327 win32_perror(const char *str)
3333 win32_setbuf(FILE *pf, char *buf)
3339 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
3341 return setvbuf(pf, buf, type, size);
3345 win32_flushall(void)
3351 win32_fcloseall(void)
3357 win32_fgets(char *s, int n, FILE *pf)
3359 return fgets(s, n, pf);
3369 win32_fgetc(FILE *pf)
3375 win32_putc(int c, FILE *pf)
3381 win32_puts(const char *s)
3393 win32_putchar(int c)
3400 #ifndef USE_PERL_SBRK
3402 static char *committed = NULL;
3403 static char *base = NULL;
3404 static char *reserved = NULL;
3405 static char *brk = NULL;
3406 static DWORD pagesize = 0;
3407 static DWORD allocsize = 0;
3415 GetSystemInfo(&info);
3416 /* Pretend page size is larger so we don't perpetually
3417 * call the OS to commit just one page ...
3419 pagesize = info.dwPageSize << 3;
3420 allocsize = info.dwAllocationGranularity;
3422 /* This scheme fails eventually if request for contiguous
3423 * block is denied so reserve big blocks - this is only
3424 * address space not memory ...
3426 if (brk+need >= reserved)
3428 DWORD size = 64*1024*1024;
3430 if (committed && reserved && committed < reserved)
3432 /* Commit last of previous chunk cannot span allocations */
3433 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
3435 committed = reserved;
3437 /* Reserve some (more) space
3438 * Note this is a little sneaky, 1st call passes NULL as reserved
3439 * so lets system choose where we start, subsequent calls pass
3440 * the old end address so ask for a contiguous block
3442 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
3445 reserved = addr+size;
3460 if (brk > committed)
3462 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
3463 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
3478 win32_malloc(size_t size)
3480 return malloc(size);
3484 win32_calloc(size_t numitems, size_t size)
3486 return calloc(numitems,size);
3490 win32_realloc(void *block, size_t size)
3492 return realloc(block,size);
3496 win32_free(void *block)
3503 win32_open_osfhandle(long handle, int flags)
3505 #ifdef USE_FIXED_OSFHANDLE
3507 return my_open_osfhandle(handle, flags);
3509 return _open_osfhandle(handle, flags);
3513 win32_get_osfhandle(int fd)
3515 return _get_osfhandle(fd);
3519 win32_dynaload(const char* filename)
3524 WCHAR wfilename[MAX_PATH+1];
3525 A2WHELPER(filename, wfilename, sizeof(wfilename));
3526 hModule = LoadLibraryExW(PerlDir_mapW(wfilename), NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
3529 hModule = LoadLibraryExA(PerlDir_mapA(filename), NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
3542 /* Make the host for current directory */
3543 char* ptr = PerlEnv_get_childdir();
3546 * then it worked, set PV valid,
3547 * else return 'undef'
3550 SV *sv = sv_newmortal();
3552 PerlEnv_free_childdir(ptr);
3567 Perl_croak(aTHX_ "usage: Win32::SetCurrentDirectory($cwd)");
3568 if (!PerlDir_chdir(SvPV_nolen(ST(0))))
3575 XS(w32_GetNextAvailDrive)
3579 char root[] = "_:\\";
3584 if (GetDriveType(root) == 1) {
3593 XS(w32_GetLastError)
3597 XSRETURN_IV(GetLastError());
3601 XS(w32_SetLastError)
3605 Perl_croak(aTHX_ "usage: Win32::SetLastError($error)");
3606 SetLastError(SvIV(ST(0)));
3614 char *name = w32_getlogin_buffer;
3615 DWORD size = sizeof(w32_getlogin_buffer);
3617 if (GetUserName(name,&size)) {
3618 /* size includes NULL */
3619 ST(0) = sv_2mortal(newSVpvn(name,size-1));
3629 char name[MAX_COMPUTERNAME_LENGTH+1];
3630 DWORD size = sizeof(name);
3632 if (GetComputerName(name,&size)) {
3633 /* size does NOT include NULL :-( */
3634 ST(0) = sv_2mortal(newSVpvn(name,size));
3645 HINSTANCE hNetApi32 = LoadLibrary("netapi32.dll");
3646 DWORD (__stdcall *pfnNetApiBufferFree)(LPVOID Buffer);
3647 DWORD (__stdcall *pfnNetWkstaGetInfo)(LPWSTR servername, DWORD level,
3651 pfnNetApiBufferFree = (DWORD (__stdcall *)(void *))
3652 GetProcAddress(hNetApi32, "NetApiBufferFree");
3653 pfnNetWkstaGetInfo = (DWORD (__stdcall *)(LPWSTR, DWORD, void *))
3654 GetProcAddress(hNetApi32, "NetWkstaGetInfo");
3657 if (hNetApi32 && pfnNetWkstaGetInfo && pfnNetApiBufferFree) {
3658 /* this way is more reliable, in case user has a local account. */
3660 DWORD dnamelen = sizeof(dname);
3662 DWORD wki100_platform_id;
3663 LPWSTR wki100_computername;
3664 LPWSTR wki100_langroup;
3665 DWORD wki100_ver_major;
3666 DWORD wki100_ver_minor;
3668 /* NERR_Success *is* 0*/
3669 if (0 == pfnNetWkstaGetInfo(NULL, 100, &pwi)) {
3670 if (pwi->wki100_langroup && *(pwi->wki100_langroup)) {
3671 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_langroup,
3672 -1, (LPSTR)dname, dnamelen, NULL, NULL);
3675 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_computername,
3676 -1, (LPSTR)dname, dnamelen, NULL, NULL);
3678 pfnNetApiBufferFree(pwi);
3679 FreeLibrary(hNetApi32);
3682 FreeLibrary(hNetApi32);
3685 /* Win95 doesn't have NetWksta*(), so do it the old way */
3687 DWORD size = sizeof(name);
3689 FreeLibrary(hNetApi32);
3690 if (GetUserName(name,&size)) {
3691 char sid[ONE_K_BUFSIZE];
3692 DWORD sidlen = sizeof(sid);
3694 DWORD dnamelen = sizeof(dname);
3696 if (LookupAccountName(NULL, name, (PSID)&sid, &sidlen,
3697 dname, &dnamelen, &snu)) {
3698 XSRETURN_PV(dname); /* all that for this */
3710 DWORD flags, filecomplen;
3711 if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
3712 &flags, fsname, sizeof(fsname))) {
3713 if (GIMME_V == G_ARRAY) {
3714 XPUSHs(sv_2mortal(newSVpvn(fsname,strlen(fsname))));
3715 XPUSHs(sv_2mortal(newSViv(flags)));
3716 XPUSHs(sv_2mortal(newSViv(filecomplen)));
3721 XSRETURN_PV(fsname);
3727 XS(w32_GetOSVersion)
3730 OSVERSIONINFOA osver;
3733 OSVERSIONINFOW osverw;
3734 char szCSDVersion[sizeof(osverw.szCSDVersion)];
3735 osverw.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
3736 if (!GetVersionExW(&osverw)) {
3739 W2AHELPER(osverw.szCSDVersion, szCSDVersion, sizeof(szCSDVersion));
3740 XPUSHs(newSVpvn(szCSDVersion, strlen(szCSDVersion)));
3741 osver.dwMajorVersion = osverw.dwMajorVersion;
3742 osver.dwMinorVersion = osverw.dwMinorVersion;
3743 osver.dwBuildNumber = osverw.dwBuildNumber;
3744 osver.dwPlatformId = osverw.dwPlatformId;
3747 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOA);
3748 if (!GetVersionExA(&osver)) {
3751 XPUSHs(newSVpvn(osver.szCSDVersion, strlen(osver.szCSDVersion)));
3753 XPUSHs(newSViv(osver.dwMajorVersion));
3754 XPUSHs(newSViv(osver.dwMinorVersion));
3755 XPUSHs(newSViv(osver.dwBuildNumber));
3756 XPUSHs(newSViv(osver.dwPlatformId));
3765 XSRETURN_IV(IsWinNT());
3773 XSRETURN_IV(IsWin95());
3777 XS(w32_FormatMessage)
3781 char msgbuf[ONE_K_BUFSIZE];
3784 Perl_croak(aTHX_ "usage: Win32::FormatMessage($errno)");
3787 WCHAR wmsgbuf[ONE_K_BUFSIZE];
3788 if (FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM,
3789 &source, SvIV(ST(0)), 0,
3790 wmsgbuf, ONE_K_BUFSIZE-1, NULL))
3792 W2AHELPER(wmsgbuf, msgbuf, sizeof(msgbuf));
3793 XSRETURN_PV(msgbuf);
3797 if (FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM,
3798 &source, SvIV(ST(0)), 0,
3799 msgbuf, sizeof(msgbuf)-1, NULL))
3800 XSRETURN_PV(msgbuf);
3811 PROCESS_INFORMATION stProcInfo;
3812 STARTUPINFO stStartInfo;
3813 BOOL bSuccess = FALSE;
3816 Perl_croak(aTHX_ "usage: Win32::Spawn($cmdName, $args, $PID)");
3818 cmd = SvPV_nolen(ST(0));
3819 args = SvPV_nolen(ST(1));
3821 memset(&stStartInfo, 0, sizeof(stStartInfo)); /* Clear the block */
3822 stStartInfo.cb = sizeof(stStartInfo); /* Set the structure size */
3823 stStartInfo.dwFlags = STARTF_USESHOWWINDOW; /* Enable wShowWindow control */
3824 stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE; /* Start min (normal) */
3827 cmd, /* Image path */
3828 args, /* Arguments for command line */
3829 NULL, /* Default process security */
3830 NULL, /* Default thread security */
3831 FALSE, /* Must be TRUE to use std handles */
3832 NORMAL_PRIORITY_CLASS, /* No special scheduling */
3833 NULL, /* Inherit our environment block */
3834 NULL, /* Inherit our currrent directory */
3835 &stStartInfo, /* -> Startup info */
3836 &stProcInfo)) /* <- Process info (if OK) */
3838 CloseHandle(stProcInfo.hThread);/* library source code does this. */
3839 sv_setiv(ST(2), stProcInfo.dwProcessId);
3842 XSRETURN_IV(bSuccess);
3846 XS(w32_GetTickCount)
3849 DWORD msec = GetTickCount();
3857 XS(w32_GetShortPathName)
3864 Perl_croak(aTHX_ "usage: Win32::GetShortPathName($longPathName)");
3866 shortpath = sv_mortalcopy(ST(0));
3867 SvUPGRADE(shortpath, SVt_PV);
3868 /* src == target is allowed */
3870 len = GetShortPathName(SvPVX(shortpath),
3873 } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
3875 SvCUR_set(shortpath,len);
3883 XS(w32_GetFullPathName)
3892 Perl_croak(aTHX_ "usage: Win32::GetFullPathName($filename)");
3895 fullpath = sv_mortalcopy(filename);
3896 SvUPGRADE(fullpath, SVt_PV);
3898 len = GetFullPathName(SvPVX(filename),
3902 } while (len >= SvLEN(fullpath) && sv_grow(fullpath,len+1));
3904 if (GIMME_V == G_ARRAY) {
3906 XST_mPV(1,filepart);
3907 len = filepart - SvPVX(fullpath);
3910 SvCUR_set(fullpath,len);
3918 XS(w32_GetLongPathName)
3922 char tmpbuf[MAX_PATH+1];
3927 Perl_croak(aTHX_ "usage: Win32::GetLongPathName($pathname)");
3930 pathstr = SvPV(path,len);
3931 strcpy(tmpbuf, pathstr);
3932 pathstr = win32_longpath(tmpbuf);
3934 ST(0) = sv_2mortal(newSVpvn(pathstr, strlen(pathstr)));
3945 Perl_croak(aTHX_ "usage: Win32::Sleep($milliseconds)");
3956 Perl_croak(aTHX_ "usage: Win32::CopyFile($from, $to, $overwrite)");
3958 WCHAR wSourceFile[MAX_PATH+1];
3959 WCHAR wDestFile[MAX_PATH+1];
3960 A2WHELPER(SvPV_nolen(ST(0)), wSourceFile, sizeof(wSourceFile));
3961 wcscpy(wSourceFile, PerlDir_mapW(wSourceFile));
3962 A2WHELPER(SvPV_nolen(ST(1)), wDestFile, sizeof(wDestFile));
3963 bResult = CopyFileW(wSourceFile, PerlDir_mapW(wDestFile), !SvTRUE(ST(2)));
3966 char szSourceFile[MAX_PATH+1];
3967 strcpy(szSourceFile, PerlDir_mapA(SvPV_nolen(ST(0))));
3968 bResult = CopyFileA(szSourceFile, PerlDir_mapA(SvPV_nolen(ST(1))), !SvTRUE(ST(2)));
3977 Perl_init_os_extras(void)
3980 char *file = __FILE__;
3983 /* these names are Activeware compatible */
3984 newXS("Win32::GetCwd", w32_GetCwd, file);
3985 newXS("Win32::SetCwd", w32_SetCwd, file);
3986 newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
3987 newXS("Win32::GetLastError", w32_GetLastError, file);
3988 newXS("Win32::SetLastError", w32_SetLastError, file);
3989 newXS("Win32::LoginName", w32_LoginName, file);
3990 newXS("Win32::NodeName", w32_NodeName, file);
3991 newXS("Win32::DomainName", w32_DomainName, file);
3992 newXS("Win32::FsType", w32_FsType, file);
3993 newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
3994 newXS("Win32::IsWinNT", w32_IsWinNT, file);
3995 newXS("Win32::IsWin95", w32_IsWin95, file);
3996 newXS("Win32::FormatMessage", w32_FormatMessage, file);
3997 newXS("Win32::Spawn", w32_Spawn, file);
3998 newXS("Win32::GetTickCount", w32_GetTickCount, file);
3999 newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
4000 newXS("Win32::GetFullPathName", w32_GetFullPathName, file);
4001 newXS("Win32::GetLongPathName", w32_GetLongPathName, file);
4002 newXS("Win32::CopyFile", w32_CopyFile, file);
4003 newXS("Win32::Sleep", w32_Sleep, file);
4005 /* XXX Bloat Alert! The following Activeware preloads really
4006 * ought to be part of Win32::Sys::*, so they're not included
4009 /* LookupAccountName
4011 * InitiateSystemShutdown
4012 * AbortSystemShutdown
4013 * ExpandEnvrironmentStrings
4018 Perl_win32_init(int *argcp, char ***argvp)
4020 /* Disable floating point errors, Perl will trap the ones we
4021 * care about. VC++ RTL defaults to switching these off
4022 * already, but the Borland RTL doesn't. Since we don't
4023 * want to be at the vendor's whim on the default, we set
4024 * it explicitly here.
4026 #if !defined(_ALPHA_) && !defined(__GNUC__)
4027 _control87(MCW_EM, MCW_EM);
4033 win32_get_child_IO(child_IO_table* ptbl)
4035 ptbl->childStdIn = GetStdHandle(STD_INPUT_HANDLE);
4036 ptbl->childStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
4037 ptbl->childStdErr = GetStdHandle(STD_ERROR_HANDLE);
4040 #ifdef HAVE_INTERP_INTERN
4043 # undef Perl_sys_intern_init
4044 # define Perl_sys_intern_init CPerlObj::Perl_sys_intern_init
4045 # undef Perl_sys_intern_dup
4046 # define Perl_sys_intern_dup CPerlObj::Perl_sys_intern_dup
4047 # undef Perl_sys_intern_clear
4048 # define Perl_sys_intern_clear CPerlObj::Perl_sys_intern_clear
4053 Perl_sys_intern_init(pTHX)
4055 w32_perlshell_tokens = Nullch;
4056 w32_perlshell_vec = (char**)NULL;
4057 w32_perlshell_items = 0;
4058 w32_fdpid = newAV();
4059 New(1313, w32_children, 1, child_tab);
4060 w32_num_children = 0;
4061 # ifdef USE_ITHREADS
4063 New(1313, w32_pseudo_children, 1, child_tab);
4064 w32_num_pseudo_children = 0;
4066 w32_init_socktype = 0;
4070 Perl_sys_intern_clear(pTHX)
4072 Safefree(w32_perlshell_tokens);
4073 Safefree(w32_perlshell_vec);
4074 /* NOTE: w32_fdpid is freed by sv_clean_all() */
4075 Safefree(w32_children);
4076 # ifdef USE_ITHREADS
4077 Safefree(w32_pseudo_children);
4081 # ifdef USE_ITHREADS
4084 Perl_sys_intern_dup(pTHX_ struct interp_intern *src, struct interp_intern *dst)
4086 dst->perlshell_tokens = Nullch;
4087 dst->perlshell_vec = (char**)NULL;
4088 dst->perlshell_items = 0;
4089 dst->fdpid = newAV();
4090 Newz(1313, dst->children, 1, child_tab);
4092 Newz(1313, dst->pseudo_children, 1, child_tab);
4093 dst->thr_intern.Winit_socktype = src->thr_intern.Winit_socktype;
4095 # endif /* USE_ITHREADS */
4096 #endif /* HAVE_INTERP_INTERN */
4104 win32_free_argvw(pTHXo_ void *ptr)
4106 char** argv = (char**)ptr;
4114 win32_argv2utf8(int argc, char** argv)
4119 LPWSTR* lpwStr = CommandLineToArgvW(GetCommandLineW(), &wargc);
4120 if (lpwStr && argc) {
4122 length = WideCharToMultiByte(CP_UTF8, 0, lpwStr[--wargc], -1, NULL, 0, NULL, NULL);
4123 Newz(0, psz, length, char);
4124 WideCharToMultiByte(CP_UTF8, 0, lpwStr[wargc], -1, psz, length, NULL, NULL);
4127 call_atexit(win32_free_argvw, argv);
4129 GlobalFree((HGLOBAL)lpwStr);