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);
992 hProcess = w32_pseudo_child_handles[child];
993 if (TerminateThread(hProcess, sig)) {
994 remove_dead_pseudo_process(child);
1002 long child = find_pid(pid);
1004 hProcess = w32_child_handles[child];
1005 if (TerminateProcess(hProcess, sig)) {
1006 remove_dead_process(child);
1011 hProcess = OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid);
1012 if (hProcess && TerminateProcess(hProcess, sig)) {
1013 CloseHandle(hProcess);
1026 DllExport unsigned int
1027 win32_sleep(unsigned int t)
1034 win32_stat(const char *path, struct stat *sbuf)
1037 char buffer[MAX_PATH+1];
1038 int l = strlen(path);
1040 WCHAR wbuffer[MAX_PATH+1];
1046 switch(path[l - 1]) {
1047 /* FindFirstFile() and stat() are buggy with a trailing
1048 * backslash, so change it to a forward slash :-( */
1050 strncpy(buffer, path, l-1);
1051 buffer[l - 1] = '/';
1055 /* FindFirstFile() is buggy with "x:", so add a dot :-( */
1057 if (l == 2 && isALPHA(path[0])) {
1058 buffer[0] = path[0];
1069 /* We *must* open & close the file once; otherwise file attribute changes */
1070 /* might not yet have propagated to "other" hard links of the same file. */
1071 /* This also gives us an opportunity to determine the number of links. */
1073 A2WHELPER(path, wbuffer, sizeof(wbuffer));
1074 pwbuffer = PerlDir_mapW(wbuffer);
1075 handle = CreateFileW(pwbuffer, 0, 0, NULL, OPEN_EXISTING, 0, NULL);
1078 path = PerlDir_mapA(path);
1080 handle = CreateFileA(path, 0, 0, NULL, OPEN_EXISTING, 0, NULL);
1082 if (handle != INVALID_HANDLE_VALUE) {
1083 BY_HANDLE_FILE_INFORMATION bhi;
1084 if (GetFileInformationByHandle(handle, &bhi))
1085 nlink = bhi.nNumberOfLinks;
1086 CloseHandle(handle);
1089 /* pwbuffer or path will be mapped correctly above */
1091 res = _wstat(pwbuffer, (struct _stat *)sbuf);
1094 res = stat(path, sbuf);
1096 sbuf->st_nlink = nlink;
1099 /* CRT is buggy on sharenames, so make sure it really isn't.
1100 * XXX using GetFileAttributesEx() will enable us to set
1101 * sbuf->st_*time (but note that's not available on the
1102 * Windows of 1995) */
1105 r = GetFileAttributesW(pwbuffer);
1108 r = GetFileAttributesA(path);
1110 if (r != 0xffffffff && (r & FILE_ATTRIBUTE_DIRECTORY)) {
1111 /* sbuf may still contain old garbage since stat() failed */
1112 Zero(sbuf, 1, struct stat);
1113 sbuf->st_mode = S_IFDIR | S_IREAD;
1115 if (!(r & FILE_ATTRIBUTE_READONLY))
1116 sbuf->st_mode |= S_IWRITE | S_IEXEC;
1121 if (l == 3 && isALPHA(path[0]) && path[1] == ':'
1122 && (path[2] == '\\' || path[2] == '/'))
1124 /* The drive can be inaccessible, some _stat()s are buggy */
1126 ? !GetVolumeInformationW(pwbuffer,NULL,0,NULL,NULL,NULL,NULL,0)
1127 : !GetVolumeInformationA(path,NULL,0,NULL,NULL,NULL,NULL,0)) {
1133 if (S_ISDIR(sbuf->st_mode))
1134 sbuf->st_mode |= S_IWRITE | S_IEXEC;
1135 else if (S_ISREG(sbuf->st_mode)) {
1137 if (l >= 4 && path[l-4] == '.') {
1138 const char *e = path + l - 3;
1139 if (strnicmp(e,"exe",3)
1140 && strnicmp(e,"bat",3)
1141 && strnicmp(e,"com",3)
1142 && (IsWin95() || strnicmp(e,"cmd",3)))
1143 sbuf->st_mode &= ~S_IEXEC;
1145 sbuf->st_mode |= S_IEXEC;
1148 sbuf->st_mode &= ~S_IEXEC;
1149 /* Propagate permissions to _group_ and _others_ */
1150 perms = sbuf->st_mode & (S_IREAD|S_IWRITE|S_IEXEC);
1151 sbuf->st_mode |= (perms>>3) | (perms>>6);
1158 /* Find the longname of a given path. path is destructively modified.
1159 * It should have space for at least MAX_PATH characters. */
1161 win32_longpath(char *path)
1163 WIN32_FIND_DATA fdata;
1165 char tmpbuf[MAX_PATH+1];
1166 char *tmpstart = tmpbuf;
1173 if (isALPHA(path[0]) && path[1] == ':' &&
1174 (path[2] == '/' || path[2] == '\\'))
1177 *tmpstart++ = path[0];
1181 else if ((path[0] == '/' || path[0] == '\\') &&
1182 (path[1] == '/' || path[1] == '\\'))
1185 *tmpstart++ = path[0];
1186 *tmpstart++ = path[1];
1187 /* copy machine name */
1188 while (*start && *start != '/' && *start != '\\')
1189 *tmpstart++ = *start++;
1191 *tmpstart++ = *start;
1193 /* copy share name */
1194 while (*start && *start != '/' && *start != '\\')
1195 *tmpstart++ = *start++;
1199 if (sep == '/' || sep == '\\')
1203 /* walk up to slash */
1204 while (*start && *start != '/' && *start != '\\')
1207 /* discard doubled slashes */
1208 while (*start && (start[1] == '/' || start[1] == '\\'))
1212 /* stop and find full name of component */
1214 fhand = FindFirstFile(path,&fdata);
1215 if (fhand != INVALID_HANDLE_VALUE) {
1216 strcpy(tmpstart, fdata.cFileName);
1217 tmpstart += strlen(fdata.cFileName);
1225 /* failed a step, just return without side effects */
1226 /*PerlIO_printf(Perl_debug_log, "Failed to find %s\n", path);*/
1231 strcpy(path,tmpbuf);
1235 #ifndef USE_WIN32_RTL_ENV
1238 win32_getenv(const char *name)
1241 WCHAR wBuffer[MAX_PATH+1];
1243 SV *curitem = Nullsv;
1246 A2WHELPER(name, wBuffer, sizeof(wBuffer));
1247 needlen = GetEnvironmentVariableW(wBuffer, NULL, 0);
1250 needlen = GetEnvironmentVariableA(name,NULL,0);
1252 curitem = sv_2mortal(newSVpvn("", 0));
1256 SvGROW(curitem, (needlen+1)*sizeof(WCHAR));
1257 needlen = GetEnvironmentVariableW(wBuffer,
1258 (WCHAR*)SvPVX(curitem),
1260 } while (needlen >= SvLEN(curitem)/sizeof(WCHAR));
1261 SvCUR_set(curitem, (needlen*sizeof(WCHAR))+1);
1262 acuritem = sv_2mortal(newSVsv(curitem));
1263 W2AHELPER((WCHAR*)SvPVX(acuritem), SvPVX(curitem), SvCUR(curitem));
1267 SvGROW(curitem, needlen+1);
1268 needlen = GetEnvironmentVariableA(name,SvPVX(curitem),
1270 } while (needlen >= SvLEN(curitem));
1271 SvCUR_set(curitem, needlen);
1275 /* allow any environment variables that begin with 'PERL'
1276 to be stored in the registry */
1277 if (strncmp(name, "PERL", 4) == 0)
1278 (void)get_regstr(name, &curitem);
1280 if (curitem && SvCUR(curitem))
1281 return SvPVX(curitem);
1287 win32_putenv(const char *name)
1294 int length, relval = -1;
1298 length = strlen(name)+1;
1299 New(1309,wCuritem,length,WCHAR);
1300 A2WHELPER(name, wCuritem, length*sizeof(WCHAR));
1301 wVal = wcschr(wCuritem, '=');
1304 if (SetEnvironmentVariableW(wCuritem, *wVal ? wVal : NULL))
1310 New(1309,curitem,strlen(name)+1,char);
1311 strcpy(curitem, name);
1312 val = strchr(curitem, '=');
1314 /* The sane way to deal with the environment.
1315 * Has these advantages over putenv() & co.:
1316 * * enables us to store a truly empty value in the
1317 * environment (like in UNIX).
1318 * * we don't have to deal with RTL globals, bugs and leaks.
1320 * Why you may want to enable USE_WIN32_RTL_ENV:
1321 * * environ[] and RTL functions will not reflect changes,
1322 * which might be an issue if extensions want to access
1323 * the env. via RTL. This cuts both ways, since RTL will
1324 * not see changes made by extensions that call the Win32
1325 * functions directly, either.
1329 if (SetEnvironmentVariableA(curitem, *val ? val : NULL))
1341 filetime_to_clock(PFILETIME ft)
1343 __int64 qw = ft->dwHighDateTime;
1345 qw |= ft->dwLowDateTime;
1346 qw /= 10000; /* File time ticks at 0.1uS, clock at 1mS */
1351 win32_times(struct tms *timebuf)
1356 if (GetProcessTimes(GetCurrentProcess(), &dummy, &dummy,
1358 timebuf->tms_utime = filetime_to_clock(&user);
1359 timebuf->tms_stime = filetime_to_clock(&kernel);
1360 timebuf->tms_cutime = 0;
1361 timebuf->tms_cstime = 0;
1364 /* That failed - e.g. Win95 fallback to clock() */
1365 clock_t t = clock();
1366 timebuf->tms_utime = t;
1367 timebuf->tms_stime = 0;
1368 timebuf->tms_cutime = 0;
1369 timebuf->tms_cstime = 0;
1374 /* fix utime() so it works on directories in NT */
1376 filetime_from_time(PFILETIME pFileTime, time_t Time)
1378 struct tm *pTM = localtime(&Time);
1379 SYSTEMTIME SystemTime;
1385 SystemTime.wYear = pTM->tm_year + 1900;
1386 SystemTime.wMonth = pTM->tm_mon + 1;
1387 SystemTime.wDay = pTM->tm_mday;
1388 SystemTime.wHour = pTM->tm_hour;
1389 SystemTime.wMinute = pTM->tm_min;
1390 SystemTime.wSecond = pTM->tm_sec;
1391 SystemTime.wMilliseconds = 0;
1393 return SystemTimeToFileTime(&SystemTime, &LocalTime) &&
1394 LocalFileTimeToFileTime(&LocalTime, pFileTime);
1398 win32_unlink(const char *filename)
1405 WCHAR wBuffer[MAX_PATH+1];
1408 A2WHELPER(filename, wBuffer, sizeof(wBuffer));
1409 pwBuffer = PerlDir_mapW(wBuffer);
1410 attrs = GetFileAttributesW(pwBuffer);
1411 if (attrs == 0xFFFFFFFF)
1413 if (attrs & FILE_ATTRIBUTE_READONLY) {
1414 (void)SetFileAttributesW(pwBuffer, attrs & ~FILE_ATTRIBUTE_READONLY);
1415 ret = _wunlink(pwBuffer);
1417 (void)SetFileAttributesW(pwBuffer, attrs);
1420 ret = _wunlink(pwBuffer);
1423 filename = PerlDir_mapA(filename);
1424 attrs = GetFileAttributesA(filename);
1425 if (attrs == 0xFFFFFFFF)
1427 if (attrs & FILE_ATTRIBUTE_READONLY) {
1428 (void)SetFileAttributesA(filename, attrs & ~FILE_ATTRIBUTE_READONLY);
1429 ret = unlink(filename);
1431 (void)SetFileAttributesA(filename, attrs);
1434 ret = unlink(filename);
1443 win32_utime(const char *filename, struct utimbuf *times)
1450 struct utimbuf TimeBuffer;
1451 WCHAR wbuffer[MAX_PATH+1];
1456 A2WHELPER(filename, wbuffer, sizeof(wbuffer));
1457 pwbuffer = PerlDir_mapW(wbuffer);
1458 rc = _wutime(pwbuffer, (struct _utimbuf*)times);
1461 filename = PerlDir_mapA(filename);
1462 rc = utime(filename, times);
1464 /* EACCES: path specifies directory or readonly file */
1465 if (rc == 0 || errno != EACCES /* || !IsWinNT() */)
1468 if (times == NULL) {
1469 times = &TimeBuffer;
1470 time(×->actime);
1471 times->modtime = times->actime;
1474 /* This will (and should) still fail on readonly files */
1476 handle = CreateFileW(pwbuffer, GENERIC_READ | GENERIC_WRITE,
1477 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1478 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1481 handle = CreateFileA(filename, GENERIC_READ | GENERIC_WRITE,
1482 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1483 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1485 if (handle == INVALID_HANDLE_VALUE)
1488 if (GetFileTime(handle, &ftCreate, &ftAccess, &ftWrite) &&
1489 filetime_from_time(&ftAccess, times->actime) &&
1490 filetime_from_time(&ftWrite, times->modtime) &&
1491 SetFileTime(handle, &ftCreate, &ftAccess, &ftWrite))
1496 CloseHandle(handle);
1501 win32_uname(struct utsname *name)
1503 struct hostent *hep;
1504 STRLEN nodemax = sizeof(name->nodename)-1;
1505 OSVERSIONINFO osver;
1507 memset(&osver, 0, sizeof(OSVERSIONINFO));
1508 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1509 if (GetVersionEx(&osver)) {
1511 switch (osver.dwPlatformId) {
1512 case VER_PLATFORM_WIN32_WINDOWS:
1513 strcpy(name->sysname, "Windows");
1515 case VER_PLATFORM_WIN32_NT:
1516 strcpy(name->sysname, "Windows NT");
1518 case VER_PLATFORM_WIN32s:
1519 strcpy(name->sysname, "Win32s");
1522 strcpy(name->sysname, "Win32 Unknown");
1527 sprintf(name->release, "%d.%d",
1528 osver.dwMajorVersion, osver.dwMinorVersion);
1531 sprintf(name->version, "Build %d",
1532 osver.dwPlatformId == VER_PLATFORM_WIN32_NT
1533 ? osver.dwBuildNumber : (osver.dwBuildNumber & 0xffff));
1534 if (osver.szCSDVersion[0]) {
1535 char *buf = name->version + strlen(name->version);
1536 sprintf(buf, " (%s)", osver.szCSDVersion);
1540 *name->sysname = '\0';
1541 *name->version = '\0';
1542 *name->release = '\0';
1546 hep = win32_gethostbyname("localhost");
1548 STRLEN len = strlen(hep->h_name);
1549 if (len <= nodemax) {
1550 strcpy(name->nodename, hep->h_name);
1553 strncpy(name->nodename, hep->h_name, nodemax);
1554 name->nodename[nodemax] = '\0';
1559 if (!GetComputerName(name->nodename, &sz))
1560 *name->nodename = '\0';
1563 /* machine (architecture) */
1567 GetSystemInfo(&info);
1569 #if defined(__BORLANDC__) || defined(__MINGW32__)
1570 switch (info.u.s.wProcessorArchitecture) {
1572 switch (info.wProcessorArchitecture) {
1574 case PROCESSOR_ARCHITECTURE_INTEL:
1575 arch = "x86"; break;
1576 case PROCESSOR_ARCHITECTURE_MIPS:
1577 arch = "mips"; break;
1578 case PROCESSOR_ARCHITECTURE_ALPHA:
1579 arch = "alpha"; break;
1580 case PROCESSOR_ARCHITECTURE_PPC:
1581 arch = "ppc"; break;
1583 arch = "unknown"; break;
1585 strcpy(name->machine, arch);
1591 win32_waitpid(int pid, int *status, int flags)
1595 if (pid == -1) /* XXX threadid == 1 ? */
1596 return win32_wait(status);
1599 long child = find_pseudo_pid(-pid);
1601 HANDLE hThread = w32_pseudo_child_handles[child];
1602 DWORD waitcode = WaitForSingleObject(hThread, INFINITE);
1603 if (waitcode != WAIT_FAILED) {
1604 if (GetExitCodeThread(hThread, &waitcode)) {
1605 *status = (int)((waitcode & 0xff) << 8);
1606 retval = (int)w32_pseudo_child_pids[child];
1607 remove_dead_pseudo_process(child);
1617 long child = find_pid(pid);
1619 HANDLE hProcess = w32_child_handles[child];
1620 DWORD waitcode = WaitForSingleObject(hProcess, INFINITE);
1621 if (waitcode != WAIT_FAILED) {
1622 if (GetExitCodeProcess(hProcess, &waitcode)) {
1623 *status = (int)((waitcode & 0xff) << 8);
1624 retval = (int)w32_child_pids[child];
1625 remove_dead_process(child);
1633 retval = cwait(status, pid, WAIT_CHILD);
1634 /* cwait() returns "correctly" on Borland */
1635 #ifndef __BORLANDC__
1641 return retval >= 0 ? pid : retval;
1645 win32_wait(int *status)
1647 /* XXX this wait emulation only knows about processes
1648 * spawned via win32_spawnvp(P_NOWAIT, ...).
1652 DWORD exitcode, waitcode;
1655 if (w32_num_pseudo_children) {
1656 waitcode = WaitForMultipleObjects(w32_num_pseudo_children,
1657 w32_pseudo_child_handles,
1660 if (waitcode != WAIT_FAILED) {
1661 if (waitcode >= WAIT_ABANDONED_0
1662 && waitcode < WAIT_ABANDONED_0 + w32_num_pseudo_children)
1663 i = waitcode - WAIT_ABANDONED_0;
1665 i = waitcode - WAIT_OBJECT_0;
1666 if (GetExitCodeThread(w32_pseudo_child_handles[i], &exitcode)) {
1667 *status = (int)((exitcode & 0xff) << 8);
1668 retval = (int)w32_pseudo_child_pids[i];
1669 remove_dead_pseudo_process(i);
1676 if (!w32_num_children) {
1681 /* if a child exists, wait for it to die */
1682 waitcode = WaitForMultipleObjects(w32_num_children,
1686 if (waitcode != WAIT_FAILED) {
1687 if (waitcode >= WAIT_ABANDONED_0
1688 && waitcode < WAIT_ABANDONED_0 + w32_num_children)
1689 i = waitcode - WAIT_ABANDONED_0;
1691 i = waitcode - WAIT_OBJECT_0;
1692 if (GetExitCodeProcess(w32_child_handles[i], &exitcode) ) {
1693 *status = (int)((exitcode & 0xff) << 8);
1694 retval = (int)w32_child_pids[i];
1695 remove_dead_process(i);
1701 errno = GetLastError();
1707 static UINT timerid = 0;
1709 static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
1712 KillTimer(NULL,timerid);
1716 #endif /* !PERL_OBJECT */
1718 DllExport unsigned int
1719 win32_alarm(unsigned int sec)
1723 * the 'obvious' implentation is SetTimer() with a callback
1724 * which does whatever receiving SIGALRM would do
1725 * we cannot use SIGALRM even via raise() as it is not
1726 * one of the supported codes in <signal.h>
1728 * Snag is unless something is looking at the message queue
1729 * nothing happens :-(
1734 timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
1736 Perl_croak_nocontext("Cannot set timer");
1742 KillTimer(NULL,timerid);
1746 #endif /* !PERL_OBJECT */
1750 #ifdef HAVE_DES_FCRYPT
1751 extern char * des_fcrypt(const char *txt, const char *salt, char *cbuf);
1755 win32_crypt(const char *txt, const char *salt)
1758 #ifdef HAVE_DES_FCRYPT
1760 return des_fcrypt(txt, salt, w32_crypt_buffer);
1762 Perl_croak(aTHX_ "The crypt() function is unimplemented due to excessive paranoia.");
1767 /* C doesn't like repeat struct definitions */
1769 #if defined(USE_FIXED_OSFHANDLE) || defined(PERL_MSVCRT_READFIX)
1772 #define _CRTIMP __declspec(dllimport)
1776 * Control structure for lowio file handles
1779 long osfhnd; /* underlying OS file HANDLE */
1780 char osfile; /* attributes of file (e.g., open in text mode?) */
1781 char pipech; /* one char buffer for handles opened on pipes */
1783 CRITICAL_SECTION lock;
1788 * Array of arrays of control structures for lowio files.
1790 EXTERN_C _CRTIMP ioinfo* __pioinfo[];
1793 * Definition of IOINFO_L2E, the log base 2 of the number of elements in each
1794 * array of ioinfo structs.
1796 #define IOINFO_L2E 5
1799 * Definition of IOINFO_ARRAY_ELTS, the number of elements in ioinfo array
1801 #define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
1804 * Access macros for getting at an ioinfo struct and its fields from a
1807 #define _pioinfo(i) (__pioinfo[(i) >> IOINFO_L2E] + ((i) & (IOINFO_ARRAY_ELTS - 1)))
1808 #define _osfhnd(i) (_pioinfo(i)->osfhnd)
1809 #define _osfile(i) (_pioinfo(i)->osfile)
1810 #define _pipech(i) (_pioinfo(i)->pipech)
1814 #ifdef USE_FIXED_OSFHANDLE
1816 #define FOPEN 0x01 /* file handle open */
1817 #define FNOINHERIT 0x10 /* file handle opened O_NOINHERIT */
1818 #define FAPPEND 0x20 /* file handle opened O_APPEND */
1819 #define FDEV 0x40 /* file handle refers to device */
1820 #define FTEXT 0x80 /* file handle is in text mode */
1823 *int my_open_osfhandle(long osfhandle, int flags) - open C Runtime file handle
1826 * This function allocates a free C Runtime file handle and associates
1827 * it with the Win32 HANDLE specified by the first parameter. This is a
1828 * temperary fix for WIN95's brain damage GetFileType() error on socket
1829 * we just bypass that call for socket
1831 * This works with MSVC++ 4.0+ or GCC/Mingw32
1834 * long osfhandle - Win32 HANDLE to associate with C Runtime file handle.
1835 * int flags - flags to associate with C Runtime file handle.
1838 * returns index of entry in fh, if successful
1839 * return -1, if no free entry is found
1843 *******************************************************************************/
1846 * we fake up some parts of the CRT that aren't exported by MSVCRT.dll
1847 * this lets sockets work on Win9X with GCC and should fix the problems
1852 /* since we are not doing a dup2(), this works fine */
1854 #define _set_osfhnd(fh, osfh) (void)(_osfhnd(fh) = osfh)
1856 /* create an ioinfo entry, kill its handle, and steal the entry */
1861 HANDLE hF = CreateFile("NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
1862 int fh = _open_osfhandle((long)hF, 0);
1866 EnterCriticalSection(&(_pioinfo(fh)->lock));
1871 my_open_osfhandle(long osfhandle, int flags)
1874 char fileflags; /* _osfile flags */
1876 /* copy relevant flags from second parameter */
1879 if (flags & O_APPEND)
1880 fileflags |= FAPPEND;
1885 if (flags & O_NOINHERIT)
1886 fileflags |= FNOINHERIT;
1888 /* attempt to allocate a C Runtime file handle */
1889 if ((fh = _alloc_osfhnd()) == -1) {
1890 errno = EMFILE; /* too many open files */
1891 _doserrno = 0L; /* not an OS error */
1892 return -1; /* return error to caller */
1895 /* the file is open. now, set the info in _osfhnd array */
1896 _set_osfhnd(fh, osfhandle);
1898 fileflags |= FOPEN; /* mark as open */
1900 _osfile(fh) = fileflags; /* set osfile entry */
1901 LeaveCriticalSection(&_pioinfo(fh)->lock);
1903 return fh; /* return handle */
1906 #endif /* USE_FIXED_OSFHANDLE */
1908 /* simulate flock by locking a range on the file */
1910 #define LK_ERR(f,i) ((f) ? (i = 0) : (errno = GetLastError()))
1911 #define LK_LEN 0xffff0000
1914 win32_flock(int fd, int oper)
1922 Perl_croak_nocontext("flock() unimplemented on this platform");
1925 fh = (HANDLE)_get_osfhandle(fd);
1926 memset(&o, 0, sizeof(o));
1929 case LOCK_SH: /* shared lock */
1930 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
1932 case LOCK_EX: /* exclusive lock */
1933 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
1935 case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
1936 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
1938 case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
1939 LK_ERR(LockFileEx(fh,
1940 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
1941 0, LK_LEN, 0, &o),i);
1943 case LOCK_UN: /* unlock lock */
1944 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, 0, &o),i);
1946 default: /* unknown */
1957 * redirected io subsystem for all XS modules
1970 return (&(_environ));
1973 /* the rest are the remapped stdio routines */
1993 win32_ferror(FILE *fp)
1995 return (ferror(fp));
2000 win32_feof(FILE *fp)
2006 * Since the errors returned by the socket error function
2007 * WSAGetLastError() are not known by the library routine strerror
2008 * we have to roll our own.
2012 win32_strerror(int e)
2014 #ifndef __BORLANDC__ /* Borland intolerance */
2015 extern int sys_nerr;
2019 if (e < 0 || e > sys_nerr) {
2024 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
2025 w32_strerror_buffer,
2026 sizeof(w32_strerror_buffer), NULL) == 0)
2027 strcpy(w32_strerror_buffer, "Unknown Error");
2029 return w32_strerror_buffer;
2035 win32_str_os_error(void *sv, DWORD dwErr)
2039 dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
2040 |FORMAT_MESSAGE_IGNORE_INSERTS
2041 |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
2042 dwErr, 0, (char *)&sMsg, 1, NULL);
2043 /* strip trailing whitespace and period */
2046 --dwLen; /* dwLen doesn't include trailing null */
2047 } while (0 < dwLen && isSPACE(sMsg[dwLen]));
2048 if ('.' != sMsg[dwLen])
2053 sMsg = (char*)LocalAlloc(0, 64/**sizeof(TCHAR)*/);
2055 dwLen = sprintf(sMsg,
2056 "Unknown error #0x%lX (lookup 0x%lX)",
2057 dwErr, GetLastError());
2061 sv_setpvn((SV*)sv, sMsg, dwLen);
2068 win32_fprintf(FILE *fp, const char *format, ...)
2071 va_start(marker, format); /* Initialize variable arguments. */
2073 return (vfprintf(fp, format, marker));
2077 win32_printf(const char *format, ...)
2080 va_start(marker, format); /* Initialize variable arguments. */
2082 return (vprintf(format, marker));
2086 win32_vfprintf(FILE *fp, const char *format, va_list args)
2088 return (vfprintf(fp, format, args));
2092 win32_vprintf(const char *format, va_list args)
2094 return (vprintf(format, args));
2098 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
2100 return fread(buf, size, count, fp);
2104 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
2106 return fwrite(buf, size, count, fp);
2109 #define MODE_SIZE 10
2112 win32_fopen(const char *filename, const char *mode)
2115 WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH+1];
2121 if (stricmp(filename, "/dev/null")==0)
2125 A2WHELPER(mode, wMode, sizeof(wMode));
2126 A2WHELPER(filename, wBuffer, sizeof(wBuffer));
2127 f = _wfopen(PerlDir_mapW(wBuffer), wMode);
2130 f = fopen(PerlDir_mapA(filename), mode);
2131 /* avoid buffering headaches for child processes */
2132 if (f && *mode == 'a')
2133 win32_fseek(f, 0, SEEK_END);
2137 #ifndef USE_SOCKETS_AS_HANDLES
2139 #define fdopen my_fdopen
2143 win32_fdopen(int handle, const char *mode)
2146 WCHAR wMode[MODE_SIZE];
2149 A2WHELPER(mode, wMode, sizeof(wMode));
2150 f = _wfdopen(handle, wMode);
2153 f = fdopen(handle, (char *) mode);
2154 /* avoid buffering headaches for child processes */
2155 if (f && *mode == 'a')
2156 win32_fseek(f, 0, SEEK_END);
2161 win32_freopen(const char *path, const char *mode, FILE *stream)
2164 WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH+1];
2165 if (stricmp(path, "/dev/null")==0)
2169 A2WHELPER(mode, wMode, sizeof(wMode));
2170 A2WHELPER(path, wBuffer, sizeof(wBuffer));
2171 return _wfreopen(PerlDir_mapW(wBuffer), wMode, stream);
2173 return freopen(PerlDir_mapA(path), mode, stream);
2177 win32_fclose(FILE *pf)
2179 return my_fclose(pf); /* defined in win32sck.c */
2183 win32_fputs(const char *s,FILE *pf)
2185 return fputs(s, pf);
2189 win32_fputc(int c,FILE *pf)
2195 win32_ungetc(int c,FILE *pf)
2197 return ungetc(c,pf);
2201 win32_getc(FILE *pf)
2207 win32_fileno(FILE *pf)
2213 win32_clearerr(FILE *pf)
2220 win32_fflush(FILE *pf)
2226 win32_ftell(FILE *pf)
2232 win32_fseek(FILE *pf,long offset,int origin)
2234 return fseek(pf, offset, origin);
2238 win32_fgetpos(FILE *pf,fpos_t *p)
2240 return fgetpos(pf, p);
2244 win32_fsetpos(FILE *pf,const fpos_t *p)
2246 return fsetpos(pf, p);
2250 win32_rewind(FILE *pf)
2270 win32_fstat(int fd,struct stat *sbufptr)
2272 return fstat(fd,sbufptr);
2276 win32_pipe(int *pfd, unsigned int size, int mode)
2278 return _pipe(pfd, size, mode);
2282 * a popen() clone that respects PERL5SHELL
2286 win32_popen(const char *command, const char *mode)
2288 #ifdef USE_RTL_POPEN
2289 return _popen(command, mode);
2297 /* establish which ends read and write */
2298 if (strchr(mode,'w')) {
2299 stdfd = 0; /* stdin */
2303 else if (strchr(mode,'r')) {
2304 stdfd = 1; /* stdout */
2311 /* set the correct mode */
2312 if (strchr(mode,'b'))
2314 else if (strchr(mode,'t'))
2317 ourmode = _fmode & (O_TEXT | O_BINARY);
2319 /* the child doesn't inherit handles */
2320 ourmode |= O_NOINHERIT;
2322 if (win32_pipe( p, 512, ourmode) == -1)
2325 /* save current stdfd */
2326 if ((oldfd = win32_dup(stdfd)) == -1)
2329 /* make stdfd go to child end of pipe (implicitly closes stdfd) */
2330 /* stdfd will be inherited by the child */
2331 if (win32_dup2(p[child], stdfd) == -1)
2334 /* close the child end in parent */
2335 win32_close(p[child]);
2337 /* start the child */
2340 if ((childpid = do_spawn_nowait((char*)command)) == -1)
2343 /* revert stdfd to whatever it was before */
2344 if (win32_dup2(oldfd, stdfd) == -1)
2347 /* close saved handle */
2350 sv_setiv(*av_fetch(w32_fdpid, p[parent], TRUE), childpid);
2352 /* set process id so that it can be returned by perl's open() */
2353 PL_forkprocess = childpid;
2356 /* we have an fd, return a file stream */
2357 return (win32_fdopen(p[parent], (char *)mode));
2360 /* we don't need to check for errors here */
2364 win32_dup2(oldfd, stdfd);
2369 #endif /* USE_RTL_POPEN */
2377 win32_pclose(FILE *pf)
2379 #ifdef USE_RTL_POPEN
2383 int childpid, status;
2386 sv = *av_fetch(w32_fdpid, win32_fileno(pf), TRUE);
2388 childpid = SvIVX(sv);
2400 if (win32_waitpid(childpid, &status, 0) == -1)
2405 #endif /* USE_RTL_POPEN */
2411 LPCWSTR lpExistingFileName,
2412 LPSECURITY_ATTRIBUTES lpSecurityAttributes)
2415 WCHAR wFullName[MAX_PATH+1];
2416 LPVOID lpContext = NULL;
2417 WIN32_STREAM_ID StreamId;
2418 DWORD dwSize = (char*)&StreamId.cStreamName - (char*)&StreamId;
2423 BOOL (__stdcall *pfnBackupWrite)(HANDLE, LPBYTE, DWORD, LPDWORD,
2424 BOOL, BOOL, LPVOID*) =
2425 (BOOL (__stdcall *)(HANDLE, LPBYTE, DWORD, LPDWORD,
2426 BOOL, BOOL, LPVOID*))
2427 GetProcAddress(GetModuleHandle("kernel32.dll"), "BackupWrite");
2428 if (pfnBackupWrite == NULL)
2431 dwLen = GetFullPathNameW(lpFileName, MAX_PATH, wFullName, NULL);
2434 dwLen = (dwLen+1)*sizeof(WCHAR);
2436 handle = CreateFileW(lpExistingFileName, FILE_WRITE_ATTRIBUTES,
2437 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
2438 NULL, OPEN_EXISTING, 0, NULL);
2439 if (handle == INVALID_HANDLE_VALUE)
2442 StreamId.dwStreamId = BACKUP_LINK;
2443 StreamId.dwStreamAttributes = 0;
2444 StreamId.dwStreamNameSize = 0;
2445 #if defined(__BORLANDC__) || defined(__MINGW32__)
2446 StreamId.Size.u.HighPart = 0;
2447 StreamId.Size.u.LowPart = dwLen;
2449 StreamId.Size.HighPart = 0;
2450 StreamId.Size.LowPart = dwLen;
2453 bSuccess = pfnBackupWrite(handle, (LPBYTE)&StreamId, dwSize, &dwWritten,
2454 FALSE, FALSE, &lpContext);
2456 bSuccess = pfnBackupWrite(handle, (LPBYTE)wFullName, dwLen, &dwWritten,
2457 FALSE, FALSE, &lpContext);
2458 pfnBackupWrite(handle, NULL, 0, &dwWritten, TRUE, FALSE, &lpContext);
2461 CloseHandle(handle);
2466 win32_link(const char *oldname, const char *newname)
2469 BOOL (__stdcall *pfnCreateHardLinkW)(LPCWSTR,LPCWSTR,LPSECURITY_ATTRIBUTES);
2470 WCHAR wOldName[MAX_PATH+1];
2471 WCHAR wNewName[MAX_PATH+1];
2474 Perl_croak(aTHX_ PL_no_func, "link");
2476 pfnCreateHardLinkW =
2477 (BOOL (__stdcall *)(LPCWSTR, LPCWSTR, LPSECURITY_ATTRIBUTES))
2478 GetProcAddress(GetModuleHandle("kernel32.dll"), "CreateHardLinkW");
2479 if (pfnCreateHardLinkW == NULL)
2480 pfnCreateHardLinkW = Nt4CreateHardLinkW;
2482 if ((A2WHELPER(oldname, wOldName, sizeof(wOldName))) &&
2483 (A2WHELPER(newname, wNewName, sizeof(wNewName))) &&
2484 (wcscpy(wOldName, PerlDir_mapW(wOldName)),
2485 pfnCreateHardLinkW(PerlDir_mapW(wNewName), wOldName, NULL)))
2489 errno = (GetLastError() == ERROR_FILE_NOT_FOUND) ? ENOENT : EINVAL;
2494 win32_rename(const char *oname, const char *newname)
2496 WCHAR wOldName[MAX_PATH+1];
2497 WCHAR wNewName[MAX_PATH+1];
2498 char szOldName[MAX_PATH+1];
2499 char szNewName[MAX_PATH+1];
2503 /* XXX despite what the documentation says about MoveFileEx(),
2504 * it doesn't work under Windows95!
2507 DWORD dwFlags = MOVEFILE_COPY_ALLOWED;
2509 A2WHELPER(oname, wOldName, sizeof(wOldName));
2510 A2WHELPER(newname, wNewName, sizeof(wNewName));
2511 if (wcsicmp(wNewName, wOldName))
2512 dwFlags |= MOVEFILE_REPLACE_EXISTING;
2513 wcscpy(wOldName, PerlDir_mapW(wOldName));
2514 bResult = MoveFileExW(wOldName,PerlDir_mapW(wNewName), dwFlags);
2517 if (stricmp(newname, oname))
2518 dwFlags |= MOVEFILE_REPLACE_EXISTING;
2519 strcpy(szOldName, PerlDir_mapA(oname));
2520 bResult = MoveFileExA(szOldName,PerlDir_mapA(newname), dwFlags);
2523 DWORD err = GetLastError();
2525 case ERROR_BAD_NET_NAME:
2526 case ERROR_BAD_NETPATH:
2527 case ERROR_BAD_PATHNAME:
2528 case ERROR_FILE_NOT_FOUND:
2529 case ERROR_FILENAME_EXCED_RANGE:
2530 case ERROR_INVALID_DRIVE:
2531 case ERROR_NO_MORE_FILES:
2532 case ERROR_PATH_NOT_FOUND:
2545 char szTmpName[MAX_PATH+1];
2546 char dname[MAX_PATH+1];
2547 char *endname = Nullch;
2549 DWORD from_attr, to_attr;
2551 strcpy(szOldName, PerlDir_mapA(oname));
2552 strcpy(szNewName, PerlDir_mapA(newname));
2554 /* if oname doesn't exist, do nothing */
2555 from_attr = GetFileAttributes(szOldName);
2556 if (from_attr == 0xFFFFFFFF) {
2561 /* if newname exists, rename it to a temporary name so that we
2562 * don't delete it in case oname happens to be the same file
2563 * (but perhaps accessed via a different path)
2565 to_attr = GetFileAttributes(szNewName);
2566 if (to_attr != 0xFFFFFFFF) {
2567 /* if newname is a directory, we fail
2568 * XXX could overcome this with yet more convoluted logic */
2569 if (to_attr & FILE_ATTRIBUTE_DIRECTORY) {
2573 tmplen = strlen(szNewName);
2574 strcpy(szTmpName,szNewName);
2575 endname = szTmpName+tmplen;
2576 for (; endname > szTmpName ; --endname) {
2577 if (*endname == '/' || *endname == '\\') {
2582 if (endname > szTmpName)
2583 endname = strcpy(dname,szTmpName);
2587 /* get a temporary filename in same directory
2588 * XXX is this really the best we can do? */
2589 if (!GetTempFileName((LPCTSTR)endname, "plr", 0, szTmpName)) {
2593 DeleteFile(szTmpName);
2595 retval = rename(szNewName, szTmpName);
2602 /* rename oname to newname */
2603 retval = rename(szOldName, szNewName);
2605 /* if we created a temporary file before ... */
2606 if (endname != Nullch) {
2607 /* ...and rename succeeded, delete temporary file/directory */
2609 DeleteFile(szTmpName);
2610 /* else restore it to what it was */
2612 (void)rename(szTmpName, szNewName);
2619 win32_setmode(int fd, int mode)
2621 return setmode(fd, mode);
2625 win32_lseek(int fd, long offset, int origin)
2627 return lseek(fd, offset, origin);
2637 win32_open(const char *path, int flag, ...)
2642 WCHAR wBuffer[MAX_PATH+1];
2645 pmode = va_arg(ap, int);
2648 if (stricmp(path, "/dev/null")==0)
2652 A2WHELPER(path, wBuffer, sizeof(wBuffer));
2653 return _wopen(PerlDir_mapW(wBuffer), flag, pmode);
2655 return open(PerlDir_mapA(path), flag, pmode);
2677 win32_dup2(int fd1,int fd2)
2679 return dup2(fd1,fd2);
2682 #ifdef PERL_MSVCRT_READFIX
2684 #define LF 10 /* line feed */
2685 #define CR 13 /* carriage return */
2686 #define CTRLZ 26 /* ctrl-z means eof for text */
2687 #define FOPEN 0x01 /* file handle open */
2688 #define FEOFLAG 0x02 /* end of file has been encountered */
2689 #define FCRLF 0x04 /* CR-LF across read buffer (in text mode) */
2690 #define FPIPE 0x08 /* file handle refers to a pipe */
2691 #define FAPPEND 0x20 /* file handle opened O_APPEND */
2692 #define FDEV 0x40 /* file handle refers to device */
2693 #define FTEXT 0x80 /* file handle is in text mode */
2694 #define MAX_DESCRIPTOR_COUNT (64*32) /* this is the maximun that MSVCRT can handle */
2697 _fixed_read(int fh, void *buf, unsigned cnt)
2699 int bytes_read; /* number of bytes read */
2700 char *buffer; /* buffer to read to */
2701 int os_read; /* bytes read on OS call */
2702 char *p, *q; /* pointers into buffer */
2703 char peekchr; /* peek-ahead character */
2704 ULONG filepos; /* file position after seek */
2705 ULONG dosretval; /* o.s. return value */
2707 /* validate handle */
2708 if (((unsigned)fh >= (unsigned)MAX_DESCRIPTOR_COUNT) ||
2709 !(_osfile(fh) & FOPEN))
2711 /* out of range -- return error */
2713 _doserrno = 0; /* not o.s. error */
2718 * If lockinitflag is FALSE, assume fd is device
2719 * lockinitflag is set to TRUE by open.
2721 if (_pioinfo(fh)->lockinitflag)
2722 EnterCriticalSection(&(_pioinfo(fh)->lock)); /* lock file */
2724 bytes_read = 0; /* nothing read yet */
2725 buffer = (char*)buf;
2727 if (cnt == 0 || (_osfile(fh) & FEOFLAG)) {
2728 /* nothing to read or at EOF, so return 0 read */
2732 if ((_osfile(fh) & (FPIPE|FDEV)) && _pipech(fh) != LF) {
2733 /* a pipe/device and pipe lookahead non-empty: read the lookahead
2735 *buffer++ = _pipech(fh);
2738 _pipech(fh) = LF; /* mark as empty */
2743 if (!ReadFile((HANDLE)_osfhnd(fh), buffer, cnt, (LPDWORD)&os_read, NULL))
2745 /* ReadFile has reported an error. recognize two special cases.
2747 * 1. map ERROR_ACCESS_DENIED to EBADF
2749 * 2. just return 0 if ERROR_BROKEN_PIPE has occurred. it
2750 * means the handle is a read-handle on a pipe for which
2751 * all write-handles have been closed and all data has been
2754 if ((dosretval = GetLastError()) == ERROR_ACCESS_DENIED) {
2755 /* wrong read/write mode should return EBADF, not EACCES */
2757 _doserrno = dosretval;
2761 else if (dosretval == ERROR_BROKEN_PIPE) {
2771 bytes_read += os_read; /* update bytes read */
2773 if (_osfile(fh) & FTEXT) {
2774 /* now must translate CR-LFs to LFs in the buffer */
2776 /* set CRLF flag to indicate LF at beginning of buffer */
2777 /* if ((os_read != 0) && (*(char *)buf == LF)) */
2778 /* _osfile(fh) |= FCRLF; */
2780 /* _osfile(fh) &= ~FCRLF; */
2782 _osfile(fh) &= ~FCRLF;
2784 /* convert chars in the buffer: p is src, q is dest */
2786 while (p < (char *)buf + bytes_read) {
2788 /* if fh is not a device, set ctrl-z flag */
2789 if (!(_osfile(fh) & FDEV))
2790 _osfile(fh) |= FEOFLAG;
2791 break; /* stop translating */
2796 /* *p is CR, so must check next char for LF */
2797 if (p < (char *)buf + bytes_read - 1) {
2800 *q++ = LF; /* convert CR-LF to LF */
2803 *q++ = *p++; /* store char normally */
2806 /* This is the hard part. We found a CR at end of
2807 buffer. We must peek ahead to see if next char
2812 if (!ReadFile((HANDLE)_osfhnd(fh), &peekchr, 1,
2813 (LPDWORD)&os_read, NULL))
2814 dosretval = GetLastError();
2816 if (dosretval != 0 || os_read == 0) {
2817 /* couldn't read ahead, store CR */
2821 /* peekchr now has the extra character -- we now
2822 have several possibilities:
2823 1. disk file and char is not LF; just seek back
2825 2. disk file and char is LF; store LF, don't seek back
2826 3. pipe/device and char is LF; store LF.
2827 4. pipe/device and char isn't LF, store CR and
2828 put char in pipe lookahead buffer. */
2829 if (_osfile(fh) & (FDEV|FPIPE)) {
2830 /* non-seekable device */
2835 _pipech(fh) = peekchr;
2840 if (peekchr == LF) {
2841 /* nothing read yet; must make some
2844 /* turn on this flag for tell routine */
2845 _osfile(fh) |= FCRLF;
2848 HANDLE osHandle; /* o.s. handle value */
2850 if ((osHandle = (HANDLE)_get_osfhandle(fh)) != (HANDLE)-1)
2852 if ((filepos = SetFilePointer(osHandle, -1, NULL, FILE_CURRENT)) == -1)
2853 dosretval = GetLastError();
2864 /* we now change bytes_read to reflect the true number of chars
2866 bytes_read = q - (char *)buf;
2870 if (_pioinfo(fh)->lockinitflag)
2871 LeaveCriticalSection(&(_pioinfo(fh)->lock)); /* unlock file */
2876 #endif /* PERL_MSVCRT_READFIX */
2879 win32_read(int fd, void *buf, unsigned int cnt)
2881 #ifdef PERL_MSVCRT_READFIX
2882 return _fixed_read(fd, buf, cnt);
2884 return read(fd, buf, cnt);
2889 win32_write(int fd, const void *buf, unsigned int cnt)
2891 return write(fd, buf, cnt);
2895 win32_mkdir(const char *dir, int mode)
2899 WCHAR wBuffer[MAX_PATH+1];
2900 A2WHELPER(dir, wBuffer, sizeof(wBuffer));
2901 return _wmkdir(PerlDir_mapW(wBuffer));
2903 return mkdir(PerlDir_mapA(dir)); /* just ignore mode */
2907 win32_rmdir(const char *dir)
2911 WCHAR wBuffer[MAX_PATH+1];
2912 A2WHELPER(dir, wBuffer, sizeof(wBuffer));
2913 return _wrmdir(PerlDir_mapW(wBuffer));
2915 return rmdir(PerlDir_mapA(dir));
2919 win32_chdir(const char *dir)
2923 WCHAR wBuffer[MAX_PATH+1];
2924 A2WHELPER(dir, wBuffer, sizeof(wBuffer));
2925 return _wchdir(wBuffer);
2931 win32_access(const char *path, int mode)
2935 WCHAR wBuffer[MAX_PATH+1];
2936 A2WHELPER(path, wBuffer, sizeof(wBuffer));
2937 return _waccess(PerlDir_mapW(wBuffer), mode);
2939 return access(PerlDir_mapA(path), mode);
2943 win32_chmod(const char *path, int mode)
2947 WCHAR wBuffer[MAX_PATH+1];
2948 A2WHELPER(path, wBuffer, sizeof(wBuffer));
2949 return _wchmod(PerlDir_mapW(wBuffer), mode);
2951 return chmod(PerlDir_mapA(path), mode);
2956 create_command_line(const char* command, const char * const *args)
2960 char *cmd, *ptr, *arg;
2961 STRLEN len = strlen(command) + 1;
2963 for (index = 0; (ptr = (char*)args[index]) != NULL; ++index)
2964 len += strlen(ptr) + 1;
2966 New(1310, cmd, len, char);
2968 strcpy(ptr, command);
2970 for (index = 0; (arg = (char*)args[index]) != NULL; ++index) {
2980 qualified_path(const char *cmd)
2984 char *fullcmd, *curfullcmd;
2990 fullcmd = (char*)cmd;
2992 if (*fullcmd == '/' || *fullcmd == '\\')
2999 pathstr = win32_getenv("PATH");
3000 New(0, fullcmd, MAX_PATH+1, char);
3001 curfullcmd = fullcmd;
3006 /* start by appending the name to the current prefix */
3007 strcpy(curfullcmd, cmd);
3008 curfullcmd += cmdlen;
3010 /* if it doesn't end with '.', or has no extension, try adding
3011 * a trailing .exe first */
3012 if (cmd[cmdlen-1] != '.'
3013 && (cmdlen < 4 || cmd[cmdlen-4] != '.'))
3015 strcpy(curfullcmd, ".exe");
3016 res = GetFileAttributes(fullcmd);
3017 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
3022 /* that failed, try the bare name */
3023 res = GetFileAttributes(fullcmd);
3024 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
3027 /* quit if no other path exists, or if cmd already has path */
3028 if (!pathstr || !*pathstr || has_slash)
3031 /* skip leading semis */
3032 while (*pathstr == ';')
3035 /* build a new prefix from scratch */
3036 curfullcmd = fullcmd;
3037 while (*pathstr && *pathstr != ';') {
3038 if (*pathstr == '"') { /* foo;"baz;etc";bar */
3039 pathstr++; /* skip initial '"' */
3040 while (*pathstr && *pathstr != '"') {
3041 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
3042 *curfullcmd++ = *pathstr;
3046 pathstr++; /* skip trailing '"' */
3049 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
3050 *curfullcmd++ = *pathstr;
3055 pathstr++; /* skip trailing semi */
3056 if (curfullcmd > fullcmd /* append a dir separator */
3057 && curfullcmd[-1] != '/' && curfullcmd[-1] != '\\')
3059 *curfullcmd++ = '\\';
3067 /* The following are just place holders.
3068 * Some hosts may provide and environment that the OS is
3069 * not tracking, therefore, these host must provide that
3070 * environment and the current directory to CreateProcess
3080 free_childenv(void* d)
3089 char szfilename[(MAX_PATH+1)*2];
3091 WCHAR wfilename[MAX_PATH+1];
3092 GetCurrentDirectoryW(MAX_PATH+1, wfilename);
3093 W2AHELPER(wfilename, szfilename, sizeof(szfilename));
3096 GetCurrentDirectoryA(MAX_PATH+1, szfilename);
3099 New(0, ptr, strlen(szfilename)+1, char);
3100 strcpy(ptr, szfilename);
3105 free_childdir(char* d)
3112 /* XXX this needs to be made more compatible with the spawnvp()
3113 * provided by the various RTLs. In particular, searching for
3114 * *.{com,bat,cmd} files (as done by the RTLs) is unimplemented.
3115 * This doesn't significantly affect perl itself, because we
3116 * always invoke things using PERL5SHELL if a direct attempt to
3117 * spawn the executable fails.
3119 * XXX splitting and rejoining the commandline between do_aspawn()
3120 * and win32_spawnvp() could also be avoided.
3124 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
3126 #ifdef USE_RTL_SPAWNVP
3127 return spawnvp(mode, cmdname, (char * const *)argv);
3134 STARTUPINFO StartupInfo;
3135 PROCESS_INFORMATION ProcessInformation;
3138 char *cmd = create_command_line(cmdname, strcmp(cmdname, argv[0]) == 0
3140 char *fullcmd = Nullch;
3142 env = PerlEnv_get_childenv();
3143 dir = PerlEnv_get_childdir();
3146 case P_NOWAIT: /* asynch + remember result */
3147 if (w32_num_children >= MAXIMUM_WAIT_OBJECTS) {
3153 case P_WAIT: /* synchronous execution */
3155 default: /* invalid mode */
3160 memset(&StartupInfo,0,sizeof(StartupInfo));
3161 StartupInfo.cb = sizeof(StartupInfo);
3162 PerlEnv_get_child_IO(&tbl);
3163 StartupInfo.hStdInput = tbl.childStdIn;
3164 StartupInfo.hStdOutput = tbl.childStdOut;
3165 StartupInfo.hStdError = tbl.childStdErr;
3166 if (StartupInfo.hStdInput != INVALID_HANDLE_VALUE &&
3167 StartupInfo.hStdOutput != INVALID_HANDLE_VALUE &&
3168 StartupInfo.hStdError != INVALID_HANDLE_VALUE)
3170 StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
3173 create |= CREATE_NEW_CONSOLE;
3177 if (!CreateProcess(cmdname, /* search PATH to find executable */
3178 cmd, /* executable, and its arguments */
3179 NULL, /* process attributes */
3180 NULL, /* thread attributes */
3181 TRUE, /* inherit handles */
3182 create, /* creation flags */
3183 (LPVOID)env, /* inherit environment */
3184 dir, /* inherit cwd */
3186 &ProcessInformation))
3188 /* initial NULL argument to CreateProcess() does a PATH
3189 * search, but it always first looks in the directory
3190 * where the current process was started, which behavior
3191 * is undesirable for backward compatibility. So we
3192 * jump through our own hoops by picking out the path
3193 * we really want it to use. */
3195 fullcmd = qualified_path(cmdname);
3206 if (mode == P_NOWAIT) {
3207 /* asynchronous spawn -- store handle, return PID */
3208 w32_child_handles[w32_num_children] = ProcessInformation.hProcess;
3209 w32_child_pids[w32_num_children] = ProcessInformation.dwProcessId;
3210 ret = (int)ProcessInformation.dwProcessId;
3215 WaitForSingleObject(ProcessInformation.hProcess, INFINITE);
3216 GetExitCodeProcess(ProcessInformation.hProcess, &status);
3218 CloseHandle(ProcessInformation.hProcess);
3221 CloseHandle(ProcessInformation.hThread);
3224 PerlEnv_free_childenv(env);
3225 PerlEnv_free_childdir(dir);
3233 win32_execv(const char *cmdname, const char *const *argv)
3237 /* if this is a pseudo-forked child, we just want to spawn
3238 * the new program, and return */
3240 return spawnv(P_WAIT, cmdname, (char *const *)argv);
3242 return execv(cmdname, (char *const *)argv);
3246 win32_execvp(const char *cmdname, const char *const *argv)
3250 /* if this is a pseudo-forked child, we just want to spawn
3251 * the new program, and return */
3253 return win32_spawnvp(P_WAIT, cmdname, (char *const *)argv);
3255 return execvp(cmdname, (char *const *)argv);
3259 win32_perror(const char *str)
3265 win32_setbuf(FILE *pf, char *buf)
3271 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
3273 return setvbuf(pf, buf, type, size);
3277 win32_flushall(void)
3283 win32_fcloseall(void)
3289 win32_fgets(char *s, int n, FILE *pf)
3291 return fgets(s, n, pf);
3301 win32_fgetc(FILE *pf)
3307 win32_putc(int c, FILE *pf)
3313 win32_puts(const char *s)
3325 win32_putchar(int c)
3332 #ifndef USE_PERL_SBRK
3334 static char *committed = NULL;
3335 static char *base = NULL;
3336 static char *reserved = NULL;
3337 static char *brk = NULL;
3338 static DWORD pagesize = 0;
3339 static DWORD allocsize = 0;
3347 GetSystemInfo(&info);
3348 /* Pretend page size is larger so we don't perpetually
3349 * call the OS to commit just one page ...
3351 pagesize = info.dwPageSize << 3;
3352 allocsize = info.dwAllocationGranularity;
3354 /* This scheme fails eventually if request for contiguous
3355 * block is denied so reserve big blocks - this is only
3356 * address space not memory ...
3358 if (brk+need >= reserved)
3360 DWORD size = 64*1024*1024;
3362 if (committed && reserved && committed < reserved)
3364 /* Commit last of previous chunk cannot span allocations */
3365 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
3367 committed = reserved;
3369 /* Reserve some (more) space
3370 * Note this is a little sneaky, 1st call passes NULL as reserved
3371 * so lets system choose where we start, subsequent calls pass
3372 * the old end address so ask for a contiguous block
3374 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
3377 reserved = addr+size;
3392 if (brk > committed)
3394 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
3395 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
3410 win32_malloc(size_t size)
3412 return malloc(size);
3416 win32_calloc(size_t numitems, size_t size)
3418 return calloc(numitems,size);
3422 win32_realloc(void *block, size_t size)
3424 return realloc(block,size);
3428 win32_free(void *block)
3435 win32_open_osfhandle(long handle, int flags)
3437 #ifdef USE_FIXED_OSFHANDLE
3439 return my_open_osfhandle(handle, flags);
3441 return _open_osfhandle(handle, flags);
3445 win32_get_osfhandle(int fd)
3447 return _get_osfhandle(fd);
3451 win32_dynaload(const char* filename)
3456 WCHAR wfilename[MAX_PATH+1];
3457 A2WHELPER(filename, wfilename, sizeof(wfilename));
3458 hModule = LoadLibraryExW(PerlDir_mapW(wfilename), NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
3461 hModule = LoadLibraryExA(PerlDir_mapA(filename), NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
3474 /* Make the host for current directory */
3475 char* ptr = PerlEnv_get_childdir();
3478 * then it worked, set PV valid,
3479 * else return 'undef'
3482 SV *sv = sv_newmortal();
3484 PerlEnv_free_childdir(ptr);
3499 Perl_croak(aTHX_ "usage: Win32::SetCurrentDirectory($cwd)");
3500 if (!PerlDir_chdir(SvPV_nolen(ST(0))))
3507 XS(w32_GetNextAvailDrive)
3511 char root[] = "_:\\";
3516 if (GetDriveType(root) == 1) {
3525 XS(w32_GetLastError)
3529 XSRETURN_IV(GetLastError());
3533 XS(w32_SetLastError)
3537 Perl_croak(aTHX_ "usage: Win32::SetLastError($error)");
3538 SetLastError(SvIV(ST(0)));
3546 char *name = w32_getlogin_buffer;
3547 DWORD size = sizeof(w32_getlogin_buffer);
3549 if (GetUserName(name,&size)) {
3550 /* size includes NULL */
3551 ST(0) = sv_2mortal(newSVpvn(name,size-1));
3561 char name[MAX_COMPUTERNAME_LENGTH+1];
3562 DWORD size = sizeof(name);
3564 if (GetComputerName(name,&size)) {
3565 /* size does NOT include NULL :-( */
3566 ST(0) = sv_2mortal(newSVpvn(name,size));
3577 HINSTANCE hNetApi32 = LoadLibrary("netapi32.dll");
3578 DWORD (__stdcall *pfnNetApiBufferFree)(LPVOID Buffer);
3579 DWORD (__stdcall *pfnNetWkstaGetInfo)(LPWSTR servername, DWORD level,
3583 pfnNetApiBufferFree = (DWORD (__stdcall *)(void *))
3584 GetProcAddress(hNetApi32, "NetApiBufferFree");
3585 pfnNetWkstaGetInfo = (DWORD (__stdcall *)(LPWSTR, DWORD, void *))
3586 GetProcAddress(hNetApi32, "NetWkstaGetInfo");
3589 if (hNetApi32 && pfnNetWkstaGetInfo && pfnNetApiBufferFree) {
3590 /* this way is more reliable, in case user has a local account. */
3592 DWORD dnamelen = sizeof(dname);
3594 DWORD wki100_platform_id;
3595 LPWSTR wki100_computername;
3596 LPWSTR wki100_langroup;
3597 DWORD wki100_ver_major;
3598 DWORD wki100_ver_minor;
3600 /* NERR_Success *is* 0*/
3601 if (0 == pfnNetWkstaGetInfo(NULL, 100, &pwi)) {
3602 if (pwi->wki100_langroup && *(pwi->wki100_langroup)) {
3603 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_langroup,
3604 -1, (LPSTR)dname, dnamelen, NULL, NULL);
3607 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_computername,
3608 -1, (LPSTR)dname, dnamelen, NULL, NULL);
3610 pfnNetApiBufferFree(pwi);
3611 FreeLibrary(hNetApi32);
3614 FreeLibrary(hNetApi32);
3617 /* Win95 doesn't have NetWksta*(), so do it the old way */
3619 DWORD size = sizeof(name);
3621 FreeLibrary(hNetApi32);
3622 if (GetUserName(name,&size)) {
3623 char sid[ONE_K_BUFSIZE];
3624 DWORD sidlen = sizeof(sid);
3626 DWORD dnamelen = sizeof(dname);
3628 if (LookupAccountName(NULL, name, (PSID)&sid, &sidlen,
3629 dname, &dnamelen, &snu)) {
3630 XSRETURN_PV(dname); /* all that for this */
3642 DWORD flags, filecomplen;
3643 if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
3644 &flags, fsname, sizeof(fsname))) {
3645 if (GIMME_V == G_ARRAY) {
3646 XPUSHs(sv_2mortal(newSVpvn(fsname,strlen(fsname))));
3647 XPUSHs(sv_2mortal(newSViv(flags)));
3648 XPUSHs(sv_2mortal(newSViv(filecomplen)));
3653 XSRETURN_PV(fsname);
3659 XS(w32_GetOSVersion)
3662 OSVERSIONINFOA osver;
3665 OSVERSIONINFOW osverw;
3666 char szCSDVersion[sizeof(osverw.szCSDVersion)];
3667 osverw.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
3668 if (!GetVersionExW(&osverw)) {
3671 W2AHELPER(osverw.szCSDVersion, szCSDVersion, sizeof(szCSDVersion));
3672 XPUSHs(newSVpvn(szCSDVersion, strlen(szCSDVersion)));
3673 osver.dwMajorVersion = osverw.dwMajorVersion;
3674 osver.dwMinorVersion = osverw.dwMinorVersion;
3675 osver.dwBuildNumber = osverw.dwBuildNumber;
3676 osver.dwPlatformId = osverw.dwPlatformId;
3679 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOA);
3680 if (!GetVersionExA(&osver)) {
3683 XPUSHs(newSVpvn(osver.szCSDVersion, strlen(osver.szCSDVersion)));
3685 XPUSHs(newSViv(osver.dwMajorVersion));
3686 XPUSHs(newSViv(osver.dwMinorVersion));
3687 XPUSHs(newSViv(osver.dwBuildNumber));
3688 XPUSHs(newSViv(osver.dwPlatformId));
3697 XSRETURN_IV(IsWinNT());
3705 XSRETURN_IV(IsWin95());
3709 XS(w32_FormatMessage)
3713 char msgbuf[ONE_K_BUFSIZE];
3716 Perl_croak(aTHX_ "usage: Win32::FormatMessage($errno)");
3719 WCHAR wmsgbuf[ONE_K_BUFSIZE];
3720 if (FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM,
3721 &source, SvIV(ST(0)), 0,
3722 wmsgbuf, ONE_K_BUFSIZE-1, NULL))
3724 W2AHELPER(wmsgbuf, msgbuf, sizeof(msgbuf));
3725 XSRETURN_PV(msgbuf);
3729 if (FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM,
3730 &source, SvIV(ST(0)), 0,
3731 msgbuf, sizeof(msgbuf)-1, NULL))
3732 XSRETURN_PV(msgbuf);
3743 PROCESS_INFORMATION stProcInfo;
3744 STARTUPINFO stStartInfo;
3745 BOOL bSuccess = FALSE;
3748 Perl_croak(aTHX_ "usage: Win32::Spawn($cmdName, $args, $PID)");
3750 cmd = SvPV_nolen(ST(0));
3751 args = SvPV_nolen(ST(1));
3753 memset(&stStartInfo, 0, sizeof(stStartInfo)); /* Clear the block */
3754 stStartInfo.cb = sizeof(stStartInfo); /* Set the structure size */
3755 stStartInfo.dwFlags = STARTF_USESHOWWINDOW; /* Enable wShowWindow control */
3756 stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE; /* Start min (normal) */
3759 cmd, /* Image path */
3760 args, /* Arguments for command line */
3761 NULL, /* Default process security */
3762 NULL, /* Default thread security */
3763 FALSE, /* Must be TRUE to use std handles */
3764 NORMAL_PRIORITY_CLASS, /* No special scheduling */
3765 NULL, /* Inherit our environment block */
3766 NULL, /* Inherit our currrent directory */
3767 &stStartInfo, /* -> Startup info */
3768 &stProcInfo)) /* <- Process info (if OK) */
3770 CloseHandle(stProcInfo.hThread);/* library source code does this. */
3771 sv_setiv(ST(2), stProcInfo.dwProcessId);
3774 XSRETURN_IV(bSuccess);
3778 XS(w32_GetTickCount)
3781 DWORD msec = GetTickCount();
3789 XS(w32_GetShortPathName)
3796 Perl_croak(aTHX_ "usage: Win32::GetShortPathName($longPathName)");
3798 shortpath = sv_mortalcopy(ST(0));
3799 SvUPGRADE(shortpath, SVt_PV);
3800 /* src == target is allowed */
3802 len = GetShortPathName(SvPVX(shortpath),
3805 } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
3807 SvCUR_set(shortpath,len);
3815 XS(w32_GetFullPathName)
3824 Perl_croak(aTHX_ "usage: Win32::GetFullPathName($filename)");
3827 fullpath = sv_mortalcopy(filename);
3828 SvUPGRADE(fullpath, SVt_PV);
3830 len = GetFullPathName(SvPVX(filename),
3834 } while (len >= SvLEN(fullpath) && sv_grow(fullpath,len+1));
3836 if (GIMME_V == G_ARRAY) {
3838 XST_mPV(1,filepart);
3839 len = filepart - SvPVX(fullpath);
3842 SvCUR_set(fullpath,len);
3850 XS(w32_GetLongPathName)
3854 char tmpbuf[MAX_PATH+1];
3859 Perl_croak(aTHX_ "usage: Win32::GetLongPathName($pathname)");
3862 pathstr = SvPV(path,len);
3863 strcpy(tmpbuf, pathstr);
3864 pathstr = win32_longpath(tmpbuf);
3866 ST(0) = sv_2mortal(newSVpvn(pathstr, strlen(pathstr)));
3877 Perl_croak(aTHX_ "usage: Win32::Sleep($milliseconds)");
3888 Perl_croak(aTHX_ "usage: Win32::CopyFile($from, $to, $overwrite)");
3890 WCHAR wSourceFile[MAX_PATH+1];
3891 WCHAR wDestFile[MAX_PATH+1];
3892 A2WHELPER(SvPV_nolen(ST(0)), wSourceFile, sizeof(wSourceFile));
3893 wcscpy(wSourceFile, PerlDir_mapW(wSourceFile));
3894 A2WHELPER(SvPV_nolen(ST(1)), wDestFile, sizeof(wDestFile));
3895 bResult = CopyFileW(wSourceFile, PerlDir_mapW(wDestFile), !SvTRUE(ST(2)));
3898 char szSourceFile[MAX_PATH+1];
3899 strcpy(szSourceFile, PerlDir_mapA(SvPV_nolen(ST(0))));
3900 bResult = CopyFileA(szSourceFile, PerlDir_mapA(SvPV_nolen(ST(1))), !SvTRUE(ST(2)));
3909 Perl_init_os_extras(void)
3912 char *file = __FILE__;
3915 w32_perlshell_tokens = Nullch;
3916 w32_perlshell_items = -1;
3917 w32_fdpid = newAV(); /* XXX needs to be in Perl_win32_init()? */
3918 New(1313, w32_children, 1, child_tab);
3919 w32_num_children = 0;
3920 w32_init_socktype = 0;
3923 New(1313, w32_pseudo_children, 1, child_tab);
3924 w32_num_pseudo_children = 0;
3927 /* these names are Activeware compatible */
3928 newXS("Win32::GetCwd", w32_GetCwd, file);
3929 newXS("Win32::SetCwd", w32_SetCwd, file);
3930 newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
3931 newXS("Win32::GetLastError", w32_GetLastError, file);
3932 newXS("Win32::SetLastError", w32_SetLastError, file);
3933 newXS("Win32::LoginName", w32_LoginName, file);
3934 newXS("Win32::NodeName", w32_NodeName, file);
3935 newXS("Win32::DomainName", w32_DomainName, file);
3936 newXS("Win32::FsType", w32_FsType, file);
3937 newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
3938 newXS("Win32::IsWinNT", w32_IsWinNT, file);
3939 newXS("Win32::IsWin95", w32_IsWin95, file);
3940 newXS("Win32::FormatMessage", w32_FormatMessage, file);
3941 newXS("Win32::Spawn", w32_Spawn, file);
3942 newXS("Win32::GetTickCount", w32_GetTickCount, file);
3943 newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
3944 newXS("Win32::GetFullPathName", w32_GetFullPathName, file);
3945 newXS("Win32::GetLongPathName", w32_GetLongPathName, file);
3946 newXS("Win32::CopyFile", w32_CopyFile, file);
3947 newXS("Win32::Sleep", w32_Sleep, file);
3949 /* XXX Bloat Alert! The following Activeware preloads really
3950 * ought to be part of Win32::Sys::*, so they're not included
3953 /* LookupAccountName
3955 * InitiateSystemShutdown
3956 * AbortSystemShutdown
3957 * ExpandEnvrironmentStrings
3962 Perl_win32_init(int *argcp, char ***argvp)
3964 /* Disable floating point errors, Perl will trap the ones we
3965 * care about. VC++ RTL defaults to switching these off
3966 * already, but the Borland RTL doesn't. Since we don't
3967 * want to be at the vendor's whim on the default, we set
3968 * it explicitly here.
3970 #if !defined(_ALPHA_) && !defined(__GNUC__)
3971 _control87(MCW_EM, MCW_EM);
3977 win32_get_child_IO(child_IO_table* ptbl)
3979 ptbl->childStdIn = GetStdHandle(STD_INPUT_HANDLE);
3980 ptbl->childStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
3981 ptbl->childStdErr = GetStdHandle(STD_ERROR_HANDLE);
3988 # undef Perl_sys_intern_dup
3989 # define Perl_sys_intern_dup CPerlObj::Perl_sys_intern_dup
3994 Perl_sys_intern_dup(pTHX_ struct interp_intern *src, struct interp_intern *dst)
3996 dst->perlshell_tokens = Nullch;
3997 dst->perlshell_vec = (char**)NULL;
3998 dst->perlshell_items = 0;
3999 dst->fdpid = newAV();
4000 Newz(1313, dst->children, 1, child_tab);
4001 Newz(1313, dst->pseudo_children, 1, child_tab);
4003 dst->children->num = 0;
4004 dst->thr_intern.Winit_socktype = src->thr_intern.Winit_socktype;
4014 win32_free_argvw(pTHXo_ void *ptr)
4016 char** argv = (char**)ptr;
4024 win32_argv2utf8(int argc, char** argv)
4029 LPWSTR* lpwStr = CommandLineToArgvW(GetCommandLineW(), &wargc);
4030 if (lpwStr && argc) {
4032 length = WideCharToMultiByte(CP_UTF8, 0, lpwStr[--wargc], -1, NULL, 0, NULL, NULL);
4033 Newz(0, psz, length, char);
4034 WideCharToMultiByte(CP_UTF8, 0, lpwStr[wargc], -1, psz, length, NULL, NULL);
4037 call_atexit(win32_free_argvw, argv);
4039 GlobalFree((HGLOBAL)lpwStr);