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>
58 /* Mingw32 defaults to globing command line
59 * So we turn it off like this:
64 #if defined(__MINGW32__)
65 /* Mingw32 is missing some prototypes */
66 FILE * _wfopen(LPCWSTR wszFileName, LPCWSTR wszMode);
67 FILE * _wfdopen(int nFd, LPCWSTR wszMode);
68 FILE * _freopen(LPCWSTR wszFileName, LPCWSTR wszMode, FILE * pOldStream);
73 #if defined(__BORLANDC__)
75 # define _utimbuf utimbuf
80 #define EXECF_SPAWN_NOWAIT 3
82 #if defined(PERL_IMPLICIT_SYS)
83 # undef win32_get_privlib
84 # define win32_get_privlib g_win32_get_privlib
85 # undef win32_get_sitelib
86 # define win32_get_sitelib g_win32_get_sitelib
88 # define do_spawn g_do_spawn
90 # define getlogin g_getlogin
93 #if defined(PERL_OBJECT)
95 # define do_aspawn g_do_aspawn
97 # define Perl_do_exec g_do_exec
100 static void get_shell(void);
101 static long tokenize(const char *str, char **dest, char ***destv);
102 int do_spawn2(char *cmd, int exectype);
103 static BOOL has_shell_metachars(char *ptr);
104 static long filetime_to_clock(PFILETIME ft);
105 static BOOL filetime_from_time(PFILETIME ft, time_t t);
106 static char * get_emd_part(SV **leading, char *trailing, ...);
107 static void remove_dead_process(long deceased);
108 static long find_pid(int pid);
109 static char * qualified_path(const char *cmd);
111 static void remove_dead_pseudo_process(long child);
112 static long find_pseudo_pid(int pid);
116 HANDLE w32_perldll_handle = INVALID_HANDLE_VALUE;
117 char w32_module_name[MAX_PATH+1];
120 static DWORD w32_platform = (DWORD)-1;
122 #define ONE_K_BUFSIZE 1024
127 return (win32_os_id() == VER_PLATFORM_WIN32_WINDOWS);
133 return (win32_os_id() == VER_PLATFORM_WIN32_NT);
137 set_w32_module_name(void)
140 GetModuleFileName((HMODULE)((w32_perldll_handle == INVALID_HANDLE_VALUE)
141 ? GetModuleHandle(NULL)
142 : w32_perldll_handle),
143 w32_module_name, sizeof(w32_module_name));
145 /* try to get full path to binary (which may be mangled when perl is
146 * run from a 16-bit app) */
147 /*PerlIO_printf(Perl_debug_log, "Before %s\n", w32_module_name);*/
148 (void)win32_longpath(w32_module_name);
149 /*PerlIO_printf(Perl_debug_log, "After %s\n", w32_module_name);*/
151 /* normalize to forward slashes */
152 ptr = w32_module_name;
160 /* *svp (if non-NULL) is expected to be POK (valid allocated SvPVX(*svp)) */
162 get_regstr_from(HKEY hkey, const char *valuename, SV **svp)
164 /* Retrieve a REG_SZ or REG_EXPAND_SZ from the registry */
167 const char *subkey = "Software\\Perl";
171 retval = RegOpenKeyEx(hkey, subkey, 0, KEY_READ, &handle);
172 if (retval == ERROR_SUCCESS) {
174 retval = RegQueryValueEx(handle, valuename, 0, &type, NULL, &datalen);
175 if (retval == ERROR_SUCCESS && type == REG_SZ) {
178 *svp = sv_2mortal(newSVpvn("",0));
179 SvGROW(*svp, datalen);
180 retval = RegQueryValueEx(handle, valuename, 0, NULL,
181 (PBYTE)SvPVX(*svp), &datalen);
182 if (retval == ERROR_SUCCESS) {
184 SvCUR_set(*svp,datalen-1);
192 /* *svp (if non-NULL) is expected to be POK (valid allocated SvPVX(*svp)) */
194 get_regstr(const char *valuename, SV **svp)
196 char *str = get_regstr_from(HKEY_CURRENT_USER, valuename, svp);
198 str = get_regstr_from(HKEY_LOCAL_MACHINE, valuename, svp);
202 /* *prev_pathp (if non-NULL) is expected to be POK (valid allocated SvPVX(sv)) */
204 get_emd_part(SV **prev_pathp, char *trailing_path, ...)
208 char mod_name[MAX_PATH+1];
212 int oldsize, newsize;
215 va_start(ap, trailing_path);
216 strip = va_arg(ap, char *);
218 sprintf(base, "%d.%d", (int)PERL_REVISION, (int)PERL_VERSION);
219 baselen = strlen(base);
221 if (!*w32_module_name) {
222 set_w32_module_name();
224 strcpy(mod_name, w32_module_name);
225 ptr = strrchr(mod_name, '/');
226 while (ptr && strip) {
227 /* look for directories to skip back */
230 ptr = strrchr(mod_name, '/');
231 /* avoid stripping component if there is no slash,
232 * or it doesn't match ... */
233 if (!ptr || stricmp(ptr+1, strip) != 0) {
234 /* ... but not if component matches m|5\.$patchlevel.*| */
235 if (!ptr || !(*strip == '5' && *(ptr+1) == '5'
236 && strncmp(strip, base, baselen) == 0
237 && strncmp(ptr+1, base, baselen) == 0))
243 strip = va_arg(ap, char *);
251 strcpy(++ptr, trailing_path);
253 /* only add directory if it exists */
254 if (GetFileAttributes(mod_name) != (DWORD) -1) {
255 /* directory exists */
258 *prev_pathp = sv_2mortal(newSVpvn("",0));
259 sv_catpvn(*prev_pathp, ";", 1);
260 sv_catpv(*prev_pathp, mod_name);
261 return SvPVX(*prev_pathp);
268 win32_get_privlib(char *pl)
271 char *stdlib = "lib";
272 char buffer[MAX_PATH+1];
275 /* $stdlib = $HKCU{"lib-$]"} || $HKLM{"lib-$]"} || $HKCU{"lib"} || $HKLM{"lib"} || ""; */
276 sprintf(buffer, "%s-%s", stdlib, pl);
277 if (!get_regstr(buffer, &sv))
278 (void)get_regstr(stdlib, &sv);
280 /* $stdlib .= ";$EMD/../../lib" */
281 return get_emd_part(&sv, stdlib, ARCHNAME, "bin", Nullch);
285 win32_get_sitelib(char *pl)
288 char *sitelib = "sitelib";
290 char pathstr[MAX_PATH+1];
296 /* $HKCU{"sitelib-$]"} || $HKLM{"sitelib-$]"} . ---; */
297 sprintf(regstr, "%s-%s", sitelib, pl);
298 (void)get_regstr(regstr, &sv1);
301 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/site/$]/lib"; */
302 sprintf(pathstr, "site/%s/lib", pl);
303 (void)get_emd_part(&sv1, pathstr, ARCHNAME, "bin", pl, Nullch);
305 /* $HKCU{'sitelib'} || $HKLM{'sitelib'} . ---; */
306 (void)get_regstr(sitelib, &sv2);
309 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/site/lib"; */
310 (void)get_emd_part(&sv2, "site/lib", ARCHNAME, "bin", pl, Nullch);
319 sv_catpvn(sv1, ";", 1);
327 has_shell_metachars(char *ptr)
333 * Scan string looking for redirection (< or >) or pipe
334 * characters (|) that are not in a quoted string.
335 * Shell variable interpolation (%VAR%) can also happen inside strings.
367 #if !defined(PERL_IMPLICIT_SYS)
368 /* since the current process environment is being updated in util.c
369 * the library functions will get the correct environment
372 Perl_my_popen(pTHX_ char *cmd, char *mode)
375 #define fixcmd(x) { \
376 char *pspace = strchr((x),' '); \
379 while (p < pspace) { \
390 PERL_FLUSHALL_FOR_CHILD;
391 return win32_popen(cmd, mode);
395 Perl_my_pclose(pTHX_ PerlIO *fp)
397 return win32_pclose(fp);
401 DllExport unsigned long
404 static OSVERSIONINFO osver;
406 if (osver.dwPlatformId != w32_platform) {
407 memset(&osver, 0, sizeof(OSVERSIONINFO));
408 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
409 GetVersionEx(&osver);
410 w32_platform = osver.dwPlatformId;
412 return (unsigned long)w32_platform;
421 return -((int)w32_pseudo_id);
426 /* Tokenize a string. Words are null-separated, and the list
427 * ends with a doubled null. Any character (except null and
428 * including backslash) may be escaped by preceding it with a
429 * backslash (the backslash will be stripped).
430 * Returns number of words in result buffer.
433 tokenize(const char *str, char **dest, char ***destv)
435 char *retstart = Nullch;
436 char **retvstart = 0;
440 int slen = strlen(str);
442 register char **retv;
443 New(1307, ret, slen+2, char);
444 New(1308, retv, (slen+3)/2, char*);
452 if (*ret == '\\' && *str)
454 else if (*ret == ' ') {
470 retvstart[items] = Nullch;
483 if (!w32_perlshell_tokens) {
484 /* we don't use COMSPEC here for two reasons:
485 * 1. the same reason perl on UNIX doesn't use SHELL--rampant and
486 * uncontrolled unportability of the ensuing scripts.
487 * 2. PERL5SHELL could be set to a shell that may not be fit for
488 * interactive use (which is what most programs look in COMSPEC
491 const char* defaultshell = (IsWinNT()
492 ? "cmd.exe /x/c" : "command.com /c");
493 const char *usershell = getenv("PERL5SHELL");
494 w32_perlshell_items = tokenize(usershell ? usershell : defaultshell,
495 &w32_perlshell_tokens,
501 do_aspawn(void *vreally, void **vmark, void **vsp)
504 SV *really = (SV*)vreally;
505 SV **mark = (SV**)vmark;
517 New(1306, argv, (sp - mark) + w32_perlshell_items + 2, char*);
519 if (SvNIOKp(*(mark+1)) && !SvPOKp(*(mark+1))) {
524 while (++mark <= sp) {
525 if (*mark && (str = SvPV_nolen(*mark)))
532 status = win32_spawnvp(flag,
533 (const char*)(really ? SvPV_nolen(really) : argv[0]),
534 (const char* const*)argv);
536 if (status < 0 && (errno == ENOEXEC || errno == ENOENT)) {
537 /* possible shell-builtin, invoke with shell */
539 sh_items = w32_perlshell_items;
541 argv[index+sh_items] = argv[index];
542 while (--sh_items >= 0)
543 argv[sh_items] = w32_perlshell_vec[sh_items];
545 status = win32_spawnvp(flag,
546 (const char*)(really ? SvPV_nolen(really) : argv[0]),
547 (const char* const*)argv);
550 if (flag != P_NOWAIT) {
553 if (ckWARN(WARN_EXEC))
554 Perl_warner(aTHX_ WARN_EXEC, "Can't spawn \"%s\": %s", argv[0], strerror(errno));
559 PL_statusvalue = status;
566 do_spawn2(char *cmd, int exectype)
573 BOOL needToTry = TRUE;
576 /* Save an extra exec if possible. See if there are shell
577 * metacharacters in it */
578 if (!has_shell_metachars(cmd)) {
579 New(1301,argv, strlen(cmd) / 2 + 2, char*);
580 New(1302,cmd2, strlen(cmd) + 1, char);
583 for (s = cmd2; *s;) {
584 while (*s && isSPACE(*s))
588 while (*s && !isSPACE(*s))
597 status = win32_spawnvp(P_WAIT, argv[0],
598 (const char* const*)argv);
600 case EXECF_SPAWN_NOWAIT:
601 status = win32_spawnvp(P_NOWAIT, argv[0],
602 (const char* const*)argv);
605 status = win32_execvp(argv[0], (const char* const*)argv);
608 if (status != -1 || errno == 0)
618 New(1306, argv, w32_perlshell_items + 2, char*);
619 while (++i < w32_perlshell_items)
620 argv[i] = w32_perlshell_vec[i];
625 status = win32_spawnvp(P_WAIT, argv[0],
626 (const char* const*)argv);
628 case EXECF_SPAWN_NOWAIT:
629 status = win32_spawnvp(P_NOWAIT, argv[0],
630 (const char* const*)argv);
633 status = win32_execvp(argv[0], (const char* const*)argv);
639 if (exectype != EXECF_SPAWN_NOWAIT) {
642 if (ckWARN(WARN_EXEC))
643 Perl_warner(aTHX_ WARN_EXEC, "Can't %s \"%s\": %s",
644 (exectype == EXECF_EXEC ? "exec" : "spawn"),
645 cmd, strerror(errno));
650 PL_statusvalue = status;
658 return do_spawn2(cmd, EXECF_SPAWN);
662 do_spawn_nowait(char *cmd)
664 return do_spawn2(cmd, EXECF_SPAWN_NOWAIT);
668 Perl_do_exec(pTHX_ char *cmd)
670 do_spawn2(cmd, EXECF_EXEC);
674 /* The idea here is to read all the directory names into a string table
675 * (separated by nulls) and when one of the other dir functions is called
676 * return the pointer to the current file name.
679 win32_opendir(char *filename)
685 char scanname[MAX_PATH+3];
687 WIN32_FIND_DATAA aFindData;
688 WIN32_FIND_DATAW wFindData;
690 char buffer[MAX_PATH*2];
691 WCHAR wbuffer[MAX_PATH+1];
694 len = strlen(filename);
698 /* check to see if filename is a directory */
699 if (win32_stat(filename, &sbuf) < 0 || !S_ISDIR(sbuf.st_mode))
702 /* Get us a DIR structure */
703 Newz(1303, dirp, 1, DIR);
705 /* Create the search pattern */
706 strcpy(scanname, filename);
708 /* bare drive name means look in cwd for drive */
709 if (len == 2 && isALPHA(scanname[0]) && scanname[1] == ':') {
710 scanname[len++] = '.';
711 scanname[len++] = '/';
713 else if (scanname[len-1] != '/' && scanname[len-1] != '\\') {
714 scanname[len++] = '/';
716 scanname[len++] = '*';
717 scanname[len] = '\0';
719 /* do the FindFirstFile call */
721 A2WHELPER(scanname, wbuffer, sizeof(wbuffer));
722 fh = FindFirstFileW(PerlDir_mapW(wbuffer), &wFindData);
725 fh = FindFirstFileA(PerlDir_mapA(scanname), &aFindData);
728 if (fh == INVALID_HANDLE_VALUE) {
729 DWORD err = GetLastError();
730 /* FindFirstFile() fails on empty drives! */
732 case ERROR_FILE_NOT_FOUND:
734 case ERROR_NO_MORE_FILES:
735 case ERROR_PATH_NOT_FOUND:
738 case ERROR_NOT_ENOUGH_MEMORY:
749 /* now allocate the first part of the string table for
750 * the filenames that we find.
753 W2AHELPER(wFindData.cFileName, buffer, sizeof(buffer));
757 ptr = aFindData.cFileName;
764 New(1304, dirp->start, dirp->size, char);
765 strcpy(dirp->start, ptr);
767 dirp->end = dirp->curr = dirp->start;
773 /* Readdir just returns the current string pointer and bumps the
774 * string pointer to the nDllExport entry.
776 DllExport struct direct *
777 win32_readdir(DIR *dirp)
782 /* first set up the structure to return */
783 len = strlen(dirp->curr);
784 strcpy(dirp->dirstr.d_name, dirp->curr);
785 dirp->dirstr.d_namlen = len;
788 dirp->dirstr.d_ino = dirp->curr - dirp->start;
790 /* Now set up for the next call to readdir */
791 dirp->curr += len + 1;
792 if (dirp->curr >= dirp->end) {
796 WIN32_FIND_DATAW wFindData;
797 WIN32_FIND_DATAA aFindData;
798 char buffer[MAX_PATH*2];
800 /* finding the next file that matches the wildcard
801 * (which should be all of them in this directory!).
804 res = FindNextFileW(dirp->handle, &wFindData);
806 W2AHELPER(wFindData.cFileName, buffer, sizeof(buffer));
811 res = FindNextFileA(dirp->handle, &aFindData);
813 ptr = aFindData.cFileName;
816 long endpos = dirp->end - dirp->start;
817 long newsize = endpos + strlen(ptr) + 1;
818 /* bump the string table size by enough for the
819 * new name and it's null terminator */
820 while (newsize > dirp->size) {
821 long curpos = dirp->curr - dirp->start;
823 Renew(dirp->start, dirp->size, char);
824 dirp->curr = dirp->start + curpos;
826 strcpy(dirp->start + endpos, ptr);
827 dirp->end = dirp->start + newsize;
833 return &(dirp->dirstr);
839 /* Telldir returns the current string pointer position */
841 win32_telldir(DIR *dirp)
843 return (dirp->curr - dirp->start);
847 /* Seekdir moves the string pointer to a previously saved position
848 * (returned by telldir).
851 win32_seekdir(DIR *dirp, long loc)
853 dirp->curr = dirp->start + loc;
856 /* Rewinddir resets the string pointer to the start */
858 win32_rewinddir(DIR *dirp)
860 dirp->curr = dirp->start;
863 /* free the memory allocated by opendir */
865 win32_closedir(DIR *dirp)
868 if (dirp->handle != INVALID_HANDLE_VALUE)
869 FindClose(dirp->handle);
870 Safefree(dirp->start);
883 * Just pretend that everyone is a superuser. NT will let us know if
884 * we don\'t really have permission to do something.
887 #define ROOT_UID ((uid_t)0)
888 #define ROOT_GID ((gid_t)0)
917 return (auid == ROOT_UID ? 0 : -1);
923 return (agid == ROOT_GID ? 0 : -1);
930 char *buf = w32_getlogin_buffer;
931 DWORD size = sizeof(w32_getlogin_buffer);
932 if (GetUserName(buf,&size))
938 chown(const char *path, uid_t owner, gid_t group)
948 long child = w32_num_children;
949 while (--child >= 0) {
950 if (w32_child_pids[child] == pid)
957 remove_dead_process(long child)
961 CloseHandle(w32_child_handles[child]);
962 Move(&w32_child_handles[child+1], &w32_child_handles[child],
963 (w32_num_children-child-1), HANDLE);
964 Move(&w32_child_pids[child+1], &w32_child_pids[child],
965 (w32_num_children-child-1), DWORD);
972 find_pseudo_pid(int pid)
975 long child = w32_num_pseudo_children;
976 while (--child >= 0) {
977 if (w32_pseudo_child_pids[child] == pid)
984 remove_dead_pseudo_process(long child)
988 CloseHandle(w32_pseudo_child_handles[child]);
989 Move(&w32_pseudo_child_handles[child+1], &w32_pseudo_child_handles[child],
990 (w32_num_pseudo_children-child-1), HANDLE);
991 Move(&w32_pseudo_child_pids[child+1], &w32_pseudo_child_pids[child],
992 (w32_num_pseudo_children-child-1), DWORD);
993 w32_num_pseudo_children--;
999 win32_kill(int pid, int sig)
1005 /* it is a pseudo-forked child */
1006 long child = find_pseudo_pid(-pid);
1010 hProcess = w32_pseudo_child_handles[child];
1011 if (TerminateThread(hProcess, sig)) {
1012 remove_dead_pseudo_process(child);
1020 long child = find_pid(pid);
1024 hProcess = w32_child_handles[child];
1025 if (TerminateProcess(hProcess, sig)) {
1026 remove_dead_process(child);
1031 hProcess = OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid);
1035 if (TerminateProcess(hProcess, sig)) {
1036 CloseHandle(hProcess);
1050 DllExport unsigned int
1051 win32_sleep(unsigned int t)
1058 win32_stat(const char *path, struct stat *sbuf)
1061 char buffer[MAX_PATH+1];
1062 int l = strlen(path);
1064 WCHAR wbuffer[MAX_PATH+1];
1070 switch(path[l - 1]) {
1071 /* FindFirstFile() and stat() are buggy with a trailing
1072 * backslash, so change it to a forward slash :-( */
1074 strncpy(buffer, path, l-1);
1075 buffer[l - 1] = '/';
1079 /* FindFirstFile() is buggy with "x:", so add a dot :-( */
1081 if (l == 2 && isALPHA(path[0])) {
1082 buffer[0] = path[0];
1093 /* We *must* open & close the file once; otherwise file attribute changes */
1094 /* might not yet have propagated to "other" hard links of the same file. */
1095 /* This also gives us an opportunity to determine the number of links. */
1097 A2WHELPER(path, wbuffer, sizeof(wbuffer));
1098 pwbuffer = PerlDir_mapW(wbuffer);
1099 handle = CreateFileW(pwbuffer, 0, 0, NULL, OPEN_EXISTING, 0, NULL);
1102 path = PerlDir_mapA(path);
1104 handle = CreateFileA(path, 0, 0, NULL, OPEN_EXISTING, 0, NULL);
1106 if (handle != INVALID_HANDLE_VALUE) {
1107 BY_HANDLE_FILE_INFORMATION bhi;
1108 if (GetFileInformationByHandle(handle, &bhi))
1109 nlink = bhi.nNumberOfLinks;
1110 CloseHandle(handle);
1113 /* pwbuffer or path will be mapped correctly above */
1115 res = _wstat(pwbuffer, (struct _stat *)sbuf);
1118 res = stat(path, sbuf);
1120 sbuf->st_nlink = nlink;
1123 /* CRT is buggy on sharenames, so make sure it really isn't.
1124 * XXX using GetFileAttributesEx() will enable us to set
1125 * sbuf->st_*time (but note that's not available on the
1126 * Windows of 1995) */
1129 r = GetFileAttributesW(pwbuffer);
1132 r = GetFileAttributesA(path);
1134 if (r != 0xffffffff && (r & FILE_ATTRIBUTE_DIRECTORY)) {
1135 /* sbuf may still contain old garbage since stat() failed */
1136 Zero(sbuf, 1, struct stat);
1137 sbuf->st_mode = S_IFDIR | S_IREAD;
1139 if (!(r & FILE_ATTRIBUTE_READONLY))
1140 sbuf->st_mode |= S_IWRITE | S_IEXEC;
1145 if (l == 3 && isALPHA(path[0]) && path[1] == ':'
1146 && (path[2] == '\\' || path[2] == '/'))
1148 /* The drive can be inaccessible, some _stat()s are buggy */
1150 ? !GetVolumeInformationW(pwbuffer,NULL,0,NULL,NULL,NULL,NULL,0)
1151 : !GetVolumeInformationA(path,NULL,0,NULL,NULL,NULL,NULL,0)) {
1157 if (S_ISDIR(sbuf->st_mode))
1158 sbuf->st_mode |= S_IWRITE | S_IEXEC;
1159 else if (S_ISREG(sbuf->st_mode)) {
1161 if (l >= 4 && path[l-4] == '.') {
1162 const char *e = path + l - 3;
1163 if (strnicmp(e,"exe",3)
1164 && strnicmp(e,"bat",3)
1165 && strnicmp(e,"com",3)
1166 && (IsWin95() || strnicmp(e,"cmd",3)))
1167 sbuf->st_mode &= ~S_IEXEC;
1169 sbuf->st_mode |= S_IEXEC;
1172 sbuf->st_mode &= ~S_IEXEC;
1173 /* Propagate permissions to _group_ and _others_ */
1174 perms = sbuf->st_mode & (S_IREAD|S_IWRITE|S_IEXEC);
1175 sbuf->st_mode |= (perms>>3) | (perms>>6);
1182 /* Find the longname of a given path. path is destructively modified.
1183 * It should have space for at least MAX_PATH characters. */
1185 win32_longpath(char *path)
1187 WIN32_FIND_DATA fdata;
1189 char tmpbuf[MAX_PATH+1];
1190 char *tmpstart = tmpbuf;
1197 if (isALPHA(path[0]) && path[1] == ':' &&
1198 (path[2] == '/' || path[2] == '\\'))
1201 *tmpstart++ = path[0];
1205 else if ((path[0] == '/' || path[0] == '\\') &&
1206 (path[1] == '/' || path[1] == '\\'))
1209 *tmpstart++ = path[0];
1210 *tmpstart++ = path[1];
1211 /* copy machine name */
1212 while (*start && *start != '/' && *start != '\\')
1213 *tmpstart++ = *start++;
1215 *tmpstart++ = *start;
1217 /* copy share name */
1218 while (*start && *start != '/' && *start != '\\')
1219 *tmpstart++ = *start++;
1223 if (sep == '/' || sep == '\\')
1227 /* walk up to slash */
1228 while (*start && *start != '/' && *start != '\\')
1231 /* discard doubled slashes */
1232 while (*start && (start[1] == '/' || start[1] == '\\'))
1236 /* stop and find full name of component */
1238 fhand = FindFirstFile(path,&fdata);
1239 if (fhand != INVALID_HANDLE_VALUE) {
1240 strcpy(tmpstart, fdata.cFileName);
1241 tmpstart += strlen(fdata.cFileName);
1249 /* failed a step, just return without side effects */
1250 /*PerlIO_printf(Perl_debug_log, "Failed to find %s\n", path);*/
1255 strcpy(path,tmpbuf);
1259 #ifndef USE_WIN32_RTL_ENV
1262 win32_getenv(const char *name)
1265 WCHAR wBuffer[MAX_PATH+1];
1267 SV *curitem = Nullsv;
1270 A2WHELPER(name, wBuffer, sizeof(wBuffer));
1271 needlen = GetEnvironmentVariableW(wBuffer, NULL, 0);
1274 needlen = GetEnvironmentVariableA(name,NULL,0);
1276 curitem = sv_2mortal(newSVpvn("", 0));
1280 SvGROW(curitem, (needlen+1)*sizeof(WCHAR));
1281 needlen = GetEnvironmentVariableW(wBuffer,
1282 (WCHAR*)SvPVX(curitem),
1284 } while (needlen >= SvLEN(curitem)/sizeof(WCHAR));
1285 SvCUR_set(curitem, (needlen*sizeof(WCHAR))+1);
1286 acuritem = sv_2mortal(newSVsv(curitem));
1287 W2AHELPER((WCHAR*)SvPVX(acuritem), SvPVX(curitem), SvCUR(curitem));
1291 SvGROW(curitem, needlen+1);
1292 needlen = GetEnvironmentVariableA(name,SvPVX(curitem),
1294 } while (needlen >= SvLEN(curitem));
1295 SvCUR_set(curitem, needlen);
1299 /* allow any environment variables that begin with 'PERL'
1300 to be stored in the registry */
1301 if (strncmp(name, "PERL", 4) == 0)
1302 (void)get_regstr(name, &curitem);
1304 if (curitem && SvCUR(curitem))
1305 return SvPVX(curitem);
1311 win32_putenv(const char *name)
1318 int length, relval = -1;
1322 length = strlen(name)+1;
1323 New(1309,wCuritem,length,WCHAR);
1324 A2WHELPER(name, wCuritem, length*sizeof(WCHAR));
1325 wVal = wcschr(wCuritem, '=');
1328 if (SetEnvironmentVariableW(wCuritem, *wVal ? wVal : NULL))
1334 New(1309,curitem,strlen(name)+1,char);
1335 strcpy(curitem, name);
1336 val = strchr(curitem, '=');
1338 /* The sane way to deal with the environment.
1339 * Has these advantages over putenv() & co.:
1340 * * enables us to store a truly empty value in the
1341 * environment (like in UNIX).
1342 * * we don't have to deal with RTL globals, bugs and leaks.
1344 * Why you may want to enable USE_WIN32_RTL_ENV:
1345 * * environ[] and RTL functions will not reflect changes,
1346 * which might be an issue if extensions want to access
1347 * the env. via RTL. This cuts both ways, since RTL will
1348 * not see changes made by extensions that call the Win32
1349 * functions directly, either.
1353 if (SetEnvironmentVariableA(curitem, *val ? val : NULL))
1365 filetime_to_clock(PFILETIME ft)
1367 __int64 qw = ft->dwHighDateTime;
1369 qw |= ft->dwLowDateTime;
1370 qw /= 10000; /* File time ticks at 0.1uS, clock at 1mS */
1375 win32_times(struct tms *timebuf)
1380 if (GetProcessTimes(GetCurrentProcess(), &dummy, &dummy,
1382 timebuf->tms_utime = filetime_to_clock(&user);
1383 timebuf->tms_stime = filetime_to_clock(&kernel);
1384 timebuf->tms_cutime = 0;
1385 timebuf->tms_cstime = 0;
1388 /* That failed - e.g. Win95 fallback to clock() */
1389 clock_t t = clock();
1390 timebuf->tms_utime = t;
1391 timebuf->tms_stime = 0;
1392 timebuf->tms_cutime = 0;
1393 timebuf->tms_cstime = 0;
1398 /* fix utime() so it works on directories in NT */
1400 filetime_from_time(PFILETIME pFileTime, time_t Time)
1402 struct tm *pTM = localtime(&Time);
1403 SYSTEMTIME SystemTime;
1409 SystemTime.wYear = pTM->tm_year + 1900;
1410 SystemTime.wMonth = pTM->tm_mon + 1;
1411 SystemTime.wDay = pTM->tm_mday;
1412 SystemTime.wHour = pTM->tm_hour;
1413 SystemTime.wMinute = pTM->tm_min;
1414 SystemTime.wSecond = pTM->tm_sec;
1415 SystemTime.wMilliseconds = 0;
1417 return SystemTimeToFileTime(&SystemTime, &LocalTime) &&
1418 LocalFileTimeToFileTime(&LocalTime, pFileTime);
1422 win32_unlink(const char *filename)
1429 WCHAR wBuffer[MAX_PATH+1];
1432 A2WHELPER(filename, wBuffer, sizeof(wBuffer));
1433 pwBuffer = PerlDir_mapW(wBuffer);
1434 attrs = GetFileAttributesW(pwBuffer);
1435 if (attrs == 0xFFFFFFFF)
1437 if (attrs & FILE_ATTRIBUTE_READONLY) {
1438 (void)SetFileAttributesW(pwBuffer, attrs & ~FILE_ATTRIBUTE_READONLY);
1439 ret = _wunlink(pwBuffer);
1441 (void)SetFileAttributesW(pwBuffer, attrs);
1444 ret = _wunlink(pwBuffer);
1447 filename = PerlDir_mapA(filename);
1448 attrs = GetFileAttributesA(filename);
1449 if (attrs == 0xFFFFFFFF)
1451 if (attrs & FILE_ATTRIBUTE_READONLY) {
1452 (void)SetFileAttributesA(filename, attrs & ~FILE_ATTRIBUTE_READONLY);
1453 ret = unlink(filename);
1455 (void)SetFileAttributesA(filename, attrs);
1458 ret = unlink(filename);
1467 win32_utime(const char *filename, struct utimbuf *times)
1474 struct utimbuf TimeBuffer;
1475 WCHAR wbuffer[MAX_PATH+1];
1480 A2WHELPER(filename, wbuffer, sizeof(wbuffer));
1481 pwbuffer = PerlDir_mapW(wbuffer);
1482 rc = _wutime(pwbuffer, (struct _utimbuf*)times);
1485 filename = PerlDir_mapA(filename);
1486 rc = utime(filename, times);
1488 /* EACCES: path specifies directory or readonly file */
1489 if (rc == 0 || errno != EACCES /* || !IsWinNT() */)
1492 if (times == NULL) {
1493 times = &TimeBuffer;
1494 time(×->actime);
1495 times->modtime = times->actime;
1498 /* This will (and should) still fail on readonly files */
1500 handle = CreateFileW(pwbuffer, GENERIC_READ | GENERIC_WRITE,
1501 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1502 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1505 handle = CreateFileA(filename, GENERIC_READ | GENERIC_WRITE,
1506 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1507 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1509 if (handle == INVALID_HANDLE_VALUE)
1512 if (GetFileTime(handle, &ftCreate, &ftAccess, &ftWrite) &&
1513 filetime_from_time(&ftAccess, times->actime) &&
1514 filetime_from_time(&ftWrite, times->modtime) &&
1515 SetFileTime(handle, &ftCreate, &ftAccess, &ftWrite))
1520 CloseHandle(handle);
1525 win32_uname(struct utsname *name)
1527 struct hostent *hep;
1528 STRLEN nodemax = sizeof(name->nodename)-1;
1529 OSVERSIONINFO osver;
1531 memset(&osver, 0, sizeof(OSVERSIONINFO));
1532 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1533 if (GetVersionEx(&osver)) {
1535 switch (osver.dwPlatformId) {
1536 case VER_PLATFORM_WIN32_WINDOWS:
1537 strcpy(name->sysname, "Windows");
1539 case VER_PLATFORM_WIN32_NT:
1540 strcpy(name->sysname, "Windows NT");
1542 case VER_PLATFORM_WIN32s:
1543 strcpy(name->sysname, "Win32s");
1546 strcpy(name->sysname, "Win32 Unknown");
1551 sprintf(name->release, "%d.%d",
1552 osver.dwMajorVersion, osver.dwMinorVersion);
1555 sprintf(name->version, "Build %d",
1556 osver.dwPlatformId == VER_PLATFORM_WIN32_NT
1557 ? osver.dwBuildNumber : (osver.dwBuildNumber & 0xffff));
1558 if (osver.szCSDVersion[0]) {
1559 char *buf = name->version + strlen(name->version);
1560 sprintf(buf, " (%s)", osver.szCSDVersion);
1564 *name->sysname = '\0';
1565 *name->version = '\0';
1566 *name->release = '\0';
1570 hep = win32_gethostbyname("localhost");
1572 STRLEN len = strlen(hep->h_name);
1573 if (len <= nodemax) {
1574 strcpy(name->nodename, hep->h_name);
1577 strncpy(name->nodename, hep->h_name, nodemax);
1578 name->nodename[nodemax] = '\0';
1583 if (!GetComputerName(name->nodename, &sz))
1584 *name->nodename = '\0';
1587 /* machine (architecture) */
1591 GetSystemInfo(&info);
1593 #if defined(__BORLANDC__) || defined(__MINGW32__)
1594 switch (info.u.s.wProcessorArchitecture) {
1596 switch (info.wProcessorArchitecture) {
1598 case PROCESSOR_ARCHITECTURE_INTEL:
1599 arch = "x86"; break;
1600 case PROCESSOR_ARCHITECTURE_MIPS:
1601 arch = "mips"; break;
1602 case PROCESSOR_ARCHITECTURE_ALPHA:
1603 arch = "alpha"; break;
1604 case PROCESSOR_ARCHITECTURE_PPC:
1605 arch = "ppc"; break;
1607 arch = "unknown"; break;
1609 strcpy(name->machine, arch);
1615 win32_waitpid(int pid, int *status, int flags)
1619 if (pid == -1) /* XXX threadid == 1 ? */
1620 return win32_wait(status);
1623 long child = find_pseudo_pid(-pid);
1625 HANDLE hThread = w32_pseudo_child_handles[child];
1626 DWORD waitcode = WaitForSingleObject(hThread, INFINITE);
1627 if (waitcode != WAIT_FAILED) {
1628 if (GetExitCodeThread(hThread, &waitcode)) {
1629 *status = (int)((waitcode & 0xff) << 8);
1630 retval = (int)w32_pseudo_child_pids[child];
1631 remove_dead_pseudo_process(child);
1641 long child = find_pid(pid);
1643 HANDLE hProcess = w32_child_handles[child];
1644 DWORD waitcode = WaitForSingleObject(hProcess, INFINITE);
1645 if (waitcode != WAIT_FAILED) {
1646 if (GetExitCodeProcess(hProcess, &waitcode)) {
1647 *status = (int)((waitcode & 0xff) << 8);
1648 retval = (int)w32_child_pids[child];
1649 remove_dead_process(child);
1657 retval = cwait(status, pid, WAIT_CHILD);
1658 /* cwait() returns "correctly" on Borland */
1659 #ifndef __BORLANDC__
1665 return retval >= 0 ? pid : retval;
1669 win32_wait(int *status)
1671 /* XXX this wait emulation only knows about processes
1672 * spawned via win32_spawnvp(P_NOWAIT, ...).
1676 DWORD exitcode, waitcode;
1679 if (w32_num_pseudo_children) {
1680 waitcode = WaitForMultipleObjects(w32_num_pseudo_children,
1681 w32_pseudo_child_handles,
1684 if (waitcode != WAIT_FAILED) {
1685 if (waitcode >= WAIT_ABANDONED_0
1686 && waitcode < WAIT_ABANDONED_0 + w32_num_pseudo_children)
1687 i = waitcode - WAIT_ABANDONED_0;
1689 i = waitcode - WAIT_OBJECT_0;
1690 if (GetExitCodeThread(w32_pseudo_child_handles[i], &exitcode)) {
1691 *status = (int)((exitcode & 0xff) << 8);
1692 retval = (int)w32_pseudo_child_pids[i];
1693 remove_dead_pseudo_process(i);
1700 if (!w32_num_children) {
1705 /* if a child exists, wait for it to die */
1706 waitcode = WaitForMultipleObjects(w32_num_children,
1710 if (waitcode != WAIT_FAILED) {
1711 if (waitcode >= WAIT_ABANDONED_0
1712 && waitcode < WAIT_ABANDONED_0 + w32_num_children)
1713 i = waitcode - WAIT_ABANDONED_0;
1715 i = waitcode - WAIT_OBJECT_0;
1716 if (GetExitCodeProcess(w32_child_handles[i], &exitcode) ) {
1717 *status = (int)((exitcode & 0xff) << 8);
1718 retval = (int)w32_child_pids[i];
1719 remove_dead_process(i);
1725 errno = GetLastError();
1731 static UINT timerid = 0;
1733 static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
1736 KillTimer(NULL,timerid);
1740 #endif /* !PERL_OBJECT */
1742 DllExport unsigned int
1743 win32_alarm(unsigned int sec)
1747 * the 'obvious' implentation is SetTimer() with a callback
1748 * which does whatever receiving SIGALRM would do
1749 * we cannot use SIGALRM even via raise() as it is not
1750 * one of the supported codes in <signal.h>
1752 * Snag is unless something is looking at the message queue
1753 * nothing happens :-(
1758 timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
1760 Perl_croak_nocontext("Cannot set timer");
1766 KillTimer(NULL,timerid);
1770 #endif /* !PERL_OBJECT */
1774 #ifdef HAVE_DES_FCRYPT
1775 extern char * des_fcrypt(const char *txt, const char *salt, char *cbuf);
1779 win32_crypt(const char *txt, const char *salt)
1782 #ifdef HAVE_DES_FCRYPT
1784 return des_fcrypt(txt, salt, w32_crypt_buffer);
1786 Perl_croak(aTHX_ "The crypt() function is unimplemented due to excessive paranoia.");
1791 /* C doesn't like repeat struct definitions */
1793 #if defined(USE_FIXED_OSFHANDLE) || defined(PERL_MSVCRT_READFIX)
1796 #define _CRTIMP __declspec(dllimport)
1800 * Control structure for lowio file handles
1803 long osfhnd; /* underlying OS file HANDLE */
1804 char osfile; /* attributes of file (e.g., open in text mode?) */
1805 char pipech; /* one char buffer for handles opened on pipes */
1807 CRITICAL_SECTION lock;
1812 * Array of arrays of control structures for lowio files.
1814 EXTERN_C _CRTIMP ioinfo* __pioinfo[];
1817 * Definition of IOINFO_L2E, the log base 2 of the number of elements in each
1818 * array of ioinfo structs.
1820 #define IOINFO_L2E 5
1823 * Definition of IOINFO_ARRAY_ELTS, the number of elements in ioinfo array
1825 #define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
1828 * Access macros for getting at an ioinfo struct and its fields from a
1831 #define _pioinfo(i) (__pioinfo[(i) >> IOINFO_L2E] + ((i) & (IOINFO_ARRAY_ELTS - 1)))
1832 #define _osfhnd(i) (_pioinfo(i)->osfhnd)
1833 #define _osfile(i) (_pioinfo(i)->osfile)
1834 #define _pipech(i) (_pioinfo(i)->pipech)
1838 #ifdef USE_FIXED_OSFHANDLE
1840 #define FOPEN 0x01 /* file handle open */
1841 #define FNOINHERIT 0x10 /* file handle opened O_NOINHERIT */
1842 #define FAPPEND 0x20 /* file handle opened O_APPEND */
1843 #define FDEV 0x40 /* file handle refers to device */
1844 #define FTEXT 0x80 /* file handle is in text mode */
1847 *int my_open_osfhandle(long osfhandle, int flags) - open C Runtime file handle
1850 * This function allocates a free C Runtime file handle and associates
1851 * it with the Win32 HANDLE specified by the first parameter. This is a
1852 * temperary fix for WIN95's brain damage GetFileType() error on socket
1853 * we just bypass that call for socket
1855 * This works with MSVC++ 4.0+ or GCC/Mingw32
1858 * long osfhandle - Win32 HANDLE to associate with C Runtime file handle.
1859 * int flags - flags to associate with C Runtime file handle.
1862 * returns index of entry in fh, if successful
1863 * return -1, if no free entry is found
1867 *******************************************************************************/
1870 * we fake up some parts of the CRT that aren't exported by MSVCRT.dll
1871 * this lets sockets work on Win9X with GCC and should fix the problems
1876 /* since we are not doing a dup2(), this works fine */
1878 #define _set_osfhnd(fh, osfh) (void)(_osfhnd(fh) = osfh)
1880 /* create an ioinfo entry, kill its handle, and steal the entry */
1885 HANDLE hF = CreateFile("NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
1886 int fh = _open_osfhandle((long)hF, 0);
1890 EnterCriticalSection(&(_pioinfo(fh)->lock));
1895 my_open_osfhandle(long osfhandle, int flags)
1898 char fileflags; /* _osfile flags */
1900 /* copy relevant flags from second parameter */
1903 if (flags & O_APPEND)
1904 fileflags |= FAPPEND;
1909 if (flags & O_NOINHERIT)
1910 fileflags |= FNOINHERIT;
1912 /* attempt to allocate a C Runtime file handle */
1913 if ((fh = _alloc_osfhnd()) == -1) {
1914 errno = EMFILE; /* too many open files */
1915 _doserrno = 0L; /* not an OS error */
1916 return -1; /* return error to caller */
1919 /* the file is open. now, set the info in _osfhnd array */
1920 _set_osfhnd(fh, osfhandle);
1922 fileflags |= FOPEN; /* mark as open */
1924 _osfile(fh) = fileflags; /* set osfile entry */
1925 LeaveCriticalSection(&_pioinfo(fh)->lock);
1927 return fh; /* return handle */
1930 #endif /* USE_FIXED_OSFHANDLE */
1932 /* simulate flock by locking a range on the file */
1934 #define LK_ERR(f,i) ((f) ? (i = 0) : (errno = GetLastError()))
1935 #define LK_LEN 0xffff0000
1938 win32_flock(int fd, int oper)
1946 Perl_croak_nocontext("flock() unimplemented on this platform");
1949 fh = (HANDLE)_get_osfhandle(fd);
1950 memset(&o, 0, sizeof(o));
1953 case LOCK_SH: /* shared lock */
1954 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
1956 case LOCK_EX: /* exclusive lock */
1957 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
1959 case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
1960 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
1962 case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
1963 LK_ERR(LockFileEx(fh,
1964 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
1965 0, LK_LEN, 0, &o),i);
1967 case LOCK_UN: /* unlock lock */
1968 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, 0, &o),i);
1970 default: /* unknown */
1981 * redirected io subsystem for all XS modules
1994 return (&(_environ));
1997 /* the rest are the remapped stdio routines */
2017 win32_ferror(FILE *fp)
2019 return (ferror(fp));
2024 win32_feof(FILE *fp)
2030 * Since the errors returned by the socket error function
2031 * WSAGetLastError() are not known by the library routine strerror
2032 * we have to roll our own.
2036 win32_strerror(int e)
2038 #ifndef __BORLANDC__ /* Borland intolerance */
2039 extern int sys_nerr;
2043 if (e < 0 || e > sys_nerr) {
2048 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
2049 w32_strerror_buffer,
2050 sizeof(w32_strerror_buffer), NULL) == 0)
2051 strcpy(w32_strerror_buffer, "Unknown Error");
2053 return w32_strerror_buffer;
2059 win32_str_os_error(void *sv, DWORD dwErr)
2063 dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
2064 |FORMAT_MESSAGE_IGNORE_INSERTS
2065 |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
2066 dwErr, 0, (char *)&sMsg, 1, NULL);
2067 /* strip trailing whitespace and period */
2070 --dwLen; /* dwLen doesn't include trailing null */
2071 } while (0 < dwLen && isSPACE(sMsg[dwLen]));
2072 if ('.' != sMsg[dwLen])
2077 sMsg = (char*)LocalAlloc(0, 64/**sizeof(TCHAR)*/);
2079 dwLen = sprintf(sMsg,
2080 "Unknown error #0x%lX (lookup 0x%lX)",
2081 dwErr, GetLastError());
2085 sv_setpvn((SV*)sv, sMsg, dwLen);
2092 win32_fprintf(FILE *fp, const char *format, ...)
2095 va_start(marker, format); /* Initialize variable arguments. */
2097 return (vfprintf(fp, format, marker));
2101 win32_printf(const char *format, ...)
2104 va_start(marker, format); /* Initialize variable arguments. */
2106 return (vprintf(format, marker));
2110 win32_vfprintf(FILE *fp, const char *format, va_list args)
2112 return (vfprintf(fp, format, args));
2116 win32_vprintf(const char *format, va_list args)
2118 return (vprintf(format, args));
2122 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
2124 return fread(buf, size, count, fp);
2128 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
2130 return fwrite(buf, size, count, fp);
2133 #define MODE_SIZE 10
2136 win32_fopen(const char *filename, const char *mode)
2139 WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH+1];
2145 if (stricmp(filename, "/dev/null")==0)
2149 A2WHELPER(mode, wMode, sizeof(wMode));
2150 A2WHELPER(filename, wBuffer, sizeof(wBuffer));
2151 f = _wfopen(PerlDir_mapW(wBuffer), wMode);
2154 f = fopen(PerlDir_mapA(filename), mode);
2155 /* avoid buffering headaches for child processes */
2156 if (f && *mode == 'a')
2157 win32_fseek(f, 0, SEEK_END);
2161 #ifndef USE_SOCKETS_AS_HANDLES
2163 #define fdopen my_fdopen
2167 win32_fdopen(int handle, const char *mode)
2170 WCHAR wMode[MODE_SIZE];
2173 A2WHELPER(mode, wMode, sizeof(wMode));
2174 f = _wfdopen(handle, wMode);
2177 f = fdopen(handle, (char *) mode);
2178 /* avoid buffering headaches for child processes */
2179 if (f && *mode == 'a')
2180 win32_fseek(f, 0, SEEK_END);
2185 win32_freopen(const char *path, const char *mode, FILE *stream)
2188 WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH+1];
2189 if (stricmp(path, "/dev/null")==0)
2193 A2WHELPER(mode, wMode, sizeof(wMode));
2194 A2WHELPER(path, wBuffer, sizeof(wBuffer));
2195 return _wfreopen(PerlDir_mapW(wBuffer), wMode, stream);
2197 return freopen(PerlDir_mapA(path), mode, stream);
2201 win32_fclose(FILE *pf)
2203 return my_fclose(pf); /* defined in win32sck.c */
2207 win32_fputs(const char *s,FILE *pf)
2209 return fputs(s, pf);
2213 win32_fputc(int c,FILE *pf)
2219 win32_ungetc(int c,FILE *pf)
2221 return ungetc(c,pf);
2225 win32_getc(FILE *pf)
2231 win32_fileno(FILE *pf)
2237 win32_clearerr(FILE *pf)
2244 win32_fflush(FILE *pf)
2250 win32_ftell(FILE *pf)
2256 win32_fseek(FILE *pf,long offset,int origin)
2258 return fseek(pf, offset, origin);
2262 win32_fgetpos(FILE *pf,fpos_t *p)
2264 return fgetpos(pf, p);
2268 win32_fsetpos(FILE *pf,const fpos_t *p)
2270 return fsetpos(pf, p);
2274 win32_rewind(FILE *pf)
2294 win32_fstat(int fd,struct stat *sbufptr)
2296 return fstat(fd,sbufptr);
2300 win32_pipe(int *pfd, unsigned int size, int mode)
2302 return _pipe(pfd, size, mode);
2306 * a popen() clone that respects PERL5SHELL
2310 win32_popen(const char *command, const char *mode)
2312 #ifdef USE_RTL_POPEN
2313 return _popen(command, mode);
2321 /* establish which ends read and write */
2322 if (strchr(mode,'w')) {
2323 stdfd = 0; /* stdin */
2327 else if (strchr(mode,'r')) {
2328 stdfd = 1; /* stdout */
2335 /* set the correct mode */
2336 if (strchr(mode,'b'))
2338 else if (strchr(mode,'t'))
2341 ourmode = _fmode & (O_TEXT | O_BINARY);
2343 /* the child doesn't inherit handles */
2344 ourmode |= O_NOINHERIT;
2346 if (win32_pipe( p, 512, ourmode) == -1)
2349 /* save current stdfd */
2350 if ((oldfd = win32_dup(stdfd)) == -1)
2353 /* make stdfd go to child end of pipe (implicitly closes stdfd) */
2354 /* stdfd will be inherited by the child */
2355 if (win32_dup2(p[child], stdfd) == -1)
2358 /* close the child end in parent */
2359 win32_close(p[child]);
2361 /* start the child */
2364 if ((childpid = do_spawn_nowait((char*)command)) == -1)
2367 /* revert stdfd to whatever it was before */
2368 if (win32_dup2(oldfd, stdfd) == -1)
2371 /* close saved handle */
2374 sv_setiv(*av_fetch(w32_fdpid, p[parent], TRUE), childpid);
2376 /* set process id so that it can be returned by perl's open() */
2377 PL_forkprocess = childpid;
2380 /* we have an fd, return a file stream */
2381 return (win32_fdopen(p[parent], (char *)mode));
2384 /* we don't need to check for errors here */
2388 win32_dup2(oldfd, stdfd);
2393 #endif /* USE_RTL_POPEN */
2401 win32_pclose(FILE *pf)
2403 #ifdef USE_RTL_POPEN
2407 int childpid, status;
2410 sv = *av_fetch(w32_fdpid, win32_fileno(pf), TRUE);
2412 childpid = SvIVX(sv);
2424 if (win32_waitpid(childpid, &status, 0) == -1)
2429 #endif /* USE_RTL_POPEN */
2435 LPCWSTR lpExistingFileName,
2436 LPSECURITY_ATTRIBUTES lpSecurityAttributes)
2439 WCHAR wFullName[MAX_PATH+1];
2440 LPVOID lpContext = NULL;
2441 WIN32_STREAM_ID StreamId;
2442 DWORD dwSize = (char*)&StreamId.cStreamName - (char*)&StreamId;
2447 BOOL (__stdcall *pfnBackupWrite)(HANDLE, LPBYTE, DWORD, LPDWORD,
2448 BOOL, BOOL, LPVOID*) =
2449 (BOOL (__stdcall *)(HANDLE, LPBYTE, DWORD, LPDWORD,
2450 BOOL, BOOL, LPVOID*))
2451 GetProcAddress(GetModuleHandle("kernel32.dll"), "BackupWrite");
2452 if (pfnBackupWrite == NULL)
2455 dwLen = GetFullPathNameW(lpFileName, MAX_PATH, wFullName, NULL);
2458 dwLen = (dwLen+1)*sizeof(WCHAR);
2460 handle = CreateFileW(lpExistingFileName, FILE_WRITE_ATTRIBUTES,
2461 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
2462 NULL, OPEN_EXISTING, 0, NULL);
2463 if (handle == INVALID_HANDLE_VALUE)
2466 StreamId.dwStreamId = BACKUP_LINK;
2467 StreamId.dwStreamAttributes = 0;
2468 StreamId.dwStreamNameSize = 0;
2469 #if defined(__BORLANDC__) || defined(__MINGW32__)
2470 StreamId.Size.u.HighPart = 0;
2471 StreamId.Size.u.LowPart = dwLen;
2473 StreamId.Size.HighPart = 0;
2474 StreamId.Size.LowPart = dwLen;
2477 bSuccess = pfnBackupWrite(handle, (LPBYTE)&StreamId, dwSize, &dwWritten,
2478 FALSE, FALSE, &lpContext);
2480 bSuccess = pfnBackupWrite(handle, (LPBYTE)wFullName, dwLen, &dwWritten,
2481 FALSE, FALSE, &lpContext);
2482 pfnBackupWrite(handle, NULL, 0, &dwWritten, TRUE, FALSE, &lpContext);
2485 CloseHandle(handle);
2490 win32_link(const char *oldname, const char *newname)
2493 BOOL (__stdcall *pfnCreateHardLinkW)(LPCWSTR,LPCWSTR,LPSECURITY_ATTRIBUTES);
2494 WCHAR wOldName[MAX_PATH+1];
2495 WCHAR wNewName[MAX_PATH+1];
2498 Perl_croak(aTHX_ PL_no_func, "link");
2500 pfnCreateHardLinkW =
2501 (BOOL (__stdcall *)(LPCWSTR, LPCWSTR, LPSECURITY_ATTRIBUTES))
2502 GetProcAddress(GetModuleHandle("kernel32.dll"), "CreateHardLinkW");
2503 if (pfnCreateHardLinkW == NULL)
2504 pfnCreateHardLinkW = Nt4CreateHardLinkW;
2506 if ((A2WHELPER(oldname, wOldName, sizeof(wOldName))) &&
2507 (A2WHELPER(newname, wNewName, sizeof(wNewName))) &&
2508 (wcscpy(wOldName, PerlDir_mapW(wOldName)),
2509 pfnCreateHardLinkW(PerlDir_mapW(wNewName), wOldName, NULL)))
2513 errno = (GetLastError() == ERROR_FILE_NOT_FOUND) ? ENOENT : EINVAL;
2518 win32_rename(const char *oname, const char *newname)
2520 WCHAR wOldName[MAX_PATH+1];
2521 WCHAR wNewName[MAX_PATH+1];
2522 char szOldName[MAX_PATH+1];
2523 char szNewName[MAX_PATH+1];
2527 /* XXX despite what the documentation says about MoveFileEx(),
2528 * it doesn't work under Windows95!
2531 DWORD dwFlags = MOVEFILE_COPY_ALLOWED;
2533 A2WHELPER(oname, wOldName, sizeof(wOldName));
2534 A2WHELPER(newname, wNewName, sizeof(wNewName));
2535 if (wcsicmp(wNewName, wOldName))
2536 dwFlags |= MOVEFILE_REPLACE_EXISTING;
2537 wcscpy(wOldName, PerlDir_mapW(wOldName));
2538 bResult = MoveFileExW(wOldName,PerlDir_mapW(wNewName), dwFlags);
2541 if (stricmp(newname, oname))
2542 dwFlags |= MOVEFILE_REPLACE_EXISTING;
2543 strcpy(szOldName, PerlDir_mapA(oname));
2544 bResult = MoveFileExA(szOldName,PerlDir_mapA(newname), dwFlags);
2547 DWORD err = GetLastError();
2549 case ERROR_BAD_NET_NAME:
2550 case ERROR_BAD_NETPATH:
2551 case ERROR_BAD_PATHNAME:
2552 case ERROR_FILE_NOT_FOUND:
2553 case ERROR_FILENAME_EXCED_RANGE:
2554 case ERROR_INVALID_DRIVE:
2555 case ERROR_NO_MORE_FILES:
2556 case ERROR_PATH_NOT_FOUND:
2569 char szTmpName[MAX_PATH+1];
2570 char dname[MAX_PATH+1];
2571 char *endname = Nullch;
2573 DWORD from_attr, to_attr;
2575 strcpy(szOldName, PerlDir_mapA(oname));
2576 strcpy(szNewName, PerlDir_mapA(newname));
2578 /* if oname doesn't exist, do nothing */
2579 from_attr = GetFileAttributes(szOldName);
2580 if (from_attr == 0xFFFFFFFF) {
2585 /* if newname exists, rename it to a temporary name so that we
2586 * don't delete it in case oname happens to be the same file
2587 * (but perhaps accessed via a different path)
2589 to_attr = GetFileAttributes(szNewName);
2590 if (to_attr != 0xFFFFFFFF) {
2591 /* if newname is a directory, we fail
2592 * XXX could overcome this with yet more convoluted logic */
2593 if (to_attr & FILE_ATTRIBUTE_DIRECTORY) {
2597 tmplen = strlen(szNewName);
2598 strcpy(szTmpName,szNewName);
2599 endname = szTmpName+tmplen;
2600 for (; endname > szTmpName ; --endname) {
2601 if (*endname == '/' || *endname == '\\') {
2606 if (endname > szTmpName)
2607 endname = strcpy(dname,szTmpName);
2611 /* get a temporary filename in same directory
2612 * XXX is this really the best we can do? */
2613 if (!GetTempFileName((LPCTSTR)endname, "plr", 0, szTmpName)) {
2617 DeleteFile(szTmpName);
2619 retval = rename(szNewName, szTmpName);
2626 /* rename oname to newname */
2627 retval = rename(szOldName, szNewName);
2629 /* if we created a temporary file before ... */
2630 if (endname != Nullch) {
2631 /* ...and rename succeeded, delete temporary file/directory */
2633 DeleteFile(szTmpName);
2634 /* else restore it to what it was */
2636 (void)rename(szTmpName, szNewName);
2643 win32_setmode(int fd, int mode)
2645 return setmode(fd, mode);
2649 win32_lseek(int fd, long offset, int origin)
2651 return lseek(fd, offset, origin);
2661 win32_open(const char *path, int flag, ...)
2666 WCHAR wBuffer[MAX_PATH+1];
2669 pmode = va_arg(ap, int);
2672 if (stricmp(path, "/dev/null")==0)
2676 A2WHELPER(path, wBuffer, sizeof(wBuffer));
2677 return _wopen(PerlDir_mapW(wBuffer), flag, pmode);
2679 return open(PerlDir_mapA(path), flag, pmode);
2701 win32_dup2(int fd1,int fd2)
2703 return dup2(fd1,fd2);
2706 #ifdef PERL_MSVCRT_READFIX
2708 #define LF 10 /* line feed */
2709 #define CR 13 /* carriage return */
2710 #define CTRLZ 26 /* ctrl-z means eof for text */
2711 #define FOPEN 0x01 /* file handle open */
2712 #define FEOFLAG 0x02 /* end of file has been encountered */
2713 #define FCRLF 0x04 /* CR-LF across read buffer (in text mode) */
2714 #define FPIPE 0x08 /* file handle refers to a pipe */
2715 #define FAPPEND 0x20 /* file handle opened O_APPEND */
2716 #define FDEV 0x40 /* file handle refers to device */
2717 #define FTEXT 0x80 /* file handle is in text mode */
2718 #define MAX_DESCRIPTOR_COUNT (64*32) /* this is the maximun that MSVCRT can handle */
2721 _fixed_read(int fh, void *buf, unsigned cnt)
2723 int bytes_read; /* number of bytes read */
2724 char *buffer; /* buffer to read to */
2725 int os_read; /* bytes read on OS call */
2726 char *p, *q; /* pointers into buffer */
2727 char peekchr; /* peek-ahead character */
2728 ULONG filepos; /* file position after seek */
2729 ULONG dosretval; /* o.s. return value */
2731 /* validate handle */
2732 if (((unsigned)fh >= (unsigned)MAX_DESCRIPTOR_COUNT) ||
2733 !(_osfile(fh) & FOPEN))
2735 /* out of range -- return error */
2737 _doserrno = 0; /* not o.s. error */
2742 * If lockinitflag is FALSE, assume fd is device
2743 * lockinitflag is set to TRUE by open.
2745 if (_pioinfo(fh)->lockinitflag)
2746 EnterCriticalSection(&(_pioinfo(fh)->lock)); /* lock file */
2748 bytes_read = 0; /* nothing read yet */
2749 buffer = (char*)buf;
2751 if (cnt == 0 || (_osfile(fh) & FEOFLAG)) {
2752 /* nothing to read or at EOF, so return 0 read */
2756 if ((_osfile(fh) & (FPIPE|FDEV)) && _pipech(fh) != LF) {
2757 /* a pipe/device and pipe lookahead non-empty: read the lookahead
2759 *buffer++ = _pipech(fh);
2762 _pipech(fh) = LF; /* mark as empty */
2767 if (!ReadFile((HANDLE)_osfhnd(fh), buffer, cnt, (LPDWORD)&os_read, NULL))
2769 /* ReadFile has reported an error. recognize two special cases.
2771 * 1. map ERROR_ACCESS_DENIED to EBADF
2773 * 2. just return 0 if ERROR_BROKEN_PIPE has occurred. it
2774 * means the handle is a read-handle on a pipe for which
2775 * all write-handles have been closed and all data has been
2778 if ((dosretval = GetLastError()) == ERROR_ACCESS_DENIED) {
2779 /* wrong read/write mode should return EBADF, not EACCES */
2781 _doserrno = dosretval;
2785 else if (dosretval == ERROR_BROKEN_PIPE) {
2795 bytes_read += os_read; /* update bytes read */
2797 if (_osfile(fh) & FTEXT) {
2798 /* now must translate CR-LFs to LFs in the buffer */
2800 /* set CRLF flag to indicate LF at beginning of buffer */
2801 /* if ((os_read != 0) && (*(char *)buf == LF)) */
2802 /* _osfile(fh) |= FCRLF; */
2804 /* _osfile(fh) &= ~FCRLF; */
2806 _osfile(fh) &= ~FCRLF;
2808 /* convert chars in the buffer: p is src, q is dest */
2810 while (p < (char *)buf + bytes_read) {
2812 /* if fh is not a device, set ctrl-z flag */
2813 if (!(_osfile(fh) & FDEV))
2814 _osfile(fh) |= FEOFLAG;
2815 break; /* stop translating */
2820 /* *p is CR, so must check next char for LF */
2821 if (p < (char *)buf + bytes_read - 1) {
2824 *q++ = LF; /* convert CR-LF to LF */
2827 *q++ = *p++; /* store char normally */
2830 /* This is the hard part. We found a CR at end of
2831 buffer. We must peek ahead to see if next char
2836 if (!ReadFile((HANDLE)_osfhnd(fh), &peekchr, 1,
2837 (LPDWORD)&os_read, NULL))
2838 dosretval = GetLastError();
2840 if (dosretval != 0 || os_read == 0) {
2841 /* couldn't read ahead, store CR */
2845 /* peekchr now has the extra character -- we now
2846 have several possibilities:
2847 1. disk file and char is not LF; just seek back
2849 2. disk file and char is LF; store LF, don't seek back
2850 3. pipe/device and char is LF; store LF.
2851 4. pipe/device and char isn't LF, store CR and
2852 put char in pipe lookahead buffer. */
2853 if (_osfile(fh) & (FDEV|FPIPE)) {
2854 /* non-seekable device */
2859 _pipech(fh) = peekchr;
2864 if (peekchr == LF) {
2865 /* nothing read yet; must make some
2868 /* turn on this flag for tell routine */
2869 _osfile(fh) |= FCRLF;
2872 HANDLE osHandle; /* o.s. handle value */
2874 if ((osHandle = (HANDLE)_get_osfhandle(fh)) != (HANDLE)-1)
2876 if ((filepos = SetFilePointer(osHandle, -1, NULL, FILE_CURRENT)) == -1)
2877 dosretval = GetLastError();
2888 /* we now change bytes_read to reflect the true number of chars
2890 bytes_read = q - (char *)buf;
2894 if (_pioinfo(fh)->lockinitflag)
2895 LeaveCriticalSection(&(_pioinfo(fh)->lock)); /* unlock file */
2900 #endif /* PERL_MSVCRT_READFIX */
2903 win32_read(int fd, void *buf, unsigned int cnt)
2905 #ifdef PERL_MSVCRT_READFIX
2906 return _fixed_read(fd, buf, cnt);
2908 return read(fd, buf, cnt);
2913 win32_write(int fd, const void *buf, unsigned int cnt)
2915 return write(fd, buf, cnt);
2919 win32_mkdir(const char *dir, int mode)
2923 WCHAR wBuffer[MAX_PATH+1];
2924 A2WHELPER(dir, wBuffer, sizeof(wBuffer));
2925 return _wmkdir(PerlDir_mapW(wBuffer));
2927 return mkdir(PerlDir_mapA(dir)); /* just ignore mode */
2931 win32_rmdir(const char *dir)
2935 WCHAR wBuffer[MAX_PATH+1];
2936 A2WHELPER(dir, wBuffer, sizeof(wBuffer));
2937 return _wrmdir(PerlDir_mapW(wBuffer));
2939 return rmdir(PerlDir_mapA(dir));
2943 win32_chdir(const char *dir)
2947 WCHAR wBuffer[MAX_PATH+1];
2948 A2WHELPER(dir, wBuffer, sizeof(wBuffer));
2949 return _wchdir(wBuffer);
2955 win32_access(const char *path, int mode)
2959 WCHAR wBuffer[MAX_PATH+1];
2960 A2WHELPER(path, wBuffer, sizeof(wBuffer));
2961 return _waccess(PerlDir_mapW(wBuffer), mode);
2963 return access(PerlDir_mapA(path), mode);
2967 win32_chmod(const char *path, int mode)
2971 WCHAR wBuffer[MAX_PATH+1];
2972 A2WHELPER(path, wBuffer, sizeof(wBuffer));
2973 return _wchmod(PerlDir_mapW(wBuffer), mode);
2975 return chmod(PerlDir_mapA(path), mode);
2980 create_command_line(const char* command, const char * const *args)
2984 char *cmd, *ptr, *arg;
2985 STRLEN len = strlen(command) + 1;
2987 for (index = 0; (ptr = (char*)args[index]) != NULL; ++index)
2988 len += strlen(ptr) + 1;
2990 New(1310, cmd, len, char);
2992 strcpy(ptr, command);
2994 for (index = 0; (arg = (char*)args[index]) != NULL; ++index) {
3004 qualified_path(const char *cmd)
3008 char *fullcmd, *curfullcmd;
3014 fullcmd = (char*)cmd;
3016 if (*fullcmd == '/' || *fullcmd == '\\')
3023 pathstr = win32_getenv("PATH");
3024 New(0, fullcmd, MAX_PATH+1, char);
3025 curfullcmd = fullcmd;
3030 /* start by appending the name to the current prefix */
3031 strcpy(curfullcmd, cmd);
3032 curfullcmd += cmdlen;
3034 /* if it doesn't end with '.', or has no extension, try adding
3035 * a trailing .exe first */
3036 if (cmd[cmdlen-1] != '.'
3037 && (cmdlen < 4 || cmd[cmdlen-4] != '.'))
3039 strcpy(curfullcmd, ".exe");
3040 res = GetFileAttributes(fullcmd);
3041 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
3046 /* that failed, try the bare name */
3047 res = GetFileAttributes(fullcmd);
3048 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
3051 /* quit if no other path exists, or if cmd already has path */
3052 if (!pathstr || !*pathstr || has_slash)
3055 /* skip leading semis */
3056 while (*pathstr == ';')
3059 /* build a new prefix from scratch */
3060 curfullcmd = fullcmd;
3061 while (*pathstr && *pathstr != ';') {
3062 if (*pathstr == '"') { /* foo;"baz;etc";bar */
3063 pathstr++; /* skip initial '"' */
3064 while (*pathstr && *pathstr != '"') {
3065 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
3066 *curfullcmd++ = *pathstr;
3070 pathstr++; /* skip trailing '"' */
3073 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
3074 *curfullcmd++ = *pathstr;
3079 pathstr++; /* skip trailing semi */
3080 if (curfullcmd > fullcmd /* append a dir separator */
3081 && curfullcmd[-1] != '/' && curfullcmd[-1] != '\\')
3083 *curfullcmd++ = '\\';
3091 /* The following are just place holders.
3092 * Some hosts may provide and environment that the OS is
3093 * not tracking, therefore, these host must provide that
3094 * environment and the current directory to CreateProcess
3104 free_childenv(void* d)
3113 char szfilename[(MAX_PATH+1)*2];
3115 WCHAR wfilename[MAX_PATH+1];
3116 GetCurrentDirectoryW(MAX_PATH+1, wfilename);
3117 W2AHELPER(wfilename, szfilename, sizeof(szfilename));
3120 GetCurrentDirectoryA(MAX_PATH+1, szfilename);
3123 New(0, ptr, strlen(szfilename)+1, char);
3124 strcpy(ptr, szfilename);
3129 free_childdir(char* d)
3136 /* XXX this needs to be made more compatible with the spawnvp()
3137 * provided by the various RTLs. In particular, searching for
3138 * *.{com,bat,cmd} files (as done by the RTLs) is unimplemented.
3139 * This doesn't significantly affect perl itself, because we
3140 * always invoke things using PERL5SHELL if a direct attempt to
3141 * spawn the executable fails.
3143 * XXX splitting and rejoining the commandline between do_aspawn()
3144 * and win32_spawnvp() could also be avoided.
3148 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
3150 #ifdef USE_RTL_SPAWNVP
3151 return spawnvp(mode, cmdname, (char * const *)argv);
3158 STARTUPINFO StartupInfo;
3159 PROCESS_INFORMATION ProcessInformation;
3162 char *cmd = create_command_line(cmdname, strcmp(cmdname, argv[0]) == 0
3164 char *fullcmd = Nullch;
3166 env = PerlEnv_get_childenv();
3167 dir = PerlEnv_get_childdir();
3170 case P_NOWAIT: /* asynch + remember result */
3171 if (w32_num_children >= MAXIMUM_WAIT_OBJECTS) {
3177 case P_WAIT: /* synchronous execution */
3179 default: /* invalid mode */
3184 memset(&StartupInfo,0,sizeof(StartupInfo));
3185 StartupInfo.cb = sizeof(StartupInfo);
3186 PerlEnv_get_child_IO(&tbl);
3187 StartupInfo.hStdInput = tbl.childStdIn;
3188 StartupInfo.hStdOutput = tbl.childStdOut;
3189 StartupInfo.hStdError = tbl.childStdErr;
3190 if (StartupInfo.hStdInput != INVALID_HANDLE_VALUE &&
3191 StartupInfo.hStdOutput != INVALID_HANDLE_VALUE &&
3192 StartupInfo.hStdError != INVALID_HANDLE_VALUE)
3194 StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
3197 create |= CREATE_NEW_CONSOLE;
3201 if (!CreateProcess(cmdname, /* search PATH to find executable */
3202 cmd, /* executable, and its arguments */
3203 NULL, /* process attributes */
3204 NULL, /* thread attributes */
3205 TRUE, /* inherit handles */
3206 create, /* creation flags */
3207 (LPVOID)env, /* inherit environment */
3208 dir, /* inherit cwd */
3210 &ProcessInformation))
3212 /* initial NULL argument to CreateProcess() does a PATH
3213 * search, but it always first looks in the directory
3214 * where the current process was started, which behavior
3215 * is undesirable for backward compatibility. So we
3216 * jump through our own hoops by picking out the path
3217 * we really want it to use. */
3219 fullcmd = qualified_path(cmdname);
3230 if (mode == P_NOWAIT) {
3231 /* asynchronous spawn -- store handle, return PID */
3232 w32_child_handles[w32_num_children] = ProcessInformation.hProcess;
3233 w32_child_pids[w32_num_children] = ProcessInformation.dwProcessId;
3234 ret = (int)ProcessInformation.dwProcessId;
3239 WaitForSingleObject(ProcessInformation.hProcess, INFINITE);
3240 GetExitCodeProcess(ProcessInformation.hProcess, &status);
3242 CloseHandle(ProcessInformation.hProcess);
3245 CloseHandle(ProcessInformation.hThread);
3248 PerlEnv_free_childenv(env);
3249 PerlEnv_free_childdir(dir);
3257 win32_execv(const char *cmdname, const char *const *argv)
3261 /* if this is a pseudo-forked child, we just want to spawn
3262 * the new program, and return */
3264 return spawnv(P_WAIT, cmdname, (char *const *)argv);
3266 return execv(cmdname, (char *const *)argv);
3270 win32_execvp(const char *cmdname, const char *const *argv)
3274 /* if this is a pseudo-forked child, we just want to spawn
3275 * the new program, and return */
3277 return win32_spawnvp(P_WAIT, cmdname, (char *const *)argv);
3279 return execvp(cmdname, (char *const *)argv);
3283 win32_perror(const char *str)
3289 win32_setbuf(FILE *pf, char *buf)
3295 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
3297 return setvbuf(pf, buf, type, size);
3301 win32_flushall(void)
3307 win32_fcloseall(void)
3313 win32_fgets(char *s, int n, FILE *pf)
3315 return fgets(s, n, pf);
3325 win32_fgetc(FILE *pf)
3331 win32_putc(int c, FILE *pf)
3337 win32_puts(const char *s)
3349 win32_putchar(int c)
3356 #ifndef USE_PERL_SBRK
3358 static char *committed = NULL;
3359 static char *base = NULL;
3360 static char *reserved = NULL;
3361 static char *brk = NULL;
3362 static DWORD pagesize = 0;
3363 static DWORD allocsize = 0;
3371 GetSystemInfo(&info);
3372 /* Pretend page size is larger so we don't perpetually
3373 * call the OS to commit just one page ...
3375 pagesize = info.dwPageSize << 3;
3376 allocsize = info.dwAllocationGranularity;
3378 /* This scheme fails eventually if request for contiguous
3379 * block is denied so reserve big blocks - this is only
3380 * address space not memory ...
3382 if (brk+need >= reserved)
3384 DWORD size = 64*1024*1024;
3386 if (committed && reserved && committed < reserved)
3388 /* Commit last of previous chunk cannot span allocations */
3389 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
3391 committed = reserved;
3393 /* Reserve some (more) space
3394 * Note this is a little sneaky, 1st call passes NULL as reserved
3395 * so lets system choose where we start, subsequent calls pass
3396 * the old end address so ask for a contiguous block
3398 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
3401 reserved = addr+size;
3416 if (brk > committed)
3418 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
3419 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
3434 win32_malloc(size_t size)
3436 return malloc(size);
3440 win32_calloc(size_t numitems, size_t size)
3442 return calloc(numitems,size);
3446 win32_realloc(void *block, size_t size)
3448 return realloc(block,size);
3452 win32_free(void *block)
3459 win32_open_osfhandle(long handle, int flags)
3461 #ifdef USE_FIXED_OSFHANDLE
3463 return my_open_osfhandle(handle, flags);
3465 return _open_osfhandle(handle, flags);
3469 win32_get_osfhandle(int fd)
3471 return _get_osfhandle(fd);
3475 win32_dynaload(const char* filename)
3480 WCHAR wfilename[MAX_PATH+1];
3481 A2WHELPER(filename, wfilename, sizeof(wfilename));
3482 hModule = LoadLibraryExW(PerlDir_mapW(wfilename), NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
3485 hModule = LoadLibraryExA(PerlDir_mapA(filename), NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
3498 /* Make the host for current directory */
3499 char* ptr = PerlEnv_get_childdir();
3502 * then it worked, set PV valid,
3503 * else return 'undef'
3506 SV *sv = sv_newmortal();
3508 PerlEnv_free_childdir(ptr);
3523 Perl_croak(aTHX_ "usage: Win32::SetCurrentDirectory($cwd)");
3524 if (!PerlDir_chdir(SvPV_nolen(ST(0))))
3531 XS(w32_GetNextAvailDrive)
3535 char root[] = "_:\\";
3540 if (GetDriveType(root) == 1) {
3549 XS(w32_GetLastError)
3553 XSRETURN_IV(GetLastError());
3557 XS(w32_SetLastError)
3561 Perl_croak(aTHX_ "usage: Win32::SetLastError($error)");
3562 SetLastError(SvIV(ST(0)));
3570 char *name = w32_getlogin_buffer;
3571 DWORD size = sizeof(w32_getlogin_buffer);
3573 if (GetUserName(name,&size)) {
3574 /* size includes NULL */
3575 ST(0) = sv_2mortal(newSVpvn(name,size-1));
3585 char name[MAX_COMPUTERNAME_LENGTH+1];
3586 DWORD size = sizeof(name);
3588 if (GetComputerName(name,&size)) {
3589 /* size does NOT include NULL :-( */
3590 ST(0) = sv_2mortal(newSVpvn(name,size));
3601 HINSTANCE hNetApi32 = LoadLibrary("netapi32.dll");
3602 DWORD (__stdcall *pfnNetApiBufferFree)(LPVOID Buffer);
3603 DWORD (__stdcall *pfnNetWkstaGetInfo)(LPWSTR servername, DWORD level,
3607 pfnNetApiBufferFree = (DWORD (__stdcall *)(void *))
3608 GetProcAddress(hNetApi32, "NetApiBufferFree");
3609 pfnNetWkstaGetInfo = (DWORD (__stdcall *)(LPWSTR, DWORD, void *))
3610 GetProcAddress(hNetApi32, "NetWkstaGetInfo");
3613 if (hNetApi32 && pfnNetWkstaGetInfo && pfnNetApiBufferFree) {
3614 /* this way is more reliable, in case user has a local account. */
3616 DWORD dnamelen = sizeof(dname);
3618 DWORD wki100_platform_id;
3619 LPWSTR wki100_computername;
3620 LPWSTR wki100_langroup;
3621 DWORD wki100_ver_major;
3622 DWORD wki100_ver_minor;
3624 /* NERR_Success *is* 0*/
3625 if (0 == pfnNetWkstaGetInfo(NULL, 100, &pwi)) {
3626 if (pwi->wki100_langroup && *(pwi->wki100_langroup)) {
3627 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_langroup,
3628 -1, (LPSTR)dname, dnamelen, NULL, NULL);
3631 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_computername,
3632 -1, (LPSTR)dname, dnamelen, NULL, NULL);
3634 pfnNetApiBufferFree(pwi);
3635 FreeLibrary(hNetApi32);
3638 FreeLibrary(hNetApi32);
3641 /* Win95 doesn't have NetWksta*(), so do it the old way */
3643 DWORD size = sizeof(name);
3645 FreeLibrary(hNetApi32);
3646 if (GetUserName(name,&size)) {
3647 char sid[ONE_K_BUFSIZE];
3648 DWORD sidlen = sizeof(sid);
3650 DWORD dnamelen = sizeof(dname);
3652 if (LookupAccountName(NULL, name, (PSID)&sid, &sidlen,
3653 dname, &dnamelen, &snu)) {
3654 XSRETURN_PV(dname); /* all that for this */
3666 DWORD flags, filecomplen;
3667 if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
3668 &flags, fsname, sizeof(fsname))) {
3669 if (GIMME_V == G_ARRAY) {
3670 XPUSHs(sv_2mortal(newSVpvn(fsname,strlen(fsname))));
3671 XPUSHs(sv_2mortal(newSViv(flags)));
3672 XPUSHs(sv_2mortal(newSViv(filecomplen)));
3677 XSRETURN_PV(fsname);
3683 XS(w32_GetOSVersion)
3686 OSVERSIONINFOA osver;
3689 OSVERSIONINFOW osverw;
3690 char szCSDVersion[sizeof(osverw.szCSDVersion)];
3691 osverw.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
3692 if (!GetVersionExW(&osverw)) {
3695 W2AHELPER(osverw.szCSDVersion, szCSDVersion, sizeof(szCSDVersion));
3696 XPUSHs(newSVpvn(szCSDVersion, strlen(szCSDVersion)));
3697 osver.dwMajorVersion = osverw.dwMajorVersion;
3698 osver.dwMinorVersion = osverw.dwMinorVersion;
3699 osver.dwBuildNumber = osverw.dwBuildNumber;
3700 osver.dwPlatformId = osverw.dwPlatformId;
3703 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOA);
3704 if (!GetVersionExA(&osver)) {
3707 XPUSHs(newSVpvn(osver.szCSDVersion, strlen(osver.szCSDVersion)));
3709 XPUSHs(newSViv(osver.dwMajorVersion));
3710 XPUSHs(newSViv(osver.dwMinorVersion));
3711 XPUSHs(newSViv(osver.dwBuildNumber));
3712 XPUSHs(newSViv(osver.dwPlatformId));
3721 XSRETURN_IV(IsWinNT());
3729 XSRETURN_IV(IsWin95());
3733 XS(w32_FormatMessage)
3737 char msgbuf[ONE_K_BUFSIZE];
3740 Perl_croak(aTHX_ "usage: Win32::FormatMessage($errno)");
3743 WCHAR wmsgbuf[ONE_K_BUFSIZE];
3744 if (FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM,
3745 &source, SvIV(ST(0)), 0,
3746 wmsgbuf, ONE_K_BUFSIZE-1, NULL))
3748 W2AHELPER(wmsgbuf, msgbuf, sizeof(msgbuf));
3749 XSRETURN_PV(msgbuf);
3753 if (FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM,
3754 &source, SvIV(ST(0)), 0,
3755 msgbuf, sizeof(msgbuf)-1, NULL))
3756 XSRETURN_PV(msgbuf);
3767 PROCESS_INFORMATION stProcInfo;
3768 STARTUPINFO stStartInfo;
3769 BOOL bSuccess = FALSE;
3772 Perl_croak(aTHX_ "usage: Win32::Spawn($cmdName, $args, $PID)");
3774 cmd = SvPV_nolen(ST(0));
3775 args = SvPV_nolen(ST(1));
3777 memset(&stStartInfo, 0, sizeof(stStartInfo)); /* Clear the block */
3778 stStartInfo.cb = sizeof(stStartInfo); /* Set the structure size */
3779 stStartInfo.dwFlags = STARTF_USESHOWWINDOW; /* Enable wShowWindow control */
3780 stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE; /* Start min (normal) */
3783 cmd, /* Image path */
3784 args, /* Arguments for command line */
3785 NULL, /* Default process security */
3786 NULL, /* Default thread security */
3787 FALSE, /* Must be TRUE to use std handles */
3788 NORMAL_PRIORITY_CLASS, /* No special scheduling */
3789 NULL, /* Inherit our environment block */
3790 NULL, /* Inherit our currrent directory */
3791 &stStartInfo, /* -> Startup info */
3792 &stProcInfo)) /* <- Process info (if OK) */
3794 CloseHandle(stProcInfo.hThread);/* library source code does this. */
3795 sv_setiv(ST(2), stProcInfo.dwProcessId);
3798 XSRETURN_IV(bSuccess);
3802 XS(w32_GetTickCount)
3805 DWORD msec = GetTickCount();
3813 XS(w32_GetShortPathName)
3820 Perl_croak(aTHX_ "usage: Win32::GetShortPathName($longPathName)");
3822 shortpath = sv_mortalcopy(ST(0));
3823 SvUPGRADE(shortpath, SVt_PV);
3824 /* src == target is allowed */
3826 len = GetShortPathName(SvPVX(shortpath),
3829 } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
3831 SvCUR_set(shortpath,len);
3839 XS(w32_GetFullPathName)
3848 Perl_croak(aTHX_ "usage: Win32::GetFullPathName($filename)");
3851 fullpath = sv_mortalcopy(filename);
3852 SvUPGRADE(fullpath, SVt_PV);
3854 len = GetFullPathName(SvPVX(filename),
3858 } while (len >= SvLEN(fullpath) && sv_grow(fullpath,len+1));
3860 if (GIMME_V == G_ARRAY) {
3862 XST_mPV(1,filepart);
3863 len = filepart - SvPVX(fullpath);
3866 SvCUR_set(fullpath,len);
3874 XS(w32_GetLongPathName)
3878 char tmpbuf[MAX_PATH+1];
3883 Perl_croak(aTHX_ "usage: Win32::GetLongPathName($pathname)");
3886 pathstr = SvPV(path,len);
3887 strcpy(tmpbuf, pathstr);
3888 pathstr = win32_longpath(tmpbuf);
3890 ST(0) = sv_2mortal(newSVpvn(pathstr, strlen(pathstr)));
3901 Perl_croak(aTHX_ "usage: Win32::Sleep($milliseconds)");
3912 Perl_croak(aTHX_ "usage: Win32::CopyFile($from, $to, $overwrite)");
3914 WCHAR wSourceFile[MAX_PATH+1];
3915 WCHAR wDestFile[MAX_PATH+1];
3916 A2WHELPER(SvPV_nolen(ST(0)), wSourceFile, sizeof(wSourceFile));
3917 wcscpy(wSourceFile, PerlDir_mapW(wSourceFile));
3918 A2WHELPER(SvPV_nolen(ST(1)), wDestFile, sizeof(wDestFile));
3919 bResult = CopyFileW(wSourceFile, PerlDir_mapW(wDestFile), !SvTRUE(ST(2)));
3922 char szSourceFile[MAX_PATH+1];
3923 strcpy(szSourceFile, PerlDir_mapA(SvPV_nolen(ST(0))));
3924 bResult = CopyFileA(szSourceFile, PerlDir_mapA(SvPV_nolen(ST(1))), !SvTRUE(ST(2)));
3933 Perl_init_os_extras(void)
3936 char *file = __FILE__;
3939 w32_perlshell_tokens = Nullch;
3940 w32_perlshell_items = -1;
3941 w32_fdpid = newAV(); /* XXX needs to be in Perl_win32_init()? */
3942 New(1313, w32_children, 1, child_tab);
3943 w32_num_children = 0;
3944 w32_init_socktype = 0;
3947 New(1313, w32_pseudo_children, 1, child_tab);
3948 w32_num_pseudo_children = 0;
3951 /* these names are Activeware compatible */
3952 newXS("Win32::GetCwd", w32_GetCwd, file);
3953 newXS("Win32::SetCwd", w32_SetCwd, file);
3954 newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
3955 newXS("Win32::GetLastError", w32_GetLastError, file);
3956 newXS("Win32::SetLastError", w32_SetLastError, file);
3957 newXS("Win32::LoginName", w32_LoginName, file);
3958 newXS("Win32::NodeName", w32_NodeName, file);
3959 newXS("Win32::DomainName", w32_DomainName, file);
3960 newXS("Win32::FsType", w32_FsType, file);
3961 newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
3962 newXS("Win32::IsWinNT", w32_IsWinNT, file);
3963 newXS("Win32::IsWin95", w32_IsWin95, file);
3964 newXS("Win32::FormatMessage", w32_FormatMessage, file);
3965 newXS("Win32::Spawn", w32_Spawn, file);
3966 newXS("Win32::GetTickCount", w32_GetTickCount, file);
3967 newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
3968 newXS("Win32::GetFullPathName", w32_GetFullPathName, file);
3969 newXS("Win32::GetLongPathName", w32_GetLongPathName, file);
3970 newXS("Win32::CopyFile", w32_CopyFile, file);
3971 newXS("Win32::Sleep", w32_Sleep, file);
3973 /* XXX Bloat Alert! The following Activeware preloads really
3974 * ought to be part of Win32::Sys::*, so they're not included
3977 /* LookupAccountName
3979 * InitiateSystemShutdown
3980 * AbortSystemShutdown
3981 * ExpandEnvrironmentStrings
3986 Perl_win32_init(int *argcp, char ***argvp)
3988 /* Disable floating point errors, Perl will trap the ones we
3989 * care about. VC++ RTL defaults to switching these off
3990 * already, but the Borland RTL doesn't. Since we don't
3991 * want to be at the vendor's whim on the default, we set
3992 * it explicitly here.
3994 #if !defined(_ALPHA_) && !defined(__GNUC__)
3995 _control87(MCW_EM, MCW_EM);
4001 win32_get_child_IO(child_IO_table* ptbl)
4003 ptbl->childStdIn = GetStdHandle(STD_INPUT_HANDLE);
4004 ptbl->childStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
4005 ptbl->childStdErr = GetStdHandle(STD_ERROR_HANDLE);
4012 # undef Perl_sys_intern_dup
4013 # define Perl_sys_intern_dup CPerlObj::Perl_sys_intern_dup
4018 Perl_sys_intern_dup(pTHX_ struct interp_intern *src, struct interp_intern *dst)
4020 dst->perlshell_tokens = Nullch;
4021 dst->perlshell_vec = (char**)NULL;
4022 dst->perlshell_items = 0;
4023 dst->fdpid = newAV();
4024 Newz(1313, dst->children, 1, child_tab);
4025 Newz(1313, dst->pseudo_children, 1, child_tab);
4027 dst->children->num = 0;
4028 dst->thr_intern.Winit_socktype = src->thr_intern.Winit_socktype;
4038 win32_free_argvw(pTHXo_ void *ptr)
4040 char** argv = (char**)ptr;
4048 win32_argv2utf8(int argc, char** argv)
4053 LPWSTR* lpwStr = CommandLineToArgvW(GetCommandLineW(), &wargc);
4054 if (lpwStr && argc) {
4056 length = WideCharToMultiByte(CP_UTF8, 0, lpwStr[--wargc], -1, NULL, 0, NULL, NULL);
4057 Newz(0, psz, length, char);
4058 WideCharToMultiByte(CP_UTF8, 0, lpwStr[wargc], -1, psz, length, NULL, NULL);
4061 call_atexit(win32_free_argvw, argv);
4063 GlobalFree((HGLOBAL)lpwStr);