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
22 /* #include "config.h" */
24 #define PERLIO_NOT_STDIO 0
25 #if !defined(PERLIO_IS_STDIO) && !defined(USE_SFIO)
34 #define PERL_NO_GET_CONTEXT
40 /* assert.h conflicts with #define of assert in perl.h */
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__)
64 #if defined(__BORLANDC__)
66 # define _utimbuf utimbuf
71 #define EXECF_SPAWN_NOWAIT 3
73 #if defined(PERL_IMPLICIT_SYS)
74 # undef win32_get_privlib
75 # define win32_get_privlib g_win32_get_privlib
76 # undef win32_get_sitelib
77 # define win32_get_sitelib g_win32_get_sitelib
79 # define do_spawn g_do_spawn
81 # define getlogin g_getlogin
84 #if defined(PERL_OBJECT)
86 # define do_aspawn g_do_aspawn
88 # define Perl_do_exec g_do_exec
91 static void get_shell(void);
92 static long tokenize(const char *str, char **dest, char ***destv);
93 int do_spawn2(char *cmd, int exectype);
94 static BOOL has_shell_metachars(char *ptr);
95 static long filetime_to_clock(PFILETIME ft);
96 static BOOL filetime_from_time(PFILETIME ft, time_t t);
97 static char * get_emd_part(SV **leading, char *trailing, ...);
98 static void remove_dead_process(long deceased);
99 static long find_pid(int pid);
100 static char * qualified_path(const char *cmd);
102 static void remove_dead_pseudo_process(long child);
103 static long find_pseudo_pid(int pid);
107 HANDLE w32_perldll_handle = INVALID_HANDLE_VALUE;
108 char w32_module_name[MAX_PATH+1];
111 static DWORD w32_platform = (DWORD)-1;
113 #define ONE_K_BUFSIZE 1024
118 return (win32_os_id() == VER_PLATFORM_WIN32_WINDOWS);
124 return (win32_os_id() == VER_PLATFORM_WIN32_NT);
128 set_w32_module_name(void)
131 GetModuleFileName((HMODULE)((w32_perldll_handle == INVALID_HANDLE_VALUE)
132 ? GetModuleHandle(NULL)
133 : w32_perldll_handle),
134 w32_module_name, sizeof(w32_module_name));
136 /* try to get full path to binary (which may be mangled when perl is
137 * run from a 16-bit app) */
138 /*PerlIO_printf(Perl_debug_log, "Before %s\n", w32_module_name);*/
139 (void)win32_longpath(w32_module_name);
140 /*PerlIO_printf(Perl_debug_log, "After %s\n", w32_module_name);*/
142 /* normalize to forward slashes */
143 ptr = w32_module_name;
151 /* *svp (if non-NULL) is expected to be POK (valid allocated SvPVX(*svp)) */
153 get_regstr_from(HKEY hkey, const char *valuename, SV **svp)
155 /* Retrieve a REG_SZ or REG_EXPAND_SZ from the registry */
158 const char *subkey = "Software\\Perl";
162 retval = RegOpenKeyEx(hkey, subkey, 0, KEY_READ, &handle);
163 if (retval == ERROR_SUCCESS) {
165 retval = RegQueryValueEx(handle, valuename, 0, &type, NULL, &datalen);
166 if (retval == ERROR_SUCCESS && type == REG_SZ) {
169 *svp = sv_2mortal(newSVpvn("",0));
170 SvGROW(*svp, datalen);
171 retval = RegQueryValueEx(handle, valuename, 0, NULL,
172 (PBYTE)SvPVX(*svp), &datalen);
173 if (retval == ERROR_SUCCESS) {
175 SvCUR_set(*svp,datalen-1);
183 /* *svp (if non-NULL) is expected to be POK (valid allocated SvPVX(*svp)) */
185 get_regstr(const char *valuename, SV **svp)
187 char *str = get_regstr_from(HKEY_CURRENT_USER, valuename, svp);
189 str = get_regstr_from(HKEY_LOCAL_MACHINE, valuename, svp);
193 /* *prev_pathp (if non-NULL) is expected to be POK (valid allocated SvPVX(sv)) */
195 get_emd_part(SV **prev_pathp, char *trailing_path, ...)
199 char mod_name[MAX_PATH+1];
203 int oldsize, newsize;
206 va_start(ap, trailing_path);
207 strip = va_arg(ap, char *);
209 sprintf(base, "%d.%d", (int)PERL_REVISION, (int)PERL_VERSION);
210 baselen = strlen(base);
212 if (!*w32_module_name) {
213 set_w32_module_name();
215 strcpy(mod_name, w32_module_name);
216 ptr = strrchr(mod_name, '/');
217 while (ptr && strip) {
218 /* look for directories to skip back */
221 ptr = strrchr(mod_name, '/');
222 /* avoid stripping component if there is no slash,
223 * or it doesn't match ... */
224 if (!ptr || stricmp(ptr+1, strip) != 0) {
225 /* ... but not if component matches m|5\.$patchlevel.*| */
226 if (!ptr || !(*strip == '5' && *(ptr+1) == '5'
227 && strncmp(strip, base, baselen) == 0
228 && strncmp(ptr+1, base, baselen) == 0))
234 strip = va_arg(ap, char *);
242 strcpy(++ptr, trailing_path);
244 /* only add directory if it exists */
245 if (GetFileAttributes(mod_name) != (DWORD) -1) {
246 /* directory exists */
249 *prev_pathp = sv_2mortal(newSVpvn("",0));
250 sv_catpvn(*prev_pathp, ";", 1);
251 sv_catpv(*prev_pathp, mod_name);
252 return SvPVX(*prev_pathp);
259 win32_get_privlib(char *pl)
262 char *stdlib = "lib";
263 char buffer[MAX_PATH+1];
266 /* $stdlib = $HKCU{"lib-$]"} || $HKLM{"lib-$]"} || $HKCU{"lib"} || $HKLM{"lib"} || ""; */
267 sprintf(buffer, "%s-%s", stdlib, pl);
268 if (!get_regstr(buffer, &sv))
269 (void)get_regstr(stdlib, &sv);
271 /* $stdlib .= ";$EMD/../../lib" */
272 return get_emd_part(&sv, stdlib, ARCHNAME, "bin", Nullch);
276 win32_get_sitelib(char *pl)
279 char *sitelib = "sitelib";
281 char pathstr[MAX_PATH+1];
287 /* $HKCU{"sitelib-$]"} || $HKLM{"sitelib-$]"} . ---; */
288 sprintf(regstr, "%s-%s", sitelib, pl);
289 (void)get_regstr(regstr, &sv1);
292 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/site/$]/lib"; */
293 sprintf(pathstr, "site/%s/lib", pl);
294 (void)get_emd_part(&sv1, pathstr, ARCHNAME, "bin", pl, Nullch);
296 /* $HKCU{'sitelib'} || $HKLM{'sitelib'} . ---; */
297 (void)get_regstr(sitelib, &sv2);
300 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/site/lib"; */
301 (void)get_emd_part(&sv2, "site/lib", ARCHNAME, "bin", pl, Nullch);
310 sv_catpvn(sv1, ";", 1);
318 has_shell_metachars(char *ptr)
324 * Scan string looking for redirection (< or >) or pipe
325 * characters (|) that are not in a quoted string.
326 * Shell variable interpolation (%VAR%) can also happen inside strings.
358 #if !defined(PERL_IMPLICIT_SYS)
359 /* since the current process environment is being updated in util.c
360 * the library functions will get the correct environment
363 Perl_my_popen(pTHX_ char *cmd, char *mode)
366 #define fixcmd(x) { \
367 char *pspace = strchr((x),' '); \
370 while (p < pspace) { \
381 PERL_FLUSHALL_FOR_CHILD;
382 return win32_popen(cmd, mode);
386 Perl_my_pclose(pTHX_ PerlIO *fp)
388 return win32_pclose(fp);
392 DllExport unsigned long
395 static OSVERSIONINFO osver;
397 if (osver.dwPlatformId != w32_platform) {
398 memset(&osver, 0, sizeof(OSVERSIONINFO));
399 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
400 GetVersionEx(&osver);
401 w32_platform = osver.dwPlatformId;
403 return (unsigned long)w32_platform;
412 return -((int)w32_pseudo_id);
417 /* Tokenize a string. Words are null-separated, and the list
418 * ends with a doubled null. Any character (except null and
419 * including backslash) may be escaped by preceding it with a
420 * backslash (the backslash will be stripped).
421 * Returns number of words in result buffer.
424 tokenize(const char *str, char **dest, char ***destv)
426 char *retstart = Nullch;
427 char **retvstart = 0;
431 int slen = strlen(str);
433 register char **retv;
434 New(1307, ret, slen+2, char);
435 New(1308, retv, (slen+3)/2, char*);
443 if (*ret == '\\' && *str)
445 else if (*ret == ' ') {
461 retvstart[items] = Nullch;
474 if (!w32_perlshell_tokens) {
475 /* we don't use COMSPEC here for two reasons:
476 * 1. the same reason perl on UNIX doesn't use SHELL--rampant and
477 * uncontrolled unportability of the ensuing scripts.
478 * 2. PERL5SHELL could be set to a shell that may not be fit for
479 * interactive use (which is what most programs look in COMSPEC
482 const char* defaultshell = (IsWinNT()
483 ? "cmd.exe /x/c" : "command.com /c");
484 const char *usershell = getenv("PERL5SHELL");
485 w32_perlshell_items = tokenize(usershell ? usershell : defaultshell,
486 &w32_perlshell_tokens,
492 do_aspawn(void *vreally, void **vmark, void **vsp)
495 SV *really = (SV*)vreally;
496 SV **mark = (SV**)vmark;
508 New(1306, argv, (sp - mark) + w32_perlshell_items + 2, char*);
510 if (SvNIOKp(*(mark+1)) && !SvPOKp(*(mark+1))) {
515 while (++mark <= sp) {
516 if (*mark && (str = SvPV_nolen(*mark)))
523 status = win32_spawnvp(flag,
524 (const char*)(really ? SvPV_nolen(really) : argv[0]),
525 (const char* const*)argv);
527 if (status < 0 && (errno == ENOEXEC || errno == ENOENT)) {
528 /* possible shell-builtin, invoke with shell */
530 sh_items = w32_perlshell_items;
532 argv[index+sh_items] = argv[index];
533 while (--sh_items >= 0)
534 argv[sh_items] = w32_perlshell_vec[sh_items];
536 status = win32_spawnvp(flag,
537 (const char*)(really ? SvPV_nolen(really) : argv[0]),
538 (const char* const*)argv);
541 if (flag != P_NOWAIT) {
544 if (ckWARN(WARN_EXEC))
545 Perl_warner(aTHX_ WARN_EXEC, "Can't spawn \"%s\": %s", argv[0], strerror(errno));
550 PL_statusvalue = status;
557 do_spawn2(char *cmd, int exectype)
564 BOOL needToTry = TRUE;
567 /* Save an extra exec if possible. See if there are shell
568 * metacharacters in it */
569 if (!has_shell_metachars(cmd)) {
570 New(1301,argv, strlen(cmd) / 2 + 2, char*);
571 New(1302,cmd2, strlen(cmd) + 1, char);
574 for (s = cmd2; *s;) {
575 while (*s && isSPACE(*s))
579 while (*s && !isSPACE(*s))
588 status = win32_spawnvp(P_WAIT, argv[0],
589 (const char* const*)argv);
591 case EXECF_SPAWN_NOWAIT:
592 status = win32_spawnvp(P_NOWAIT, argv[0],
593 (const char* const*)argv);
596 status = win32_execvp(argv[0], (const char* const*)argv);
599 if (status != -1 || errno == 0)
609 New(1306, argv, w32_perlshell_items + 2, char*);
610 while (++i < w32_perlshell_items)
611 argv[i] = w32_perlshell_vec[i];
616 status = win32_spawnvp(P_WAIT, argv[0],
617 (const char* const*)argv);
619 case EXECF_SPAWN_NOWAIT:
620 status = win32_spawnvp(P_NOWAIT, argv[0],
621 (const char* const*)argv);
624 status = win32_execvp(argv[0], (const char* const*)argv);
630 if (exectype != EXECF_SPAWN_NOWAIT) {
633 if (ckWARN(WARN_EXEC))
634 Perl_warner(aTHX_ WARN_EXEC, "Can't %s \"%s\": %s",
635 (exectype == EXECF_EXEC ? "exec" : "spawn"),
636 cmd, strerror(errno));
641 PL_statusvalue = status;
649 return do_spawn2(cmd, EXECF_SPAWN);
653 do_spawn_nowait(char *cmd)
655 return do_spawn2(cmd, EXECF_SPAWN_NOWAIT);
659 Perl_do_exec(pTHX_ char *cmd)
661 do_spawn2(cmd, EXECF_EXEC);
665 /* The idea here is to read all the directory names into a string table
666 * (separated by nulls) and when one of the other dir functions is called
667 * return the pointer to the current file name.
670 win32_opendir(char *filename)
676 char scanname[MAX_PATH+3];
678 WIN32_FIND_DATAA aFindData;
679 WIN32_FIND_DATAW wFindData;
681 char buffer[MAX_PATH*2];
682 WCHAR wbuffer[MAX_PATH+1];
685 len = strlen(filename);
689 /* check to see if filename is a directory */
690 if (win32_stat(filename, &sbuf) < 0 || !S_ISDIR(sbuf.st_mode))
693 /* Get us a DIR structure */
694 Newz(1303, dirp, 1, DIR);
696 /* Create the search pattern */
697 strcpy(scanname, filename);
699 /* bare drive name means look in cwd for drive */
700 if (len == 2 && isALPHA(scanname[0]) && scanname[1] == ':') {
701 scanname[len++] = '.';
702 scanname[len++] = '/';
704 else if (scanname[len-1] != '/' && scanname[len-1] != '\\') {
705 scanname[len++] = '/';
707 scanname[len++] = '*';
708 scanname[len] = '\0';
710 /* do the FindFirstFile call */
712 A2WHELPER(scanname, wbuffer, sizeof(wbuffer));
713 fh = FindFirstFileW(PerlDir_mapW(wbuffer), &wFindData);
716 fh = FindFirstFileA(PerlDir_mapA(scanname), &aFindData);
719 if (fh == INVALID_HANDLE_VALUE) {
720 DWORD err = GetLastError();
721 /* FindFirstFile() fails on empty drives! */
723 case ERROR_FILE_NOT_FOUND:
725 case ERROR_NO_MORE_FILES:
726 case ERROR_PATH_NOT_FOUND:
729 case ERROR_NOT_ENOUGH_MEMORY:
740 /* now allocate the first part of the string table for
741 * the filenames that we find.
744 W2AHELPER(wFindData.cFileName, buffer, sizeof(buffer));
748 ptr = aFindData.cFileName;
755 New(1304, dirp->start, dirp->size, char);
756 strcpy(dirp->start, ptr);
758 dirp->end = dirp->curr = dirp->start;
764 /* Readdir just returns the current string pointer and bumps the
765 * string pointer to the nDllExport entry.
767 DllExport struct direct *
768 win32_readdir(DIR *dirp)
773 /* first set up the structure to return */
774 len = strlen(dirp->curr);
775 strcpy(dirp->dirstr.d_name, dirp->curr);
776 dirp->dirstr.d_namlen = len;
779 dirp->dirstr.d_ino = dirp->curr - dirp->start;
781 /* Now set up for the next call to readdir */
782 dirp->curr += len + 1;
783 if (dirp->curr >= dirp->end) {
787 WIN32_FIND_DATAW wFindData;
788 WIN32_FIND_DATAA aFindData;
789 char buffer[MAX_PATH*2];
791 /* finding the next file that matches the wildcard
792 * (which should be all of them in this directory!).
795 res = FindNextFileW(dirp->handle, &wFindData);
797 W2AHELPER(wFindData.cFileName, buffer, sizeof(buffer));
802 res = FindNextFileA(dirp->handle, &aFindData);
804 ptr = aFindData.cFileName;
807 long endpos = dirp->end - dirp->start;
808 long newsize = endpos + strlen(ptr) + 1;
809 /* bump the string table size by enough for the
810 * new name and it's null terminator */
811 while (newsize > dirp->size) {
812 long curpos = dirp->curr - dirp->start;
814 Renew(dirp->start, dirp->size, char);
815 dirp->curr = dirp->start + curpos;
817 strcpy(dirp->start + endpos, ptr);
818 dirp->end = dirp->start + newsize;
824 return &(dirp->dirstr);
830 /* Telldir returns the current string pointer position */
832 win32_telldir(DIR *dirp)
834 return (dirp->curr - dirp->start);
838 /* Seekdir moves the string pointer to a previously saved position
839 * (returned by telldir).
842 win32_seekdir(DIR *dirp, long loc)
844 dirp->curr = dirp->start + loc;
847 /* Rewinddir resets the string pointer to the start */
849 win32_rewinddir(DIR *dirp)
851 dirp->curr = dirp->start;
854 /* free the memory allocated by opendir */
856 win32_closedir(DIR *dirp)
859 if (dirp->handle != INVALID_HANDLE_VALUE)
860 FindClose(dirp->handle);
861 Safefree(dirp->start);
874 * Just pretend that everyone is a superuser. NT will let us know if
875 * we don\'t really have permission to do something.
878 #define ROOT_UID ((uid_t)0)
879 #define ROOT_GID ((gid_t)0)
908 return (auid == ROOT_UID ? 0 : -1);
914 return (agid == ROOT_GID ? 0 : -1);
921 char *buf = w32_getlogin_buffer;
922 DWORD size = sizeof(w32_getlogin_buffer);
923 if (GetUserName(buf,&size))
929 chown(const char *path, uid_t owner, gid_t group)
939 long child = w32_num_children;
940 while (--child >= 0) {
941 if (w32_child_pids[child] == pid)
948 remove_dead_process(long child)
952 CloseHandle(w32_child_handles[child]);
953 Move(&w32_child_handles[child+1], &w32_child_handles[child],
954 (w32_num_children-child-1), HANDLE);
955 Move(&w32_child_pids[child+1], &w32_child_pids[child],
956 (w32_num_children-child-1), DWORD);
963 find_pseudo_pid(int pid)
966 long child = w32_num_pseudo_children;
967 while (--child >= 0) {
968 if (w32_pseudo_child_pids[child] == pid)
975 remove_dead_pseudo_process(long child)
979 CloseHandle(w32_pseudo_child_handles[child]);
980 Move(&w32_pseudo_child_handles[child+1], &w32_pseudo_child_handles[child],
981 (w32_num_pseudo_children-child-1), HANDLE);
982 Move(&w32_pseudo_child_pids[child+1], &w32_pseudo_child_pids[child],
983 (w32_num_pseudo_children-child-1), DWORD);
984 w32_num_pseudo_children--;
990 win32_kill(int pid, int sig)
996 /* it is a pseudo-forked child */
997 long child = find_pseudo_pid(-pid);
1001 hProcess = w32_pseudo_child_handles[child];
1002 if (TerminateThread(hProcess, sig)) {
1003 remove_dead_pseudo_process(child);
1011 long child = find_pid(pid);
1015 hProcess = w32_child_handles[child];
1016 if (TerminateProcess(hProcess, sig)) {
1017 remove_dead_process(child);
1022 hProcess = OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid);
1026 if (TerminateProcess(hProcess, sig)) {
1027 CloseHandle(hProcess);
1041 DllExport unsigned int
1042 win32_sleep(unsigned int t)
1049 win32_stat(const char *path, struct stat *sbuf)
1052 char buffer[MAX_PATH+1];
1053 int l = strlen(path);
1055 WCHAR wbuffer[MAX_PATH+1];
1061 switch(path[l - 1]) {
1062 /* FindFirstFile() and stat() are buggy with a trailing
1063 * backslash, so change it to a forward slash :-( */
1065 strncpy(buffer, path, l-1);
1066 buffer[l - 1] = '/';
1070 /* FindFirstFile() is buggy with "x:", so add a dot :-( */
1072 if (l == 2 && isALPHA(path[0])) {
1073 buffer[0] = path[0];
1084 /* We *must* open & close the file once; otherwise file attribute changes */
1085 /* might not yet have propagated to "other" hard links of the same file. */
1086 /* This also gives us an opportunity to determine the number of links. */
1088 A2WHELPER(path, wbuffer, sizeof(wbuffer));
1089 pwbuffer = PerlDir_mapW(wbuffer);
1090 handle = CreateFileW(pwbuffer, 0, 0, NULL, OPEN_EXISTING, 0, NULL);
1093 path = PerlDir_mapA(path);
1095 handle = CreateFileA(path, 0, 0, NULL, OPEN_EXISTING, 0, NULL);
1097 if (handle != INVALID_HANDLE_VALUE) {
1098 BY_HANDLE_FILE_INFORMATION bhi;
1099 if (GetFileInformationByHandle(handle, &bhi))
1100 nlink = bhi.nNumberOfLinks;
1101 CloseHandle(handle);
1104 /* pwbuffer or path will be mapped correctly above */
1106 res = _wstat(pwbuffer, (struct _stat *)sbuf);
1109 res = stat(path, sbuf);
1111 sbuf->st_nlink = nlink;
1114 /* CRT is buggy on sharenames, so make sure it really isn't.
1115 * XXX using GetFileAttributesEx() will enable us to set
1116 * sbuf->st_*time (but note that's not available on the
1117 * Windows of 1995) */
1120 r = GetFileAttributesW(pwbuffer);
1123 r = GetFileAttributesA(path);
1125 if (r != 0xffffffff && (r & FILE_ATTRIBUTE_DIRECTORY)) {
1126 /* sbuf may still contain old garbage since stat() failed */
1127 Zero(sbuf, 1, struct stat);
1128 sbuf->st_mode = S_IFDIR | S_IREAD;
1130 if (!(r & FILE_ATTRIBUTE_READONLY))
1131 sbuf->st_mode |= S_IWRITE | S_IEXEC;
1136 if (l == 3 && isALPHA(path[0]) && path[1] == ':'
1137 && (path[2] == '\\' || path[2] == '/'))
1139 /* The drive can be inaccessible, some _stat()s are buggy */
1141 ? !GetVolumeInformationW(pwbuffer,NULL,0,NULL,NULL,NULL,NULL,0)
1142 : !GetVolumeInformationA(path,NULL,0,NULL,NULL,NULL,NULL,0)) {
1148 if (S_ISDIR(sbuf->st_mode))
1149 sbuf->st_mode |= S_IWRITE | S_IEXEC;
1150 else if (S_ISREG(sbuf->st_mode)) {
1152 if (l >= 4 && path[l-4] == '.') {
1153 const char *e = path + l - 3;
1154 if (strnicmp(e,"exe",3)
1155 && strnicmp(e,"bat",3)
1156 && strnicmp(e,"com",3)
1157 && (IsWin95() || strnicmp(e,"cmd",3)))
1158 sbuf->st_mode &= ~S_IEXEC;
1160 sbuf->st_mode |= S_IEXEC;
1163 sbuf->st_mode &= ~S_IEXEC;
1164 /* Propagate permissions to _group_ and _others_ */
1165 perms = sbuf->st_mode & (S_IREAD|S_IWRITE|S_IEXEC);
1166 sbuf->st_mode |= (perms>>3) | (perms>>6);
1173 /* Find the longname of a given path. path is destructively modified.
1174 * It should have space for at least MAX_PATH characters. */
1176 win32_longpath(char *path)
1178 WIN32_FIND_DATA fdata;
1180 char tmpbuf[MAX_PATH+1];
1181 char *tmpstart = tmpbuf;
1188 if (isALPHA(path[0]) && path[1] == ':' &&
1189 (path[2] == '/' || path[2] == '\\'))
1192 *tmpstart++ = path[0];
1196 else if ((path[0] == '/' || path[0] == '\\') &&
1197 (path[1] == '/' || path[1] == '\\'))
1200 *tmpstart++ = path[0];
1201 *tmpstart++ = path[1];
1202 /* copy machine name */
1203 while (*start && *start != '/' && *start != '\\')
1204 *tmpstart++ = *start++;
1206 *tmpstart++ = *start;
1208 /* copy share name */
1209 while (*start && *start != '/' && *start != '\\')
1210 *tmpstart++ = *start++;
1214 if (sep == '/' || sep == '\\')
1218 /* walk up to slash */
1219 while (*start && *start != '/' && *start != '\\')
1222 /* discard doubled slashes */
1223 while (*start && (start[1] == '/' || start[1] == '\\'))
1227 /* stop and find full name of component */
1229 fhand = FindFirstFile(path,&fdata);
1230 if (fhand != INVALID_HANDLE_VALUE) {
1231 strcpy(tmpstart, fdata.cFileName);
1232 tmpstart += strlen(fdata.cFileName);
1240 /* failed a step, just return without side effects */
1241 /*PerlIO_printf(Perl_debug_log, "Failed to find %s\n", path);*/
1246 strcpy(path,tmpbuf);
1250 #ifndef USE_WIN32_RTL_ENV
1253 win32_getenv(const char *name)
1256 WCHAR wBuffer[MAX_PATH+1];
1258 SV *curitem = Nullsv;
1261 A2WHELPER(name, wBuffer, sizeof(wBuffer));
1262 needlen = GetEnvironmentVariableW(wBuffer, NULL, 0);
1265 needlen = GetEnvironmentVariableA(name,NULL,0);
1267 curitem = sv_2mortal(newSVpvn("", 0));
1271 SvGROW(curitem, (needlen+1)*sizeof(WCHAR));
1272 needlen = GetEnvironmentVariableW(wBuffer,
1273 (WCHAR*)SvPVX(curitem),
1275 } while (needlen >= SvLEN(curitem)/sizeof(WCHAR));
1276 SvCUR_set(curitem, (needlen*sizeof(WCHAR))+1);
1277 acuritem = sv_2mortal(newSVsv(curitem));
1278 W2AHELPER((WCHAR*)SvPVX(acuritem), SvPVX(curitem), SvCUR(curitem));
1282 SvGROW(curitem, needlen+1);
1283 needlen = GetEnvironmentVariableA(name,SvPVX(curitem),
1285 } while (needlen >= SvLEN(curitem));
1286 SvCUR_set(curitem, needlen);
1290 /* allow any environment variables that begin with 'PERL'
1291 to be stored in the registry */
1292 if (strncmp(name, "PERL", 4) == 0)
1293 (void)get_regstr(name, &curitem);
1295 if (curitem && SvCUR(curitem))
1296 return SvPVX(curitem);
1302 win32_putenv(const char *name)
1309 int length, relval = -1;
1313 length = strlen(name)+1;
1314 New(1309,wCuritem,length,WCHAR);
1315 A2WHELPER(name, wCuritem, length*sizeof(WCHAR));
1316 wVal = wcschr(wCuritem, '=');
1319 if (SetEnvironmentVariableW(wCuritem, *wVal ? wVal : NULL))
1325 New(1309,curitem,strlen(name)+1,char);
1326 strcpy(curitem, name);
1327 val = strchr(curitem, '=');
1329 /* The sane way to deal with the environment.
1330 * Has these advantages over putenv() & co.:
1331 * * enables us to store a truly empty value in the
1332 * environment (like in UNIX).
1333 * * we don't have to deal with RTL globals, bugs and leaks.
1335 * Why you may want to enable USE_WIN32_RTL_ENV:
1336 * * environ[] and RTL functions will not reflect changes,
1337 * which might be an issue if extensions want to access
1338 * the env. via RTL. This cuts both ways, since RTL will
1339 * not see changes made by extensions that call the Win32
1340 * functions directly, either.
1344 if (SetEnvironmentVariableA(curitem, *val ? val : NULL))
1356 filetime_to_clock(PFILETIME ft)
1358 __int64 qw = ft->dwHighDateTime;
1360 qw |= ft->dwLowDateTime;
1361 qw /= 10000; /* File time ticks at 0.1uS, clock at 1mS */
1366 win32_times(struct tms *timebuf)
1371 if (GetProcessTimes(GetCurrentProcess(), &dummy, &dummy,
1373 timebuf->tms_utime = filetime_to_clock(&user);
1374 timebuf->tms_stime = filetime_to_clock(&kernel);
1375 timebuf->tms_cutime = 0;
1376 timebuf->tms_cstime = 0;
1379 /* That failed - e.g. Win95 fallback to clock() */
1380 clock_t t = clock();
1381 timebuf->tms_utime = t;
1382 timebuf->tms_stime = 0;
1383 timebuf->tms_cutime = 0;
1384 timebuf->tms_cstime = 0;
1389 /* fix utime() so it works on directories in NT */
1391 filetime_from_time(PFILETIME pFileTime, time_t Time)
1393 struct tm *pTM = localtime(&Time);
1394 SYSTEMTIME SystemTime;
1400 SystemTime.wYear = pTM->tm_year + 1900;
1401 SystemTime.wMonth = pTM->tm_mon + 1;
1402 SystemTime.wDay = pTM->tm_mday;
1403 SystemTime.wHour = pTM->tm_hour;
1404 SystemTime.wMinute = pTM->tm_min;
1405 SystemTime.wSecond = pTM->tm_sec;
1406 SystemTime.wMilliseconds = 0;
1408 return SystemTimeToFileTime(&SystemTime, &LocalTime) &&
1409 LocalFileTimeToFileTime(&LocalTime, pFileTime);
1413 win32_unlink(const char *filename)
1420 WCHAR wBuffer[MAX_PATH+1];
1423 A2WHELPER(filename, wBuffer, sizeof(wBuffer));
1424 pwBuffer = PerlDir_mapW(wBuffer);
1425 attrs = GetFileAttributesW(pwBuffer);
1426 if (attrs == 0xFFFFFFFF)
1428 if (attrs & FILE_ATTRIBUTE_READONLY) {
1429 (void)SetFileAttributesW(pwBuffer, attrs & ~FILE_ATTRIBUTE_READONLY);
1430 ret = _wunlink(pwBuffer);
1432 (void)SetFileAttributesW(pwBuffer, attrs);
1435 ret = _wunlink(pwBuffer);
1438 filename = PerlDir_mapA(filename);
1439 attrs = GetFileAttributesA(filename);
1440 if (attrs == 0xFFFFFFFF)
1442 if (attrs & FILE_ATTRIBUTE_READONLY) {
1443 (void)SetFileAttributesA(filename, attrs & ~FILE_ATTRIBUTE_READONLY);
1444 ret = unlink(filename);
1446 (void)SetFileAttributesA(filename, attrs);
1449 ret = unlink(filename);
1458 win32_utime(const char *filename, struct utimbuf *times)
1465 struct utimbuf TimeBuffer;
1466 WCHAR wbuffer[MAX_PATH+1];
1471 A2WHELPER(filename, wbuffer, sizeof(wbuffer));
1472 pwbuffer = PerlDir_mapW(wbuffer);
1473 rc = _wutime(pwbuffer, (struct _utimbuf*)times);
1476 filename = PerlDir_mapA(filename);
1477 rc = utime(filename, times);
1479 /* EACCES: path specifies directory or readonly file */
1480 if (rc == 0 || errno != EACCES /* || !IsWinNT() */)
1483 if (times == NULL) {
1484 times = &TimeBuffer;
1485 time(×->actime);
1486 times->modtime = times->actime;
1489 /* This will (and should) still fail on readonly files */
1491 handle = CreateFileW(pwbuffer, GENERIC_READ | GENERIC_WRITE,
1492 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1493 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1496 handle = CreateFileA(filename, GENERIC_READ | GENERIC_WRITE,
1497 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1498 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1500 if (handle == INVALID_HANDLE_VALUE)
1503 if (GetFileTime(handle, &ftCreate, &ftAccess, &ftWrite) &&
1504 filetime_from_time(&ftAccess, times->actime) &&
1505 filetime_from_time(&ftWrite, times->modtime) &&
1506 SetFileTime(handle, &ftCreate, &ftAccess, &ftWrite))
1511 CloseHandle(handle);
1516 win32_uname(struct utsname *name)
1518 struct hostent *hep;
1519 STRLEN nodemax = sizeof(name->nodename)-1;
1520 OSVERSIONINFO osver;
1522 memset(&osver, 0, sizeof(OSVERSIONINFO));
1523 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1524 if (GetVersionEx(&osver)) {
1526 switch (osver.dwPlatformId) {
1527 case VER_PLATFORM_WIN32_WINDOWS:
1528 strcpy(name->sysname, "Windows");
1530 case VER_PLATFORM_WIN32_NT:
1531 strcpy(name->sysname, "Windows NT");
1533 case VER_PLATFORM_WIN32s:
1534 strcpy(name->sysname, "Win32s");
1537 strcpy(name->sysname, "Win32 Unknown");
1542 sprintf(name->release, "%d.%d",
1543 osver.dwMajorVersion, osver.dwMinorVersion);
1546 sprintf(name->version, "Build %d",
1547 osver.dwPlatformId == VER_PLATFORM_WIN32_NT
1548 ? osver.dwBuildNumber : (osver.dwBuildNumber & 0xffff));
1549 if (osver.szCSDVersion[0]) {
1550 char *buf = name->version + strlen(name->version);
1551 sprintf(buf, " (%s)", osver.szCSDVersion);
1555 *name->sysname = '\0';
1556 *name->version = '\0';
1557 *name->release = '\0';
1561 hep = win32_gethostbyname("localhost");
1563 STRLEN len = strlen(hep->h_name);
1564 if (len <= nodemax) {
1565 strcpy(name->nodename, hep->h_name);
1568 strncpy(name->nodename, hep->h_name, nodemax);
1569 name->nodename[nodemax] = '\0';
1574 if (!GetComputerName(name->nodename, &sz))
1575 *name->nodename = '\0';
1578 /* machine (architecture) */
1582 GetSystemInfo(&info);
1584 #if defined(__BORLANDC__) || defined(__MINGW32__)
1585 switch (info.u.s.wProcessorArchitecture) {
1587 switch (info.wProcessorArchitecture) {
1589 case PROCESSOR_ARCHITECTURE_INTEL:
1590 arch = "x86"; break;
1591 case PROCESSOR_ARCHITECTURE_MIPS:
1592 arch = "mips"; break;
1593 case PROCESSOR_ARCHITECTURE_ALPHA:
1594 arch = "alpha"; break;
1595 case PROCESSOR_ARCHITECTURE_PPC:
1596 arch = "ppc"; break;
1598 arch = "unknown"; break;
1600 strcpy(name->machine, arch);
1606 win32_waitpid(int pid, int *status, int flags)
1610 if (pid == -1) /* XXX threadid == 1 ? */
1611 return win32_wait(status);
1614 long child = find_pseudo_pid(-pid);
1616 HANDLE hThread = w32_pseudo_child_handles[child];
1617 DWORD waitcode = WaitForSingleObject(hThread, INFINITE);
1618 if (waitcode != WAIT_FAILED) {
1619 if (GetExitCodeThread(hThread, &waitcode)) {
1620 *status = (int)((waitcode & 0xff) << 8);
1621 retval = (int)w32_pseudo_child_pids[child];
1622 remove_dead_pseudo_process(child);
1632 long child = find_pid(pid);
1634 HANDLE hProcess = w32_child_handles[child];
1635 DWORD waitcode = WaitForSingleObject(hProcess, INFINITE);
1636 if (waitcode != WAIT_FAILED) {
1637 if (GetExitCodeProcess(hProcess, &waitcode)) {
1638 *status = (int)((waitcode & 0xff) << 8);
1639 retval = (int)w32_child_pids[child];
1640 remove_dead_process(child);
1648 retval = cwait(status, pid, WAIT_CHILD);
1649 /* cwait() returns "correctly" on Borland */
1650 #ifndef __BORLANDC__
1656 return retval >= 0 ? pid : retval;
1660 win32_wait(int *status)
1662 /* XXX this wait emulation only knows about processes
1663 * spawned via win32_spawnvp(P_NOWAIT, ...).
1667 DWORD exitcode, waitcode;
1670 if (w32_num_pseudo_children) {
1671 waitcode = WaitForMultipleObjects(w32_num_pseudo_children,
1672 w32_pseudo_child_handles,
1675 if (waitcode != WAIT_FAILED) {
1676 if (waitcode >= WAIT_ABANDONED_0
1677 && waitcode < WAIT_ABANDONED_0 + w32_num_pseudo_children)
1678 i = waitcode - WAIT_ABANDONED_0;
1680 i = waitcode - WAIT_OBJECT_0;
1681 if (GetExitCodeThread(w32_pseudo_child_handles[i], &exitcode)) {
1682 *status = (int)((exitcode & 0xff) << 8);
1683 retval = (int)w32_pseudo_child_pids[i];
1684 remove_dead_pseudo_process(i);
1691 if (!w32_num_children) {
1696 /* if a child exists, wait for it to die */
1697 waitcode = WaitForMultipleObjects(w32_num_children,
1701 if (waitcode != WAIT_FAILED) {
1702 if (waitcode >= WAIT_ABANDONED_0
1703 && waitcode < WAIT_ABANDONED_0 + w32_num_children)
1704 i = waitcode - WAIT_ABANDONED_0;
1706 i = waitcode - WAIT_OBJECT_0;
1707 if (GetExitCodeProcess(w32_child_handles[i], &exitcode) ) {
1708 *status = (int)((exitcode & 0xff) << 8);
1709 retval = (int)w32_child_pids[i];
1710 remove_dead_process(i);
1716 errno = GetLastError();
1722 static UINT timerid = 0;
1724 static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
1727 KillTimer(NULL,timerid);
1731 #endif /* !PERL_OBJECT */
1733 DllExport unsigned int
1734 win32_alarm(unsigned int sec)
1738 * the 'obvious' implentation is SetTimer() with a callback
1739 * which does whatever receiving SIGALRM would do
1740 * we cannot use SIGALRM even via raise() as it is not
1741 * one of the supported codes in <signal.h>
1743 * Snag is unless something is looking at the message queue
1744 * nothing happens :-(
1749 timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
1751 Perl_croak_nocontext("Cannot set timer");
1757 KillTimer(NULL,timerid);
1761 #endif /* !PERL_OBJECT */
1765 #ifdef HAVE_DES_FCRYPT
1766 extern char * des_fcrypt(const char *txt, const char *salt, char *cbuf);
1770 win32_crypt(const char *txt, const char *salt)
1773 #ifdef HAVE_DES_FCRYPT
1775 return des_fcrypt(txt, salt, w32_crypt_buffer);
1777 Perl_croak(aTHX_ "The crypt() function is unimplemented due to excessive paranoia.");
1782 /* C doesn't like repeat struct definitions */
1784 #if defined(USE_FIXED_OSFHANDLE) || defined(PERL_MSVCRT_READFIX)
1787 #define _CRTIMP __declspec(dllimport)
1791 * Control structure for lowio file handles
1794 long osfhnd; /* underlying OS file HANDLE */
1795 char osfile; /* attributes of file (e.g., open in text mode?) */
1796 char pipech; /* one char buffer for handles opened on pipes */
1798 CRITICAL_SECTION lock;
1803 * Array of arrays of control structures for lowio files.
1805 EXTERN_C _CRTIMP ioinfo* __pioinfo[];
1808 * Definition of IOINFO_L2E, the log base 2 of the number of elements in each
1809 * array of ioinfo structs.
1811 #define IOINFO_L2E 5
1814 * Definition of IOINFO_ARRAY_ELTS, the number of elements in ioinfo array
1816 #define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
1819 * Access macros for getting at an ioinfo struct and its fields from a
1822 #define _pioinfo(i) (__pioinfo[(i) >> IOINFO_L2E] + ((i) & (IOINFO_ARRAY_ELTS - 1)))
1823 #define _osfhnd(i) (_pioinfo(i)->osfhnd)
1824 #define _osfile(i) (_pioinfo(i)->osfile)
1825 #define _pipech(i) (_pioinfo(i)->pipech)
1829 #ifdef USE_FIXED_OSFHANDLE
1831 #define FOPEN 0x01 /* file handle open */
1832 #define FNOINHERIT 0x10 /* file handle opened O_NOINHERIT */
1833 #define FAPPEND 0x20 /* file handle opened O_APPEND */
1834 #define FDEV 0x40 /* file handle refers to device */
1835 #define FTEXT 0x80 /* file handle is in text mode */
1838 *int my_open_osfhandle(long osfhandle, int flags) - open C Runtime file handle
1841 * This function allocates a free C Runtime file handle and associates
1842 * it with the Win32 HANDLE specified by the first parameter. This is a
1843 * temperary fix for WIN95's brain damage GetFileType() error on socket
1844 * we just bypass that call for socket
1846 * This works with MSVC++ 4.0+ or GCC/Mingw32
1849 * long osfhandle - Win32 HANDLE to associate with C Runtime file handle.
1850 * int flags - flags to associate with C Runtime file handle.
1853 * returns index of entry in fh, if successful
1854 * return -1, if no free entry is found
1858 *******************************************************************************/
1861 * we fake up some parts of the CRT that aren't exported by MSVCRT.dll
1862 * this lets sockets work on Win9X with GCC and should fix the problems
1867 /* since we are not doing a dup2(), this works fine */
1869 #define _set_osfhnd(fh, osfh) (void)(_osfhnd(fh) = osfh)
1871 /* create an ioinfo entry, kill its handle, and steal the entry */
1876 HANDLE hF = CreateFile("NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
1877 int fh = _open_osfhandle((long)hF, 0);
1881 EnterCriticalSection(&(_pioinfo(fh)->lock));
1886 my_open_osfhandle(long osfhandle, int flags)
1889 char fileflags; /* _osfile flags */
1891 /* copy relevant flags from second parameter */
1894 if (flags & O_APPEND)
1895 fileflags |= FAPPEND;
1900 if (flags & O_NOINHERIT)
1901 fileflags |= FNOINHERIT;
1903 /* attempt to allocate a C Runtime file handle */
1904 if ((fh = _alloc_osfhnd()) == -1) {
1905 errno = EMFILE; /* too many open files */
1906 _doserrno = 0L; /* not an OS error */
1907 return -1; /* return error to caller */
1910 /* the file is open. now, set the info in _osfhnd array */
1911 _set_osfhnd(fh, osfhandle);
1913 fileflags |= FOPEN; /* mark as open */
1915 _osfile(fh) = fileflags; /* set osfile entry */
1916 LeaveCriticalSection(&_pioinfo(fh)->lock);
1918 return fh; /* return handle */
1921 #endif /* USE_FIXED_OSFHANDLE */
1923 /* simulate flock by locking a range on the file */
1925 #define LK_ERR(f,i) ((f) ? (i = 0) : (errno = GetLastError()))
1926 #define LK_LEN 0xffff0000
1929 win32_flock(int fd, int oper)
1937 Perl_croak_nocontext("flock() unimplemented on this platform");
1940 fh = (HANDLE)_get_osfhandle(fd);
1941 memset(&o, 0, sizeof(o));
1944 case LOCK_SH: /* shared lock */
1945 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
1947 case LOCK_EX: /* exclusive lock */
1948 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
1950 case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
1951 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
1953 case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
1954 LK_ERR(LockFileEx(fh,
1955 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
1956 0, LK_LEN, 0, &o),i);
1958 case LOCK_UN: /* unlock lock */
1959 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, 0, &o),i);
1961 default: /* unknown */
1972 * redirected io subsystem for all XS modules
1985 return (&(_environ));
1988 /* the rest are the remapped stdio routines */
2008 win32_ferror(FILE *fp)
2010 return (ferror(fp));
2015 win32_feof(FILE *fp)
2021 * Since the errors returned by the socket error function
2022 * WSAGetLastError() are not known by the library routine strerror
2023 * we have to roll our own.
2027 win32_strerror(int e)
2029 #ifndef __BORLANDC__ /* Borland intolerance */
2030 extern int sys_nerr;
2034 if (e < 0 || e > sys_nerr) {
2039 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
2040 w32_strerror_buffer,
2041 sizeof(w32_strerror_buffer), NULL) == 0)
2042 strcpy(w32_strerror_buffer, "Unknown Error");
2044 return w32_strerror_buffer;
2050 win32_str_os_error(void *sv, DWORD dwErr)
2054 dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
2055 |FORMAT_MESSAGE_IGNORE_INSERTS
2056 |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
2057 dwErr, 0, (char *)&sMsg, 1, NULL);
2058 /* strip trailing whitespace and period */
2061 --dwLen; /* dwLen doesn't include trailing null */
2062 } while (0 < dwLen && isSPACE(sMsg[dwLen]));
2063 if ('.' != sMsg[dwLen])
2068 sMsg = (char*)LocalAlloc(0, 64/**sizeof(TCHAR)*/);
2070 dwLen = sprintf(sMsg,
2071 "Unknown error #0x%lX (lookup 0x%lX)",
2072 dwErr, GetLastError());
2076 sv_setpvn((SV*)sv, sMsg, dwLen);
2083 win32_fprintf(FILE *fp, const char *format, ...)
2086 va_start(marker, format); /* Initialize variable arguments. */
2088 return (vfprintf(fp, format, marker));
2092 win32_printf(const char *format, ...)
2095 va_start(marker, format); /* Initialize variable arguments. */
2097 return (vprintf(format, marker));
2101 win32_vfprintf(FILE *fp, const char *format, va_list args)
2103 return (vfprintf(fp, format, args));
2107 win32_vprintf(const char *format, va_list args)
2109 return (vprintf(format, args));
2113 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
2115 return fread(buf, size, count, fp);
2119 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
2121 return fwrite(buf, size, count, fp);
2124 #define MODE_SIZE 10
2127 win32_fopen(const char *filename, const char *mode)
2130 WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH+1];
2136 if (stricmp(filename, "/dev/null")==0)
2140 A2WHELPER(mode, wMode, sizeof(wMode));
2141 A2WHELPER(filename, wBuffer, sizeof(wBuffer));
2142 f = _wfopen(PerlDir_mapW(wBuffer), wMode);
2145 f = fopen(PerlDir_mapA(filename), mode);
2146 /* avoid buffering headaches for child processes */
2147 if (f && *mode == 'a')
2148 win32_fseek(f, 0, SEEK_END);
2152 #ifndef USE_SOCKETS_AS_HANDLES
2154 #define fdopen my_fdopen
2158 win32_fdopen(int handle, const char *mode)
2161 WCHAR wMode[MODE_SIZE];
2164 A2WHELPER(mode, wMode, sizeof(wMode));
2165 f = _wfdopen(handle, wMode);
2168 f = fdopen(handle, (char *) mode);
2169 /* avoid buffering headaches for child processes */
2170 if (f && *mode == 'a')
2171 win32_fseek(f, 0, SEEK_END);
2176 win32_freopen(const char *path, const char *mode, FILE *stream)
2179 WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH+1];
2180 if (stricmp(path, "/dev/null")==0)
2184 A2WHELPER(mode, wMode, sizeof(wMode));
2185 A2WHELPER(path, wBuffer, sizeof(wBuffer));
2186 return _wfreopen(PerlDir_mapW(wBuffer), wMode, stream);
2188 return freopen(PerlDir_mapA(path), mode, stream);
2192 win32_fclose(FILE *pf)
2194 return my_fclose(pf); /* defined in win32sck.c */
2198 win32_fputs(const char *s,FILE *pf)
2200 return fputs(s, pf);
2204 win32_fputc(int c,FILE *pf)
2210 win32_ungetc(int c,FILE *pf)
2212 return ungetc(c,pf);
2216 win32_getc(FILE *pf)
2222 win32_fileno(FILE *pf)
2228 win32_clearerr(FILE *pf)
2235 win32_fflush(FILE *pf)
2241 win32_ftell(FILE *pf)
2247 win32_fseek(FILE *pf,long offset,int origin)
2249 return fseek(pf, offset, origin);
2253 win32_fgetpos(FILE *pf,fpos_t *p)
2255 return fgetpos(pf, p);
2259 win32_fsetpos(FILE *pf,const fpos_t *p)
2261 return fsetpos(pf, p);
2265 win32_rewind(FILE *pf)
2285 win32_fstat(int fd,struct stat *sbufptr)
2287 return fstat(fd,sbufptr);
2291 win32_pipe(int *pfd, unsigned int size, int mode)
2293 return _pipe(pfd, size, mode);
2297 * a popen() clone that respects PERL5SHELL
2301 win32_popen(const char *command, const char *mode)
2303 #ifdef USE_RTL_POPEN
2304 return _popen(command, mode);
2312 /* establish which ends read and write */
2313 if (strchr(mode,'w')) {
2314 stdfd = 0; /* stdin */
2318 else if (strchr(mode,'r')) {
2319 stdfd = 1; /* stdout */
2326 /* set the correct mode */
2327 if (strchr(mode,'b'))
2329 else if (strchr(mode,'t'))
2332 ourmode = _fmode & (O_TEXT | O_BINARY);
2334 /* the child doesn't inherit handles */
2335 ourmode |= O_NOINHERIT;
2337 if (win32_pipe( p, 512, ourmode) == -1)
2340 /* save current stdfd */
2341 if ((oldfd = win32_dup(stdfd)) == -1)
2344 /* make stdfd go to child end of pipe (implicitly closes stdfd) */
2345 /* stdfd will be inherited by the child */
2346 if (win32_dup2(p[child], stdfd) == -1)
2349 /* close the child end in parent */
2350 win32_close(p[child]);
2352 /* start the child */
2355 if ((childpid = do_spawn_nowait((char*)command)) == -1)
2358 /* revert stdfd to whatever it was before */
2359 if (win32_dup2(oldfd, stdfd) == -1)
2362 /* close saved handle */
2365 sv_setiv(*av_fetch(w32_fdpid, p[parent], TRUE), childpid);
2367 /* set process id so that it can be returned by perl's open() */
2368 PL_forkprocess = childpid;
2371 /* we have an fd, return a file stream */
2372 return (win32_fdopen(p[parent], (char *)mode));
2375 /* we don't need to check for errors here */
2379 win32_dup2(oldfd, stdfd);
2384 #endif /* USE_RTL_POPEN */
2392 win32_pclose(FILE *pf)
2394 #ifdef USE_RTL_POPEN
2398 int childpid, status;
2401 sv = *av_fetch(w32_fdpid, win32_fileno(pf), TRUE);
2403 childpid = SvIVX(sv);
2415 if (win32_waitpid(childpid, &status, 0) == -1)
2420 #endif /* USE_RTL_POPEN */
2426 LPCWSTR lpExistingFileName,
2427 LPSECURITY_ATTRIBUTES lpSecurityAttributes)
2430 WCHAR wFullName[MAX_PATH+1];
2431 LPVOID lpContext = NULL;
2432 WIN32_STREAM_ID StreamId;
2433 DWORD dwSize = (char*)&StreamId.cStreamName - (char*)&StreamId;
2438 BOOL (__stdcall *pfnBackupWrite)(HANDLE, LPBYTE, DWORD, LPDWORD,
2439 BOOL, BOOL, LPVOID*) =
2440 (BOOL (__stdcall *)(HANDLE, LPBYTE, DWORD, LPDWORD,
2441 BOOL, BOOL, LPVOID*))
2442 GetProcAddress(GetModuleHandle("kernel32.dll"), "BackupWrite");
2443 if (pfnBackupWrite == NULL)
2446 dwLen = GetFullPathNameW(lpFileName, MAX_PATH, wFullName, NULL);
2449 dwLen = (dwLen+1)*sizeof(WCHAR);
2451 handle = CreateFileW(lpExistingFileName, FILE_WRITE_ATTRIBUTES,
2452 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
2453 NULL, OPEN_EXISTING, 0, NULL);
2454 if (handle == INVALID_HANDLE_VALUE)
2457 StreamId.dwStreamId = BACKUP_LINK;
2458 StreamId.dwStreamAttributes = 0;
2459 StreamId.dwStreamNameSize = 0;
2460 #if defined(__BORLANDC__) || defined(__MINGW32__)
2461 StreamId.Size.u.HighPart = 0;
2462 StreamId.Size.u.LowPart = dwLen;
2464 StreamId.Size.HighPart = 0;
2465 StreamId.Size.LowPart = dwLen;
2468 bSuccess = pfnBackupWrite(handle, (LPBYTE)&StreamId, dwSize, &dwWritten,
2469 FALSE, FALSE, &lpContext);
2471 bSuccess = pfnBackupWrite(handle, (LPBYTE)wFullName, dwLen, &dwWritten,
2472 FALSE, FALSE, &lpContext);
2473 pfnBackupWrite(handle, NULL, 0, &dwWritten, TRUE, FALSE, &lpContext);
2476 CloseHandle(handle);
2481 win32_link(const char *oldname, const char *newname)
2484 BOOL (__stdcall *pfnCreateHardLinkW)(LPCWSTR,LPCWSTR,LPSECURITY_ATTRIBUTES);
2485 WCHAR wOldName[MAX_PATH+1];
2486 WCHAR wNewName[MAX_PATH+1];
2489 Perl_croak(aTHX_ PL_no_func, "link");
2491 pfnCreateHardLinkW =
2492 (BOOL (__stdcall *)(LPCWSTR, LPCWSTR, LPSECURITY_ATTRIBUTES))
2493 GetProcAddress(GetModuleHandle("kernel32.dll"), "CreateHardLinkW");
2494 if (pfnCreateHardLinkW == NULL)
2495 pfnCreateHardLinkW = Nt4CreateHardLinkW;
2497 if ((A2WHELPER(oldname, wOldName, sizeof(wOldName))) &&
2498 (A2WHELPER(newname, wNewName, sizeof(wNewName))) &&
2499 (wcscpy(wOldName, PerlDir_mapW(wOldName)),
2500 pfnCreateHardLinkW(PerlDir_mapW(wNewName), wOldName, NULL)))
2504 errno = (GetLastError() == ERROR_FILE_NOT_FOUND) ? ENOENT : EINVAL;
2509 win32_rename(const char *oname, const char *newname)
2511 WCHAR wOldName[MAX_PATH+1];
2512 WCHAR wNewName[MAX_PATH+1];
2513 char szOldName[MAX_PATH+1];
2514 char szNewName[MAX_PATH+1];
2518 /* XXX despite what the documentation says about MoveFileEx(),
2519 * it doesn't work under Windows95!
2522 DWORD dwFlags = MOVEFILE_COPY_ALLOWED;
2524 A2WHELPER(oname, wOldName, sizeof(wOldName));
2525 A2WHELPER(newname, wNewName, sizeof(wNewName));
2526 if (wcsicmp(wNewName, wOldName))
2527 dwFlags |= MOVEFILE_REPLACE_EXISTING;
2528 wcscpy(wOldName, PerlDir_mapW(wOldName));
2529 bResult = MoveFileExW(wOldName,PerlDir_mapW(wNewName), dwFlags);
2532 if (stricmp(newname, oname))
2533 dwFlags |= MOVEFILE_REPLACE_EXISTING;
2534 strcpy(szOldName, PerlDir_mapA(oname));
2535 bResult = MoveFileExA(szOldName,PerlDir_mapA(newname), dwFlags);
2538 DWORD err = GetLastError();
2540 case ERROR_BAD_NET_NAME:
2541 case ERROR_BAD_NETPATH:
2542 case ERROR_BAD_PATHNAME:
2543 case ERROR_FILE_NOT_FOUND:
2544 case ERROR_FILENAME_EXCED_RANGE:
2545 case ERROR_INVALID_DRIVE:
2546 case ERROR_NO_MORE_FILES:
2547 case ERROR_PATH_NOT_FOUND:
2560 char szTmpName[MAX_PATH+1];
2561 char dname[MAX_PATH+1];
2562 char *endname = Nullch;
2564 DWORD from_attr, to_attr;
2566 strcpy(szOldName, PerlDir_mapA(oname));
2567 strcpy(szNewName, PerlDir_mapA(newname));
2569 /* if oname doesn't exist, do nothing */
2570 from_attr = GetFileAttributes(szOldName);
2571 if (from_attr == 0xFFFFFFFF) {
2576 /* if newname exists, rename it to a temporary name so that we
2577 * don't delete it in case oname happens to be the same file
2578 * (but perhaps accessed via a different path)
2580 to_attr = GetFileAttributes(szNewName);
2581 if (to_attr != 0xFFFFFFFF) {
2582 /* if newname is a directory, we fail
2583 * XXX could overcome this with yet more convoluted logic */
2584 if (to_attr & FILE_ATTRIBUTE_DIRECTORY) {
2588 tmplen = strlen(szNewName);
2589 strcpy(szTmpName,szNewName);
2590 endname = szTmpName+tmplen;
2591 for (; endname > szTmpName ; --endname) {
2592 if (*endname == '/' || *endname == '\\') {
2597 if (endname > szTmpName)
2598 endname = strcpy(dname,szTmpName);
2602 /* get a temporary filename in same directory
2603 * XXX is this really the best we can do? */
2604 if (!GetTempFileName((LPCTSTR)endname, "plr", 0, szTmpName)) {
2608 DeleteFile(szTmpName);
2610 retval = rename(szNewName, szTmpName);
2617 /* rename oname to newname */
2618 retval = rename(szOldName, szNewName);
2620 /* if we created a temporary file before ... */
2621 if (endname != Nullch) {
2622 /* ...and rename succeeded, delete temporary file/directory */
2624 DeleteFile(szTmpName);
2625 /* else restore it to what it was */
2627 (void)rename(szTmpName, szNewName);
2634 win32_setmode(int fd, int mode)
2636 return setmode(fd, mode);
2640 win32_lseek(int fd, long offset, int origin)
2642 return lseek(fd, offset, origin);
2652 win32_open(const char *path, int flag, ...)
2657 WCHAR wBuffer[MAX_PATH+1];
2660 pmode = va_arg(ap, int);
2663 if (stricmp(path, "/dev/null")==0)
2667 A2WHELPER(path, wBuffer, sizeof(wBuffer));
2668 return _wopen(PerlDir_mapW(wBuffer), flag, pmode);
2670 return open(PerlDir_mapA(path), flag, pmode);
2692 win32_dup2(int fd1,int fd2)
2694 return dup2(fd1,fd2);
2697 #ifdef PERL_MSVCRT_READFIX
2699 #define LF 10 /* line feed */
2700 #define CR 13 /* carriage return */
2701 #define CTRLZ 26 /* ctrl-z means eof for text */
2702 #define FOPEN 0x01 /* file handle open */
2703 #define FEOFLAG 0x02 /* end of file has been encountered */
2704 #define FCRLF 0x04 /* CR-LF across read buffer (in text mode) */
2705 #define FPIPE 0x08 /* file handle refers to a pipe */
2706 #define FAPPEND 0x20 /* file handle opened O_APPEND */
2707 #define FDEV 0x40 /* file handle refers to device */
2708 #define FTEXT 0x80 /* file handle is in text mode */
2709 #define MAX_DESCRIPTOR_COUNT (64*32) /* this is the maximun that MSVCRT can handle */
2712 _fixed_read(int fh, void *buf, unsigned cnt)
2714 int bytes_read; /* number of bytes read */
2715 char *buffer; /* buffer to read to */
2716 int os_read; /* bytes read on OS call */
2717 char *p, *q; /* pointers into buffer */
2718 char peekchr; /* peek-ahead character */
2719 ULONG filepos; /* file position after seek */
2720 ULONG dosretval; /* o.s. return value */
2722 /* validate handle */
2723 if (((unsigned)fh >= (unsigned)MAX_DESCRIPTOR_COUNT) ||
2724 !(_osfile(fh) & FOPEN))
2726 /* out of range -- return error */
2728 _doserrno = 0; /* not o.s. error */
2733 * If lockinitflag is FALSE, assume fd is device
2734 * lockinitflag is set to TRUE by open.
2736 if (_pioinfo(fh)->lockinitflag)
2737 EnterCriticalSection(&(_pioinfo(fh)->lock)); /* lock file */
2739 bytes_read = 0; /* nothing read yet */
2740 buffer = (char*)buf;
2742 if (cnt == 0 || (_osfile(fh) & FEOFLAG)) {
2743 /* nothing to read or at EOF, so return 0 read */
2747 if ((_osfile(fh) & (FPIPE|FDEV)) && _pipech(fh) != LF) {
2748 /* a pipe/device and pipe lookahead non-empty: read the lookahead
2750 *buffer++ = _pipech(fh);
2753 _pipech(fh) = LF; /* mark as empty */
2758 if (!ReadFile((HANDLE)_osfhnd(fh), buffer, cnt, (LPDWORD)&os_read, NULL))
2760 /* ReadFile has reported an error. recognize two special cases.
2762 * 1. map ERROR_ACCESS_DENIED to EBADF
2764 * 2. just return 0 if ERROR_BROKEN_PIPE has occurred. it
2765 * means the handle is a read-handle on a pipe for which
2766 * all write-handles have been closed and all data has been
2769 if ((dosretval = GetLastError()) == ERROR_ACCESS_DENIED) {
2770 /* wrong read/write mode should return EBADF, not EACCES */
2772 _doserrno = dosretval;
2776 else if (dosretval == ERROR_BROKEN_PIPE) {
2786 bytes_read += os_read; /* update bytes read */
2788 if (_osfile(fh) & FTEXT) {
2789 /* now must translate CR-LFs to LFs in the buffer */
2791 /* set CRLF flag to indicate LF at beginning of buffer */
2792 /* if ((os_read != 0) && (*(char *)buf == LF)) */
2793 /* _osfile(fh) |= FCRLF; */
2795 /* _osfile(fh) &= ~FCRLF; */
2797 _osfile(fh) &= ~FCRLF;
2799 /* convert chars in the buffer: p is src, q is dest */
2801 while (p < (char *)buf + bytes_read) {
2803 /* if fh is not a device, set ctrl-z flag */
2804 if (!(_osfile(fh) & FDEV))
2805 _osfile(fh) |= FEOFLAG;
2806 break; /* stop translating */
2811 /* *p is CR, so must check next char for LF */
2812 if (p < (char *)buf + bytes_read - 1) {
2815 *q++ = LF; /* convert CR-LF to LF */
2818 *q++ = *p++; /* store char normally */
2821 /* This is the hard part. We found a CR at end of
2822 buffer. We must peek ahead to see if next char
2827 if (!ReadFile((HANDLE)_osfhnd(fh), &peekchr, 1,
2828 (LPDWORD)&os_read, NULL))
2829 dosretval = GetLastError();
2831 if (dosretval != 0 || os_read == 0) {
2832 /* couldn't read ahead, store CR */
2836 /* peekchr now has the extra character -- we now
2837 have several possibilities:
2838 1. disk file and char is not LF; just seek back
2840 2. disk file and char is LF; store LF, don't seek back
2841 3. pipe/device and char is LF; store LF.
2842 4. pipe/device and char isn't LF, store CR and
2843 put char in pipe lookahead buffer. */
2844 if (_osfile(fh) & (FDEV|FPIPE)) {
2845 /* non-seekable device */
2850 _pipech(fh) = peekchr;
2855 if (peekchr == LF) {
2856 /* nothing read yet; must make some
2859 /* turn on this flag for tell routine */
2860 _osfile(fh) |= FCRLF;
2863 HANDLE osHandle; /* o.s. handle value */
2865 if ((osHandle = (HANDLE)_get_osfhandle(fh)) != (HANDLE)-1)
2867 if ((filepos = SetFilePointer(osHandle, -1, NULL, FILE_CURRENT)) == -1)
2868 dosretval = GetLastError();
2879 /* we now change bytes_read to reflect the true number of chars
2881 bytes_read = q - (char *)buf;
2885 if (_pioinfo(fh)->lockinitflag)
2886 LeaveCriticalSection(&(_pioinfo(fh)->lock)); /* unlock file */
2891 #endif /* PERL_MSVCRT_READFIX */
2894 win32_read(int fd, void *buf, unsigned int cnt)
2896 #ifdef PERL_MSVCRT_READFIX
2897 return _fixed_read(fd, buf, cnt);
2899 return read(fd, buf, cnt);
2904 win32_write(int fd, const void *buf, unsigned int cnt)
2906 return write(fd, buf, cnt);
2910 win32_mkdir(const char *dir, int mode)
2914 WCHAR wBuffer[MAX_PATH+1];
2915 A2WHELPER(dir, wBuffer, sizeof(wBuffer));
2916 return _wmkdir(PerlDir_mapW(wBuffer));
2918 return mkdir(PerlDir_mapA(dir)); /* just ignore mode */
2922 win32_rmdir(const char *dir)
2926 WCHAR wBuffer[MAX_PATH+1];
2927 A2WHELPER(dir, wBuffer, sizeof(wBuffer));
2928 return _wrmdir(PerlDir_mapW(wBuffer));
2930 return rmdir(PerlDir_mapA(dir));
2934 win32_chdir(const char *dir)
2938 WCHAR wBuffer[MAX_PATH+1];
2939 A2WHELPER(dir, wBuffer, sizeof(wBuffer));
2940 return _wchdir(wBuffer);
2946 win32_access(const char *path, int mode)
2950 WCHAR wBuffer[MAX_PATH+1];
2951 A2WHELPER(path, wBuffer, sizeof(wBuffer));
2952 return _waccess(PerlDir_mapW(wBuffer), mode);
2954 return access(PerlDir_mapA(path), mode);
2958 win32_chmod(const char *path, int mode)
2962 WCHAR wBuffer[MAX_PATH+1];
2963 A2WHELPER(path, wBuffer, sizeof(wBuffer));
2964 return _wchmod(PerlDir_mapW(wBuffer), mode);
2966 return chmod(PerlDir_mapA(path), mode);
2971 create_command_line(const char* command, const char * const *args)
2975 char *cmd, *ptr, *arg;
2976 STRLEN len = strlen(command) + 1;
2978 for (index = 0; (ptr = (char*)args[index]) != NULL; ++index)
2979 len += strlen(ptr) + 1;
2981 New(1310, cmd, len, char);
2983 strcpy(ptr, command);
2985 for (index = 0; (arg = (char*)args[index]) != NULL; ++index) {
2995 qualified_path(const char *cmd)
2999 char *fullcmd, *curfullcmd;
3005 fullcmd = (char*)cmd;
3007 if (*fullcmd == '/' || *fullcmd == '\\')
3014 pathstr = win32_getenv("PATH");
3015 New(0, fullcmd, MAX_PATH+1, char);
3016 curfullcmd = fullcmd;
3021 /* start by appending the name to the current prefix */
3022 strcpy(curfullcmd, cmd);
3023 curfullcmd += cmdlen;
3025 /* if it doesn't end with '.', or has no extension, try adding
3026 * a trailing .exe first */
3027 if (cmd[cmdlen-1] != '.'
3028 && (cmdlen < 4 || cmd[cmdlen-4] != '.'))
3030 strcpy(curfullcmd, ".exe");
3031 res = GetFileAttributes(fullcmd);
3032 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
3037 /* that failed, try the bare name */
3038 res = GetFileAttributes(fullcmd);
3039 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
3042 /* quit if no other path exists, or if cmd already has path */
3043 if (!pathstr || !*pathstr || has_slash)
3046 /* skip leading semis */
3047 while (*pathstr == ';')
3050 /* build a new prefix from scratch */
3051 curfullcmd = fullcmd;
3052 while (*pathstr && *pathstr != ';') {
3053 if (*pathstr == '"') { /* foo;"baz;etc";bar */
3054 pathstr++; /* skip initial '"' */
3055 while (*pathstr && *pathstr != '"') {
3056 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
3057 *curfullcmd++ = *pathstr;
3061 pathstr++; /* skip trailing '"' */
3064 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
3065 *curfullcmd++ = *pathstr;
3070 pathstr++; /* skip trailing semi */
3071 if (curfullcmd > fullcmd /* append a dir separator */
3072 && curfullcmd[-1] != '/' && curfullcmd[-1] != '\\')
3074 *curfullcmd++ = '\\';
3082 /* The following are just place holders.
3083 * Some hosts may provide and environment that the OS is
3084 * not tracking, therefore, these host must provide that
3085 * environment and the current directory to CreateProcess
3095 free_childenv(void* d)
3104 char szfilename[(MAX_PATH+1)*2];
3106 WCHAR wfilename[MAX_PATH+1];
3107 GetCurrentDirectoryW(MAX_PATH+1, wfilename);
3108 W2AHELPER(wfilename, szfilename, sizeof(szfilename));
3111 GetCurrentDirectoryA(MAX_PATH+1, szfilename);
3114 New(0, ptr, strlen(szfilename)+1, char);
3115 strcpy(ptr, szfilename);
3120 free_childdir(char* d)
3127 /* XXX this needs to be made more compatible with the spawnvp()
3128 * provided by the various RTLs. In particular, searching for
3129 * *.{com,bat,cmd} files (as done by the RTLs) is unimplemented.
3130 * This doesn't significantly affect perl itself, because we
3131 * always invoke things using PERL5SHELL if a direct attempt to
3132 * spawn the executable fails.
3134 * XXX splitting and rejoining the commandline between do_aspawn()
3135 * and win32_spawnvp() could also be avoided.
3139 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
3141 #ifdef USE_RTL_SPAWNVP
3142 return spawnvp(mode, cmdname, (char * const *)argv);
3149 STARTUPINFO StartupInfo;
3150 PROCESS_INFORMATION ProcessInformation;
3153 char *cmd = create_command_line(cmdname, strcmp(cmdname, argv[0]) == 0
3155 char *fullcmd = Nullch;
3157 env = PerlEnv_get_childenv();
3158 dir = PerlEnv_get_childdir();
3161 case P_NOWAIT: /* asynch + remember result */
3162 if (w32_num_children >= MAXIMUM_WAIT_OBJECTS) {
3168 case P_WAIT: /* synchronous execution */
3170 default: /* invalid mode */
3175 memset(&StartupInfo,0,sizeof(StartupInfo));
3176 StartupInfo.cb = sizeof(StartupInfo);
3177 PerlEnv_get_child_IO(&tbl);
3178 StartupInfo.hStdInput = tbl.childStdIn;
3179 StartupInfo.hStdOutput = tbl.childStdOut;
3180 StartupInfo.hStdError = tbl.childStdErr;
3181 if (StartupInfo.hStdInput != INVALID_HANDLE_VALUE &&
3182 StartupInfo.hStdOutput != INVALID_HANDLE_VALUE &&
3183 StartupInfo.hStdError != INVALID_HANDLE_VALUE)
3185 StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
3188 create |= CREATE_NEW_CONSOLE;
3192 if (!CreateProcess(cmdname, /* search PATH to find executable */
3193 cmd, /* executable, and its arguments */
3194 NULL, /* process attributes */
3195 NULL, /* thread attributes */
3196 TRUE, /* inherit handles */
3197 create, /* creation flags */
3198 (LPVOID)env, /* inherit environment */
3199 dir, /* inherit cwd */
3201 &ProcessInformation))
3203 /* initial NULL argument to CreateProcess() does a PATH
3204 * search, but it always first looks in the directory
3205 * where the current process was started, which behavior
3206 * is undesirable for backward compatibility. So we
3207 * jump through our own hoops by picking out the path
3208 * we really want it to use. */
3210 fullcmd = qualified_path(cmdname);
3221 if (mode == P_NOWAIT) {
3222 /* asynchronous spawn -- store handle, return PID */
3223 w32_child_handles[w32_num_children] = ProcessInformation.hProcess;
3224 w32_child_pids[w32_num_children] = ProcessInformation.dwProcessId;
3225 ret = (int)ProcessInformation.dwProcessId;
3230 WaitForSingleObject(ProcessInformation.hProcess, INFINITE);
3231 GetExitCodeProcess(ProcessInformation.hProcess, &status);
3233 CloseHandle(ProcessInformation.hProcess);
3236 CloseHandle(ProcessInformation.hThread);
3239 PerlEnv_free_childenv(env);
3240 PerlEnv_free_childdir(dir);
3248 win32_execv(const char *cmdname, const char *const *argv)
3252 /* if this is a pseudo-forked child, we just want to spawn
3253 * the new program, and return */
3255 return spawnv(P_WAIT, cmdname, (char *const *)argv);
3257 return execv(cmdname, (char *const *)argv);
3261 win32_execvp(const char *cmdname, const char *const *argv)
3265 /* if this is a pseudo-forked child, we just want to spawn
3266 * the new program, and return */
3268 return win32_spawnvp(P_WAIT, cmdname, (char *const *)argv);
3270 return execvp(cmdname, (char *const *)argv);
3274 win32_perror(const char *str)
3280 win32_setbuf(FILE *pf, char *buf)
3286 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
3288 return setvbuf(pf, buf, type, size);
3292 win32_flushall(void)
3298 win32_fcloseall(void)
3304 win32_fgets(char *s, int n, FILE *pf)
3306 return fgets(s, n, pf);
3316 win32_fgetc(FILE *pf)
3322 win32_putc(int c, FILE *pf)
3328 win32_puts(const char *s)
3340 win32_putchar(int c)
3347 #ifndef USE_PERL_SBRK
3349 static char *committed = NULL;
3350 static char *base = NULL;
3351 static char *reserved = NULL;
3352 static char *brk = NULL;
3353 static DWORD pagesize = 0;
3354 static DWORD allocsize = 0;
3362 GetSystemInfo(&info);
3363 /* Pretend page size is larger so we don't perpetually
3364 * call the OS to commit just one page ...
3366 pagesize = info.dwPageSize << 3;
3367 allocsize = info.dwAllocationGranularity;
3369 /* This scheme fails eventually if request for contiguous
3370 * block is denied so reserve big blocks - this is only
3371 * address space not memory ...
3373 if (brk+need >= reserved)
3375 DWORD size = 64*1024*1024;
3377 if (committed && reserved && committed < reserved)
3379 /* Commit last of previous chunk cannot span allocations */
3380 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
3382 committed = reserved;
3384 /* Reserve some (more) space
3385 * Note this is a little sneaky, 1st call passes NULL as reserved
3386 * so lets system choose where we start, subsequent calls pass
3387 * the old end address so ask for a contiguous block
3389 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
3392 reserved = addr+size;
3407 if (brk > committed)
3409 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
3410 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
3425 win32_malloc(size_t size)
3427 return malloc(size);
3431 win32_calloc(size_t numitems, size_t size)
3433 return calloc(numitems,size);
3437 win32_realloc(void *block, size_t size)
3439 return realloc(block,size);
3443 win32_free(void *block)
3450 win32_open_osfhandle(long handle, int flags)
3452 #ifdef USE_FIXED_OSFHANDLE
3454 return my_open_osfhandle(handle, flags);
3456 return _open_osfhandle(handle, flags);
3460 win32_get_osfhandle(int fd)
3462 return _get_osfhandle(fd);
3466 win32_dynaload(const char* filename)
3471 WCHAR wfilename[MAX_PATH+1];
3472 A2WHELPER(filename, wfilename, sizeof(wfilename));
3473 hModule = LoadLibraryExW(PerlDir_mapW(wfilename), NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
3476 hModule = LoadLibraryExA(PerlDir_mapA(filename), NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
3489 /* Make the host for current directory */
3490 char* ptr = PerlEnv_get_childdir();
3493 * then it worked, set PV valid,
3494 * else return 'undef'
3497 SV *sv = sv_newmortal();
3499 PerlEnv_free_childdir(ptr);
3514 Perl_croak(aTHX_ "usage: Win32::SetCurrentDirectory($cwd)");
3515 if (!PerlDir_chdir(SvPV_nolen(ST(0))))
3522 XS(w32_GetNextAvailDrive)
3526 char root[] = "_:\\";
3531 if (GetDriveType(root) == 1) {
3540 XS(w32_GetLastError)
3544 XSRETURN_IV(GetLastError());
3548 XS(w32_SetLastError)
3552 Perl_croak(aTHX_ "usage: Win32::SetLastError($error)");
3553 SetLastError(SvIV(ST(0)));
3561 char *name = w32_getlogin_buffer;
3562 DWORD size = sizeof(w32_getlogin_buffer);
3564 if (GetUserName(name,&size)) {
3565 /* size includes NULL */
3566 ST(0) = sv_2mortal(newSVpvn(name,size-1));
3576 char name[MAX_COMPUTERNAME_LENGTH+1];
3577 DWORD size = sizeof(name);
3579 if (GetComputerName(name,&size)) {
3580 /* size does NOT include NULL :-( */
3581 ST(0) = sv_2mortal(newSVpvn(name,size));
3592 HINSTANCE hNetApi32 = LoadLibrary("netapi32.dll");
3593 DWORD (__stdcall *pfnNetApiBufferFree)(LPVOID Buffer);
3594 DWORD (__stdcall *pfnNetWkstaGetInfo)(LPWSTR servername, DWORD level,
3598 pfnNetApiBufferFree = (DWORD (__stdcall *)(void *))
3599 GetProcAddress(hNetApi32, "NetApiBufferFree");
3600 pfnNetWkstaGetInfo = (DWORD (__stdcall *)(LPWSTR, DWORD, void *))
3601 GetProcAddress(hNetApi32, "NetWkstaGetInfo");
3604 if (hNetApi32 && pfnNetWkstaGetInfo && pfnNetApiBufferFree) {
3605 /* this way is more reliable, in case user has a local account. */
3607 DWORD dnamelen = sizeof(dname);
3609 DWORD wki100_platform_id;
3610 LPWSTR wki100_computername;
3611 LPWSTR wki100_langroup;
3612 DWORD wki100_ver_major;
3613 DWORD wki100_ver_minor;
3615 /* NERR_Success *is* 0*/
3616 if (0 == pfnNetWkstaGetInfo(NULL, 100, &pwi)) {
3617 if (pwi->wki100_langroup && *(pwi->wki100_langroup)) {
3618 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_langroup,
3619 -1, (LPSTR)dname, dnamelen, NULL, NULL);
3622 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_computername,
3623 -1, (LPSTR)dname, dnamelen, NULL, NULL);
3625 pfnNetApiBufferFree(pwi);
3626 FreeLibrary(hNetApi32);
3629 FreeLibrary(hNetApi32);
3632 /* Win95 doesn't have NetWksta*(), so do it the old way */
3634 DWORD size = sizeof(name);
3636 FreeLibrary(hNetApi32);
3637 if (GetUserName(name,&size)) {
3638 char sid[ONE_K_BUFSIZE];
3639 DWORD sidlen = sizeof(sid);
3641 DWORD dnamelen = sizeof(dname);
3643 if (LookupAccountName(NULL, name, (PSID)&sid, &sidlen,
3644 dname, &dnamelen, &snu)) {
3645 XSRETURN_PV(dname); /* all that for this */
3657 DWORD flags, filecomplen;
3658 if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
3659 &flags, fsname, sizeof(fsname))) {
3660 if (GIMME_V == G_ARRAY) {
3661 XPUSHs(sv_2mortal(newSVpvn(fsname,strlen(fsname))));
3662 XPUSHs(sv_2mortal(newSViv(flags)));
3663 XPUSHs(sv_2mortal(newSViv(filecomplen)));
3668 XSRETURN_PV(fsname);
3674 XS(w32_GetOSVersion)
3677 OSVERSIONINFOA osver;
3680 OSVERSIONINFOW osverw;
3681 char szCSDVersion[sizeof(osverw.szCSDVersion)];
3682 osverw.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
3683 if (!GetVersionExW(&osverw)) {
3686 W2AHELPER(osverw.szCSDVersion, szCSDVersion, sizeof(szCSDVersion));
3687 XPUSHs(newSVpvn(szCSDVersion, strlen(szCSDVersion)));
3688 osver.dwMajorVersion = osverw.dwMajorVersion;
3689 osver.dwMinorVersion = osverw.dwMinorVersion;
3690 osver.dwBuildNumber = osverw.dwBuildNumber;
3691 osver.dwPlatformId = osverw.dwPlatformId;
3694 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOA);
3695 if (!GetVersionExA(&osver)) {
3698 XPUSHs(newSVpvn(osver.szCSDVersion, strlen(osver.szCSDVersion)));
3700 XPUSHs(newSViv(osver.dwMajorVersion));
3701 XPUSHs(newSViv(osver.dwMinorVersion));
3702 XPUSHs(newSViv(osver.dwBuildNumber));
3703 XPUSHs(newSViv(osver.dwPlatformId));
3712 XSRETURN_IV(IsWinNT());
3720 XSRETURN_IV(IsWin95());
3724 XS(w32_FormatMessage)
3728 char msgbuf[ONE_K_BUFSIZE];
3731 Perl_croak(aTHX_ "usage: Win32::FormatMessage($errno)");
3734 WCHAR wmsgbuf[ONE_K_BUFSIZE];
3735 if (FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM,
3736 &source, SvIV(ST(0)), 0,
3737 wmsgbuf, ONE_K_BUFSIZE-1, NULL))
3739 W2AHELPER(wmsgbuf, msgbuf, sizeof(msgbuf));
3740 XSRETURN_PV(msgbuf);
3744 if (FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM,
3745 &source, SvIV(ST(0)), 0,
3746 msgbuf, sizeof(msgbuf)-1, NULL))
3747 XSRETURN_PV(msgbuf);
3758 PROCESS_INFORMATION stProcInfo;
3759 STARTUPINFO stStartInfo;
3760 BOOL bSuccess = FALSE;
3763 Perl_croak(aTHX_ "usage: Win32::Spawn($cmdName, $args, $PID)");
3765 cmd = SvPV_nolen(ST(0));
3766 args = SvPV_nolen(ST(1));
3768 memset(&stStartInfo, 0, sizeof(stStartInfo)); /* Clear the block */
3769 stStartInfo.cb = sizeof(stStartInfo); /* Set the structure size */
3770 stStartInfo.dwFlags = STARTF_USESHOWWINDOW; /* Enable wShowWindow control */
3771 stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE; /* Start min (normal) */
3774 cmd, /* Image path */
3775 args, /* Arguments for command line */
3776 NULL, /* Default process security */
3777 NULL, /* Default thread security */
3778 FALSE, /* Must be TRUE to use std handles */
3779 NORMAL_PRIORITY_CLASS, /* No special scheduling */
3780 NULL, /* Inherit our environment block */
3781 NULL, /* Inherit our currrent directory */
3782 &stStartInfo, /* -> Startup info */
3783 &stProcInfo)) /* <- Process info (if OK) */
3785 CloseHandle(stProcInfo.hThread);/* library source code does this. */
3786 sv_setiv(ST(2), stProcInfo.dwProcessId);
3789 XSRETURN_IV(bSuccess);
3793 XS(w32_GetTickCount)
3796 DWORD msec = GetTickCount();
3804 XS(w32_GetShortPathName)
3811 Perl_croak(aTHX_ "usage: Win32::GetShortPathName($longPathName)");
3813 shortpath = sv_mortalcopy(ST(0));
3814 SvUPGRADE(shortpath, SVt_PV);
3815 /* src == target is allowed */
3817 len = GetShortPathName(SvPVX(shortpath),
3820 } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
3822 SvCUR_set(shortpath,len);
3830 XS(w32_GetFullPathName)
3839 Perl_croak(aTHX_ "usage: Win32::GetFullPathName($filename)");
3842 fullpath = sv_mortalcopy(filename);
3843 SvUPGRADE(fullpath, SVt_PV);
3845 len = GetFullPathName(SvPVX(filename),
3849 } while (len >= SvLEN(fullpath) && sv_grow(fullpath,len+1));
3851 if (GIMME_V == G_ARRAY) {
3853 XST_mPV(1,filepart);
3854 len = filepart - SvPVX(fullpath);
3857 SvCUR_set(fullpath,len);
3865 XS(w32_GetLongPathName)
3869 char tmpbuf[MAX_PATH+1];
3874 Perl_croak(aTHX_ "usage: Win32::GetLongPathName($pathname)");
3877 pathstr = SvPV(path,len);
3878 strcpy(tmpbuf, pathstr);
3879 pathstr = win32_longpath(tmpbuf);
3881 ST(0) = sv_2mortal(newSVpvn(pathstr, strlen(pathstr)));
3892 Perl_croak(aTHX_ "usage: Win32::Sleep($milliseconds)");
3903 Perl_croak(aTHX_ "usage: Win32::CopyFile($from, $to, $overwrite)");
3905 WCHAR wSourceFile[MAX_PATH+1];
3906 WCHAR wDestFile[MAX_PATH+1];
3907 A2WHELPER(SvPV_nolen(ST(0)), wSourceFile, sizeof(wSourceFile));
3908 wcscpy(wSourceFile, PerlDir_mapW(wSourceFile));
3909 A2WHELPER(SvPV_nolen(ST(1)), wDestFile, sizeof(wDestFile));
3910 bResult = CopyFileW(wSourceFile, PerlDir_mapW(wDestFile), !SvTRUE(ST(2)));
3913 char szSourceFile[MAX_PATH+1];
3914 strcpy(szSourceFile, PerlDir_mapA(SvPV_nolen(ST(0))));
3915 bResult = CopyFileA(szSourceFile, PerlDir_mapA(SvPV_nolen(ST(1))), !SvTRUE(ST(2)));
3924 Perl_init_os_extras(void)
3927 char *file = __FILE__;
3930 w32_perlshell_tokens = Nullch;
3931 w32_perlshell_items = -1;
3932 w32_fdpid = newAV(); /* XXX needs to be in Perl_win32_init()? */
3933 New(1313, w32_children, 1, child_tab);
3934 w32_num_children = 0;
3935 w32_init_socktype = 0;
3938 New(1313, w32_pseudo_children, 1, child_tab);
3939 w32_num_pseudo_children = 0;
3942 /* these names are Activeware compatible */
3943 newXS("Win32::GetCwd", w32_GetCwd, file);
3944 newXS("Win32::SetCwd", w32_SetCwd, file);
3945 newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
3946 newXS("Win32::GetLastError", w32_GetLastError, file);
3947 newXS("Win32::SetLastError", w32_SetLastError, file);
3948 newXS("Win32::LoginName", w32_LoginName, file);
3949 newXS("Win32::NodeName", w32_NodeName, file);
3950 newXS("Win32::DomainName", w32_DomainName, file);
3951 newXS("Win32::FsType", w32_FsType, file);
3952 newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
3953 newXS("Win32::IsWinNT", w32_IsWinNT, file);
3954 newXS("Win32::IsWin95", w32_IsWin95, file);
3955 newXS("Win32::FormatMessage", w32_FormatMessage, file);
3956 newXS("Win32::Spawn", w32_Spawn, file);
3957 newXS("Win32::GetTickCount", w32_GetTickCount, file);
3958 newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
3959 newXS("Win32::GetFullPathName", w32_GetFullPathName, file);
3960 newXS("Win32::GetLongPathName", w32_GetLongPathName, file);
3961 newXS("Win32::CopyFile", w32_CopyFile, file);
3962 newXS("Win32::Sleep", w32_Sleep, file);
3964 /* XXX Bloat Alert! The following Activeware preloads really
3965 * ought to be part of Win32::Sys::*, so they're not included
3968 /* LookupAccountName
3970 * InitiateSystemShutdown
3971 * AbortSystemShutdown
3972 * ExpandEnvrironmentStrings
3977 Perl_win32_init(int *argcp, char ***argvp)
3979 /* Disable floating point errors, Perl will trap the ones we
3980 * care about. VC++ RTL defaults to switching these off
3981 * already, but the Borland RTL doesn't. Since we don't
3982 * want to be at the vendor's whim on the default, we set
3983 * it explicitly here.
3985 #if !defined(_ALPHA_) && !defined(__GNUC__)
3986 _control87(MCW_EM, MCW_EM);
3992 win32_get_child_IO(child_IO_table* ptbl)
3994 ptbl->childStdIn = GetStdHandle(STD_INPUT_HANDLE);
3995 ptbl->childStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
3996 ptbl->childStdErr = GetStdHandle(STD_ERROR_HANDLE);
4003 # undef Perl_sys_intern_dup
4004 # define Perl_sys_intern_dup CPerlObj::Perl_sys_intern_dup
4009 Perl_sys_intern_dup(pTHX_ struct interp_intern *src, struct interp_intern *dst)
4011 dst->perlshell_tokens = Nullch;
4012 dst->perlshell_vec = (char**)NULL;
4013 dst->perlshell_items = 0;
4014 dst->fdpid = newAV();
4015 Newz(1313, dst->children, 1, child_tab);
4016 Newz(1313, dst->pseudo_children, 1, child_tab);
4018 dst->children->num = 0;
4019 dst->thr_intern.Winit_socktype = src->thr_intern.Winit_socktype;
4029 win32_free_argvw(pTHXo_ void *ptr)
4031 char** argv = (char**)ptr;
4039 win32_argv2utf8(int argc, char** argv)
4044 LPWSTR* lpwStr = CommandLineToArgvW(GetCommandLineW(), &wargc);
4045 if (lpwStr && argc) {
4047 length = WideCharToMultiByte(CP_UTF8, 0, lpwStr[--wargc], -1, NULL, 0, NULL, NULL);
4048 Newz(0, psz, length, char);
4049 WideCharToMultiByte(CP_UTF8, 0, lpwStr[wargc], -1, psz, length, NULL, NULL);
4052 call_atexit(win32_free_argvw, argv);
4054 GlobalFree((HGLOBAL)lpwStr);