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
21 /* #include "config.h" */
23 #define PERLIO_NOT_STDIO 0
24 #if !defined(PERLIO_IS_STDIO) && !defined(USE_SFIO)
33 #define PERL_NO_GET_CONTEXT
39 /* assert.h conflicts with #define of assert in perl.h */
46 #if defined(_MSC_VER) || defined(__MINGW32__)
47 #include <sys/utime.h>
53 /* Mingw32 defaults to globing command line
54 * So we turn it off like this:
59 #if defined(__MINGW32__)
63 #if defined(__BORLANDC__)
65 # define _utimbuf utimbuf
70 #define EXECF_SPAWN_NOWAIT 3
72 #if defined(PERL_IMPLICIT_SYS)
73 # undef win32_get_privlib
74 # define win32_get_privlib g_win32_get_privlib
75 # undef win32_get_sitelib
76 # define win32_get_sitelib g_win32_get_sitelib
78 # define do_spawn g_do_spawn
80 # define getlogin g_getlogin
83 #if defined(PERL_OBJECT)
85 # define do_aspawn g_do_aspawn
87 # define Perl_do_exec g_do_exec
90 static void get_shell(void);
91 static long tokenize(const char *str, char **dest, char ***destv);
92 int do_spawn2(char *cmd, int exectype);
93 static BOOL has_shell_metachars(char *ptr);
94 static long filetime_to_clock(PFILETIME ft);
95 static BOOL filetime_from_time(PFILETIME ft, time_t t);
96 static char * get_emd_part(SV **leading, char *trailing, ...);
97 static void remove_dead_process(long deceased);
98 static long find_pid(int pid);
99 static char * qualified_path(const char *cmd);
101 static void remove_dead_pseudo_process(long child);
102 static long find_pseudo_pid(int pid);
106 HANDLE w32_perldll_handle = INVALID_HANDLE_VALUE;
107 char w32_module_name[MAX_PATH+1];
110 static DWORD w32_platform = (DWORD)-1;
112 #define ONE_K_BUFSIZE 1024
117 return (win32_os_id() == VER_PLATFORM_WIN32_WINDOWS);
123 return (win32_os_id() == VER_PLATFORM_WIN32_NT);
126 /* *svp (if non-NULL) is expected to be POK (valid allocated SvPVX(*svp)) */
128 get_regstr_from(HKEY hkey, const char *valuename, SV **svp)
130 /* Retrieve a REG_SZ or REG_EXPAND_SZ from the registry */
133 const char *subkey = "Software\\Perl";
137 retval = RegOpenKeyEx(hkey, subkey, 0, KEY_READ, &handle);
138 if (retval == ERROR_SUCCESS) {
140 retval = RegQueryValueEx(handle, valuename, 0, &type, NULL, &datalen);
141 if (retval == ERROR_SUCCESS && type == REG_SZ) {
144 *svp = sv_2mortal(newSVpvn("",0));
145 SvGROW(*svp, datalen);
146 retval = RegQueryValueEx(handle, valuename, 0, NULL,
147 (PBYTE)SvPVX(*svp), &datalen);
148 if (retval == ERROR_SUCCESS) {
150 SvCUR_set(*svp,datalen-1);
158 /* *svp (if non-NULL) is expected to be POK (valid allocated SvPVX(*svp)) */
160 get_regstr(const char *valuename, SV **svp)
162 char *str = get_regstr_from(HKEY_CURRENT_USER, valuename, svp);
164 str = get_regstr_from(HKEY_LOCAL_MACHINE, valuename, svp);
168 /* *prev_pathp (if non-NULL) is expected to be POK (valid allocated SvPVX(sv)) */
170 get_emd_part(SV **prev_pathp, char *trailing_path, ...)
174 char mod_name[MAX_PATH+1];
178 int oldsize, newsize;
181 va_start(ap, trailing_path);
182 strip = va_arg(ap, char *);
184 sprintf(base, "%d.%d", (int)PERL_REVISION, (int)PERL_VERSION);
185 baselen = strlen(base);
187 if (!*w32_module_name) {
188 GetModuleFileName((HMODULE)((w32_perldll_handle == INVALID_HANDLE_VALUE)
189 ? GetModuleHandle(NULL)
190 : w32_perldll_handle),
191 w32_module_name, sizeof(w32_module_name));
193 /* try to get full path to binary (which may be mangled when perl is
194 * run from a 16-bit app) */
195 /*PerlIO_printf(Perl_debug_log, "Before %s\n", w32_module_name);*/
196 (void)win32_longpath(w32_module_name);
197 /*PerlIO_printf(Perl_debug_log, "After %s\n", w32_module_name);*/
199 /* normalize to forward slashes */
200 ptr = w32_module_name;
207 strcpy(mod_name, w32_module_name);
208 ptr = strrchr(mod_name, '/');
209 while (ptr && strip) {
210 /* look for directories to skip back */
213 ptr = strrchr(mod_name, '/');
214 /* avoid stripping component if there is no slash,
215 * or it doesn't match ... */
216 if (!ptr || stricmp(ptr+1, strip) != 0) {
217 /* ... but not if component matches m|5\.$patchlevel.*| */
218 if (!ptr || !(*strip == '5' && *(ptr+1) == '5'
219 && strncmp(strip, base, baselen) == 0
220 && strncmp(ptr+1, base, baselen) == 0))
226 strip = va_arg(ap, char *);
234 strcpy(++ptr, trailing_path);
236 /* only add directory if it exists */
237 if (GetFileAttributes(mod_name) != (DWORD) -1) {
238 /* directory exists */
241 *prev_pathp = sv_2mortal(newSVpvn("",0));
242 sv_catpvn(*prev_pathp, ";", 1);
243 sv_catpv(*prev_pathp, mod_name);
244 return SvPVX(*prev_pathp);
251 win32_get_privlib(char *pl)
254 char *stdlib = "lib";
255 char buffer[MAX_PATH+1];
258 /* $stdlib = $HKCU{"lib-$]"} || $HKLM{"lib-$]"} || $HKCU{"lib"} || $HKLM{"lib"} || ""; */
259 sprintf(buffer, "%s-%s", stdlib, pl);
260 if (!get_regstr(buffer, &sv))
261 (void)get_regstr(stdlib, &sv);
263 /* $stdlib .= ";$EMD/../../lib" */
264 return get_emd_part(&sv, stdlib, ARCHNAME, "bin", Nullch);
268 win32_get_sitelib(char *pl)
271 char *sitelib = "sitelib";
273 char pathstr[MAX_PATH+1];
279 /* $HKCU{"sitelib-$]"} || $HKLM{"sitelib-$]"} . ---; */
280 sprintf(regstr, "%s-%s", sitelib, pl);
281 (void)get_regstr(regstr, &sv1);
284 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/site/$]/lib"; */
285 sprintf(pathstr, "site/%s/lib", pl);
286 (void)get_emd_part(&sv1, pathstr, ARCHNAME, "bin", pl, Nullch);
288 /* $HKCU{'sitelib'} || $HKLM{'sitelib'} . ---; */
289 (void)get_regstr(sitelib, &sv2);
292 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/site/lib"; */
293 (void)get_emd_part(&sv2, "site/lib", ARCHNAME, "bin", pl, Nullch);
302 sv_catpvn(sv1, ";", 1);
310 has_shell_metachars(char *ptr)
316 * Scan string looking for redirection (< or >) or pipe
317 * characters (|) that are not in a quoted string.
318 * Shell variable interpolation (%VAR%) can also happen inside strings.
350 #if !defined(PERL_IMPLICIT_SYS)
351 /* since the current process environment is being updated in util.c
352 * the library functions will get the correct environment
355 Perl_my_popen(pTHX_ char *cmd, char *mode)
358 #define fixcmd(x) { \
359 char *pspace = strchr((x),' '); \
362 while (p < pspace) { \
373 PERL_FLUSHALL_FOR_CHILD;
374 return win32_popen(cmd, mode);
378 Perl_my_pclose(pTHX_ PerlIO *fp)
380 return win32_pclose(fp);
384 DllExport unsigned long
387 static OSVERSIONINFO osver;
389 if (osver.dwPlatformId != w32_platform) {
390 memset(&osver, 0, sizeof(OSVERSIONINFO));
391 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
392 GetVersionEx(&osver);
393 w32_platform = osver.dwPlatformId;
395 return (unsigned long)w32_platform;
404 return -((int)w32_pseudo_id);
409 /* Tokenize a string. Words are null-separated, and the list
410 * ends with a doubled null. Any character (except null and
411 * including backslash) may be escaped by preceding it with a
412 * backslash (the backslash will be stripped).
413 * Returns number of words in result buffer.
416 tokenize(const char *str, char **dest, char ***destv)
418 char *retstart = Nullch;
419 char **retvstart = 0;
423 int slen = strlen(str);
425 register char **retv;
426 New(1307, ret, slen+2, char);
427 New(1308, retv, (slen+3)/2, char*);
435 if (*ret == '\\' && *str)
437 else if (*ret == ' ') {
453 retvstart[items] = Nullch;
466 if (!w32_perlshell_tokens) {
467 /* we don't use COMSPEC here for two reasons:
468 * 1. the same reason perl on UNIX doesn't use SHELL--rampant and
469 * uncontrolled unportability of the ensuing scripts.
470 * 2. PERL5SHELL could be set to a shell that may not be fit for
471 * interactive use (which is what most programs look in COMSPEC
474 const char* defaultshell = (IsWinNT()
475 ? "cmd.exe /x/c" : "command.com /c");
476 const char *usershell = getenv("PERL5SHELL");
477 w32_perlshell_items = tokenize(usershell ? usershell : defaultshell,
478 &w32_perlshell_tokens,
484 do_aspawn(void *vreally, void **vmark, void **vsp)
487 SV *really = (SV*)vreally;
488 SV **mark = (SV**)vmark;
500 New(1306, argv, (sp - mark) + w32_perlshell_items + 2, char*);
502 if (SvNIOKp(*(mark+1)) && !SvPOKp(*(mark+1))) {
507 while (++mark <= sp) {
508 if (*mark && (str = SvPV_nolen(*mark)))
515 status = win32_spawnvp(flag,
516 (const char*)(really ? SvPV_nolen(really) : argv[0]),
517 (const char* const*)argv);
519 if (status < 0 && (errno == ENOEXEC || errno == ENOENT)) {
520 /* possible shell-builtin, invoke with shell */
522 sh_items = w32_perlshell_items;
524 argv[index+sh_items] = argv[index];
525 while (--sh_items >= 0)
526 argv[sh_items] = w32_perlshell_vec[sh_items];
528 status = win32_spawnvp(flag,
529 (const char*)(really ? SvPV_nolen(really) : argv[0]),
530 (const char* const*)argv);
533 if (flag != P_NOWAIT) {
536 if (ckWARN(WARN_EXEC))
537 Perl_warner(aTHX_ WARN_EXEC, "Can't spawn \"%s\": %s", argv[0], strerror(errno));
542 PL_statusvalue = status;
549 do_spawn2(char *cmd, int exectype)
556 BOOL needToTry = TRUE;
559 /* Save an extra exec if possible. See if there are shell
560 * metacharacters in it */
561 if (!has_shell_metachars(cmd)) {
562 New(1301,argv, strlen(cmd) / 2 + 2, char*);
563 New(1302,cmd2, strlen(cmd) + 1, char);
566 for (s = cmd2; *s;) {
567 while (*s && isSPACE(*s))
571 while (*s && !isSPACE(*s))
580 status = win32_spawnvp(P_WAIT, argv[0],
581 (const char* const*)argv);
583 case EXECF_SPAWN_NOWAIT:
584 status = win32_spawnvp(P_NOWAIT, argv[0],
585 (const char* const*)argv);
588 status = win32_execvp(argv[0], (const char* const*)argv);
591 if (status != -1 || errno == 0)
601 New(1306, argv, w32_perlshell_items + 2, char*);
602 while (++i < w32_perlshell_items)
603 argv[i] = w32_perlshell_vec[i];
608 status = win32_spawnvp(P_WAIT, argv[0],
609 (const char* const*)argv);
611 case EXECF_SPAWN_NOWAIT:
612 status = win32_spawnvp(P_NOWAIT, argv[0],
613 (const char* const*)argv);
616 status = win32_execvp(argv[0], (const char* const*)argv);
622 if (exectype != EXECF_SPAWN_NOWAIT) {
625 if (ckWARN(WARN_EXEC))
626 Perl_warner(aTHX_ WARN_EXEC, "Can't %s \"%s\": %s",
627 (exectype == EXECF_EXEC ? "exec" : "spawn"),
628 cmd, strerror(errno));
633 PL_statusvalue = status;
641 return do_spawn2(cmd, EXECF_SPAWN);
645 do_spawn_nowait(char *cmd)
647 return do_spawn2(cmd, EXECF_SPAWN_NOWAIT);
651 Perl_do_exec(pTHX_ char *cmd)
653 do_spawn2(cmd, EXECF_EXEC);
657 /* The idea here is to read all the directory names into a string table
658 * (separated by nulls) and when one of the other dir functions is called
659 * return the pointer to the current file name.
662 win32_opendir(char *filename)
668 char scanname[MAX_PATH+3];
670 WIN32_FIND_DATAA aFindData;
671 WIN32_FIND_DATAW wFindData;
673 char buffer[MAX_PATH*2];
674 WCHAR wbuffer[MAX_PATH];
677 len = strlen(filename);
681 /* check to see if filename is a directory */
682 if (win32_stat(filename, &sbuf) < 0 || !S_ISDIR(sbuf.st_mode))
685 /* Get us a DIR structure */
686 Newz(1303, dirp, 1, DIR);
688 /* Create the search pattern */
689 strcpy(scanname, filename);
691 /* bare drive name means look in cwd for drive */
692 if (len == 2 && isALPHA(scanname[0]) && scanname[1] == ':') {
693 scanname[len++] = '.';
694 scanname[len++] = '/';
696 else if (scanname[len-1] != '/' && scanname[len-1] != '\\') {
697 scanname[len++] = '/';
699 scanname[len++] = '*';
700 scanname[len] = '\0';
702 /* do the FindFirstFile call */
704 A2WHELPER(scanname, wbuffer, sizeof(wbuffer));
705 fh = FindFirstFileW(PerlDir_mapW(wbuffer), &wFindData);
708 fh = FindFirstFileA(PerlDir_mapA(scanname), &aFindData);
711 if (fh == INVALID_HANDLE_VALUE) {
712 DWORD err = GetLastError();
713 /* FindFirstFile() fails on empty drives! */
715 case ERROR_FILE_NOT_FOUND:
717 case ERROR_NO_MORE_FILES:
718 case ERROR_PATH_NOT_FOUND:
721 case ERROR_NOT_ENOUGH_MEMORY:
732 /* now allocate the first part of the string table for
733 * the filenames that we find.
736 W2AHELPER(wFindData.cFileName, buffer, sizeof(buffer));
740 ptr = aFindData.cFileName;
747 New(1304, dirp->start, dirp->size, char);
748 strcpy(dirp->start, ptr);
750 dirp->end = dirp->curr = dirp->start;
756 /* Readdir just returns the current string pointer and bumps the
757 * string pointer to the nDllExport entry.
759 DllExport struct direct *
760 win32_readdir(DIR *dirp)
765 /* first set up the structure to return */
766 len = strlen(dirp->curr);
767 strcpy(dirp->dirstr.d_name, dirp->curr);
768 dirp->dirstr.d_namlen = len;
771 dirp->dirstr.d_ino = dirp->curr - dirp->start;
773 /* Now set up for the next call to readdir */
774 dirp->curr += len + 1;
775 if (dirp->curr >= dirp->end) {
779 WIN32_FIND_DATAW wFindData;
780 WIN32_FIND_DATAA aFindData;
781 char buffer[MAX_PATH*2];
783 /* finding the next file that matches the wildcard
784 * (which should be all of them in this directory!).
787 res = FindNextFileW(dirp->handle, &wFindData);
789 W2AHELPER(wFindData.cFileName, buffer, sizeof(buffer));
794 res = FindNextFileA(dirp->handle, &aFindData);
796 ptr = aFindData.cFileName;
799 long endpos = dirp->end - dirp->start;
800 long newsize = endpos + strlen(ptr) + 1;
801 /* bump the string table size by enough for the
802 * new name and it's null terminator */
803 while (newsize > dirp->size) {
804 long curpos = dirp->curr - dirp->start;
806 Renew(dirp->start, dirp->size, char);
807 dirp->curr = dirp->start + curpos;
809 strcpy(dirp->start + endpos, ptr);
810 dirp->end = dirp->start + newsize;
816 return &(dirp->dirstr);
822 /* Telldir returns the current string pointer position */
824 win32_telldir(DIR *dirp)
826 return (dirp->curr - dirp->start);
830 /* Seekdir moves the string pointer to a previously saved position
831 * (returned by telldir).
834 win32_seekdir(DIR *dirp, long loc)
836 dirp->curr = dirp->start + loc;
839 /* Rewinddir resets the string pointer to the start */
841 win32_rewinddir(DIR *dirp)
843 dirp->curr = dirp->start;
846 /* free the memory allocated by opendir */
848 win32_closedir(DIR *dirp)
851 if (dirp->handle != INVALID_HANDLE_VALUE)
852 FindClose(dirp->handle);
853 Safefree(dirp->start);
866 * Just pretend that everyone is a superuser. NT will let us know if
867 * we don\'t really have permission to do something.
870 #define ROOT_UID ((uid_t)0)
871 #define ROOT_GID ((gid_t)0)
900 return (auid == ROOT_UID ? 0 : -1);
906 return (agid == ROOT_GID ? 0 : -1);
913 char *buf = w32_getlogin_buffer;
914 DWORD size = sizeof(w32_getlogin_buffer);
915 if (GetUserName(buf,&size))
921 chown(const char *path, uid_t owner, gid_t group)
931 long child = w32_num_children;
932 while (--child >= 0) {
933 if (w32_child_pids[child] == pid)
940 remove_dead_process(long child)
944 CloseHandle(w32_child_handles[child]);
945 Copy(&w32_child_handles[child+1], &w32_child_handles[child],
946 (w32_num_children-child-1), HANDLE);
947 Copy(&w32_child_pids[child+1], &w32_child_pids[child],
948 (w32_num_children-child-1), DWORD);
955 find_pseudo_pid(int pid)
958 long child = w32_num_pseudo_children;
959 while (--child >= 0) {
960 if (w32_pseudo_child_pids[child] == pid)
967 remove_dead_pseudo_process(long child)
971 CloseHandle(w32_pseudo_child_handles[child]);
972 Copy(&w32_pseudo_child_handles[child+1], &w32_pseudo_child_handles[child],
973 (w32_num_pseudo_children-child-1), HANDLE);
974 Copy(&w32_pseudo_child_pids[child+1], &w32_pseudo_child_pids[child],
975 (w32_num_pseudo_children-child-1), DWORD);
976 w32_num_pseudo_children--;
982 win32_kill(int pid, int sig)
988 /* it is a pseudo-forked child */
989 long child = find_pseudo_pid(-pid);
991 hProcess = w32_pseudo_child_handles[child];
992 if (TerminateThread(hProcess, sig)) {
993 remove_dead_pseudo_process(child);
1001 long child = find_pid(pid);
1003 hProcess = w32_child_handles[child];
1004 if (TerminateProcess(hProcess, sig)) {
1005 remove_dead_process(child);
1010 hProcess = OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid);
1011 if (hProcess && TerminateProcess(hProcess, sig)) {
1012 CloseHandle(hProcess);
1025 DllExport unsigned int
1026 win32_sleep(unsigned int t)
1033 win32_stat(const char *path, struct stat *buffer)
1037 int l = strlen(path);
1039 WCHAR wbuffer[MAX_PATH];
1044 switch(path[l - 1]) {
1045 /* FindFirstFile() and stat() are buggy with a trailing
1046 * backslash, so change it to a forward slash :-( */
1048 strncpy(t, path, l-1);
1053 /* FindFirstFile() is buggy with "x:", so add a dot :-( */
1055 if (l == 2 && isALPHA(path[0])) {
1056 t[0] = path[0]; t[1] = ':'; t[2] = '.'; t[3] = '\0';
1064 /* We *must* open & close the file once; otherwise file attribute changes */
1065 /* might not yet have propagated to "other" hard links of the same file. */
1066 /* This also gives us an opportunity to determine the number of links. */
1068 A2WHELPER(path, wbuffer, sizeof(wbuffer));
1069 wcscpy(wbuffer, PerlDir_mapW(wbuffer));
1070 handle = CreateFileW(wbuffer, 0, 0, NULL, OPEN_EXISTING, 0, NULL);
1073 path = PerlDir_mapA(path);
1074 handle = CreateFileA(path, 0, 0, NULL, OPEN_EXISTING, 0, NULL);
1076 if (handle != INVALID_HANDLE_VALUE) {
1077 BY_HANDLE_FILE_INFORMATION bhi;
1078 if (GetFileInformationByHandle(handle, &bhi))
1079 nlink = bhi.nNumberOfLinks;
1080 CloseHandle(handle);
1083 /* wbuffer or path will be mapped correctly above */
1085 res = _wstat(wbuffer, (struct _stat *)buffer);
1088 res = stat(path, buffer);
1090 buffer->st_nlink = nlink;
1093 /* CRT is buggy on sharenames, so make sure it really isn't.
1094 * XXX using GetFileAttributesEx() will enable us to set
1095 * buffer->st_*time (but note that's not available on the
1096 * Windows of 1995) */
1099 r = GetFileAttributesW(wbuffer);
1102 r = GetFileAttributesA(path);
1104 if (r != 0xffffffff && (r & FILE_ATTRIBUTE_DIRECTORY)) {
1105 /* buffer may still contain old garbage since stat() failed */
1106 Zero(buffer, 1, struct stat);
1107 buffer->st_mode = S_IFDIR | S_IREAD;
1109 if (!(r & FILE_ATTRIBUTE_READONLY))
1110 buffer->st_mode |= S_IWRITE | S_IEXEC;
1115 if (l == 3 && isALPHA(path[0]) && path[1] == ':'
1116 && (path[2] == '\\' || path[2] == '/'))
1118 /* The drive can be inaccessible, some _stat()s are buggy */
1120 ? !GetVolumeInformationW(wbuffer,NULL,0,NULL,NULL,NULL,NULL,0)
1121 : !GetVolumeInformationA(path,NULL,0,NULL,NULL,NULL,NULL,0)) {
1127 if (S_ISDIR(buffer->st_mode))
1128 buffer->st_mode |= S_IWRITE | S_IEXEC;
1129 else if (S_ISREG(buffer->st_mode)) {
1130 if (l >= 4 && path[l-4] == '.') {
1131 const char *e = path + l - 3;
1132 if (strnicmp(e,"exe",3)
1133 && strnicmp(e,"bat",3)
1134 && strnicmp(e,"com",3)
1135 && (IsWin95() || strnicmp(e,"cmd",3)))
1136 buffer->st_mode &= ~S_IEXEC;
1138 buffer->st_mode |= S_IEXEC;
1141 buffer->st_mode &= ~S_IEXEC;
1148 /* Find the longname of a given path. path is destructively modified.
1149 * It should have space for at least MAX_PATH characters. */
1151 win32_longpath(char *path)
1153 WIN32_FIND_DATA fdata;
1155 char tmpbuf[MAX_PATH+1];
1156 char *tmpstart = tmpbuf;
1163 if (isALPHA(path[0]) && path[1] == ':' &&
1164 (path[2] == '/' || path[2] == '\\'))
1167 *tmpstart++ = path[0];
1171 else if ((path[0] == '/' || path[0] == '\\') &&
1172 (path[1] == '/' || path[1] == '\\'))
1175 *tmpstart++ = path[0];
1176 *tmpstart++ = path[1];
1177 /* copy machine name */
1178 while (*start && *start != '/' && *start != '\\')
1179 *tmpstart++ = *start++;
1181 *tmpstart++ = *start;
1183 /* copy share name */
1184 while (*start && *start != '/' && *start != '\\')
1185 *tmpstart++ = *start++;
1189 if (sep == '/' || sep == '\\')
1193 /* walk up to slash */
1194 while (*start && *start != '/' && *start != '\\')
1197 /* discard doubled slashes */
1198 while (*start && (start[1] == '/' || start[1] == '\\'))
1202 /* stop and find full name of component */
1204 fhand = FindFirstFile(path,&fdata);
1205 if (fhand != INVALID_HANDLE_VALUE) {
1206 strcpy(tmpstart, fdata.cFileName);
1207 tmpstart += strlen(fdata.cFileName);
1215 /* failed a step, just return without side effects */
1216 /*PerlIO_printf(Perl_debug_log, "Failed to find %s\n", path);*/
1221 strcpy(path,tmpbuf);
1225 #ifndef USE_WIN32_RTL_ENV
1228 win32_getenv(const char *name)
1231 WCHAR wBuffer[MAX_PATH];
1233 SV *curitem = Nullsv;
1236 A2WHELPER(name, wBuffer, sizeof(wBuffer));
1237 needlen = GetEnvironmentVariableW(wBuffer, NULL, 0);
1240 needlen = GetEnvironmentVariableA(name,NULL,0);
1242 curitem = sv_2mortal(newSVpvn("", 0));
1246 SvGROW(curitem, (needlen+1)*sizeof(WCHAR));
1247 needlen = GetEnvironmentVariableW(wBuffer,
1248 (WCHAR*)SvPVX(curitem),
1250 } while (needlen >= SvLEN(curitem)/sizeof(WCHAR));
1251 SvCUR_set(curitem, (needlen*sizeof(WCHAR))+1);
1252 acuritem = sv_2mortal(newSVsv(curitem));
1253 W2AHELPER((WCHAR*)SvPVX(acuritem), SvPVX(curitem), SvCUR(curitem));
1257 SvGROW(curitem, needlen+1);
1258 needlen = GetEnvironmentVariableA(name,SvPVX(curitem),
1260 } while (needlen >= SvLEN(curitem));
1261 SvCUR_set(curitem, needlen);
1265 /* allow any environment variables that begin with 'PERL'
1266 to be stored in the registry */
1267 if (strncmp(name, "PERL", 4) == 0)
1268 (void)get_regstr(name, &curitem);
1270 if (curitem && SvCUR(curitem))
1271 return SvPVX(curitem);
1277 win32_putenv(const char *name)
1284 int length, relval = -1;
1288 length = strlen(name)+1;
1289 New(1309,wCuritem,length,WCHAR);
1290 A2WHELPER(name, wCuritem, length*sizeof(WCHAR));
1291 wVal = wcschr(wCuritem, '=');
1294 if (SetEnvironmentVariableW(wCuritem, *wVal ? wVal : NULL))
1300 New(1309,curitem,strlen(name)+1,char);
1301 strcpy(curitem, name);
1302 val = strchr(curitem, '=');
1304 /* The sane way to deal with the environment.
1305 * Has these advantages over putenv() & co.:
1306 * * enables us to store a truly empty value in the
1307 * environment (like in UNIX).
1308 * * we don't have to deal with RTL globals, bugs and leaks.
1310 * Why you may want to enable USE_WIN32_RTL_ENV:
1311 * * environ[] and RTL functions will not reflect changes,
1312 * which might be an issue if extensions want to access
1313 * the env. via RTL. This cuts both ways, since RTL will
1314 * not see changes made by extensions that call the Win32
1315 * functions directly, either.
1319 if (SetEnvironmentVariableA(curitem, *val ? val : NULL))
1331 filetime_to_clock(PFILETIME ft)
1333 __int64 qw = ft->dwHighDateTime;
1335 qw |= ft->dwLowDateTime;
1336 qw /= 10000; /* File time ticks at 0.1uS, clock at 1mS */
1341 win32_times(struct tms *timebuf)
1346 if (GetProcessTimes(GetCurrentProcess(), &dummy, &dummy,
1348 timebuf->tms_utime = filetime_to_clock(&user);
1349 timebuf->tms_stime = filetime_to_clock(&kernel);
1350 timebuf->tms_cutime = 0;
1351 timebuf->tms_cstime = 0;
1354 /* That failed - e.g. Win95 fallback to clock() */
1355 clock_t t = clock();
1356 timebuf->tms_utime = t;
1357 timebuf->tms_stime = 0;
1358 timebuf->tms_cutime = 0;
1359 timebuf->tms_cstime = 0;
1364 /* fix utime() so it works on directories in NT */
1366 filetime_from_time(PFILETIME pFileTime, time_t Time)
1368 struct tm *pTM = localtime(&Time);
1369 SYSTEMTIME SystemTime;
1375 SystemTime.wYear = pTM->tm_year + 1900;
1376 SystemTime.wMonth = pTM->tm_mon + 1;
1377 SystemTime.wDay = pTM->tm_mday;
1378 SystemTime.wHour = pTM->tm_hour;
1379 SystemTime.wMinute = pTM->tm_min;
1380 SystemTime.wSecond = pTM->tm_sec;
1381 SystemTime.wMilliseconds = 0;
1383 return SystemTimeToFileTime(&SystemTime, &LocalTime) &&
1384 LocalFileTimeToFileTime(&LocalTime, pFileTime);
1388 win32_unlink(const char *filename)
1395 WCHAR wBuffer[MAX_PATH];
1397 A2WHELPER(filename, wBuffer, sizeof(wBuffer));
1398 wcscpy(wBuffer, PerlDir_mapW(wBuffer));
1399 attrs = GetFileAttributesW(wBuffer);
1400 if (attrs & FILE_ATTRIBUTE_READONLY) {
1401 (void)SetFileAttributesW(wBuffer, attrs & ~FILE_ATTRIBUTE_READONLY);
1402 ret = _wunlink(wBuffer);
1404 (void)SetFileAttributesW(wBuffer, attrs);
1407 ret = _wunlink(wBuffer);
1410 filename = PerlDir_mapA(filename);
1411 attrs = GetFileAttributesA(filename);
1412 if (attrs & FILE_ATTRIBUTE_READONLY) {
1413 (void)SetFileAttributesA(filename, attrs & ~FILE_ATTRIBUTE_READONLY);
1414 ret = unlink(filename);
1416 (void)SetFileAttributesA(filename, attrs);
1419 ret = unlink(filename);
1425 win32_utime(const char *filename, struct utimbuf *times)
1432 struct utimbuf TimeBuffer;
1433 WCHAR wbuffer[MAX_PATH];
1437 A2WHELPER(filename, wbuffer, sizeof(wbuffer));
1438 wcscpy(wbuffer, PerlDir_mapW(wbuffer));
1439 rc = _wutime(wbuffer, (struct _utimbuf*)times);
1442 filename = PerlDir_mapA(filename);
1443 rc = utime(filename, times);
1445 /* EACCES: path specifies directory or readonly file */
1446 if (rc == 0 || errno != EACCES /* || !IsWinNT() */)
1449 if (times == NULL) {
1450 times = &TimeBuffer;
1451 time(×->actime);
1452 times->modtime = times->actime;
1455 /* This will (and should) still fail on readonly files */
1457 handle = CreateFileW(wbuffer, GENERIC_READ | GENERIC_WRITE,
1458 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1459 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1462 handle = CreateFileA(filename, GENERIC_READ | GENERIC_WRITE,
1463 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1464 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1466 if (handle == INVALID_HANDLE_VALUE)
1469 if (GetFileTime(handle, &ftCreate, &ftAccess, &ftWrite) &&
1470 filetime_from_time(&ftAccess, times->actime) &&
1471 filetime_from_time(&ftWrite, times->modtime) &&
1472 SetFileTime(handle, &ftCreate, &ftAccess, &ftWrite))
1477 CloseHandle(handle);
1482 win32_uname(struct utsname *name)
1484 struct hostent *hep;
1485 STRLEN nodemax = sizeof(name->nodename)-1;
1486 OSVERSIONINFO osver;
1488 memset(&osver, 0, sizeof(OSVERSIONINFO));
1489 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1490 if (GetVersionEx(&osver)) {
1492 switch (osver.dwPlatformId) {
1493 case VER_PLATFORM_WIN32_WINDOWS:
1494 strcpy(name->sysname, "Windows");
1496 case VER_PLATFORM_WIN32_NT:
1497 strcpy(name->sysname, "Windows NT");
1499 case VER_PLATFORM_WIN32s:
1500 strcpy(name->sysname, "Win32s");
1503 strcpy(name->sysname, "Win32 Unknown");
1508 sprintf(name->release, "%d.%d",
1509 osver.dwMajorVersion, osver.dwMinorVersion);
1512 sprintf(name->version, "Build %d",
1513 osver.dwPlatformId == VER_PLATFORM_WIN32_NT
1514 ? osver.dwBuildNumber : (osver.dwBuildNumber & 0xffff));
1515 if (osver.szCSDVersion[0]) {
1516 char *buf = name->version + strlen(name->version);
1517 sprintf(buf, " (%s)", osver.szCSDVersion);
1521 *name->sysname = '\0';
1522 *name->version = '\0';
1523 *name->release = '\0';
1527 hep = win32_gethostbyname("localhost");
1529 STRLEN len = strlen(hep->h_name);
1530 if (len <= nodemax) {
1531 strcpy(name->nodename, hep->h_name);
1534 strncpy(name->nodename, hep->h_name, nodemax);
1535 name->nodename[nodemax] = '\0';
1540 if (!GetComputerName(name->nodename, &sz))
1541 *name->nodename = '\0';
1544 /* machine (architecture) */
1548 GetSystemInfo(&info);
1550 #if defined(__BORLANDC__) || defined(__MINGW32__)
1551 switch (info.u.s.wProcessorArchitecture) {
1553 switch (info.wProcessorArchitecture) {
1555 case PROCESSOR_ARCHITECTURE_INTEL:
1556 arch = "x86"; break;
1557 case PROCESSOR_ARCHITECTURE_MIPS:
1558 arch = "mips"; break;
1559 case PROCESSOR_ARCHITECTURE_ALPHA:
1560 arch = "alpha"; break;
1561 case PROCESSOR_ARCHITECTURE_PPC:
1562 arch = "ppc"; break;
1564 arch = "unknown"; break;
1566 strcpy(name->machine, arch);
1572 win32_waitpid(int pid, int *status, int flags)
1576 if (pid == -1) /* XXX threadid == 1 ? */
1577 return win32_wait(status);
1580 long child = find_pseudo_pid(-pid);
1582 HANDLE hThread = w32_pseudo_child_handles[child];
1583 DWORD waitcode = WaitForSingleObject(hThread, INFINITE);
1584 if (waitcode != WAIT_FAILED) {
1585 if (GetExitCodeThread(hThread, &waitcode)) {
1586 *status = (int)((waitcode & 0xff) << 8);
1587 retval = (int)w32_pseudo_child_pids[child];
1588 remove_dead_pseudo_process(child);
1598 long child = find_pid(pid);
1600 HANDLE hProcess = w32_child_handles[child];
1601 DWORD waitcode = WaitForSingleObject(hProcess, INFINITE);
1602 if (waitcode != WAIT_FAILED) {
1603 if (GetExitCodeProcess(hProcess, &waitcode)) {
1604 *status = (int)((waitcode & 0xff) << 8);
1605 retval = (int)w32_child_pids[child];
1606 remove_dead_process(child);
1614 retval = cwait(status, pid, WAIT_CHILD);
1615 /* cwait() returns "correctly" on Borland */
1616 #ifndef __BORLANDC__
1622 return retval >= 0 ? pid : retval;
1626 win32_wait(int *status)
1628 /* XXX this wait emulation only knows about processes
1629 * spawned via win32_spawnvp(P_NOWAIT, ...).
1633 DWORD exitcode, waitcode;
1636 if (w32_num_pseudo_children) {
1637 waitcode = WaitForMultipleObjects(w32_num_pseudo_children,
1638 w32_pseudo_child_handles,
1641 if (waitcode != WAIT_FAILED) {
1642 if (waitcode >= WAIT_ABANDONED_0
1643 && waitcode < WAIT_ABANDONED_0 + w32_num_pseudo_children)
1644 i = waitcode - WAIT_ABANDONED_0;
1646 i = waitcode - WAIT_OBJECT_0;
1647 if (GetExitCodeThread(w32_pseudo_child_handles[i], &exitcode)) {
1648 *status = (int)((exitcode & 0xff) << 8);
1649 retval = (int)w32_pseudo_child_pids[i];
1650 remove_dead_pseudo_process(i);
1657 if (!w32_num_children) {
1662 /* if a child exists, wait for it to die */
1663 waitcode = WaitForMultipleObjects(w32_num_children,
1667 if (waitcode != WAIT_FAILED) {
1668 if (waitcode >= WAIT_ABANDONED_0
1669 && waitcode < WAIT_ABANDONED_0 + w32_num_children)
1670 i = waitcode - WAIT_ABANDONED_0;
1672 i = waitcode - WAIT_OBJECT_0;
1673 if (GetExitCodeProcess(w32_child_handles[i], &exitcode) ) {
1674 *status = (int)((exitcode & 0xff) << 8);
1675 retval = (int)w32_child_pids[i];
1676 remove_dead_process(i);
1682 errno = GetLastError();
1686 static UINT timerid = 0;
1688 static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
1691 KillTimer(NULL,timerid);
1696 DllExport unsigned int
1697 win32_alarm(unsigned int sec)
1700 * the 'obvious' implentation is SetTimer() with a callback
1701 * which does whatever receiving SIGALRM would do
1702 * we cannot use SIGALRM even via raise() as it is not
1703 * one of the supported codes in <signal.h>
1705 * Snag is unless something is looking at the message queue
1706 * nothing happens :-(
1711 timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
1713 Perl_croak_nocontext("Cannot set timer");
1719 KillTimer(NULL,timerid);
1726 #ifdef HAVE_DES_FCRYPT
1727 extern char * des_fcrypt(const char *txt, const char *salt, char *cbuf);
1731 win32_crypt(const char *txt, const char *salt)
1734 #ifdef HAVE_DES_FCRYPT
1736 return des_fcrypt(txt, salt, w32_crypt_buffer);
1738 Perl_croak(aTHX_ "The crypt() function is unimplemented due to excessive paranoia.");
1743 #ifdef USE_FIXED_OSFHANDLE
1745 EXTERN_C int __cdecl _alloc_osfhnd(void);
1746 EXTERN_C int __cdecl _set_osfhnd(int fh, long value);
1747 EXTERN_C void __cdecl _lock_fhandle(int);
1748 EXTERN_C void __cdecl _unlock_fhandle(int);
1749 EXTERN_C void __cdecl _unlock(int);
1751 #if (_MSC_VER >= 1000)
1753 long osfhnd; /* underlying OS file HANDLE */
1754 char osfile; /* attributes of file (e.g., open in text mode?) */
1755 char pipech; /* one char buffer for handles opened on pipes */
1756 #if defined (_MT) && !defined (DLL_FOR_WIN32S)
1758 CRITICAL_SECTION lock;
1759 #endif /* defined (_MT) && !defined (DLL_FOR_WIN32S) */
1762 EXTERN_C ioinfo * __pioinfo[];
1764 #define IOINFO_L2E 5
1765 #define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
1766 #define _pioinfo(i) (__pioinfo[i >> IOINFO_L2E] + (i & (IOINFO_ARRAY_ELTS - 1)))
1767 #define _osfile(i) (_pioinfo(i)->osfile)
1769 #else /* (_MSC_VER >= 1000) */
1770 extern char _osfile[];
1771 #endif /* (_MSC_VER >= 1000) */
1773 #define FOPEN 0x01 /* file handle open */
1774 #define FAPPEND 0x20 /* file handle opened O_APPEND */
1775 #define FDEV 0x40 /* file handle refers to device */
1776 #define FTEXT 0x80 /* file handle is in text mode */
1778 #define _STREAM_LOCKS 26 /* Table of stream locks */
1779 #define _LAST_STREAM_LOCK (_STREAM_LOCKS+_NSTREAM_-1) /* Last stream lock */
1780 #define _FH_LOCKS (_LAST_STREAM_LOCK+1) /* Table of fh locks */
1783 *int my_open_osfhandle(long osfhandle, int flags) - open C Runtime file handle
1786 * This function allocates a free C Runtime file handle and associates
1787 * it with the Win32 HANDLE specified by the first parameter. This is a
1788 * temperary fix for WIN95's brain damage GetFileType() error on socket
1789 * we just bypass that call for socket
1792 * long osfhandle - Win32 HANDLE to associate with C Runtime file handle.
1793 * int flags - flags to associate with C Runtime file handle.
1796 * returns index of entry in fh, if successful
1797 * return -1, if no free entry is found
1801 *******************************************************************************/
1804 my_open_osfhandle(long osfhandle, int flags)
1807 char fileflags; /* _osfile flags */
1809 /* copy relevant flags from second parameter */
1812 if (flags & O_APPEND)
1813 fileflags |= FAPPEND;
1818 /* attempt to allocate a C Runtime file handle */
1819 if ((fh = _alloc_osfhnd()) == -1) {
1820 errno = EMFILE; /* too many open files */
1821 _doserrno = 0L; /* not an OS error */
1822 return -1; /* return error to caller */
1825 /* the file is open. now, set the info in _osfhnd array */
1826 _set_osfhnd(fh, osfhandle);
1828 fileflags |= FOPEN; /* mark as open */
1830 #if (_MSC_VER >= 1000)
1831 _osfile(fh) = fileflags; /* set osfile entry */
1832 _unlock_fhandle(fh);
1834 _osfile[fh] = fileflags; /* set osfile entry */
1835 _unlock(fh+_FH_LOCKS); /* unlock handle */
1838 return fh; /* return handle */
1841 #define _open_osfhandle my_open_osfhandle
1842 #endif /* USE_FIXED_OSFHANDLE */
1844 /* simulate flock by locking a range on the file */
1846 #define LK_ERR(f,i) ((f) ? (i = 0) : (errno = GetLastError()))
1847 #define LK_LEN 0xffff0000
1850 win32_flock(int fd, int oper)
1858 Perl_croak_nocontext("flock() unimplemented on this platform");
1861 fh = (HANDLE)_get_osfhandle(fd);
1862 memset(&o, 0, sizeof(o));
1865 case LOCK_SH: /* shared lock */
1866 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
1868 case LOCK_EX: /* exclusive lock */
1869 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
1871 case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
1872 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
1874 case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
1875 LK_ERR(LockFileEx(fh,
1876 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
1877 0, LK_LEN, 0, &o),i);
1879 case LOCK_UN: /* unlock lock */
1880 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, 0, &o),i);
1882 default: /* unknown */
1893 * redirected io subsystem for all XS modules
1906 return (&(_environ));
1909 /* the rest are the remapped stdio routines */
1929 win32_ferror(FILE *fp)
1931 return (ferror(fp));
1936 win32_feof(FILE *fp)
1942 * Since the errors returned by the socket error function
1943 * WSAGetLastError() are not known by the library routine strerror
1944 * we have to roll our own.
1948 win32_strerror(int e)
1950 #ifndef __BORLANDC__ /* Borland intolerance */
1951 extern int sys_nerr;
1955 if (e < 0 || e > sys_nerr) {
1960 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
1961 w32_strerror_buffer,
1962 sizeof(w32_strerror_buffer), NULL) == 0)
1963 strcpy(w32_strerror_buffer, "Unknown Error");
1965 return w32_strerror_buffer;
1971 win32_str_os_error(void *sv, DWORD dwErr)
1975 dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
1976 |FORMAT_MESSAGE_IGNORE_INSERTS
1977 |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
1978 dwErr, 0, (char *)&sMsg, 1, NULL);
1979 /* strip trailing whitespace and period */
1982 --dwLen; /* dwLen doesn't include trailing null */
1983 } while (0 < dwLen && isSPACE(sMsg[dwLen]));
1984 if ('.' != sMsg[dwLen])
1989 sMsg = (char*)LocalAlloc(0, 64/**sizeof(TCHAR)*/);
1991 dwLen = sprintf(sMsg,
1992 "Unknown error #0x%lX (lookup 0x%lX)",
1993 dwErr, GetLastError());
1997 sv_setpvn((SV*)sv, sMsg, dwLen);
2004 win32_fprintf(FILE *fp, const char *format, ...)
2007 va_start(marker, format); /* Initialize variable arguments. */
2009 return (vfprintf(fp, format, marker));
2013 win32_printf(const char *format, ...)
2016 va_start(marker, format); /* Initialize variable arguments. */
2018 return (vprintf(format, marker));
2022 win32_vfprintf(FILE *fp, const char *format, va_list args)
2024 return (vfprintf(fp, format, args));
2028 win32_vprintf(const char *format, va_list args)
2030 return (vprintf(format, args));
2034 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
2036 return fread(buf, size, count, fp);
2040 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
2042 return fwrite(buf, size, count, fp);
2045 #define MODE_SIZE 10
2048 win32_fopen(const char *filename, const char *mode)
2051 WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH];
2056 if (stricmp(filename, "/dev/null")==0)
2060 A2WHELPER(mode, wMode, sizeof(wMode));
2061 A2WHELPER(filename, wBuffer, sizeof(wBuffer));
2062 return _wfopen(PerlDir_mapW(wBuffer), wMode);
2064 return fopen(PerlDir_mapA(filename), mode);
2067 #ifndef USE_SOCKETS_AS_HANDLES
2069 #define fdopen my_fdopen
2073 win32_fdopen(int handle, const char *mode)
2076 WCHAR wMode[MODE_SIZE];
2078 A2WHELPER(mode, wMode, sizeof(wMode));
2079 return _wfdopen(handle, wMode);
2081 return fdopen(handle, (char *) mode);
2085 win32_freopen(const char *path, const char *mode, FILE *stream)
2088 WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH];
2089 if (stricmp(path, "/dev/null")==0)
2093 A2WHELPER(mode, wMode, sizeof(wMode));
2094 A2WHELPER(path, wBuffer, sizeof(wBuffer));
2095 return _wfreopen(PerlDir_mapW(wBuffer), wMode, stream);
2097 return freopen(PerlDir_mapA(path), mode, stream);
2101 win32_fclose(FILE *pf)
2103 return my_fclose(pf); /* defined in win32sck.c */
2107 win32_fputs(const char *s,FILE *pf)
2109 return fputs(s, pf);
2113 win32_fputc(int c,FILE *pf)
2119 win32_ungetc(int c,FILE *pf)
2121 return ungetc(c,pf);
2125 win32_getc(FILE *pf)
2131 win32_fileno(FILE *pf)
2137 win32_clearerr(FILE *pf)
2144 win32_fflush(FILE *pf)
2150 win32_ftell(FILE *pf)
2156 win32_fseek(FILE *pf,long offset,int origin)
2158 return fseek(pf, offset, origin);
2162 win32_fgetpos(FILE *pf,fpos_t *p)
2164 return fgetpos(pf, p);
2168 win32_fsetpos(FILE *pf,const fpos_t *p)
2170 return fsetpos(pf, p);
2174 win32_rewind(FILE *pf)
2194 win32_fstat(int fd,struct stat *sbufptr)
2196 return fstat(fd,sbufptr);
2200 win32_pipe(int *pfd, unsigned int size, int mode)
2202 return _pipe(pfd, size, mode);
2206 * a popen() clone that respects PERL5SHELL
2210 win32_popen(const char *command, const char *mode)
2212 #ifdef USE_RTL_POPEN
2213 return _popen(command, mode);
2221 /* establish which ends read and write */
2222 if (strchr(mode,'w')) {
2223 stdfd = 0; /* stdin */
2227 else if (strchr(mode,'r')) {
2228 stdfd = 1; /* stdout */
2235 /* set the correct mode */
2236 if (strchr(mode,'b'))
2238 else if (strchr(mode,'t'))
2241 ourmode = _fmode & (O_TEXT | O_BINARY);
2243 /* the child doesn't inherit handles */
2244 ourmode |= O_NOINHERIT;
2246 if (win32_pipe( p, 512, ourmode) == -1)
2249 /* save current stdfd */
2250 if ((oldfd = win32_dup(stdfd)) == -1)
2253 /* make stdfd go to child end of pipe (implicitly closes stdfd) */
2254 /* stdfd will be inherited by the child */
2255 if (win32_dup2(p[child], stdfd) == -1)
2258 /* close the child end in parent */
2259 win32_close(p[child]);
2261 /* start the child */
2264 if ((childpid = do_spawn_nowait((char*)command)) == -1)
2267 /* revert stdfd to whatever it was before */
2268 if (win32_dup2(oldfd, stdfd) == -1)
2271 /* close saved handle */
2274 sv_setiv(*av_fetch(w32_fdpid, p[parent], TRUE), childpid);
2276 /* set process id so that it can be returned by perl's open() */
2277 PL_forkprocess = childpid;
2280 /* we have an fd, return a file stream */
2281 return (win32_fdopen(p[parent], (char *)mode));
2284 /* we don't need to check for errors here */
2288 win32_dup2(oldfd, stdfd);
2293 #endif /* USE_RTL_POPEN */
2301 win32_pclose(FILE *pf)
2303 #ifdef USE_RTL_POPEN
2307 int childpid, status;
2310 sv = *av_fetch(w32_fdpid, win32_fileno(pf), TRUE);
2312 childpid = SvIVX(sv);
2324 if (win32_waitpid(childpid, &status, 0) == -1)
2329 #endif /* USE_RTL_POPEN */
2335 LPCWSTR lpExistingFileName,
2336 LPSECURITY_ATTRIBUTES lpSecurityAttributes)
2339 WCHAR wFullName[MAX_PATH+1];
2340 LPVOID lpContext = NULL;
2341 WIN32_STREAM_ID StreamId;
2342 DWORD dwSize = (char*)&StreamId.cStreamName - (char*)&StreamId;
2347 BOOL (__stdcall *pfnBackupWrite)(HANDLE, LPBYTE, DWORD, LPDWORD,
2348 BOOL, BOOL, LPVOID*) =
2349 (BOOL (__stdcall *)(HANDLE, LPBYTE, DWORD, LPDWORD,
2350 BOOL, BOOL, LPVOID*))
2351 GetProcAddress(GetModuleHandle("kernel32.dll"), "BackupWrite");
2352 if (pfnBackupWrite == NULL)
2355 dwLen = GetFullPathNameW(lpFileName, MAX_PATH, wFullName, NULL);
2358 dwLen = (dwLen+1)*sizeof(WCHAR);
2360 handle = CreateFileW(lpExistingFileName, FILE_WRITE_ATTRIBUTES,
2361 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
2362 NULL, OPEN_EXISTING, 0, NULL);
2363 if (handle == INVALID_HANDLE_VALUE)
2366 StreamId.dwStreamId = BACKUP_LINK;
2367 StreamId.dwStreamAttributes = 0;
2368 StreamId.dwStreamNameSize = 0;
2369 #if defined(__BORLANDC__) || defined(__MINGW32__)
2370 StreamId.Size.u.HighPart = 0;
2371 StreamId.Size.u.LowPart = dwLen;
2373 StreamId.Size.HighPart = 0;
2374 StreamId.Size.LowPart = dwLen;
2377 bSuccess = pfnBackupWrite(handle, (LPBYTE)&StreamId, dwSize, &dwWritten,
2378 FALSE, FALSE, &lpContext);
2380 bSuccess = pfnBackupWrite(handle, (LPBYTE)wFullName, dwLen, &dwWritten,
2381 FALSE, FALSE, &lpContext);
2382 pfnBackupWrite(handle, NULL, 0, &dwWritten, TRUE, FALSE, &lpContext);
2385 CloseHandle(handle);
2390 win32_link(const char *oldname, const char *newname)
2393 BOOL (__stdcall *pfnCreateHardLinkW)(LPCWSTR,LPCWSTR,LPSECURITY_ATTRIBUTES);
2394 WCHAR wOldName[MAX_PATH];
2395 WCHAR wNewName[MAX_PATH];
2398 Perl_die(aTHX_ PL_no_func, "link");
2400 pfnCreateHardLinkW =
2401 (BOOL (__stdcall *)(LPCWSTR, LPCWSTR, LPSECURITY_ATTRIBUTES))
2402 GetProcAddress(GetModuleHandle("kernel32.dll"), "CreateHardLinkW");
2403 if (pfnCreateHardLinkW == NULL)
2404 pfnCreateHardLinkW = Nt4CreateHardLinkW;
2406 if ((A2WHELPER(oldname, wOldName, sizeof(wOldName))) &&
2407 (A2WHELPER(newname, wNewName, sizeof(wNewName))) &&
2408 (wcscpy(wOldName, PerlDir_mapW(wOldName)),
2409 pfnCreateHardLinkW(PerlDir_mapW(wNewName), wOldName, NULL)))
2413 errno = (GetLastError() == ERROR_FILE_NOT_FOUND) ? ENOENT : EINVAL;
2418 win32_rename(const char *oname, const char *newname)
2420 WCHAR wOldName[MAX_PATH];
2421 WCHAR wNewName[MAX_PATH];
2422 char szOldName[MAX_PATH];
2424 /* XXX despite what the documentation says about MoveFileEx(),
2425 * it doesn't work under Windows95!
2430 A2WHELPER(oname, wOldName, sizeof(wOldName));
2431 A2WHELPER(newname, wNewName, sizeof(wNewName));
2432 wcscpy(wOldName, PerlDir_mapW(wOldName));
2433 bResult = MoveFileExW(wOldName,PerlDir_mapW(wNewName),
2434 MOVEFILE_COPY_ALLOWED|MOVEFILE_REPLACE_EXISTING);
2437 strcpy(szOldName, PerlDir_mapA(szOldName));
2438 bResult = MoveFileExA(szOldName,PerlDir_mapA(newname),
2439 MOVEFILE_COPY_ALLOWED|MOVEFILE_REPLACE_EXISTING);
2442 DWORD err = GetLastError();
2444 case ERROR_BAD_NET_NAME:
2445 case ERROR_BAD_NETPATH:
2446 case ERROR_BAD_PATHNAME:
2447 case ERROR_FILE_NOT_FOUND:
2448 case ERROR_FILENAME_EXCED_RANGE:
2449 case ERROR_INVALID_DRIVE:
2450 case ERROR_NO_MORE_FILES:
2451 case ERROR_PATH_NOT_FOUND:
2464 char tmpname[MAX_PATH+1];
2465 char dname[MAX_PATH+1];
2466 char *endname = Nullch;
2468 DWORD from_attr, to_attr;
2470 /* if oname doesn't exist, do nothing */
2471 from_attr = GetFileAttributes(oname);
2472 if (from_attr == 0xFFFFFFFF) {
2477 /* if newname exists, rename it to a temporary name so that we
2478 * don't delete it in case oname happens to be the same file
2479 * (but perhaps accessed via a different path)
2481 to_attr = GetFileAttributes(newname);
2482 if (to_attr != 0xFFFFFFFF) {
2483 /* if newname is a directory, we fail
2484 * XXX could overcome this with yet more convoluted logic */
2485 if (to_attr & FILE_ATTRIBUTE_DIRECTORY) {
2489 tmplen = strlen(newname);
2490 strcpy(tmpname,newname);
2491 endname = tmpname+tmplen;
2492 for (; endname > tmpname ; --endname) {
2493 if (*endname == '/' || *endname == '\\') {
2498 if (endname > tmpname)
2499 endname = strcpy(dname,tmpname);
2503 /* get a temporary filename in same directory
2504 * XXX is this really the best we can do? */
2505 if (!GetTempFileName((LPCTSTR)endname, "plr", 0, tmpname)) {
2509 DeleteFile(tmpname);
2511 retval = rename(newname, tmpname);
2518 /* rename oname to newname */
2519 retval = rename(oname, newname);
2521 /* if we created a temporary file before ... */
2522 if (endname != Nullch) {
2523 /* ...and rename succeeded, delete temporary file/directory */
2525 DeleteFile(tmpname);
2526 /* else restore it to what it was */
2528 (void)rename(tmpname, newname);
2535 win32_setmode(int fd, int mode)
2537 return setmode(fd, mode);
2541 win32_lseek(int fd, long offset, int origin)
2543 return lseek(fd, offset, origin);
2553 win32_open(const char *path, int flag, ...)
2558 WCHAR wBuffer[MAX_PATH];
2561 pmode = va_arg(ap, int);
2564 if (stricmp(path, "/dev/null")==0)
2568 A2WHELPER(path, wBuffer, sizeof(wBuffer));
2569 return _wopen(PerlDir_mapW(wBuffer), flag, pmode);
2571 return open(PerlDir_mapA(path), flag, pmode);
2593 win32_dup2(int fd1,int fd2)
2595 return dup2(fd1,fd2);
2599 win32_read(int fd, void *buf, unsigned int cnt)
2601 return read(fd, buf, cnt);
2605 win32_write(int fd, const void *buf, unsigned int cnt)
2607 return write(fd, buf, cnt);
2611 win32_mkdir(const char *dir, int mode)
2615 WCHAR wBuffer[MAX_PATH];
2616 A2WHELPER(dir, wBuffer, sizeof(wBuffer));
2617 return _wmkdir(PerlDir_mapW(wBuffer));
2619 return mkdir(PerlDir_mapA(dir)); /* just ignore mode */
2623 win32_rmdir(const char *dir)
2627 WCHAR wBuffer[MAX_PATH];
2628 A2WHELPER(dir, wBuffer, sizeof(wBuffer));
2629 return _wrmdir(PerlDir_mapW(wBuffer));
2631 return rmdir(PerlDir_mapA(dir));
2635 win32_chdir(const char *dir)
2639 WCHAR wBuffer[MAX_PATH];
2640 A2WHELPER(dir, wBuffer, sizeof(wBuffer));
2641 return _wchdir(wBuffer);
2647 win32_access(const char *path, int mode)
2651 WCHAR wBuffer[MAX_PATH];
2652 A2WHELPER(path, wBuffer, sizeof(wBuffer));
2653 return _waccess(PerlDir_mapW(wBuffer), mode);
2655 return access(PerlDir_mapA(path), mode);
2659 win32_chmod(const char *path, int mode)
2663 WCHAR wBuffer[MAX_PATH];
2664 A2WHELPER(path, wBuffer, sizeof(wBuffer));
2665 return _wchmod(PerlDir_mapW(wBuffer), mode);
2667 return chmod(PerlDir_mapA(path), mode);
2672 create_command_line(const char* command, const char * const *args)
2676 char *cmd, *ptr, *arg;
2677 STRLEN len = strlen(command) + 1;
2679 for (index = 0; (ptr = (char*)args[index]) != NULL; ++index)
2680 len += strlen(ptr) + 1;
2682 New(1310, cmd, len, char);
2684 strcpy(ptr, command);
2686 for (index = 0; (arg = (char*)args[index]) != NULL; ++index) {
2696 qualified_path(const char *cmd)
2700 char *fullcmd, *curfullcmd;
2706 fullcmd = (char*)cmd;
2708 if (*fullcmd == '/' || *fullcmd == '\\')
2715 pathstr = win32_getenv("PATH");
2716 New(0, fullcmd, MAX_PATH+1, char);
2717 curfullcmd = fullcmd;
2722 /* start by appending the name to the current prefix */
2723 strcpy(curfullcmd, cmd);
2724 curfullcmd += cmdlen;
2726 /* if it doesn't end with '.', or has no extension, try adding
2727 * a trailing .exe first */
2728 if (cmd[cmdlen-1] != '.'
2729 && (cmdlen < 4 || cmd[cmdlen-4] != '.'))
2731 strcpy(curfullcmd, ".exe");
2732 res = GetFileAttributes(fullcmd);
2733 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
2738 /* that failed, try the bare name */
2739 res = GetFileAttributes(fullcmd);
2740 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
2743 /* quit if no other path exists, or if cmd already has path */
2744 if (!pathstr || !*pathstr || has_slash)
2747 /* skip leading semis */
2748 while (*pathstr == ';')
2751 /* build a new prefix from scratch */
2752 curfullcmd = fullcmd;
2753 while (*pathstr && *pathstr != ';') {
2754 if (*pathstr == '"') { /* foo;"baz;etc";bar */
2755 pathstr++; /* skip initial '"' */
2756 while (*pathstr && *pathstr != '"') {
2757 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
2758 *curfullcmd++ = *pathstr;
2762 pathstr++; /* skip trailing '"' */
2765 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
2766 *curfullcmd++ = *pathstr;
2771 pathstr++; /* skip trailing semi */
2772 if (curfullcmd > fullcmd /* append a dir separator */
2773 && curfullcmd[-1] != '/' && curfullcmd[-1] != '\\')
2775 *curfullcmd++ = '\\';
2783 /* The following are just place holders.
2784 * Some hosts may provide and environment that the OS is
2785 * not tracking, therefore, these host must provide that
2786 * environment and the current directory to CreateProcess
2796 free_childenv(void* d)
2805 char szfilename[(MAX_PATH+1)*2];
2807 WCHAR wfilename[MAX_PATH+1];
2808 GetCurrentDirectoryW(MAX_PATH+1, wfilename);
2809 W2AHELPER(wfilename, szfilename, sizeof(szfilename));
2812 GetCurrentDirectoryA(MAX_PATH+1, szfilename);
2815 New(0, ptr, strlen(szfilename)+1, char);
2816 strcpy(ptr, szfilename);
2821 free_childdir(char* d)
2828 /* XXX this needs to be made more compatible with the spawnvp()
2829 * provided by the various RTLs. In particular, searching for
2830 * *.{com,bat,cmd} files (as done by the RTLs) is unimplemented.
2831 * This doesn't significantly affect perl itself, because we
2832 * always invoke things using PERL5SHELL if a direct attempt to
2833 * spawn the executable fails.
2835 * XXX splitting and rejoining the commandline between do_aspawn()
2836 * and win32_spawnvp() could also be avoided.
2840 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
2842 #ifdef USE_RTL_SPAWNVP
2843 return spawnvp(mode, cmdname, (char * const *)argv);
2849 STARTUPINFO StartupInfo;
2850 PROCESS_INFORMATION ProcessInformation;
2853 char *cmd = create_command_line(cmdname, strcmp(cmdname, argv[0]) == 0
2855 char *fullcmd = Nullch;
2857 env = PerlEnv_get_childenv();
2858 dir = PerlEnv_get_childdir();
2861 case P_NOWAIT: /* asynch + remember result */
2862 if (w32_num_children >= MAXIMUM_WAIT_OBJECTS) {
2868 case P_WAIT: /* synchronous execution */
2870 default: /* invalid mode */
2875 memset(&StartupInfo,0,sizeof(StartupInfo));
2876 StartupInfo.cb = sizeof(StartupInfo);
2877 StartupInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
2878 StartupInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
2879 StartupInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
2880 if (StartupInfo.hStdInput != INVALID_HANDLE_VALUE &&
2881 StartupInfo.hStdOutput != INVALID_HANDLE_VALUE &&
2882 StartupInfo.hStdError != INVALID_HANDLE_VALUE)
2884 StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
2887 create |= CREATE_NEW_CONSOLE;
2891 if (!CreateProcess(cmdname, /* search PATH to find executable */
2892 cmd, /* executable, and its arguments */
2893 NULL, /* process attributes */
2894 NULL, /* thread attributes */
2895 TRUE, /* inherit handles */
2896 create, /* creation flags */
2897 (LPVOID)env, /* inherit environment */
2898 dir, /* inherit cwd */
2900 &ProcessInformation))
2902 /* initial NULL argument to CreateProcess() does a PATH
2903 * search, but it always first looks in the directory
2904 * where the current process was started, which behavior
2905 * is undesirable for backward compatibility. So we
2906 * jump through our own hoops by picking out the path
2907 * we really want it to use. */
2909 fullcmd = qualified_path(cmdname);
2920 if (mode == P_NOWAIT) {
2921 /* asynchronous spawn -- store handle, return PID */
2922 w32_child_handles[w32_num_children] = ProcessInformation.hProcess;
2923 w32_child_pids[w32_num_children] = ProcessInformation.dwProcessId;
2924 ret = (int)ProcessInformation.dwProcessId;
2929 WaitForSingleObject(ProcessInformation.hProcess, INFINITE);
2930 GetExitCodeProcess(ProcessInformation.hProcess, &status);
2932 CloseHandle(ProcessInformation.hProcess);
2935 CloseHandle(ProcessInformation.hThread);
2938 PerlEnv_free_childenv(env);
2939 PerlEnv_free_childdir(dir);
2947 win32_execv(const char *cmdname, const char *const *argv)
2951 /* if this is a pseudo-forked child, we just want to spawn
2952 * the new program, and return */
2954 return spawnv(P_WAIT, cmdname, (char *const *)argv);
2956 return execv(cmdname, (char *const *)argv);
2960 win32_execvp(const char *cmdname, const char *const *argv)
2964 /* if this is a pseudo-forked child, we just want to spawn
2965 * the new program, and return */
2967 return win32_spawnvp(P_WAIT, cmdname, (char *const *)argv);
2969 return execvp(cmdname, (char *const *)argv);
2973 win32_perror(const char *str)
2979 win32_setbuf(FILE *pf, char *buf)
2985 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
2987 return setvbuf(pf, buf, type, size);
2991 win32_flushall(void)
2997 win32_fcloseall(void)
3003 win32_fgets(char *s, int n, FILE *pf)
3005 return fgets(s, n, pf);
3015 win32_fgetc(FILE *pf)
3021 win32_putc(int c, FILE *pf)
3027 win32_puts(const char *s)
3039 win32_putchar(int c)
3046 #ifndef USE_PERL_SBRK
3048 static char *committed = NULL;
3049 static char *base = NULL;
3050 static char *reserved = NULL;
3051 static char *brk = NULL;
3052 static DWORD pagesize = 0;
3053 static DWORD allocsize = 0;
3061 GetSystemInfo(&info);
3062 /* Pretend page size is larger so we don't perpetually
3063 * call the OS to commit just one page ...
3065 pagesize = info.dwPageSize << 3;
3066 allocsize = info.dwAllocationGranularity;
3068 /* This scheme fails eventually if request for contiguous
3069 * block is denied so reserve big blocks - this is only
3070 * address space not memory ...
3072 if (brk+need >= reserved)
3074 DWORD size = 64*1024*1024;
3076 if (committed && reserved && committed < reserved)
3078 /* Commit last of previous chunk cannot span allocations */
3079 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
3081 committed = reserved;
3083 /* Reserve some (more) space
3084 * Note this is a little sneaky, 1st call passes NULL as reserved
3085 * so lets system choose where we start, subsequent calls pass
3086 * the old end address so ask for a contiguous block
3088 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
3091 reserved = addr+size;
3106 if (brk > committed)
3108 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
3109 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
3124 win32_malloc(size_t size)
3126 return malloc(size);
3130 win32_calloc(size_t numitems, size_t size)
3132 return calloc(numitems,size);
3136 win32_realloc(void *block, size_t size)
3138 return realloc(block,size);
3142 win32_free(void *block)
3149 win32_open_osfhandle(long handle, int flags)
3151 return _open_osfhandle(handle, flags);
3155 win32_get_osfhandle(int fd)
3157 return _get_osfhandle(fd);
3161 win32_dynaload(const char* filename)
3166 WCHAR wfilename[MAX_PATH];
3167 A2WHELPER(filename, wfilename, sizeof(wfilename));
3168 hModule = LoadLibraryExW(PerlDir_mapW(wfilename), NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
3171 hModule = LoadLibraryExA(PerlDir_mapA(filename), NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
3184 /* Make the host for current directory */
3185 char* ptr = PerlEnv_get_childdir();
3188 * then it worked, set PV valid,
3189 * else return 'undef'
3192 SV *sv = sv_newmortal();
3194 PerlEnv_free_childdir(ptr);
3209 Perl_croak(aTHX_ "usage: Win32::SetCurrentDirectory($cwd)");
3210 if (!PerlDir_chdir(SvPV_nolen(ST(0))))
3217 XS(w32_GetNextAvailDrive)
3221 char root[] = "_:\\";
3226 if (GetDriveType(root) == 1) {
3235 XS(w32_GetLastError)
3239 XSRETURN_IV(GetLastError());
3243 XS(w32_SetLastError)
3247 Perl_croak(aTHX_ "usage: Win32::SetLastError($error)");
3248 SetLastError(SvIV(ST(0)));
3256 char *name = w32_getlogin_buffer;
3257 DWORD size = sizeof(w32_getlogin_buffer);
3259 if (GetUserName(name,&size)) {
3260 /* size includes NULL */
3261 ST(0) = sv_2mortal(newSVpvn(name,size-1));
3271 char name[MAX_COMPUTERNAME_LENGTH+1];
3272 DWORD size = sizeof(name);
3274 if (GetComputerName(name,&size)) {
3275 /* size does NOT include NULL :-( */
3276 ST(0) = sv_2mortal(newSVpvn(name,size));
3287 HINSTANCE hNetApi32 = LoadLibrary("netapi32.dll");
3288 DWORD (__stdcall *pfnNetApiBufferFree)(LPVOID Buffer);
3289 DWORD (__stdcall *pfnNetWkstaGetInfo)(LPWSTR servername, DWORD level,
3293 pfnNetApiBufferFree = (DWORD (__stdcall *)(void *))
3294 GetProcAddress(hNetApi32, "NetApiBufferFree");
3295 pfnNetWkstaGetInfo = (DWORD (__stdcall *)(LPWSTR, DWORD, void *))
3296 GetProcAddress(hNetApi32, "NetWkstaGetInfo");
3299 if (hNetApi32 && pfnNetWkstaGetInfo && pfnNetApiBufferFree) {
3300 /* this way is more reliable, in case user has a local account. */
3302 DWORD dnamelen = sizeof(dname);
3304 DWORD wki100_platform_id;
3305 LPWSTR wki100_computername;
3306 LPWSTR wki100_langroup;
3307 DWORD wki100_ver_major;
3308 DWORD wki100_ver_minor;
3310 /* NERR_Success *is* 0*/
3311 if (0 == pfnNetWkstaGetInfo(NULL, 100, &pwi)) {
3312 if (pwi->wki100_langroup && *(pwi->wki100_langroup)) {
3313 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_langroup,
3314 -1, (LPSTR)dname, dnamelen, NULL, NULL);
3317 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_computername,
3318 -1, (LPSTR)dname, dnamelen, NULL, NULL);
3320 pfnNetApiBufferFree(pwi);
3321 FreeLibrary(hNetApi32);
3324 FreeLibrary(hNetApi32);
3327 /* Win95 doesn't have NetWksta*(), so do it the old way */
3329 DWORD size = sizeof(name);
3331 FreeLibrary(hNetApi32);
3332 if (GetUserName(name,&size)) {
3333 char sid[ONE_K_BUFSIZE];
3334 DWORD sidlen = sizeof(sid);
3336 DWORD dnamelen = sizeof(dname);
3338 if (LookupAccountName(NULL, name, (PSID)&sid, &sidlen,
3339 dname, &dnamelen, &snu)) {
3340 XSRETURN_PV(dname); /* all that for this */
3352 DWORD flags, filecomplen;
3353 if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
3354 &flags, fsname, sizeof(fsname))) {
3355 if (GIMME_V == G_ARRAY) {
3356 XPUSHs(sv_2mortal(newSVpvn(fsname,strlen(fsname))));
3357 XPUSHs(sv_2mortal(newSViv(flags)));
3358 XPUSHs(sv_2mortal(newSViv(filecomplen)));
3363 XSRETURN_PV(fsname);
3369 XS(w32_GetOSVersion)
3372 OSVERSIONINFOA osver;
3375 OSVERSIONINFOW osverw;
3376 char szCSDVersion[sizeof(osverw.szCSDVersion)];
3377 osverw.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
3378 if (!GetVersionExW(&osverw)) {
3381 W2AHELPER(osverw.szCSDVersion, szCSDVersion, sizeof(szCSDVersion));
3382 XPUSHs(newSVpvn(szCSDVersion, strlen(szCSDVersion)));
3383 osver.dwMajorVersion = osverw.dwMajorVersion;
3384 osver.dwMinorVersion = osverw.dwMinorVersion;
3385 osver.dwBuildNumber = osverw.dwBuildNumber;
3386 osver.dwPlatformId = osverw.dwPlatformId;
3389 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOA);
3390 if (!GetVersionExA(&osver)) {
3393 XPUSHs(newSVpvn(osver.szCSDVersion, strlen(osver.szCSDVersion)));
3395 XPUSHs(newSViv(osver.dwMajorVersion));
3396 XPUSHs(newSViv(osver.dwMinorVersion));
3397 XPUSHs(newSViv(osver.dwBuildNumber));
3398 XPUSHs(newSViv(osver.dwPlatformId));
3407 XSRETURN_IV(IsWinNT());
3415 XSRETURN_IV(IsWin95());
3419 XS(w32_FormatMessage)
3423 char msgbuf[ONE_K_BUFSIZE];
3426 Perl_croak(aTHX_ "usage: Win32::FormatMessage($errno)");
3429 WCHAR wmsgbuf[ONE_K_BUFSIZE];
3430 if (FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM,
3431 &source, SvIV(ST(0)), 0,
3432 wmsgbuf, ONE_K_BUFSIZE-1, NULL))
3434 W2AHELPER(wmsgbuf, msgbuf, sizeof(msgbuf));
3435 XSRETURN_PV(msgbuf);
3439 if (FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM,
3440 &source, SvIV(ST(0)), 0,
3441 msgbuf, sizeof(msgbuf)-1, NULL))
3442 XSRETURN_PV(msgbuf);
3453 PROCESS_INFORMATION stProcInfo;
3454 STARTUPINFO stStartInfo;
3455 BOOL bSuccess = FALSE;
3458 Perl_croak(aTHX_ "usage: Win32::Spawn($cmdName, $args, $PID)");
3460 cmd = SvPV_nolen(ST(0));
3461 args = SvPV_nolen(ST(1));
3463 memset(&stStartInfo, 0, sizeof(stStartInfo)); /* Clear the block */
3464 stStartInfo.cb = sizeof(stStartInfo); /* Set the structure size */
3465 stStartInfo.dwFlags = STARTF_USESHOWWINDOW; /* Enable wShowWindow control */
3466 stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE; /* Start min (normal) */
3469 cmd, /* Image path */
3470 args, /* Arguments for command line */
3471 NULL, /* Default process security */
3472 NULL, /* Default thread security */
3473 FALSE, /* Must be TRUE to use std handles */
3474 NORMAL_PRIORITY_CLASS, /* No special scheduling */
3475 NULL, /* Inherit our environment block */
3476 NULL, /* Inherit our currrent directory */
3477 &stStartInfo, /* -> Startup info */
3478 &stProcInfo)) /* <- Process info (if OK) */
3480 CloseHandle(stProcInfo.hThread);/* library source code does this. */
3481 sv_setiv(ST(2), stProcInfo.dwProcessId);
3484 XSRETURN_IV(bSuccess);
3488 XS(w32_GetTickCount)
3491 DWORD msec = GetTickCount();
3499 XS(w32_GetShortPathName)
3506 Perl_croak(aTHX_ "usage: Win32::GetShortPathName($longPathName)");
3508 shortpath = sv_mortalcopy(ST(0));
3509 SvUPGRADE(shortpath, SVt_PV);
3510 /* src == target is allowed */
3512 len = GetShortPathName(SvPVX(shortpath),
3515 } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
3517 SvCUR_set(shortpath,len);
3525 XS(w32_GetFullPathName)
3534 Perl_croak(aTHX_ "usage: Win32::GetFullPathName($filename)");
3537 fullpath = sv_mortalcopy(filename);
3538 SvUPGRADE(fullpath, SVt_PV);
3540 len = GetFullPathName(SvPVX(filename),
3544 } while (len >= SvLEN(fullpath) && sv_grow(fullpath,len+1));
3546 if (GIMME_V == G_ARRAY) {
3548 XST_mPV(1,filepart);
3549 len = filepart - SvPVX(fullpath);
3552 SvCUR_set(fullpath,len);
3560 XS(w32_GetLongPathName)
3564 char tmpbuf[MAX_PATH+1];
3569 Perl_croak(aTHX_ "usage: Win32::GetLongPathName($pathname)");
3572 pathstr = SvPV(path,len);
3573 strcpy(tmpbuf, pathstr);
3574 pathstr = win32_longpath(tmpbuf);
3576 ST(0) = sv_2mortal(newSVpvn(pathstr, strlen(pathstr)));
3587 Perl_croak(aTHX_ "usage: Win32::Sleep($milliseconds)");
3598 Perl_croak(aTHX_ "usage: Win32::CopyFile($from, $to, $overwrite)");
3600 WCHAR wSourceFile[MAX_PATH];
3601 WCHAR wDestFile[MAX_PATH];
3602 A2WHELPER(SvPV_nolen(ST(0)), wSourceFile, sizeof(wSourceFile));
3603 wcscpy(wSourceFile, PerlDir_mapW(wSourceFile));
3604 A2WHELPER(SvPV_nolen(ST(1)), wDestFile, sizeof(wDestFile));
3605 bResult = CopyFileW(wSourceFile, PerlDir_mapW(wDestFile), !SvTRUE(ST(2)));
3608 char szSourceFile[MAX_PATH];
3609 strcpy(szSourceFile, PerlDir_mapA(SvPV_nolen(ST(0))));
3610 bResult = CopyFileA(szSourceFile, PerlDir_mapA(SvPV_nolen(ST(1))), !SvTRUE(ST(2)));
3619 Perl_init_os_extras(void)
3622 char *file = __FILE__;
3625 w32_perlshell_tokens = Nullch;
3626 w32_perlshell_items = -1;
3627 w32_fdpid = newAV(); /* XXX needs to be in Perl_win32_init()? */
3628 New(1313, w32_children, 1, child_tab);
3629 w32_num_children = 0;
3630 w32_init_socktype = 0;
3633 New(1313, w32_pseudo_children, 1, child_tab);
3634 w32_num_pseudo_children = 0;
3637 /* these names are Activeware compatible */
3638 newXS("Win32::GetCwd", w32_GetCwd, file);
3639 newXS("Win32::SetCwd", w32_SetCwd, file);
3640 newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
3641 newXS("Win32::GetLastError", w32_GetLastError, file);
3642 newXS("Win32::SetLastError", w32_SetLastError, file);
3643 newXS("Win32::LoginName", w32_LoginName, file);
3644 newXS("Win32::NodeName", w32_NodeName, file);
3645 newXS("Win32::DomainName", w32_DomainName, file);
3646 newXS("Win32::FsType", w32_FsType, file);
3647 newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
3648 newXS("Win32::IsWinNT", w32_IsWinNT, file);
3649 newXS("Win32::IsWin95", w32_IsWin95, file);
3650 newXS("Win32::FormatMessage", w32_FormatMessage, file);
3651 newXS("Win32::Spawn", w32_Spawn, file);
3652 newXS("Win32::GetTickCount", w32_GetTickCount, file);
3653 newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
3654 newXS("Win32::GetFullPathName", w32_GetFullPathName, file);
3655 newXS("Win32::GetLongPathName", w32_GetLongPathName, file);
3656 newXS("Win32::CopyFile", w32_CopyFile, file);
3657 newXS("Win32::Sleep", w32_Sleep, file);
3659 /* XXX Bloat Alert! The following Activeware preloads really
3660 * ought to be part of Win32::Sys::*, so they're not included
3663 /* LookupAccountName
3665 * InitiateSystemShutdown
3666 * AbortSystemShutdown
3667 * ExpandEnvrironmentStrings
3672 Perl_win32_init(int *argcp, char ***argvp)
3674 /* Disable floating point errors, Perl will trap the ones we
3675 * care about. VC++ RTL defaults to switching these off
3676 * already, but the Borland RTL doesn't. Since we don't
3677 * want to be at the vendor's whim on the default, we set
3678 * it explicitly here.
3680 #if !defined(_ALPHA_) && !defined(__GNUC__)
3681 _control87(MCW_EM, MCW_EM);
3689 # undef Perl_sys_intern_dup
3690 # define Perl_sys_intern_dup CPerlObj::Perl_sys_intern_dup
3695 Perl_sys_intern_dup(pTHX_ struct interp_intern *src, struct interp_intern *dst)
3697 dst->perlshell_tokens = Nullch;
3698 dst->perlshell_vec = (char**)NULL;
3699 dst->perlshell_items = 0;
3700 dst->fdpid = newAV();
3701 Newz(1313, dst->children, 1, child_tab);
3702 Newz(1313, dst->pseudo_children, 1, child_tab);
3704 dst->children->num = 0;
3705 dst->thr_intern.Winit_socktype = src->thr_intern.Winit_socktype;