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);
127 /* *svp (if non-NULL) is expected to be POK (valid allocated SvPVX(*svp)) */
129 get_regstr_from(HKEY hkey, const char *valuename, SV **svp)
131 /* Retrieve a REG_SZ or REG_EXPAND_SZ from the registry */
134 const char *subkey = "Software\\Perl";
138 retval = RegOpenKeyEx(hkey, subkey, 0, KEY_READ, &handle);
139 if (retval == ERROR_SUCCESS) {
141 retval = RegQueryValueEx(handle, valuename, 0, &type, NULL, &datalen);
142 if (retval == ERROR_SUCCESS && type == REG_SZ) {
145 *svp = sv_2mortal(newSVpvn("",0));
146 SvGROW(*svp, datalen);
147 retval = RegQueryValueEx(handle, valuename, 0, NULL,
148 (PBYTE)SvPVX(*svp), &datalen);
149 if (retval == ERROR_SUCCESS) {
151 SvCUR_set(*svp,datalen-1);
159 /* *svp (if non-NULL) is expected to be POK (valid allocated SvPVX(*svp)) */
161 get_regstr(const char *valuename, SV **svp)
163 char *str = get_regstr_from(HKEY_CURRENT_USER, valuename, svp);
165 str = get_regstr_from(HKEY_LOCAL_MACHINE, valuename, svp);
169 /* *prev_pathp (if non-NULL) is expected to be POK (valid allocated SvPVX(sv)) */
171 get_emd_part(SV **prev_pathp, char *trailing_path, ...)
175 char mod_name[MAX_PATH+1];
179 int oldsize, newsize;
182 va_start(ap, trailing_path);
183 strip = va_arg(ap, char *);
185 sprintf(base, "%d.%d", (int)PERL_REVISION, (int)PERL_VERSION);
186 baselen = strlen(base);
188 if (!*w32_module_name) {
189 GetModuleFileName((HMODULE)((w32_perldll_handle == INVALID_HANDLE_VALUE)
190 ? GetModuleHandle(NULL)
191 : w32_perldll_handle),
192 w32_module_name, sizeof(w32_module_name));
194 /* try to get full path to binary (which may be mangled when perl is
195 * run from a 16-bit app) */
196 /*PerlIO_printf(Perl_debug_log, "Before %s\n", w32_module_name);*/
197 (void)win32_longpath(w32_module_name);
198 /*PerlIO_printf(Perl_debug_log, "After %s\n", w32_module_name);*/
200 /* normalize to forward slashes */
201 ptr = w32_module_name;
208 strcpy(mod_name, w32_module_name);
209 ptr = strrchr(mod_name, '/');
210 while (ptr && strip) {
211 /* look for directories to skip back */
214 ptr = strrchr(mod_name, '/');
215 /* avoid stripping component if there is no slash,
216 * or it doesn't match ... */
217 if (!ptr || stricmp(ptr+1, strip) != 0) {
218 /* ... but not if component matches m|5\.$patchlevel.*| */
219 if (!ptr || !(*strip == '5' && *(ptr+1) == '5'
220 && strncmp(strip, base, baselen) == 0
221 && strncmp(ptr+1, base, baselen) == 0))
227 strip = va_arg(ap, char *);
235 strcpy(++ptr, trailing_path);
237 /* only add directory if it exists */
238 if (GetFileAttributes(mod_name) != (DWORD) -1) {
239 /* directory exists */
242 *prev_pathp = sv_2mortal(newSVpvn("",0));
243 sv_catpvn(*prev_pathp, ";", 1);
244 sv_catpv(*prev_pathp, mod_name);
245 return SvPVX(*prev_pathp);
252 win32_get_privlib(char *pl)
255 char *stdlib = "lib";
256 char buffer[MAX_PATH+1];
259 /* $stdlib = $HKCU{"lib-$]"} || $HKLM{"lib-$]"} || $HKCU{"lib"} || $HKLM{"lib"} || ""; */
260 sprintf(buffer, "%s-%s", stdlib, pl);
261 if (!get_regstr(buffer, &sv))
262 (void)get_regstr(stdlib, &sv);
264 /* $stdlib .= ";$EMD/../../lib" */
265 return get_emd_part(&sv, stdlib, ARCHNAME, "bin", Nullch);
269 win32_get_sitelib(char *pl)
272 char *sitelib = "sitelib";
274 char pathstr[MAX_PATH+1];
280 /* $HKCU{"sitelib-$]"} || $HKLM{"sitelib-$]"} . ---; */
281 sprintf(regstr, "%s-%s", sitelib, pl);
282 (void)get_regstr(regstr, &sv1);
285 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/site/$]/lib"; */
286 sprintf(pathstr, "site/%s/lib", pl);
287 (void)get_emd_part(&sv1, pathstr, ARCHNAME, "bin", pl, Nullch);
289 /* $HKCU{'sitelib'} || $HKLM{'sitelib'} . ---; */
290 (void)get_regstr(sitelib, &sv2);
293 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/site/lib"; */
294 (void)get_emd_part(&sv2, "site/lib", ARCHNAME, "bin", pl, Nullch);
303 sv_catpvn(sv1, ";", 1);
311 has_shell_metachars(char *ptr)
317 * Scan string looking for redirection (< or >) or pipe
318 * characters (|) that are not in a quoted string.
319 * Shell variable interpolation (%VAR%) can also happen inside strings.
351 #if !defined(PERL_IMPLICIT_SYS)
352 /* since the current process environment is being updated in util.c
353 * the library functions will get the correct environment
356 Perl_my_popen(pTHX_ char *cmd, char *mode)
359 #define fixcmd(x) { \
360 char *pspace = strchr((x),' '); \
363 while (p < pspace) { \
374 PERL_FLUSHALL_FOR_CHILD;
375 return win32_popen(cmd, mode);
379 Perl_my_pclose(pTHX_ PerlIO *fp)
381 return win32_pclose(fp);
385 DllExport unsigned long
388 static OSVERSIONINFO osver;
390 if (osver.dwPlatformId != w32_platform) {
391 memset(&osver, 0, sizeof(OSVERSIONINFO));
392 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
393 GetVersionEx(&osver);
394 w32_platform = osver.dwPlatformId;
396 return (unsigned long)w32_platform;
405 return -((int)w32_pseudo_id);
410 /* Tokenize a string. Words are null-separated, and the list
411 * ends with a doubled null. Any character (except null and
412 * including backslash) may be escaped by preceding it with a
413 * backslash (the backslash will be stripped).
414 * Returns number of words in result buffer.
417 tokenize(const char *str, char **dest, char ***destv)
419 char *retstart = Nullch;
420 char **retvstart = 0;
424 int slen = strlen(str);
426 register char **retv;
427 New(1307, ret, slen+2, char);
428 New(1308, retv, (slen+3)/2, char*);
436 if (*ret == '\\' && *str)
438 else if (*ret == ' ') {
454 retvstart[items] = Nullch;
467 if (!w32_perlshell_tokens) {
468 /* we don't use COMSPEC here for two reasons:
469 * 1. the same reason perl on UNIX doesn't use SHELL--rampant and
470 * uncontrolled unportability of the ensuing scripts.
471 * 2. PERL5SHELL could be set to a shell that may not be fit for
472 * interactive use (which is what most programs look in COMSPEC
475 const char* defaultshell = (IsWinNT()
476 ? "cmd.exe /x/c" : "command.com /c");
477 const char *usershell = getenv("PERL5SHELL");
478 w32_perlshell_items = tokenize(usershell ? usershell : defaultshell,
479 &w32_perlshell_tokens,
485 do_aspawn(void *vreally, void **vmark, void **vsp)
488 SV *really = (SV*)vreally;
489 SV **mark = (SV**)vmark;
501 New(1306, argv, (sp - mark) + w32_perlshell_items + 2, char*);
503 if (SvNIOKp(*(mark+1)) && !SvPOKp(*(mark+1))) {
508 while (++mark <= sp) {
509 if (*mark && (str = SvPV_nolen(*mark)))
516 status = win32_spawnvp(flag,
517 (const char*)(really ? SvPV_nolen(really) : argv[0]),
518 (const char* const*)argv);
520 if (status < 0 && (errno == ENOEXEC || errno == ENOENT)) {
521 /* possible shell-builtin, invoke with shell */
523 sh_items = w32_perlshell_items;
525 argv[index+sh_items] = argv[index];
526 while (--sh_items >= 0)
527 argv[sh_items] = w32_perlshell_vec[sh_items];
529 status = win32_spawnvp(flag,
530 (const char*)(really ? SvPV_nolen(really) : argv[0]),
531 (const char* const*)argv);
534 if (flag != P_NOWAIT) {
537 if (ckWARN(WARN_EXEC))
538 Perl_warner(aTHX_ WARN_EXEC, "Can't spawn \"%s\": %s", argv[0], strerror(errno));
543 PL_statusvalue = status;
550 do_spawn2(char *cmd, int exectype)
557 BOOL needToTry = TRUE;
560 /* Save an extra exec if possible. See if there are shell
561 * metacharacters in it */
562 if (!has_shell_metachars(cmd)) {
563 New(1301,argv, strlen(cmd) / 2 + 2, char*);
564 New(1302,cmd2, strlen(cmd) + 1, char);
567 for (s = cmd2; *s;) {
568 while (*s && isSPACE(*s))
572 while (*s && !isSPACE(*s))
581 status = win32_spawnvp(P_WAIT, argv[0],
582 (const char* const*)argv);
584 case EXECF_SPAWN_NOWAIT:
585 status = win32_spawnvp(P_NOWAIT, argv[0],
586 (const char* const*)argv);
589 status = win32_execvp(argv[0], (const char* const*)argv);
592 if (status != -1 || errno == 0)
602 New(1306, argv, w32_perlshell_items + 2, char*);
603 while (++i < w32_perlshell_items)
604 argv[i] = w32_perlshell_vec[i];
609 status = win32_spawnvp(P_WAIT, argv[0],
610 (const char* const*)argv);
612 case EXECF_SPAWN_NOWAIT:
613 status = win32_spawnvp(P_NOWAIT, argv[0],
614 (const char* const*)argv);
617 status = win32_execvp(argv[0], (const char* const*)argv);
623 if (exectype != EXECF_SPAWN_NOWAIT) {
626 if (ckWARN(WARN_EXEC))
627 Perl_warner(aTHX_ WARN_EXEC, "Can't %s \"%s\": %s",
628 (exectype == EXECF_EXEC ? "exec" : "spawn"),
629 cmd, strerror(errno));
634 PL_statusvalue = status;
642 return do_spawn2(cmd, EXECF_SPAWN);
646 do_spawn_nowait(char *cmd)
648 return do_spawn2(cmd, EXECF_SPAWN_NOWAIT);
652 Perl_do_exec(pTHX_ char *cmd)
654 do_spawn2(cmd, EXECF_EXEC);
658 /* The idea here is to read all the directory names into a string table
659 * (separated by nulls) and when one of the other dir functions is called
660 * return the pointer to the current file name.
663 win32_opendir(char *filename)
669 char scanname[MAX_PATH+3];
671 WIN32_FIND_DATAA aFindData;
672 WIN32_FIND_DATAW wFindData;
674 char buffer[MAX_PATH*2];
675 WCHAR wbuffer[MAX_PATH+1];
678 len = strlen(filename);
682 /* check to see if filename is a directory */
683 if (win32_stat(filename, &sbuf) < 0 || !S_ISDIR(sbuf.st_mode))
686 /* Get us a DIR structure */
687 Newz(1303, dirp, 1, DIR);
689 /* Create the search pattern */
690 strcpy(scanname, filename);
692 /* bare drive name means look in cwd for drive */
693 if (len == 2 && isALPHA(scanname[0]) && scanname[1] == ':') {
694 scanname[len++] = '.';
695 scanname[len++] = '/';
697 else if (scanname[len-1] != '/' && scanname[len-1] != '\\') {
698 scanname[len++] = '/';
700 scanname[len++] = '*';
701 scanname[len] = '\0';
703 /* do the FindFirstFile call */
705 A2WHELPER(scanname, wbuffer, sizeof(wbuffer));
706 fh = FindFirstFileW(PerlDir_mapW(wbuffer), &wFindData);
709 fh = FindFirstFileA(PerlDir_mapA(scanname), &aFindData);
712 if (fh == INVALID_HANDLE_VALUE) {
713 DWORD err = GetLastError();
714 /* FindFirstFile() fails on empty drives! */
716 case ERROR_FILE_NOT_FOUND:
718 case ERROR_NO_MORE_FILES:
719 case ERROR_PATH_NOT_FOUND:
722 case ERROR_NOT_ENOUGH_MEMORY:
733 /* now allocate the first part of the string table for
734 * the filenames that we find.
737 W2AHELPER(wFindData.cFileName, buffer, sizeof(buffer));
741 ptr = aFindData.cFileName;
748 New(1304, dirp->start, dirp->size, char);
749 strcpy(dirp->start, ptr);
751 dirp->end = dirp->curr = dirp->start;
757 /* Readdir just returns the current string pointer and bumps the
758 * string pointer to the nDllExport entry.
760 DllExport struct direct *
761 win32_readdir(DIR *dirp)
766 /* first set up the structure to return */
767 len = strlen(dirp->curr);
768 strcpy(dirp->dirstr.d_name, dirp->curr);
769 dirp->dirstr.d_namlen = len;
772 dirp->dirstr.d_ino = dirp->curr - dirp->start;
774 /* Now set up for the next call to readdir */
775 dirp->curr += len + 1;
776 if (dirp->curr >= dirp->end) {
780 WIN32_FIND_DATAW wFindData;
781 WIN32_FIND_DATAA aFindData;
782 char buffer[MAX_PATH*2];
784 /* finding the next file that matches the wildcard
785 * (which should be all of them in this directory!).
788 res = FindNextFileW(dirp->handle, &wFindData);
790 W2AHELPER(wFindData.cFileName, buffer, sizeof(buffer));
795 res = FindNextFileA(dirp->handle, &aFindData);
797 ptr = aFindData.cFileName;
800 long endpos = dirp->end - dirp->start;
801 long newsize = endpos + strlen(ptr) + 1;
802 /* bump the string table size by enough for the
803 * new name and it's null terminator */
804 while (newsize > dirp->size) {
805 long curpos = dirp->curr - dirp->start;
807 Renew(dirp->start, dirp->size, char);
808 dirp->curr = dirp->start + curpos;
810 strcpy(dirp->start + endpos, ptr);
811 dirp->end = dirp->start + newsize;
817 return &(dirp->dirstr);
823 /* Telldir returns the current string pointer position */
825 win32_telldir(DIR *dirp)
827 return (dirp->curr - dirp->start);
831 /* Seekdir moves the string pointer to a previously saved position
832 * (returned by telldir).
835 win32_seekdir(DIR *dirp, long loc)
837 dirp->curr = dirp->start + loc;
840 /* Rewinddir resets the string pointer to the start */
842 win32_rewinddir(DIR *dirp)
844 dirp->curr = dirp->start;
847 /* free the memory allocated by opendir */
849 win32_closedir(DIR *dirp)
852 if (dirp->handle != INVALID_HANDLE_VALUE)
853 FindClose(dirp->handle);
854 Safefree(dirp->start);
867 * Just pretend that everyone is a superuser. NT will let us know if
868 * we don\'t really have permission to do something.
871 #define ROOT_UID ((uid_t)0)
872 #define ROOT_GID ((gid_t)0)
901 return (auid == ROOT_UID ? 0 : -1);
907 return (agid == ROOT_GID ? 0 : -1);
914 char *buf = w32_getlogin_buffer;
915 DWORD size = sizeof(w32_getlogin_buffer);
916 if (GetUserName(buf,&size))
922 chown(const char *path, uid_t owner, gid_t group)
932 long child = w32_num_children;
933 while (--child >= 0) {
934 if (w32_child_pids[child] == pid)
941 remove_dead_process(long child)
945 CloseHandle(w32_child_handles[child]);
946 Move(&w32_child_handles[child+1], &w32_child_handles[child],
947 (w32_num_children-child-1), HANDLE);
948 Move(&w32_child_pids[child+1], &w32_child_pids[child],
949 (w32_num_children-child-1), DWORD);
956 find_pseudo_pid(int pid)
959 long child = w32_num_pseudo_children;
960 while (--child >= 0) {
961 if (w32_pseudo_child_pids[child] == pid)
968 remove_dead_pseudo_process(long child)
972 CloseHandle(w32_pseudo_child_handles[child]);
973 Move(&w32_pseudo_child_handles[child+1], &w32_pseudo_child_handles[child],
974 (w32_num_pseudo_children-child-1), HANDLE);
975 Move(&w32_pseudo_child_pids[child+1], &w32_pseudo_child_pids[child],
976 (w32_num_pseudo_children-child-1), DWORD);
977 w32_num_pseudo_children--;
983 win32_kill(int pid, int sig)
989 /* it is a pseudo-forked child */
990 long child = find_pseudo_pid(-pid);
994 hProcess = w32_pseudo_child_handles[child];
995 if (TerminateThread(hProcess, sig)) {
996 remove_dead_pseudo_process(child);
1004 long child = find_pid(pid);
1008 hProcess = w32_child_handles[child];
1009 if (TerminateProcess(hProcess, sig)) {
1010 remove_dead_process(child);
1015 hProcess = OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid);
1019 if (TerminateProcess(hProcess, sig)) {
1020 CloseHandle(hProcess);
1034 DllExport unsigned int
1035 win32_sleep(unsigned int t)
1042 win32_stat(const char *path, struct stat *sbuf)
1045 char buffer[MAX_PATH+1];
1046 int l = strlen(path);
1048 WCHAR wbuffer[MAX_PATH+1];
1054 switch(path[l - 1]) {
1055 /* FindFirstFile() and stat() are buggy with a trailing
1056 * backslash, so change it to a forward slash :-( */
1058 strncpy(buffer, path, l-1);
1059 buffer[l - 1] = '/';
1063 /* FindFirstFile() is buggy with "x:", so add a dot :-( */
1065 if (l == 2 && isALPHA(path[0])) {
1066 buffer[0] = path[0];
1077 /* We *must* open & close the file once; otherwise file attribute changes */
1078 /* might not yet have propagated to "other" hard links of the same file. */
1079 /* This also gives us an opportunity to determine the number of links. */
1081 A2WHELPER(path, wbuffer, sizeof(wbuffer));
1082 pwbuffer = PerlDir_mapW(wbuffer);
1083 handle = CreateFileW(pwbuffer, 0, 0, NULL, OPEN_EXISTING, 0, NULL);
1086 path = PerlDir_mapA(path);
1088 handle = CreateFileA(path, 0, 0, NULL, OPEN_EXISTING, 0, NULL);
1090 if (handle != INVALID_HANDLE_VALUE) {
1091 BY_HANDLE_FILE_INFORMATION bhi;
1092 if (GetFileInformationByHandle(handle, &bhi))
1093 nlink = bhi.nNumberOfLinks;
1094 CloseHandle(handle);
1097 /* pwbuffer or path will be mapped correctly above */
1099 res = _wstat(pwbuffer, (struct _stat *)sbuf);
1102 res = stat(path, sbuf);
1104 sbuf->st_nlink = nlink;
1107 /* CRT is buggy on sharenames, so make sure it really isn't.
1108 * XXX using GetFileAttributesEx() will enable us to set
1109 * sbuf->st_*time (but note that's not available on the
1110 * Windows of 1995) */
1113 r = GetFileAttributesW(pwbuffer);
1116 r = GetFileAttributesA(path);
1118 if (r != 0xffffffff && (r & FILE_ATTRIBUTE_DIRECTORY)) {
1119 /* sbuf may still contain old garbage since stat() failed */
1120 Zero(sbuf, 1, struct stat);
1121 sbuf->st_mode = S_IFDIR | S_IREAD;
1123 if (!(r & FILE_ATTRIBUTE_READONLY))
1124 sbuf->st_mode |= S_IWRITE | S_IEXEC;
1129 if (l == 3 && isALPHA(path[0]) && path[1] == ':'
1130 && (path[2] == '\\' || path[2] == '/'))
1132 /* The drive can be inaccessible, some _stat()s are buggy */
1134 ? !GetVolumeInformationW(pwbuffer,NULL,0,NULL,NULL,NULL,NULL,0)
1135 : !GetVolumeInformationA(path,NULL,0,NULL,NULL,NULL,NULL,0)) {
1141 if (S_ISDIR(sbuf->st_mode))
1142 sbuf->st_mode |= S_IWRITE | S_IEXEC;
1143 else if (S_ISREG(sbuf->st_mode)) {
1145 if (l >= 4 && path[l-4] == '.') {
1146 const char *e = path + l - 3;
1147 if (strnicmp(e,"exe",3)
1148 && strnicmp(e,"bat",3)
1149 && strnicmp(e,"com",3)
1150 && (IsWin95() || strnicmp(e,"cmd",3)))
1151 sbuf->st_mode &= ~S_IEXEC;
1153 sbuf->st_mode |= S_IEXEC;
1156 sbuf->st_mode &= ~S_IEXEC;
1157 /* Propagate permissions to _group_ and _others_ */
1158 perms = sbuf->st_mode & (S_IREAD|S_IWRITE|S_IEXEC);
1159 sbuf->st_mode |= (perms>>3) | (perms>>6);
1166 /* Find the longname of a given path. path is destructively modified.
1167 * It should have space for at least MAX_PATH characters. */
1169 win32_longpath(char *path)
1171 WIN32_FIND_DATA fdata;
1173 char tmpbuf[MAX_PATH+1];
1174 char *tmpstart = tmpbuf;
1181 if (isALPHA(path[0]) && path[1] == ':' &&
1182 (path[2] == '/' || path[2] == '\\'))
1185 *tmpstart++ = path[0];
1189 else if ((path[0] == '/' || path[0] == '\\') &&
1190 (path[1] == '/' || path[1] == '\\'))
1193 *tmpstart++ = path[0];
1194 *tmpstart++ = path[1];
1195 /* copy machine name */
1196 while (*start && *start != '/' && *start != '\\')
1197 *tmpstart++ = *start++;
1199 *tmpstart++ = *start;
1201 /* copy share name */
1202 while (*start && *start != '/' && *start != '\\')
1203 *tmpstart++ = *start++;
1207 if (sep == '/' || sep == '\\')
1211 /* walk up to slash */
1212 while (*start && *start != '/' && *start != '\\')
1215 /* discard doubled slashes */
1216 while (*start && (start[1] == '/' || start[1] == '\\'))
1220 /* stop and find full name of component */
1222 fhand = FindFirstFile(path,&fdata);
1223 if (fhand != INVALID_HANDLE_VALUE) {
1224 strcpy(tmpstart, fdata.cFileName);
1225 tmpstart += strlen(fdata.cFileName);
1233 /* failed a step, just return without side effects */
1234 /*PerlIO_printf(Perl_debug_log, "Failed to find %s\n", path);*/
1239 strcpy(path,tmpbuf);
1243 #ifndef USE_WIN32_RTL_ENV
1246 win32_getenv(const char *name)
1249 WCHAR wBuffer[MAX_PATH+1];
1251 SV *curitem = Nullsv;
1254 A2WHELPER(name, wBuffer, sizeof(wBuffer));
1255 needlen = GetEnvironmentVariableW(wBuffer, NULL, 0);
1258 needlen = GetEnvironmentVariableA(name,NULL,0);
1260 curitem = sv_2mortal(newSVpvn("", 0));
1264 SvGROW(curitem, (needlen+1)*sizeof(WCHAR));
1265 needlen = GetEnvironmentVariableW(wBuffer,
1266 (WCHAR*)SvPVX(curitem),
1268 } while (needlen >= SvLEN(curitem)/sizeof(WCHAR));
1269 SvCUR_set(curitem, (needlen*sizeof(WCHAR))+1);
1270 acuritem = sv_2mortal(newSVsv(curitem));
1271 W2AHELPER((WCHAR*)SvPVX(acuritem), SvPVX(curitem), SvCUR(curitem));
1275 SvGROW(curitem, needlen+1);
1276 needlen = GetEnvironmentVariableA(name,SvPVX(curitem),
1278 } while (needlen >= SvLEN(curitem));
1279 SvCUR_set(curitem, needlen);
1283 /* allow any environment variables that begin with 'PERL'
1284 to be stored in the registry */
1285 if (strncmp(name, "PERL", 4) == 0)
1286 (void)get_regstr(name, &curitem);
1288 if (curitem && SvCUR(curitem))
1289 return SvPVX(curitem);
1295 win32_putenv(const char *name)
1302 int length, relval = -1;
1306 length = strlen(name)+1;
1307 New(1309,wCuritem,length,WCHAR);
1308 A2WHELPER(name, wCuritem, length*sizeof(WCHAR));
1309 wVal = wcschr(wCuritem, '=');
1312 if (SetEnvironmentVariableW(wCuritem, *wVal ? wVal : NULL))
1318 New(1309,curitem,strlen(name)+1,char);
1319 strcpy(curitem, name);
1320 val = strchr(curitem, '=');
1322 /* The sane way to deal with the environment.
1323 * Has these advantages over putenv() & co.:
1324 * * enables us to store a truly empty value in the
1325 * environment (like in UNIX).
1326 * * we don't have to deal with RTL globals, bugs and leaks.
1328 * Why you may want to enable USE_WIN32_RTL_ENV:
1329 * * environ[] and RTL functions will not reflect changes,
1330 * which might be an issue if extensions want to access
1331 * the env. via RTL. This cuts both ways, since RTL will
1332 * not see changes made by extensions that call the Win32
1333 * functions directly, either.
1337 if (SetEnvironmentVariableA(curitem, *val ? val : NULL))
1349 filetime_to_clock(PFILETIME ft)
1351 __int64 qw = ft->dwHighDateTime;
1353 qw |= ft->dwLowDateTime;
1354 qw /= 10000; /* File time ticks at 0.1uS, clock at 1mS */
1359 win32_times(struct tms *timebuf)
1364 if (GetProcessTimes(GetCurrentProcess(), &dummy, &dummy,
1366 timebuf->tms_utime = filetime_to_clock(&user);
1367 timebuf->tms_stime = filetime_to_clock(&kernel);
1368 timebuf->tms_cutime = 0;
1369 timebuf->tms_cstime = 0;
1372 /* That failed - e.g. Win95 fallback to clock() */
1373 clock_t t = clock();
1374 timebuf->tms_utime = t;
1375 timebuf->tms_stime = 0;
1376 timebuf->tms_cutime = 0;
1377 timebuf->tms_cstime = 0;
1382 /* fix utime() so it works on directories in NT */
1384 filetime_from_time(PFILETIME pFileTime, time_t Time)
1386 struct tm *pTM = localtime(&Time);
1387 SYSTEMTIME SystemTime;
1393 SystemTime.wYear = pTM->tm_year + 1900;
1394 SystemTime.wMonth = pTM->tm_mon + 1;
1395 SystemTime.wDay = pTM->tm_mday;
1396 SystemTime.wHour = pTM->tm_hour;
1397 SystemTime.wMinute = pTM->tm_min;
1398 SystemTime.wSecond = pTM->tm_sec;
1399 SystemTime.wMilliseconds = 0;
1401 return SystemTimeToFileTime(&SystemTime, &LocalTime) &&
1402 LocalFileTimeToFileTime(&LocalTime, pFileTime);
1406 win32_unlink(const char *filename)
1413 WCHAR wBuffer[MAX_PATH+1];
1416 A2WHELPER(filename, wBuffer, sizeof(wBuffer));
1417 pwBuffer = PerlDir_mapW(wBuffer);
1418 attrs = GetFileAttributesW(pwBuffer);
1419 if (attrs == 0xFFFFFFFF)
1421 if (attrs & FILE_ATTRIBUTE_READONLY) {
1422 (void)SetFileAttributesW(pwBuffer, attrs & ~FILE_ATTRIBUTE_READONLY);
1423 ret = _wunlink(pwBuffer);
1425 (void)SetFileAttributesW(pwBuffer, attrs);
1428 ret = _wunlink(pwBuffer);
1431 filename = PerlDir_mapA(filename);
1432 attrs = GetFileAttributesA(filename);
1433 if (attrs == 0xFFFFFFFF)
1435 if (attrs & FILE_ATTRIBUTE_READONLY) {
1436 (void)SetFileAttributesA(filename, attrs & ~FILE_ATTRIBUTE_READONLY);
1437 ret = unlink(filename);
1439 (void)SetFileAttributesA(filename, attrs);
1442 ret = unlink(filename);
1451 win32_utime(const char *filename, struct utimbuf *times)
1458 struct utimbuf TimeBuffer;
1459 WCHAR wbuffer[MAX_PATH+1];
1464 A2WHELPER(filename, wbuffer, sizeof(wbuffer));
1465 pwbuffer = PerlDir_mapW(wbuffer);
1466 rc = _wutime(pwbuffer, (struct _utimbuf*)times);
1469 filename = PerlDir_mapA(filename);
1470 rc = utime(filename, times);
1472 /* EACCES: path specifies directory or readonly file */
1473 if (rc == 0 || errno != EACCES /* || !IsWinNT() */)
1476 if (times == NULL) {
1477 times = &TimeBuffer;
1478 time(×->actime);
1479 times->modtime = times->actime;
1482 /* This will (and should) still fail on readonly files */
1484 handle = CreateFileW(pwbuffer, GENERIC_READ | GENERIC_WRITE,
1485 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1486 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1489 handle = CreateFileA(filename, GENERIC_READ | GENERIC_WRITE,
1490 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1491 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1493 if (handle == INVALID_HANDLE_VALUE)
1496 if (GetFileTime(handle, &ftCreate, &ftAccess, &ftWrite) &&
1497 filetime_from_time(&ftAccess, times->actime) &&
1498 filetime_from_time(&ftWrite, times->modtime) &&
1499 SetFileTime(handle, &ftCreate, &ftAccess, &ftWrite))
1504 CloseHandle(handle);
1509 win32_uname(struct utsname *name)
1511 struct hostent *hep;
1512 STRLEN nodemax = sizeof(name->nodename)-1;
1513 OSVERSIONINFO osver;
1515 memset(&osver, 0, sizeof(OSVERSIONINFO));
1516 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1517 if (GetVersionEx(&osver)) {
1519 switch (osver.dwPlatformId) {
1520 case VER_PLATFORM_WIN32_WINDOWS:
1521 strcpy(name->sysname, "Windows");
1523 case VER_PLATFORM_WIN32_NT:
1524 strcpy(name->sysname, "Windows NT");
1526 case VER_PLATFORM_WIN32s:
1527 strcpy(name->sysname, "Win32s");
1530 strcpy(name->sysname, "Win32 Unknown");
1535 sprintf(name->release, "%d.%d",
1536 osver.dwMajorVersion, osver.dwMinorVersion);
1539 sprintf(name->version, "Build %d",
1540 osver.dwPlatformId == VER_PLATFORM_WIN32_NT
1541 ? osver.dwBuildNumber : (osver.dwBuildNumber & 0xffff));
1542 if (osver.szCSDVersion[0]) {
1543 char *buf = name->version + strlen(name->version);
1544 sprintf(buf, " (%s)", osver.szCSDVersion);
1548 *name->sysname = '\0';
1549 *name->version = '\0';
1550 *name->release = '\0';
1554 hep = win32_gethostbyname("localhost");
1556 STRLEN len = strlen(hep->h_name);
1557 if (len <= nodemax) {
1558 strcpy(name->nodename, hep->h_name);
1561 strncpy(name->nodename, hep->h_name, nodemax);
1562 name->nodename[nodemax] = '\0';
1567 if (!GetComputerName(name->nodename, &sz))
1568 *name->nodename = '\0';
1571 /* machine (architecture) */
1575 GetSystemInfo(&info);
1577 #if defined(__BORLANDC__) || defined(__MINGW32__)
1578 switch (info.u.s.wProcessorArchitecture) {
1580 switch (info.wProcessorArchitecture) {
1582 case PROCESSOR_ARCHITECTURE_INTEL:
1583 arch = "x86"; break;
1584 case PROCESSOR_ARCHITECTURE_MIPS:
1585 arch = "mips"; break;
1586 case PROCESSOR_ARCHITECTURE_ALPHA:
1587 arch = "alpha"; break;
1588 case PROCESSOR_ARCHITECTURE_PPC:
1589 arch = "ppc"; break;
1591 arch = "unknown"; break;
1593 strcpy(name->machine, arch);
1599 win32_waitpid(int pid, int *status, int flags)
1603 if (pid == -1) /* XXX threadid == 1 ? */
1604 return win32_wait(status);
1607 long child = find_pseudo_pid(-pid);
1609 HANDLE hThread = w32_pseudo_child_handles[child];
1610 DWORD waitcode = WaitForSingleObject(hThread, INFINITE);
1611 if (waitcode != WAIT_FAILED) {
1612 if (GetExitCodeThread(hThread, &waitcode)) {
1613 *status = (int)((waitcode & 0xff) << 8);
1614 retval = (int)w32_pseudo_child_pids[child];
1615 remove_dead_pseudo_process(child);
1625 long child = find_pid(pid);
1627 HANDLE hProcess = w32_child_handles[child];
1628 DWORD waitcode = WaitForSingleObject(hProcess, INFINITE);
1629 if (waitcode != WAIT_FAILED) {
1630 if (GetExitCodeProcess(hProcess, &waitcode)) {
1631 *status = (int)((waitcode & 0xff) << 8);
1632 retval = (int)w32_child_pids[child];
1633 remove_dead_process(child);
1641 retval = cwait(status, pid, WAIT_CHILD);
1642 /* cwait() returns "correctly" on Borland */
1643 #ifndef __BORLANDC__
1649 return retval >= 0 ? pid : retval;
1653 win32_wait(int *status)
1655 /* XXX this wait emulation only knows about processes
1656 * spawned via win32_spawnvp(P_NOWAIT, ...).
1660 DWORD exitcode, waitcode;
1663 if (w32_num_pseudo_children) {
1664 waitcode = WaitForMultipleObjects(w32_num_pseudo_children,
1665 w32_pseudo_child_handles,
1668 if (waitcode != WAIT_FAILED) {
1669 if (waitcode >= WAIT_ABANDONED_0
1670 && waitcode < WAIT_ABANDONED_0 + w32_num_pseudo_children)
1671 i = waitcode - WAIT_ABANDONED_0;
1673 i = waitcode - WAIT_OBJECT_0;
1674 if (GetExitCodeThread(w32_pseudo_child_handles[i], &exitcode)) {
1675 *status = (int)((exitcode & 0xff) << 8);
1676 retval = (int)w32_pseudo_child_pids[i];
1677 remove_dead_pseudo_process(i);
1684 if (!w32_num_children) {
1689 /* if a child exists, wait for it to die */
1690 waitcode = WaitForMultipleObjects(w32_num_children,
1694 if (waitcode != WAIT_FAILED) {
1695 if (waitcode >= WAIT_ABANDONED_0
1696 && waitcode < WAIT_ABANDONED_0 + w32_num_children)
1697 i = waitcode - WAIT_ABANDONED_0;
1699 i = waitcode - WAIT_OBJECT_0;
1700 if (GetExitCodeProcess(w32_child_handles[i], &exitcode) ) {
1701 *status = (int)((exitcode & 0xff) << 8);
1702 retval = (int)w32_child_pids[i];
1703 remove_dead_process(i);
1709 errno = GetLastError();
1715 static UINT timerid = 0;
1717 static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
1720 KillTimer(NULL,timerid);
1724 #endif /* !PERL_OBJECT */
1726 DllExport unsigned int
1727 win32_alarm(unsigned int sec)
1731 * the 'obvious' implentation is SetTimer() with a callback
1732 * which does whatever receiving SIGALRM would do
1733 * we cannot use SIGALRM even via raise() as it is not
1734 * one of the supported codes in <signal.h>
1736 * Snag is unless something is looking at the message queue
1737 * nothing happens :-(
1742 timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
1744 Perl_croak_nocontext("Cannot set timer");
1750 KillTimer(NULL,timerid);
1754 #endif /* !PERL_OBJECT */
1758 #ifdef HAVE_DES_FCRYPT
1759 extern char * des_fcrypt(const char *txt, const char *salt, char *cbuf);
1763 win32_crypt(const char *txt, const char *salt)
1766 #ifdef HAVE_DES_FCRYPT
1768 return des_fcrypt(txt, salt, w32_crypt_buffer);
1770 Perl_croak(aTHX_ "The crypt() function is unimplemented due to excessive paranoia.");
1775 /* C doesn't like repeat struct definitions */
1777 #if defined(USE_FIXED_OSFHANDLE) || defined(PERL_MSVCRT_READFIX)
1780 #define _CRTIMP __declspec(dllimport)
1784 * Control structure for lowio file handles
1787 long osfhnd; /* underlying OS file HANDLE */
1788 char osfile; /* attributes of file (e.g., open in text mode?) */
1789 char pipech; /* one char buffer for handles opened on pipes */
1791 CRITICAL_SECTION lock;
1796 * Array of arrays of control structures for lowio files.
1798 EXTERN_C _CRTIMP ioinfo* __pioinfo[];
1801 * Definition of IOINFO_L2E, the log base 2 of the number of elements in each
1802 * array of ioinfo structs.
1804 #define IOINFO_L2E 5
1807 * Definition of IOINFO_ARRAY_ELTS, the number of elements in ioinfo array
1809 #define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
1812 * Access macros for getting at an ioinfo struct and its fields from a
1815 #define _pioinfo(i) (__pioinfo[(i) >> IOINFO_L2E] + ((i) & (IOINFO_ARRAY_ELTS - 1)))
1816 #define _osfhnd(i) (_pioinfo(i)->osfhnd)
1817 #define _osfile(i) (_pioinfo(i)->osfile)
1818 #define _pipech(i) (_pioinfo(i)->pipech)
1822 #ifdef USE_FIXED_OSFHANDLE
1824 #define FOPEN 0x01 /* file handle open */
1825 #define FNOINHERIT 0x10 /* file handle opened O_NOINHERIT */
1826 #define FAPPEND 0x20 /* file handle opened O_APPEND */
1827 #define FDEV 0x40 /* file handle refers to device */
1828 #define FTEXT 0x80 /* file handle is in text mode */
1831 *int my_open_osfhandle(long osfhandle, int flags) - open C Runtime file handle
1834 * This function allocates a free C Runtime file handle and associates
1835 * it with the Win32 HANDLE specified by the first parameter. This is a
1836 * temperary fix for WIN95's brain damage GetFileType() error on socket
1837 * we just bypass that call for socket
1839 * This works with MSVC++ 4.0+ or GCC/Mingw32
1842 * long osfhandle - Win32 HANDLE to associate with C Runtime file handle.
1843 * int flags - flags to associate with C Runtime file handle.
1846 * returns index of entry in fh, if successful
1847 * return -1, if no free entry is found
1851 *******************************************************************************/
1854 * we fake up some parts of the CRT that aren't exported by MSVCRT.dll
1855 * this lets sockets work on Win9X with GCC and should fix the problems
1860 /* since we are not doing a dup2(), this works fine */
1862 #define _set_osfhnd(fh, osfh) (void)(_osfhnd(fh) = osfh)
1864 /* create an ioinfo entry, kill its handle, and steal the entry */
1869 HANDLE hF = CreateFile("NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
1870 int fh = _open_osfhandle((long)hF, 0);
1874 EnterCriticalSection(&(_pioinfo(fh)->lock));
1879 my_open_osfhandle(long osfhandle, int flags)
1882 char fileflags; /* _osfile flags */
1884 /* copy relevant flags from second parameter */
1887 if (flags & O_APPEND)
1888 fileflags |= FAPPEND;
1893 if (flags & O_NOINHERIT)
1894 fileflags |= FNOINHERIT;
1896 /* attempt to allocate a C Runtime file handle */
1897 if ((fh = _alloc_osfhnd()) == -1) {
1898 errno = EMFILE; /* too many open files */
1899 _doserrno = 0L; /* not an OS error */
1900 return -1; /* return error to caller */
1903 /* the file is open. now, set the info in _osfhnd array */
1904 _set_osfhnd(fh, osfhandle);
1906 fileflags |= FOPEN; /* mark as open */
1908 _osfile(fh) = fileflags; /* set osfile entry */
1909 LeaveCriticalSection(&_pioinfo(fh)->lock);
1911 return fh; /* return handle */
1914 #endif /* USE_FIXED_OSFHANDLE */
1916 /* simulate flock by locking a range on the file */
1918 #define LK_ERR(f,i) ((f) ? (i = 0) : (errno = GetLastError()))
1919 #define LK_LEN 0xffff0000
1922 win32_flock(int fd, int oper)
1930 Perl_croak_nocontext("flock() unimplemented on this platform");
1933 fh = (HANDLE)_get_osfhandle(fd);
1934 memset(&o, 0, sizeof(o));
1937 case LOCK_SH: /* shared lock */
1938 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
1940 case LOCK_EX: /* exclusive lock */
1941 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
1943 case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
1944 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
1946 case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
1947 LK_ERR(LockFileEx(fh,
1948 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
1949 0, LK_LEN, 0, &o),i);
1951 case LOCK_UN: /* unlock lock */
1952 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, 0, &o),i);
1954 default: /* unknown */
1965 * redirected io subsystem for all XS modules
1978 return (&(_environ));
1981 /* the rest are the remapped stdio routines */
2001 win32_ferror(FILE *fp)
2003 return (ferror(fp));
2008 win32_feof(FILE *fp)
2014 * Since the errors returned by the socket error function
2015 * WSAGetLastError() are not known by the library routine strerror
2016 * we have to roll our own.
2020 win32_strerror(int e)
2022 #ifndef __BORLANDC__ /* Borland intolerance */
2023 extern int sys_nerr;
2027 if (e < 0 || e > sys_nerr) {
2032 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
2033 w32_strerror_buffer,
2034 sizeof(w32_strerror_buffer), NULL) == 0)
2035 strcpy(w32_strerror_buffer, "Unknown Error");
2037 return w32_strerror_buffer;
2043 win32_str_os_error(void *sv, DWORD dwErr)
2047 dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
2048 |FORMAT_MESSAGE_IGNORE_INSERTS
2049 |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
2050 dwErr, 0, (char *)&sMsg, 1, NULL);
2051 /* strip trailing whitespace and period */
2054 --dwLen; /* dwLen doesn't include trailing null */
2055 } while (0 < dwLen && isSPACE(sMsg[dwLen]));
2056 if ('.' != sMsg[dwLen])
2061 sMsg = (char*)LocalAlloc(0, 64/**sizeof(TCHAR)*/);
2063 dwLen = sprintf(sMsg,
2064 "Unknown error #0x%lX (lookup 0x%lX)",
2065 dwErr, GetLastError());
2069 sv_setpvn((SV*)sv, sMsg, dwLen);
2076 win32_fprintf(FILE *fp, const char *format, ...)
2079 va_start(marker, format); /* Initialize variable arguments. */
2081 return (vfprintf(fp, format, marker));
2085 win32_printf(const char *format, ...)
2088 va_start(marker, format); /* Initialize variable arguments. */
2090 return (vprintf(format, marker));
2094 win32_vfprintf(FILE *fp, const char *format, va_list args)
2096 return (vfprintf(fp, format, args));
2100 win32_vprintf(const char *format, va_list args)
2102 return (vprintf(format, args));
2106 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
2108 return fread(buf, size, count, fp);
2112 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
2114 return fwrite(buf, size, count, fp);
2117 #define MODE_SIZE 10
2120 win32_fopen(const char *filename, const char *mode)
2123 WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH+1];
2129 if (stricmp(filename, "/dev/null")==0)
2133 A2WHELPER(mode, wMode, sizeof(wMode));
2134 A2WHELPER(filename, wBuffer, sizeof(wBuffer));
2135 f = _wfopen(PerlDir_mapW(wBuffer), wMode);
2138 f = fopen(PerlDir_mapA(filename), mode);
2139 /* avoid buffering headaches for child processes */
2140 if (f && *mode == 'a')
2141 win32_fseek(f, 0, SEEK_END);
2145 #ifndef USE_SOCKETS_AS_HANDLES
2147 #define fdopen my_fdopen
2151 win32_fdopen(int handle, const char *mode)
2154 WCHAR wMode[MODE_SIZE];
2157 A2WHELPER(mode, wMode, sizeof(wMode));
2158 f = _wfdopen(handle, wMode);
2161 f = fdopen(handle, (char *) mode);
2162 /* avoid buffering headaches for child processes */
2163 if (f && *mode == 'a')
2164 win32_fseek(f, 0, SEEK_END);
2169 win32_freopen(const char *path, const char *mode, FILE *stream)
2172 WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH+1];
2173 if (stricmp(path, "/dev/null")==0)
2177 A2WHELPER(mode, wMode, sizeof(wMode));
2178 A2WHELPER(path, wBuffer, sizeof(wBuffer));
2179 return _wfreopen(PerlDir_mapW(wBuffer), wMode, stream);
2181 return freopen(PerlDir_mapA(path), mode, stream);
2185 win32_fclose(FILE *pf)
2187 return my_fclose(pf); /* defined in win32sck.c */
2191 win32_fputs(const char *s,FILE *pf)
2193 return fputs(s, pf);
2197 win32_fputc(int c,FILE *pf)
2203 win32_ungetc(int c,FILE *pf)
2205 return ungetc(c,pf);
2209 win32_getc(FILE *pf)
2215 win32_fileno(FILE *pf)
2221 win32_clearerr(FILE *pf)
2228 win32_fflush(FILE *pf)
2234 win32_ftell(FILE *pf)
2240 win32_fseek(FILE *pf,long offset,int origin)
2242 return fseek(pf, offset, origin);
2246 win32_fgetpos(FILE *pf,fpos_t *p)
2248 return fgetpos(pf, p);
2252 win32_fsetpos(FILE *pf,const fpos_t *p)
2254 return fsetpos(pf, p);
2258 win32_rewind(FILE *pf)
2278 win32_fstat(int fd,struct stat *sbufptr)
2280 return fstat(fd,sbufptr);
2284 win32_pipe(int *pfd, unsigned int size, int mode)
2286 return _pipe(pfd, size, mode);
2290 * a popen() clone that respects PERL5SHELL
2294 win32_popen(const char *command, const char *mode)
2296 #ifdef USE_RTL_POPEN
2297 return _popen(command, mode);
2305 /* establish which ends read and write */
2306 if (strchr(mode,'w')) {
2307 stdfd = 0; /* stdin */
2311 else if (strchr(mode,'r')) {
2312 stdfd = 1; /* stdout */
2319 /* set the correct mode */
2320 if (strchr(mode,'b'))
2322 else if (strchr(mode,'t'))
2325 ourmode = _fmode & (O_TEXT | O_BINARY);
2327 /* the child doesn't inherit handles */
2328 ourmode |= O_NOINHERIT;
2330 if (win32_pipe( p, 512, ourmode) == -1)
2333 /* save current stdfd */
2334 if ((oldfd = win32_dup(stdfd)) == -1)
2337 /* make stdfd go to child end of pipe (implicitly closes stdfd) */
2338 /* stdfd will be inherited by the child */
2339 if (win32_dup2(p[child], stdfd) == -1)
2342 /* close the child end in parent */
2343 win32_close(p[child]);
2345 /* start the child */
2348 if ((childpid = do_spawn_nowait((char*)command)) == -1)
2351 /* revert stdfd to whatever it was before */
2352 if (win32_dup2(oldfd, stdfd) == -1)
2355 /* close saved handle */
2358 sv_setiv(*av_fetch(w32_fdpid, p[parent], TRUE), childpid);
2360 /* set process id so that it can be returned by perl's open() */
2361 PL_forkprocess = childpid;
2364 /* we have an fd, return a file stream */
2365 return (win32_fdopen(p[parent], (char *)mode));
2368 /* we don't need to check for errors here */
2372 win32_dup2(oldfd, stdfd);
2377 #endif /* USE_RTL_POPEN */
2385 win32_pclose(FILE *pf)
2387 #ifdef USE_RTL_POPEN
2391 int childpid, status;
2394 sv = *av_fetch(w32_fdpid, win32_fileno(pf), TRUE);
2396 childpid = SvIVX(sv);
2408 if (win32_waitpid(childpid, &status, 0) == -1)
2413 #endif /* USE_RTL_POPEN */
2419 LPCWSTR lpExistingFileName,
2420 LPSECURITY_ATTRIBUTES lpSecurityAttributes)
2423 WCHAR wFullName[MAX_PATH+1];
2424 LPVOID lpContext = NULL;
2425 WIN32_STREAM_ID StreamId;
2426 DWORD dwSize = (char*)&StreamId.cStreamName - (char*)&StreamId;
2431 BOOL (__stdcall *pfnBackupWrite)(HANDLE, LPBYTE, DWORD, LPDWORD,
2432 BOOL, BOOL, LPVOID*) =
2433 (BOOL (__stdcall *)(HANDLE, LPBYTE, DWORD, LPDWORD,
2434 BOOL, BOOL, LPVOID*))
2435 GetProcAddress(GetModuleHandle("kernel32.dll"), "BackupWrite");
2436 if (pfnBackupWrite == NULL)
2439 dwLen = GetFullPathNameW(lpFileName, MAX_PATH, wFullName, NULL);
2442 dwLen = (dwLen+1)*sizeof(WCHAR);
2444 handle = CreateFileW(lpExistingFileName, FILE_WRITE_ATTRIBUTES,
2445 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
2446 NULL, OPEN_EXISTING, 0, NULL);
2447 if (handle == INVALID_HANDLE_VALUE)
2450 StreamId.dwStreamId = BACKUP_LINK;
2451 StreamId.dwStreamAttributes = 0;
2452 StreamId.dwStreamNameSize = 0;
2453 #if defined(__BORLANDC__) || defined(__MINGW32__)
2454 StreamId.Size.u.HighPart = 0;
2455 StreamId.Size.u.LowPart = dwLen;
2457 StreamId.Size.HighPart = 0;
2458 StreamId.Size.LowPart = dwLen;
2461 bSuccess = pfnBackupWrite(handle, (LPBYTE)&StreamId, dwSize, &dwWritten,
2462 FALSE, FALSE, &lpContext);
2464 bSuccess = pfnBackupWrite(handle, (LPBYTE)wFullName, dwLen, &dwWritten,
2465 FALSE, FALSE, &lpContext);
2466 pfnBackupWrite(handle, NULL, 0, &dwWritten, TRUE, FALSE, &lpContext);
2469 CloseHandle(handle);
2474 win32_link(const char *oldname, const char *newname)
2477 BOOL (__stdcall *pfnCreateHardLinkW)(LPCWSTR,LPCWSTR,LPSECURITY_ATTRIBUTES);
2478 WCHAR wOldName[MAX_PATH+1];
2479 WCHAR wNewName[MAX_PATH+1];
2482 Perl_croak(aTHX_ PL_no_func, "link");
2484 pfnCreateHardLinkW =
2485 (BOOL (__stdcall *)(LPCWSTR, LPCWSTR, LPSECURITY_ATTRIBUTES))
2486 GetProcAddress(GetModuleHandle("kernel32.dll"), "CreateHardLinkW");
2487 if (pfnCreateHardLinkW == NULL)
2488 pfnCreateHardLinkW = Nt4CreateHardLinkW;
2490 if ((A2WHELPER(oldname, wOldName, sizeof(wOldName))) &&
2491 (A2WHELPER(newname, wNewName, sizeof(wNewName))) &&
2492 (wcscpy(wOldName, PerlDir_mapW(wOldName)),
2493 pfnCreateHardLinkW(PerlDir_mapW(wNewName), wOldName, NULL)))
2497 errno = (GetLastError() == ERROR_FILE_NOT_FOUND) ? ENOENT : EINVAL;
2502 win32_rename(const char *oname, const char *newname)
2504 WCHAR wOldName[MAX_PATH+1];
2505 WCHAR wNewName[MAX_PATH+1];
2506 char szOldName[MAX_PATH+1];
2507 char szNewName[MAX_PATH+1];
2511 /* XXX despite what the documentation says about MoveFileEx(),
2512 * it doesn't work under Windows95!
2515 DWORD dwFlags = MOVEFILE_COPY_ALLOWED;
2517 A2WHELPER(oname, wOldName, sizeof(wOldName));
2518 A2WHELPER(newname, wNewName, sizeof(wNewName));
2519 if (wcsicmp(wNewName, wOldName))
2520 dwFlags |= MOVEFILE_REPLACE_EXISTING;
2521 wcscpy(wOldName, PerlDir_mapW(wOldName));
2522 bResult = MoveFileExW(wOldName,PerlDir_mapW(wNewName), dwFlags);
2525 if (stricmp(newname, oname))
2526 dwFlags |= MOVEFILE_REPLACE_EXISTING;
2527 strcpy(szOldName, PerlDir_mapA(oname));
2528 bResult = MoveFileExA(szOldName,PerlDir_mapA(newname), dwFlags);
2531 DWORD err = GetLastError();
2533 case ERROR_BAD_NET_NAME:
2534 case ERROR_BAD_NETPATH:
2535 case ERROR_BAD_PATHNAME:
2536 case ERROR_FILE_NOT_FOUND:
2537 case ERROR_FILENAME_EXCED_RANGE:
2538 case ERROR_INVALID_DRIVE:
2539 case ERROR_NO_MORE_FILES:
2540 case ERROR_PATH_NOT_FOUND:
2553 char szTmpName[MAX_PATH+1];
2554 char dname[MAX_PATH+1];
2555 char *endname = Nullch;
2557 DWORD from_attr, to_attr;
2559 strcpy(szOldName, PerlDir_mapA(oname));
2560 strcpy(szNewName, PerlDir_mapA(newname));
2562 /* if oname doesn't exist, do nothing */
2563 from_attr = GetFileAttributes(szOldName);
2564 if (from_attr == 0xFFFFFFFF) {
2569 /* if newname exists, rename it to a temporary name so that we
2570 * don't delete it in case oname happens to be the same file
2571 * (but perhaps accessed via a different path)
2573 to_attr = GetFileAttributes(szNewName);
2574 if (to_attr != 0xFFFFFFFF) {
2575 /* if newname is a directory, we fail
2576 * XXX could overcome this with yet more convoluted logic */
2577 if (to_attr & FILE_ATTRIBUTE_DIRECTORY) {
2581 tmplen = strlen(szNewName);
2582 strcpy(szTmpName,szNewName);
2583 endname = szTmpName+tmplen;
2584 for (; endname > szTmpName ; --endname) {
2585 if (*endname == '/' || *endname == '\\') {
2590 if (endname > szTmpName)
2591 endname = strcpy(dname,szTmpName);
2595 /* get a temporary filename in same directory
2596 * XXX is this really the best we can do? */
2597 if (!GetTempFileName((LPCTSTR)endname, "plr", 0, szTmpName)) {
2601 DeleteFile(szTmpName);
2603 retval = rename(szNewName, szTmpName);
2610 /* rename oname to newname */
2611 retval = rename(szOldName, szNewName);
2613 /* if we created a temporary file before ... */
2614 if (endname != Nullch) {
2615 /* ...and rename succeeded, delete temporary file/directory */
2617 DeleteFile(szTmpName);
2618 /* else restore it to what it was */
2620 (void)rename(szTmpName, szNewName);
2627 win32_setmode(int fd, int mode)
2629 return setmode(fd, mode);
2633 win32_lseek(int fd, long offset, int origin)
2635 return lseek(fd, offset, origin);
2645 win32_open(const char *path, int flag, ...)
2650 WCHAR wBuffer[MAX_PATH+1];
2653 pmode = va_arg(ap, int);
2656 if (stricmp(path, "/dev/null")==0)
2660 A2WHELPER(path, wBuffer, sizeof(wBuffer));
2661 return _wopen(PerlDir_mapW(wBuffer), flag, pmode);
2663 return open(PerlDir_mapA(path), flag, pmode);
2685 win32_dup2(int fd1,int fd2)
2687 return dup2(fd1,fd2);
2690 #ifdef PERL_MSVCRT_READFIX
2692 #define LF 10 /* line feed */
2693 #define CR 13 /* carriage return */
2694 #define CTRLZ 26 /* ctrl-z means eof for text */
2695 #define FOPEN 0x01 /* file handle open */
2696 #define FEOFLAG 0x02 /* end of file has been encountered */
2697 #define FCRLF 0x04 /* CR-LF across read buffer (in text mode) */
2698 #define FPIPE 0x08 /* file handle refers to a pipe */
2699 #define FAPPEND 0x20 /* file handle opened O_APPEND */
2700 #define FDEV 0x40 /* file handle refers to device */
2701 #define FTEXT 0x80 /* file handle is in text mode */
2702 #define MAX_DESCRIPTOR_COUNT (64*32) /* this is the maximun that MSVCRT can handle */
2705 _fixed_read(int fh, void *buf, unsigned cnt)
2707 int bytes_read; /* number of bytes read */
2708 char *buffer; /* buffer to read to */
2709 int os_read; /* bytes read on OS call */
2710 char *p, *q; /* pointers into buffer */
2711 char peekchr; /* peek-ahead character */
2712 ULONG filepos; /* file position after seek */
2713 ULONG dosretval; /* o.s. return value */
2715 /* validate handle */
2716 if (((unsigned)fh >= (unsigned)MAX_DESCRIPTOR_COUNT) ||
2717 !(_osfile(fh) & FOPEN))
2719 /* out of range -- return error */
2721 _doserrno = 0; /* not o.s. error */
2726 * If lockinitflag is FALSE, assume fd is device
2727 * lockinitflag is set to TRUE by open.
2729 if (_pioinfo(fh)->lockinitflag)
2730 EnterCriticalSection(&(_pioinfo(fh)->lock)); /* lock file */
2732 bytes_read = 0; /* nothing read yet */
2733 buffer = (char*)buf;
2735 if (cnt == 0 || (_osfile(fh) & FEOFLAG)) {
2736 /* nothing to read or at EOF, so return 0 read */
2740 if ((_osfile(fh) & (FPIPE|FDEV)) && _pipech(fh) != LF) {
2741 /* a pipe/device and pipe lookahead non-empty: read the lookahead
2743 *buffer++ = _pipech(fh);
2746 _pipech(fh) = LF; /* mark as empty */
2751 if (!ReadFile((HANDLE)_osfhnd(fh), buffer, cnt, (LPDWORD)&os_read, NULL))
2753 /* ReadFile has reported an error. recognize two special cases.
2755 * 1. map ERROR_ACCESS_DENIED to EBADF
2757 * 2. just return 0 if ERROR_BROKEN_PIPE has occurred. it
2758 * means the handle is a read-handle on a pipe for which
2759 * all write-handles have been closed and all data has been
2762 if ((dosretval = GetLastError()) == ERROR_ACCESS_DENIED) {
2763 /* wrong read/write mode should return EBADF, not EACCES */
2765 _doserrno = dosretval;
2769 else if (dosretval == ERROR_BROKEN_PIPE) {
2779 bytes_read += os_read; /* update bytes read */
2781 if (_osfile(fh) & FTEXT) {
2782 /* now must translate CR-LFs to LFs in the buffer */
2784 /* set CRLF flag to indicate LF at beginning of buffer */
2785 /* if ((os_read != 0) && (*(char *)buf == LF)) */
2786 /* _osfile(fh) |= FCRLF; */
2788 /* _osfile(fh) &= ~FCRLF; */
2790 _osfile(fh) &= ~FCRLF;
2792 /* convert chars in the buffer: p is src, q is dest */
2794 while (p < (char *)buf + bytes_read) {
2796 /* if fh is not a device, set ctrl-z flag */
2797 if (!(_osfile(fh) & FDEV))
2798 _osfile(fh) |= FEOFLAG;
2799 break; /* stop translating */
2804 /* *p is CR, so must check next char for LF */
2805 if (p < (char *)buf + bytes_read - 1) {
2808 *q++ = LF; /* convert CR-LF to LF */
2811 *q++ = *p++; /* store char normally */
2814 /* This is the hard part. We found a CR at end of
2815 buffer. We must peek ahead to see if next char
2820 if (!ReadFile((HANDLE)_osfhnd(fh), &peekchr, 1,
2821 (LPDWORD)&os_read, NULL))
2822 dosretval = GetLastError();
2824 if (dosretval != 0 || os_read == 0) {
2825 /* couldn't read ahead, store CR */
2829 /* peekchr now has the extra character -- we now
2830 have several possibilities:
2831 1. disk file and char is not LF; just seek back
2833 2. disk file and char is LF; store LF, don't seek back
2834 3. pipe/device and char is LF; store LF.
2835 4. pipe/device and char isn't LF, store CR and
2836 put char in pipe lookahead buffer. */
2837 if (_osfile(fh) & (FDEV|FPIPE)) {
2838 /* non-seekable device */
2843 _pipech(fh) = peekchr;
2848 if (peekchr == LF) {
2849 /* nothing read yet; must make some
2852 /* turn on this flag for tell routine */
2853 _osfile(fh) |= FCRLF;
2856 HANDLE osHandle; /* o.s. handle value */
2858 if ((osHandle = (HANDLE)_get_osfhandle(fh)) != (HANDLE)-1)
2860 if ((filepos = SetFilePointer(osHandle, -1, NULL, FILE_CURRENT)) == -1)
2861 dosretval = GetLastError();
2872 /* we now change bytes_read to reflect the true number of chars
2874 bytes_read = q - (char *)buf;
2878 if (_pioinfo(fh)->lockinitflag)
2879 LeaveCriticalSection(&(_pioinfo(fh)->lock)); /* unlock file */
2884 #endif /* PERL_MSVCRT_READFIX */
2887 win32_read(int fd, void *buf, unsigned int cnt)
2889 #ifdef PERL_MSVCRT_READFIX
2890 return _fixed_read(fd, buf, cnt);
2892 return read(fd, buf, cnt);
2897 win32_write(int fd, const void *buf, unsigned int cnt)
2899 return write(fd, buf, cnt);
2903 win32_mkdir(const char *dir, int mode)
2907 WCHAR wBuffer[MAX_PATH+1];
2908 A2WHELPER(dir, wBuffer, sizeof(wBuffer));
2909 return _wmkdir(PerlDir_mapW(wBuffer));
2911 return mkdir(PerlDir_mapA(dir)); /* just ignore mode */
2915 win32_rmdir(const char *dir)
2919 WCHAR wBuffer[MAX_PATH+1];
2920 A2WHELPER(dir, wBuffer, sizeof(wBuffer));
2921 return _wrmdir(PerlDir_mapW(wBuffer));
2923 return rmdir(PerlDir_mapA(dir));
2927 win32_chdir(const char *dir)
2931 WCHAR wBuffer[MAX_PATH+1];
2932 A2WHELPER(dir, wBuffer, sizeof(wBuffer));
2933 return _wchdir(wBuffer);
2939 win32_access(const char *path, int mode)
2943 WCHAR wBuffer[MAX_PATH+1];
2944 A2WHELPER(path, wBuffer, sizeof(wBuffer));
2945 return _waccess(PerlDir_mapW(wBuffer), mode);
2947 return access(PerlDir_mapA(path), mode);
2951 win32_chmod(const char *path, int mode)
2955 WCHAR wBuffer[MAX_PATH+1];
2956 A2WHELPER(path, wBuffer, sizeof(wBuffer));
2957 return _wchmod(PerlDir_mapW(wBuffer), mode);
2959 return chmod(PerlDir_mapA(path), mode);
2964 create_command_line(const char* command, const char * const *args)
2968 char *cmd, *ptr, *arg;
2969 STRLEN len = strlen(command) + 1;
2971 for (index = 0; (ptr = (char*)args[index]) != NULL; ++index)
2972 len += strlen(ptr) + 1;
2974 New(1310, cmd, len, char);
2976 strcpy(ptr, command);
2978 for (index = 0; (arg = (char*)args[index]) != NULL; ++index) {
2988 qualified_path(const char *cmd)
2992 char *fullcmd, *curfullcmd;
2998 fullcmd = (char*)cmd;
3000 if (*fullcmd == '/' || *fullcmd == '\\')
3007 pathstr = win32_getenv("PATH");
3008 New(0, fullcmd, MAX_PATH+1, char);
3009 curfullcmd = fullcmd;
3014 /* start by appending the name to the current prefix */
3015 strcpy(curfullcmd, cmd);
3016 curfullcmd += cmdlen;
3018 /* if it doesn't end with '.', or has no extension, try adding
3019 * a trailing .exe first */
3020 if (cmd[cmdlen-1] != '.'
3021 && (cmdlen < 4 || cmd[cmdlen-4] != '.'))
3023 strcpy(curfullcmd, ".exe");
3024 res = GetFileAttributes(fullcmd);
3025 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
3030 /* that failed, try the bare name */
3031 res = GetFileAttributes(fullcmd);
3032 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
3035 /* quit if no other path exists, or if cmd already has path */
3036 if (!pathstr || !*pathstr || has_slash)
3039 /* skip leading semis */
3040 while (*pathstr == ';')
3043 /* build a new prefix from scratch */
3044 curfullcmd = fullcmd;
3045 while (*pathstr && *pathstr != ';') {
3046 if (*pathstr == '"') { /* foo;"baz;etc";bar */
3047 pathstr++; /* skip initial '"' */
3048 while (*pathstr && *pathstr != '"') {
3049 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
3050 *curfullcmd++ = *pathstr;
3054 pathstr++; /* skip trailing '"' */
3057 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
3058 *curfullcmd++ = *pathstr;
3063 pathstr++; /* skip trailing semi */
3064 if (curfullcmd > fullcmd /* append a dir separator */
3065 && curfullcmd[-1] != '/' && curfullcmd[-1] != '\\')
3067 *curfullcmd++ = '\\';
3075 /* The following are just place holders.
3076 * Some hosts may provide and environment that the OS is
3077 * not tracking, therefore, these host must provide that
3078 * environment and the current directory to CreateProcess
3088 free_childenv(void* d)
3097 char szfilename[(MAX_PATH+1)*2];
3099 WCHAR wfilename[MAX_PATH+1];
3100 GetCurrentDirectoryW(MAX_PATH+1, wfilename);
3101 W2AHELPER(wfilename, szfilename, sizeof(szfilename));
3104 GetCurrentDirectoryA(MAX_PATH+1, szfilename);
3107 New(0, ptr, strlen(szfilename)+1, char);
3108 strcpy(ptr, szfilename);
3113 free_childdir(char* d)
3120 /* XXX this needs to be made more compatible with the spawnvp()
3121 * provided by the various RTLs. In particular, searching for
3122 * *.{com,bat,cmd} files (as done by the RTLs) is unimplemented.
3123 * This doesn't significantly affect perl itself, because we
3124 * always invoke things using PERL5SHELL if a direct attempt to
3125 * spawn the executable fails.
3127 * XXX splitting and rejoining the commandline between do_aspawn()
3128 * and win32_spawnvp() could also be avoided.
3132 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
3134 #ifdef USE_RTL_SPAWNVP
3135 return spawnvp(mode, cmdname, (char * const *)argv);
3142 STARTUPINFO StartupInfo;
3143 PROCESS_INFORMATION ProcessInformation;
3146 char *cmd = create_command_line(cmdname, strcmp(cmdname, argv[0]) == 0
3148 char *fullcmd = Nullch;
3150 env = PerlEnv_get_childenv();
3151 dir = PerlEnv_get_childdir();
3154 case P_NOWAIT: /* asynch + remember result */
3155 if (w32_num_children >= MAXIMUM_WAIT_OBJECTS) {
3161 case P_WAIT: /* synchronous execution */
3163 default: /* invalid mode */
3168 memset(&StartupInfo,0,sizeof(StartupInfo));
3169 StartupInfo.cb = sizeof(StartupInfo);
3170 PerlEnv_get_child_IO(&tbl);
3171 StartupInfo.hStdInput = tbl.childStdIn;
3172 StartupInfo.hStdOutput = tbl.childStdOut;
3173 StartupInfo.hStdError = tbl.childStdErr;
3174 if (StartupInfo.hStdInput != INVALID_HANDLE_VALUE &&
3175 StartupInfo.hStdOutput != INVALID_HANDLE_VALUE &&
3176 StartupInfo.hStdError != INVALID_HANDLE_VALUE)
3178 StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
3181 create |= CREATE_NEW_CONSOLE;
3185 if (!CreateProcess(cmdname, /* search PATH to find executable */
3186 cmd, /* executable, and its arguments */
3187 NULL, /* process attributes */
3188 NULL, /* thread attributes */
3189 TRUE, /* inherit handles */
3190 create, /* creation flags */
3191 (LPVOID)env, /* inherit environment */
3192 dir, /* inherit cwd */
3194 &ProcessInformation))
3196 /* initial NULL argument to CreateProcess() does a PATH
3197 * search, but it always first looks in the directory
3198 * where the current process was started, which behavior
3199 * is undesirable for backward compatibility. So we
3200 * jump through our own hoops by picking out the path
3201 * we really want it to use. */
3203 fullcmd = qualified_path(cmdname);
3214 if (mode == P_NOWAIT) {
3215 /* asynchronous spawn -- store handle, return PID */
3216 w32_child_handles[w32_num_children] = ProcessInformation.hProcess;
3217 w32_child_pids[w32_num_children] = ProcessInformation.dwProcessId;
3218 ret = (int)ProcessInformation.dwProcessId;
3223 WaitForSingleObject(ProcessInformation.hProcess, INFINITE);
3224 GetExitCodeProcess(ProcessInformation.hProcess, &status);
3226 CloseHandle(ProcessInformation.hProcess);
3229 CloseHandle(ProcessInformation.hThread);
3232 PerlEnv_free_childenv(env);
3233 PerlEnv_free_childdir(dir);
3241 win32_execv(const char *cmdname, const char *const *argv)
3245 /* if this is a pseudo-forked child, we just want to spawn
3246 * the new program, and return */
3248 return spawnv(P_WAIT, cmdname, (char *const *)argv);
3250 return execv(cmdname, (char *const *)argv);
3254 win32_execvp(const char *cmdname, const char *const *argv)
3258 /* if this is a pseudo-forked child, we just want to spawn
3259 * the new program, and return */
3261 return win32_spawnvp(P_WAIT, cmdname, (char *const *)argv);
3263 return execvp(cmdname, (char *const *)argv);
3267 win32_perror(const char *str)
3273 win32_setbuf(FILE *pf, char *buf)
3279 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
3281 return setvbuf(pf, buf, type, size);
3285 win32_flushall(void)
3291 win32_fcloseall(void)
3297 win32_fgets(char *s, int n, FILE *pf)
3299 return fgets(s, n, pf);
3309 win32_fgetc(FILE *pf)
3315 win32_putc(int c, FILE *pf)
3321 win32_puts(const char *s)
3333 win32_putchar(int c)
3340 #ifndef USE_PERL_SBRK
3342 static char *committed = NULL;
3343 static char *base = NULL;
3344 static char *reserved = NULL;
3345 static char *brk = NULL;
3346 static DWORD pagesize = 0;
3347 static DWORD allocsize = 0;
3355 GetSystemInfo(&info);
3356 /* Pretend page size is larger so we don't perpetually
3357 * call the OS to commit just one page ...
3359 pagesize = info.dwPageSize << 3;
3360 allocsize = info.dwAllocationGranularity;
3362 /* This scheme fails eventually if request for contiguous
3363 * block is denied so reserve big blocks - this is only
3364 * address space not memory ...
3366 if (brk+need >= reserved)
3368 DWORD size = 64*1024*1024;
3370 if (committed && reserved && committed < reserved)
3372 /* Commit last of previous chunk cannot span allocations */
3373 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
3375 committed = reserved;
3377 /* Reserve some (more) space
3378 * Note this is a little sneaky, 1st call passes NULL as reserved
3379 * so lets system choose where we start, subsequent calls pass
3380 * the old end address so ask for a contiguous block
3382 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
3385 reserved = addr+size;
3400 if (brk > committed)
3402 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
3403 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
3418 win32_malloc(size_t size)
3420 return malloc(size);
3424 win32_calloc(size_t numitems, size_t size)
3426 return calloc(numitems,size);
3430 win32_realloc(void *block, size_t size)
3432 return realloc(block,size);
3436 win32_free(void *block)
3443 win32_open_osfhandle(long handle, int flags)
3445 #ifdef USE_FIXED_OSFHANDLE
3447 return my_open_osfhandle(handle, flags);
3449 return _open_osfhandle(handle, flags);
3453 win32_get_osfhandle(int fd)
3455 return _get_osfhandle(fd);
3459 win32_dynaload(const char* filename)
3464 WCHAR wfilename[MAX_PATH+1];
3465 A2WHELPER(filename, wfilename, sizeof(wfilename));
3466 hModule = LoadLibraryExW(PerlDir_mapW(wfilename), NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
3469 hModule = LoadLibraryExA(PerlDir_mapA(filename), NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
3482 /* Make the host for current directory */
3483 char* ptr = PerlEnv_get_childdir();
3486 * then it worked, set PV valid,
3487 * else return 'undef'
3490 SV *sv = sv_newmortal();
3492 PerlEnv_free_childdir(ptr);
3507 Perl_croak(aTHX_ "usage: Win32::SetCurrentDirectory($cwd)");
3508 if (!PerlDir_chdir(SvPV_nolen(ST(0))))
3515 XS(w32_GetNextAvailDrive)
3519 char root[] = "_:\\";
3524 if (GetDriveType(root) == 1) {
3533 XS(w32_GetLastError)
3537 XSRETURN_IV(GetLastError());
3541 XS(w32_SetLastError)
3545 Perl_croak(aTHX_ "usage: Win32::SetLastError($error)");
3546 SetLastError(SvIV(ST(0)));
3554 char *name = w32_getlogin_buffer;
3555 DWORD size = sizeof(w32_getlogin_buffer);
3557 if (GetUserName(name,&size)) {
3558 /* size includes NULL */
3559 ST(0) = sv_2mortal(newSVpvn(name,size-1));
3569 char name[MAX_COMPUTERNAME_LENGTH+1];
3570 DWORD size = sizeof(name);
3572 if (GetComputerName(name,&size)) {
3573 /* size does NOT include NULL :-( */
3574 ST(0) = sv_2mortal(newSVpvn(name,size));
3585 HINSTANCE hNetApi32 = LoadLibrary("netapi32.dll");
3586 DWORD (__stdcall *pfnNetApiBufferFree)(LPVOID Buffer);
3587 DWORD (__stdcall *pfnNetWkstaGetInfo)(LPWSTR servername, DWORD level,
3591 pfnNetApiBufferFree = (DWORD (__stdcall *)(void *))
3592 GetProcAddress(hNetApi32, "NetApiBufferFree");
3593 pfnNetWkstaGetInfo = (DWORD (__stdcall *)(LPWSTR, DWORD, void *))
3594 GetProcAddress(hNetApi32, "NetWkstaGetInfo");
3597 if (hNetApi32 && pfnNetWkstaGetInfo && pfnNetApiBufferFree) {
3598 /* this way is more reliable, in case user has a local account. */
3600 DWORD dnamelen = sizeof(dname);
3602 DWORD wki100_platform_id;
3603 LPWSTR wki100_computername;
3604 LPWSTR wki100_langroup;
3605 DWORD wki100_ver_major;
3606 DWORD wki100_ver_minor;
3608 /* NERR_Success *is* 0*/
3609 if (0 == pfnNetWkstaGetInfo(NULL, 100, &pwi)) {
3610 if (pwi->wki100_langroup && *(pwi->wki100_langroup)) {
3611 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_langroup,
3612 -1, (LPSTR)dname, dnamelen, NULL, NULL);
3615 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_computername,
3616 -1, (LPSTR)dname, dnamelen, NULL, NULL);
3618 pfnNetApiBufferFree(pwi);
3619 FreeLibrary(hNetApi32);
3622 FreeLibrary(hNetApi32);
3625 /* Win95 doesn't have NetWksta*(), so do it the old way */
3627 DWORD size = sizeof(name);
3629 FreeLibrary(hNetApi32);
3630 if (GetUserName(name,&size)) {
3631 char sid[ONE_K_BUFSIZE];
3632 DWORD sidlen = sizeof(sid);
3634 DWORD dnamelen = sizeof(dname);
3636 if (LookupAccountName(NULL, name, (PSID)&sid, &sidlen,
3637 dname, &dnamelen, &snu)) {
3638 XSRETURN_PV(dname); /* all that for this */
3650 DWORD flags, filecomplen;
3651 if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
3652 &flags, fsname, sizeof(fsname))) {
3653 if (GIMME_V == G_ARRAY) {
3654 XPUSHs(sv_2mortal(newSVpvn(fsname,strlen(fsname))));
3655 XPUSHs(sv_2mortal(newSViv(flags)));
3656 XPUSHs(sv_2mortal(newSViv(filecomplen)));
3661 XSRETURN_PV(fsname);
3667 XS(w32_GetOSVersion)
3670 OSVERSIONINFOA osver;
3673 OSVERSIONINFOW osverw;
3674 char szCSDVersion[sizeof(osverw.szCSDVersion)];
3675 osverw.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
3676 if (!GetVersionExW(&osverw)) {
3679 W2AHELPER(osverw.szCSDVersion, szCSDVersion, sizeof(szCSDVersion));
3680 XPUSHs(newSVpvn(szCSDVersion, strlen(szCSDVersion)));
3681 osver.dwMajorVersion = osverw.dwMajorVersion;
3682 osver.dwMinorVersion = osverw.dwMinorVersion;
3683 osver.dwBuildNumber = osverw.dwBuildNumber;
3684 osver.dwPlatformId = osverw.dwPlatformId;
3687 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOA);
3688 if (!GetVersionExA(&osver)) {
3691 XPUSHs(newSVpvn(osver.szCSDVersion, strlen(osver.szCSDVersion)));
3693 XPUSHs(newSViv(osver.dwMajorVersion));
3694 XPUSHs(newSViv(osver.dwMinorVersion));
3695 XPUSHs(newSViv(osver.dwBuildNumber));
3696 XPUSHs(newSViv(osver.dwPlatformId));
3705 XSRETURN_IV(IsWinNT());
3713 XSRETURN_IV(IsWin95());
3717 XS(w32_FormatMessage)
3721 char msgbuf[ONE_K_BUFSIZE];
3724 Perl_croak(aTHX_ "usage: Win32::FormatMessage($errno)");
3727 WCHAR wmsgbuf[ONE_K_BUFSIZE];
3728 if (FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM,
3729 &source, SvIV(ST(0)), 0,
3730 wmsgbuf, ONE_K_BUFSIZE-1, NULL))
3732 W2AHELPER(wmsgbuf, msgbuf, sizeof(msgbuf));
3733 XSRETURN_PV(msgbuf);
3737 if (FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM,
3738 &source, SvIV(ST(0)), 0,
3739 msgbuf, sizeof(msgbuf)-1, NULL))
3740 XSRETURN_PV(msgbuf);
3751 PROCESS_INFORMATION stProcInfo;
3752 STARTUPINFO stStartInfo;
3753 BOOL bSuccess = FALSE;
3756 Perl_croak(aTHX_ "usage: Win32::Spawn($cmdName, $args, $PID)");
3758 cmd = SvPV_nolen(ST(0));
3759 args = SvPV_nolen(ST(1));
3761 memset(&stStartInfo, 0, sizeof(stStartInfo)); /* Clear the block */
3762 stStartInfo.cb = sizeof(stStartInfo); /* Set the structure size */
3763 stStartInfo.dwFlags = STARTF_USESHOWWINDOW; /* Enable wShowWindow control */
3764 stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE; /* Start min (normal) */
3767 cmd, /* Image path */
3768 args, /* Arguments for command line */
3769 NULL, /* Default process security */
3770 NULL, /* Default thread security */
3771 FALSE, /* Must be TRUE to use std handles */
3772 NORMAL_PRIORITY_CLASS, /* No special scheduling */
3773 NULL, /* Inherit our environment block */
3774 NULL, /* Inherit our currrent directory */
3775 &stStartInfo, /* -> Startup info */
3776 &stProcInfo)) /* <- Process info (if OK) */
3778 CloseHandle(stProcInfo.hThread);/* library source code does this. */
3779 sv_setiv(ST(2), stProcInfo.dwProcessId);
3782 XSRETURN_IV(bSuccess);
3786 XS(w32_GetTickCount)
3789 DWORD msec = GetTickCount();
3797 XS(w32_GetShortPathName)
3804 Perl_croak(aTHX_ "usage: Win32::GetShortPathName($longPathName)");
3806 shortpath = sv_mortalcopy(ST(0));
3807 SvUPGRADE(shortpath, SVt_PV);
3808 /* src == target is allowed */
3810 len = GetShortPathName(SvPVX(shortpath),
3813 } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
3815 SvCUR_set(shortpath,len);
3823 XS(w32_GetFullPathName)
3832 Perl_croak(aTHX_ "usage: Win32::GetFullPathName($filename)");
3835 fullpath = sv_mortalcopy(filename);
3836 SvUPGRADE(fullpath, SVt_PV);
3838 len = GetFullPathName(SvPVX(filename),
3842 } while (len >= SvLEN(fullpath) && sv_grow(fullpath,len+1));
3844 if (GIMME_V == G_ARRAY) {
3846 XST_mPV(1,filepart);
3847 len = filepart - SvPVX(fullpath);
3850 SvCUR_set(fullpath,len);
3858 XS(w32_GetLongPathName)
3862 char tmpbuf[MAX_PATH+1];
3867 Perl_croak(aTHX_ "usage: Win32::GetLongPathName($pathname)");
3870 pathstr = SvPV(path,len);
3871 strcpy(tmpbuf, pathstr);
3872 pathstr = win32_longpath(tmpbuf);
3874 ST(0) = sv_2mortal(newSVpvn(pathstr, strlen(pathstr)));
3885 Perl_croak(aTHX_ "usage: Win32::Sleep($milliseconds)");
3896 Perl_croak(aTHX_ "usage: Win32::CopyFile($from, $to, $overwrite)");
3898 WCHAR wSourceFile[MAX_PATH+1];
3899 WCHAR wDestFile[MAX_PATH+1];
3900 A2WHELPER(SvPV_nolen(ST(0)), wSourceFile, sizeof(wSourceFile));
3901 wcscpy(wSourceFile, PerlDir_mapW(wSourceFile));
3902 A2WHELPER(SvPV_nolen(ST(1)), wDestFile, sizeof(wDestFile));
3903 bResult = CopyFileW(wSourceFile, PerlDir_mapW(wDestFile), !SvTRUE(ST(2)));
3906 char szSourceFile[MAX_PATH+1];
3907 strcpy(szSourceFile, PerlDir_mapA(SvPV_nolen(ST(0))));
3908 bResult = CopyFileA(szSourceFile, PerlDir_mapA(SvPV_nolen(ST(1))), !SvTRUE(ST(2)));
3917 Perl_init_os_extras(void)
3920 char *file = __FILE__;
3923 w32_perlshell_tokens = Nullch;
3924 w32_perlshell_items = -1;
3925 w32_fdpid = newAV(); /* XXX needs to be in Perl_win32_init()? */
3926 New(1313, w32_children, 1, child_tab);
3927 w32_num_children = 0;
3928 w32_init_socktype = 0;
3931 New(1313, w32_pseudo_children, 1, child_tab);
3932 w32_num_pseudo_children = 0;
3935 /* these names are Activeware compatible */
3936 newXS("Win32::GetCwd", w32_GetCwd, file);
3937 newXS("Win32::SetCwd", w32_SetCwd, file);
3938 newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
3939 newXS("Win32::GetLastError", w32_GetLastError, file);
3940 newXS("Win32::SetLastError", w32_SetLastError, file);
3941 newXS("Win32::LoginName", w32_LoginName, file);
3942 newXS("Win32::NodeName", w32_NodeName, file);
3943 newXS("Win32::DomainName", w32_DomainName, file);
3944 newXS("Win32::FsType", w32_FsType, file);
3945 newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
3946 newXS("Win32::IsWinNT", w32_IsWinNT, file);
3947 newXS("Win32::IsWin95", w32_IsWin95, file);
3948 newXS("Win32::FormatMessage", w32_FormatMessage, file);
3949 newXS("Win32::Spawn", w32_Spawn, file);
3950 newXS("Win32::GetTickCount", w32_GetTickCount, file);
3951 newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
3952 newXS("Win32::GetFullPathName", w32_GetFullPathName, file);
3953 newXS("Win32::GetLongPathName", w32_GetLongPathName, file);
3954 newXS("Win32::CopyFile", w32_CopyFile, file);
3955 newXS("Win32::Sleep", w32_Sleep, file);
3957 /* XXX Bloat Alert! The following Activeware preloads really
3958 * ought to be part of Win32::Sys::*, so they're not included
3961 /* LookupAccountName
3963 * InitiateSystemShutdown
3964 * AbortSystemShutdown
3965 * ExpandEnvrironmentStrings
3970 Perl_win32_init(int *argcp, char ***argvp)
3972 /* Disable floating point errors, Perl will trap the ones we
3973 * care about. VC++ RTL defaults to switching these off
3974 * already, but the Borland RTL doesn't. Since we don't
3975 * want to be at the vendor's whim on the default, we set
3976 * it explicitly here.
3978 #if !defined(_ALPHA_) && !defined(__GNUC__)
3979 _control87(MCW_EM, MCW_EM);
3985 win32_get_child_IO(child_IO_table* ptbl)
3987 ptbl->childStdIn = GetStdHandle(STD_INPUT_HANDLE);
3988 ptbl->childStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
3989 ptbl->childStdErr = GetStdHandle(STD_ERROR_HANDLE);
3996 # undef Perl_sys_intern_dup
3997 # define Perl_sys_intern_dup CPerlObj::Perl_sys_intern_dup
4002 Perl_sys_intern_dup(pTHX_ struct interp_intern *src, struct interp_intern *dst)
4004 dst->perlshell_tokens = Nullch;
4005 dst->perlshell_vec = (char**)NULL;
4006 dst->perlshell_items = 0;
4007 dst->fdpid = newAV();
4008 Newz(1313, dst->children, 1, child_tab);
4009 Newz(1313, dst->pseudo_children, 1, child_tab);
4011 dst->children->num = 0;
4012 dst->thr_intern.Winit_socktype = src->thr_intern.Winit_socktype;
4022 win32_free_argvw(pTHXo_ void *ptr)
4024 char** argv = (char**)ptr;
4032 win32_argv2utf8(int argc, char** argv)
4037 LPWSTR* lpwStr = CommandLineToArgvW(GetCommandLineW(), &wargc);
4038 if (lpwStr && argc) {
4040 length = WideCharToMultiByte(CP_UTF8, 0, lpwStr[--wargc], -1, NULL, 0, NULL, NULL);
4041 Newz(0, psz, length, char);
4042 WideCharToMultiByte(CP_UTF8, 0, lpwStr[wargc], -1, psz, length, NULL, NULL);
4045 call_atexit(win32_free_argvw, argv);
4047 GlobalFree((HGLOBAL)lpwStr);