3 * (c) 1995 Microsoft Corporation. All rights reserved.
4 * Developed by hip communications inc., http://info.hip.com/info/
5 * Portions (c) 1993 Intergraph Corporation. All rights reserved.
7 * You may distribute under the terms of either the GNU General Public
8 * License or the Artistic License, as specified in the README file.
11 #define WIN32_LEAN_AND_MEAN
12 #define WIN32IO_IS_STDIO
18 #ifndef __MINGW32__ /* GCC/Mingw32-2.95.2 forgot the WINAPI on CommandLineToArgvW() */
19 # include <shellapi.h>
21 LPWSTR* WINAPI CommandLineToArgvW(LPCWSTR lpCommandLine, int * pNumArgs);
26 /* #include "config.h" */
28 #define PERLIO_NOT_STDIO 0
29 #if !defined(PERLIO_IS_STDIO) && !defined(USE_SFIO)
38 #define PERL_NO_GET_CONTEXT
44 /* assert.h conflicts with #define of assert in perl.h */
51 #if defined(_MSC_VER) || defined(__MINGW32__)
52 #include <sys/utime.h>
58 /* Mingw32 defaults to globing command line
59 * So we turn it off like this:
64 #if defined(__MINGW32__)
65 /* Mingw32 is missing some prototypes */
66 FILE * _wfopen(LPCWSTR wszFileName, LPCWSTR wszMode);
67 FILE * _wfdopen(int nFd, LPCWSTR wszMode);
68 FILE * _freopen(LPCWSTR wszFileName, LPCWSTR wszMode, FILE * pOldStream);
73 #if defined(__BORLANDC__)
75 # define _utimbuf utimbuf
80 #define EXECF_SPAWN_NOWAIT 3
82 #if defined(PERL_IMPLICIT_SYS)
83 # undef win32_get_privlib
84 # define win32_get_privlib g_win32_get_privlib
85 # undef win32_get_sitelib
86 # define win32_get_sitelib g_win32_get_sitelib
87 # undef win32_get_vendorlib
88 # define win32_get_vendorlib g_win32_get_vendorlib
90 # define do_spawn g_do_spawn
92 # define getlogin g_getlogin
95 #if defined(PERL_OBJECT)
97 # define do_aspawn g_do_aspawn
99 # define Perl_do_exec g_do_exec
102 static void get_shell(void);
103 static long tokenize(const char *str, char **dest, char ***destv);
104 int do_spawn2(char *cmd, int exectype);
105 static BOOL has_shell_metachars(char *ptr);
106 static long filetime_to_clock(PFILETIME ft);
107 static BOOL filetime_from_time(PFILETIME ft, time_t t);
108 static char * get_emd_part(SV **leading, char *trailing, ...);
109 static void remove_dead_process(long deceased);
110 static long find_pid(int pid);
111 static char * qualified_path(const char *cmd);
112 static char * win32_get_xlib(const char *pl, const char *xlib,
113 const char *libname);
116 static void remove_dead_pseudo_process(long child);
117 static long find_pseudo_pid(int pid);
121 HANDLE w32_perldll_handle = INVALID_HANDLE_VALUE;
122 char w32_module_name[MAX_PATH+1];
125 static DWORD w32_platform = (DWORD)-1;
127 #define ONE_K_BUFSIZE 1024
132 return (win32_os_id() == VER_PLATFORM_WIN32_WINDOWS);
138 return (win32_os_id() == VER_PLATFORM_WIN32_NT);
142 set_w32_module_name(void)
145 GetModuleFileName((HMODULE)((w32_perldll_handle == INVALID_HANDLE_VALUE)
146 ? GetModuleHandle(NULL)
147 : w32_perldll_handle),
148 w32_module_name, sizeof(w32_module_name));
150 /* try to get full path to binary (which may be mangled when perl is
151 * run from a 16-bit app) */
152 /*PerlIO_printf(Perl_debug_log, "Before %s\n", w32_module_name);*/
153 (void)win32_longpath(w32_module_name);
154 /*PerlIO_printf(Perl_debug_log, "After %s\n", w32_module_name);*/
156 /* normalize to forward slashes */
157 ptr = w32_module_name;
165 /* *svp (if non-NULL) is expected to be POK (valid allocated SvPVX(*svp)) */
167 get_regstr_from(HKEY hkey, const char *valuename, SV **svp)
169 /* Retrieve a REG_SZ or REG_EXPAND_SZ from the registry */
172 const char *subkey = "Software\\Perl";
176 retval = RegOpenKeyEx(hkey, subkey, 0, KEY_READ, &handle);
177 if (retval == ERROR_SUCCESS) {
179 retval = RegQueryValueEx(handle, valuename, 0, &type, NULL, &datalen);
180 if (retval == ERROR_SUCCESS
181 && (type == REG_SZ || type == REG_EXPAND_SZ))
185 *svp = sv_2mortal(newSVpvn("",0));
186 SvGROW(*svp, datalen);
187 retval = RegQueryValueEx(handle, valuename, 0, NULL,
188 (PBYTE)SvPVX(*svp), &datalen);
189 if (retval == ERROR_SUCCESS) {
191 SvCUR_set(*svp,datalen-1);
199 /* *svp (if non-NULL) is expected to be POK (valid allocated SvPVX(*svp)) */
201 get_regstr(const char *valuename, SV **svp)
203 char *str = get_regstr_from(HKEY_CURRENT_USER, valuename, svp);
205 str = get_regstr_from(HKEY_LOCAL_MACHINE, valuename, svp);
209 /* *prev_pathp (if non-NULL) is expected to be POK (valid allocated SvPVX(sv)) */
211 get_emd_part(SV **prev_pathp, char *trailing_path, ...)
215 char mod_name[MAX_PATH+1];
219 int oldsize, newsize;
222 va_start(ap, trailing_path);
223 strip = va_arg(ap, char *);
225 sprintf(base, "%d.%d", (int)PERL_REVISION, (int)PERL_VERSION);
226 baselen = strlen(base);
228 if (!*w32_module_name) {
229 set_w32_module_name();
231 strcpy(mod_name, w32_module_name);
232 ptr = strrchr(mod_name, '/');
233 while (ptr && strip) {
234 /* look for directories to skip back */
237 ptr = strrchr(mod_name, '/');
238 /* avoid stripping component if there is no slash,
239 * or it doesn't match ... */
240 if (!ptr || stricmp(ptr+1, strip) != 0) {
241 /* ... but not if component matches m|5\.$patchlevel.*| */
242 if (!ptr || !(*strip == '5' && *(ptr+1) == '5'
243 && strncmp(strip, base, baselen) == 0
244 && strncmp(ptr+1, base, baselen) == 0))
250 strip = va_arg(ap, char *);
258 strcpy(++ptr, trailing_path);
260 /* only add directory if it exists */
261 if (GetFileAttributes(mod_name) != (DWORD) -1) {
262 /* directory exists */
265 *prev_pathp = sv_2mortal(newSVpvn("",0));
266 sv_catpvn(*prev_pathp, ";", 1);
267 sv_catpv(*prev_pathp, mod_name);
268 return SvPVX(*prev_pathp);
275 win32_get_privlib(const char *pl)
278 char *stdlib = "lib";
279 char buffer[MAX_PATH+1];
282 /* $stdlib = $HKCU{"lib-$]"} || $HKLM{"lib-$]"} || $HKCU{"lib"} || $HKLM{"lib"} || ""; */
283 sprintf(buffer, "%s-%s", stdlib, pl);
284 if (!get_regstr(buffer, &sv))
285 (void)get_regstr(stdlib, &sv);
287 /* $stdlib .= ";$EMD/../../lib" */
288 return get_emd_part(&sv, stdlib, ARCHNAME, "bin", Nullch);
292 win32_get_xlib(const char *pl, const char *xlib, const char *libname)
296 char pathstr[MAX_PATH+1];
302 /* $HKCU{"$xlib-$]"} || $HKLM{"$xlib-$]"} . ---; */
303 sprintf(regstr, "%s-%s", xlib, pl);
304 (void)get_regstr(regstr, &sv1);
307 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/$libname/$]/lib"; */
308 sprintf(pathstr, "%s/%s/lib", libname, pl);
309 (void)get_emd_part(&sv1, pathstr, ARCHNAME, "bin", pl, Nullch);
311 /* $HKCU{$xlib} || $HKLM{$xlib} . ---; */
312 (void)get_regstr(xlib, &sv2);
315 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/$libname/lib"; */
316 sprintf(pathstr, "%s/lib", libname);
317 (void)get_emd_part(&sv2, pathstr, ARCHNAME, "bin", pl, Nullch);
326 sv_catpvn(sv1, ";", 1);
333 win32_get_sitelib(const char *pl)
335 return win32_get_xlib(pl, "sitelib", "site");
338 #ifndef PERL_VENDORLIB_NAME
339 # define PERL_VENDORLIB_NAME "vendor"
343 win32_get_vendorlib(const char *pl)
345 return win32_get_xlib(pl, "vendorlib", PERL_VENDORLIB_NAME);
349 has_shell_metachars(char *ptr)
355 * Scan string looking for redirection (< or >) or pipe
356 * characters (|) that are not in a quoted string.
357 * Shell variable interpolation (%VAR%) can also happen inside strings.
389 #if !defined(PERL_IMPLICIT_SYS)
390 /* since the current process environment is being updated in util.c
391 * the library functions will get the correct environment
394 Perl_my_popen(pTHX_ char *cmd, char *mode)
397 #define fixcmd(x) { \
398 char *pspace = strchr((x),' '); \
401 while (p < pspace) { \
412 PERL_FLUSHALL_FOR_CHILD;
413 return win32_popen(cmd, mode);
417 Perl_my_pclose(pTHX_ PerlIO *fp)
419 return win32_pclose(fp);
423 DllExport unsigned long
426 static OSVERSIONINFO osver;
428 if (osver.dwPlatformId != w32_platform) {
429 memset(&osver, 0, sizeof(OSVERSIONINFO));
430 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
431 GetVersionEx(&osver);
432 w32_platform = osver.dwPlatformId;
434 return (unsigned long)w32_platform;
443 return -((int)w32_pseudo_id);
448 /* Tokenize a string. Words are null-separated, and the list
449 * ends with a doubled null. Any character (except null and
450 * including backslash) may be escaped by preceding it with a
451 * backslash (the backslash will be stripped).
452 * Returns number of words in result buffer.
455 tokenize(const char *str, char **dest, char ***destv)
457 char *retstart = Nullch;
458 char **retvstart = 0;
462 int slen = strlen(str);
464 register char **retv;
465 New(1307, ret, slen+2, char);
466 New(1308, retv, (slen+3)/2, char*);
474 if (*ret == '\\' && *str)
476 else if (*ret == ' ') {
492 retvstart[items] = Nullch;
505 if (!w32_perlshell_tokens) {
506 /* we don't use COMSPEC here for two reasons:
507 * 1. the same reason perl on UNIX doesn't use SHELL--rampant and
508 * uncontrolled unportability of the ensuing scripts.
509 * 2. PERL5SHELL could be set to a shell that may not be fit for
510 * interactive use (which is what most programs look in COMSPEC
513 const char* defaultshell = (IsWinNT()
514 ? "cmd.exe /x/c" : "command.com /c");
515 const char *usershell = getenv("PERL5SHELL");
516 w32_perlshell_items = tokenize(usershell ? usershell : defaultshell,
517 &w32_perlshell_tokens,
523 do_aspawn(void *vreally, void **vmark, void **vsp)
526 SV *really = (SV*)vreally;
527 SV **mark = (SV**)vmark;
539 New(1306, argv, (sp - mark) + w32_perlshell_items + 2, char*);
541 if (SvNIOKp(*(mark+1)) && !SvPOKp(*(mark+1))) {
546 while (++mark <= sp) {
547 if (*mark && (str = SvPV_nolen(*mark)))
554 status = win32_spawnvp(flag,
555 (const char*)(really ? SvPV_nolen(really) : argv[0]),
556 (const char* const*)argv);
558 if (status < 0 && (errno == ENOEXEC || errno == ENOENT)) {
559 /* possible shell-builtin, invoke with shell */
561 sh_items = w32_perlshell_items;
563 argv[index+sh_items] = argv[index];
564 while (--sh_items >= 0)
565 argv[sh_items] = w32_perlshell_vec[sh_items];
567 status = win32_spawnvp(flag,
568 (const char*)(really ? SvPV_nolen(really) : argv[0]),
569 (const char* const*)argv);
572 if (flag != P_NOWAIT) {
575 if (ckWARN(WARN_EXEC))
576 Perl_warner(aTHX_ WARN_EXEC, "Can't spawn \"%s\": %s", argv[0], strerror(errno));
581 PL_statusvalue = status;
588 do_spawn2(char *cmd, int exectype)
595 BOOL needToTry = TRUE;
598 /* Save an extra exec if possible. See if there are shell
599 * metacharacters in it */
600 if (!has_shell_metachars(cmd)) {
601 New(1301,argv, strlen(cmd) / 2 + 2, char*);
602 New(1302,cmd2, strlen(cmd) + 1, char);
605 for (s = cmd2; *s;) {
606 while (*s && isSPACE(*s))
610 while (*s && !isSPACE(*s))
619 status = win32_spawnvp(P_WAIT, argv[0],
620 (const char* const*)argv);
622 case EXECF_SPAWN_NOWAIT:
623 status = win32_spawnvp(P_NOWAIT, argv[0],
624 (const char* const*)argv);
627 status = win32_execvp(argv[0], (const char* const*)argv);
630 if (status != -1 || errno == 0)
640 New(1306, argv, w32_perlshell_items + 2, char*);
641 while (++i < w32_perlshell_items)
642 argv[i] = w32_perlshell_vec[i];
647 status = win32_spawnvp(P_WAIT, argv[0],
648 (const char* const*)argv);
650 case EXECF_SPAWN_NOWAIT:
651 status = win32_spawnvp(P_NOWAIT, argv[0],
652 (const char* const*)argv);
655 status = win32_execvp(argv[0], (const char* const*)argv);
661 if (exectype != EXECF_SPAWN_NOWAIT) {
664 if (ckWARN(WARN_EXEC))
665 Perl_warner(aTHX_ WARN_EXEC, "Can't %s \"%s\": %s",
666 (exectype == EXECF_EXEC ? "exec" : "spawn"),
667 cmd, strerror(errno));
672 PL_statusvalue = status;
680 return do_spawn2(cmd, EXECF_SPAWN);
684 do_spawn_nowait(char *cmd)
686 return do_spawn2(cmd, EXECF_SPAWN_NOWAIT);
690 Perl_do_exec(pTHX_ char *cmd)
692 do_spawn2(cmd, EXECF_EXEC);
696 /* The idea here is to read all the directory names into a string table
697 * (separated by nulls) and when one of the other dir functions is called
698 * return the pointer to the current file name.
701 win32_opendir(char *filename)
707 char scanname[MAX_PATH+3];
709 WIN32_FIND_DATAA aFindData;
710 WIN32_FIND_DATAW wFindData;
712 char buffer[MAX_PATH*2];
713 WCHAR wbuffer[MAX_PATH+1];
716 len = strlen(filename);
720 /* check to see if filename is a directory */
721 if (win32_stat(filename, &sbuf) < 0 || !S_ISDIR(sbuf.st_mode))
724 /* Get us a DIR structure */
725 Newz(1303, dirp, 1, DIR);
727 /* Create the search pattern */
728 strcpy(scanname, filename);
730 /* bare drive name means look in cwd for drive */
731 if (len == 2 && isALPHA(scanname[0]) && scanname[1] == ':') {
732 scanname[len++] = '.';
733 scanname[len++] = '/';
735 else if (scanname[len-1] != '/' && scanname[len-1] != '\\') {
736 scanname[len++] = '/';
738 scanname[len++] = '*';
739 scanname[len] = '\0';
741 /* do the FindFirstFile call */
743 A2WHELPER(scanname, wbuffer, sizeof(wbuffer));
744 fh = FindFirstFileW(PerlDir_mapW(wbuffer), &wFindData);
747 fh = FindFirstFileA(PerlDir_mapA(scanname), &aFindData);
750 if (fh == INVALID_HANDLE_VALUE) {
751 DWORD err = GetLastError();
752 /* FindFirstFile() fails on empty drives! */
754 case ERROR_FILE_NOT_FOUND:
756 case ERROR_NO_MORE_FILES:
757 case ERROR_PATH_NOT_FOUND:
760 case ERROR_NOT_ENOUGH_MEMORY:
771 /* now allocate the first part of the string table for
772 * the filenames that we find.
775 W2AHELPER(wFindData.cFileName, buffer, sizeof(buffer));
779 ptr = aFindData.cFileName;
786 New(1304, dirp->start, dirp->size, char);
787 strcpy(dirp->start, ptr);
789 dirp->end = dirp->curr = dirp->start;
795 /* Readdir just returns the current string pointer and bumps the
796 * string pointer to the nDllExport entry.
798 DllExport struct direct *
799 win32_readdir(DIR *dirp)
804 /* first set up the structure to return */
805 len = strlen(dirp->curr);
806 strcpy(dirp->dirstr.d_name, dirp->curr);
807 dirp->dirstr.d_namlen = len;
810 dirp->dirstr.d_ino = dirp->curr - dirp->start;
812 /* Now set up for the next call to readdir */
813 dirp->curr += len + 1;
814 if (dirp->curr >= dirp->end) {
818 WIN32_FIND_DATAW wFindData;
819 WIN32_FIND_DATAA aFindData;
820 char buffer[MAX_PATH*2];
822 /* finding the next file that matches the wildcard
823 * (which should be all of them in this directory!).
826 res = FindNextFileW(dirp->handle, &wFindData);
828 W2AHELPER(wFindData.cFileName, buffer, sizeof(buffer));
833 res = FindNextFileA(dirp->handle, &aFindData);
835 ptr = aFindData.cFileName;
838 long endpos = dirp->end - dirp->start;
839 long newsize = endpos + strlen(ptr) + 1;
840 /* bump the string table size by enough for the
841 * new name and it's null terminator */
842 while (newsize > dirp->size) {
843 long curpos = dirp->curr - dirp->start;
845 Renew(dirp->start, dirp->size, char);
846 dirp->curr = dirp->start + curpos;
848 strcpy(dirp->start + endpos, ptr);
849 dirp->end = dirp->start + newsize;
855 return &(dirp->dirstr);
861 /* Telldir returns the current string pointer position */
863 win32_telldir(DIR *dirp)
865 return (dirp->curr - dirp->start);
869 /* Seekdir moves the string pointer to a previously saved position
870 * (returned by telldir).
873 win32_seekdir(DIR *dirp, long loc)
875 dirp->curr = dirp->start + loc;
878 /* Rewinddir resets the string pointer to the start */
880 win32_rewinddir(DIR *dirp)
882 dirp->curr = dirp->start;
885 /* free the memory allocated by opendir */
887 win32_closedir(DIR *dirp)
890 if (dirp->handle != INVALID_HANDLE_VALUE)
891 FindClose(dirp->handle);
892 Safefree(dirp->start);
905 * Just pretend that everyone is a superuser. NT will let us know if
906 * we don\'t really have permission to do something.
909 #define ROOT_UID ((uid_t)0)
910 #define ROOT_GID ((gid_t)0)
939 return (auid == ROOT_UID ? 0 : -1);
945 return (agid == ROOT_GID ? 0 : -1);
952 char *buf = w32_getlogin_buffer;
953 DWORD size = sizeof(w32_getlogin_buffer);
954 if (GetUserName(buf,&size))
960 chown(const char *path, uid_t owner, gid_t group)
970 long child = w32_num_children;
971 while (--child >= 0) {
972 if (w32_child_pids[child] == pid)
979 remove_dead_process(long child)
983 CloseHandle(w32_child_handles[child]);
984 Move(&w32_child_handles[child+1], &w32_child_handles[child],
985 (w32_num_children-child-1), HANDLE);
986 Move(&w32_child_pids[child+1], &w32_child_pids[child],
987 (w32_num_children-child-1), DWORD);
994 find_pseudo_pid(int pid)
997 long child = w32_num_pseudo_children;
998 while (--child >= 0) {
999 if (w32_pseudo_child_pids[child] == pid)
1006 remove_dead_pseudo_process(long child)
1010 CloseHandle(w32_pseudo_child_handles[child]);
1011 Move(&w32_pseudo_child_handles[child+1], &w32_pseudo_child_handles[child],
1012 (w32_num_pseudo_children-child-1), HANDLE);
1013 Move(&w32_pseudo_child_pids[child+1], &w32_pseudo_child_pids[child],
1014 (w32_num_pseudo_children-child-1), DWORD);
1015 w32_num_pseudo_children--;
1021 win32_kill(int pid, int sig)
1027 /* it is a pseudo-forked child */
1028 long child = find_pseudo_pid(-pid);
1032 hProcess = w32_pseudo_child_handles[child];
1033 if (TerminateThread(hProcess, sig)) {
1034 remove_dead_pseudo_process(child);
1042 long child = find_pid(pid);
1046 hProcess = w32_child_handles[child];
1047 if (TerminateProcess(hProcess, sig)) {
1048 remove_dead_process(child);
1053 hProcess = OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid);
1057 if (TerminateProcess(hProcess, sig)) {
1058 CloseHandle(hProcess);
1072 DllExport unsigned int
1073 win32_sleep(unsigned int t)
1080 win32_stat(const char *path, struct stat *sbuf)
1083 char buffer[MAX_PATH+1];
1084 int l = strlen(path);
1086 WCHAR wbuffer[MAX_PATH+1];
1092 switch(path[l - 1]) {
1093 /* FindFirstFile() and stat() are buggy with a trailing
1094 * backslash, so change it to a forward slash :-( */
1096 strncpy(buffer, path, l-1);
1097 buffer[l - 1] = '/';
1101 /* FindFirstFile() is buggy with "x:", so add a dot :-( */
1103 if (l == 2 && isALPHA(path[0])) {
1104 buffer[0] = path[0];
1115 /* We *must* open & close the file once; otherwise file attribute changes */
1116 /* might not yet have propagated to "other" hard links of the same file. */
1117 /* This also gives us an opportunity to determine the number of links. */
1119 A2WHELPER(path, wbuffer, sizeof(wbuffer));
1120 pwbuffer = PerlDir_mapW(wbuffer);
1121 handle = CreateFileW(pwbuffer, 0, 0, NULL, OPEN_EXISTING, 0, NULL);
1124 path = PerlDir_mapA(path);
1126 handle = CreateFileA(path, 0, 0, NULL, OPEN_EXISTING, 0, NULL);
1128 if (handle != INVALID_HANDLE_VALUE) {
1129 BY_HANDLE_FILE_INFORMATION bhi;
1130 if (GetFileInformationByHandle(handle, &bhi))
1131 nlink = bhi.nNumberOfLinks;
1132 CloseHandle(handle);
1135 /* pwbuffer or path will be mapped correctly above */
1137 res = _wstat(pwbuffer, (struct _stat *)sbuf);
1140 res = stat(path, sbuf);
1142 sbuf->st_nlink = nlink;
1145 /* CRT is buggy on sharenames, so make sure it really isn't.
1146 * XXX using GetFileAttributesEx() will enable us to set
1147 * sbuf->st_*time (but note that's not available on the
1148 * Windows of 1995) */
1151 r = GetFileAttributesW(pwbuffer);
1154 r = GetFileAttributesA(path);
1156 if (r != 0xffffffff && (r & FILE_ATTRIBUTE_DIRECTORY)) {
1157 /* sbuf may still contain old garbage since stat() failed */
1158 Zero(sbuf, 1, struct stat);
1159 sbuf->st_mode = S_IFDIR | S_IREAD;
1161 if (!(r & FILE_ATTRIBUTE_READONLY))
1162 sbuf->st_mode |= S_IWRITE | S_IEXEC;
1167 if (l == 3 && isALPHA(path[0]) && path[1] == ':'
1168 && (path[2] == '\\' || path[2] == '/'))
1170 /* The drive can be inaccessible, some _stat()s are buggy */
1172 ? !GetVolumeInformationW(pwbuffer,NULL,0,NULL,NULL,NULL,NULL,0)
1173 : !GetVolumeInformationA(path,NULL,0,NULL,NULL,NULL,NULL,0)) {
1179 if (S_ISDIR(sbuf->st_mode))
1180 sbuf->st_mode |= S_IWRITE | S_IEXEC;
1181 else if (S_ISREG(sbuf->st_mode)) {
1183 if (l >= 4 && path[l-4] == '.') {
1184 const char *e = path + l - 3;
1185 if (strnicmp(e,"exe",3)
1186 && strnicmp(e,"bat",3)
1187 && strnicmp(e,"com",3)
1188 && (IsWin95() || strnicmp(e,"cmd",3)))
1189 sbuf->st_mode &= ~S_IEXEC;
1191 sbuf->st_mode |= S_IEXEC;
1194 sbuf->st_mode &= ~S_IEXEC;
1195 /* Propagate permissions to _group_ and _others_ */
1196 perms = sbuf->st_mode & (S_IREAD|S_IWRITE|S_IEXEC);
1197 sbuf->st_mode |= (perms>>3) | (perms>>6);
1204 /* Find the longname of a given path. path is destructively modified.
1205 * It should have space for at least MAX_PATH characters. */
1207 win32_longpath(char *path)
1209 WIN32_FIND_DATA fdata;
1211 char tmpbuf[MAX_PATH+1];
1212 char *tmpstart = tmpbuf;
1219 if (isALPHA(path[0]) && path[1] == ':' &&
1220 (path[2] == '/' || path[2] == '\\'))
1223 *tmpstart++ = path[0];
1227 else if ((path[0] == '/' || path[0] == '\\') &&
1228 (path[1] == '/' || path[1] == '\\'))
1231 *tmpstart++ = path[0];
1232 *tmpstart++ = path[1];
1233 /* copy machine name */
1234 while (*start && *start != '/' && *start != '\\')
1235 *tmpstart++ = *start++;
1237 *tmpstart++ = *start;
1239 /* copy share name */
1240 while (*start && *start != '/' && *start != '\\')
1241 *tmpstart++ = *start++;
1245 if (sep == '/' || sep == '\\')
1249 /* walk up to slash */
1250 while (*start && *start != '/' && *start != '\\')
1253 /* discard doubled slashes */
1254 while (*start && (start[1] == '/' || start[1] == '\\'))
1258 /* stop and find full name of component */
1260 fhand = FindFirstFile(path,&fdata);
1261 if (fhand != INVALID_HANDLE_VALUE) {
1262 strcpy(tmpstart, fdata.cFileName);
1263 tmpstart += strlen(fdata.cFileName);
1271 /* failed a step, just return without side effects */
1272 /*PerlIO_printf(Perl_debug_log, "Failed to find %s\n", path);*/
1277 strcpy(path,tmpbuf);
1281 #ifndef USE_WIN32_RTL_ENV
1284 win32_getenv(const char *name)
1287 WCHAR wBuffer[MAX_PATH+1];
1289 SV *curitem = Nullsv;
1292 A2WHELPER(name, wBuffer, sizeof(wBuffer));
1293 needlen = GetEnvironmentVariableW(wBuffer, NULL, 0);
1296 needlen = GetEnvironmentVariableA(name,NULL,0);
1298 curitem = sv_2mortal(newSVpvn("", 0));
1302 SvGROW(curitem, (needlen+1)*sizeof(WCHAR));
1303 needlen = GetEnvironmentVariableW(wBuffer,
1304 (WCHAR*)SvPVX(curitem),
1306 } while (needlen >= SvLEN(curitem)/sizeof(WCHAR));
1307 SvCUR_set(curitem, (needlen*sizeof(WCHAR))+1);
1308 acuritem = sv_2mortal(newSVsv(curitem));
1309 W2AHELPER((WCHAR*)SvPVX(acuritem), SvPVX(curitem), SvCUR(curitem));
1313 SvGROW(curitem, needlen+1);
1314 needlen = GetEnvironmentVariableA(name,SvPVX(curitem),
1316 } while (needlen >= SvLEN(curitem));
1317 SvCUR_set(curitem, needlen);
1321 /* allow any environment variables that begin with 'PERL'
1322 to be stored in the registry */
1323 if (strncmp(name, "PERL", 4) == 0)
1324 (void)get_regstr(name, &curitem);
1326 if (curitem && SvCUR(curitem))
1327 return SvPVX(curitem);
1333 win32_putenv(const char *name)
1340 int length, relval = -1;
1344 length = strlen(name)+1;
1345 New(1309,wCuritem,length,WCHAR);
1346 A2WHELPER(name, wCuritem, length*sizeof(WCHAR));
1347 wVal = wcschr(wCuritem, '=');
1350 if (SetEnvironmentVariableW(wCuritem, *wVal ? wVal : NULL))
1356 New(1309,curitem,strlen(name)+1,char);
1357 strcpy(curitem, name);
1358 val = strchr(curitem, '=');
1360 /* The sane way to deal with the environment.
1361 * Has these advantages over putenv() & co.:
1362 * * enables us to store a truly empty value in the
1363 * environment (like in UNIX).
1364 * * we don't have to deal with RTL globals, bugs and leaks.
1366 * Why you may want to enable USE_WIN32_RTL_ENV:
1367 * * environ[] and RTL functions will not reflect changes,
1368 * which might be an issue if extensions want to access
1369 * the env. via RTL. This cuts both ways, since RTL will
1370 * not see changes made by extensions that call the Win32
1371 * functions directly, either.
1375 if (SetEnvironmentVariableA(curitem, *val ? val : NULL))
1387 filetime_to_clock(PFILETIME ft)
1389 __int64 qw = ft->dwHighDateTime;
1391 qw |= ft->dwLowDateTime;
1392 qw /= 10000; /* File time ticks at 0.1uS, clock at 1mS */
1397 win32_times(struct tms *timebuf)
1402 if (GetProcessTimes(GetCurrentProcess(), &dummy, &dummy,
1404 timebuf->tms_utime = filetime_to_clock(&user);
1405 timebuf->tms_stime = filetime_to_clock(&kernel);
1406 timebuf->tms_cutime = 0;
1407 timebuf->tms_cstime = 0;
1410 /* That failed - e.g. Win95 fallback to clock() */
1411 clock_t t = clock();
1412 timebuf->tms_utime = t;
1413 timebuf->tms_stime = 0;
1414 timebuf->tms_cutime = 0;
1415 timebuf->tms_cstime = 0;
1420 /* fix utime() so it works on directories in NT */
1422 filetime_from_time(PFILETIME pFileTime, time_t Time)
1424 struct tm *pTM = localtime(&Time);
1425 SYSTEMTIME SystemTime;
1431 SystemTime.wYear = pTM->tm_year + 1900;
1432 SystemTime.wMonth = pTM->tm_mon + 1;
1433 SystemTime.wDay = pTM->tm_mday;
1434 SystemTime.wHour = pTM->tm_hour;
1435 SystemTime.wMinute = pTM->tm_min;
1436 SystemTime.wSecond = pTM->tm_sec;
1437 SystemTime.wMilliseconds = 0;
1439 return SystemTimeToFileTime(&SystemTime, &LocalTime) &&
1440 LocalFileTimeToFileTime(&LocalTime, pFileTime);
1444 win32_unlink(const char *filename)
1451 WCHAR wBuffer[MAX_PATH+1];
1454 A2WHELPER(filename, wBuffer, sizeof(wBuffer));
1455 pwBuffer = PerlDir_mapW(wBuffer);
1456 attrs = GetFileAttributesW(pwBuffer);
1457 if (attrs == 0xFFFFFFFF)
1459 if (attrs & FILE_ATTRIBUTE_READONLY) {
1460 (void)SetFileAttributesW(pwBuffer, attrs & ~FILE_ATTRIBUTE_READONLY);
1461 ret = _wunlink(pwBuffer);
1463 (void)SetFileAttributesW(pwBuffer, attrs);
1466 ret = _wunlink(pwBuffer);
1469 filename = PerlDir_mapA(filename);
1470 attrs = GetFileAttributesA(filename);
1471 if (attrs == 0xFFFFFFFF)
1473 if (attrs & FILE_ATTRIBUTE_READONLY) {
1474 (void)SetFileAttributesA(filename, attrs & ~FILE_ATTRIBUTE_READONLY);
1475 ret = unlink(filename);
1477 (void)SetFileAttributesA(filename, attrs);
1480 ret = unlink(filename);
1489 win32_utime(const char *filename, struct utimbuf *times)
1496 struct utimbuf TimeBuffer;
1497 WCHAR wbuffer[MAX_PATH+1];
1502 A2WHELPER(filename, wbuffer, sizeof(wbuffer));
1503 pwbuffer = PerlDir_mapW(wbuffer);
1504 rc = _wutime(pwbuffer, (struct _utimbuf*)times);
1507 filename = PerlDir_mapA(filename);
1508 rc = utime(filename, times);
1510 /* EACCES: path specifies directory or readonly file */
1511 if (rc == 0 || errno != EACCES /* || !IsWinNT() */)
1514 if (times == NULL) {
1515 times = &TimeBuffer;
1516 time(×->actime);
1517 times->modtime = times->actime;
1520 /* This will (and should) still fail on readonly files */
1522 handle = CreateFileW(pwbuffer, GENERIC_READ | GENERIC_WRITE,
1523 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1524 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1527 handle = CreateFileA(filename, GENERIC_READ | GENERIC_WRITE,
1528 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1529 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1531 if (handle == INVALID_HANDLE_VALUE)
1534 if (GetFileTime(handle, &ftCreate, &ftAccess, &ftWrite) &&
1535 filetime_from_time(&ftAccess, times->actime) &&
1536 filetime_from_time(&ftWrite, times->modtime) &&
1537 SetFileTime(handle, &ftCreate, &ftAccess, &ftWrite))
1542 CloseHandle(handle);
1547 win32_uname(struct utsname *name)
1549 struct hostent *hep;
1550 STRLEN nodemax = sizeof(name->nodename)-1;
1551 OSVERSIONINFO osver;
1553 memset(&osver, 0, sizeof(OSVERSIONINFO));
1554 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1555 if (GetVersionEx(&osver)) {
1557 switch (osver.dwPlatformId) {
1558 case VER_PLATFORM_WIN32_WINDOWS:
1559 strcpy(name->sysname, "Windows");
1561 case VER_PLATFORM_WIN32_NT:
1562 strcpy(name->sysname, "Windows NT");
1564 case VER_PLATFORM_WIN32s:
1565 strcpy(name->sysname, "Win32s");
1568 strcpy(name->sysname, "Win32 Unknown");
1573 sprintf(name->release, "%d.%d",
1574 osver.dwMajorVersion, osver.dwMinorVersion);
1577 sprintf(name->version, "Build %d",
1578 osver.dwPlatformId == VER_PLATFORM_WIN32_NT
1579 ? osver.dwBuildNumber : (osver.dwBuildNumber & 0xffff));
1580 if (osver.szCSDVersion[0]) {
1581 char *buf = name->version + strlen(name->version);
1582 sprintf(buf, " (%s)", osver.szCSDVersion);
1586 *name->sysname = '\0';
1587 *name->version = '\0';
1588 *name->release = '\0';
1592 hep = win32_gethostbyname("localhost");
1594 STRLEN len = strlen(hep->h_name);
1595 if (len <= nodemax) {
1596 strcpy(name->nodename, hep->h_name);
1599 strncpy(name->nodename, hep->h_name, nodemax);
1600 name->nodename[nodemax] = '\0';
1605 if (!GetComputerName(name->nodename, &sz))
1606 *name->nodename = '\0';
1609 /* machine (architecture) */
1613 GetSystemInfo(&info);
1615 #if defined(__BORLANDC__) || defined(__MINGW32__)
1616 switch (info.u.s.wProcessorArchitecture) {
1618 switch (info.wProcessorArchitecture) {
1620 case PROCESSOR_ARCHITECTURE_INTEL:
1621 arch = "x86"; break;
1622 case PROCESSOR_ARCHITECTURE_MIPS:
1623 arch = "mips"; break;
1624 case PROCESSOR_ARCHITECTURE_ALPHA:
1625 arch = "alpha"; break;
1626 case PROCESSOR_ARCHITECTURE_PPC:
1627 arch = "ppc"; break;
1629 arch = "unknown"; break;
1631 strcpy(name->machine, arch);
1637 win32_waitpid(int pid, int *status, int flags)
1641 if (pid == -1) /* XXX threadid == 1 ? */
1642 return win32_wait(status);
1645 long child = find_pseudo_pid(-pid);
1647 HANDLE hThread = w32_pseudo_child_handles[child];
1648 DWORD waitcode = WaitForSingleObject(hThread, INFINITE);
1649 if (waitcode != WAIT_FAILED) {
1650 if (GetExitCodeThread(hThread, &waitcode)) {
1651 *status = (int)((waitcode & 0xff) << 8);
1652 retval = (int)w32_pseudo_child_pids[child];
1653 remove_dead_pseudo_process(child);
1663 long child = find_pid(pid);
1665 HANDLE hProcess = w32_child_handles[child];
1666 DWORD waitcode = WaitForSingleObject(hProcess, INFINITE);
1667 if (waitcode != WAIT_FAILED) {
1668 if (GetExitCodeProcess(hProcess, &waitcode)) {
1669 *status = (int)((waitcode & 0xff) << 8);
1670 retval = (int)w32_child_pids[child];
1671 remove_dead_process(child);
1679 retval = cwait(status, pid, WAIT_CHILD);
1680 /* cwait() returns "correctly" on Borland */
1681 #ifndef __BORLANDC__
1687 return retval >= 0 ? pid : retval;
1691 win32_wait(int *status)
1693 /* XXX this wait emulation only knows about processes
1694 * spawned via win32_spawnvp(P_NOWAIT, ...).
1698 DWORD exitcode, waitcode;
1701 if (w32_num_pseudo_children) {
1702 waitcode = WaitForMultipleObjects(w32_num_pseudo_children,
1703 w32_pseudo_child_handles,
1706 if (waitcode != WAIT_FAILED) {
1707 if (waitcode >= WAIT_ABANDONED_0
1708 && waitcode < WAIT_ABANDONED_0 + w32_num_pseudo_children)
1709 i = waitcode - WAIT_ABANDONED_0;
1711 i = waitcode - WAIT_OBJECT_0;
1712 if (GetExitCodeThread(w32_pseudo_child_handles[i], &exitcode)) {
1713 *status = (int)((exitcode & 0xff) << 8);
1714 retval = (int)w32_pseudo_child_pids[i];
1715 remove_dead_pseudo_process(i);
1722 if (!w32_num_children) {
1727 /* if a child exists, wait for it to die */
1728 waitcode = WaitForMultipleObjects(w32_num_children,
1732 if (waitcode != WAIT_FAILED) {
1733 if (waitcode >= WAIT_ABANDONED_0
1734 && waitcode < WAIT_ABANDONED_0 + w32_num_children)
1735 i = waitcode - WAIT_ABANDONED_0;
1737 i = waitcode - WAIT_OBJECT_0;
1738 if (GetExitCodeProcess(w32_child_handles[i], &exitcode) ) {
1739 *status = (int)((exitcode & 0xff) << 8);
1740 retval = (int)w32_child_pids[i];
1741 remove_dead_process(i);
1747 errno = GetLastError();
1753 static UINT timerid = 0;
1755 static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
1758 KillTimer(NULL,timerid);
1760 CALL_FPTR(PL_sighandlerp)(14);
1762 #endif /* !PERL_OBJECT */
1764 DllExport unsigned int
1765 win32_alarm(unsigned int sec)
1769 * the 'obvious' implentation is SetTimer() with a callback
1770 * which does whatever receiving SIGALRM would do
1771 * we cannot use SIGALRM even via raise() as it is not
1772 * one of the supported codes in <signal.h>
1774 * Snag is unless something is looking at the message queue
1775 * nothing happens :-(
1780 timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
1782 Perl_croak_nocontext("Cannot set timer");
1788 KillTimer(NULL,timerid);
1792 #endif /* !PERL_OBJECT */
1796 #ifdef HAVE_DES_FCRYPT
1797 extern char * des_fcrypt(const char *txt, const char *salt, char *cbuf);
1801 win32_crypt(const char *txt, const char *salt)
1804 #ifdef HAVE_DES_FCRYPT
1806 return des_fcrypt(txt, salt, w32_crypt_buffer);
1808 Perl_croak(aTHX_ "The crypt() function is unimplemented due to excessive paranoia.");
1813 /* C doesn't like repeat struct definitions */
1815 #if defined(USE_FIXED_OSFHANDLE) || defined(PERL_MSVCRT_READFIX)
1818 #define _CRTIMP __declspec(dllimport)
1822 * Control structure for lowio file handles
1825 long osfhnd; /* underlying OS file HANDLE */
1826 char osfile; /* attributes of file (e.g., open in text mode?) */
1827 char pipech; /* one char buffer for handles opened on pipes */
1829 CRITICAL_SECTION lock;
1834 * Array of arrays of control structures for lowio files.
1836 EXTERN_C _CRTIMP ioinfo* __pioinfo[];
1839 * Definition of IOINFO_L2E, the log base 2 of the number of elements in each
1840 * array of ioinfo structs.
1842 #define IOINFO_L2E 5
1845 * Definition of IOINFO_ARRAY_ELTS, the number of elements in ioinfo array
1847 #define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
1850 * Access macros for getting at an ioinfo struct and its fields from a
1853 #define _pioinfo(i) (__pioinfo[(i) >> IOINFO_L2E] + ((i) & (IOINFO_ARRAY_ELTS - 1)))
1854 #define _osfhnd(i) (_pioinfo(i)->osfhnd)
1855 #define _osfile(i) (_pioinfo(i)->osfile)
1856 #define _pipech(i) (_pioinfo(i)->pipech)
1860 #ifdef USE_FIXED_OSFHANDLE
1862 #define FOPEN 0x01 /* file handle open */
1863 #define FNOINHERIT 0x10 /* file handle opened O_NOINHERIT */
1864 #define FAPPEND 0x20 /* file handle opened O_APPEND */
1865 #define FDEV 0x40 /* file handle refers to device */
1866 #define FTEXT 0x80 /* file handle is in text mode */
1869 *int my_open_osfhandle(long osfhandle, int flags) - open C Runtime file handle
1872 * This function allocates a free C Runtime file handle and associates
1873 * it with the Win32 HANDLE specified by the first parameter. This is a
1874 * temperary fix for WIN95's brain damage GetFileType() error on socket
1875 * we just bypass that call for socket
1877 * This works with MSVC++ 4.0+ or GCC/Mingw32
1880 * long osfhandle - Win32 HANDLE to associate with C Runtime file handle.
1881 * int flags - flags to associate with C Runtime file handle.
1884 * returns index of entry in fh, if successful
1885 * return -1, if no free entry is found
1889 *******************************************************************************/
1892 * we fake up some parts of the CRT that aren't exported by MSVCRT.dll
1893 * this lets sockets work on Win9X with GCC and should fix the problems
1898 /* since we are not doing a dup2(), this works fine */
1900 #define _set_osfhnd(fh, osfh) (void)(_osfhnd(fh) = osfh)
1902 /* create an ioinfo entry, kill its handle, and steal the entry */
1907 HANDLE hF = CreateFile("NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
1908 int fh = _open_osfhandle((long)hF, 0);
1912 EnterCriticalSection(&(_pioinfo(fh)->lock));
1917 my_open_osfhandle(long osfhandle, int flags)
1920 char fileflags; /* _osfile flags */
1922 /* copy relevant flags from second parameter */
1925 if (flags & O_APPEND)
1926 fileflags |= FAPPEND;
1931 if (flags & O_NOINHERIT)
1932 fileflags |= FNOINHERIT;
1934 /* attempt to allocate a C Runtime file handle */
1935 if ((fh = _alloc_osfhnd()) == -1) {
1936 errno = EMFILE; /* too many open files */
1937 _doserrno = 0L; /* not an OS error */
1938 return -1; /* return error to caller */
1941 /* the file is open. now, set the info in _osfhnd array */
1942 _set_osfhnd(fh, osfhandle);
1944 fileflags |= FOPEN; /* mark as open */
1946 _osfile(fh) = fileflags; /* set osfile entry */
1947 LeaveCriticalSection(&_pioinfo(fh)->lock);
1949 return fh; /* return handle */
1952 #endif /* USE_FIXED_OSFHANDLE */
1954 /* simulate flock by locking a range on the file */
1956 #define LK_ERR(f,i) ((f) ? (i = 0) : (errno = GetLastError()))
1957 #define LK_LEN 0xffff0000
1960 win32_flock(int fd, int oper)
1968 Perl_croak_nocontext("flock() unimplemented on this platform");
1971 fh = (HANDLE)_get_osfhandle(fd);
1972 memset(&o, 0, sizeof(o));
1975 case LOCK_SH: /* shared lock */
1976 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
1978 case LOCK_EX: /* exclusive lock */
1979 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
1981 case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
1982 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
1984 case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
1985 LK_ERR(LockFileEx(fh,
1986 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
1987 0, LK_LEN, 0, &o),i);
1989 case LOCK_UN: /* unlock lock */
1990 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, 0, &o),i);
1992 default: /* unknown */
2003 * redirected io subsystem for all XS modules
2016 return (&(_environ));
2019 /* the rest are the remapped stdio routines */
2039 win32_ferror(FILE *fp)
2041 return (ferror(fp));
2046 win32_feof(FILE *fp)
2052 * Since the errors returned by the socket error function
2053 * WSAGetLastError() are not known by the library routine strerror
2054 * we have to roll our own.
2058 win32_strerror(int e)
2060 #ifndef __BORLANDC__ /* Borland intolerance */
2061 extern int sys_nerr;
2065 if (e < 0 || e > sys_nerr) {
2070 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
2071 w32_strerror_buffer,
2072 sizeof(w32_strerror_buffer), NULL) == 0)
2073 strcpy(w32_strerror_buffer, "Unknown Error");
2075 return w32_strerror_buffer;
2081 win32_str_os_error(void *sv, DWORD dwErr)
2085 dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
2086 |FORMAT_MESSAGE_IGNORE_INSERTS
2087 |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
2088 dwErr, 0, (char *)&sMsg, 1, NULL);
2089 /* strip trailing whitespace and period */
2092 --dwLen; /* dwLen doesn't include trailing null */
2093 } while (0 < dwLen && isSPACE(sMsg[dwLen]));
2094 if ('.' != sMsg[dwLen])
2099 sMsg = (char*)LocalAlloc(0, 64/**sizeof(TCHAR)*/);
2101 dwLen = sprintf(sMsg,
2102 "Unknown error #0x%lX (lookup 0x%lX)",
2103 dwErr, GetLastError());
2107 sv_setpvn((SV*)sv, sMsg, dwLen);
2114 win32_fprintf(FILE *fp, const char *format, ...)
2117 va_start(marker, format); /* Initialize variable arguments. */
2119 return (vfprintf(fp, format, marker));
2123 win32_printf(const char *format, ...)
2126 va_start(marker, format); /* Initialize variable arguments. */
2128 return (vprintf(format, marker));
2132 win32_vfprintf(FILE *fp, const char *format, va_list args)
2134 return (vfprintf(fp, format, args));
2138 win32_vprintf(const char *format, va_list args)
2140 return (vprintf(format, args));
2144 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
2146 return fread(buf, size, count, fp);
2150 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
2152 return fwrite(buf, size, count, fp);
2155 #define MODE_SIZE 10
2158 win32_fopen(const char *filename, const char *mode)
2161 WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH+1];
2167 if (stricmp(filename, "/dev/null")==0)
2171 A2WHELPER(mode, wMode, sizeof(wMode));
2172 A2WHELPER(filename, wBuffer, sizeof(wBuffer));
2173 f = _wfopen(PerlDir_mapW(wBuffer), wMode);
2176 f = fopen(PerlDir_mapA(filename), mode);
2177 /* avoid buffering headaches for child processes */
2178 if (f && *mode == 'a')
2179 win32_fseek(f, 0, SEEK_END);
2183 #ifndef USE_SOCKETS_AS_HANDLES
2185 #define fdopen my_fdopen
2189 win32_fdopen(int handle, const char *mode)
2192 WCHAR wMode[MODE_SIZE];
2195 A2WHELPER(mode, wMode, sizeof(wMode));
2196 f = _wfdopen(handle, wMode);
2199 f = fdopen(handle, (char *) mode);
2200 /* avoid buffering headaches for child processes */
2201 if (f && *mode == 'a')
2202 win32_fseek(f, 0, SEEK_END);
2207 win32_freopen(const char *path, const char *mode, FILE *stream)
2210 WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH+1];
2211 if (stricmp(path, "/dev/null")==0)
2215 A2WHELPER(mode, wMode, sizeof(wMode));
2216 A2WHELPER(path, wBuffer, sizeof(wBuffer));
2217 return _wfreopen(PerlDir_mapW(wBuffer), wMode, stream);
2219 return freopen(PerlDir_mapA(path), mode, stream);
2223 win32_fclose(FILE *pf)
2225 return my_fclose(pf); /* defined in win32sck.c */
2229 win32_fputs(const char *s,FILE *pf)
2231 return fputs(s, pf);
2235 win32_fputc(int c,FILE *pf)
2241 win32_ungetc(int c,FILE *pf)
2243 return ungetc(c,pf);
2247 win32_getc(FILE *pf)
2253 win32_fileno(FILE *pf)
2259 win32_clearerr(FILE *pf)
2266 win32_fflush(FILE *pf)
2272 win32_ftell(FILE *pf)
2278 win32_fseek(FILE *pf,long offset,int origin)
2280 return fseek(pf, offset, origin);
2284 win32_fgetpos(FILE *pf,fpos_t *p)
2286 return fgetpos(pf, p);
2290 win32_fsetpos(FILE *pf,const fpos_t *p)
2292 return fsetpos(pf, p);
2296 win32_rewind(FILE *pf)
2316 win32_fstat(int fd,struct stat *sbufptr)
2318 return fstat(fd,sbufptr);
2322 win32_pipe(int *pfd, unsigned int size, int mode)
2324 return _pipe(pfd, size, mode);
2328 * a popen() clone that respects PERL5SHELL
2332 win32_popen(const char *command, const char *mode)
2334 #ifdef USE_RTL_POPEN
2335 return _popen(command, mode);
2343 /* establish which ends read and write */
2344 if (strchr(mode,'w')) {
2345 stdfd = 0; /* stdin */
2349 else if (strchr(mode,'r')) {
2350 stdfd = 1; /* stdout */
2357 /* set the correct mode */
2358 if (strchr(mode,'b'))
2360 else if (strchr(mode,'t'))
2363 ourmode = _fmode & (O_TEXT | O_BINARY);
2365 /* the child doesn't inherit handles */
2366 ourmode |= O_NOINHERIT;
2368 if (win32_pipe( p, 512, ourmode) == -1)
2371 /* save current stdfd */
2372 if ((oldfd = win32_dup(stdfd)) == -1)
2375 /* make stdfd go to child end of pipe (implicitly closes stdfd) */
2376 /* stdfd will be inherited by the child */
2377 if (win32_dup2(p[child], stdfd) == -1)
2380 /* close the child end in parent */
2381 win32_close(p[child]);
2383 /* start the child */
2386 if ((childpid = do_spawn_nowait((char*)command)) == -1)
2389 /* revert stdfd to whatever it was before */
2390 if (win32_dup2(oldfd, stdfd) == -1)
2393 /* close saved handle */
2396 sv_setiv(*av_fetch(w32_fdpid, p[parent], TRUE), childpid);
2398 /* set process id so that it can be returned by perl's open() */
2399 PL_forkprocess = childpid;
2402 /* we have an fd, return a file stream */
2403 return (win32_fdopen(p[parent], (char *)mode));
2406 /* we don't need to check for errors here */
2410 win32_dup2(oldfd, stdfd);
2415 #endif /* USE_RTL_POPEN */
2423 win32_pclose(FILE *pf)
2425 #ifdef USE_RTL_POPEN
2429 int childpid, status;
2432 sv = *av_fetch(w32_fdpid, win32_fileno(pf), TRUE);
2434 childpid = SvIVX(sv);
2446 if (win32_waitpid(childpid, &status, 0) == -1)
2451 #endif /* USE_RTL_POPEN */
2457 LPCWSTR lpExistingFileName,
2458 LPSECURITY_ATTRIBUTES lpSecurityAttributes)
2461 WCHAR wFullName[MAX_PATH+1];
2462 LPVOID lpContext = NULL;
2463 WIN32_STREAM_ID StreamId;
2464 DWORD dwSize = (char*)&StreamId.cStreamName - (char*)&StreamId;
2469 BOOL (__stdcall *pfnBackupWrite)(HANDLE, LPBYTE, DWORD, LPDWORD,
2470 BOOL, BOOL, LPVOID*) =
2471 (BOOL (__stdcall *)(HANDLE, LPBYTE, DWORD, LPDWORD,
2472 BOOL, BOOL, LPVOID*))
2473 GetProcAddress(GetModuleHandle("kernel32.dll"), "BackupWrite");
2474 if (pfnBackupWrite == NULL)
2477 dwLen = GetFullPathNameW(lpFileName, MAX_PATH, wFullName, NULL);
2480 dwLen = (dwLen+1)*sizeof(WCHAR);
2482 handle = CreateFileW(lpExistingFileName, FILE_WRITE_ATTRIBUTES,
2483 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
2484 NULL, OPEN_EXISTING, 0, NULL);
2485 if (handle == INVALID_HANDLE_VALUE)
2488 StreamId.dwStreamId = BACKUP_LINK;
2489 StreamId.dwStreamAttributes = 0;
2490 StreamId.dwStreamNameSize = 0;
2491 #if defined(__BORLANDC__) || defined(__MINGW32__)
2492 StreamId.Size.u.HighPart = 0;
2493 StreamId.Size.u.LowPart = dwLen;
2495 StreamId.Size.HighPart = 0;
2496 StreamId.Size.LowPart = dwLen;
2499 bSuccess = pfnBackupWrite(handle, (LPBYTE)&StreamId, dwSize, &dwWritten,
2500 FALSE, FALSE, &lpContext);
2502 bSuccess = pfnBackupWrite(handle, (LPBYTE)wFullName, dwLen, &dwWritten,
2503 FALSE, FALSE, &lpContext);
2504 pfnBackupWrite(handle, NULL, 0, &dwWritten, TRUE, FALSE, &lpContext);
2507 CloseHandle(handle);
2512 win32_link(const char *oldname, const char *newname)
2515 BOOL (__stdcall *pfnCreateHardLinkW)(LPCWSTR,LPCWSTR,LPSECURITY_ATTRIBUTES);
2516 WCHAR wOldName[MAX_PATH+1];
2517 WCHAR wNewName[MAX_PATH+1];
2520 Perl_croak(aTHX_ PL_no_func, "link");
2522 pfnCreateHardLinkW =
2523 (BOOL (__stdcall *)(LPCWSTR, LPCWSTR, LPSECURITY_ATTRIBUTES))
2524 GetProcAddress(GetModuleHandle("kernel32.dll"), "CreateHardLinkW");
2525 if (pfnCreateHardLinkW == NULL)
2526 pfnCreateHardLinkW = Nt4CreateHardLinkW;
2528 if ((A2WHELPER(oldname, wOldName, sizeof(wOldName))) &&
2529 (A2WHELPER(newname, wNewName, sizeof(wNewName))) &&
2530 (wcscpy(wOldName, PerlDir_mapW(wOldName)),
2531 pfnCreateHardLinkW(PerlDir_mapW(wNewName), wOldName, NULL)))
2535 errno = (GetLastError() == ERROR_FILE_NOT_FOUND) ? ENOENT : EINVAL;
2540 win32_rename(const char *oname, const char *newname)
2542 WCHAR wOldName[MAX_PATH+1];
2543 WCHAR wNewName[MAX_PATH+1];
2544 char szOldName[MAX_PATH+1];
2545 char szNewName[MAX_PATH+1];
2549 /* XXX despite what the documentation says about MoveFileEx(),
2550 * it doesn't work under Windows95!
2553 DWORD dwFlags = MOVEFILE_COPY_ALLOWED;
2555 A2WHELPER(oname, wOldName, sizeof(wOldName));
2556 A2WHELPER(newname, wNewName, sizeof(wNewName));
2557 if (wcsicmp(wNewName, wOldName))
2558 dwFlags |= MOVEFILE_REPLACE_EXISTING;
2559 wcscpy(wOldName, PerlDir_mapW(wOldName));
2560 bResult = MoveFileExW(wOldName,PerlDir_mapW(wNewName), dwFlags);
2563 if (stricmp(newname, oname))
2564 dwFlags |= MOVEFILE_REPLACE_EXISTING;
2565 strcpy(szOldName, PerlDir_mapA(oname));
2566 bResult = MoveFileExA(szOldName,PerlDir_mapA(newname), dwFlags);
2569 DWORD err = GetLastError();
2571 case ERROR_BAD_NET_NAME:
2572 case ERROR_BAD_NETPATH:
2573 case ERROR_BAD_PATHNAME:
2574 case ERROR_FILE_NOT_FOUND:
2575 case ERROR_FILENAME_EXCED_RANGE:
2576 case ERROR_INVALID_DRIVE:
2577 case ERROR_NO_MORE_FILES:
2578 case ERROR_PATH_NOT_FOUND:
2591 char szTmpName[MAX_PATH+1];
2592 char dname[MAX_PATH+1];
2593 char *endname = Nullch;
2595 DWORD from_attr, to_attr;
2597 strcpy(szOldName, PerlDir_mapA(oname));
2598 strcpy(szNewName, PerlDir_mapA(newname));
2600 /* if oname doesn't exist, do nothing */
2601 from_attr = GetFileAttributes(szOldName);
2602 if (from_attr == 0xFFFFFFFF) {
2607 /* if newname exists, rename it to a temporary name so that we
2608 * don't delete it in case oname happens to be the same file
2609 * (but perhaps accessed via a different path)
2611 to_attr = GetFileAttributes(szNewName);
2612 if (to_attr != 0xFFFFFFFF) {
2613 /* if newname is a directory, we fail
2614 * XXX could overcome this with yet more convoluted logic */
2615 if (to_attr & FILE_ATTRIBUTE_DIRECTORY) {
2619 tmplen = strlen(szNewName);
2620 strcpy(szTmpName,szNewName);
2621 endname = szTmpName+tmplen;
2622 for (; endname > szTmpName ; --endname) {
2623 if (*endname == '/' || *endname == '\\') {
2628 if (endname > szTmpName)
2629 endname = strcpy(dname,szTmpName);
2633 /* get a temporary filename in same directory
2634 * XXX is this really the best we can do? */
2635 if (!GetTempFileName((LPCTSTR)endname, "plr", 0, szTmpName)) {
2639 DeleteFile(szTmpName);
2641 retval = rename(szNewName, szTmpName);
2648 /* rename oname to newname */
2649 retval = rename(szOldName, szNewName);
2651 /* if we created a temporary file before ... */
2652 if (endname != Nullch) {
2653 /* ...and rename succeeded, delete temporary file/directory */
2655 DeleteFile(szTmpName);
2656 /* else restore it to what it was */
2658 (void)rename(szTmpName, szNewName);
2665 win32_setmode(int fd, int mode)
2667 return setmode(fd, mode);
2671 win32_lseek(int fd, long offset, int origin)
2673 return lseek(fd, offset, origin);
2683 win32_open(const char *path, int flag, ...)
2688 WCHAR wBuffer[MAX_PATH+1];
2691 pmode = va_arg(ap, int);
2694 if (stricmp(path, "/dev/null")==0)
2698 A2WHELPER(path, wBuffer, sizeof(wBuffer));
2699 return _wopen(PerlDir_mapW(wBuffer), flag, pmode);
2701 return open(PerlDir_mapA(path), flag, pmode);
2723 win32_dup2(int fd1,int fd2)
2725 return dup2(fd1,fd2);
2728 #ifdef PERL_MSVCRT_READFIX
2730 #define LF 10 /* line feed */
2731 #define CR 13 /* carriage return */
2732 #define CTRLZ 26 /* ctrl-z means eof for text */
2733 #define FOPEN 0x01 /* file handle open */
2734 #define FEOFLAG 0x02 /* end of file has been encountered */
2735 #define FCRLF 0x04 /* CR-LF across read buffer (in text mode) */
2736 #define FPIPE 0x08 /* file handle refers to a pipe */
2737 #define FAPPEND 0x20 /* file handle opened O_APPEND */
2738 #define FDEV 0x40 /* file handle refers to device */
2739 #define FTEXT 0x80 /* file handle is in text mode */
2740 #define MAX_DESCRIPTOR_COUNT (64*32) /* this is the maximun that MSVCRT can handle */
2743 _fixed_read(int fh, void *buf, unsigned cnt)
2745 int bytes_read; /* number of bytes read */
2746 char *buffer; /* buffer to read to */
2747 int os_read; /* bytes read on OS call */
2748 char *p, *q; /* pointers into buffer */
2749 char peekchr; /* peek-ahead character */
2750 ULONG filepos; /* file position after seek */
2751 ULONG dosretval; /* o.s. return value */
2753 /* validate handle */
2754 if (((unsigned)fh >= (unsigned)MAX_DESCRIPTOR_COUNT) ||
2755 !(_osfile(fh) & FOPEN))
2757 /* out of range -- return error */
2759 _doserrno = 0; /* not o.s. error */
2764 * If lockinitflag is FALSE, assume fd is device
2765 * lockinitflag is set to TRUE by open.
2767 if (_pioinfo(fh)->lockinitflag)
2768 EnterCriticalSection(&(_pioinfo(fh)->lock)); /* lock file */
2770 bytes_read = 0; /* nothing read yet */
2771 buffer = (char*)buf;
2773 if (cnt == 0 || (_osfile(fh) & FEOFLAG)) {
2774 /* nothing to read or at EOF, so return 0 read */
2778 if ((_osfile(fh) & (FPIPE|FDEV)) && _pipech(fh) != LF) {
2779 /* a pipe/device and pipe lookahead non-empty: read the lookahead
2781 *buffer++ = _pipech(fh);
2784 _pipech(fh) = LF; /* mark as empty */
2789 if (!ReadFile((HANDLE)_osfhnd(fh), buffer, cnt, (LPDWORD)&os_read, NULL))
2791 /* ReadFile has reported an error. recognize two special cases.
2793 * 1. map ERROR_ACCESS_DENIED to EBADF
2795 * 2. just return 0 if ERROR_BROKEN_PIPE has occurred. it
2796 * means the handle is a read-handle on a pipe for which
2797 * all write-handles have been closed and all data has been
2800 if ((dosretval = GetLastError()) == ERROR_ACCESS_DENIED) {
2801 /* wrong read/write mode should return EBADF, not EACCES */
2803 _doserrno = dosretval;
2807 else if (dosretval == ERROR_BROKEN_PIPE) {
2817 bytes_read += os_read; /* update bytes read */
2819 if (_osfile(fh) & FTEXT) {
2820 /* now must translate CR-LFs to LFs in the buffer */
2822 /* set CRLF flag to indicate LF at beginning of buffer */
2823 /* if ((os_read != 0) && (*(char *)buf == LF)) */
2824 /* _osfile(fh) |= FCRLF; */
2826 /* _osfile(fh) &= ~FCRLF; */
2828 _osfile(fh) &= ~FCRLF;
2830 /* convert chars in the buffer: p is src, q is dest */
2832 while (p < (char *)buf + bytes_read) {
2834 /* if fh is not a device, set ctrl-z flag */
2835 if (!(_osfile(fh) & FDEV))
2836 _osfile(fh) |= FEOFLAG;
2837 break; /* stop translating */
2842 /* *p is CR, so must check next char for LF */
2843 if (p < (char *)buf + bytes_read - 1) {
2846 *q++ = LF; /* convert CR-LF to LF */
2849 *q++ = *p++; /* store char normally */
2852 /* This is the hard part. We found a CR at end of
2853 buffer. We must peek ahead to see if next char
2858 if (!ReadFile((HANDLE)_osfhnd(fh), &peekchr, 1,
2859 (LPDWORD)&os_read, NULL))
2860 dosretval = GetLastError();
2862 if (dosretval != 0 || os_read == 0) {
2863 /* couldn't read ahead, store CR */
2867 /* peekchr now has the extra character -- we now
2868 have several possibilities:
2869 1. disk file and char is not LF; just seek back
2871 2. disk file and char is LF; store LF, don't seek back
2872 3. pipe/device and char is LF; store LF.
2873 4. pipe/device and char isn't LF, store CR and
2874 put char in pipe lookahead buffer. */
2875 if (_osfile(fh) & (FDEV|FPIPE)) {
2876 /* non-seekable device */
2881 _pipech(fh) = peekchr;
2886 if (peekchr == LF) {
2887 /* nothing read yet; must make some
2890 /* turn on this flag for tell routine */
2891 _osfile(fh) |= FCRLF;
2894 HANDLE osHandle; /* o.s. handle value */
2896 if ((osHandle = (HANDLE)_get_osfhandle(fh)) != (HANDLE)-1)
2898 if ((filepos = SetFilePointer(osHandle, -1, NULL, FILE_CURRENT)) == -1)
2899 dosretval = GetLastError();
2910 /* we now change bytes_read to reflect the true number of chars
2912 bytes_read = q - (char *)buf;
2916 if (_pioinfo(fh)->lockinitflag)
2917 LeaveCriticalSection(&(_pioinfo(fh)->lock)); /* unlock file */
2922 #endif /* PERL_MSVCRT_READFIX */
2925 win32_read(int fd, void *buf, unsigned int cnt)
2927 #ifdef PERL_MSVCRT_READFIX
2928 return _fixed_read(fd, buf, cnt);
2930 return read(fd, buf, cnt);
2935 win32_write(int fd, const void *buf, unsigned int cnt)
2937 return write(fd, buf, cnt);
2941 win32_mkdir(const char *dir, int mode)
2945 WCHAR wBuffer[MAX_PATH+1];
2946 A2WHELPER(dir, wBuffer, sizeof(wBuffer));
2947 return _wmkdir(PerlDir_mapW(wBuffer));
2949 return mkdir(PerlDir_mapA(dir)); /* just ignore mode */
2953 win32_rmdir(const char *dir)
2957 WCHAR wBuffer[MAX_PATH+1];
2958 A2WHELPER(dir, wBuffer, sizeof(wBuffer));
2959 return _wrmdir(PerlDir_mapW(wBuffer));
2961 return rmdir(PerlDir_mapA(dir));
2965 win32_chdir(const char *dir)
2969 WCHAR wBuffer[MAX_PATH+1];
2970 A2WHELPER(dir, wBuffer, sizeof(wBuffer));
2971 return _wchdir(wBuffer);
2977 win32_access(const char *path, int mode)
2981 WCHAR wBuffer[MAX_PATH+1];
2982 A2WHELPER(path, wBuffer, sizeof(wBuffer));
2983 return _waccess(PerlDir_mapW(wBuffer), mode);
2985 return access(PerlDir_mapA(path), mode);
2989 win32_chmod(const char *path, int mode)
2993 WCHAR wBuffer[MAX_PATH+1];
2994 A2WHELPER(path, wBuffer, sizeof(wBuffer));
2995 return _wchmod(PerlDir_mapW(wBuffer), mode);
2997 return chmod(PerlDir_mapA(path), mode);
3002 create_command_line(const char* command, const char * const *args)
3006 char *cmd, *ptr, *arg;
3007 STRLEN len = strlen(command) + 1;
3009 for (index = 0; (ptr = (char*)args[index]) != NULL; ++index)
3010 len += strlen(ptr) + 1;
3012 New(1310, cmd, len, char);
3014 strcpy(ptr, command);
3016 for (index = 0; (arg = (char*)args[index]) != NULL; ++index) {
3026 qualified_path(const char *cmd)
3030 char *fullcmd, *curfullcmd;
3036 fullcmd = (char*)cmd;
3038 if (*fullcmd == '/' || *fullcmd == '\\')
3045 pathstr = win32_getenv("PATH");
3046 New(0, fullcmd, MAX_PATH+1, char);
3047 curfullcmd = fullcmd;
3052 /* start by appending the name to the current prefix */
3053 strcpy(curfullcmd, cmd);
3054 curfullcmd += cmdlen;
3056 /* if it doesn't end with '.', or has no extension, try adding
3057 * a trailing .exe first */
3058 if (cmd[cmdlen-1] != '.'
3059 && (cmdlen < 4 || cmd[cmdlen-4] != '.'))
3061 strcpy(curfullcmd, ".exe");
3062 res = GetFileAttributes(fullcmd);
3063 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
3068 /* that failed, try the bare name */
3069 res = GetFileAttributes(fullcmd);
3070 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
3073 /* quit if no other path exists, or if cmd already has path */
3074 if (!pathstr || !*pathstr || has_slash)
3077 /* skip leading semis */
3078 while (*pathstr == ';')
3081 /* build a new prefix from scratch */
3082 curfullcmd = fullcmd;
3083 while (*pathstr && *pathstr != ';') {
3084 if (*pathstr == '"') { /* foo;"baz;etc";bar */
3085 pathstr++; /* skip initial '"' */
3086 while (*pathstr && *pathstr != '"') {
3087 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
3088 *curfullcmd++ = *pathstr;
3092 pathstr++; /* skip trailing '"' */
3095 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
3096 *curfullcmd++ = *pathstr;
3101 pathstr++; /* skip trailing semi */
3102 if (curfullcmd > fullcmd /* append a dir separator */
3103 && curfullcmd[-1] != '/' && curfullcmd[-1] != '\\')
3105 *curfullcmd++ = '\\';
3113 /* The following are just place holders.
3114 * Some hosts may provide and environment that the OS is
3115 * not tracking, therefore, these host must provide that
3116 * environment and the current directory to CreateProcess
3126 free_childenv(void* d)
3135 char szfilename[(MAX_PATH+1)*2];
3137 WCHAR wfilename[MAX_PATH+1];
3138 GetCurrentDirectoryW(MAX_PATH+1, wfilename);
3139 W2AHELPER(wfilename, szfilename, sizeof(szfilename));
3142 GetCurrentDirectoryA(MAX_PATH+1, szfilename);
3145 New(0, ptr, strlen(szfilename)+1, char);
3146 strcpy(ptr, szfilename);
3151 free_childdir(char* d)
3158 /* XXX this needs to be made more compatible with the spawnvp()
3159 * provided by the various RTLs. In particular, searching for
3160 * *.{com,bat,cmd} files (as done by the RTLs) is unimplemented.
3161 * This doesn't significantly affect perl itself, because we
3162 * always invoke things using PERL5SHELL if a direct attempt to
3163 * spawn the executable fails.
3165 * XXX splitting and rejoining the commandline between do_aspawn()
3166 * and win32_spawnvp() could also be avoided.
3170 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
3172 #ifdef USE_RTL_SPAWNVP
3173 return spawnvp(mode, cmdname, (char * const *)argv);
3180 STARTUPINFO StartupInfo;
3181 PROCESS_INFORMATION ProcessInformation;
3184 char *cmd = create_command_line(cmdname, strcmp(cmdname, argv[0]) == 0
3186 char *fullcmd = Nullch;
3188 env = PerlEnv_get_childenv();
3189 dir = PerlEnv_get_childdir();
3192 case P_NOWAIT: /* asynch + remember result */
3193 if (w32_num_children >= MAXIMUM_WAIT_OBJECTS) {
3199 case P_WAIT: /* synchronous execution */
3201 default: /* invalid mode */
3206 memset(&StartupInfo,0,sizeof(StartupInfo));
3207 StartupInfo.cb = sizeof(StartupInfo);
3208 memset(&tbl,0,sizeof(tbl));
3209 PerlEnv_get_child_IO(&tbl);
3210 StartupInfo.dwFlags = tbl.dwFlags;
3211 StartupInfo.dwX = tbl.dwX;
3212 StartupInfo.dwY = tbl.dwY;
3213 StartupInfo.dwXSize = tbl.dwXSize;
3214 StartupInfo.dwYSize = tbl.dwYSize;
3215 StartupInfo.dwXCountChars = tbl.dwXCountChars;
3216 StartupInfo.dwYCountChars = tbl.dwYCountChars;
3217 StartupInfo.dwFillAttribute = tbl.dwFillAttribute;
3218 StartupInfo.wShowWindow = tbl.wShowWindow;
3219 StartupInfo.hStdInput = tbl.childStdIn;
3220 StartupInfo.hStdOutput = tbl.childStdOut;
3221 StartupInfo.hStdError = tbl.childStdErr;
3222 if (StartupInfo.hStdInput != INVALID_HANDLE_VALUE &&
3223 StartupInfo.hStdOutput != INVALID_HANDLE_VALUE &&
3224 StartupInfo.hStdError != INVALID_HANDLE_VALUE)
3226 StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
3229 create |= CREATE_NEW_CONSOLE;
3233 if (!CreateProcess(cmdname, /* search PATH to find executable */
3234 cmd, /* executable, and its arguments */
3235 NULL, /* process attributes */
3236 NULL, /* thread attributes */
3237 TRUE, /* inherit handles */
3238 create, /* creation flags */
3239 (LPVOID)env, /* inherit environment */
3240 dir, /* inherit cwd */
3242 &ProcessInformation))
3244 /* initial NULL argument to CreateProcess() does a PATH
3245 * search, but it always first looks in the directory
3246 * where the current process was started, which behavior
3247 * is undesirable for backward compatibility. So we
3248 * jump through our own hoops by picking out the path
3249 * we really want it to use. */
3251 fullcmd = qualified_path(cmdname);
3262 if (mode == P_NOWAIT) {
3263 /* asynchronous spawn -- store handle, return PID */
3264 w32_child_handles[w32_num_children] = ProcessInformation.hProcess;
3265 w32_child_pids[w32_num_children] = ProcessInformation.dwProcessId;
3266 ret = (int)ProcessInformation.dwProcessId;
3271 WaitForSingleObject(ProcessInformation.hProcess, INFINITE);
3272 GetExitCodeProcess(ProcessInformation.hProcess, &status);
3274 CloseHandle(ProcessInformation.hProcess);
3277 CloseHandle(ProcessInformation.hThread);
3280 PerlEnv_free_childenv(env);
3281 PerlEnv_free_childdir(dir);
3289 win32_execv(const char *cmdname, const char *const *argv)
3293 /* if this is a pseudo-forked child, we just want to spawn
3294 * the new program, and return */
3296 return spawnv(P_WAIT, cmdname, (char *const *)argv);
3298 return execv(cmdname, (char *const *)argv);
3302 win32_execvp(const char *cmdname, const char *const *argv)
3306 /* if this is a pseudo-forked child, we just want to spawn
3307 * the new program, and return */
3309 return win32_spawnvp(P_WAIT, cmdname, (char *const *)argv);
3311 return execvp(cmdname, (char *const *)argv);
3315 win32_perror(const char *str)
3321 win32_setbuf(FILE *pf, char *buf)
3327 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
3329 return setvbuf(pf, buf, type, size);
3333 win32_flushall(void)
3339 win32_fcloseall(void)
3345 win32_fgets(char *s, int n, FILE *pf)
3347 return fgets(s, n, pf);
3357 win32_fgetc(FILE *pf)
3363 win32_putc(int c, FILE *pf)
3369 win32_puts(const char *s)
3381 win32_putchar(int c)
3388 #ifndef USE_PERL_SBRK
3390 static char *committed = NULL;
3391 static char *base = NULL;
3392 static char *reserved = NULL;
3393 static char *brk = NULL;
3394 static DWORD pagesize = 0;
3395 static DWORD allocsize = 0;
3403 GetSystemInfo(&info);
3404 /* Pretend page size is larger so we don't perpetually
3405 * call the OS to commit just one page ...
3407 pagesize = info.dwPageSize << 3;
3408 allocsize = info.dwAllocationGranularity;
3410 /* This scheme fails eventually if request for contiguous
3411 * block is denied so reserve big blocks - this is only
3412 * address space not memory ...
3414 if (brk+need >= reserved)
3416 DWORD size = 64*1024*1024;
3418 if (committed && reserved && committed < reserved)
3420 /* Commit last of previous chunk cannot span allocations */
3421 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
3423 committed = reserved;
3425 /* Reserve some (more) space
3426 * Note this is a little sneaky, 1st call passes NULL as reserved
3427 * so lets system choose where we start, subsequent calls pass
3428 * the old end address so ask for a contiguous block
3430 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
3433 reserved = addr+size;
3448 if (brk > committed)
3450 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
3451 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
3466 win32_malloc(size_t size)
3468 return malloc(size);
3472 win32_calloc(size_t numitems, size_t size)
3474 return calloc(numitems,size);
3478 win32_realloc(void *block, size_t size)
3480 return realloc(block,size);
3484 win32_free(void *block)
3491 win32_open_osfhandle(long handle, int flags)
3493 #ifdef USE_FIXED_OSFHANDLE
3495 return my_open_osfhandle(handle, flags);
3497 return _open_osfhandle(handle, flags);
3501 win32_get_osfhandle(int fd)
3503 return _get_osfhandle(fd);
3507 win32_dynaload(const char* filename)
3512 WCHAR wfilename[MAX_PATH+1];
3513 A2WHELPER(filename, wfilename, sizeof(wfilename));
3514 hModule = LoadLibraryExW(PerlDir_mapW(wfilename), NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
3517 hModule = LoadLibraryExA(PerlDir_mapA(filename), NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
3530 /* Make the host for current directory */
3531 char* ptr = PerlEnv_get_childdir();
3534 * then it worked, set PV valid,
3535 * else return 'undef'
3538 SV *sv = sv_newmortal();
3540 PerlEnv_free_childdir(ptr);
3555 Perl_croak(aTHX_ "usage: Win32::SetCurrentDirectory($cwd)");
3556 if (!PerlDir_chdir(SvPV_nolen(ST(0))))
3563 XS(w32_GetNextAvailDrive)
3567 char root[] = "_:\\";
3572 if (GetDriveType(root) == 1) {
3581 XS(w32_GetLastError)
3585 XSRETURN_IV(GetLastError());
3589 XS(w32_SetLastError)
3593 Perl_croak(aTHX_ "usage: Win32::SetLastError($error)");
3594 SetLastError(SvIV(ST(0)));
3602 char *name = w32_getlogin_buffer;
3603 DWORD size = sizeof(w32_getlogin_buffer);
3605 if (GetUserName(name,&size)) {
3606 /* size includes NULL */
3607 ST(0) = sv_2mortal(newSVpvn(name,size-1));
3617 char name[MAX_COMPUTERNAME_LENGTH+1];
3618 DWORD size = sizeof(name);
3620 if (GetComputerName(name,&size)) {
3621 /* size does NOT include NULL :-( */
3622 ST(0) = sv_2mortal(newSVpvn(name,size));
3633 HINSTANCE hNetApi32 = LoadLibrary("netapi32.dll");
3634 DWORD (__stdcall *pfnNetApiBufferFree)(LPVOID Buffer);
3635 DWORD (__stdcall *pfnNetWkstaGetInfo)(LPWSTR servername, DWORD level,
3639 pfnNetApiBufferFree = (DWORD (__stdcall *)(void *))
3640 GetProcAddress(hNetApi32, "NetApiBufferFree");
3641 pfnNetWkstaGetInfo = (DWORD (__stdcall *)(LPWSTR, DWORD, void *))
3642 GetProcAddress(hNetApi32, "NetWkstaGetInfo");
3645 if (hNetApi32 && pfnNetWkstaGetInfo && pfnNetApiBufferFree) {
3646 /* this way is more reliable, in case user has a local account. */
3648 DWORD dnamelen = sizeof(dname);
3650 DWORD wki100_platform_id;
3651 LPWSTR wki100_computername;
3652 LPWSTR wki100_langroup;
3653 DWORD wki100_ver_major;
3654 DWORD wki100_ver_minor;
3656 /* NERR_Success *is* 0*/
3657 if (0 == pfnNetWkstaGetInfo(NULL, 100, &pwi)) {
3658 if (pwi->wki100_langroup && *(pwi->wki100_langroup)) {
3659 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_langroup,
3660 -1, (LPSTR)dname, dnamelen, NULL, NULL);
3663 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_computername,
3664 -1, (LPSTR)dname, dnamelen, NULL, NULL);
3666 pfnNetApiBufferFree(pwi);
3667 FreeLibrary(hNetApi32);
3670 FreeLibrary(hNetApi32);
3673 /* Win95 doesn't have NetWksta*(), so do it the old way */
3675 DWORD size = sizeof(name);
3677 FreeLibrary(hNetApi32);
3678 if (GetUserName(name,&size)) {
3679 char sid[ONE_K_BUFSIZE];
3680 DWORD sidlen = sizeof(sid);
3682 DWORD dnamelen = sizeof(dname);
3684 if (LookupAccountName(NULL, name, (PSID)&sid, &sidlen,
3685 dname, &dnamelen, &snu)) {
3686 XSRETURN_PV(dname); /* all that for this */
3698 DWORD flags, filecomplen;
3699 if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
3700 &flags, fsname, sizeof(fsname))) {
3701 if (GIMME_V == G_ARRAY) {
3702 XPUSHs(sv_2mortal(newSVpvn(fsname,strlen(fsname))));
3703 XPUSHs(sv_2mortal(newSViv(flags)));
3704 XPUSHs(sv_2mortal(newSViv(filecomplen)));
3709 XSRETURN_PV(fsname);
3715 XS(w32_GetOSVersion)
3718 OSVERSIONINFOA osver;
3721 OSVERSIONINFOW osverw;
3722 char szCSDVersion[sizeof(osverw.szCSDVersion)];
3723 osverw.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
3724 if (!GetVersionExW(&osverw)) {
3727 W2AHELPER(osverw.szCSDVersion, szCSDVersion, sizeof(szCSDVersion));
3728 XPUSHs(newSVpvn(szCSDVersion, strlen(szCSDVersion)));
3729 osver.dwMajorVersion = osverw.dwMajorVersion;
3730 osver.dwMinorVersion = osverw.dwMinorVersion;
3731 osver.dwBuildNumber = osverw.dwBuildNumber;
3732 osver.dwPlatformId = osverw.dwPlatformId;
3735 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOA);
3736 if (!GetVersionExA(&osver)) {
3739 XPUSHs(newSVpvn(osver.szCSDVersion, strlen(osver.szCSDVersion)));
3741 XPUSHs(newSViv(osver.dwMajorVersion));
3742 XPUSHs(newSViv(osver.dwMinorVersion));
3743 XPUSHs(newSViv(osver.dwBuildNumber));
3744 XPUSHs(newSViv(osver.dwPlatformId));
3753 XSRETURN_IV(IsWinNT());
3761 XSRETURN_IV(IsWin95());
3765 XS(w32_FormatMessage)
3769 char msgbuf[ONE_K_BUFSIZE];
3772 Perl_croak(aTHX_ "usage: Win32::FormatMessage($errno)");
3775 WCHAR wmsgbuf[ONE_K_BUFSIZE];
3776 if (FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM,
3777 &source, SvIV(ST(0)), 0,
3778 wmsgbuf, ONE_K_BUFSIZE-1, NULL))
3780 W2AHELPER(wmsgbuf, msgbuf, sizeof(msgbuf));
3781 XSRETURN_PV(msgbuf);
3785 if (FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM,
3786 &source, SvIV(ST(0)), 0,
3787 msgbuf, sizeof(msgbuf)-1, NULL))
3788 XSRETURN_PV(msgbuf);
3799 PROCESS_INFORMATION stProcInfo;
3800 STARTUPINFO stStartInfo;
3801 BOOL bSuccess = FALSE;
3804 Perl_croak(aTHX_ "usage: Win32::Spawn($cmdName, $args, $PID)");
3806 cmd = SvPV_nolen(ST(0));
3807 args = SvPV_nolen(ST(1));
3809 memset(&stStartInfo, 0, sizeof(stStartInfo)); /* Clear the block */
3810 stStartInfo.cb = sizeof(stStartInfo); /* Set the structure size */
3811 stStartInfo.dwFlags = STARTF_USESHOWWINDOW; /* Enable wShowWindow control */
3812 stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE; /* Start min (normal) */
3815 cmd, /* Image path */
3816 args, /* Arguments for command line */
3817 NULL, /* Default process security */
3818 NULL, /* Default thread security */
3819 FALSE, /* Must be TRUE to use std handles */
3820 NORMAL_PRIORITY_CLASS, /* No special scheduling */
3821 NULL, /* Inherit our environment block */
3822 NULL, /* Inherit our currrent directory */
3823 &stStartInfo, /* -> Startup info */
3824 &stProcInfo)) /* <- Process info (if OK) */
3826 CloseHandle(stProcInfo.hThread);/* library source code does this. */
3827 sv_setiv(ST(2), stProcInfo.dwProcessId);
3830 XSRETURN_IV(bSuccess);
3834 XS(w32_GetTickCount)
3837 DWORD msec = GetTickCount();
3845 XS(w32_GetShortPathName)
3852 Perl_croak(aTHX_ "usage: Win32::GetShortPathName($longPathName)");
3854 shortpath = sv_mortalcopy(ST(0));
3855 SvUPGRADE(shortpath, SVt_PV);
3856 /* src == target is allowed */
3858 len = GetShortPathName(SvPVX(shortpath),
3861 } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
3863 SvCUR_set(shortpath,len);
3871 XS(w32_GetFullPathName)
3880 Perl_croak(aTHX_ "usage: Win32::GetFullPathName($filename)");
3883 fullpath = sv_mortalcopy(filename);
3884 SvUPGRADE(fullpath, SVt_PV);
3886 len = GetFullPathName(SvPVX(filename),
3890 } while (len >= SvLEN(fullpath) && sv_grow(fullpath,len+1));
3892 if (GIMME_V == G_ARRAY) {
3894 XST_mPV(1,filepart);
3895 len = filepart - SvPVX(fullpath);
3898 SvCUR_set(fullpath,len);
3906 XS(w32_GetLongPathName)
3910 char tmpbuf[MAX_PATH+1];
3915 Perl_croak(aTHX_ "usage: Win32::GetLongPathName($pathname)");
3918 pathstr = SvPV(path,len);
3919 strcpy(tmpbuf, pathstr);
3920 pathstr = win32_longpath(tmpbuf);
3922 ST(0) = sv_2mortal(newSVpvn(pathstr, strlen(pathstr)));
3933 Perl_croak(aTHX_ "usage: Win32::Sleep($milliseconds)");
3944 Perl_croak(aTHX_ "usage: Win32::CopyFile($from, $to, $overwrite)");
3946 WCHAR wSourceFile[MAX_PATH+1];
3947 WCHAR wDestFile[MAX_PATH+1];
3948 A2WHELPER(SvPV_nolen(ST(0)), wSourceFile, sizeof(wSourceFile));
3949 wcscpy(wSourceFile, PerlDir_mapW(wSourceFile));
3950 A2WHELPER(SvPV_nolen(ST(1)), wDestFile, sizeof(wDestFile));
3951 bResult = CopyFileW(wSourceFile, PerlDir_mapW(wDestFile), !SvTRUE(ST(2)));
3954 char szSourceFile[MAX_PATH+1];
3955 strcpy(szSourceFile, PerlDir_mapA(SvPV_nolen(ST(0))));
3956 bResult = CopyFileA(szSourceFile, PerlDir_mapA(SvPV_nolen(ST(1))), !SvTRUE(ST(2)));
3965 Perl_init_os_extras(void)
3968 char *file = __FILE__;
3971 /* these names are Activeware compatible */
3972 newXS("Win32::GetCwd", w32_GetCwd, file);
3973 newXS("Win32::SetCwd", w32_SetCwd, file);
3974 newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
3975 newXS("Win32::GetLastError", w32_GetLastError, file);
3976 newXS("Win32::SetLastError", w32_SetLastError, file);
3977 newXS("Win32::LoginName", w32_LoginName, file);
3978 newXS("Win32::NodeName", w32_NodeName, file);
3979 newXS("Win32::DomainName", w32_DomainName, file);
3980 newXS("Win32::FsType", w32_FsType, file);
3981 newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
3982 newXS("Win32::IsWinNT", w32_IsWinNT, file);
3983 newXS("Win32::IsWin95", w32_IsWin95, file);
3984 newXS("Win32::FormatMessage", w32_FormatMessage, file);
3985 newXS("Win32::Spawn", w32_Spawn, file);
3986 newXS("Win32::GetTickCount", w32_GetTickCount, file);
3987 newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
3988 newXS("Win32::GetFullPathName", w32_GetFullPathName, file);
3989 newXS("Win32::GetLongPathName", w32_GetLongPathName, file);
3990 newXS("Win32::CopyFile", w32_CopyFile, file);
3991 newXS("Win32::Sleep", w32_Sleep, file);
3993 /* XXX Bloat Alert! The following Activeware preloads really
3994 * ought to be part of Win32::Sys::*, so they're not included
3997 /* LookupAccountName
3999 * InitiateSystemShutdown
4000 * AbortSystemShutdown
4001 * ExpandEnvrironmentStrings
4006 Perl_win32_init(int *argcp, char ***argvp)
4008 /* Disable floating point errors, Perl will trap the ones we
4009 * care about. VC++ RTL defaults to switching these off
4010 * already, but the Borland RTL doesn't. Since we don't
4011 * want to be at the vendor's whim on the default, we set
4012 * it explicitly here.
4014 #if !defined(_ALPHA_) && !defined(__GNUC__)
4015 _control87(MCW_EM, MCW_EM);
4021 win32_get_child_IO(child_IO_table* ptbl)
4023 ptbl->childStdIn = GetStdHandle(STD_INPUT_HANDLE);
4024 ptbl->childStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
4025 ptbl->childStdErr = GetStdHandle(STD_ERROR_HANDLE);
4028 #ifdef HAVE_INTERP_INTERN
4031 # undef Perl_sys_intern_init
4032 # define Perl_sys_intern_init CPerlObj::Perl_sys_intern_init
4033 # undef Perl_sys_intern_dup
4034 # define Perl_sys_intern_dup CPerlObj::Perl_sys_intern_dup
4035 # undef Perl_sys_intern_clear
4036 # define Perl_sys_intern_clear CPerlObj::Perl_sys_intern_clear
4041 Perl_sys_intern_init(pTHX)
4043 w32_perlshell_tokens = Nullch;
4044 w32_perlshell_vec = (char**)NULL;
4045 w32_perlshell_items = 0;
4046 w32_fdpid = newAV();
4047 New(1313, w32_children, 1, child_tab);
4048 w32_num_children = 0;
4049 # ifdef USE_ITHREADS
4051 New(1313, w32_pseudo_children, 1, child_tab);
4052 w32_num_pseudo_children = 0;
4054 w32_init_socktype = 0;
4057 # ifdef USE_ITHREADS
4060 Perl_sys_intern_dup(pTHX_ struct interp_intern *src, struct interp_intern *dst)
4062 dst->perlshell_tokens = Nullch;
4063 dst->perlshell_vec = (char**)NULL;
4064 dst->perlshell_items = 0;
4065 dst->fdpid = newAV();
4066 Newz(1313, dst->children, 1, child_tab);
4068 Newz(1313, dst->pseudo_children, 1, child_tab);
4069 dst->thr_intern.Winit_socktype = src->thr_intern.Winit_socktype;
4073 Perl_sys_intern_clear(pTHX)
4075 Safefree(w32_perlshell_tokens);
4076 Safefree(w32_perlshell_vec);
4077 /* NOTE: w32_fdpid is freed by sv_clean_all() */
4078 Safefree(w32_children);
4079 # ifdef USE_ITHREADS
4080 Safefree(w32_pseudo_children);
4083 # endif /* USE_ITHREADS */
4084 #endif /* HAVE_INTERP_INTERN */
4092 win32_free_argvw(pTHXo_ void *ptr)
4094 char** argv = (char**)ptr;
4102 win32_argv2utf8(int argc, char** argv)
4107 LPWSTR* lpwStr = CommandLineToArgvW(GetCommandLineW(), &wargc);
4108 if (lpwStr && argc) {
4110 length = WideCharToMultiByte(CP_UTF8, 0, lpwStr[--wargc], -1, NULL, 0, NULL, NULL);
4111 Newz(0, psz, length, char);
4112 WideCharToMultiByte(CP_UTF8, 0, lpwStr[wargc], -1, psz, length, NULL, NULL);
4115 call_atexit(win32_free_argvw, argv);
4117 GlobalFree((HGLOBAL)lpwStr);