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.
10 #define PERLIO_NOT_STDIO 0
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 #if !defined(PERLIO_IS_STDIO) && !defined(USE_SFIO)
37 #define PERL_NO_GET_CONTEXT
43 /* assert.h conflicts with #define of assert in perl.h */
50 #if defined(_MSC_VER) || defined(__MINGW32__)
51 #include <sys/utime.h>
56 /* Mingw32 defaults to globing command line
57 * So we turn it off like this:
62 #if defined(__MINGW32__)
63 /* Mingw32 is missing some prototypes */
64 FILE * _wfopen(LPCWSTR wszFileName, LPCWSTR wszMode);
65 FILE * _wfdopen(int nFd, LPCWSTR wszMode);
66 FILE * _freopen(LPCWSTR wszFileName, LPCWSTR wszMode, FILE * pOldStream);
71 #if defined(__BORLANDC__)
73 # define _utimbuf utimbuf
78 #define EXECF_SPAWN_NOWAIT 3
80 #if defined(PERL_IMPLICIT_SYS)
81 # undef win32_get_privlib
82 # define win32_get_privlib g_win32_get_privlib
83 # undef win32_get_sitelib
84 # define win32_get_sitelib g_win32_get_sitelib
85 # undef win32_get_vendorlib
86 # define win32_get_vendorlib g_win32_get_vendorlib
88 # define do_spawn g_do_spawn
90 # define getlogin g_getlogin
93 static void get_shell(void);
94 static long tokenize(const char *str, char **dest, char ***destv);
95 int do_spawn2(char *cmd, int exectype);
96 static BOOL has_shell_metachars(char *ptr);
97 static long filetime_to_clock(PFILETIME ft);
98 static BOOL filetime_from_time(PFILETIME ft, time_t t);
99 static char * get_emd_part(SV **leading, char *trailing, ...);
100 static void remove_dead_process(long deceased);
101 static long find_pid(int pid);
102 static char * qualified_path(const char *cmd);
103 static char * win32_get_xlib(const char *pl, const char *xlib,
104 const char *libname);
107 static void remove_dead_pseudo_process(long child);
108 static long find_pseudo_pid(int pid);
112 HANDLE w32_perldll_handle = INVALID_HANDLE_VALUE;
113 char w32_module_name[MAX_PATH+1];
116 static DWORD w32_platform = (DWORD)-1;
118 #define ONE_K_BUFSIZE 1024
123 return (win32_os_id() == VER_PLATFORM_WIN32_WINDOWS);
129 return (win32_os_id() == VER_PLATFORM_WIN32_NT);
133 set_w32_module_name(void)
136 GetModuleFileName((HMODULE)((w32_perldll_handle == INVALID_HANDLE_VALUE)
137 ? GetModuleHandle(NULL)
138 : w32_perldll_handle),
139 w32_module_name, sizeof(w32_module_name));
141 /* try to get full path to binary (which may be mangled when perl is
142 * run from a 16-bit app) */
143 /*PerlIO_printf(Perl_debug_log, "Before %s\n", w32_module_name);*/
144 (void)win32_longpath(w32_module_name);
145 /*PerlIO_printf(Perl_debug_log, "After %s\n", w32_module_name);*/
147 /* normalize to forward slashes */
148 ptr = w32_module_name;
156 /* *svp (if non-NULL) is expected to be POK (valid allocated SvPVX(*svp)) */
158 get_regstr_from(HKEY hkey, const char *valuename, SV **svp)
160 /* Retrieve a REG_SZ or REG_EXPAND_SZ from the registry */
163 const char *subkey = "Software\\Perl";
167 retval = RegOpenKeyEx(hkey, subkey, 0, KEY_READ, &handle);
168 if (retval == ERROR_SUCCESS) {
170 retval = RegQueryValueEx(handle, valuename, 0, &type, NULL, &datalen);
171 if (retval == ERROR_SUCCESS
172 && (type == REG_SZ || type == REG_EXPAND_SZ))
176 *svp = sv_2mortal(newSVpvn("",0));
177 SvGROW(*svp, datalen);
178 retval = RegQueryValueEx(handle, valuename, 0, NULL,
179 (PBYTE)SvPVX(*svp), &datalen);
180 if (retval == ERROR_SUCCESS) {
182 SvCUR_set(*svp,datalen-1);
190 /* *svp (if non-NULL) is expected to be POK (valid allocated SvPVX(*svp)) */
192 get_regstr(const char *valuename, SV **svp)
194 char *str = get_regstr_from(HKEY_CURRENT_USER, valuename, svp);
196 str = get_regstr_from(HKEY_LOCAL_MACHINE, valuename, svp);
200 /* *prev_pathp (if non-NULL) is expected to be POK (valid allocated SvPVX(sv)) */
202 get_emd_part(SV **prev_pathp, char *trailing_path, ...)
206 char mod_name[MAX_PATH+1];
210 int oldsize, newsize;
213 va_start(ap, trailing_path);
214 strip = va_arg(ap, char *);
216 sprintf(base, "%d.%d", (int)PERL_REVISION, (int)PERL_VERSION);
217 baselen = strlen(base);
219 if (!*w32_module_name) {
220 set_w32_module_name();
222 strcpy(mod_name, w32_module_name);
223 ptr = strrchr(mod_name, '/');
224 while (ptr && strip) {
225 /* look for directories to skip back */
228 ptr = strrchr(mod_name, '/');
229 /* avoid stripping component if there is no slash,
230 * or it doesn't match ... */
231 if (!ptr || stricmp(ptr+1, strip) != 0) {
232 /* ... but not if component matches m|5\.$patchlevel.*| */
233 if (!ptr || !(*strip == '5' && *(ptr+1) == '5'
234 && strncmp(strip, base, baselen) == 0
235 && strncmp(ptr+1, base, baselen) == 0))
241 strip = va_arg(ap, char *);
249 strcpy(++ptr, trailing_path);
251 /* only add directory if it exists */
252 if (GetFileAttributes(mod_name) != (DWORD) -1) {
253 /* directory exists */
256 *prev_pathp = sv_2mortal(newSVpvn("",0));
257 sv_catpvn(*prev_pathp, ";", 1);
258 sv_catpv(*prev_pathp, mod_name);
259 return SvPVX(*prev_pathp);
266 win32_get_privlib(const char *pl)
269 char *stdlib = "lib";
270 char buffer[MAX_PATH+1];
273 /* $stdlib = $HKCU{"lib-$]"} || $HKLM{"lib-$]"} || $HKCU{"lib"} || $HKLM{"lib"} || ""; */
274 sprintf(buffer, "%s-%s", stdlib, pl);
275 if (!get_regstr(buffer, &sv))
276 (void)get_regstr(stdlib, &sv);
278 /* $stdlib .= ";$EMD/../../lib" */
279 return get_emd_part(&sv, stdlib, ARCHNAME, "bin", Nullch);
283 win32_get_xlib(const char *pl, const char *xlib, const char *libname)
287 char pathstr[MAX_PATH+1];
293 /* $HKCU{"$xlib-$]"} || $HKLM{"$xlib-$]"} . ---; */
294 sprintf(regstr, "%s-%s", xlib, pl);
295 (void)get_regstr(regstr, &sv1);
298 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/$libname/$]/lib"; */
299 sprintf(pathstr, "%s/%s/lib", libname, pl);
300 (void)get_emd_part(&sv1, pathstr, ARCHNAME, "bin", pl, Nullch);
302 /* $HKCU{$xlib} || $HKLM{$xlib} . ---; */
303 (void)get_regstr(xlib, &sv2);
306 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/$libname/lib"; */
307 sprintf(pathstr, "%s/lib", libname);
308 (void)get_emd_part(&sv2, pathstr, ARCHNAME, "bin", pl, Nullch);
317 sv_catpvn(sv1, ";", 1);
324 win32_get_sitelib(const char *pl)
326 return win32_get_xlib(pl, "sitelib", "site");
329 #ifndef PERL_VENDORLIB_NAME
330 # define PERL_VENDORLIB_NAME "vendor"
334 win32_get_vendorlib(const char *pl)
336 return win32_get_xlib(pl, "vendorlib", PERL_VENDORLIB_NAME);
340 has_shell_metachars(char *ptr)
346 * Scan string looking for redirection (< or >) or pipe
347 * characters (|) that are not in a quoted string.
348 * Shell variable interpolation (%VAR%) can also happen inside strings.
380 #if !defined(PERL_IMPLICIT_SYS)
381 /* since the current process environment is being updated in util.c
382 * the library functions will get the correct environment
385 Perl_my_popen(pTHX_ char *cmd, char *mode)
388 #define fixcmd(x) { \
389 char *pspace = strchr((x),' '); \
392 while (p < pspace) { \
403 PERL_FLUSHALL_FOR_CHILD;
404 return win32_popen(cmd, mode);
408 Perl_my_pclose(pTHX_ PerlIO *fp)
410 return win32_pclose(fp);
414 DllExport unsigned long
417 static OSVERSIONINFO osver;
419 if (osver.dwPlatformId != w32_platform) {
420 memset(&osver, 0, sizeof(OSVERSIONINFO));
421 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
422 GetVersionEx(&osver);
423 w32_platform = osver.dwPlatformId;
425 return (unsigned long)w32_platform;
435 return -((int)w32_pseudo_id);
438 /* Windows 9x appears to always reports a pid for threads and processes
439 * that has the high bit set. So we treat the lower 31 bits as the
440 * "real" PID for Perl's purposes. */
441 if (IsWin95() && pid < 0)
446 /* Tokenize a string. Words are null-separated, and the list
447 * ends with a doubled null. Any character (except null and
448 * including backslash) may be escaped by preceding it with a
449 * backslash (the backslash will be stripped).
450 * Returns number of words in result buffer.
453 tokenize(const char *str, char **dest, char ***destv)
455 char *retstart = Nullch;
456 char **retvstart = 0;
460 int slen = strlen(str);
462 register char **retv;
463 New(1307, ret, slen+2, char);
464 New(1308, retv, (slen+3)/2, char*);
472 if (*ret == '\\' && *str)
474 else if (*ret == ' ') {
490 retvstart[items] = Nullch;
503 if (!w32_perlshell_tokens) {
504 /* we don't use COMSPEC here for two reasons:
505 * 1. the same reason perl on UNIX doesn't use SHELL--rampant and
506 * uncontrolled unportability of the ensuing scripts.
507 * 2. PERL5SHELL could be set to a shell that may not be fit for
508 * interactive use (which is what most programs look in COMSPEC
511 const char* defaultshell = (IsWinNT()
512 ? "cmd.exe /x/c" : "command.com /c");
513 const char *usershell = PerlEnv_getenv("PERL5SHELL");
514 w32_perlshell_items = tokenize(usershell ? usershell : defaultshell,
515 &w32_perlshell_tokens,
521 do_aspawn(void *vreally, void **vmark, void **vsp)
524 SV *really = (SV*)vreally;
525 SV **mark = (SV**)vmark;
537 New(1306, argv, (sp - mark) + w32_perlshell_items + 2, char*);
539 if (SvNIOKp(*(mark+1)) && !SvPOKp(*(mark+1))) {
544 while (++mark <= sp) {
545 if (*mark && (str = SvPV_nolen(*mark)))
552 status = win32_spawnvp(flag,
553 (const char*)(really ? SvPV_nolen(really) : argv[0]),
554 (const char* const*)argv);
556 if (status < 0 && (errno == ENOEXEC || errno == ENOENT)) {
557 /* possible shell-builtin, invoke with shell */
559 sh_items = w32_perlshell_items;
561 argv[index+sh_items] = argv[index];
562 while (--sh_items >= 0)
563 argv[sh_items] = w32_perlshell_vec[sh_items];
565 status = win32_spawnvp(flag,
566 (const char*)(really ? SvPV_nolen(really) : argv[0]),
567 (const char* const*)argv);
570 if (flag == P_NOWAIT) {
572 PL_statusvalue = -1; /* >16bits hint for pp_system() */
576 if (ckWARN(WARN_EXEC))
577 Perl_warner(aTHX_ WARN_EXEC, "Can't spawn \"%s\": %s", argv[0], strerror(errno));
582 PL_statusvalue = status;
588 /* returns pointer to the next unquoted space or the end of the string */
590 find_next_space(const char *s)
592 bool in_quotes = FALSE;
594 /* ignore doubled backslashes, or backslash+quote */
595 if (*s == '\\' && (s[1] == '\\' || s[1] == '"')) {
598 /* keep track of when we're within quotes */
599 else if (*s == '"') {
601 in_quotes = !in_quotes;
603 /* break it up only at spaces that aren't in quotes */
604 else if (!in_quotes && isSPACE(*s))
613 do_spawn2(char *cmd, int exectype)
620 BOOL needToTry = TRUE;
623 /* Save an extra exec if possible. See if there are shell
624 * metacharacters in it */
625 if (!has_shell_metachars(cmd)) {
626 New(1301,argv, strlen(cmd) / 2 + 2, char*);
627 New(1302,cmd2, strlen(cmd) + 1, char);
630 for (s = cmd2; *s;) {
631 while (*s && isSPACE(*s))
635 s = find_next_space(s);
643 status = win32_spawnvp(P_WAIT, argv[0],
644 (const char* const*)argv);
646 case EXECF_SPAWN_NOWAIT:
647 status = win32_spawnvp(P_NOWAIT, argv[0],
648 (const char* const*)argv);
651 status = win32_execvp(argv[0], (const char* const*)argv);
654 if (status != -1 || errno == 0)
664 New(1306, argv, w32_perlshell_items + 2, char*);
665 while (++i < w32_perlshell_items)
666 argv[i] = w32_perlshell_vec[i];
671 status = win32_spawnvp(P_WAIT, argv[0],
672 (const char* const*)argv);
674 case EXECF_SPAWN_NOWAIT:
675 status = win32_spawnvp(P_NOWAIT, argv[0],
676 (const char* const*)argv);
679 status = win32_execvp(argv[0], (const char* const*)argv);
685 if (exectype == EXECF_SPAWN_NOWAIT) {
687 PL_statusvalue = -1; /* >16bits hint for pp_system() */
691 if (ckWARN(WARN_EXEC))
692 Perl_warner(aTHX_ WARN_EXEC, "Can't %s \"%s\": %s",
693 (exectype == EXECF_EXEC ? "exec" : "spawn"),
694 cmd, strerror(errno));
699 PL_statusvalue = status;
707 return do_spawn2(cmd, EXECF_SPAWN);
711 do_spawn_nowait(char *cmd)
713 return do_spawn2(cmd, EXECF_SPAWN_NOWAIT);
717 Perl_do_exec(pTHX_ char *cmd)
719 do_spawn2(cmd, EXECF_EXEC);
723 /* The idea here is to read all the directory names into a string table
724 * (separated by nulls) and when one of the other dir functions is called
725 * return the pointer to the current file name.
728 win32_opendir(char *filename)
734 char scanname[MAX_PATH+3];
736 WIN32_FIND_DATAA aFindData;
737 WIN32_FIND_DATAW wFindData;
739 char buffer[MAX_PATH*2];
740 WCHAR wbuffer[MAX_PATH+1];
743 len = strlen(filename);
747 /* check to see if filename is a directory */
748 if (win32_stat(filename, &sbuf) < 0 || !S_ISDIR(sbuf.st_mode))
751 /* Get us a DIR structure */
752 Newz(1303, dirp, 1, DIR);
754 /* Create the search pattern */
755 strcpy(scanname, filename);
757 /* bare drive name means look in cwd for drive */
758 if (len == 2 && isALPHA(scanname[0]) && scanname[1] == ':') {
759 scanname[len++] = '.';
760 scanname[len++] = '/';
762 else if (scanname[len-1] != '/' && scanname[len-1] != '\\') {
763 scanname[len++] = '/';
765 scanname[len++] = '*';
766 scanname[len] = '\0';
768 /* do the FindFirstFile call */
770 A2WHELPER(scanname, wbuffer, sizeof(wbuffer));
771 fh = FindFirstFileW(PerlDir_mapW(wbuffer), &wFindData);
774 fh = FindFirstFileA(PerlDir_mapA(scanname), &aFindData);
777 if (fh == INVALID_HANDLE_VALUE) {
778 DWORD err = GetLastError();
779 /* FindFirstFile() fails on empty drives! */
781 case ERROR_FILE_NOT_FOUND:
783 case ERROR_NO_MORE_FILES:
784 case ERROR_PATH_NOT_FOUND:
787 case ERROR_NOT_ENOUGH_MEMORY:
798 /* now allocate the first part of the string table for
799 * the filenames that we find.
802 W2AHELPER(wFindData.cFileName, buffer, sizeof(buffer));
806 ptr = aFindData.cFileName;
813 New(1304, dirp->start, dirp->size, char);
814 strcpy(dirp->start, ptr);
816 dirp->end = dirp->curr = dirp->start;
822 /* Readdir just returns the current string pointer and bumps the
823 * string pointer to the nDllExport entry.
825 DllExport struct direct *
826 win32_readdir(DIR *dirp)
831 /* first set up the structure to return */
832 len = strlen(dirp->curr);
833 strcpy(dirp->dirstr.d_name, dirp->curr);
834 dirp->dirstr.d_namlen = len;
837 dirp->dirstr.d_ino = dirp->curr - dirp->start;
839 /* Now set up for the next call to readdir */
840 dirp->curr += len + 1;
841 if (dirp->curr >= dirp->end) {
845 WIN32_FIND_DATAW wFindData;
846 WIN32_FIND_DATAA aFindData;
847 char buffer[MAX_PATH*2];
849 /* finding the next file that matches the wildcard
850 * (which should be all of them in this directory!).
853 res = FindNextFileW(dirp->handle, &wFindData);
855 W2AHELPER(wFindData.cFileName, buffer, sizeof(buffer));
860 res = FindNextFileA(dirp->handle, &aFindData);
862 ptr = aFindData.cFileName;
865 long endpos = dirp->end - dirp->start;
866 long newsize = endpos + strlen(ptr) + 1;
867 /* bump the string table size by enough for the
868 * new name and its null terminator */
869 while (newsize > dirp->size) {
870 long curpos = dirp->curr - dirp->start;
872 Renew(dirp->start, dirp->size, char);
873 dirp->curr = dirp->start + curpos;
875 strcpy(dirp->start + endpos, ptr);
876 dirp->end = dirp->start + newsize;
882 return &(dirp->dirstr);
888 /* Telldir returns the current string pointer position */
890 win32_telldir(DIR *dirp)
892 return (dirp->curr - dirp->start);
896 /* Seekdir moves the string pointer to a previously saved position
897 * (returned by telldir).
900 win32_seekdir(DIR *dirp, long loc)
902 dirp->curr = dirp->start + loc;
905 /* Rewinddir resets the string pointer to the start */
907 win32_rewinddir(DIR *dirp)
909 dirp->curr = dirp->start;
912 /* free the memory allocated by opendir */
914 win32_closedir(DIR *dirp)
917 if (dirp->handle != INVALID_HANDLE_VALUE)
918 FindClose(dirp->handle);
919 Safefree(dirp->start);
932 * Just pretend that everyone is a superuser. NT will let us know if
933 * we don\'t really have permission to do something.
936 #define ROOT_UID ((uid_t)0)
937 #define ROOT_GID ((gid_t)0)
966 return (auid == ROOT_UID ? 0 : -1);
972 return (agid == ROOT_GID ? 0 : -1);
979 char *buf = w32_getlogin_buffer;
980 DWORD size = sizeof(w32_getlogin_buffer);
981 if (GetUserName(buf,&size))
987 chown(const char *path, uid_t owner, gid_t group)
994 * XXX this needs strengthening (for PerlIO)
997 int mkstemp(const char *path)
1000 char buf[MAX_PATH+1];
1004 if (i++ > 10) { /* give up */
1008 if (!GetTempFileNameA((LPCSTR)path, "plr", 1, buf)) {
1012 fd = PerlLIO_open3(buf, O_CREAT|O_RDWR|O_EXCL, 0600);
1022 long child = w32_num_children;
1023 while (--child >= 0) {
1024 if (w32_child_pids[child] == pid)
1031 remove_dead_process(long child)
1035 CloseHandle(w32_child_handles[child]);
1036 Move(&w32_child_handles[child+1], &w32_child_handles[child],
1037 (w32_num_children-child-1), HANDLE);
1038 Move(&w32_child_pids[child+1], &w32_child_pids[child],
1039 (w32_num_children-child-1), DWORD);
1046 find_pseudo_pid(int pid)
1049 long child = w32_num_pseudo_children;
1050 while (--child >= 0) {
1051 if (w32_pseudo_child_pids[child] == pid)
1058 remove_dead_pseudo_process(long child)
1062 CloseHandle(w32_pseudo_child_handles[child]);
1063 Move(&w32_pseudo_child_handles[child+1], &w32_pseudo_child_handles[child],
1064 (w32_num_pseudo_children-child-1), HANDLE);
1065 Move(&w32_pseudo_child_pids[child+1], &w32_pseudo_child_pids[child],
1066 (w32_num_pseudo_children-child-1), DWORD);
1067 w32_num_pseudo_children--;
1073 win32_kill(int pid, int sig)
1080 /* it is a pseudo-forked child */
1081 child = find_pseudo_pid(-pid);
1083 hProcess = w32_pseudo_child_handles[child];
1088 /* kill -9 style un-graceful exit */
1089 if (TerminateThread(hProcess, sig)) {
1090 remove_dead_pseudo_process(child);
1095 /* We fake signals to pseudo-processes using message queue */
1096 if (PostThreadMessage(-pid,WM_USER,sig,0)) {
1097 /* It might be us ... */
1104 else if (IsWin95()) {
1112 child = find_pid(pid);
1114 hProcess = w32_child_handles[child];
1119 if (GenerateConsoleCtrlEvent(CTRL_C_EVENT,pid))
1123 if (TerminateProcess(hProcess, sig)) {
1124 remove_dead_process(child);
1132 hProcess = OpenProcess(PROCESS_ALL_ACCESS, TRUE,
1133 (IsWin95() ? -pid : pid));
1139 if (GenerateConsoleCtrlEvent(CTRL_C_EVENT,pid))
1143 if (TerminateProcess(hProcess, sig)) {
1144 CloseHandle(hProcess);
1156 win32_stat(const char *path, struct stat *sbuf)
1159 char buffer[MAX_PATH+1];
1160 int l = strlen(path);
1162 WCHAR wbuffer[MAX_PATH+1];
1168 switch(path[l - 1]) {
1169 /* FindFirstFile() and stat() are buggy with a trailing
1170 * backslash, so change it to a forward slash :-( */
1172 strncpy(buffer, path, l-1);
1173 buffer[l - 1] = '/';
1177 /* FindFirstFile() is buggy with "x:", so add a dot :-( */
1179 if (l == 2 && isALPHA(path[0])) {
1180 buffer[0] = path[0];
1191 /* We *must* open & close the file once; otherwise file attribute changes */
1192 /* might not yet have propagated to "other" hard links of the same file. */
1193 /* This also gives us an opportunity to determine the number of links. */
1195 A2WHELPER(path, wbuffer, sizeof(wbuffer));
1196 pwbuffer = PerlDir_mapW(wbuffer);
1197 handle = CreateFileW(pwbuffer, 0, 0, NULL, OPEN_EXISTING, 0, NULL);
1200 path = PerlDir_mapA(path);
1202 handle = CreateFileA(path, 0, 0, NULL, OPEN_EXISTING, 0, NULL);
1204 if (handle != INVALID_HANDLE_VALUE) {
1205 BY_HANDLE_FILE_INFORMATION bhi;
1206 if (GetFileInformationByHandle(handle, &bhi))
1207 nlink = bhi.nNumberOfLinks;
1208 CloseHandle(handle);
1211 /* pwbuffer or path will be mapped correctly above */
1213 res = _wstat(pwbuffer, (struct _stat *)sbuf);
1216 res = stat(path, sbuf);
1218 sbuf->st_nlink = nlink;
1221 /* CRT is buggy on sharenames, so make sure it really isn't.
1222 * XXX using GetFileAttributesEx() will enable us to set
1223 * sbuf->st_*time (but note that's not available on the
1224 * Windows of 1995) */
1227 r = GetFileAttributesW(pwbuffer);
1230 r = GetFileAttributesA(path);
1232 if (r != 0xffffffff && (r & FILE_ATTRIBUTE_DIRECTORY)) {
1233 /* sbuf may still contain old garbage since stat() failed */
1234 Zero(sbuf, 1, struct stat);
1235 sbuf->st_mode = S_IFDIR | S_IREAD;
1237 if (!(r & FILE_ATTRIBUTE_READONLY))
1238 sbuf->st_mode |= S_IWRITE | S_IEXEC;
1243 if (l == 3 && isALPHA(path[0]) && path[1] == ':'
1244 && (path[2] == '\\' || path[2] == '/'))
1246 /* The drive can be inaccessible, some _stat()s are buggy */
1248 ? !GetVolumeInformationW(pwbuffer,NULL,0,NULL,NULL,NULL,NULL,0)
1249 : !GetVolumeInformationA(path,NULL,0,NULL,NULL,NULL,NULL,0)) {
1255 if (S_ISDIR(sbuf->st_mode))
1256 sbuf->st_mode |= S_IWRITE | S_IEXEC;
1257 else if (S_ISREG(sbuf->st_mode)) {
1259 if (l >= 4 && path[l-4] == '.') {
1260 const char *e = path + l - 3;
1261 if (strnicmp(e,"exe",3)
1262 && strnicmp(e,"bat",3)
1263 && strnicmp(e,"com",3)
1264 && (IsWin95() || strnicmp(e,"cmd",3)))
1265 sbuf->st_mode &= ~S_IEXEC;
1267 sbuf->st_mode |= S_IEXEC;
1270 sbuf->st_mode &= ~S_IEXEC;
1271 /* Propagate permissions to _group_ and _others_ */
1272 perms = sbuf->st_mode & (S_IREAD|S_IWRITE|S_IEXEC);
1273 sbuf->st_mode |= (perms>>3) | (perms>>6);
1280 /* Find the longname of a given path. path is destructively modified.
1281 * It should have space for at least MAX_PATH characters. */
1283 win32_longpath(char *path)
1285 WIN32_FIND_DATA fdata;
1287 char tmpbuf[MAX_PATH+1];
1288 char *tmpstart = tmpbuf;
1295 if (isALPHA(path[0]) && path[1] == ':' &&
1296 (path[2] == '/' || path[2] == '\\'))
1299 *tmpstart++ = path[0];
1303 else if ((path[0] == '/' || path[0] == '\\') &&
1304 (path[1] == '/' || path[1] == '\\'))
1307 *tmpstart++ = path[0];
1308 *tmpstart++ = path[1];
1309 /* copy machine name */
1310 while (*start && *start != '/' && *start != '\\')
1311 *tmpstart++ = *start++;
1313 *tmpstart++ = *start;
1315 /* copy share name */
1316 while (*start && *start != '/' && *start != '\\')
1317 *tmpstart++ = *start++;
1321 if (sep == '/' || sep == '\\')
1325 /* walk up to slash */
1326 while (*start && *start != '/' && *start != '\\')
1329 /* discard doubled slashes */
1330 while (*start && (start[1] == '/' || start[1] == '\\'))
1334 /* stop and find full name of component */
1336 fhand = FindFirstFile(path,&fdata);
1337 if (fhand != INVALID_HANDLE_VALUE) {
1338 strcpy(tmpstart, fdata.cFileName);
1339 tmpstart += strlen(fdata.cFileName);
1347 /* failed a step, just return without side effects */
1348 /*PerlIO_printf(Perl_debug_log, "Failed to find %s\n", path);*/
1353 strcpy(path,tmpbuf);
1358 win32_getenv(const char *name)
1361 WCHAR wBuffer[MAX_PATH+1];
1363 SV *curitem = Nullsv;
1366 A2WHELPER(name, wBuffer, sizeof(wBuffer));
1367 needlen = GetEnvironmentVariableW(wBuffer, NULL, 0);
1370 needlen = GetEnvironmentVariableA(name,NULL,0);
1372 curitem = sv_2mortal(newSVpvn("", 0));
1376 SvGROW(curitem, (needlen+1)*sizeof(WCHAR));
1377 needlen = GetEnvironmentVariableW(wBuffer,
1378 (WCHAR*)SvPVX(curitem),
1380 } while (needlen >= SvLEN(curitem)/sizeof(WCHAR));
1381 SvCUR_set(curitem, (needlen*sizeof(WCHAR))+1);
1382 acuritem = sv_2mortal(newSVsv(curitem));
1383 W2AHELPER((WCHAR*)SvPVX(acuritem), SvPVX(curitem), SvCUR(curitem));
1387 SvGROW(curitem, needlen+1);
1388 needlen = GetEnvironmentVariableA(name,SvPVX(curitem),
1390 } while (needlen >= SvLEN(curitem));
1391 SvCUR_set(curitem, needlen);
1395 /* allow any environment variables that begin with 'PERL'
1396 to be stored in the registry */
1397 if (strncmp(name, "PERL", 4) == 0)
1398 (void)get_regstr(name, &curitem);
1400 if (curitem && SvCUR(curitem))
1401 return SvPVX(curitem);
1407 win32_putenv(const char *name)
1414 int length, relval = -1;
1418 length = strlen(name)+1;
1419 New(1309,wCuritem,length,WCHAR);
1420 A2WHELPER(name, wCuritem, length*sizeof(WCHAR));
1421 wVal = wcschr(wCuritem, '=');
1424 if (SetEnvironmentVariableW(wCuritem, *wVal ? wVal : NULL))
1430 New(1309,curitem,strlen(name)+1,char);
1431 strcpy(curitem, name);
1432 val = strchr(curitem, '=');
1434 /* The sane way to deal with the environment.
1435 * Has these advantages over putenv() & co.:
1436 * * enables us to store a truly empty value in the
1437 * environment (like in UNIX).
1438 * * we don't have to deal with RTL globals, bugs and leaks.
1440 * Why you may want to enable USE_WIN32_RTL_ENV:
1441 * * environ[] and RTL functions will not reflect changes,
1442 * which might be an issue if extensions want to access
1443 * the env. via RTL. This cuts both ways, since RTL will
1444 * not see changes made by extensions that call the Win32
1445 * functions directly, either.
1449 if (SetEnvironmentVariableA(curitem, *val ? val : NULL))
1459 filetime_to_clock(PFILETIME ft)
1461 __int64 qw = ft->dwHighDateTime;
1463 qw |= ft->dwLowDateTime;
1464 qw /= 10000; /* File time ticks at 0.1uS, clock at 1mS */
1469 win32_times(struct tms *timebuf)
1474 if (GetProcessTimes(GetCurrentProcess(), &dummy, &dummy,
1476 timebuf->tms_utime = filetime_to_clock(&user);
1477 timebuf->tms_stime = filetime_to_clock(&kernel);
1478 timebuf->tms_cutime = 0;
1479 timebuf->tms_cstime = 0;
1482 /* That failed - e.g. Win95 fallback to clock() */
1483 clock_t t = clock();
1484 timebuf->tms_utime = t;
1485 timebuf->tms_stime = 0;
1486 timebuf->tms_cutime = 0;
1487 timebuf->tms_cstime = 0;
1492 /* fix utime() so it works on directories in NT */
1494 filetime_from_time(PFILETIME pFileTime, time_t Time)
1496 struct tm *pTM = localtime(&Time);
1497 SYSTEMTIME SystemTime;
1503 SystemTime.wYear = pTM->tm_year + 1900;
1504 SystemTime.wMonth = pTM->tm_mon + 1;
1505 SystemTime.wDay = pTM->tm_mday;
1506 SystemTime.wHour = pTM->tm_hour;
1507 SystemTime.wMinute = pTM->tm_min;
1508 SystemTime.wSecond = pTM->tm_sec;
1509 SystemTime.wMilliseconds = 0;
1511 return SystemTimeToFileTime(&SystemTime, &LocalTime) &&
1512 LocalFileTimeToFileTime(&LocalTime, pFileTime);
1516 win32_unlink(const char *filename)
1523 WCHAR wBuffer[MAX_PATH+1];
1526 A2WHELPER(filename, wBuffer, sizeof(wBuffer));
1527 pwBuffer = PerlDir_mapW(wBuffer);
1528 attrs = GetFileAttributesW(pwBuffer);
1529 if (attrs == 0xFFFFFFFF)
1531 if (attrs & FILE_ATTRIBUTE_READONLY) {
1532 (void)SetFileAttributesW(pwBuffer, attrs & ~FILE_ATTRIBUTE_READONLY);
1533 ret = _wunlink(pwBuffer);
1535 (void)SetFileAttributesW(pwBuffer, attrs);
1538 ret = _wunlink(pwBuffer);
1541 filename = PerlDir_mapA(filename);
1542 attrs = GetFileAttributesA(filename);
1543 if (attrs == 0xFFFFFFFF)
1545 if (attrs & FILE_ATTRIBUTE_READONLY) {
1546 (void)SetFileAttributesA(filename, attrs & ~FILE_ATTRIBUTE_READONLY);
1547 ret = unlink(filename);
1549 (void)SetFileAttributesA(filename, attrs);
1552 ret = unlink(filename);
1561 win32_utime(const char *filename, struct utimbuf *times)
1568 struct utimbuf TimeBuffer;
1569 WCHAR wbuffer[MAX_PATH+1];
1574 A2WHELPER(filename, wbuffer, sizeof(wbuffer));
1575 pwbuffer = PerlDir_mapW(wbuffer);
1576 rc = _wutime(pwbuffer, (struct _utimbuf*)times);
1579 filename = PerlDir_mapA(filename);
1580 rc = utime(filename, times);
1582 /* EACCES: path specifies directory or readonly file */
1583 if (rc == 0 || errno != EACCES /* || !IsWinNT() */)
1586 if (times == NULL) {
1587 times = &TimeBuffer;
1588 time(×->actime);
1589 times->modtime = times->actime;
1592 /* This will (and should) still fail on readonly files */
1594 handle = CreateFileW(pwbuffer, GENERIC_READ | GENERIC_WRITE,
1595 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1596 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1599 handle = CreateFileA(filename, GENERIC_READ | GENERIC_WRITE,
1600 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1601 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1603 if (handle == INVALID_HANDLE_VALUE)
1606 if (GetFileTime(handle, &ftCreate, &ftAccess, &ftWrite) &&
1607 filetime_from_time(&ftAccess, times->actime) &&
1608 filetime_from_time(&ftWrite, times->modtime) &&
1609 SetFileTime(handle, &ftCreate, &ftAccess, &ftWrite))
1614 CloseHandle(handle);
1619 win32_uname(struct utsname *name)
1621 struct hostent *hep;
1622 STRLEN nodemax = sizeof(name->nodename)-1;
1623 OSVERSIONINFO osver;
1625 memset(&osver, 0, sizeof(OSVERSIONINFO));
1626 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1627 if (GetVersionEx(&osver)) {
1629 switch (osver.dwPlatformId) {
1630 case VER_PLATFORM_WIN32_WINDOWS:
1631 strcpy(name->sysname, "Windows");
1633 case VER_PLATFORM_WIN32_NT:
1634 strcpy(name->sysname, "Windows NT");
1636 case VER_PLATFORM_WIN32s:
1637 strcpy(name->sysname, "Win32s");
1640 strcpy(name->sysname, "Win32 Unknown");
1645 sprintf(name->release, "%d.%d",
1646 osver.dwMajorVersion, osver.dwMinorVersion);
1649 sprintf(name->version, "Build %d",
1650 osver.dwPlatformId == VER_PLATFORM_WIN32_NT
1651 ? osver.dwBuildNumber : (osver.dwBuildNumber & 0xffff));
1652 if (osver.szCSDVersion[0]) {
1653 char *buf = name->version + strlen(name->version);
1654 sprintf(buf, " (%s)", osver.szCSDVersion);
1658 *name->sysname = '\0';
1659 *name->version = '\0';
1660 *name->release = '\0';
1664 hep = win32_gethostbyname("localhost");
1666 STRLEN len = strlen(hep->h_name);
1667 if (len <= nodemax) {
1668 strcpy(name->nodename, hep->h_name);
1671 strncpy(name->nodename, hep->h_name, nodemax);
1672 name->nodename[nodemax] = '\0';
1677 if (!GetComputerName(name->nodename, &sz))
1678 *name->nodename = '\0';
1681 /* machine (architecture) */
1685 GetSystemInfo(&info);
1687 #if (defined(__BORLANDC__)&&(__BORLANDC__<=0x520)) \
1688 || (defined(__MINGW32__) && !defined(_ANONYMOUS_UNION))
1689 switch (info.u.s.wProcessorArchitecture) {
1691 switch (info.wProcessorArchitecture) {
1693 case PROCESSOR_ARCHITECTURE_INTEL:
1694 arch = "x86"; break;
1695 case PROCESSOR_ARCHITECTURE_MIPS:
1696 arch = "mips"; break;
1697 case PROCESSOR_ARCHITECTURE_ALPHA:
1698 arch = "alpha"; break;
1699 case PROCESSOR_ARCHITECTURE_PPC:
1700 arch = "ppc"; break;
1702 arch = "unknown"; break;
1704 strcpy(name->machine, arch);
1709 /* Timing related stuff */
1712 win32_async_check(pTHX)
1716 /* Passing PeekMessage -1 as HWND (2nd arg) only get PostThreadMessage() messages
1717 * and ignores window messages - should co-exist better with windows apps e.g. Tk
1719 while (PeekMessage(&msg, (HWND)-1, 0, 0, PM_REMOVE)) {
1720 switch(msg.message) {
1723 /* Perhaps some other messages could map to signals ? ... */
1726 /* Treat WM_QUIT like SIGHUP? */
1727 CALL_FPTR(PL_sighandlerp)(1);
1731 /* plan to use WM_USER to fake kill() with other signals */
1737 /* alarm() is a one-shot but SetTimer() repeats so kill it */
1738 KillTimer(NULL,w32_timerid);
1740 /* Now fake a call to signal handler */
1741 CALL_FPTR(PL_sighandlerp)(14);
1745 /* Otherwise do normal Win32 thing - in case it is useful */
1747 TranslateMessage(&msg);
1748 DispatchMessage(&msg);
1754 /* Above or other stuff may have set a signal flag */
1755 if (PL_sig_pending) {
1762 win32_msgwait(pTHX_ DWORD count, LPHANDLE handles, DWORD timeout, LPDWORD resultp)
1764 /* We may need several goes at this - so compute when we stop */
1766 if (timeout != INFINITE) {
1767 ticks = GetTickCount();
1771 DWORD result = MsgWaitForMultipleObjects(count,handles,FALSE,timeout-ticks, QS_ALLEVENTS);
1774 if (result == WAIT_TIMEOUT) {
1775 /* Ran out of time - explicit return of zero to avoid -ve if we
1776 have scheduling issues
1780 if (timeout != INFINITE) {
1781 ticks = GetTickCount();
1783 if (result == WAIT_OBJECT_0 + count) {
1784 /* Message has arrived - check it */
1785 if (win32_async_check(aTHX)) {
1786 /* was one of ours */
1791 /* Not timeout or message - one of handles is ready */
1795 /* compute time left to wait */
1796 ticks = timeout - ticks;
1797 /* If we are past the end say zero */
1798 return (ticks > 0) ? ticks : 0;
1802 win32_internal_wait(int *status, DWORD timeout)
1804 /* XXX this wait emulation only knows about processes
1805 * spawned via win32_spawnvp(P_NOWAIT, ...).
1809 DWORD exitcode, waitcode;
1812 if (w32_num_pseudo_children) {
1813 win32_msgwait(aTHX_ w32_num_pseudo_children, w32_pseudo_child_handles,
1814 timeout, &waitcode);
1815 /* Time out here if there are no other children to wait for. */
1816 if (waitcode == WAIT_TIMEOUT) {
1817 if (!w32_num_children) {
1821 else if (waitcode != WAIT_FAILED) {
1822 if (waitcode >= WAIT_ABANDONED_0
1823 && waitcode < WAIT_ABANDONED_0 + w32_num_pseudo_children)
1824 i = waitcode - WAIT_ABANDONED_0;
1826 i = waitcode - WAIT_OBJECT_0;
1827 if (GetExitCodeThread(w32_pseudo_child_handles[i], &exitcode)) {
1828 *status = (int)((exitcode & 0xff) << 8);
1829 retval = (int)w32_pseudo_child_pids[i];
1830 remove_dead_pseudo_process(i);
1837 if (!w32_num_children) {
1842 /* if a child exists, wait for it to die */
1843 win32_msgwait(aTHX_ w32_num_children, w32_child_handles, timeout, &waitcode);
1844 if (waitcode == WAIT_TIMEOUT) {
1847 if (waitcode != WAIT_FAILED) {
1848 if (waitcode >= WAIT_ABANDONED_0
1849 && waitcode < WAIT_ABANDONED_0 + w32_num_children)
1850 i = waitcode - WAIT_ABANDONED_0;
1852 i = waitcode - WAIT_OBJECT_0;
1853 if (GetExitCodeProcess(w32_child_handles[i], &exitcode) ) {
1854 *status = (int)((exitcode & 0xff) << 8);
1855 retval = (int)w32_child_pids[i];
1856 remove_dead_process(i);
1862 errno = GetLastError();
1867 win32_waitpid(int pid, int *status, int flags)
1870 DWORD timeout = (flags & WNOHANG) ? 0 : INFINITE;
1873 if (pid == -1) /* XXX threadid == 1 ? */
1874 return win32_internal_wait(status, timeout);
1877 child = find_pseudo_pid(-pid);
1879 HANDLE hThread = w32_pseudo_child_handles[child];
1881 win32_msgwait(aTHX_ 1, &hThread, timeout, &waitcode);
1882 if (waitcode == WAIT_TIMEOUT) {
1885 else if (waitcode == WAIT_OBJECT_0) {
1886 if (GetExitCodeThread(hThread, &waitcode)) {
1887 *status = (int)((waitcode & 0xff) << 8);
1888 retval = (int)w32_pseudo_child_pids[child];
1889 remove_dead_pseudo_process(child);
1896 else if (IsWin95()) {
1905 child = find_pid(pid);
1907 hProcess = w32_child_handles[child];
1908 win32_msgwait(aTHX_ 1, &hProcess, timeout, &waitcode);
1909 if (waitcode == WAIT_TIMEOUT) {
1912 else if (waitcode == WAIT_OBJECT_0) {
1913 if (GetExitCodeProcess(hProcess, &waitcode)) {
1914 *status = (int)((waitcode & 0xff) << 8);
1915 retval = (int)w32_child_pids[child];
1916 remove_dead_process(child);
1925 hProcess = OpenProcess(PROCESS_ALL_ACCESS, TRUE,
1926 (IsWin95() ? -pid : pid));
1928 win32_msgwait(aTHX_ 1, &hProcess, timeout, &waitcode);
1929 if (waitcode == WAIT_TIMEOUT) {
1932 else if (waitcode == WAIT_OBJECT_0) {
1933 if (GetExitCodeProcess(hProcess, &waitcode)) {
1934 *status = (int)((waitcode & 0xff) << 8);
1935 CloseHandle(hProcess);
1939 CloseHandle(hProcess);
1945 return retval >= 0 ? pid : retval;
1949 win32_wait(int *status)
1951 return win32_internal_wait(status, INFINITE);
1954 DllExport unsigned int
1955 win32_sleep(unsigned int t)
1958 /* Win32 times are in ms so *1000 in and /1000 out */
1959 return win32_msgwait(aTHX_ 0, NULL, t*1000, NULL)/1000;
1962 DllExport unsigned int
1963 win32_alarm(unsigned int sec)
1966 * the 'obvious' implentation is SetTimer() with a callback
1967 * which does whatever receiving SIGALRM would do
1968 * we cannot use SIGALRM even via raise() as it is not
1969 * one of the supported codes in <signal.h>
1973 w32_timerid = SetTimer(NULL,w32_timerid,sec*1000,NULL);
1977 KillTimer(NULL,w32_timerid);
1984 #ifdef HAVE_DES_FCRYPT
1985 extern char * des_fcrypt(const char *txt, const char *salt, char *cbuf);
1989 win32_crypt(const char *txt, const char *salt)
1992 #ifdef HAVE_DES_FCRYPT
1993 return des_fcrypt(txt, salt, w32_crypt_buffer);
1995 Perl_croak(aTHX_ "The crypt() function is unimplemented due to excessive paranoia.");
2000 #ifdef USE_FIXED_OSFHANDLE
2002 #define FOPEN 0x01 /* file handle open */
2003 #define FNOINHERIT 0x10 /* file handle opened O_NOINHERIT */
2004 #define FAPPEND 0x20 /* file handle opened O_APPEND */
2005 #define FDEV 0x40 /* file handle refers to device */
2006 #define FTEXT 0x80 /* file handle is in text mode */
2009 *int my_open_osfhandle(long osfhandle, int flags) - open C Runtime file handle
2012 * This function allocates a free C Runtime file handle and associates
2013 * it with the Win32 HANDLE specified by the first parameter. This is a
2014 * temperary fix for WIN95's brain damage GetFileType() error on socket
2015 * we just bypass that call for socket
2017 * This works with MSVC++ 4.0+ or GCC/Mingw32
2020 * long osfhandle - Win32 HANDLE to associate with C Runtime file handle.
2021 * int flags - flags to associate with C Runtime file handle.
2024 * returns index of entry in fh, if successful
2025 * return -1, if no free entry is found
2029 *******************************************************************************/
2032 * we fake up some parts of the CRT that aren't exported by MSVCRT.dll
2033 * this lets sockets work on Win9X with GCC and should fix the problems
2038 /* create an ioinfo entry, kill its handle, and steal the entry */
2043 HANDLE hF = CreateFile("NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
2044 int fh = _open_osfhandle((long)hF, 0);
2048 EnterCriticalSection(&(_pioinfo(fh)->lock));
2053 my_open_osfhandle(long osfhandle, int flags)
2056 char fileflags; /* _osfile flags */
2058 /* copy relevant flags from second parameter */
2061 if (flags & O_APPEND)
2062 fileflags |= FAPPEND;
2067 if (flags & O_NOINHERIT)
2068 fileflags |= FNOINHERIT;
2070 /* attempt to allocate a C Runtime file handle */
2071 if ((fh = _alloc_osfhnd()) == -1) {
2072 errno = EMFILE; /* too many open files */
2073 _doserrno = 0L; /* not an OS error */
2074 return -1; /* return error to caller */
2077 /* the file is open. now, set the info in _osfhnd array */
2078 _set_osfhnd(fh, osfhandle);
2080 fileflags |= FOPEN; /* mark as open */
2082 _osfile(fh) = fileflags; /* set osfile entry */
2083 LeaveCriticalSection(&_pioinfo(fh)->lock);
2085 return fh; /* return handle */
2088 #endif /* USE_FIXED_OSFHANDLE */
2090 /* simulate flock by locking a range on the file */
2092 #define LK_ERR(f,i) ((f) ? (i = 0) : (errno = GetLastError()))
2093 #define LK_LEN 0xffff0000
2096 win32_flock(int fd, int oper)
2104 Perl_croak_nocontext("flock() unimplemented on this platform");
2107 fh = (HANDLE)_get_osfhandle(fd);
2108 memset(&o, 0, sizeof(o));
2111 case LOCK_SH: /* shared lock */
2112 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
2114 case LOCK_EX: /* exclusive lock */
2115 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
2117 case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
2118 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
2120 case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
2121 LK_ERR(LockFileEx(fh,
2122 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
2123 0, LK_LEN, 0, &o),i);
2125 case LOCK_UN: /* unlock lock */
2126 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, 0, &o),i);
2128 default: /* unknown */
2139 * redirected io subsystem for all XS modules
2152 return (&(_environ));
2155 /* the rest are the remapped stdio routines */
2175 win32_ferror(FILE *fp)
2177 return (ferror(fp));
2182 win32_feof(FILE *fp)
2188 * Since the errors returned by the socket error function
2189 * WSAGetLastError() are not known by the library routine strerror
2190 * we have to roll our own.
2194 win32_strerror(int e)
2196 #if !defined __BORLANDC__ && !defined __MINGW32__ /* compiler intolerance */
2197 extern int sys_nerr;
2201 if (e < 0 || e > sys_nerr) {
2206 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
2207 w32_strerror_buffer,
2208 sizeof(w32_strerror_buffer), NULL) == 0)
2209 strcpy(w32_strerror_buffer, "Unknown Error");
2211 return w32_strerror_buffer;
2217 win32_str_os_error(void *sv, DWORD dwErr)
2221 dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
2222 |FORMAT_MESSAGE_IGNORE_INSERTS
2223 |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
2224 dwErr, 0, (char *)&sMsg, 1, NULL);
2225 /* strip trailing whitespace and period */
2228 --dwLen; /* dwLen doesn't include trailing null */
2229 } while (0 < dwLen && isSPACE(sMsg[dwLen]));
2230 if ('.' != sMsg[dwLen])
2235 sMsg = (char*)LocalAlloc(0, 64/**sizeof(TCHAR)*/);
2237 dwLen = sprintf(sMsg,
2238 "Unknown error #0x%lX (lookup 0x%lX)",
2239 dwErr, GetLastError());
2243 sv_setpvn((SV*)sv, sMsg, dwLen);
2249 win32_fprintf(FILE *fp, const char *format, ...)
2252 va_start(marker, format); /* Initialize variable arguments. */
2254 return (vfprintf(fp, format, marker));
2258 win32_printf(const char *format, ...)
2261 va_start(marker, format); /* Initialize variable arguments. */
2263 return (vprintf(format, marker));
2267 win32_vfprintf(FILE *fp, const char *format, va_list args)
2269 return (vfprintf(fp, format, args));
2273 win32_vprintf(const char *format, va_list args)
2275 return (vprintf(format, args));
2279 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
2281 return fread(buf, size, count, fp);
2285 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
2287 return fwrite(buf, size, count, fp);
2290 #define MODE_SIZE 10
2293 win32_fopen(const char *filename, const char *mode)
2296 WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH+1];
2302 if (stricmp(filename, "/dev/null")==0)
2306 A2WHELPER(mode, wMode, sizeof(wMode));
2307 A2WHELPER(filename, wBuffer, sizeof(wBuffer));
2308 f = _wfopen(PerlDir_mapW(wBuffer), wMode);
2311 f = fopen(PerlDir_mapA(filename), mode);
2312 /* avoid buffering headaches for child processes */
2313 if (f && *mode == 'a')
2314 win32_fseek(f, 0, SEEK_END);
2318 #ifndef USE_SOCKETS_AS_HANDLES
2320 #define fdopen my_fdopen
2324 win32_fdopen(int handle, const char *mode)
2327 WCHAR wMode[MODE_SIZE];
2330 A2WHELPER(mode, wMode, sizeof(wMode));
2331 f = _wfdopen(handle, wMode);
2334 f = fdopen(handle, (char *) mode);
2335 /* avoid buffering headaches for child processes */
2336 if (f && *mode == 'a')
2337 win32_fseek(f, 0, SEEK_END);
2342 win32_freopen(const char *path, const char *mode, FILE *stream)
2345 WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH+1];
2346 if (stricmp(path, "/dev/null")==0)
2350 A2WHELPER(mode, wMode, sizeof(wMode));
2351 A2WHELPER(path, wBuffer, sizeof(wBuffer));
2352 return _wfreopen(PerlDir_mapW(wBuffer), wMode, stream);
2354 return freopen(PerlDir_mapA(path), mode, stream);
2358 win32_fclose(FILE *pf)
2360 return my_fclose(pf); /* defined in win32sck.c */
2364 win32_fputs(const char *s,FILE *pf)
2366 return fputs(s, pf);
2370 win32_fputc(int c,FILE *pf)
2376 win32_ungetc(int c,FILE *pf)
2378 return ungetc(c,pf);
2382 win32_getc(FILE *pf)
2388 win32_fileno(FILE *pf)
2394 win32_clearerr(FILE *pf)
2401 win32_fflush(FILE *pf)
2407 win32_ftell(FILE *pf)
2413 win32_fseek(FILE *pf,long offset,int origin)
2415 return fseek(pf, offset, origin);
2419 win32_fgetpos(FILE *pf,fpos_t *p)
2421 return fgetpos(pf, p);
2425 win32_fsetpos(FILE *pf,const fpos_t *p)
2427 return fsetpos(pf, p);
2431 win32_rewind(FILE *pf)
2441 char prefix[MAX_PATH+1];
2442 char filename[MAX_PATH+1];
2443 DWORD len = GetTempPath(MAX_PATH, prefix);
2444 if (len && len < MAX_PATH) {
2445 if (GetTempFileName(prefix, "plx", 0, filename)) {
2446 HANDLE fh = CreateFile(filename,
2447 DELETE | GENERIC_READ | GENERIC_WRITE,
2451 FILE_ATTRIBUTE_NORMAL
2452 | FILE_FLAG_DELETE_ON_CLOSE,
2454 if (fh != INVALID_HANDLE_VALUE) {
2455 int fd = win32_open_osfhandle((long)fh, 0);
2457 DEBUG_p(PerlIO_printf(Perl_debug_log,
2458 "Created tmpfile=%s\n",filename));
2459 return fdopen(fd, "w+b");
2475 win32_fstat(int fd,struct stat *sbufptr)
2478 /* A file designated by filehandle is not shown as accessible
2479 * for write operations, probably because it is opened for reading.
2482 int rc = fstat(fd,sbufptr);
2483 BY_HANDLE_FILE_INFORMATION bhfi;
2484 if (GetFileInformationByHandle((HANDLE)_get_osfhandle(fd), &bhfi)) {
2485 sbufptr->st_mode &= 0xFE00;
2486 if (bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
2487 sbufptr->st_mode |= (S_IREAD + (S_IREAD >> 3) + (S_IREAD >> 6));
2489 sbufptr->st_mode |= ((S_IREAD|S_IWRITE) + ((S_IREAD|S_IWRITE) >> 3)
2490 + ((S_IREAD|S_IWRITE) >> 6));
2494 return my_fstat(fd,sbufptr);
2499 win32_pipe(int *pfd, unsigned int size, int mode)
2501 return _pipe(pfd, size, mode);
2505 win32_popenlist(const char *mode, IV narg, SV **args)
2508 Perl_croak(aTHX_ "List form of pipe open not implemented");
2513 * a popen() clone that respects PERL5SHELL
2515 * changed to return PerlIO* rather than FILE * by BKS, 11-11-2000
2519 win32_popen(const char *command, const char *mode)
2521 #ifdef USE_RTL_POPEN
2522 return _popen(command, mode);
2530 /* establish which ends read and write */
2531 if (strchr(mode,'w')) {
2532 stdfd = 0; /* stdin */
2536 else if (strchr(mode,'r')) {
2537 stdfd = 1; /* stdout */
2544 /* set the correct mode */
2545 if (strchr(mode,'b'))
2547 else if (strchr(mode,'t'))
2550 ourmode = _fmode & (O_TEXT | O_BINARY);
2552 /* the child doesn't inherit handles */
2553 ourmode |= O_NOINHERIT;
2555 if (win32_pipe( p, 512, ourmode) == -1)
2558 /* save current stdfd */
2559 if ((oldfd = win32_dup(stdfd)) == -1)
2562 /* make stdfd go to child end of pipe (implicitly closes stdfd) */
2563 /* stdfd will be inherited by the child */
2564 if (win32_dup2(p[child], stdfd) == -1)
2567 /* close the child end in parent */
2568 win32_close(p[child]);
2570 /* start the child */
2573 if ((childpid = do_spawn_nowait((char*)command)) == -1)
2576 /* revert stdfd to whatever it was before */
2577 if (win32_dup2(oldfd, stdfd) == -1)
2580 /* close saved handle */
2584 sv_setiv(*av_fetch(w32_fdpid, p[parent], TRUE), childpid);
2587 /* set process id so that it can be returned by perl's open() */
2588 PL_forkprocess = childpid;
2591 /* we have an fd, return a file stream */
2592 return (PerlIO_fdopen(p[parent], (char *)mode));
2595 /* we don't need to check for errors here */
2599 win32_dup2(oldfd, stdfd);
2604 #endif /* USE_RTL_POPEN */
2612 win32_pclose(PerlIO *pf)
2614 #ifdef USE_RTL_POPEN
2618 int childpid, status;
2622 sv = *av_fetch(w32_fdpid, PerlIO_fileno(pf), TRUE);
2625 childpid = SvIVX(sv);
2642 if (win32_waitpid(childpid, &status, 0) == -1)
2647 #endif /* USE_RTL_POPEN */
2653 LPCWSTR lpExistingFileName,
2654 LPSECURITY_ATTRIBUTES lpSecurityAttributes)
2657 WCHAR wFullName[MAX_PATH+1];
2658 LPVOID lpContext = NULL;
2659 WIN32_STREAM_ID StreamId;
2660 DWORD dwSize = (char*)&StreamId.cStreamName - (char*)&StreamId;
2665 BOOL (__stdcall *pfnBackupWrite)(HANDLE, LPBYTE, DWORD, LPDWORD,
2666 BOOL, BOOL, LPVOID*) =
2667 (BOOL (__stdcall *)(HANDLE, LPBYTE, DWORD, LPDWORD,
2668 BOOL, BOOL, LPVOID*))
2669 GetProcAddress(GetModuleHandle("kernel32.dll"), "BackupWrite");
2670 if (pfnBackupWrite == NULL)
2673 dwLen = GetFullPathNameW(lpFileName, MAX_PATH, wFullName, NULL);
2676 dwLen = (dwLen+1)*sizeof(WCHAR);
2678 handle = CreateFileW(lpExistingFileName, FILE_WRITE_ATTRIBUTES,
2679 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
2680 NULL, OPEN_EXISTING, 0, NULL);
2681 if (handle == INVALID_HANDLE_VALUE)
2684 StreamId.dwStreamId = BACKUP_LINK;
2685 StreamId.dwStreamAttributes = 0;
2686 StreamId.dwStreamNameSize = 0;
2687 #if defined(__BORLANDC__) \
2688 ||(defined(__MINGW32__) && !defined(_ANONYMOUS_UNION))
2689 StreamId.Size.u.HighPart = 0;
2690 StreamId.Size.u.LowPart = dwLen;
2692 StreamId.Size.HighPart = 0;
2693 StreamId.Size.LowPart = dwLen;
2696 bSuccess = pfnBackupWrite(handle, (LPBYTE)&StreamId, dwSize, &dwWritten,
2697 FALSE, FALSE, &lpContext);
2699 bSuccess = pfnBackupWrite(handle, (LPBYTE)wFullName, dwLen, &dwWritten,
2700 FALSE, FALSE, &lpContext);
2701 pfnBackupWrite(handle, NULL, 0, &dwWritten, TRUE, FALSE, &lpContext);
2704 CloseHandle(handle);
2709 win32_link(const char *oldname, const char *newname)
2712 BOOL (__stdcall *pfnCreateHardLinkW)(LPCWSTR,LPCWSTR,LPSECURITY_ATTRIBUTES);
2713 WCHAR wOldName[MAX_PATH+1];
2714 WCHAR wNewName[MAX_PATH+1];
2717 Perl_croak(aTHX_ PL_no_func, "link");
2719 pfnCreateHardLinkW =
2720 (BOOL (__stdcall *)(LPCWSTR, LPCWSTR, LPSECURITY_ATTRIBUTES))
2721 GetProcAddress(GetModuleHandle("kernel32.dll"), "CreateHardLinkW");
2722 if (pfnCreateHardLinkW == NULL)
2723 pfnCreateHardLinkW = Nt4CreateHardLinkW;
2725 if ((A2WHELPER(oldname, wOldName, sizeof(wOldName))) &&
2726 (A2WHELPER(newname, wNewName, sizeof(wNewName))) &&
2727 (wcscpy(wOldName, PerlDir_mapW(wOldName)),
2728 pfnCreateHardLinkW(PerlDir_mapW(wNewName), wOldName, NULL)))
2732 errno = (GetLastError() == ERROR_FILE_NOT_FOUND) ? ENOENT : EINVAL;
2737 win32_rename(const char *oname, const char *newname)
2739 WCHAR wOldName[MAX_PATH+1];
2740 WCHAR wNewName[MAX_PATH+1];
2741 char szOldName[MAX_PATH+1];
2742 char szNewName[MAX_PATH+1];
2746 /* XXX despite what the documentation says about MoveFileEx(),
2747 * it doesn't work under Windows95!
2750 DWORD dwFlags = MOVEFILE_COPY_ALLOWED;
2752 A2WHELPER(oname, wOldName, sizeof(wOldName));
2753 A2WHELPER(newname, wNewName, sizeof(wNewName));
2754 if (wcsicmp(wNewName, wOldName))
2755 dwFlags |= MOVEFILE_REPLACE_EXISTING;
2756 wcscpy(wOldName, PerlDir_mapW(wOldName));
2757 bResult = MoveFileExW(wOldName,PerlDir_mapW(wNewName), dwFlags);
2760 if (stricmp(newname, oname))
2761 dwFlags |= MOVEFILE_REPLACE_EXISTING;
2762 strcpy(szOldName, PerlDir_mapA(oname));
2763 bResult = MoveFileExA(szOldName,PerlDir_mapA(newname), dwFlags);
2766 DWORD err = GetLastError();
2768 case ERROR_BAD_NET_NAME:
2769 case ERROR_BAD_NETPATH:
2770 case ERROR_BAD_PATHNAME:
2771 case ERROR_FILE_NOT_FOUND:
2772 case ERROR_FILENAME_EXCED_RANGE:
2773 case ERROR_INVALID_DRIVE:
2774 case ERROR_NO_MORE_FILES:
2775 case ERROR_PATH_NOT_FOUND:
2788 char szTmpName[MAX_PATH+1];
2789 char dname[MAX_PATH+1];
2790 char *endname = Nullch;
2792 DWORD from_attr, to_attr;
2794 strcpy(szOldName, PerlDir_mapA(oname));
2795 strcpy(szNewName, PerlDir_mapA(newname));
2797 /* if oname doesn't exist, do nothing */
2798 from_attr = GetFileAttributes(szOldName);
2799 if (from_attr == 0xFFFFFFFF) {
2804 /* if newname exists, rename it to a temporary name so that we
2805 * don't delete it in case oname happens to be the same file
2806 * (but perhaps accessed via a different path)
2808 to_attr = GetFileAttributes(szNewName);
2809 if (to_attr != 0xFFFFFFFF) {
2810 /* if newname is a directory, we fail
2811 * XXX could overcome this with yet more convoluted logic */
2812 if (to_attr & FILE_ATTRIBUTE_DIRECTORY) {
2816 tmplen = strlen(szNewName);
2817 strcpy(szTmpName,szNewName);
2818 endname = szTmpName+tmplen;
2819 for (; endname > szTmpName ; --endname) {
2820 if (*endname == '/' || *endname == '\\') {
2825 if (endname > szTmpName)
2826 endname = strcpy(dname,szTmpName);
2830 /* get a temporary filename in same directory
2831 * XXX is this really the best we can do? */
2832 if (!GetTempFileName((LPCTSTR)endname, "plr", 0, szTmpName)) {
2836 DeleteFile(szTmpName);
2838 retval = rename(szNewName, szTmpName);
2845 /* rename oname to newname */
2846 retval = rename(szOldName, szNewName);
2848 /* if we created a temporary file before ... */
2849 if (endname != Nullch) {
2850 /* ...and rename succeeded, delete temporary file/directory */
2852 DeleteFile(szTmpName);
2853 /* else restore it to what it was */
2855 (void)rename(szTmpName, szNewName);
2862 win32_setmode(int fd, int mode)
2864 return setmode(fd, mode);
2868 win32_lseek(int fd, long offset, int origin)
2870 return lseek(fd, offset, origin);
2880 win32_open(const char *path, int flag, ...)
2885 WCHAR wBuffer[MAX_PATH+1];
2888 pmode = va_arg(ap, int);
2891 if (stricmp(path, "/dev/null")==0)
2895 A2WHELPER(path, wBuffer, sizeof(wBuffer));
2896 return _wopen(PerlDir_mapW(wBuffer), flag, pmode);
2898 return open(PerlDir_mapA(path), flag, pmode);
2901 /* close() that understands socket */
2902 extern int my_close(int); /* in win32sck.c */
2907 return my_close(fd);
2923 win32_dup2(int fd1,int fd2)
2925 return dup2(fd1,fd2);
2928 #ifdef PERL_MSVCRT_READFIX
2930 #define LF 10 /* line feed */
2931 #define CR 13 /* carriage return */
2932 #define CTRLZ 26 /* ctrl-z means eof for text */
2933 #define FOPEN 0x01 /* file handle open */
2934 #define FEOFLAG 0x02 /* end of file has been encountered */
2935 #define FCRLF 0x04 /* CR-LF across read buffer (in text mode) */
2936 #define FPIPE 0x08 /* file handle refers to a pipe */
2937 #define FAPPEND 0x20 /* file handle opened O_APPEND */
2938 #define FDEV 0x40 /* file handle refers to device */
2939 #define FTEXT 0x80 /* file handle is in text mode */
2940 #define MAX_DESCRIPTOR_COUNT (64*32) /* this is the maximun that MSVCRT can handle */
2943 _fixed_read(int fh, void *buf, unsigned cnt)
2945 int bytes_read; /* number of bytes read */
2946 char *buffer; /* buffer to read to */
2947 int os_read; /* bytes read on OS call */
2948 char *p, *q; /* pointers into buffer */
2949 char peekchr; /* peek-ahead character */
2950 ULONG filepos; /* file position after seek */
2951 ULONG dosretval; /* o.s. return value */
2953 /* validate handle */
2954 if (((unsigned)fh >= (unsigned)MAX_DESCRIPTOR_COUNT) ||
2955 !(_osfile(fh) & FOPEN))
2957 /* out of range -- return error */
2959 _doserrno = 0; /* not o.s. error */
2964 * If lockinitflag is FALSE, assume fd is device
2965 * lockinitflag is set to TRUE by open.
2967 if (_pioinfo(fh)->lockinitflag)
2968 EnterCriticalSection(&(_pioinfo(fh)->lock)); /* lock file */
2970 bytes_read = 0; /* nothing read yet */
2971 buffer = (char*)buf;
2973 if (cnt == 0 || (_osfile(fh) & FEOFLAG)) {
2974 /* nothing to read or at EOF, so return 0 read */
2978 if ((_osfile(fh) & (FPIPE|FDEV)) && _pipech(fh) != LF) {
2979 /* a pipe/device and pipe lookahead non-empty: read the lookahead
2981 *buffer++ = _pipech(fh);
2984 _pipech(fh) = LF; /* mark as empty */
2989 if (!ReadFile((HANDLE)_osfhnd(fh), buffer, cnt, (LPDWORD)&os_read, NULL))
2991 /* ReadFile has reported an error. recognize two special cases.
2993 * 1. map ERROR_ACCESS_DENIED to EBADF
2995 * 2. just return 0 if ERROR_BROKEN_PIPE has occurred. it
2996 * means the handle is a read-handle on a pipe for which
2997 * all write-handles have been closed and all data has been
3000 if ((dosretval = GetLastError()) == ERROR_ACCESS_DENIED) {
3001 /* wrong read/write mode should return EBADF, not EACCES */
3003 _doserrno = dosretval;
3007 else if (dosretval == ERROR_BROKEN_PIPE) {
3017 bytes_read += os_read; /* update bytes read */
3019 if (_osfile(fh) & FTEXT) {
3020 /* now must translate CR-LFs to LFs in the buffer */
3022 /* set CRLF flag to indicate LF at beginning of buffer */
3023 /* if ((os_read != 0) && (*(char *)buf == LF)) */
3024 /* _osfile(fh) |= FCRLF; */
3026 /* _osfile(fh) &= ~FCRLF; */
3028 _osfile(fh) &= ~FCRLF;
3030 /* convert chars in the buffer: p is src, q is dest */
3032 while (p < (char *)buf + bytes_read) {
3034 /* if fh is not a device, set ctrl-z flag */
3035 if (!(_osfile(fh) & FDEV))
3036 _osfile(fh) |= FEOFLAG;
3037 break; /* stop translating */
3042 /* *p is CR, so must check next char for LF */
3043 if (p < (char *)buf + bytes_read - 1) {
3046 *q++ = LF; /* convert CR-LF to LF */
3049 *q++ = *p++; /* store char normally */
3052 /* This is the hard part. We found a CR at end of
3053 buffer. We must peek ahead to see if next char
3058 if (!ReadFile((HANDLE)_osfhnd(fh), &peekchr, 1,
3059 (LPDWORD)&os_read, NULL))
3060 dosretval = GetLastError();
3062 if (dosretval != 0 || os_read == 0) {
3063 /* couldn't read ahead, store CR */
3067 /* peekchr now has the extra character -- we now
3068 have several possibilities:
3069 1. disk file and char is not LF; just seek back
3071 2. disk file and char is LF; store LF, don't seek back
3072 3. pipe/device and char is LF; store LF.
3073 4. pipe/device and char isn't LF, store CR and
3074 put char in pipe lookahead buffer. */
3075 if (_osfile(fh) & (FDEV|FPIPE)) {
3076 /* non-seekable device */
3081 _pipech(fh) = peekchr;
3086 if (peekchr == LF) {
3087 /* nothing read yet; must make some
3090 /* turn on this flag for tell routine */
3091 _osfile(fh) |= FCRLF;
3094 HANDLE osHandle; /* o.s. handle value */
3096 if ((osHandle = (HANDLE)_get_osfhandle(fh)) != (HANDLE)-1)
3098 if ((filepos = SetFilePointer(osHandle, -1, NULL, FILE_CURRENT)) == -1)
3099 dosretval = GetLastError();
3110 /* we now change bytes_read to reflect the true number of chars
3112 bytes_read = q - (char *)buf;
3116 if (_pioinfo(fh)->lockinitflag)
3117 LeaveCriticalSection(&(_pioinfo(fh)->lock)); /* unlock file */
3122 #endif /* PERL_MSVCRT_READFIX */
3125 win32_read(int fd, void *buf, unsigned int cnt)
3127 #ifdef PERL_MSVCRT_READFIX
3128 return _fixed_read(fd, buf, cnt);
3130 return read(fd, buf, cnt);
3135 win32_write(int fd, const void *buf, unsigned int cnt)
3137 return write(fd, buf, cnt);
3141 win32_mkdir(const char *dir, int mode)
3145 WCHAR wBuffer[MAX_PATH+1];
3146 A2WHELPER(dir, wBuffer, sizeof(wBuffer));
3147 return _wmkdir(PerlDir_mapW(wBuffer));
3149 return mkdir(PerlDir_mapA(dir)); /* just ignore mode */
3153 win32_rmdir(const char *dir)
3157 WCHAR wBuffer[MAX_PATH+1];
3158 A2WHELPER(dir, wBuffer, sizeof(wBuffer));
3159 return _wrmdir(PerlDir_mapW(wBuffer));
3161 return rmdir(PerlDir_mapA(dir));
3165 win32_chdir(const char *dir)
3173 WCHAR wBuffer[MAX_PATH+1];
3174 A2WHELPER(dir, wBuffer, sizeof(wBuffer));
3175 return _wchdir(wBuffer);
3181 win32_access(const char *path, int mode)
3185 WCHAR wBuffer[MAX_PATH+1];
3186 A2WHELPER(path, wBuffer, sizeof(wBuffer));
3187 return _waccess(PerlDir_mapW(wBuffer), mode);
3189 return access(PerlDir_mapA(path), mode);
3193 win32_chmod(const char *path, int mode)
3197 WCHAR wBuffer[MAX_PATH+1];
3198 A2WHELPER(path, wBuffer, sizeof(wBuffer));
3199 return _wchmod(PerlDir_mapW(wBuffer), mode);
3201 return chmod(PerlDir_mapA(path), mode);
3206 create_command_line(char *cname, STRLEN clen, const char * const *args)
3213 bool bat_file = FALSE;
3214 bool cmd_shell = FALSE;
3215 bool dumb_shell = FALSE;
3216 bool extra_quotes = FALSE;
3217 bool quote_next = FALSE;
3220 cname = (char*)args[0];
3222 /* The NT cmd.exe shell has the following peculiarity that needs to be
3223 * worked around. It strips a leading and trailing dquote when any
3224 * of the following is true:
3225 * 1. the /S switch was used
3226 * 2. there are more than two dquotes
3227 * 3. there is a special character from this set: &<>()@^|
3228 * 4. no whitespace characters within the two dquotes
3229 * 5. string between two dquotes isn't an executable file
3230 * To work around this, we always add a leading and trailing dquote
3231 * to the string, if the first argument is either "cmd.exe" or "cmd",
3232 * and there were at least two or more arguments passed to cmd.exe
3233 * (not including switches).
3234 * XXX the above rules (from "cmd /?") don't seem to be applied
3235 * always, making for the convolutions below :-(
3239 clen = strlen(cname);
3242 && (stricmp(&cname[clen-4], ".bat") == 0
3243 || (IsWinNT() && stricmp(&cname[clen-4], ".cmd") == 0)))
3249 char *exe = strrchr(cname, '/');
3250 char *exe2 = strrchr(cname, '\\');
3257 if (stricmp(exe, "cmd.exe") == 0 || stricmp(exe, "cmd") == 0) {
3261 else if (stricmp(exe, "command.com") == 0
3262 || stricmp(exe, "command") == 0)
3269 DEBUG_p(PerlIO_printf(Perl_debug_log, "Args "));
3270 for (index = 0; (arg = (char*)args[index]) != NULL; ++index) {
3271 STRLEN curlen = strlen(arg);
3272 if (!(arg[0] == '"' && arg[curlen-1] == '"'))
3273 len += 2; /* assume quoting needed (worst case) */
3275 DEBUG_p(PerlIO_printf(Perl_debug_log, "[%s]",arg));
3277 DEBUG_p(PerlIO_printf(Perl_debug_log, "\n"));
3280 New(1310, cmd, len, char);
3285 extra_quotes = TRUE;
3288 for (index = 0; (arg = (char*)args[index]) != NULL; ++index) {
3290 STRLEN curlen = strlen(arg);
3292 /* we want to protect empty arguments and ones with spaces with
3293 * dquotes, but only if they aren't already there */
3298 else if (quote_next) {
3299 /* see if it really is multiple arguments pretending to
3300 * be one and force a set of quotes around it */
3301 if (*find_next_space(arg))
3304 else if (!(arg[0] == '"' && curlen > 1 && arg[curlen-1] == '"')) {
3306 while (i < curlen) {
3307 if (isSPACE(arg[i])) {
3310 else if (arg[i] == '"') {
3333 && (stricmp(arg, "/x/c") == 0 || stricmp(arg, "/c") == 0))
3335 /* is there a next argument? */
3336 if (args[index+1]) {
3337 /* are there two or more next arguments? */
3338 if (args[index+2]) {
3340 extra_quotes = TRUE;
3343 /* single argument, force quoting if it has spaces */
3359 qualified_path(const char *cmd)
3363 char *fullcmd, *curfullcmd;
3369 fullcmd = (char*)cmd;
3371 if (*fullcmd == '/' || *fullcmd == '\\')
3378 pathstr = PerlEnv_getenv("PATH");
3379 New(0, fullcmd, MAX_PATH+1, char);
3380 curfullcmd = fullcmd;
3385 /* start by appending the name to the current prefix */
3386 strcpy(curfullcmd, cmd);
3387 curfullcmd += cmdlen;
3389 /* if it doesn't end with '.', or has no extension, try adding
3390 * a trailing .exe first */
3391 if (cmd[cmdlen-1] != '.'
3392 && (cmdlen < 4 || cmd[cmdlen-4] != '.'))
3394 strcpy(curfullcmd, ".exe");
3395 res = GetFileAttributes(fullcmd);
3396 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
3401 /* that failed, try the bare name */
3402 res = GetFileAttributes(fullcmd);
3403 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
3406 /* quit if no other path exists, or if cmd already has path */
3407 if (!pathstr || !*pathstr || has_slash)
3410 /* skip leading semis */
3411 while (*pathstr == ';')
3414 /* build a new prefix from scratch */
3415 curfullcmd = fullcmd;
3416 while (*pathstr && *pathstr != ';') {
3417 if (*pathstr == '"') { /* foo;"baz;etc";bar */
3418 pathstr++; /* skip initial '"' */
3419 while (*pathstr && *pathstr != '"') {
3420 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
3421 *curfullcmd++ = *pathstr;
3425 pathstr++; /* skip trailing '"' */
3428 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
3429 *curfullcmd++ = *pathstr;
3434 pathstr++; /* skip trailing semi */
3435 if (curfullcmd > fullcmd /* append a dir separator */
3436 && curfullcmd[-1] != '/' && curfullcmd[-1] != '\\')
3438 *curfullcmd++ = '\\';
3446 /* The following are just place holders.
3447 * Some hosts may provide and environment that the OS is
3448 * not tracking, therefore, these host must provide that
3449 * environment and the current directory to CreateProcess
3453 win32_get_childenv(void)
3459 win32_free_childenv(void* d)
3464 win32_clearenv(void)
3466 char *envv = GetEnvironmentStrings();
3470 char *end = strchr(cur,'=');
3471 if (end && end != cur) {
3473 SetEnvironmentVariable(cur, NULL);
3475 cur = end + strlen(end+1)+2;
3477 else if ((len = strlen(cur)))
3480 FreeEnvironmentStrings(envv);
3484 win32_get_childdir(void)
3488 char szfilename[(MAX_PATH+1)*2];
3490 WCHAR wfilename[MAX_PATH+1];
3491 GetCurrentDirectoryW(MAX_PATH+1, wfilename);
3492 W2AHELPER(wfilename, szfilename, sizeof(szfilename));
3495 GetCurrentDirectoryA(MAX_PATH+1, szfilename);
3498 New(0, ptr, strlen(szfilename)+1, char);
3499 strcpy(ptr, szfilename);
3504 win32_free_childdir(char* d)
3511 /* XXX this needs to be made more compatible with the spawnvp()
3512 * provided by the various RTLs. In particular, searching for
3513 * *.{com,bat,cmd} files (as done by the RTLs) is unimplemented.
3514 * This doesn't significantly affect perl itself, because we
3515 * always invoke things using PERL5SHELL if a direct attempt to
3516 * spawn the executable fails.
3518 * XXX splitting and rejoining the commandline between do_aspawn()
3519 * and win32_spawnvp() could also be avoided.
3523 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
3525 #ifdef USE_RTL_SPAWNVP
3526 return spawnvp(mode, cmdname, (char * const *)argv);
3533 STARTUPINFO StartupInfo;
3534 PROCESS_INFORMATION ProcessInformation;
3537 char *fullcmd = Nullch;
3538 char *cname = (char *)cmdname;
3542 clen = strlen(cname);
3543 /* if command name contains dquotes, must remove them */
3544 if (strchr(cname, '"')) {
3546 New(0,cname,clen+1,char);
3559 cmd = create_command_line(cname, clen, argv);
3561 env = PerlEnv_get_childenv();
3562 dir = PerlEnv_get_childdir();
3565 case P_NOWAIT: /* asynch + remember result */
3566 if (w32_num_children >= MAXIMUM_WAIT_OBJECTS) {
3571 /* Create a new process group so we can use GenerateConsoleCtrlEvent()
3574 create |= CREATE_NEW_PROCESS_GROUP;
3577 case P_WAIT: /* synchronous execution */
3579 default: /* invalid mode */
3584 memset(&StartupInfo,0,sizeof(StartupInfo));
3585 StartupInfo.cb = sizeof(StartupInfo);
3586 memset(&tbl,0,sizeof(tbl));
3587 PerlEnv_get_child_IO(&tbl);
3588 StartupInfo.dwFlags = tbl.dwFlags;
3589 StartupInfo.dwX = tbl.dwX;
3590 StartupInfo.dwY = tbl.dwY;
3591 StartupInfo.dwXSize = tbl.dwXSize;
3592 StartupInfo.dwYSize = tbl.dwYSize;
3593 StartupInfo.dwXCountChars = tbl.dwXCountChars;
3594 StartupInfo.dwYCountChars = tbl.dwYCountChars;
3595 StartupInfo.dwFillAttribute = tbl.dwFillAttribute;
3596 StartupInfo.wShowWindow = tbl.wShowWindow;
3597 StartupInfo.hStdInput = tbl.childStdIn;
3598 StartupInfo.hStdOutput = tbl.childStdOut;
3599 StartupInfo.hStdError = tbl.childStdErr;
3600 if (StartupInfo.hStdInput != INVALID_HANDLE_VALUE &&
3601 StartupInfo.hStdOutput != INVALID_HANDLE_VALUE &&
3602 StartupInfo.hStdError != INVALID_HANDLE_VALUE)
3604 StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
3607 create |= CREATE_NEW_CONSOLE;
3610 DEBUG_p(PerlIO_printf(Perl_debug_log, "Spawning [%s] with [%s]\n",
3613 if (!CreateProcess(cname, /* search PATH to find executable */
3614 cmd, /* executable, and its arguments */
3615 NULL, /* process attributes */
3616 NULL, /* thread attributes */
3617 TRUE, /* inherit handles */
3618 create, /* creation flags */
3619 (LPVOID)env, /* inherit environment */
3620 dir, /* inherit cwd */
3622 &ProcessInformation))
3624 /* initial NULL argument to CreateProcess() does a PATH
3625 * search, but it always first looks in the directory
3626 * where the current process was started, which behavior
3627 * is undesirable for backward compatibility. So we
3628 * jump through our own hoops by picking out the path
3629 * we really want it to use. */
3631 fullcmd = qualified_path(cname);
3633 if (cname != cmdname)
3636 DEBUG_p(PerlIO_printf(Perl_debug_log,
3637 "Retrying [%s] with same args\n",
3647 if (mode == P_NOWAIT) {
3648 /* asynchronous spawn -- store handle, return PID */
3649 ret = (int)ProcessInformation.dwProcessId;
3650 if (IsWin95() && ret < 0)
3653 w32_child_handles[w32_num_children] = ProcessInformation.hProcess;
3654 w32_child_pids[w32_num_children] = (DWORD)ret;
3659 win32_msgwait(aTHX_ 1, &ProcessInformation.hProcess, INFINITE, NULL);
3660 /* FIXME: if msgwait returned due to message perhaps forward the
3661 "signal" to the process
3663 GetExitCodeProcess(ProcessInformation.hProcess, &status);
3665 CloseHandle(ProcessInformation.hProcess);
3668 CloseHandle(ProcessInformation.hThread);
3671 PerlEnv_free_childenv(env);
3672 PerlEnv_free_childdir(dir);
3674 if (cname != cmdname)
3681 win32_execv(const char *cmdname, const char *const *argv)
3685 /* if this is a pseudo-forked child, we just want to spawn
3686 * the new program, and return */
3688 return spawnv(P_WAIT, cmdname, (char *const *)argv);
3690 return execv(cmdname, (char *const *)argv);
3694 win32_execvp(const char *cmdname, const char *const *argv)
3698 /* if this is a pseudo-forked child, we just want to spawn
3699 * the new program, and return */
3700 if (w32_pseudo_id) {
3701 int status = win32_spawnvp(P_WAIT, cmdname, (char *const *)argv);
3710 return execvp(cmdname, (char *const *)argv);
3714 win32_perror(const char *str)
3720 win32_setbuf(FILE *pf, char *buf)
3726 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
3728 return setvbuf(pf, buf, type, size);
3732 win32_flushall(void)
3738 win32_fcloseall(void)
3744 win32_fgets(char *s, int n, FILE *pf)
3746 return fgets(s, n, pf);
3756 win32_fgetc(FILE *pf)
3762 win32_putc(int c, FILE *pf)
3768 win32_puts(const char *s)
3780 win32_putchar(int c)
3787 #ifndef USE_PERL_SBRK
3789 static char *committed = NULL; /* XXX threadead */
3790 static char *base = NULL; /* XXX threadead */
3791 static char *reserved = NULL; /* XXX threadead */
3792 static char *brk = NULL; /* XXX threadead */
3793 static DWORD pagesize = 0; /* XXX threadead */
3794 static DWORD allocsize = 0; /* XXX threadead */
3802 GetSystemInfo(&info);
3803 /* Pretend page size is larger so we don't perpetually
3804 * call the OS to commit just one page ...
3806 pagesize = info.dwPageSize << 3;
3807 allocsize = info.dwAllocationGranularity;
3809 /* This scheme fails eventually if request for contiguous
3810 * block is denied so reserve big blocks - this is only
3811 * address space not memory ...
3813 if (brk+need >= reserved)
3815 DWORD size = 64*1024*1024;
3817 if (committed && reserved && committed < reserved)
3819 /* Commit last of previous chunk cannot span allocations */
3820 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
3822 committed = reserved;
3824 /* Reserve some (more) space
3825 * Note this is a little sneaky, 1st call passes NULL as reserved
3826 * so lets system choose where we start, subsequent calls pass
3827 * the old end address so ask for a contiguous block
3829 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
3832 reserved = addr+size;
3847 if (brk > committed)
3849 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
3850 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
3865 win32_malloc(size_t size)
3867 return malloc(size);
3871 win32_calloc(size_t numitems, size_t size)
3873 return calloc(numitems,size);
3877 win32_realloc(void *block, size_t size)
3879 return realloc(block,size);
3883 win32_free(void *block)
3890 win32_open_osfhandle(long handle, int flags)
3892 #ifdef USE_FIXED_OSFHANDLE
3894 return my_open_osfhandle(handle, flags);
3896 return _open_osfhandle(handle, flags);
3900 win32_get_osfhandle(int fd)
3902 return _get_osfhandle(fd);
3906 win32_dynaload(const char* filename)
3910 char buf[MAX_PATH+1];
3913 /* LoadLibrary() doesn't recognize forward slashes correctly,
3914 * so turn 'em back. */
3915 first = strchr(filename, '/');
3917 STRLEN len = strlen(filename);
3918 if (len <= MAX_PATH) {
3919 strcpy(buf, filename);
3920 filename = &buf[first - filename];
3922 if (*filename == '/')
3923 *(char*)filename = '\\';
3930 WCHAR wfilename[MAX_PATH+1];
3931 A2WHELPER(filename, wfilename, sizeof(wfilename));
3932 hModule = LoadLibraryExW(PerlDir_mapW(wfilename), NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
3935 hModule = LoadLibraryExA(PerlDir_mapA(filename), NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
3948 /* Make the host for current directory */
3949 char* ptr = PerlEnv_get_childdir();
3952 * then it worked, set PV valid,
3953 * else return 'undef'
3956 SV *sv = sv_newmortal();
3958 PerlEnv_free_childdir(ptr);
3960 #ifndef INCOMPLETE_TAINTS
3977 Perl_croak(aTHX_ "usage: Win32::SetCurrentDirectory($cwd)");
3978 if (!PerlDir_chdir(SvPV_nolen(ST(0))))
3985 XS(w32_GetNextAvailDrive)
3989 char root[] = "_:\\";
3994 if (GetDriveType(root) == 1) {
4003 XS(w32_GetLastError)
4007 XSRETURN_IV(GetLastError());
4011 XS(w32_SetLastError)
4015 Perl_croak(aTHX_ "usage: Win32::SetLastError($error)");
4016 SetLastError(SvIV(ST(0)));
4024 char *name = w32_getlogin_buffer;
4025 DWORD size = sizeof(w32_getlogin_buffer);
4027 if (GetUserName(name,&size)) {
4028 /* size includes NULL */
4029 ST(0) = sv_2mortal(newSVpvn(name,size-1));
4039 char name[MAX_COMPUTERNAME_LENGTH+1];
4040 DWORD size = sizeof(name);
4042 if (GetComputerName(name,&size)) {
4043 /* size does NOT include NULL :-( */
4044 ST(0) = sv_2mortal(newSVpvn(name,size));
4055 HINSTANCE hNetApi32 = LoadLibrary("netapi32.dll");
4056 DWORD (__stdcall *pfnNetApiBufferFree)(LPVOID Buffer);
4057 DWORD (__stdcall *pfnNetWkstaGetInfo)(LPWSTR servername, DWORD level,
4061 pfnNetApiBufferFree = (DWORD (__stdcall *)(void *))
4062 GetProcAddress(hNetApi32, "NetApiBufferFree");
4063 pfnNetWkstaGetInfo = (DWORD (__stdcall *)(LPWSTR, DWORD, void *))
4064 GetProcAddress(hNetApi32, "NetWkstaGetInfo");
4067 if (hNetApi32 && pfnNetWkstaGetInfo && pfnNetApiBufferFree) {
4068 /* this way is more reliable, in case user has a local account. */
4070 DWORD dnamelen = sizeof(dname);
4072 DWORD wki100_platform_id;
4073 LPWSTR wki100_computername;
4074 LPWSTR wki100_langroup;
4075 DWORD wki100_ver_major;
4076 DWORD wki100_ver_minor;
4078 /* NERR_Success *is* 0*/
4079 if (0 == pfnNetWkstaGetInfo(NULL, 100, &pwi)) {
4080 if (pwi->wki100_langroup && *(pwi->wki100_langroup)) {
4081 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_langroup,
4082 -1, (LPSTR)dname, dnamelen, NULL, NULL);
4085 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_computername,
4086 -1, (LPSTR)dname, dnamelen, NULL, NULL);
4088 pfnNetApiBufferFree(pwi);
4089 FreeLibrary(hNetApi32);
4092 FreeLibrary(hNetApi32);
4095 /* Win95 doesn't have NetWksta*(), so do it the old way */
4097 DWORD size = sizeof(name);
4099 FreeLibrary(hNetApi32);
4100 if (GetUserName(name,&size)) {
4101 char sid[ONE_K_BUFSIZE];
4102 DWORD sidlen = sizeof(sid);
4104 DWORD dnamelen = sizeof(dname);
4106 if (LookupAccountName(NULL, name, (PSID)&sid, &sidlen,
4107 dname, &dnamelen, &snu)) {
4108 XSRETURN_PV(dname); /* all that for this */
4120 DWORD flags, filecomplen;
4121 if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
4122 &flags, fsname, sizeof(fsname))) {
4123 if (GIMME_V == G_ARRAY) {
4124 XPUSHs(sv_2mortal(newSVpvn(fsname,strlen(fsname))));
4125 XPUSHs(sv_2mortal(newSViv(flags)));
4126 XPUSHs(sv_2mortal(newSViv(filecomplen)));
4131 XSRETURN_PV(fsname);
4137 XS(w32_GetOSVersion)
4140 OSVERSIONINFOA osver;
4143 OSVERSIONINFOW osverw;
4144 char szCSDVersion[sizeof(osverw.szCSDVersion)];
4145 osverw.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
4146 if (!GetVersionExW(&osverw)) {
4149 W2AHELPER(osverw.szCSDVersion, szCSDVersion, sizeof(szCSDVersion));
4150 XPUSHs(newSVpvn(szCSDVersion, strlen(szCSDVersion)));
4151 osver.dwMajorVersion = osverw.dwMajorVersion;
4152 osver.dwMinorVersion = osverw.dwMinorVersion;
4153 osver.dwBuildNumber = osverw.dwBuildNumber;
4154 osver.dwPlatformId = osverw.dwPlatformId;
4157 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOA);
4158 if (!GetVersionExA(&osver)) {
4161 XPUSHs(newSVpvn(osver.szCSDVersion, strlen(osver.szCSDVersion)));
4163 XPUSHs(newSViv(osver.dwMajorVersion));
4164 XPUSHs(newSViv(osver.dwMinorVersion));
4165 XPUSHs(newSViv(osver.dwBuildNumber));
4166 XPUSHs(newSViv(osver.dwPlatformId));
4175 XSRETURN_IV(IsWinNT());
4183 XSRETURN_IV(IsWin95());
4187 XS(w32_FormatMessage)
4191 char msgbuf[ONE_K_BUFSIZE];
4194 Perl_croak(aTHX_ "usage: Win32::FormatMessage($errno)");
4197 WCHAR wmsgbuf[ONE_K_BUFSIZE];
4198 if (FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM,
4199 &source, SvIV(ST(0)), 0,
4200 wmsgbuf, ONE_K_BUFSIZE-1, NULL))
4202 W2AHELPER(wmsgbuf, msgbuf, sizeof(msgbuf));
4203 XSRETURN_PV(msgbuf);
4207 if (FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM,
4208 &source, SvIV(ST(0)), 0,
4209 msgbuf, sizeof(msgbuf)-1, NULL))
4210 XSRETURN_PV(msgbuf);
4223 PROCESS_INFORMATION stProcInfo;
4224 STARTUPINFO stStartInfo;
4225 BOOL bSuccess = FALSE;
4228 Perl_croak(aTHX_ "usage: Win32::Spawn($cmdName, $args, $PID)");
4230 cmd = SvPV_nolen(ST(0));
4231 args = SvPV_nolen(ST(1));
4233 env = PerlEnv_get_childenv();
4234 dir = PerlEnv_get_childdir();
4236 memset(&stStartInfo, 0, sizeof(stStartInfo)); /* Clear the block */
4237 stStartInfo.cb = sizeof(stStartInfo); /* Set the structure size */
4238 stStartInfo.dwFlags = STARTF_USESHOWWINDOW; /* Enable wShowWindow control */
4239 stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE; /* Start min (normal) */
4242 cmd, /* Image path */
4243 args, /* Arguments for command line */
4244 NULL, /* Default process security */
4245 NULL, /* Default thread security */
4246 FALSE, /* Must be TRUE to use std handles */
4247 NORMAL_PRIORITY_CLASS, /* No special scheduling */
4248 env, /* Inherit our environment block */
4249 dir, /* Inherit our currrent directory */
4250 &stStartInfo, /* -> Startup info */
4251 &stProcInfo)) /* <- Process info (if OK) */
4253 int pid = (int)stProcInfo.dwProcessId;
4254 if (IsWin95() && pid < 0)
4256 sv_setiv(ST(2), pid);
4257 CloseHandle(stProcInfo.hThread);/* library source code does this. */
4260 PerlEnv_free_childenv(env);
4261 PerlEnv_free_childdir(dir);
4262 XSRETURN_IV(bSuccess);
4266 XS(w32_GetTickCount)
4269 DWORD msec = GetTickCount();
4277 XS(w32_GetShortPathName)
4284 Perl_croak(aTHX_ "usage: Win32::GetShortPathName($longPathName)");
4286 shortpath = sv_mortalcopy(ST(0));
4287 SvUPGRADE(shortpath, SVt_PV);
4288 if (!SvPVX(shortpath) || !SvLEN(shortpath))
4291 /* src == target is allowed */
4293 len = GetShortPathName(SvPVX(shortpath),
4296 } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
4298 SvCUR_set(shortpath,len);
4306 XS(w32_GetFullPathName)
4315 Perl_croak(aTHX_ "usage: Win32::GetFullPathName($filename)");
4318 fullpath = sv_mortalcopy(filename);
4319 SvUPGRADE(fullpath, SVt_PV);
4320 if (!SvPVX(fullpath) || !SvLEN(fullpath))
4324 len = GetFullPathName(SvPVX(filename),
4328 } while (len >= SvLEN(fullpath) && sv_grow(fullpath,len+1));
4330 if (GIMME_V == G_ARRAY) {
4332 XST_mPV(1,filepart);
4333 len = filepart - SvPVX(fullpath);
4336 SvCUR_set(fullpath,len);
4344 XS(w32_GetLongPathName)
4348 char tmpbuf[MAX_PATH+1];
4353 Perl_croak(aTHX_ "usage: Win32::GetLongPathName($pathname)");
4356 pathstr = SvPV(path,len);
4357 strcpy(tmpbuf, pathstr);
4358 pathstr = win32_longpath(tmpbuf);
4360 ST(0) = sv_2mortal(newSVpvn(pathstr, strlen(pathstr)));
4371 Perl_croak(aTHX_ "usage: Win32::Sleep($milliseconds)");
4382 Perl_croak(aTHX_ "usage: Win32::CopyFile($from, $to, $overwrite)");
4384 WCHAR wSourceFile[MAX_PATH+1];
4385 WCHAR wDestFile[MAX_PATH+1];
4386 A2WHELPER(SvPV_nolen(ST(0)), wSourceFile, sizeof(wSourceFile));
4387 wcscpy(wSourceFile, PerlDir_mapW(wSourceFile));
4388 A2WHELPER(SvPV_nolen(ST(1)), wDestFile, sizeof(wDestFile));
4389 bResult = CopyFileW(wSourceFile, PerlDir_mapW(wDestFile), !SvTRUE(ST(2)));
4392 char szSourceFile[MAX_PATH+1];
4393 strcpy(szSourceFile, PerlDir_mapA(SvPV_nolen(ST(0))));
4394 bResult = CopyFileA(szSourceFile, PerlDir_mapA(SvPV_nolen(ST(1))), !SvTRUE(ST(2)));
4403 Perl_init_os_extras(void)
4406 char *file = __FILE__;
4409 /* these names are Activeware compatible */
4410 newXS("Win32::GetCwd", w32_GetCwd, file);
4411 newXS("Win32::SetCwd", w32_SetCwd, file);
4412 newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
4413 newXS("Win32::GetLastError", w32_GetLastError, file);
4414 newXS("Win32::SetLastError", w32_SetLastError, file);
4415 newXS("Win32::LoginName", w32_LoginName, file);
4416 newXS("Win32::NodeName", w32_NodeName, file);
4417 newXS("Win32::DomainName", w32_DomainName, file);
4418 newXS("Win32::FsType", w32_FsType, file);
4419 newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
4420 newXS("Win32::IsWinNT", w32_IsWinNT, file);
4421 newXS("Win32::IsWin95", w32_IsWin95, file);
4422 newXS("Win32::FormatMessage", w32_FormatMessage, file);
4423 newXS("Win32::Spawn", w32_Spawn, file);
4424 newXS("Win32::GetTickCount", w32_GetTickCount, file);
4425 newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
4426 newXS("Win32::GetFullPathName", w32_GetFullPathName, file);
4427 newXS("Win32::GetLongPathName", w32_GetLongPathName, file);
4428 newXS("Win32::CopyFile", w32_CopyFile, file);
4429 newXS("Win32::Sleep", w32_Sleep, file);
4431 /* XXX Bloat Alert! The following Activeware preloads really
4432 * ought to be part of Win32::Sys::*, so they're not included
4435 /* LookupAccountName
4437 * InitiateSystemShutdown
4438 * AbortSystemShutdown
4439 * ExpandEnvrironmentStrings
4444 Perl_win32_init(int *argcp, char ***argvp)
4446 /* Disable floating point errors, Perl will trap the ones we
4447 * care about. VC++ RTL defaults to switching these off
4448 * already, but the Borland RTL doesn't. Since we don't
4449 * want to be at the vendor's whim on the default, we set
4450 * it explicitly here.
4452 #if !defined(_ALPHA_) && !defined(__GNUC__)
4453 _control87(MCW_EM, MCW_EM);
4459 win32_get_child_IO(child_IO_table* ptbl)
4461 ptbl->childStdIn = GetStdHandle(STD_INPUT_HANDLE);
4462 ptbl->childStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
4463 ptbl->childStdErr = GetStdHandle(STD_ERROR_HANDLE);
4466 #ifdef HAVE_INTERP_INTERN
4469 Perl_sys_intern_init(pTHX)
4471 w32_perlshell_tokens = Nullch;
4472 w32_perlshell_vec = (char**)NULL;
4473 w32_perlshell_items = 0;
4474 w32_fdpid = newAV();
4475 New(1313, w32_children, 1, child_tab);
4476 w32_num_children = 0;
4477 # ifdef USE_ITHREADS
4479 New(1313, w32_pseudo_children, 1, child_tab);
4480 w32_num_pseudo_children = 0;
4482 w32_init_socktype = 0;
4486 Perl_sys_intern_clear(pTHX)
4488 Safefree(w32_perlshell_tokens);
4489 Safefree(w32_perlshell_vec);
4490 /* NOTE: w32_fdpid is freed by sv_clean_all() */
4491 Safefree(w32_children);
4492 # ifdef USE_ITHREADS
4493 Safefree(w32_pseudo_children);
4497 # ifdef USE_ITHREADS
4500 Perl_sys_intern_dup(pTHX_ struct interp_intern *src, struct interp_intern *dst)
4502 dst->perlshell_tokens = Nullch;
4503 dst->perlshell_vec = (char**)NULL;
4504 dst->perlshell_items = 0;
4505 dst->fdpid = newAV();
4506 Newz(1313, dst->children, 1, child_tab);
4508 Newz(1313, dst->pseudo_children, 1, child_tab);
4509 dst->thr_intern.Winit_socktype = 0;
4511 # endif /* USE_ITHREADS */
4512 #endif /* HAVE_INTERP_INTERN */
4515 win32_free_argvw(pTHX_ void *ptr)
4517 char** argv = (char**)ptr;
4525 win32_argv2utf8(int argc, char** argv)
4530 LPWSTR* lpwStr = CommandLineToArgvW(GetCommandLineW(), &wargc);
4531 if (lpwStr && argc) {
4533 length = WideCharToMultiByte(CP_UTF8, 0, lpwStr[--wargc], -1, NULL, 0, NULL, NULL);
4534 Newz(0, psz, length, char);
4535 WideCharToMultiByte(CP_UTF8, 0, lpwStr[wargc], -1, psz, length, NULL, NULL);
4538 call_atexit(win32_free_argvw, argv);
4540 GlobalFree((HGLOBAL)lpwStr);