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
21 /* #include "config.h" */
23 #define PERLIO_NOT_STDIO 0
24 #if !defined(PERLIO_IS_STDIO) && !defined(USE_SFIO)
33 #define PERL_NO_GET_CONTEXT
39 /* assert.h conflicts with #define of assert in perl.h */
44 #include <stdlib.h> /* get a real declaration of sys_nerr */
47 #if defined(_MSC_VER) || defined(__MINGW32__)
48 #include <sys/utime.h>
54 /* Mingw32 defaults to globing command line
55 * So we turn it off like this:
60 #if defined(__MINGW32__)
61 /* Mingw32 is missing some prototypes */
62 FILE * _wfopen(LPCWSTR wszFileName, LPCWSTR wszMode);
63 FILE * _wfdopen(int nFd, LPCWSTR wszMode);
64 FILE * _freopen(LPCWSTR wszFileName, LPCWSTR wszMode, FILE * pOldStream);
69 #if defined(__BORLANDC__)
71 # define _utimbuf utimbuf
76 #define EXECF_SPAWN_NOWAIT 3
78 #if defined(PERL_IMPLICIT_SYS)
79 # undef win32_get_privlib
80 # define win32_get_privlib g_win32_get_privlib
81 # undef win32_get_sitelib
82 # define win32_get_sitelib g_win32_get_sitelib
83 # undef win32_get_vendorlib
84 # define win32_get_vendorlib g_win32_get_vendorlib
86 # define do_spawn g_do_spawn
88 # define getlogin g_getlogin
91 #if defined(PERL_OBJECT)
93 # define do_aspawn g_do_aspawn
95 # define Perl_do_exec g_do_exec
98 static void get_shell(void);
99 static long tokenize(const char *str, char **dest, char ***destv);
100 int do_spawn2(char *cmd, int exectype);
101 static BOOL has_shell_metachars(char *ptr);
102 static long filetime_to_clock(PFILETIME ft);
103 static BOOL filetime_from_time(PFILETIME ft, time_t t);
104 static char * get_emd_part(SV **leading, char *trailing, ...);
105 static void remove_dead_process(long deceased);
106 static long find_pid(int pid);
107 static char * qualified_path(const char *cmd);
108 static char * win32_get_xlib(const char *pl, const char *xlib,
109 const char *libname);
112 static void remove_dead_pseudo_process(long child);
113 static long find_pseudo_pid(int pid);
117 HANDLE w32_perldll_handle = INVALID_HANDLE_VALUE;
118 char w32_module_name[MAX_PATH+1];
121 static DWORD w32_platform = (DWORD)-1;
123 #define ONE_K_BUFSIZE 1024
128 return (win32_os_id() == VER_PLATFORM_WIN32_WINDOWS);
134 return (win32_os_id() == VER_PLATFORM_WIN32_NT);
138 set_w32_module_name(void)
141 GetModuleFileName((HMODULE)((w32_perldll_handle == INVALID_HANDLE_VALUE)
142 ? GetModuleHandle(NULL)
143 : w32_perldll_handle),
144 w32_module_name, sizeof(w32_module_name));
146 /* try to get full path to binary (which may be mangled when perl is
147 * run from a 16-bit app) */
148 /*PerlIO_printf(Perl_debug_log, "Before %s\n", w32_module_name);*/
149 (void)win32_longpath(w32_module_name);
150 /*PerlIO_printf(Perl_debug_log, "After %s\n", w32_module_name);*/
152 /* normalize to forward slashes */
153 ptr = w32_module_name;
161 /* *svp (if non-NULL) is expected to be POK (valid allocated SvPVX(*svp)) */
163 get_regstr_from(HKEY hkey, const char *valuename, SV **svp)
165 /* Retrieve a REG_SZ or REG_EXPAND_SZ from the registry */
168 const char *subkey = "Software\\Perl";
172 retval = RegOpenKeyEx(hkey, subkey, 0, KEY_READ, &handle);
173 if (retval == ERROR_SUCCESS) {
175 retval = RegQueryValueEx(handle, valuename, 0, &type, NULL, &datalen);
176 if (retval == ERROR_SUCCESS
177 && (type == REG_SZ || type == REG_EXPAND_SZ))
181 *svp = sv_2mortal(newSVpvn("",0));
182 SvGROW(*svp, datalen);
183 retval = RegQueryValueEx(handle, valuename, 0, NULL,
184 (PBYTE)SvPVX(*svp), &datalen);
185 if (retval == ERROR_SUCCESS) {
187 SvCUR_set(*svp,datalen-1);
195 /* *svp (if non-NULL) is expected to be POK (valid allocated SvPVX(*svp)) */
197 get_regstr(const char *valuename, SV **svp)
199 char *str = get_regstr_from(HKEY_CURRENT_USER, valuename, svp);
201 str = get_regstr_from(HKEY_LOCAL_MACHINE, valuename, svp);
205 /* *prev_pathp (if non-NULL) is expected to be POK (valid allocated SvPVX(sv)) */
207 get_emd_part(SV **prev_pathp, char *trailing_path, ...)
211 char mod_name[MAX_PATH+1];
215 int oldsize, newsize;
218 va_start(ap, trailing_path);
219 strip = va_arg(ap, char *);
221 sprintf(base, "%d.%d", (int)PERL_REVISION, (int)PERL_VERSION);
222 baselen = strlen(base);
224 if (!*w32_module_name) {
225 set_w32_module_name();
227 strcpy(mod_name, w32_module_name);
228 ptr = strrchr(mod_name, '/');
229 while (ptr && strip) {
230 /* look for directories to skip back */
233 ptr = strrchr(mod_name, '/');
234 /* avoid stripping component if there is no slash,
235 * or it doesn't match ... */
236 if (!ptr || stricmp(ptr+1, strip) != 0) {
237 /* ... but not if component matches m|5\.$patchlevel.*| */
238 if (!ptr || !(*strip == '5' && *(ptr+1) == '5'
239 && strncmp(strip, base, baselen) == 0
240 && strncmp(ptr+1, base, baselen) == 0))
246 strip = va_arg(ap, char *);
254 strcpy(++ptr, trailing_path);
256 /* only add directory if it exists */
257 if (GetFileAttributes(mod_name) != (DWORD) -1) {
258 /* directory exists */
261 *prev_pathp = sv_2mortal(newSVpvn("",0));
262 sv_catpvn(*prev_pathp, ";", 1);
263 sv_catpv(*prev_pathp, mod_name);
264 return SvPVX(*prev_pathp);
271 win32_get_privlib(const char *pl)
274 char *stdlib = "lib";
275 char buffer[MAX_PATH+1];
278 /* $stdlib = $HKCU{"lib-$]"} || $HKLM{"lib-$]"} || $HKCU{"lib"} || $HKLM{"lib"} || ""; */
279 sprintf(buffer, "%s-%s", stdlib, pl);
280 if (!get_regstr(buffer, &sv))
281 (void)get_regstr(stdlib, &sv);
283 /* $stdlib .= ";$EMD/../../lib" */
284 return get_emd_part(&sv, stdlib, ARCHNAME, "bin", Nullch);
288 win32_get_xlib(const char *pl, const char *xlib, const char *libname)
292 char pathstr[MAX_PATH+1];
298 /* $HKCU{"$xlib-$]"} || $HKLM{"$xlib-$]"} . ---; */
299 sprintf(regstr, "%s-%s", xlib, pl);
300 (void)get_regstr(regstr, &sv1);
303 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/$libname/$]/lib"; */
304 sprintf(pathstr, "%s/%s/lib", libname, pl);
305 (void)get_emd_part(&sv1, pathstr, ARCHNAME, "bin", pl, Nullch);
307 /* $HKCU{$xlib} || $HKLM{$xlib} . ---; */
308 (void)get_regstr(xlib, &sv2);
311 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/$libname/lib"; */
312 sprintf(pathstr, "%s/lib", libname);
313 (void)get_emd_part(&sv2, pathstr, ARCHNAME, "bin", pl, Nullch);
322 sv_catpvn(sv1, ";", 1);
329 win32_get_sitelib(const char *pl)
331 return win32_get_xlib(pl, "sitelib", "site");
334 #ifndef PERL_VENDORLIB_NAME
335 # define PERL_VENDORLIB_NAME "vendor"
339 win32_get_vendorlib(const char *pl)
341 return win32_get_xlib(pl, "vendorlib", PERL_VENDORLIB_NAME);
345 has_shell_metachars(char *ptr)
351 * Scan string looking for redirection (< or >) or pipe
352 * characters (|) that are not in a quoted string.
353 * Shell variable interpolation (%VAR%) can also happen inside strings.
385 #if !defined(PERL_IMPLICIT_SYS)
386 /* since the current process environment is being updated in util.c
387 * the library functions will get the correct environment
390 Perl_my_popen(pTHX_ char *cmd, char *mode)
393 #define fixcmd(x) { \
394 char *pspace = strchr((x),' '); \
397 while (p < pspace) { \
408 PERL_FLUSHALL_FOR_CHILD;
409 return win32_popen(cmd, mode);
413 Perl_my_pclose(pTHX_ PerlIO *fp)
415 return win32_pclose(fp);
419 DllExport unsigned long
422 static OSVERSIONINFO osver;
424 if (osver.dwPlatformId != w32_platform) {
425 memset(&osver, 0, sizeof(OSVERSIONINFO));
426 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
427 GetVersionEx(&osver);
428 w32_platform = osver.dwPlatformId;
430 return (unsigned long)w32_platform;
439 return -((int)w32_pseudo_id);
444 /* Tokenize a string. Words are null-separated, and the list
445 * ends with a doubled null. Any character (except null and
446 * including backslash) may be escaped by preceding it with a
447 * backslash (the backslash will be stripped).
448 * Returns number of words in result buffer.
451 tokenize(const char *str, char **dest, char ***destv)
453 char *retstart = Nullch;
454 char **retvstart = 0;
458 int slen = strlen(str);
460 register char **retv;
461 New(1307, ret, slen+2, char);
462 New(1308, retv, (slen+3)/2, char*);
470 if (*ret == '\\' && *str)
472 else if (*ret == ' ') {
488 retvstart[items] = Nullch;
501 if (!w32_perlshell_tokens) {
502 /* we don't use COMSPEC here for two reasons:
503 * 1. the same reason perl on UNIX doesn't use SHELL--rampant and
504 * uncontrolled unportability of the ensuing scripts.
505 * 2. PERL5SHELL could be set to a shell that may not be fit for
506 * interactive use (which is what most programs look in COMSPEC
509 const char* defaultshell = (IsWinNT()
510 ? "cmd.exe /x/c" : "command.com /c");
511 const char *usershell = getenv("PERL5SHELL");
512 w32_perlshell_items = tokenize(usershell ? usershell : defaultshell,
513 &w32_perlshell_tokens,
519 do_aspawn(void *vreally, void **vmark, void **vsp)
522 SV *really = (SV*)vreally;
523 SV **mark = (SV**)vmark;
535 New(1306, argv, (sp - mark) + w32_perlshell_items + 2, char*);
537 if (SvNIOKp(*(mark+1)) && !SvPOKp(*(mark+1))) {
542 while (++mark <= sp) {
543 if (*mark && (str = SvPV_nolen(*mark)))
550 status = win32_spawnvp(flag,
551 (const char*)(really ? SvPV_nolen(really) : argv[0]),
552 (const char* const*)argv);
554 if (status < 0 && (errno == ENOEXEC || errno == ENOENT)) {
555 /* possible shell-builtin, invoke with shell */
557 sh_items = w32_perlshell_items;
559 argv[index+sh_items] = argv[index];
560 while (--sh_items >= 0)
561 argv[sh_items] = w32_perlshell_vec[sh_items];
563 status = win32_spawnvp(flag,
564 (const char*)(really ? SvPV_nolen(really) : argv[0]),
565 (const char* const*)argv);
568 if (flag != P_NOWAIT) {
571 if (ckWARN(WARN_EXEC))
572 Perl_warner(aTHX_ WARN_EXEC, "Can't spawn \"%s\": %s", argv[0], strerror(errno));
577 PL_statusvalue = status;
584 do_spawn2(char *cmd, int exectype)
591 BOOL needToTry = TRUE;
594 /* Save an extra exec if possible. See if there are shell
595 * metacharacters in it */
596 if (!has_shell_metachars(cmd)) {
597 New(1301,argv, strlen(cmd) / 2 + 2, char*);
598 New(1302,cmd2, strlen(cmd) + 1, char);
601 for (s = cmd2; *s;) {
602 while (*s && isSPACE(*s))
606 while (*s && !isSPACE(*s))
615 status = win32_spawnvp(P_WAIT, argv[0],
616 (const char* const*)argv);
618 case EXECF_SPAWN_NOWAIT:
619 status = win32_spawnvp(P_NOWAIT, argv[0],
620 (const char* const*)argv);
623 status = win32_execvp(argv[0], (const char* const*)argv);
626 if (status != -1 || errno == 0)
636 New(1306, argv, w32_perlshell_items + 2, char*);
637 while (++i < w32_perlshell_items)
638 argv[i] = w32_perlshell_vec[i];
643 status = win32_spawnvp(P_WAIT, argv[0],
644 (const char* const*)argv);
646 case EXECF_SPAWN_NOWAIT:
647 status = win32_spawnvp(P_NOWAIT, argv[0],
648 (const char* const*)argv);
651 status = win32_execvp(argv[0], (const char* const*)argv);
657 if (exectype != EXECF_SPAWN_NOWAIT) {
660 if (ckWARN(WARN_EXEC))
661 Perl_warner(aTHX_ WARN_EXEC, "Can't %s \"%s\": %s",
662 (exectype == EXECF_EXEC ? "exec" : "spawn"),
663 cmd, strerror(errno));
668 PL_statusvalue = status;
676 return do_spawn2(cmd, EXECF_SPAWN);
680 do_spawn_nowait(char *cmd)
682 return do_spawn2(cmd, EXECF_SPAWN_NOWAIT);
686 Perl_do_exec(pTHX_ char *cmd)
688 do_spawn2(cmd, EXECF_EXEC);
692 /* The idea here is to read all the directory names into a string table
693 * (separated by nulls) and when one of the other dir functions is called
694 * return the pointer to the current file name.
697 win32_opendir(char *filename)
703 char scanname[MAX_PATH+3];
705 WIN32_FIND_DATAA aFindData;
706 WIN32_FIND_DATAW wFindData;
708 char buffer[MAX_PATH*2];
709 WCHAR wbuffer[MAX_PATH+1];
712 len = strlen(filename);
716 /* check to see if filename is a directory */
717 if (win32_stat(filename, &sbuf) < 0 || !S_ISDIR(sbuf.st_mode))
720 /* Get us a DIR structure */
721 Newz(1303, dirp, 1, DIR);
723 /* Create the search pattern */
724 strcpy(scanname, filename);
726 /* bare drive name means look in cwd for drive */
727 if (len == 2 && isALPHA(scanname[0]) && scanname[1] == ':') {
728 scanname[len++] = '.';
729 scanname[len++] = '/';
731 else if (scanname[len-1] != '/' && scanname[len-1] != '\\') {
732 scanname[len++] = '/';
734 scanname[len++] = '*';
735 scanname[len] = '\0';
737 /* do the FindFirstFile call */
739 A2WHELPER(scanname, wbuffer, sizeof(wbuffer));
740 fh = FindFirstFileW(PerlDir_mapW(wbuffer), &wFindData);
743 fh = FindFirstFileA(PerlDir_mapA(scanname), &aFindData);
746 if (fh == INVALID_HANDLE_VALUE) {
747 DWORD err = GetLastError();
748 /* FindFirstFile() fails on empty drives! */
750 case ERROR_FILE_NOT_FOUND:
752 case ERROR_NO_MORE_FILES:
753 case ERROR_PATH_NOT_FOUND:
756 case ERROR_NOT_ENOUGH_MEMORY:
767 /* now allocate the first part of the string table for
768 * the filenames that we find.
771 W2AHELPER(wFindData.cFileName, buffer, sizeof(buffer));
775 ptr = aFindData.cFileName;
782 New(1304, dirp->start, dirp->size, char);
783 strcpy(dirp->start, ptr);
785 dirp->end = dirp->curr = dirp->start;
791 /* Readdir just returns the current string pointer and bumps the
792 * string pointer to the nDllExport entry.
794 DllExport struct direct *
795 win32_readdir(DIR *dirp)
800 /* first set up the structure to return */
801 len = strlen(dirp->curr);
802 strcpy(dirp->dirstr.d_name, dirp->curr);
803 dirp->dirstr.d_namlen = len;
806 dirp->dirstr.d_ino = dirp->curr - dirp->start;
808 /* Now set up for the next call to readdir */
809 dirp->curr += len + 1;
810 if (dirp->curr >= dirp->end) {
814 WIN32_FIND_DATAW wFindData;
815 WIN32_FIND_DATAA aFindData;
816 char buffer[MAX_PATH*2];
818 /* finding the next file that matches the wildcard
819 * (which should be all of them in this directory!).
822 res = FindNextFileW(dirp->handle, &wFindData);
824 W2AHELPER(wFindData.cFileName, buffer, sizeof(buffer));
829 res = FindNextFileA(dirp->handle, &aFindData);
831 ptr = aFindData.cFileName;
834 long endpos = dirp->end - dirp->start;
835 long newsize = endpos + strlen(ptr) + 1;
836 /* bump the string table size by enough for the
837 * new name and it's null terminator */
838 while (newsize > dirp->size) {
839 long curpos = dirp->curr - dirp->start;
841 Renew(dirp->start, dirp->size, char);
842 dirp->curr = dirp->start + curpos;
844 strcpy(dirp->start + endpos, ptr);
845 dirp->end = dirp->start + newsize;
851 return &(dirp->dirstr);
857 /* Telldir returns the current string pointer position */
859 win32_telldir(DIR *dirp)
861 return (dirp->curr - dirp->start);
865 /* Seekdir moves the string pointer to a previously saved position
866 * (returned by telldir).
869 win32_seekdir(DIR *dirp, long loc)
871 dirp->curr = dirp->start + loc;
874 /* Rewinddir resets the string pointer to the start */
876 win32_rewinddir(DIR *dirp)
878 dirp->curr = dirp->start;
881 /* free the memory allocated by opendir */
883 win32_closedir(DIR *dirp)
886 if (dirp->handle != INVALID_HANDLE_VALUE)
887 FindClose(dirp->handle);
888 Safefree(dirp->start);
901 * Just pretend that everyone is a superuser. NT will let us know if
902 * we don\'t really have permission to do something.
905 #define ROOT_UID ((uid_t)0)
906 #define ROOT_GID ((gid_t)0)
935 return (auid == ROOT_UID ? 0 : -1);
941 return (agid == ROOT_GID ? 0 : -1);
948 char *buf = w32_getlogin_buffer;
949 DWORD size = sizeof(w32_getlogin_buffer);
950 if (GetUserName(buf,&size))
956 chown(const char *path, uid_t owner, gid_t group)
966 long child = w32_num_children;
967 while (--child >= 0) {
968 if (w32_child_pids[child] == pid)
975 remove_dead_process(long child)
979 CloseHandle(w32_child_handles[child]);
980 Move(&w32_child_handles[child+1], &w32_child_handles[child],
981 (w32_num_children-child-1), HANDLE);
982 Move(&w32_child_pids[child+1], &w32_child_pids[child],
983 (w32_num_children-child-1), DWORD);
990 find_pseudo_pid(int pid)
993 long child = w32_num_pseudo_children;
994 while (--child >= 0) {
995 if (w32_pseudo_child_pids[child] == pid)
1002 remove_dead_pseudo_process(long child)
1006 CloseHandle(w32_pseudo_child_handles[child]);
1007 Move(&w32_pseudo_child_handles[child+1], &w32_pseudo_child_handles[child],
1008 (w32_num_pseudo_children-child-1), HANDLE);
1009 Move(&w32_pseudo_child_pids[child+1], &w32_pseudo_child_pids[child],
1010 (w32_num_pseudo_children-child-1), DWORD);
1011 w32_num_pseudo_children--;
1017 win32_kill(int pid, int sig)
1023 /* it is a pseudo-forked child */
1024 long child = find_pseudo_pid(-pid);
1028 hProcess = w32_pseudo_child_handles[child];
1029 if (TerminateThread(hProcess, sig)) {
1030 remove_dead_pseudo_process(child);
1038 long child = find_pid(pid);
1042 hProcess = w32_child_handles[child];
1043 if (TerminateProcess(hProcess, sig)) {
1044 remove_dead_process(child);
1049 hProcess = OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid);
1053 if (TerminateProcess(hProcess, sig)) {
1054 CloseHandle(hProcess);
1068 DllExport unsigned int
1069 win32_sleep(unsigned int t)
1076 win32_stat(const char *path, struct stat *sbuf)
1079 char buffer[MAX_PATH+1];
1080 int l = strlen(path);
1082 WCHAR wbuffer[MAX_PATH+1];
1088 switch(path[l - 1]) {
1089 /* FindFirstFile() and stat() are buggy with a trailing
1090 * backslash, so change it to a forward slash :-( */
1092 strncpy(buffer, path, l-1);
1093 buffer[l - 1] = '/';
1097 /* FindFirstFile() is buggy with "x:", so add a dot :-( */
1099 if (l == 2 && isALPHA(path[0])) {
1100 buffer[0] = path[0];
1111 /* We *must* open & close the file once; otherwise file attribute changes */
1112 /* might not yet have propagated to "other" hard links of the same file. */
1113 /* This also gives us an opportunity to determine the number of links. */
1115 A2WHELPER(path, wbuffer, sizeof(wbuffer));
1116 pwbuffer = PerlDir_mapW(wbuffer);
1117 handle = CreateFileW(pwbuffer, 0, 0, NULL, OPEN_EXISTING, 0, NULL);
1120 path = PerlDir_mapA(path);
1122 handle = CreateFileA(path, 0, 0, NULL, OPEN_EXISTING, 0, NULL);
1124 if (handle != INVALID_HANDLE_VALUE) {
1125 BY_HANDLE_FILE_INFORMATION bhi;
1126 if (GetFileInformationByHandle(handle, &bhi))
1127 nlink = bhi.nNumberOfLinks;
1128 CloseHandle(handle);
1131 /* pwbuffer or path will be mapped correctly above */
1133 res = _wstat(pwbuffer, (struct _stat *)sbuf);
1136 res = stat(path, sbuf);
1138 sbuf->st_nlink = nlink;
1141 /* CRT is buggy on sharenames, so make sure it really isn't.
1142 * XXX using GetFileAttributesEx() will enable us to set
1143 * sbuf->st_*time (but note that's not available on the
1144 * Windows of 1995) */
1147 r = GetFileAttributesW(pwbuffer);
1150 r = GetFileAttributesA(path);
1152 if (r != 0xffffffff && (r & FILE_ATTRIBUTE_DIRECTORY)) {
1153 /* sbuf may still contain old garbage since stat() failed */
1154 Zero(sbuf, 1, struct stat);
1155 sbuf->st_mode = S_IFDIR | S_IREAD;
1157 if (!(r & FILE_ATTRIBUTE_READONLY))
1158 sbuf->st_mode |= S_IWRITE | S_IEXEC;
1163 if (l == 3 && isALPHA(path[0]) && path[1] == ':'
1164 && (path[2] == '\\' || path[2] == '/'))
1166 /* The drive can be inaccessible, some _stat()s are buggy */
1168 ? !GetVolumeInformationW(pwbuffer,NULL,0,NULL,NULL,NULL,NULL,0)
1169 : !GetVolumeInformationA(path,NULL,0,NULL,NULL,NULL,NULL,0)) {
1175 if (S_ISDIR(sbuf->st_mode))
1176 sbuf->st_mode |= S_IWRITE | S_IEXEC;
1177 else if (S_ISREG(sbuf->st_mode)) {
1179 if (l >= 4 && path[l-4] == '.') {
1180 const char *e = path + l - 3;
1181 if (strnicmp(e,"exe",3)
1182 && strnicmp(e,"bat",3)
1183 && strnicmp(e,"com",3)
1184 && (IsWin95() || strnicmp(e,"cmd",3)))
1185 sbuf->st_mode &= ~S_IEXEC;
1187 sbuf->st_mode |= S_IEXEC;
1190 sbuf->st_mode &= ~S_IEXEC;
1191 /* Propagate permissions to _group_ and _others_ */
1192 perms = sbuf->st_mode & (S_IREAD|S_IWRITE|S_IEXEC);
1193 sbuf->st_mode |= (perms>>3) | (perms>>6);
1200 /* Find the longname of a given path. path is destructively modified.
1201 * It should have space for at least MAX_PATH characters. */
1203 win32_longpath(char *path)
1205 WIN32_FIND_DATA fdata;
1207 char tmpbuf[MAX_PATH+1];
1208 char *tmpstart = tmpbuf;
1215 if (isALPHA(path[0]) && path[1] == ':' &&
1216 (path[2] == '/' || path[2] == '\\'))
1219 *tmpstart++ = path[0];
1223 else if ((path[0] == '/' || path[0] == '\\') &&
1224 (path[1] == '/' || path[1] == '\\'))
1227 *tmpstart++ = path[0];
1228 *tmpstart++ = path[1];
1229 /* copy machine name */
1230 while (*start && *start != '/' && *start != '\\')
1231 *tmpstart++ = *start++;
1233 *tmpstart++ = *start;
1235 /* copy share name */
1236 while (*start && *start != '/' && *start != '\\')
1237 *tmpstart++ = *start++;
1241 if (sep == '/' || sep == '\\')
1245 /* walk up to slash */
1246 while (*start && *start != '/' && *start != '\\')
1249 /* discard doubled slashes */
1250 while (*start && (start[1] == '/' || start[1] == '\\'))
1254 /* stop and find full name of component */
1256 fhand = FindFirstFile(path,&fdata);
1257 if (fhand != INVALID_HANDLE_VALUE) {
1258 strcpy(tmpstart, fdata.cFileName);
1259 tmpstart += strlen(fdata.cFileName);
1267 /* failed a step, just return without side effects */
1268 /*PerlIO_printf(Perl_debug_log, "Failed to find %s\n", path);*/
1273 strcpy(path,tmpbuf);
1277 #ifndef USE_WIN32_RTL_ENV
1280 win32_getenv(const char *name)
1283 WCHAR wBuffer[MAX_PATH+1];
1285 SV *curitem = Nullsv;
1288 A2WHELPER(name, wBuffer, sizeof(wBuffer));
1289 needlen = GetEnvironmentVariableW(wBuffer, NULL, 0);
1292 needlen = GetEnvironmentVariableA(name,NULL,0);
1294 curitem = sv_2mortal(newSVpvn("", 0));
1298 SvGROW(curitem, (needlen+1)*sizeof(WCHAR));
1299 needlen = GetEnvironmentVariableW(wBuffer,
1300 (WCHAR*)SvPVX(curitem),
1302 } while (needlen >= SvLEN(curitem)/sizeof(WCHAR));
1303 SvCUR_set(curitem, (needlen*sizeof(WCHAR))+1);
1304 acuritem = sv_2mortal(newSVsv(curitem));
1305 W2AHELPER((WCHAR*)SvPVX(acuritem), SvPVX(curitem), SvCUR(curitem));
1309 SvGROW(curitem, needlen+1);
1310 needlen = GetEnvironmentVariableA(name,SvPVX(curitem),
1312 } while (needlen >= SvLEN(curitem));
1313 SvCUR_set(curitem, needlen);
1317 /* allow any environment variables that begin with 'PERL'
1318 to be stored in the registry */
1319 if (strncmp(name, "PERL", 4) == 0)
1320 (void)get_regstr(name, &curitem);
1322 if (curitem && SvCUR(curitem))
1323 return SvPVX(curitem);
1329 win32_putenv(const char *name)
1336 int length, relval = -1;
1340 length = strlen(name)+1;
1341 New(1309,wCuritem,length,WCHAR);
1342 A2WHELPER(name, wCuritem, length*sizeof(WCHAR));
1343 wVal = wcschr(wCuritem, '=');
1346 if (SetEnvironmentVariableW(wCuritem, *wVal ? wVal : NULL))
1352 New(1309,curitem,strlen(name)+1,char);
1353 strcpy(curitem, name);
1354 val = strchr(curitem, '=');
1356 /* The sane way to deal with the environment.
1357 * Has these advantages over putenv() & co.:
1358 * * enables us to store a truly empty value in the
1359 * environment (like in UNIX).
1360 * * we don't have to deal with RTL globals, bugs and leaks.
1362 * Why you may want to enable USE_WIN32_RTL_ENV:
1363 * * environ[] and RTL functions will not reflect changes,
1364 * which might be an issue if extensions want to access
1365 * the env. via RTL. This cuts both ways, since RTL will
1366 * not see changes made by extensions that call the Win32
1367 * functions directly, either.
1371 if (SetEnvironmentVariableA(curitem, *val ? val : NULL))
1383 filetime_to_clock(PFILETIME ft)
1385 __int64 qw = ft->dwHighDateTime;
1387 qw |= ft->dwLowDateTime;
1388 qw /= 10000; /* File time ticks at 0.1uS, clock at 1mS */
1393 win32_times(struct tms *timebuf)
1398 if (GetProcessTimes(GetCurrentProcess(), &dummy, &dummy,
1400 timebuf->tms_utime = filetime_to_clock(&user);
1401 timebuf->tms_stime = filetime_to_clock(&kernel);
1402 timebuf->tms_cutime = 0;
1403 timebuf->tms_cstime = 0;
1406 /* That failed - e.g. Win95 fallback to clock() */
1407 clock_t t = clock();
1408 timebuf->tms_utime = t;
1409 timebuf->tms_stime = 0;
1410 timebuf->tms_cutime = 0;
1411 timebuf->tms_cstime = 0;
1416 /* fix utime() so it works on directories in NT */
1418 filetime_from_time(PFILETIME pFileTime, time_t Time)
1420 struct tm *pTM = localtime(&Time);
1421 SYSTEMTIME SystemTime;
1427 SystemTime.wYear = pTM->tm_year + 1900;
1428 SystemTime.wMonth = pTM->tm_mon + 1;
1429 SystemTime.wDay = pTM->tm_mday;
1430 SystemTime.wHour = pTM->tm_hour;
1431 SystemTime.wMinute = pTM->tm_min;
1432 SystemTime.wSecond = pTM->tm_sec;
1433 SystemTime.wMilliseconds = 0;
1435 return SystemTimeToFileTime(&SystemTime, &LocalTime) &&
1436 LocalFileTimeToFileTime(&LocalTime, pFileTime);
1440 win32_unlink(const char *filename)
1447 WCHAR wBuffer[MAX_PATH+1];
1450 A2WHELPER(filename, wBuffer, sizeof(wBuffer));
1451 pwBuffer = PerlDir_mapW(wBuffer);
1452 attrs = GetFileAttributesW(pwBuffer);
1453 if (attrs == 0xFFFFFFFF)
1455 if (attrs & FILE_ATTRIBUTE_READONLY) {
1456 (void)SetFileAttributesW(pwBuffer, attrs & ~FILE_ATTRIBUTE_READONLY);
1457 ret = _wunlink(pwBuffer);
1459 (void)SetFileAttributesW(pwBuffer, attrs);
1462 ret = _wunlink(pwBuffer);
1465 filename = PerlDir_mapA(filename);
1466 attrs = GetFileAttributesA(filename);
1467 if (attrs == 0xFFFFFFFF)
1469 if (attrs & FILE_ATTRIBUTE_READONLY) {
1470 (void)SetFileAttributesA(filename, attrs & ~FILE_ATTRIBUTE_READONLY);
1471 ret = unlink(filename);
1473 (void)SetFileAttributesA(filename, attrs);
1476 ret = unlink(filename);
1485 win32_utime(const char *filename, struct utimbuf *times)
1492 struct utimbuf TimeBuffer;
1493 WCHAR wbuffer[MAX_PATH+1];
1498 A2WHELPER(filename, wbuffer, sizeof(wbuffer));
1499 pwbuffer = PerlDir_mapW(wbuffer);
1500 rc = _wutime(pwbuffer, (struct _utimbuf*)times);
1503 filename = PerlDir_mapA(filename);
1504 rc = utime(filename, times);
1506 /* EACCES: path specifies directory or readonly file */
1507 if (rc == 0 || errno != EACCES /* || !IsWinNT() */)
1510 if (times == NULL) {
1511 times = &TimeBuffer;
1512 time(×->actime);
1513 times->modtime = times->actime;
1516 /* This will (and should) still fail on readonly files */
1518 handle = CreateFileW(pwbuffer, GENERIC_READ | GENERIC_WRITE,
1519 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1520 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1523 handle = CreateFileA(filename, GENERIC_READ | GENERIC_WRITE,
1524 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1525 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1527 if (handle == INVALID_HANDLE_VALUE)
1530 if (GetFileTime(handle, &ftCreate, &ftAccess, &ftWrite) &&
1531 filetime_from_time(&ftAccess, times->actime) &&
1532 filetime_from_time(&ftWrite, times->modtime) &&
1533 SetFileTime(handle, &ftCreate, &ftAccess, &ftWrite))
1538 CloseHandle(handle);
1543 win32_uname(struct utsname *name)
1545 struct hostent *hep;
1546 STRLEN nodemax = sizeof(name->nodename)-1;
1547 OSVERSIONINFO osver;
1549 memset(&osver, 0, sizeof(OSVERSIONINFO));
1550 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1551 if (GetVersionEx(&osver)) {
1553 switch (osver.dwPlatformId) {
1554 case VER_PLATFORM_WIN32_WINDOWS:
1555 strcpy(name->sysname, "Windows");
1557 case VER_PLATFORM_WIN32_NT:
1558 strcpy(name->sysname, "Windows NT");
1560 case VER_PLATFORM_WIN32s:
1561 strcpy(name->sysname, "Win32s");
1564 strcpy(name->sysname, "Win32 Unknown");
1569 sprintf(name->release, "%d.%d",
1570 osver.dwMajorVersion, osver.dwMinorVersion);
1573 sprintf(name->version, "Build %d",
1574 osver.dwPlatformId == VER_PLATFORM_WIN32_NT
1575 ? osver.dwBuildNumber : (osver.dwBuildNumber & 0xffff));
1576 if (osver.szCSDVersion[0]) {
1577 char *buf = name->version + strlen(name->version);
1578 sprintf(buf, " (%s)", osver.szCSDVersion);
1582 *name->sysname = '\0';
1583 *name->version = '\0';
1584 *name->release = '\0';
1588 hep = win32_gethostbyname("localhost");
1590 STRLEN len = strlen(hep->h_name);
1591 if (len <= nodemax) {
1592 strcpy(name->nodename, hep->h_name);
1595 strncpy(name->nodename, hep->h_name, nodemax);
1596 name->nodename[nodemax] = '\0';
1601 if (!GetComputerName(name->nodename, &sz))
1602 *name->nodename = '\0';
1605 /* machine (architecture) */
1609 GetSystemInfo(&info);
1611 #if defined(__BORLANDC__) || defined(__MINGW32__)
1612 #ifndef _STRUCT_NAME
1613 # define _STRUCT_NAME(s) s
1614 # define _UNION_NAME(u) u
1616 switch (info._UNION_NAME(u.)_STRUCT_NAME(s.)wProcessorArchitecture) {
1618 switch (info.wProcessorArchitecture) {
1620 case PROCESSOR_ARCHITECTURE_INTEL:
1621 arch = "x86"; break;
1622 case PROCESSOR_ARCHITECTURE_MIPS:
1623 arch = "mips"; break;
1624 case PROCESSOR_ARCHITECTURE_ALPHA:
1625 arch = "alpha"; break;
1626 case PROCESSOR_ARCHITECTURE_PPC:
1627 arch = "ppc"; break;
1629 arch = "unknown"; break;
1631 strcpy(name->machine, arch);
1637 win32_waitpid(int pid, int *status, int flags)
1641 if (pid == -1) /* XXX threadid == 1 ? */
1642 return win32_wait(status);
1645 long child = find_pseudo_pid(-pid);
1647 HANDLE hThread = w32_pseudo_child_handles[child];
1648 DWORD waitcode = WaitForSingleObject(hThread, INFINITE);
1649 if (waitcode != WAIT_FAILED) {
1650 if (GetExitCodeThread(hThread, &waitcode)) {
1651 *status = (int)((waitcode & 0xff) << 8);
1652 retval = (int)w32_pseudo_child_pids[child];
1653 remove_dead_pseudo_process(child);
1663 long child = find_pid(pid);
1665 HANDLE hProcess = w32_child_handles[child];
1666 DWORD waitcode = WaitForSingleObject(hProcess, INFINITE);
1667 if (waitcode != WAIT_FAILED) {
1668 if (GetExitCodeProcess(hProcess, &waitcode)) {
1669 *status = (int)((waitcode & 0xff) << 8);
1670 retval = (int)w32_child_pids[child];
1671 remove_dead_process(child);
1679 retval = cwait(status, pid, WAIT_CHILD);
1680 /* cwait() returns "correctly" on Borland */
1681 #ifndef __BORLANDC__
1687 return retval >= 0 ? pid : retval;
1691 win32_wait(int *status)
1693 /* XXX this wait emulation only knows about processes
1694 * spawned via win32_spawnvp(P_NOWAIT, ...).
1698 DWORD exitcode, waitcode;
1701 if (w32_num_pseudo_children) {
1702 waitcode = WaitForMultipleObjects(w32_num_pseudo_children,
1703 w32_pseudo_child_handles,
1706 if (waitcode != WAIT_FAILED) {
1707 if (waitcode >= WAIT_ABANDONED_0
1708 && waitcode < WAIT_ABANDONED_0 + w32_num_pseudo_children)
1709 i = waitcode - WAIT_ABANDONED_0;
1711 i = waitcode - WAIT_OBJECT_0;
1712 if (GetExitCodeThread(w32_pseudo_child_handles[i], &exitcode)) {
1713 *status = (int)((exitcode & 0xff) << 8);
1714 retval = (int)w32_pseudo_child_pids[i];
1715 remove_dead_pseudo_process(i);
1722 if (!w32_num_children) {
1727 /* if a child exists, wait for it to die */
1728 waitcode = WaitForMultipleObjects(w32_num_children,
1732 if (waitcode != WAIT_FAILED) {
1733 if (waitcode >= WAIT_ABANDONED_0
1734 && waitcode < WAIT_ABANDONED_0 + w32_num_children)
1735 i = waitcode - WAIT_ABANDONED_0;
1737 i = waitcode - WAIT_OBJECT_0;
1738 if (GetExitCodeProcess(w32_child_handles[i], &exitcode) ) {
1739 *status = (int)((exitcode & 0xff) << 8);
1740 retval = (int)w32_child_pids[i];
1741 remove_dead_process(i);
1747 errno = GetLastError();
1753 static UINT timerid = 0;
1755 static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
1758 KillTimer(NULL,timerid);
1760 CALL_FPTR(PL_sighandlerp)(14);
1762 #endif /* !PERL_OBJECT */
1764 DllExport unsigned int
1765 win32_alarm(unsigned int sec)
1769 * the 'obvious' implentation is SetTimer() with a callback
1770 * which does whatever receiving SIGALRM would do
1771 * we cannot use SIGALRM even via raise() as it is not
1772 * one of the supported codes in <signal.h>
1774 * Snag is unless something is looking at the message queue
1775 * nothing happens :-(
1780 timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
1782 Perl_croak_nocontext("Cannot set timer");
1788 KillTimer(NULL,timerid);
1792 #endif /* !PERL_OBJECT */
1796 #ifdef HAVE_DES_FCRYPT
1797 extern char * des_fcrypt(const char *txt, const char *salt, char *cbuf);
1801 win32_crypt(const char *txt, const char *salt)
1804 #ifdef HAVE_DES_FCRYPT
1806 return des_fcrypt(txt, salt, w32_crypt_buffer);
1808 Perl_croak(aTHX_ "The crypt() function is unimplemented due to excessive paranoia.");
1813 /* C doesn't like repeat struct definitions */
1815 #if defined(USE_FIXED_OSFHANDLE) || defined(PERL_MSVCRT_READFIX)
1818 #define _CRTIMP __declspec(dllimport)
1822 * Control structure for lowio file handles
1825 long osfhnd; /* underlying OS file HANDLE */
1826 char osfile; /* attributes of file (e.g., open in text mode?) */
1827 char pipech; /* one char buffer for handles opened on pipes */
1829 CRITICAL_SECTION lock;
1834 * Array of arrays of control structures for lowio files.
1836 EXTERN_C _CRTIMP ioinfo* __pioinfo[];
1839 * Definition of IOINFO_L2E, the log base 2 of the number of elements in each
1840 * array of ioinfo structs.
1842 #define IOINFO_L2E 5
1845 * Definition of IOINFO_ARRAY_ELTS, the number of elements in ioinfo array
1847 #define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
1850 * Access macros for getting at an ioinfo struct and its fields from a
1853 #define _pioinfo(i) (__pioinfo[(i) >> IOINFO_L2E] + ((i) & (IOINFO_ARRAY_ELTS - 1)))
1854 #define _osfhnd(i) (_pioinfo(i)->osfhnd)
1855 #define _osfile(i) (_pioinfo(i)->osfile)
1856 #define _pipech(i) (_pioinfo(i)->pipech)
1860 #ifdef USE_FIXED_OSFHANDLE
1862 #define FOPEN 0x01 /* file handle open */
1863 #define FNOINHERIT 0x10 /* file handle opened O_NOINHERIT */
1864 #define FAPPEND 0x20 /* file handle opened O_APPEND */
1865 #define FDEV 0x40 /* file handle refers to device */
1866 #define FTEXT 0x80 /* file handle is in text mode */
1869 *int my_open_osfhandle(long osfhandle, int flags) - open C Runtime file handle
1872 * This function allocates a free C Runtime file handle and associates
1873 * it with the Win32 HANDLE specified by the first parameter. This is a
1874 * temperary fix for WIN95's brain damage GetFileType() error on socket
1875 * we just bypass that call for socket
1877 * This works with MSVC++ 4.0+ or GCC/Mingw32
1880 * long osfhandle - Win32 HANDLE to associate with C Runtime file handle.
1881 * int flags - flags to associate with C Runtime file handle.
1884 * returns index of entry in fh, if successful
1885 * return -1, if no free entry is found
1889 *******************************************************************************/
1892 * we fake up some parts of the CRT that aren't exported by MSVCRT.dll
1893 * this lets sockets work on Win9X with GCC and should fix the problems
1898 /* since we are not doing a dup2(), this works fine */
1900 #define _set_osfhnd(fh, osfh) (void)(_osfhnd(fh) = osfh)
1902 /* create an ioinfo entry, kill its handle, and steal the entry */
1907 HANDLE hF = CreateFile("NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
1908 int fh = _open_osfhandle((long)hF, 0);
1912 EnterCriticalSection(&(_pioinfo(fh)->lock));
1917 my_open_osfhandle(long osfhandle, int flags)
1920 char fileflags; /* _osfile flags */
1922 /* copy relevant flags from second parameter */
1925 if (flags & O_APPEND)
1926 fileflags |= FAPPEND;
1931 if (flags & O_NOINHERIT)
1932 fileflags |= FNOINHERIT;
1934 /* attempt to allocate a C Runtime file handle */
1935 if ((fh = _alloc_osfhnd()) == -1) {
1936 errno = EMFILE; /* too many open files */
1937 _doserrno = 0L; /* not an OS error */
1938 return -1; /* return error to caller */
1941 /* the file is open. now, set the info in _osfhnd array */
1942 _set_osfhnd(fh, osfhandle);
1944 fileflags |= FOPEN; /* mark as open */
1946 _osfile(fh) = fileflags; /* set osfile entry */
1947 LeaveCriticalSection(&_pioinfo(fh)->lock);
1949 return fh; /* return handle */
1952 #endif /* USE_FIXED_OSFHANDLE */
1954 /* simulate flock by locking a range on the file */
1956 #define LK_ERR(f,i) ((f) ? (i = 0) : (errno = GetLastError()))
1957 #define LK_LEN 0xffff0000
1960 win32_flock(int fd, int oper)
1968 Perl_croak_nocontext("flock() unimplemented on this platform");
1971 fh = (HANDLE)_get_osfhandle(fd);
1972 memset(&o, 0, sizeof(o));
1975 case LOCK_SH: /* shared lock */
1976 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
1978 case LOCK_EX: /* exclusive lock */
1979 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
1981 case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
1982 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
1984 case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
1985 LK_ERR(LockFileEx(fh,
1986 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
1987 0, LK_LEN, 0, &o),i);
1989 case LOCK_UN: /* unlock lock */
1990 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, 0, &o),i);
1992 default: /* unknown */
2003 * redirected io subsystem for all XS modules
2016 return (&(_environ));
2019 /* the rest are the remapped stdio routines */
2039 win32_ferror(FILE *fp)
2041 return (ferror(fp));
2046 win32_feof(FILE *fp)
2052 * Since the errors returned by the socket error function
2053 * WSAGetLastError() are not known by the library routine strerror
2054 * we have to roll our own.
2058 win32_strerror(int e)
2062 if (e < 0 || e > sys_nerr) {
2067 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
2068 w32_strerror_buffer,
2069 sizeof(w32_strerror_buffer), NULL) == 0)
2070 strcpy(w32_strerror_buffer, "Unknown Error");
2072 return w32_strerror_buffer;
2078 win32_str_os_error(void *sv, DWORD dwErr)
2082 dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
2083 |FORMAT_MESSAGE_IGNORE_INSERTS
2084 |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
2085 dwErr, 0, (char *)&sMsg, 1, NULL);
2086 /* strip trailing whitespace and period */
2089 --dwLen; /* dwLen doesn't include trailing null */
2090 } while (0 < dwLen && isSPACE(sMsg[dwLen]));
2091 if ('.' != sMsg[dwLen])
2096 sMsg = (char*)LocalAlloc(0, 64/**sizeof(TCHAR)*/);
2098 dwLen = sprintf(sMsg,
2099 "Unknown error #0x%lX (lookup 0x%lX)",
2100 dwErr, GetLastError());
2104 sv_setpvn((SV*)sv, sMsg, dwLen);
2111 win32_fprintf(FILE *fp, const char *format, ...)
2114 va_start(marker, format); /* Initialize variable arguments. */
2116 return (vfprintf(fp, format, marker));
2120 win32_printf(const char *format, ...)
2123 va_start(marker, format); /* Initialize variable arguments. */
2125 return (vprintf(format, marker));
2129 win32_vfprintf(FILE *fp, const char *format, va_list args)
2131 return (vfprintf(fp, format, args));
2135 win32_vprintf(const char *format, va_list args)
2137 return (vprintf(format, args));
2141 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
2143 return fread(buf, size, count, fp);
2147 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
2149 return fwrite(buf, size, count, fp);
2152 #define MODE_SIZE 10
2155 win32_fopen(const char *filename, const char *mode)
2158 WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH+1];
2164 if (stricmp(filename, "/dev/null")==0)
2168 A2WHELPER(mode, wMode, sizeof(wMode));
2169 A2WHELPER(filename, wBuffer, sizeof(wBuffer));
2170 f = _wfopen(PerlDir_mapW(wBuffer), wMode);
2173 f = fopen(PerlDir_mapA(filename), mode);
2174 /* avoid buffering headaches for child processes */
2175 if (f && *mode == 'a')
2176 win32_fseek(f, 0, SEEK_END);
2180 #ifndef USE_SOCKETS_AS_HANDLES
2182 #define fdopen my_fdopen
2186 win32_fdopen(int handle, const char *mode)
2189 WCHAR wMode[MODE_SIZE];
2192 A2WHELPER(mode, wMode, sizeof(wMode));
2193 f = _wfdopen(handle, wMode);
2196 f = fdopen(handle, (char *) mode);
2197 /* avoid buffering headaches for child processes */
2198 if (f && *mode == 'a')
2199 win32_fseek(f, 0, SEEK_END);
2204 win32_freopen(const char *path, const char *mode, FILE *stream)
2207 WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH+1];
2208 if (stricmp(path, "/dev/null")==0)
2212 A2WHELPER(mode, wMode, sizeof(wMode));
2213 A2WHELPER(path, wBuffer, sizeof(wBuffer));
2214 return _wfreopen(PerlDir_mapW(wBuffer), wMode, stream);
2216 return freopen(PerlDir_mapA(path), mode, stream);
2220 win32_fclose(FILE *pf)
2222 return my_fclose(pf); /* defined in win32sck.c */
2226 win32_fputs(const char *s,FILE *pf)
2228 return fputs(s, pf);
2232 win32_fputc(int c,FILE *pf)
2238 win32_ungetc(int c,FILE *pf)
2240 return ungetc(c,pf);
2244 win32_getc(FILE *pf)
2250 win32_fileno(FILE *pf)
2256 win32_clearerr(FILE *pf)
2263 win32_fflush(FILE *pf)
2269 win32_ftell(FILE *pf)
2275 win32_fseek(FILE *pf,long offset,int origin)
2277 return fseek(pf, offset, origin);
2281 win32_fgetpos(FILE *pf,fpos_t *p)
2283 return fgetpos(pf, p);
2287 win32_fsetpos(FILE *pf,const fpos_t *p)
2289 return fsetpos(pf, p);
2293 win32_rewind(FILE *pf)
2313 win32_fstat(int fd,struct stat *sbufptr)
2315 return fstat(fd,sbufptr);
2319 win32_pipe(int *pfd, unsigned int size, int mode)
2321 return _pipe(pfd, size, mode);
2325 * a popen() clone that respects PERL5SHELL
2329 win32_popen(const char *command, const char *mode)
2331 #ifdef USE_RTL_POPEN
2332 return _popen(command, mode);
2340 /* establish which ends read and write */
2341 if (strchr(mode,'w')) {
2342 stdfd = 0; /* stdin */
2346 else if (strchr(mode,'r')) {
2347 stdfd = 1; /* stdout */
2354 /* set the correct mode */
2355 if (strchr(mode,'b'))
2357 else if (strchr(mode,'t'))
2360 ourmode = _fmode & (O_TEXT | O_BINARY);
2362 /* the child doesn't inherit handles */
2363 ourmode |= O_NOINHERIT;
2365 if (win32_pipe( p, 512, ourmode) == -1)
2368 /* save current stdfd */
2369 if ((oldfd = win32_dup(stdfd)) == -1)
2372 /* make stdfd go to child end of pipe (implicitly closes stdfd) */
2373 /* stdfd will be inherited by the child */
2374 if (win32_dup2(p[child], stdfd) == -1)
2377 /* close the child end in parent */
2378 win32_close(p[child]);
2380 /* start the child */
2383 if ((childpid = do_spawn_nowait((char*)command)) == -1)
2386 /* revert stdfd to whatever it was before */
2387 if (win32_dup2(oldfd, stdfd) == -1)
2390 /* close saved handle */
2393 sv_setiv(*av_fetch(w32_fdpid, p[parent], TRUE), childpid);
2395 /* set process id so that it can be returned by perl's open() */
2396 PL_forkprocess = childpid;
2399 /* we have an fd, return a file stream */
2400 return (win32_fdopen(p[parent], (char *)mode));
2403 /* we don't need to check for errors here */
2407 win32_dup2(oldfd, stdfd);
2412 #endif /* USE_RTL_POPEN */
2420 win32_pclose(FILE *pf)
2422 #ifdef USE_RTL_POPEN
2426 int childpid, status;
2429 sv = *av_fetch(w32_fdpid, win32_fileno(pf), TRUE);
2431 childpid = SvIVX(sv);
2443 if (win32_waitpid(childpid, &status, 0) == -1)
2448 #endif /* USE_RTL_POPEN */
2454 LPCWSTR lpExistingFileName,
2455 LPSECURITY_ATTRIBUTES lpSecurityAttributes)
2458 WCHAR wFullName[MAX_PATH+1];
2459 LPVOID lpContext = NULL;
2460 WIN32_STREAM_ID StreamId;
2461 DWORD dwSize = (char*)&StreamId.cStreamName - (char*)&StreamId;
2466 BOOL (__stdcall *pfnBackupWrite)(HANDLE, LPBYTE, DWORD, LPDWORD,
2467 BOOL, BOOL, LPVOID*) =
2468 (BOOL (__stdcall *)(HANDLE, LPBYTE, DWORD, LPDWORD,
2469 BOOL, BOOL, LPVOID*))
2470 GetProcAddress(GetModuleHandle("kernel32.dll"), "BackupWrite");
2471 if (pfnBackupWrite == NULL)
2474 dwLen = GetFullPathNameW(lpFileName, MAX_PATH, wFullName, NULL);
2477 dwLen = (dwLen+1)*sizeof(WCHAR);
2479 handle = CreateFileW(lpExistingFileName, FILE_WRITE_ATTRIBUTES,
2480 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
2481 NULL, OPEN_EXISTING, 0, NULL);
2482 if (handle == INVALID_HANDLE_VALUE)
2485 StreamId.dwStreamId = BACKUP_LINK;
2486 StreamId.dwStreamAttributes = 0;
2487 StreamId.dwStreamNameSize = 0;
2488 #if defined(__BORLANDC__) || defined(__MINGW32__)
2489 StreamId.Size._UNION_NAME(u.)HighPart = 0;
2490 StreamId.Size._UNION_NAME(u.)LowPart = dwLen;
2492 StreamId.Size.HighPart = 0;
2493 StreamId.Size.LowPart = dwLen;
2496 bSuccess = pfnBackupWrite(handle, (LPBYTE)&StreamId, dwSize, &dwWritten,
2497 FALSE, FALSE, &lpContext);
2499 bSuccess = pfnBackupWrite(handle, (LPBYTE)wFullName, dwLen, &dwWritten,
2500 FALSE, FALSE, &lpContext);
2501 pfnBackupWrite(handle, NULL, 0, &dwWritten, TRUE, FALSE, &lpContext);
2504 CloseHandle(handle);
2509 win32_link(const char *oldname, const char *newname)
2512 BOOL (__stdcall *pfnCreateHardLinkW)(LPCWSTR,LPCWSTR,LPSECURITY_ATTRIBUTES);
2513 WCHAR wOldName[MAX_PATH+1];
2514 WCHAR wNewName[MAX_PATH+1];
2517 Perl_croak(aTHX_ PL_no_func, "link");
2519 pfnCreateHardLinkW =
2520 (BOOL (__stdcall *)(LPCWSTR, LPCWSTR, LPSECURITY_ATTRIBUTES))
2521 GetProcAddress(GetModuleHandle("kernel32.dll"), "CreateHardLinkW");
2522 if (pfnCreateHardLinkW == NULL)
2523 pfnCreateHardLinkW = Nt4CreateHardLinkW;
2525 if ((A2WHELPER(oldname, wOldName, sizeof(wOldName))) &&
2526 (A2WHELPER(newname, wNewName, sizeof(wNewName))) &&
2527 (wcscpy(wOldName, PerlDir_mapW(wOldName)),
2528 pfnCreateHardLinkW(PerlDir_mapW(wNewName), wOldName, NULL)))
2532 errno = (GetLastError() == ERROR_FILE_NOT_FOUND) ? ENOENT : EINVAL;
2537 win32_rename(const char *oname, const char *newname)
2539 WCHAR wOldName[MAX_PATH+1];
2540 WCHAR wNewName[MAX_PATH+1];
2541 char szOldName[MAX_PATH+1];
2542 char szNewName[MAX_PATH+1];
2546 /* XXX despite what the documentation says about MoveFileEx(),
2547 * it doesn't work under Windows95!
2550 DWORD dwFlags = MOVEFILE_COPY_ALLOWED;
2552 A2WHELPER(oname, wOldName, sizeof(wOldName));
2553 A2WHELPER(newname, wNewName, sizeof(wNewName));
2554 if (wcsicmp(wNewName, wOldName))
2555 dwFlags |= MOVEFILE_REPLACE_EXISTING;
2556 wcscpy(wOldName, PerlDir_mapW(wOldName));
2557 bResult = MoveFileExW(wOldName,PerlDir_mapW(wNewName), dwFlags);
2560 if (stricmp(newname, oname))
2561 dwFlags |= MOVEFILE_REPLACE_EXISTING;
2562 strcpy(szOldName, PerlDir_mapA(oname));
2563 bResult = MoveFileExA(szOldName,PerlDir_mapA(newname), dwFlags);
2566 DWORD err = GetLastError();
2568 case ERROR_BAD_NET_NAME:
2569 case ERROR_BAD_NETPATH:
2570 case ERROR_BAD_PATHNAME:
2571 case ERROR_FILE_NOT_FOUND:
2572 case ERROR_FILENAME_EXCED_RANGE:
2573 case ERROR_INVALID_DRIVE:
2574 case ERROR_NO_MORE_FILES:
2575 case ERROR_PATH_NOT_FOUND:
2588 char szTmpName[MAX_PATH+1];
2589 char dname[MAX_PATH+1];
2590 char *endname = Nullch;
2592 DWORD from_attr, to_attr;
2594 strcpy(szOldName, PerlDir_mapA(oname));
2595 strcpy(szNewName, PerlDir_mapA(newname));
2597 /* if oname doesn't exist, do nothing */
2598 from_attr = GetFileAttributes(szOldName);
2599 if (from_attr == 0xFFFFFFFF) {
2604 /* if newname exists, rename it to a temporary name so that we
2605 * don't delete it in case oname happens to be the same file
2606 * (but perhaps accessed via a different path)
2608 to_attr = GetFileAttributes(szNewName);
2609 if (to_attr != 0xFFFFFFFF) {
2610 /* if newname is a directory, we fail
2611 * XXX could overcome this with yet more convoluted logic */
2612 if (to_attr & FILE_ATTRIBUTE_DIRECTORY) {
2616 tmplen = strlen(szNewName);
2617 strcpy(szTmpName,szNewName);
2618 endname = szTmpName+tmplen;
2619 for (; endname > szTmpName ; --endname) {
2620 if (*endname == '/' || *endname == '\\') {
2625 if (endname > szTmpName)
2626 endname = strcpy(dname,szTmpName);
2630 /* get a temporary filename in same directory
2631 * XXX is this really the best we can do? */
2632 if (!GetTempFileName((LPCTSTR)endname, "plr", 0, szTmpName)) {
2636 DeleteFile(szTmpName);
2638 retval = rename(szNewName, szTmpName);
2645 /* rename oname to newname */
2646 retval = rename(szOldName, szNewName);
2648 /* if we created a temporary file before ... */
2649 if (endname != Nullch) {
2650 /* ...and rename succeeded, delete temporary file/directory */
2652 DeleteFile(szTmpName);
2653 /* else restore it to what it was */
2655 (void)rename(szTmpName, szNewName);
2662 win32_setmode(int fd, int mode)
2664 return setmode(fd, mode);
2668 win32_lseek(int fd, long offset, int origin)
2670 return lseek(fd, offset, origin);
2680 win32_open(const char *path, int flag, ...)
2685 WCHAR wBuffer[MAX_PATH+1];
2688 pmode = va_arg(ap, int);
2691 if (stricmp(path, "/dev/null")==0)
2695 A2WHELPER(path, wBuffer, sizeof(wBuffer));
2696 return _wopen(PerlDir_mapW(wBuffer), flag, pmode);
2698 return open(PerlDir_mapA(path), flag, pmode);
2720 win32_dup2(int fd1,int fd2)
2722 return dup2(fd1,fd2);
2725 #ifdef PERL_MSVCRT_READFIX
2727 #define LF 10 /* line feed */
2728 #define CR 13 /* carriage return */
2729 #define CTRLZ 26 /* ctrl-z means eof for text */
2730 #define FOPEN 0x01 /* file handle open */
2731 #define FEOFLAG 0x02 /* end of file has been encountered */
2732 #define FCRLF 0x04 /* CR-LF across read buffer (in text mode) */
2733 #define FPIPE 0x08 /* file handle refers to a pipe */
2734 #define FAPPEND 0x20 /* file handle opened O_APPEND */
2735 #define FDEV 0x40 /* file handle refers to device */
2736 #define FTEXT 0x80 /* file handle is in text mode */
2737 #define MAX_DESCRIPTOR_COUNT (64*32) /* this is the maximun that MSVCRT can handle */
2740 _fixed_read(int fh, void *buf, unsigned cnt)
2742 int bytes_read; /* number of bytes read */
2743 char *buffer; /* buffer to read to */
2744 int os_read; /* bytes read on OS call */
2745 char *p, *q; /* pointers into buffer */
2746 char peekchr; /* peek-ahead character */
2747 ULONG filepos; /* file position after seek */
2748 ULONG dosretval; /* o.s. return value */
2750 /* validate handle */
2751 if (((unsigned)fh >= (unsigned)MAX_DESCRIPTOR_COUNT) ||
2752 !(_osfile(fh) & FOPEN))
2754 /* out of range -- return error */
2756 _doserrno = 0; /* not o.s. error */
2761 * If lockinitflag is FALSE, assume fd is device
2762 * lockinitflag is set to TRUE by open.
2764 if (_pioinfo(fh)->lockinitflag)
2765 EnterCriticalSection(&(_pioinfo(fh)->lock)); /* lock file */
2767 bytes_read = 0; /* nothing read yet */
2768 buffer = (char*)buf;
2770 if (cnt == 0 || (_osfile(fh) & FEOFLAG)) {
2771 /* nothing to read or at EOF, so return 0 read */
2775 if ((_osfile(fh) & (FPIPE|FDEV)) && _pipech(fh) != LF) {
2776 /* a pipe/device and pipe lookahead non-empty: read the lookahead
2778 *buffer++ = _pipech(fh);
2781 _pipech(fh) = LF; /* mark as empty */
2786 if (!ReadFile((HANDLE)_osfhnd(fh), buffer, cnt, (LPDWORD)&os_read, NULL))
2788 /* ReadFile has reported an error. recognize two special cases.
2790 * 1. map ERROR_ACCESS_DENIED to EBADF
2792 * 2. just return 0 if ERROR_BROKEN_PIPE has occurred. it
2793 * means the handle is a read-handle on a pipe for which
2794 * all write-handles have been closed and all data has been
2797 if ((dosretval = GetLastError()) == ERROR_ACCESS_DENIED) {
2798 /* wrong read/write mode should return EBADF, not EACCES */
2800 _doserrno = dosretval;
2804 else if (dosretval == ERROR_BROKEN_PIPE) {
2814 bytes_read += os_read; /* update bytes read */
2816 if (_osfile(fh) & FTEXT) {
2817 /* now must translate CR-LFs to LFs in the buffer */
2819 /* set CRLF flag to indicate LF at beginning of buffer */
2820 /* if ((os_read != 0) && (*(char *)buf == LF)) */
2821 /* _osfile(fh) |= FCRLF; */
2823 /* _osfile(fh) &= ~FCRLF; */
2825 _osfile(fh) &= ~FCRLF;
2827 /* convert chars in the buffer: p is src, q is dest */
2829 while (p < (char *)buf + bytes_read) {
2831 /* if fh is not a device, set ctrl-z flag */
2832 if (!(_osfile(fh) & FDEV))
2833 _osfile(fh) |= FEOFLAG;
2834 break; /* stop translating */
2839 /* *p is CR, so must check next char for LF */
2840 if (p < (char *)buf + bytes_read - 1) {
2843 *q++ = LF; /* convert CR-LF to LF */
2846 *q++ = *p++; /* store char normally */
2849 /* This is the hard part. We found a CR at end of
2850 buffer. We must peek ahead to see if next char
2855 if (!ReadFile((HANDLE)_osfhnd(fh), &peekchr, 1,
2856 (LPDWORD)&os_read, NULL))
2857 dosretval = GetLastError();
2859 if (dosretval != 0 || os_read == 0) {
2860 /* couldn't read ahead, store CR */
2864 /* peekchr now has the extra character -- we now
2865 have several possibilities:
2866 1. disk file and char is not LF; just seek back
2868 2. disk file and char is LF; store LF, don't seek back
2869 3. pipe/device and char is LF; store LF.
2870 4. pipe/device and char isn't LF, store CR and
2871 put char in pipe lookahead buffer. */
2872 if (_osfile(fh) & (FDEV|FPIPE)) {
2873 /* non-seekable device */
2878 _pipech(fh) = peekchr;
2883 if (peekchr == LF) {
2884 /* nothing read yet; must make some
2887 /* turn on this flag for tell routine */
2888 _osfile(fh) |= FCRLF;
2891 HANDLE osHandle; /* o.s. handle value */
2893 if ((osHandle = (HANDLE)_get_osfhandle(fh)) != (HANDLE)-1)
2895 if ((filepos = SetFilePointer(osHandle, -1, NULL, FILE_CURRENT)) == -1)
2896 dosretval = GetLastError();
2907 /* we now change bytes_read to reflect the true number of chars
2909 bytes_read = q - (char *)buf;
2913 if (_pioinfo(fh)->lockinitflag)
2914 LeaveCriticalSection(&(_pioinfo(fh)->lock)); /* unlock file */
2919 #endif /* PERL_MSVCRT_READFIX */
2922 win32_read(int fd, void *buf, unsigned int cnt)
2924 #ifdef PERL_MSVCRT_READFIX
2925 return _fixed_read(fd, buf, cnt);
2927 return read(fd, buf, cnt);
2932 win32_write(int fd, const void *buf, unsigned int cnt)
2934 return write(fd, buf, cnt);
2938 win32_mkdir(const char *dir, int mode)
2942 WCHAR wBuffer[MAX_PATH+1];
2943 A2WHELPER(dir, wBuffer, sizeof(wBuffer));
2944 return _wmkdir(PerlDir_mapW(wBuffer));
2946 return mkdir(PerlDir_mapA(dir)); /* just ignore mode */
2950 win32_rmdir(const char *dir)
2954 WCHAR wBuffer[MAX_PATH+1];
2955 A2WHELPER(dir, wBuffer, sizeof(wBuffer));
2956 return _wrmdir(PerlDir_mapW(wBuffer));
2958 return rmdir(PerlDir_mapA(dir));
2962 win32_chdir(const char *dir)
2966 WCHAR wBuffer[MAX_PATH+1];
2967 A2WHELPER(dir, wBuffer, sizeof(wBuffer));
2968 return _wchdir(wBuffer);
2974 win32_access(const char *path, int mode)
2978 WCHAR wBuffer[MAX_PATH+1];
2979 A2WHELPER(path, wBuffer, sizeof(wBuffer));
2980 return _waccess(PerlDir_mapW(wBuffer), mode);
2982 return access(PerlDir_mapA(path), mode);
2986 win32_chmod(const char *path, int mode)
2990 WCHAR wBuffer[MAX_PATH+1];
2991 A2WHELPER(path, wBuffer, sizeof(wBuffer));
2992 return _wchmod(PerlDir_mapW(wBuffer), mode);
2994 return chmod(PerlDir_mapA(path), mode);
2999 create_command_line(const char* command, const char * const *args)
3003 char *cmd, *ptr, *arg;
3004 STRLEN len = strlen(command) + 1;
3006 for (index = 0; (ptr = (char*)args[index]) != NULL; ++index)
3007 len += strlen(ptr) + 1;
3009 New(1310, cmd, len, char);
3011 strcpy(ptr, command);
3013 for (index = 0; (arg = (char*)args[index]) != NULL; ++index) {
3023 qualified_path(const char *cmd)
3027 char *fullcmd, *curfullcmd;
3033 fullcmd = (char*)cmd;
3035 if (*fullcmd == '/' || *fullcmd == '\\')
3042 pathstr = win32_getenv("PATH");
3043 New(0, fullcmd, MAX_PATH+1, char);
3044 curfullcmd = fullcmd;
3049 /* start by appending the name to the current prefix */
3050 strcpy(curfullcmd, cmd);
3051 curfullcmd += cmdlen;
3053 /* if it doesn't end with '.', or has no extension, try adding
3054 * a trailing .exe first */
3055 if (cmd[cmdlen-1] != '.'
3056 && (cmdlen < 4 || cmd[cmdlen-4] != '.'))
3058 strcpy(curfullcmd, ".exe");
3059 res = GetFileAttributes(fullcmd);
3060 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
3065 /* that failed, try the bare name */
3066 res = GetFileAttributes(fullcmd);
3067 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
3070 /* quit if no other path exists, or if cmd already has path */
3071 if (!pathstr || !*pathstr || has_slash)
3074 /* skip leading semis */
3075 while (*pathstr == ';')
3078 /* build a new prefix from scratch */
3079 curfullcmd = fullcmd;
3080 while (*pathstr && *pathstr != ';') {
3081 if (*pathstr == '"') { /* foo;"baz;etc";bar */
3082 pathstr++; /* skip initial '"' */
3083 while (*pathstr && *pathstr != '"') {
3084 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
3085 *curfullcmd++ = *pathstr;
3089 pathstr++; /* skip trailing '"' */
3092 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
3093 *curfullcmd++ = *pathstr;
3098 pathstr++; /* skip trailing semi */
3099 if (curfullcmd > fullcmd /* append a dir separator */
3100 && curfullcmd[-1] != '/' && curfullcmd[-1] != '\\')
3102 *curfullcmd++ = '\\';
3110 /* The following are just place holders.
3111 * Some hosts may provide and environment that the OS is
3112 * not tracking, therefore, these host must provide that
3113 * environment and the current directory to CreateProcess
3123 free_childenv(void* d)
3132 char szfilename[(MAX_PATH+1)*2];
3134 WCHAR wfilename[MAX_PATH+1];
3135 GetCurrentDirectoryW(MAX_PATH+1, wfilename);
3136 W2AHELPER(wfilename, szfilename, sizeof(szfilename));
3139 GetCurrentDirectoryA(MAX_PATH+1, szfilename);
3142 New(0, ptr, strlen(szfilename)+1, char);
3143 strcpy(ptr, szfilename);
3148 free_childdir(char* d)
3155 /* XXX this needs to be made more compatible with the spawnvp()
3156 * provided by the various RTLs. In particular, searching for
3157 * *.{com,bat,cmd} files (as done by the RTLs) is unimplemented.
3158 * This doesn't significantly affect perl itself, because we
3159 * always invoke things using PERL5SHELL if a direct attempt to
3160 * spawn the executable fails.
3162 * XXX splitting and rejoining the commandline between do_aspawn()
3163 * and win32_spawnvp() could also be avoided.
3167 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
3169 #ifdef USE_RTL_SPAWNVP
3170 return spawnvp(mode, cmdname, (char * const *)argv);
3177 STARTUPINFO StartupInfo;
3178 PROCESS_INFORMATION ProcessInformation;
3181 char *cmd = create_command_line(cmdname, strcmp(cmdname, argv[0]) == 0
3183 char *fullcmd = Nullch;
3185 env = PerlEnv_get_childenv();
3186 dir = PerlEnv_get_childdir();
3189 case P_NOWAIT: /* asynch + remember result */
3190 if (w32_num_children >= MAXIMUM_WAIT_OBJECTS) {
3196 case P_WAIT: /* synchronous execution */
3198 default: /* invalid mode */
3203 memset(&StartupInfo,0,sizeof(StartupInfo));
3204 StartupInfo.cb = sizeof(StartupInfo);
3205 memset(&tbl,0,sizeof(tbl));
3206 PerlEnv_get_child_IO(&tbl);
3207 StartupInfo.dwFlags = tbl.dwFlags;
3208 StartupInfo.dwX = tbl.dwX;
3209 StartupInfo.dwY = tbl.dwY;
3210 StartupInfo.dwXSize = tbl.dwXSize;
3211 StartupInfo.dwYSize = tbl.dwYSize;
3212 StartupInfo.dwXCountChars = tbl.dwXCountChars;
3213 StartupInfo.dwYCountChars = tbl.dwYCountChars;
3214 StartupInfo.dwFillAttribute = tbl.dwFillAttribute;
3215 StartupInfo.wShowWindow = tbl.wShowWindow;
3216 StartupInfo.hStdInput = tbl.childStdIn;
3217 StartupInfo.hStdOutput = tbl.childStdOut;
3218 StartupInfo.hStdError = tbl.childStdErr;
3219 if (StartupInfo.hStdInput != INVALID_HANDLE_VALUE &&
3220 StartupInfo.hStdOutput != INVALID_HANDLE_VALUE &&
3221 StartupInfo.hStdError != INVALID_HANDLE_VALUE)
3223 StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
3226 create |= CREATE_NEW_CONSOLE;
3230 if (!CreateProcess(cmdname, /* search PATH to find executable */
3231 cmd, /* executable, and its arguments */
3232 NULL, /* process attributes */
3233 NULL, /* thread attributes */
3234 TRUE, /* inherit handles */
3235 create, /* creation flags */
3236 (LPVOID)env, /* inherit environment */
3237 dir, /* inherit cwd */
3239 &ProcessInformation))
3241 /* initial NULL argument to CreateProcess() does a PATH
3242 * search, but it always first looks in the directory
3243 * where the current process was started, which behavior
3244 * is undesirable for backward compatibility. So we
3245 * jump through our own hoops by picking out the path
3246 * we really want it to use. */
3248 fullcmd = qualified_path(cmdname);
3259 if (mode == P_NOWAIT) {
3260 /* asynchronous spawn -- store handle, return PID */
3261 w32_child_handles[w32_num_children] = ProcessInformation.hProcess;
3262 w32_child_pids[w32_num_children] = ProcessInformation.dwProcessId;
3263 ret = (int)ProcessInformation.dwProcessId;
3268 WaitForSingleObject(ProcessInformation.hProcess, INFINITE);
3269 GetExitCodeProcess(ProcessInformation.hProcess, &status);
3271 CloseHandle(ProcessInformation.hProcess);
3274 CloseHandle(ProcessInformation.hThread);
3277 PerlEnv_free_childenv(env);
3278 PerlEnv_free_childdir(dir);
3286 win32_execv(const char *cmdname, const char *const *argv)
3290 /* if this is a pseudo-forked child, we just want to spawn
3291 * the new program, and return */
3293 return spawnv(P_WAIT, cmdname, (char *const *)argv);
3295 return execv(cmdname, (char *const *)argv);
3299 win32_execvp(const char *cmdname, const char *const *argv)
3303 /* if this is a pseudo-forked child, we just want to spawn
3304 * the new program, and return */
3306 return win32_spawnvp(P_WAIT, cmdname, (char *const *)argv);
3308 return execvp(cmdname, (char *const *)argv);
3312 win32_perror(const char *str)
3318 win32_setbuf(FILE *pf, char *buf)
3324 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
3326 return setvbuf(pf, buf, type, size);
3330 win32_flushall(void)
3336 win32_fcloseall(void)
3342 win32_fgets(char *s, int n, FILE *pf)
3344 return fgets(s, n, pf);
3354 win32_fgetc(FILE *pf)
3360 win32_putc(int c, FILE *pf)
3366 win32_puts(const char *s)
3378 win32_putchar(int c)
3385 #ifndef USE_PERL_SBRK
3387 static char *committed = NULL;
3388 static char *base = NULL;
3389 static char *reserved = NULL;
3390 static char *brk = NULL;
3391 static DWORD pagesize = 0;
3392 static DWORD allocsize = 0;
3400 GetSystemInfo(&info);
3401 /* Pretend page size is larger so we don't perpetually
3402 * call the OS to commit just one page ...
3404 pagesize = info.dwPageSize << 3;
3405 allocsize = info.dwAllocationGranularity;
3407 /* This scheme fails eventually if request for contiguous
3408 * block is denied so reserve big blocks - this is only
3409 * address space not memory ...
3411 if (brk+need >= reserved)
3413 DWORD size = 64*1024*1024;
3415 if (committed && reserved && committed < reserved)
3417 /* Commit last of previous chunk cannot span allocations */
3418 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
3420 committed = reserved;
3422 /* Reserve some (more) space
3423 * Note this is a little sneaky, 1st call passes NULL as reserved
3424 * so lets system choose where we start, subsequent calls pass
3425 * the old end address so ask for a contiguous block
3427 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
3430 reserved = addr+size;
3445 if (brk > committed)
3447 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
3448 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
3463 win32_malloc(size_t size)
3465 return malloc(size);
3469 win32_calloc(size_t numitems, size_t size)
3471 return calloc(numitems,size);
3475 win32_realloc(void *block, size_t size)
3477 return realloc(block,size);
3481 win32_free(void *block)
3488 win32_open_osfhandle(long handle, int flags)
3490 #ifdef USE_FIXED_OSFHANDLE
3492 return my_open_osfhandle(handle, flags);
3494 return _open_osfhandle(handle, flags);
3498 win32_get_osfhandle(int fd)
3500 return _get_osfhandle(fd);
3504 win32_dynaload(const char* filename)
3509 WCHAR wfilename[MAX_PATH+1];
3510 A2WHELPER(filename, wfilename, sizeof(wfilename));
3511 hModule = LoadLibraryExW(PerlDir_mapW(wfilename), NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
3514 hModule = LoadLibraryExA(PerlDir_mapA(filename), NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
3527 /* Make the host for current directory */
3528 char* ptr = PerlEnv_get_childdir();
3531 * then it worked, set PV valid,
3532 * else return 'undef'
3535 SV *sv = sv_newmortal();
3537 PerlEnv_free_childdir(ptr);
3552 Perl_croak(aTHX_ "usage: Win32::SetCurrentDirectory($cwd)");
3553 if (!PerlDir_chdir(SvPV_nolen(ST(0))))
3560 XS(w32_GetNextAvailDrive)
3564 char root[] = "_:\\";
3569 if (GetDriveType(root) == 1) {
3578 XS(w32_GetLastError)
3582 XSRETURN_IV(GetLastError());
3586 XS(w32_SetLastError)
3590 Perl_croak(aTHX_ "usage: Win32::SetLastError($error)");
3591 SetLastError(SvIV(ST(0)));
3599 char *name = w32_getlogin_buffer;
3600 DWORD size = sizeof(w32_getlogin_buffer);
3602 if (GetUserName(name,&size)) {
3603 /* size includes NULL */
3604 ST(0) = sv_2mortal(newSVpvn(name,size-1));
3614 char name[MAX_COMPUTERNAME_LENGTH+1];
3615 DWORD size = sizeof(name);
3617 if (GetComputerName(name,&size)) {
3618 /* size does NOT include NULL :-( */
3619 ST(0) = sv_2mortal(newSVpvn(name,size));
3630 HINSTANCE hNetApi32 = LoadLibrary("netapi32.dll");
3631 DWORD (__stdcall *pfnNetApiBufferFree)(LPVOID Buffer);
3632 DWORD (__stdcall *pfnNetWkstaGetInfo)(LPWSTR servername, DWORD level,
3636 pfnNetApiBufferFree = (DWORD (__stdcall *)(void *))
3637 GetProcAddress(hNetApi32, "NetApiBufferFree");
3638 pfnNetWkstaGetInfo = (DWORD (__stdcall *)(LPWSTR, DWORD, void *))
3639 GetProcAddress(hNetApi32, "NetWkstaGetInfo");
3642 if (hNetApi32 && pfnNetWkstaGetInfo && pfnNetApiBufferFree) {
3643 /* this way is more reliable, in case user has a local account. */
3645 DWORD dnamelen = sizeof(dname);
3647 DWORD wki100_platform_id;
3648 LPWSTR wki100_computername;
3649 LPWSTR wki100_langroup;
3650 DWORD wki100_ver_major;
3651 DWORD wki100_ver_minor;
3653 /* NERR_Success *is* 0*/
3654 if (0 == pfnNetWkstaGetInfo(NULL, 100, &pwi)) {
3655 if (pwi->wki100_langroup && *(pwi->wki100_langroup)) {
3656 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_langroup,
3657 -1, (LPSTR)dname, dnamelen, NULL, NULL);
3660 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_computername,
3661 -1, (LPSTR)dname, dnamelen, NULL, NULL);
3663 pfnNetApiBufferFree(pwi);
3664 FreeLibrary(hNetApi32);
3667 FreeLibrary(hNetApi32);
3670 /* Win95 doesn't have NetWksta*(), so do it the old way */
3672 DWORD size = sizeof(name);
3674 FreeLibrary(hNetApi32);
3675 if (GetUserName(name,&size)) {
3676 char sid[ONE_K_BUFSIZE];
3677 DWORD sidlen = sizeof(sid);
3679 DWORD dnamelen = sizeof(dname);
3681 if (LookupAccountName(NULL, name, (PSID)&sid, &sidlen,
3682 dname, &dnamelen, &snu)) {
3683 XSRETURN_PV(dname); /* all that for this */
3695 DWORD flags, filecomplen;
3696 if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
3697 &flags, fsname, sizeof(fsname))) {
3698 if (GIMME_V == G_ARRAY) {
3699 XPUSHs(sv_2mortal(newSVpvn(fsname,strlen(fsname))));
3700 XPUSHs(sv_2mortal(newSViv(flags)));
3701 XPUSHs(sv_2mortal(newSViv(filecomplen)));
3706 XSRETURN_PV(fsname);
3712 XS(w32_GetOSVersion)
3715 OSVERSIONINFOA osver;
3718 OSVERSIONINFOW osverw;
3719 char szCSDVersion[sizeof(osverw.szCSDVersion)];
3720 osverw.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
3721 if (!GetVersionExW(&osverw)) {
3724 W2AHELPER(osverw.szCSDVersion, szCSDVersion, sizeof(szCSDVersion));
3725 XPUSHs(newSVpvn(szCSDVersion, strlen(szCSDVersion)));
3726 osver.dwMajorVersion = osverw.dwMajorVersion;
3727 osver.dwMinorVersion = osverw.dwMinorVersion;
3728 osver.dwBuildNumber = osverw.dwBuildNumber;
3729 osver.dwPlatformId = osverw.dwPlatformId;
3732 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOA);
3733 if (!GetVersionExA(&osver)) {
3736 XPUSHs(newSVpvn(osver.szCSDVersion, strlen(osver.szCSDVersion)));
3738 XPUSHs(newSViv(osver.dwMajorVersion));
3739 XPUSHs(newSViv(osver.dwMinorVersion));
3740 XPUSHs(newSViv(osver.dwBuildNumber));
3741 XPUSHs(newSViv(osver.dwPlatformId));
3750 XSRETURN_IV(IsWinNT());
3758 XSRETURN_IV(IsWin95());
3762 XS(w32_FormatMessage)
3766 char msgbuf[ONE_K_BUFSIZE];
3769 Perl_croak(aTHX_ "usage: Win32::FormatMessage($errno)");
3772 WCHAR wmsgbuf[ONE_K_BUFSIZE];
3773 if (FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM,
3774 &source, SvIV(ST(0)), 0,
3775 wmsgbuf, ONE_K_BUFSIZE-1, NULL))
3777 W2AHELPER(wmsgbuf, msgbuf, sizeof(msgbuf));
3778 XSRETURN_PV(msgbuf);
3782 if (FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM,
3783 &source, SvIV(ST(0)), 0,
3784 msgbuf, sizeof(msgbuf)-1, NULL))
3785 XSRETURN_PV(msgbuf);
3796 PROCESS_INFORMATION stProcInfo;
3797 STARTUPINFO stStartInfo;
3798 BOOL bSuccess = FALSE;
3801 Perl_croak(aTHX_ "usage: Win32::Spawn($cmdName, $args, $PID)");
3803 cmd = SvPV_nolen(ST(0));
3804 args = SvPV_nolen(ST(1));
3806 memset(&stStartInfo, 0, sizeof(stStartInfo)); /* Clear the block */
3807 stStartInfo.cb = sizeof(stStartInfo); /* Set the structure size */
3808 stStartInfo.dwFlags = STARTF_USESHOWWINDOW; /* Enable wShowWindow control */
3809 stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE; /* Start min (normal) */
3812 cmd, /* Image path */
3813 args, /* Arguments for command line */
3814 NULL, /* Default process security */
3815 NULL, /* Default thread security */
3816 FALSE, /* Must be TRUE to use std handles */
3817 NORMAL_PRIORITY_CLASS, /* No special scheduling */
3818 NULL, /* Inherit our environment block */
3819 NULL, /* Inherit our currrent directory */
3820 &stStartInfo, /* -> Startup info */
3821 &stProcInfo)) /* <- Process info (if OK) */
3823 CloseHandle(stProcInfo.hThread);/* library source code does this. */
3824 sv_setiv(ST(2), stProcInfo.dwProcessId);
3827 XSRETURN_IV(bSuccess);
3831 XS(w32_GetTickCount)
3834 DWORD msec = GetTickCount();
3842 XS(w32_GetShortPathName)
3849 Perl_croak(aTHX_ "usage: Win32::GetShortPathName($longPathName)");
3851 shortpath = sv_mortalcopy(ST(0));
3852 SvUPGRADE(shortpath, SVt_PV);
3853 /* src == target is allowed */
3855 len = GetShortPathName(SvPVX(shortpath),
3858 } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
3860 SvCUR_set(shortpath,len);
3868 XS(w32_GetFullPathName)
3877 Perl_croak(aTHX_ "usage: Win32::GetFullPathName($filename)");
3880 fullpath = sv_mortalcopy(filename);
3881 SvUPGRADE(fullpath, SVt_PV);
3883 len = GetFullPathName(SvPVX(filename),
3887 } while (len >= SvLEN(fullpath) && sv_grow(fullpath,len+1));
3889 if (GIMME_V == G_ARRAY) {
3891 XST_mPV(1,filepart);
3892 len = filepart - SvPVX(fullpath);
3895 SvCUR_set(fullpath,len);
3903 XS(w32_GetLongPathName)
3907 char tmpbuf[MAX_PATH+1];
3912 Perl_croak(aTHX_ "usage: Win32::GetLongPathName($pathname)");
3915 pathstr = SvPV(path,len);
3916 strcpy(tmpbuf, pathstr);
3917 pathstr = win32_longpath(tmpbuf);
3919 ST(0) = sv_2mortal(newSVpvn(pathstr, strlen(pathstr)));
3930 Perl_croak(aTHX_ "usage: Win32::Sleep($milliseconds)");
3941 Perl_croak(aTHX_ "usage: Win32::CopyFile($from, $to, $overwrite)");
3943 WCHAR wSourceFile[MAX_PATH+1];
3944 WCHAR wDestFile[MAX_PATH+1];
3945 A2WHELPER(SvPV_nolen(ST(0)), wSourceFile, sizeof(wSourceFile));
3946 wcscpy(wSourceFile, PerlDir_mapW(wSourceFile));
3947 A2WHELPER(SvPV_nolen(ST(1)), wDestFile, sizeof(wDestFile));
3948 bResult = CopyFileW(wSourceFile, PerlDir_mapW(wDestFile), !SvTRUE(ST(2)));
3951 char szSourceFile[MAX_PATH+1];
3952 strcpy(szSourceFile, PerlDir_mapA(SvPV_nolen(ST(0))));
3953 bResult = CopyFileA(szSourceFile, PerlDir_mapA(SvPV_nolen(ST(1))), !SvTRUE(ST(2)));
3962 Perl_init_os_extras(void)
3965 char *file = __FILE__;
3968 /* these names are Activeware compatible */
3969 newXS("Win32::GetCwd", w32_GetCwd, file);
3970 newXS("Win32::SetCwd", w32_SetCwd, file);
3971 newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
3972 newXS("Win32::GetLastError", w32_GetLastError, file);
3973 newXS("Win32::SetLastError", w32_SetLastError, file);
3974 newXS("Win32::LoginName", w32_LoginName, file);
3975 newXS("Win32::NodeName", w32_NodeName, file);
3976 newXS("Win32::DomainName", w32_DomainName, file);
3977 newXS("Win32::FsType", w32_FsType, file);
3978 newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
3979 newXS("Win32::IsWinNT", w32_IsWinNT, file);
3980 newXS("Win32::IsWin95", w32_IsWin95, file);
3981 newXS("Win32::FormatMessage", w32_FormatMessage, file);
3982 newXS("Win32::Spawn", w32_Spawn, file);
3983 newXS("Win32::GetTickCount", w32_GetTickCount, file);
3984 newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
3985 newXS("Win32::GetFullPathName", w32_GetFullPathName, file);
3986 newXS("Win32::GetLongPathName", w32_GetLongPathName, file);
3987 newXS("Win32::CopyFile", w32_CopyFile, file);
3988 newXS("Win32::Sleep", w32_Sleep, file);
3990 /* XXX Bloat Alert! The following Activeware preloads really
3991 * ought to be part of Win32::Sys::*, so they're not included
3994 /* LookupAccountName
3996 * InitiateSystemShutdown
3997 * AbortSystemShutdown
3998 * ExpandEnvrironmentStrings
4003 Perl_win32_init(int *argcp, char ***argvp)
4005 /* Disable floating point errors, Perl will trap the ones we
4006 * care about. VC++ RTL defaults to switching these off
4007 * already, but the Borland RTL doesn't. Since we don't
4008 * want to be at the vendor's whim on the default, we set
4009 * it explicitly here.
4011 #if !defined(_ALPHA_) && !defined(__GNUC__)
4012 _control87(MCW_EM, MCW_EM);
4018 win32_get_child_IO(child_IO_table* ptbl)
4020 ptbl->childStdIn = GetStdHandle(STD_INPUT_HANDLE);
4021 ptbl->childStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
4022 ptbl->childStdErr = GetStdHandle(STD_ERROR_HANDLE);
4025 #ifdef HAVE_INTERP_INTERN
4028 # undef Perl_sys_intern_init
4029 # define Perl_sys_intern_init CPerlObj::Perl_sys_intern_init
4030 # undef Perl_sys_intern_dup
4031 # define Perl_sys_intern_dup CPerlObj::Perl_sys_intern_dup
4036 Perl_sys_intern_init(pTHX)
4038 w32_perlshell_tokens = Nullch;
4039 w32_perlshell_vec = (char**)NULL;
4040 w32_perlshell_items = 0;
4041 w32_fdpid = newAV();
4042 New(1313, w32_children, 1, child_tab);
4043 w32_num_children = 0;
4044 # ifdef USE_ITHREADS
4046 New(1313, w32_pseudo_children, 1, child_tab);
4047 w32_num_pseudo_children = 0;
4049 w32_init_socktype = 0;
4052 # ifdef USE_ITHREADS
4055 Perl_sys_intern_dup(pTHX_ struct interp_intern *src, struct interp_intern *dst)
4057 dst->perlshell_tokens = Nullch;
4058 dst->perlshell_vec = (char**)NULL;
4059 dst->perlshell_items = 0;
4060 dst->fdpid = newAV();
4061 Newz(1313, dst->children, 1, child_tab);
4063 Newz(1313, dst->pseudo_children, 1, child_tab);
4064 dst->thr_intern.Winit_socktype = src->thr_intern.Winit_socktype;
4066 # endif /* USE_ITHREADS */
4067 #endif /* HAVE_INTERP_INTERN */
4075 win32_free_argvw(pTHXo_ void *ptr)
4077 char** argv = (char**)ptr;
4084 typedef LPWSTR* (WINAPI CLTARGVW)(LPCWSTR lpCommandLine, int * pNumArgs);
4085 /* load shell32.dll on demand (reduces number of DLLs loaded on startup by 1/3)
4088 win32_argv2utf8(int argc, char** argv)
4093 HANDLE hDll = LoadLibraryA("shell32.dll");
4094 CLTARGVW *pCommandLineToArgvW = NULL;
4095 LPWSTR* lpwStr = NULL;
4096 if (hDll && (pCommandLineToArgvW = (CLTARGVW*)GetProcAddress(hDll, "CommandLineToArgvW"))) {
4097 lpwStr = (*pCommandLineToArgvW)(GetCommandLineW(), &wargc);
4099 if (lpwStr && argc) {
4101 length = WideCharToMultiByte(CP_UTF8, 0, lpwStr[--wargc], -1, NULL, 0, NULL, NULL);
4102 Newz(0, psz, length, char);
4103 WideCharToMultiByte(CP_UTF8, 0, lpwStr[wargc], -1, psz, length, NULL, NULL);
4106 call_atexit(win32_free_argvw, argv);
4110 GlobalFree((HGLOBAL)lpwStr);