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
19 /* #include "config.h" */
21 #define PERLIO_NOT_STDIO 0
22 #if !defined(PERLIO_IS_STDIO) && !defined(USE_SFIO)
31 #define PERL_NO_GET_CONTEXT
37 /* assert.h conflicts with #define of assert in perl.h */
44 #if defined(_MSC_VER) || defined(__MINGW32__)
45 #include <sys/utime.h>
51 /* Mingw32 defaults to globing command line
52 * So we turn it off like this:
57 #if defined(__MINGW32__)
61 #if defined(__BORLANDC__)
63 # define _utimbuf utimbuf
68 #define EXECF_SPAWN_NOWAIT 3
70 #if defined(PERL_IMPLICIT_SYS)
71 # undef win32_get_privlib
72 # define win32_get_privlib g_win32_get_privlib
73 # undef win32_get_sitelib
74 # define win32_get_sitelib g_win32_get_sitelib
76 # define do_spawn g_do_spawn
78 # define getlogin g_getlogin
81 #if defined(PERL_OBJECT)
83 # define do_aspawn g_do_aspawn
85 # define Perl_do_exec g_do_exec
88 static void get_shell(void);
89 static long tokenize(const char *str, char **dest, char ***destv);
90 int do_spawn2(char *cmd, int exectype);
91 static BOOL has_shell_metachars(char *ptr);
92 static long filetime_to_clock(PFILETIME ft);
93 static BOOL filetime_from_time(PFILETIME ft, time_t t);
94 static char * get_emd_part(SV **leading, char *trailing, ...);
95 static void remove_dead_process(long deceased);
96 static long find_pid(int pid);
97 static char * qualified_path(const char *cmd);
99 static void remove_dead_pseudo_process(long child);
100 static long find_pseudo_pid(int pid);
104 HANDLE w32_perldll_handle = INVALID_HANDLE_VALUE;
105 char w32_module_name[MAX_PATH+1];
108 static DWORD w32_platform = (DWORD)-1;
110 #define ONE_K_BUFSIZE 1024
115 return (win32_os_id() == VER_PLATFORM_WIN32_WINDOWS);
121 return (win32_os_id() == VER_PLATFORM_WIN32_NT);
124 /* *svp (if non-NULL) is expected to be POK (valid allocated SvPVX(*svp)) */
126 get_regstr_from(HKEY hkey, const char *valuename, SV **svp)
128 /* Retrieve a REG_SZ or REG_EXPAND_SZ from the registry */
131 const char *subkey = "Software\\Perl";
135 retval = RegOpenKeyEx(hkey, subkey, 0, KEY_READ, &handle);
136 if (retval == ERROR_SUCCESS) {
138 retval = RegQueryValueEx(handle, valuename, 0, &type, NULL, &datalen);
139 if (retval == ERROR_SUCCESS && type == REG_SZ) {
142 *svp = sv_2mortal(newSVpvn("",0));
143 SvGROW(*svp, datalen);
144 retval = RegQueryValueEx(handle, valuename, 0, NULL,
145 (PBYTE)SvPVX(*svp), &datalen);
146 if (retval == ERROR_SUCCESS) {
148 SvCUR_set(*svp,datalen-1);
156 /* *svp (if non-NULL) is expected to be POK (valid allocated SvPVX(*svp)) */
158 get_regstr(const char *valuename, SV **svp)
160 char *str = get_regstr_from(HKEY_CURRENT_USER, valuename, svp);
162 str = get_regstr_from(HKEY_LOCAL_MACHINE, valuename, svp);
166 /* *prev_pathp (if non-NULL) is expected to be POK (valid allocated SvPVX(sv)) */
168 get_emd_part(SV **prev_pathp, char *trailing_path, ...)
172 char mod_name[MAX_PATH+1];
176 int oldsize, newsize;
178 va_start(ap, trailing_path);
179 strip = va_arg(ap, char *);
181 sprintf(base, "%5.3f",
182 (double)PERL_REVISION + ((double)PERL_VERSION / (double)1000));
184 if (!*w32_module_name) {
185 GetModuleFileName((HMODULE)((w32_perldll_handle == INVALID_HANDLE_VALUE)
186 ? GetModuleHandle(NULL)
187 : w32_perldll_handle),
188 w32_module_name, sizeof(w32_module_name));
190 /* try to get full path to binary (which may be mangled when perl is
191 * run from a 16-bit app) */
192 /*PerlIO_printf(Perl_debug_log, "Before %s\n", w32_module_name);*/
193 (void)win32_longpath(w32_module_name);
194 /*PerlIO_printf(Perl_debug_log, "After %s\n", w32_module_name);*/
196 /* normalize to forward slashes */
197 ptr = w32_module_name;
204 strcpy(mod_name, w32_module_name);
205 ptr = strrchr(mod_name, '/');
206 while (ptr && strip) {
207 /* look for directories to skip back */
210 ptr = strrchr(mod_name, '/');
211 /* avoid stripping component if there is no slash,
212 * or it doesn't match ... */
213 if (!ptr || stricmp(ptr+1, strip) != 0) {
214 /* ... but not if component matches 5.00X* */
215 if (!ptr || !(*strip == '5' && *(ptr+1) == '5'
216 && strncmp(strip, base, 5) == 0
217 && strncmp(ptr+1, base, 5) == 0))
223 strip = va_arg(ap, char *);
231 strcpy(++ptr, trailing_path);
233 /* only add directory if it exists */
234 if (GetFileAttributes(mod_name) != (DWORD) -1) {
235 /* directory exists */
238 *prev_pathp = sv_2mortal(newSVpvn("",0));
239 sv_catpvn(*prev_pathp, ";", 1);
240 sv_catpv(*prev_pathp, mod_name);
241 return SvPVX(*prev_pathp);
248 win32_get_privlib(char *pl)
251 char *stdlib = "lib";
252 char buffer[MAX_PATH+1];
255 /* $stdlib = $HKCU{"lib-$]"} || $HKLM{"lib-$]"} || $HKCU{"lib"} || $HKLM{"lib"} || ""; */
256 sprintf(buffer, "%s-%s", stdlib, pl);
257 if (!get_regstr(buffer, &sv))
258 (void)get_regstr(stdlib, &sv);
260 /* $stdlib .= ";$EMD/../../lib" */
261 return get_emd_part(&sv, stdlib, ARCHNAME, "bin", Nullch);
265 win32_get_sitelib(char *pl)
268 char *sitelib = "sitelib";
270 char pathstr[MAX_PATH+1];
276 /* $HKCU{"sitelib-$]"} || $HKLM{"sitelib-$]"} . ---; */
277 sprintf(regstr, "%s-%s", sitelib, pl);
278 (void)get_regstr(regstr, &sv1);
281 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/site/$]/lib"; */
282 sprintf(pathstr, "site/%s/lib", pl);
283 (void)get_emd_part(&sv1, pathstr, ARCHNAME, "bin", pl, Nullch);
284 if (!sv1 && strlen(pl) == 7) {
285 /* pl may have been SUBVERSION-specific; try again without
287 sprintf(pathstr, "site/%.5s/lib", pl);
288 (void)get_emd_part(&sv1, pathstr, ARCHNAME, "bin", pl, Nullch);
291 /* $HKCU{'sitelib'} || $HKLM{'sitelib'} . ---; */
292 (void)get_regstr(sitelib, &sv2);
295 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/site/lib"; */
296 (void)get_emd_part(&sv2, "site/lib", ARCHNAME, "bin", pl, Nullch);
305 sv_catpvn(sv1, ";", 1);
313 has_shell_metachars(char *ptr)
319 * Scan string looking for redirection (< or >) or pipe
320 * characters (|) that are not in a quoted string.
321 * Shell variable interpolation (%VAR%) can also happen inside strings.
353 #if !defined(PERL_IMPLICIT_SYS)
354 /* since the current process environment is being updated in util.c
355 * the library functions will get the correct environment
358 Perl_my_popen(pTHX_ char *cmd, char *mode)
361 #define fixcmd(x) { \
362 char *pspace = strchr((x),' '); \
365 while (p < pspace) { \
376 PERL_FLUSHALL_FOR_CHILD;
377 return win32_popen(cmd, mode);
381 Perl_my_pclose(pTHX_ PerlIO *fp)
383 return win32_pclose(fp);
387 DllExport unsigned long
390 static OSVERSIONINFO osver;
392 if (osver.dwPlatformId != w32_platform) {
393 memset(&osver, 0, sizeof(OSVERSIONINFO));
394 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
395 GetVersionEx(&osver);
396 w32_platform = osver.dwPlatformId;
398 return (unsigned long)w32_platform;
407 return -((int)w32_pseudo_id);
412 /* Tokenize a string. Words are null-separated, and the list
413 * ends with a doubled null. Any character (except null and
414 * including backslash) may be escaped by preceding it with a
415 * backslash (the backslash will be stripped).
416 * Returns number of words in result buffer.
419 tokenize(const char *str, char **dest, char ***destv)
421 char *retstart = Nullch;
422 char **retvstart = 0;
426 int slen = strlen(str);
428 register char **retv;
429 New(1307, ret, slen+2, char);
430 New(1308, retv, (slen+3)/2, char*);
438 if (*ret == '\\' && *str)
440 else if (*ret == ' ') {
456 retvstart[items] = Nullch;
469 if (!w32_perlshell_tokens) {
470 /* we don't use COMSPEC here for two reasons:
471 * 1. the same reason perl on UNIX doesn't use SHELL--rampant and
472 * uncontrolled unportability of the ensuing scripts.
473 * 2. PERL5SHELL could be set to a shell that may not be fit for
474 * interactive use (which is what most programs look in COMSPEC
477 const char* defaultshell = (IsWinNT()
478 ? "cmd.exe /x/c" : "command.com /c");
479 const char *usershell = getenv("PERL5SHELL");
480 w32_perlshell_items = tokenize(usershell ? usershell : defaultshell,
481 &w32_perlshell_tokens,
487 do_aspawn(void *vreally, void **vmark, void **vsp)
490 SV *really = (SV*)vreally;
491 SV **mark = (SV**)vmark;
503 New(1306, argv, (sp - mark) + w32_perlshell_items + 2, char*);
505 if (SvNIOKp(*(mark+1)) && !SvPOKp(*(mark+1))) {
510 while (++mark <= sp) {
511 if (*mark && (str = SvPV_nolen(*mark)))
518 status = win32_spawnvp(flag,
519 (const char*)(really ? SvPV_nolen(really) : argv[0]),
520 (const char* const*)argv);
522 if (status < 0 && (errno == ENOEXEC || errno == ENOENT)) {
523 /* possible shell-builtin, invoke with shell */
525 sh_items = w32_perlshell_items;
527 argv[index+sh_items] = argv[index];
528 while (--sh_items >= 0)
529 argv[sh_items] = w32_perlshell_vec[sh_items];
531 status = win32_spawnvp(flag,
532 (const char*)(really ? SvPV_nolen(really) : argv[0]),
533 (const char* const*)argv);
536 if (flag != P_NOWAIT) {
539 if (ckWARN(WARN_EXEC))
540 Perl_warner(aTHX_ WARN_EXEC, "Can't spawn \"%s\": %s", argv[0], strerror(errno));
545 PL_statusvalue = status;
552 do_spawn2(char *cmd, int exectype)
559 BOOL needToTry = TRUE;
562 /* Save an extra exec if possible. See if there are shell
563 * metacharacters in it */
564 if (!has_shell_metachars(cmd)) {
565 New(1301,argv, strlen(cmd) / 2 + 2, char*);
566 New(1302,cmd2, strlen(cmd) + 1, char);
569 for (s = cmd2; *s;) {
570 while (*s && isSPACE(*s))
574 while (*s && !isSPACE(*s))
583 status = win32_spawnvp(P_WAIT, argv[0],
584 (const char* const*)argv);
586 case EXECF_SPAWN_NOWAIT:
587 status = win32_spawnvp(P_NOWAIT, argv[0],
588 (const char* const*)argv);
591 status = win32_execvp(argv[0], (const char* const*)argv);
594 if (status != -1 || errno == 0)
604 New(1306, argv, w32_perlshell_items + 2, char*);
605 while (++i < w32_perlshell_items)
606 argv[i] = w32_perlshell_vec[i];
611 status = win32_spawnvp(P_WAIT, argv[0],
612 (const char* const*)argv);
614 case EXECF_SPAWN_NOWAIT:
615 status = win32_spawnvp(P_NOWAIT, argv[0],
616 (const char* const*)argv);
619 status = win32_execvp(argv[0], (const char* const*)argv);
625 if (exectype != EXECF_SPAWN_NOWAIT) {
628 if (ckWARN(WARN_EXEC))
629 Perl_warner(aTHX_ WARN_EXEC, "Can't %s \"%s\": %s",
630 (exectype == EXECF_EXEC ? "exec" : "spawn"),
631 cmd, strerror(errno));
636 PL_statusvalue = status;
644 return do_spawn2(cmd, EXECF_SPAWN);
648 do_spawn_nowait(char *cmd)
650 return do_spawn2(cmd, EXECF_SPAWN_NOWAIT);
654 Perl_do_exec(pTHX_ char *cmd)
656 do_spawn2(cmd, EXECF_EXEC);
660 /* The idea here is to read all the directory names into a string table
661 * (separated by nulls) and when one of the other dir functions is called
662 * return the pointer to the current file name.
665 win32_opendir(char *filename)
671 char scanname[MAX_PATH+3];
673 WIN32_FIND_DATAA aFindData;
674 WIN32_FIND_DATAW wFindData;
676 char buffer[MAX_PATH*2];
677 WCHAR wbuffer[MAX_PATH];
680 len = strlen(filename);
684 /* check to see if filename is a directory */
685 if (win32_stat(filename, &sbuf) < 0 || !S_ISDIR(sbuf.st_mode))
688 /* Get us a DIR structure */
689 Newz(1303, dirp, 1, DIR);
691 /* Create the search pattern */
692 strcpy(scanname, filename);
694 /* bare drive name means look in cwd for drive */
695 if (len == 2 && isALPHA(scanname[0]) && scanname[1] == ':') {
696 scanname[len++] = '.';
697 scanname[len++] = '/';
699 else if (scanname[len-1] != '/' && scanname[len-1] != '\\') {
700 scanname[len++] = '/';
702 scanname[len++] = '*';
703 scanname[len] = '\0';
705 /* do the FindFirstFile call */
707 A2WHELPER(scanname, wbuffer, sizeof(wbuffer));
708 fh = FindFirstFileW(PerlDir_mapW(wbuffer), &wFindData);
711 fh = FindFirstFileA(PerlDir_mapA(scanname), &aFindData);
714 if (fh == INVALID_HANDLE_VALUE) {
715 DWORD err = GetLastError();
716 /* FindFirstFile() fails on empty drives! */
718 case ERROR_FILE_NOT_FOUND:
720 case ERROR_NO_MORE_FILES:
721 case ERROR_PATH_NOT_FOUND:
724 case ERROR_NOT_ENOUGH_MEMORY:
735 /* now allocate the first part of the string table for
736 * the filenames that we find.
739 W2AHELPER(wFindData.cFileName, buffer, sizeof(buffer));
743 ptr = aFindData.cFileName;
750 New(1304, dirp->start, dirp->size, char);
751 strcpy(dirp->start, ptr);
753 dirp->end = dirp->curr = dirp->start;
759 /* Readdir just returns the current string pointer and bumps the
760 * string pointer to the nDllExport entry.
762 DllExport struct direct *
763 win32_readdir(DIR *dirp)
768 /* first set up the structure to return */
769 len = strlen(dirp->curr);
770 strcpy(dirp->dirstr.d_name, dirp->curr);
771 dirp->dirstr.d_namlen = len;
774 dirp->dirstr.d_ino = dirp->curr - dirp->start;
776 /* Now set up for the next call to readdir */
777 dirp->curr += len + 1;
778 if (dirp->curr >= dirp->end) {
782 WIN32_FIND_DATAW wFindData;
783 WIN32_FIND_DATAA aFindData;
784 char buffer[MAX_PATH*2];
786 /* finding the next file that matches the wildcard
787 * (which should be all of them in this directory!).
790 res = FindNextFileW(dirp->handle, &wFindData);
792 W2AHELPER(wFindData.cFileName, buffer, sizeof(buffer));
797 res = FindNextFileA(dirp->handle, &aFindData);
799 ptr = aFindData.cFileName;
802 long endpos = dirp->end - dirp->start;
803 long newsize = endpos + strlen(ptr) + 1;
804 /* bump the string table size by enough for the
805 * new name and it's null terminator */
806 while (newsize > dirp->size) {
807 long curpos = dirp->curr - dirp->start;
809 Renew(dirp->start, dirp->size, char);
810 dirp->curr = dirp->start + curpos;
812 strcpy(dirp->start + endpos, ptr);
813 dirp->end = dirp->start + newsize;
819 return &(dirp->dirstr);
825 /* Telldir returns the current string pointer position */
827 win32_telldir(DIR *dirp)
829 return (dirp->curr - dirp->start);
833 /* Seekdir moves the string pointer to a previously saved position
834 * (returned by telldir).
837 win32_seekdir(DIR *dirp, long loc)
839 dirp->curr = dirp->start + loc;
842 /* Rewinddir resets the string pointer to the start */
844 win32_rewinddir(DIR *dirp)
846 dirp->curr = dirp->start;
849 /* free the memory allocated by opendir */
851 win32_closedir(DIR *dirp)
854 if (dirp->handle != INVALID_HANDLE_VALUE)
855 FindClose(dirp->handle);
856 Safefree(dirp->start);
869 * Just pretend that everyone is a superuser. NT will let us know if
870 * we don\'t really have permission to do something.
873 #define ROOT_UID ((uid_t)0)
874 #define ROOT_GID ((gid_t)0)
903 return (auid == ROOT_UID ? 0 : -1);
909 return (agid == ROOT_GID ? 0 : -1);
916 char *buf = w32_getlogin_buffer;
917 DWORD size = sizeof(w32_getlogin_buffer);
918 if (GetUserName(buf,&size))
924 chown(const char *path, uid_t owner, gid_t group)
934 long child = w32_num_children;
935 while (--child >= 0) {
936 if (w32_child_pids[child] == pid)
943 remove_dead_process(long child)
947 CloseHandle(w32_child_handles[child]);
948 Copy(&w32_child_handles[child+1], &w32_child_handles[child],
949 (w32_num_children-child-1), HANDLE);
950 Copy(&w32_child_pids[child+1], &w32_child_pids[child],
951 (w32_num_children-child-1), DWORD);
958 find_pseudo_pid(int pid)
961 long child = w32_num_pseudo_children;
962 while (--child >= 0) {
963 if (w32_pseudo_child_pids[child] == pid)
970 remove_dead_pseudo_process(long child)
974 CloseHandle(w32_pseudo_child_handles[child]);
975 Copy(&w32_pseudo_child_handles[child+1], &w32_pseudo_child_handles[child],
976 (w32_num_pseudo_children-child-1), HANDLE);
977 Copy(&w32_pseudo_child_pids[child+1], &w32_pseudo_child_pids[child],
978 (w32_num_pseudo_children-child-1), DWORD);
979 w32_num_pseudo_children--;
985 win32_kill(int pid, int sig)
991 /* it is a pseudo-forked child */
992 long child = find_pseudo_pid(-pid);
994 hProcess = w32_pseudo_child_handles[child];
995 if (TerminateThread(hProcess, sig)) {
996 remove_dead_pseudo_process(child);
1004 long child = find_pid(pid);
1006 hProcess = w32_child_handles[child];
1007 if (TerminateProcess(hProcess, sig)) {
1008 remove_dead_process(child);
1013 hProcess = OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid);
1014 if (hProcess && TerminateProcess(hProcess, sig)) {
1015 CloseHandle(hProcess);
1028 DllExport unsigned int
1029 win32_sleep(unsigned int t)
1036 win32_stat(const char *path, struct stat *buffer)
1040 int l = strlen(path);
1042 WCHAR wbuffer[MAX_PATH];
1047 switch(path[l - 1]) {
1048 /* FindFirstFile() and stat() are buggy with a trailing
1049 * backslash, so change it to a forward slash :-( */
1051 strncpy(t, path, l-1);
1056 /* FindFirstFile() is buggy with "x:", so add a dot :-( */
1058 if (l == 2 && isALPHA(path[0])) {
1059 t[0] = path[0]; t[1] = ':'; t[2] = '.'; t[3] = '\0';
1067 /* We *must* open & close the file once; otherwise file attribute changes */
1068 /* might not yet have propagated to "other" hard links of the same file. */
1069 /* This also gives us an opportunity to determine the number of links. */
1071 A2WHELPER(path, wbuffer, sizeof(wbuffer));
1072 wcscpy(wbuffer, PerlDir_mapW(wbuffer));
1073 handle = CreateFileW(wbuffer, 0, 0, NULL, OPEN_EXISTING, 0, NULL);
1076 path = PerlDir_mapA(path);
1077 handle = CreateFileA(path, 0, 0, NULL, OPEN_EXISTING, 0, NULL);
1079 if (handle != INVALID_HANDLE_VALUE) {
1080 BY_HANDLE_FILE_INFORMATION bhi;
1081 if (GetFileInformationByHandle(handle, &bhi))
1082 nlink = bhi.nNumberOfLinks;
1083 CloseHandle(handle);
1086 /* wbuffer or path will be mapped correctly above */
1088 res = _wstat(wbuffer, (struct _stat *)buffer);
1091 res = stat(path, buffer);
1093 buffer->st_nlink = nlink;
1096 /* CRT is buggy on sharenames, so make sure it really isn't.
1097 * XXX using GetFileAttributesEx() will enable us to set
1098 * buffer->st_*time (but note that's not available on the
1099 * Windows of 1995) */
1102 r = GetFileAttributesW(wbuffer);
1105 r = GetFileAttributesA(path);
1107 if (r != 0xffffffff && (r & FILE_ATTRIBUTE_DIRECTORY)) {
1108 /* buffer may still contain old garbage since stat() failed */
1109 Zero(buffer, 1, struct stat);
1110 buffer->st_mode = S_IFDIR | S_IREAD;
1112 if (!(r & FILE_ATTRIBUTE_READONLY))
1113 buffer->st_mode |= S_IWRITE | S_IEXEC;
1118 if (l == 3 && isALPHA(path[0]) && path[1] == ':'
1119 && (path[2] == '\\' || path[2] == '/'))
1121 /* The drive can be inaccessible, some _stat()s are buggy */
1123 ? !GetVolumeInformationW(wbuffer,NULL,0,NULL,NULL,NULL,NULL,0)
1124 : !GetVolumeInformationA(path,NULL,0,NULL,NULL,NULL,NULL,0)) {
1130 if (S_ISDIR(buffer->st_mode))
1131 buffer->st_mode |= S_IWRITE | S_IEXEC;
1132 else if (S_ISREG(buffer->st_mode)) {
1133 if (l >= 4 && path[l-4] == '.') {
1134 const char *e = path + l - 3;
1135 if (strnicmp(e,"exe",3)
1136 && strnicmp(e,"bat",3)
1137 && strnicmp(e,"com",3)
1138 && (IsWin95() || strnicmp(e,"cmd",3)))
1139 buffer->st_mode &= ~S_IEXEC;
1141 buffer->st_mode |= S_IEXEC;
1144 buffer->st_mode &= ~S_IEXEC;
1151 /* Find the longname of a given path. path is destructively modified.
1152 * It should have space for at least MAX_PATH characters. */
1154 win32_longpath(char *path)
1156 WIN32_FIND_DATA fdata;
1158 char tmpbuf[MAX_PATH+1];
1159 char *tmpstart = tmpbuf;
1166 if (isALPHA(path[0]) && path[1] == ':' &&
1167 (path[2] == '/' || path[2] == '\\'))
1170 *tmpstart++ = path[0];
1174 else if ((path[0] == '/' || path[0] == '\\') &&
1175 (path[1] == '/' || path[1] == '\\'))
1178 *tmpstart++ = path[0];
1179 *tmpstart++ = path[1];
1180 /* copy machine name */
1181 while (*start && *start != '/' && *start != '\\')
1182 *tmpstart++ = *start++;
1184 *tmpstart++ = *start;
1186 /* copy share name */
1187 while (*start && *start != '/' && *start != '\\')
1188 *tmpstart++ = *start++;
1192 if (sep == '/' || sep == '\\')
1196 /* walk up to slash */
1197 while (*start && *start != '/' && *start != '\\')
1200 /* discard doubled slashes */
1201 while (*start && (start[1] == '/' || start[1] == '\\'))
1205 /* stop and find full name of component */
1207 fhand = FindFirstFile(path,&fdata);
1208 if (fhand != INVALID_HANDLE_VALUE) {
1209 strcpy(tmpstart, fdata.cFileName);
1210 tmpstart += strlen(fdata.cFileName);
1218 /* failed a step, just return without side effects */
1219 /*PerlIO_printf(Perl_debug_log, "Failed to find %s\n", path);*/
1224 strcpy(path,tmpbuf);
1228 #ifndef USE_WIN32_RTL_ENV
1231 win32_getenv(const char *name)
1234 WCHAR wBuffer[MAX_PATH];
1236 SV *curitem = Nullsv;
1239 A2WHELPER(name, wBuffer, sizeof(wBuffer));
1240 needlen = GetEnvironmentVariableW(wBuffer, NULL, 0);
1243 needlen = GetEnvironmentVariableA(name,NULL,0);
1245 curitem = sv_2mortal(newSVpvn("", 0));
1249 SvGROW(curitem, (needlen+1)*sizeof(WCHAR));
1250 needlen = GetEnvironmentVariableW(wBuffer,
1251 (WCHAR*)SvPVX(curitem),
1253 } while (needlen >= SvLEN(curitem)/sizeof(WCHAR));
1254 SvCUR_set(curitem, (needlen*sizeof(WCHAR))+1);
1255 acuritem = sv_2mortal(newSVsv(curitem));
1256 W2AHELPER((WCHAR*)SvPVX(acuritem), SvPVX(curitem), SvCUR(curitem));
1260 SvGROW(curitem, needlen+1);
1261 needlen = GetEnvironmentVariableA(name,SvPVX(curitem),
1263 } while (needlen >= SvLEN(curitem));
1264 SvCUR_set(curitem, needlen);
1268 /* allow any environment variables that begin with 'PERL'
1269 to be stored in the registry */
1270 if (strncmp(name, "PERL", 4) == 0)
1271 (void)get_regstr(name, &curitem);
1273 if (curitem && SvCUR(curitem))
1274 return SvPVX(curitem);
1280 win32_putenv(const char *name)
1287 int length, relval = -1;
1291 length = strlen(name)+1;
1292 New(1309,wCuritem,length,WCHAR);
1293 A2WHELPER(name, wCuritem, length*sizeof(WCHAR));
1294 wVal = wcschr(wCuritem, '=');
1297 if (SetEnvironmentVariableW(wCuritem, *wVal ? wVal : NULL))
1303 New(1309,curitem,strlen(name)+1,char);
1304 strcpy(curitem, name);
1305 val = strchr(curitem, '=');
1307 /* The sane way to deal with the environment.
1308 * Has these advantages over putenv() & co.:
1309 * * enables us to store a truly empty value in the
1310 * environment (like in UNIX).
1311 * * we don't have to deal with RTL globals, bugs and leaks.
1313 * Why you may want to enable USE_WIN32_RTL_ENV:
1314 * * environ[] and RTL functions will not reflect changes,
1315 * which might be an issue if extensions want to access
1316 * the env. via RTL. This cuts both ways, since RTL will
1317 * not see changes made by extensions that call the Win32
1318 * functions directly, either.
1322 if (SetEnvironmentVariableA(curitem, *val ? val : NULL))
1334 filetime_to_clock(PFILETIME ft)
1336 __int64 qw = ft->dwHighDateTime;
1338 qw |= ft->dwLowDateTime;
1339 qw /= 10000; /* File time ticks at 0.1uS, clock at 1mS */
1344 win32_times(struct tms *timebuf)
1349 if (GetProcessTimes(GetCurrentProcess(), &dummy, &dummy,
1351 timebuf->tms_utime = filetime_to_clock(&user);
1352 timebuf->tms_stime = filetime_to_clock(&kernel);
1353 timebuf->tms_cutime = 0;
1354 timebuf->tms_cstime = 0;
1357 /* That failed - e.g. Win95 fallback to clock() */
1358 clock_t t = clock();
1359 timebuf->tms_utime = t;
1360 timebuf->tms_stime = 0;
1361 timebuf->tms_cutime = 0;
1362 timebuf->tms_cstime = 0;
1367 /* fix utime() so it works on directories in NT */
1369 filetime_from_time(PFILETIME pFileTime, time_t Time)
1371 struct tm *pTM = localtime(&Time);
1372 SYSTEMTIME SystemTime;
1378 SystemTime.wYear = pTM->tm_year + 1900;
1379 SystemTime.wMonth = pTM->tm_mon + 1;
1380 SystemTime.wDay = pTM->tm_mday;
1381 SystemTime.wHour = pTM->tm_hour;
1382 SystemTime.wMinute = pTM->tm_min;
1383 SystemTime.wSecond = pTM->tm_sec;
1384 SystemTime.wMilliseconds = 0;
1386 return SystemTimeToFileTime(&SystemTime, &LocalTime) &&
1387 LocalFileTimeToFileTime(&LocalTime, pFileTime);
1391 win32_unlink(const char *filename)
1398 WCHAR wBuffer[MAX_PATH];
1400 A2WHELPER(filename, wBuffer, sizeof(wBuffer));
1401 wcscpy(wBuffer, PerlDir_mapW(wBuffer));
1402 attrs = GetFileAttributesW(wBuffer);
1403 if (attrs & FILE_ATTRIBUTE_READONLY) {
1404 (void)SetFileAttributesW(wBuffer, attrs & ~FILE_ATTRIBUTE_READONLY);
1405 ret = _wunlink(wBuffer);
1407 (void)SetFileAttributesW(wBuffer, attrs);
1410 ret = _wunlink(wBuffer);
1413 filename = PerlDir_mapA(filename);
1414 attrs = GetFileAttributesA(filename);
1415 if (attrs & FILE_ATTRIBUTE_READONLY) {
1416 (void)SetFileAttributesA(filename, attrs & ~FILE_ATTRIBUTE_READONLY);
1417 ret = unlink(filename);
1419 (void)SetFileAttributesA(filename, attrs);
1422 ret = unlink(filename);
1428 win32_utime(const char *filename, struct utimbuf *times)
1435 struct utimbuf TimeBuffer;
1436 WCHAR wbuffer[MAX_PATH];
1440 A2WHELPER(filename, wbuffer, sizeof(wbuffer));
1441 wcscpy(wbuffer, PerlDir_mapW(wbuffer));
1442 rc = _wutime(wbuffer, (struct _utimbuf*)times);
1445 filename = PerlDir_mapA(filename);
1446 rc = utime(filename, times);
1448 /* EACCES: path specifies directory or readonly file */
1449 if (rc == 0 || errno != EACCES /* || !IsWinNT() */)
1452 if (times == NULL) {
1453 times = &TimeBuffer;
1454 time(×->actime);
1455 times->modtime = times->actime;
1458 /* This will (and should) still fail on readonly files */
1460 handle = CreateFileW(wbuffer, GENERIC_READ | GENERIC_WRITE,
1461 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1462 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1465 handle = CreateFileA(filename, GENERIC_READ | GENERIC_WRITE,
1466 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1467 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1469 if (handle == INVALID_HANDLE_VALUE)
1472 if (GetFileTime(handle, &ftCreate, &ftAccess, &ftWrite) &&
1473 filetime_from_time(&ftAccess, times->actime) &&
1474 filetime_from_time(&ftWrite, times->modtime) &&
1475 SetFileTime(handle, &ftCreate, &ftAccess, &ftWrite))
1480 CloseHandle(handle);
1485 win32_uname(struct utsname *name)
1487 struct hostent *hep;
1488 STRLEN nodemax = sizeof(name->nodename)-1;
1489 OSVERSIONINFO osver;
1491 memset(&osver, 0, sizeof(OSVERSIONINFO));
1492 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1493 if (GetVersionEx(&osver)) {
1495 switch (osver.dwPlatformId) {
1496 case VER_PLATFORM_WIN32_WINDOWS:
1497 strcpy(name->sysname, "Windows");
1499 case VER_PLATFORM_WIN32_NT:
1500 strcpy(name->sysname, "Windows NT");
1502 case VER_PLATFORM_WIN32s:
1503 strcpy(name->sysname, "Win32s");
1506 strcpy(name->sysname, "Win32 Unknown");
1511 sprintf(name->release, "%d.%d",
1512 osver.dwMajorVersion, osver.dwMinorVersion);
1515 sprintf(name->version, "Build %d",
1516 osver.dwPlatformId == VER_PLATFORM_WIN32_NT
1517 ? osver.dwBuildNumber : (osver.dwBuildNumber & 0xffff));
1518 if (osver.szCSDVersion[0]) {
1519 char *buf = name->version + strlen(name->version);
1520 sprintf(buf, " (%s)", osver.szCSDVersion);
1524 *name->sysname = '\0';
1525 *name->version = '\0';
1526 *name->release = '\0';
1530 hep = win32_gethostbyname("localhost");
1532 STRLEN len = strlen(hep->h_name);
1533 if (len <= nodemax) {
1534 strcpy(name->nodename, hep->h_name);
1537 strncpy(name->nodename, hep->h_name, nodemax);
1538 name->nodename[nodemax] = '\0';
1543 if (!GetComputerName(name->nodename, &sz))
1544 *name->nodename = '\0';
1547 /* machine (architecture) */
1551 GetSystemInfo(&info);
1553 #if defined(__BORLANDC__) || defined(__MINGW32__)
1554 switch (info.u.s.wProcessorArchitecture) {
1556 switch (info.wProcessorArchitecture) {
1558 case PROCESSOR_ARCHITECTURE_INTEL:
1559 arch = "x86"; break;
1560 case PROCESSOR_ARCHITECTURE_MIPS:
1561 arch = "mips"; break;
1562 case PROCESSOR_ARCHITECTURE_ALPHA:
1563 arch = "alpha"; break;
1564 case PROCESSOR_ARCHITECTURE_PPC:
1565 arch = "ppc"; break;
1567 arch = "unknown"; break;
1569 strcpy(name->machine, arch);
1575 win32_waitpid(int pid, int *status, int flags)
1579 if (pid == -1) /* XXX threadid == 1 ? */
1580 return win32_wait(status);
1583 long child = find_pseudo_pid(-pid);
1585 HANDLE hThread = w32_pseudo_child_handles[child];
1586 DWORD waitcode = WaitForSingleObject(hThread, INFINITE);
1587 if (waitcode != WAIT_FAILED) {
1588 if (GetExitCodeThread(hThread, &waitcode)) {
1589 *status = (int)((waitcode & 0xff) << 8);
1590 retval = (int)w32_pseudo_child_pids[child];
1591 remove_dead_pseudo_process(child);
1601 long child = find_pid(pid);
1603 HANDLE hProcess = w32_child_handles[child];
1604 DWORD waitcode = WaitForSingleObject(hProcess, INFINITE);
1605 if (waitcode != WAIT_FAILED) {
1606 if (GetExitCodeProcess(hProcess, &waitcode)) {
1607 *status = (int)((waitcode & 0xff) << 8);
1608 retval = (int)w32_child_pids[child];
1609 remove_dead_process(child);
1617 retval = cwait(status, pid, WAIT_CHILD);
1618 /* cwait() returns "correctly" on Borland */
1619 #ifndef __BORLANDC__
1625 return retval >= 0 ? pid : retval;
1629 win32_wait(int *status)
1631 /* XXX this wait emulation only knows about processes
1632 * spawned via win32_spawnvp(P_NOWAIT, ...).
1636 DWORD exitcode, waitcode;
1639 if (w32_num_pseudo_children) {
1640 waitcode = WaitForMultipleObjects(w32_num_pseudo_children,
1641 w32_pseudo_child_handles,
1644 if (waitcode != WAIT_FAILED) {
1645 if (waitcode >= WAIT_ABANDONED_0
1646 && waitcode < WAIT_ABANDONED_0 + w32_num_pseudo_children)
1647 i = waitcode - WAIT_ABANDONED_0;
1649 i = waitcode - WAIT_OBJECT_0;
1650 if (GetExitCodeThread(w32_pseudo_child_handles[i], &exitcode)) {
1651 *status = (int)((exitcode & 0xff) << 8);
1652 retval = (int)w32_pseudo_child_pids[i];
1653 remove_dead_pseudo_process(i);
1660 if (!w32_num_children) {
1665 /* if a child exists, wait for it to die */
1666 waitcode = WaitForMultipleObjects(w32_num_children,
1670 if (waitcode != WAIT_FAILED) {
1671 if (waitcode >= WAIT_ABANDONED_0
1672 && waitcode < WAIT_ABANDONED_0 + w32_num_children)
1673 i = waitcode - WAIT_ABANDONED_0;
1675 i = waitcode - WAIT_OBJECT_0;
1676 if (GetExitCodeProcess(w32_child_handles[i], &exitcode) ) {
1677 *status = (int)((exitcode & 0xff) << 8);
1678 retval = (int)w32_child_pids[i];
1679 remove_dead_process(i);
1685 errno = GetLastError();
1689 static UINT timerid = 0;
1691 static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
1694 KillTimer(NULL,timerid);
1699 DllExport unsigned int
1700 win32_alarm(unsigned int sec)
1703 * the 'obvious' implentation is SetTimer() with a callback
1704 * which does whatever receiving SIGALRM would do
1705 * we cannot use SIGALRM even via raise() as it is not
1706 * one of the supported codes in <signal.h>
1708 * Snag is unless something is looking at the message queue
1709 * nothing happens :-(
1714 timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
1716 Perl_croak_nocontext("Cannot set timer");
1722 KillTimer(NULL,timerid);
1729 #ifdef HAVE_DES_FCRYPT
1730 extern char * des_fcrypt(const char *txt, const char *salt, char *cbuf);
1734 win32_crypt(const char *txt, const char *salt)
1737 #ifdef HAVE_DES_FCRYPT
1739 return des_fcrypt(txt, salt, w32_crypt_buffer);
1741 Perl_croak(aTHX_ "The crypt() function is unimplemented due to excessive paranoia.");
1746 #ifdef USE_FIXED_OSFHANDLE
1748 EXTERN_C int __cdecl _alloc_osfhnd(void);
1749 EXTERN_C int __cdecl _set_osfhnd(int fh, long value);
1750 EXTERN_C void __cdecl _lock_fhandle(int);
1751 EXTERN_C void __cdecl _unlock_fhandle(int);
1752 EXTERN_C void __cdecl _unlock(int);
1754 #if (_MSC_VER >= 1000)
1756 long osfhnd; /* underlying OS file HANDLE */
1757 char osfile; /* attributes of file (e.g., open in text mode?) */
1758 char pipech; /* one char buffer for handles opened on pipes */
1759 #if defined (_MT) && !defined (DLL_FOR_WIN32S)
1761 CRITICAL_SECTION lock;
1762 #endif /* defined (_MT) && !defined (DLL_FOR_WIN32S) */
1765 EXTERN_C ioinfo * __pioinfo[];
1767 #define IOINFO_L2E 5
1768 #define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
1769 #define _pioinfo(i) (__pioinfo[i >> IOINFO_L2E] + (i & (IOINFO_ARRAY_ELTS - 1)))
1770 #define _osfile(i) (_pioinfo(i)->osfile)
1772 #else /* (_MSC_VER >= 1000) */
1773 extern char _osfile[];
1774 #endif /* (_MSC_VER >= 1000) */
1776 #define FOPEN 0x01 /* file handle open */
1777 #define FAPPEND 0x20 /* file handle opened O_APPEND */
1778 #define FDEV 0x40 /* file handle refers to device */
1779 #define FTEXT 0x80 /* file handle is in text mode */
1781 #define _STREAM_LOCKS 26 /* Table of stream locks */
1782 #define _LAST_STREAM_LOCK (_STREAM_LOCKS+_NSTREAM_-1) /* Last stream lock */
1783 #define _FH_LOCKS (_LAST_STREAM_LOCK+1) /* Table of fh locks */
1786 *int my_open_osfhandle(long osfhandle, int flags) - open C Runtime file handle
1789 * This function allocates a free C Runtime file handle and associates
1790 * it with the Win32 HANDLE specified by the first parameter. This is a
1791 * temperary fix for WIN95's brain damage GetFileType() error on socket
1792 * we just bypass that call for socket
1795 * long osfhandle - Win32 HANDLE to associate with C Runtime file handle.
1796 * int flags - flags to associate with C Runtime file handle.
1799 * returns index of entry in fh, if successful
1800 * return -1, if no free entry is found
1804 *******************************************************************************/
1807 my_open_osfhandle(long osfhandle, int flags)
1810 char fileflags; /* _osfile flags */
1812 /* copy relevant flags from second parameter */
1815 if (flags & O_APPEND)
1816 fileflags |= FAPPEND;
1821 /* attempt to allocate a C Runtime file handle */
1822 if ((fh = _alloc_osfhnd()) == -1) {
1823 errno = EMFILE; /* too many open files */
1824 _doserrno = 0L; /* not an OS error */
1825 return -1; /* return error to caller */
1828 /* the file is open. now, set the info in _osfhnd array */
1829 _set_osfhnd(fh, osfhandle);
1831 fileflags |= FOPEN; /* mark as open */
1833 #if (_MSC_VER >= 1000)
1834 _osfile(fh) = fileflags; /* set osfile entry */
1835 _unlock_fhandle(fh);
1837 _osfile[fh] = fileflags; /* set osfile entry */
1838 _unlock(fh+_FH_LOCKS); /* unlock handle */
1841 return fh; /* return handle */
1844 #define _open_osfhandle my_open_osfhandle
1845 #endif /* USE_FIXED_OSFHANDLE */
1847 /* simulate flock by locking a range on the file */
1849 #define LK_ERR(f,i) ((f) ? (i = 0) : (errno = GetLastError()))
1850 #define LK_LEN 0xffff0000
1853 win32_flock(int fd, int oper)
1861 Perl_croak_nocontext("flock() unimplemented on this platform");
1864 fh = (HANDLE)_get_osfhandle(fd);
1865 memset(&o, 0, sizeof(o));
1868 case LOCK_SH: /* shared lock */
1869 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
1871 case LOCK_EX: /* exclusive lock */
1872 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
1874 case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
1875 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
1877 case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
1878 LK_ERR(LockFileEx(fh,
1879 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
1880 0, LK_LEN, 0, &o),i);
1882 case LOCK_UN: /* unlock lock */
1883 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, 0, &o),i);
1885 default: /* unknown */
1896 * redirected io subsystem for all XS modules
1909 return (&(_environ));
1912 /* the rest are the remapped stdio routines */
1932 win32_ferror(FILE *fp)
1934 return (ferror(fp));
1939 win32_feof(FILE *fp)
1945 * Since the errors returned by the socket error function
1946 * WSAGetLastError() are not known by the library routine strerror
1947 * we have to roll our own.
1951 win32_strerror(int e)
1953 #ifndef __BORLANDC__ /* Borland intolerance */
1954 extern int sys_nerr;
1958 if (e < 0 || e > sys_nerr) {
1963 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
1964 w32_strerror_buffer,
1965 sizeof(w32_strerror_buffer), NULL) == 0)
1966 strcpy(w32_strerror_buffer, "Unknown Error");
1968 return w32_strerror_buffer;
1974 win32_str_os_error(void *sv, DWORD dwErr)
1978 dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
1979 |FORMAT_MESSAGE_IGNORE_INSERTS
1980 |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
1981 dwErr, 0, (char *)&sMsg, 1, NULL);
1982 /* strip trailing whitespace and period */
1985 --dwLen; /* dwLen doesn't include trailing null */
1986 } while (0 < dwLen && isSPACE(sMsg[dwLen]));
1987 if ('.' != sMsg[dwLen])
1992 sMsg = (char*)LocalAlloc(0, 64/**sizeof(TCHAR)*/);
1994 dwLen = sprintf(sMsg,
1995 "Unknown error #0x%lX (lookup 0x%lX)",
1996 dwErr, GetLastError());
2000 sv_setpvn((SV*)sv, sMsg, dwLen);
2007 win32_fprintf(FILE *fp, const char *format, ...)
2010 va_start(marker, format); /* Initialize variable arguments. */
2012 return (vfprintf(fp, format, marker));
2016 win32_printf(const char *format, ...)
2019 va_start(marker, format); /* Initialize variable arguments. */
2021 return (vprintf(format, marker));
2025 win32_vfprintf(FILE *fp, const char *format, va_list args)
2027 return (vfprintf(fp, format, args));
2031 win32_vprintf(const char *format, va_list args)
2033 return (vprintf(format, args));
2037 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
2039 return fread(buf, size, count, fp);
2043 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
2045 return fwrite(buf, size, count, fp);
2048 #define MODE_SIZE 10
2051 win32_fopen(const char *filename, const char *mode)
2054 WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH];
2059 if (stricmp(filename, "/dev/null")==0)
2063 A2WHELPER(mode, wMode, sizeof(wMode));
2064 A2WHELPER(filename, wBuffer, sizeof(wBuffer));
2065 return _wfopen(PerlDir_mapW(wBuffer), wMode);
2067 return fopen(PerlDir_mapA(filename), mode);
2070 #ifndef USE_SOCKETS_AS_HANDLES
2072 #define fdopen my_fdopen
2076 win32_fdopen(int handle, const char *mode)
2079 WCHAR wMode[MODE_SIZE];
2081 A2WHELPER(mode, wMode, sizeof(wMode));
2082 return _wfdopen(handle, wMode);
2084 return fdopen(handle, (char *) mode);
2088 win32_freopen(const char *path, const char *mode, FILE *stream)
2091 WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH];
2092 if (stricmp(path, "/dev/null")==0)
2096 A2WHELPER(mode, wMode, sizeof(wMode));
2097 A2WHELPER(path, wBuffer, sizeof(wBuffer));
2098 return _wfreopen(PerlDir_mapW(wBuffer), wMode, stream);
2100 return freopen(PerlDir_mapA(path), mode, stream);
2104 win32_fclose(FILE *pf)
2106 return my_fclose(pf); /* defined in win32sck.c */
2110 win32_fputs(const char *s,FILE *pf)
2112 return fputs(s, pf);
2116 win32_fputc(int c,FILE *pf)
2122 win32_ungetc(int c,FILE *pf)
2124 return ungetc(c,pf);
2128 win32_getc(FILE *pf)
2134 win32_fileno(FILE *pf)
2140 win32_clearerr(FILE *pf)
2147 win32_fflush(FILE *pf)
2153 win32_ftell(FILE *pf)
2159 win32_fseek(FILE *pf,long offset,int origin)
2161 return fseek(pf, offset, origin);
2165 win32_fgetpos(FILE *pf,fpos_t *p)
2167 return fgetpos(pf, p);
2171 win32_fsetpos(FILE *pf,const fpos_t *p)
2173 return fsetpos(pf, p);
2177 win32_rewind(FILE *pf)
2197 win32_fstat(int fd,struct stat *sbufptr)
2199 return fstat(fd,sbufptr);
2203 win32_pipe(int *pfd, unsigned int size, int mode)
2205 return _pipe(pfd, size, mode);
2209 * a popen() clone that respects PERL5SHELL
2213 win32_popen(const char *command, const char *mode)
2215 #ifdef USE_RTL_POPEN
2216 return _popen(command, mode);
2224 /* establish which ends read and write */
2225 if (strchr(mode,'w')) {
2226 stdfd = 0; /* stdin */
2230 else if (strchr(mode,'r')) {
2231 stdfd = 1; /* stdout */
2238 /* set the correct mode */
2239 if (strchr(mode,'b'))
2241 else if (strchr(mode,'t'))
2244 ourmode = _fmode & (O_TEXT | O_BINARY);
2246 /* the child doesn't inherit handles */
2247 ourmode |= O_NOINHERIT;
2249 if (win32_pipe( p, 512, ourmode) == -1)
2252 /* save current stdfd */
2253 if ((oldfd = win32_dup(stdfd)) == -1)
2256 /* make stdfd go to child end of pipe (implicitly closes stdfd) */
2257 /* stdfd will be inherited by the child */
2258 if (win32_dup2(p[child], stdfd) == -1)
2261 /* close the child end in parent */
2262 win32_close(p[child]);
2264 /* start the child */
2267 if ((childpid = do_spawn_nowait((char*)command)) == -1)
2270 /* revert stdfd to whatever it was before */
2271 if (win32_dup2(oldfd, stdfd) == -1)
2274 /* close saved handle */
2277 sv_setiv(*av_fetch(w32_fdpid, p[parent], TRUE), childpid);
2279 /* set process id so that it can be returned by perl's open() */
2280 PL_forkprocess = childpid;
2283 /* we have an fd, return a file stream */
2284 return (win32_fdopen(p[parent], (char *)mode));
2287 /* we don't need to check for errors here */
2291 win32_dup2(oldfd, stdfd);
2296 #endif /* USE_RTL_POPEN */
2304 win32_pclose(FILE *pf)
2306 #ifdef USE_RTL_POPEN
2310 int childpid, status;
2313 sv = *av_fetch(w32_fdpid, win32_fileno(pf), TRUE);
2315 childpid = SvIVX(sv);
2327 if (win32_waitpid(childpid, &status, 0) == -1)
2332 #endif /* USE_RTL_POPEN */
2338 LPCWSTR lpExistingFileName,
2339 LPSECURITY_ATTRIBUTES lpSecurityAttributes)
2342 WCHAR wFullName[MAX_PATH+1];
2343 LPVOID lpContext = NULL;
2344 WIN32_STREAM_ID StreamId;
2345 DWORD dwSize = (char*)&StreamId.cStreamName - (char*)&StreamId;
2350 BOOL (__stdcall *pfnBackupWrite)(HANDLE, LPBYTE, DWORD, LPDWORD,
2351 BOOL, BOOL, LPVOID*) =
2352 (BOOL (__stdcall *)(HANDLE, LPBYTE, DWORD, LPDWORD,
2353 BOOL, BOOL, LPVOID*))
2354 GetProcAddress(GetModuleHandle("kernel32.dll"), "BackupWrite");
2355 if (pfnBackupWrite == NULL)
2358 dwLen = GetFullPathNameW(lpFileName, MAX_PATH, wFullName, NULL);
2361 dwLen = (dwLen+1)*sizeof(WCHAR);
2363 handle = CreateFileW(lpExistingFileName, FILE_WRITE_ATTRIBUTES,
2364 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
2365 NULL, OPEN_EXISTING, 0, NULL);
2366 if (handle == INVALID_HANDLE_VALUE)
2369 StreamId.dwStreamId = BACKUP_LINK;
2370 StreamId.dwStreamAttributes = 0;
2371 StreamId.dwStreamNameSize = 0;
2372 StreamId.Size.HighPart = 0;
2373 StreamId.Size.LowPart = dwLen;
2375 bSuccess = pfnBackupWrite(handle, (LPBYTE)&StreamId, dwSize, &dwWritten,
2376 FALSE, FALSE, &lpContext);
2378 bSuccess = pfnBackupWrite(handle, (LPBYTE)wFullName, dwLen, &dwWritten,
2379 FALSE, FALSE, &lpContext);
2380 pfnBackupWrite(handle, NULL, 0, &dwWritten, TRUE, FALSE, &lpContext);
2383 CloseHandle(handle);
2388 win32_link(const char *oldname, const char *newname)
2391 BOOL (__stdcall *pfnCreateHardLinkW)(LPCWSTR,LPCWSTR,LPSECURITY_ATTRIBUTES);
2392 WCHAR wOldName[MAX_PATH];
2393 WCHAR wNewName[MAX_PATH];
2396 Perl_die(aTHX_ PL_no_func, "link");
2398 pfnCreateHardLinkW =
2399 (BOOL (__stdcall *)(LPCWSTR, LPCWSTR, LPSECURITY_ATTRIBUTES))
2400 GetProcAddress(GetModuleHandle("kernel32.dll"), "CreateHardLinkW");
2401 if (pfnCreateHardLinkW == NULL)
2402 pfnCreateHardLinkW = Nt4CreateHardLinkW;
2404 if ((A2WHELPER(oldname, wOldName, sizeof(wOldName))) &&
2405 (A2WHELPER(newname, wNewName, sizeof(wNewName))) &&
2406 (wcscpy(wOldName, PerlDir_mapW(wOldName)),
2407 pfnCreateHardLinkW(PerlDir_mapW(wNewName), wOldName, NULL)))
2411 errno = (GetLastError() == ERROR_FILE_NOT_FOUND) ? ENOENT : EINVAL;
2416 win32_rename(const char *oname, const char *newname)
2418 WCHAR wOldName[MAX_PATH];
2419 WCHAR wNewName[MAX_PATH];
2420 char szOldName[MAX_PATH];
2422 /* XXX despite what the documentation says about MoveFileEx(),
2423 * it doesn't work under Windows95!
2428 A2WHELPER(oname, wOldName, sizeof(wOldName));
2429 A2WHELPER(newname, wNewName, sizeof(wNewName));
2430 wcscpy(wOldName, PerlDir_mapW(wOldName));
2431 bResult = MoveFileExW(wOldName,PerlDir_mapW(wNewName),
2432 MOVEFILE_COPY_ALLOWED|MOVEFILE_REPLACE_EXISTING);
2435 strcpy(szOldName, PerlDir_mapA(szOldName));
2436 bResult = MoveFileExA(szOldName,PerlDir_mapA(newname),
2437 MOVEFILE_COPY_ALLOWED|MOVEFILE_REPLACE_EXISTING);
2440 DWORD err = GetLastError();
2442 case ERROR_BAD_NET_NAME:
2443 case ERROR_BAD_NETPATH:
2444 case ERROR_BAD_PATHNAME:
2445 case ERROR_FILE_NOT_FOUND:
2446 case ERROR_FILENAME_EXCED_RANGE:
2447 case ERROR_INVALID_DRIVE:
2448 case ERROR_NO_MORE_FILES:
2449 case ERROR_PATH_NOT_FOUND:
2462 char tmpname[MAX_PATH+1];
2463 char dname[MAX_PATH+1];
2464 char *endname = Nullch;
2466 DWORD from_attr, to_attr;
2468 /* if oname doesn't exist, do nothing */
2469 from_attr = GetFileAttributes(oname);
2470 if (from_attr == 0xFFFFFFFF) {
2475 /* if newname exists, rename it to a temporary name so that we
2476 * don't delete it in case oname happens to be the same file
2477 * (but perhaps accessed via a different path)
2479 to_attr = GetFileAttributes(newname);
2480 if (to_attr != 0xFFFFFFFF) {
2481 /* if newname is a directory, we fail
2482 * XXX could overcome this with yet more convoluted logic */
2483 if (to_attr & FILE_ATTRIBUTE_DIRECTORY) {
2487 tmplen = strlen(newname);
2488 strcpy(tmpname,newname);
2489 endname = tmpname+tmplen;
2490 for (; endname > tmpname ; --endname) {
2491 if (*endname == '/' || *endname == '\\') {
2496 if (endname > tmpname)
2497 endname = strcpy(dname,tmpname);
2501 /* get a temporary filename in same directory
2502 * XXX is this really the best we can do? */
2503 if (!GetTempFileName((LPCTSTR)endname, "plr", 0, tmpname)) {
2507 DeleteFile(tmpname);
2509 retval = rename(newname, tmpname);
2516 /* rename oname to newname */
2517 retval = rename(oname, newname);
2519 /* if we created a temporary file before ... */
2520 if (endname != Nullch) {
2521 /* ...and rename succeeded, delete temporary file/directory */
2523 DeleteFile(tmpname);
2524 /* else restore it to what it was */
2526 (void)rename(tmpname, newname);
2533 win32_setmode(int fd, int mode)
2535 return setmode(fd, mode);
2539 win32_lseek(int fd, long offset, int origin)
2541 return lseek(fd, offset, origin);
2551 win32_open(const char *path, int flag, ...)
2556 WCHAR wBuffer[MAX_PATH];
2559 pmode = va_arg(ap, int);
2562 if (stricmp(path, "/dev/null")==0)
2566 A2WHELPER(path, wBuffer, sizeof(wBuffer));
2567 return _wopen(PerlDir_mapW(wBuffer), flag, pmode);
2569 return open(PerlDir_mapA(path), flag, pmode);
2591 win32_dup2(int fd1,int fd2)
2593 return dup2(fd1,fd2);
2597 win32_read(int fd, void *buf, unsigned int cnt)
2599 return read(fd, buf, cnt);
2603 win32_write(int fd, const void *buf, unsigned int cnt)
2605 return write(fd, buf, cnt);
2609 win32_mkdir(const char *dir, int mode)
2613 WCHAR wBuffer[MAX_PATH];
2614 A2WHELPER(dir, wBuffer, sizeof(wBuffer));
2615 return _wmkdir(PerlDir_mapW(wBuffer));
2617 return mkdir(PerlDir_mapA(dir)); /* just ignore mode */
2621 win32_rmdir(const char *dir)
2625 WCHAR wBuffer[MAX_PATH];
2626 A2WHELPER(dir, wBuffer, sizeof(wBuffer));
2627 return _wrmdir(PerlDir_mapW(wBuffer));
2629 return rmdir(PerlDir_mapA(dir));
2633 win32_chdir(const char *dir)
2637 WCHAR wBuffer[MAX_PATH];
2638 A2WHELPER(dir, wBuffer, sizeof(wBuffer));
2639 return _wchdir(wBuffer);
2645 win32_access(const char *path, int mode)
2649 WCHAR wBuffer[MAX_PATH];
2650 A2WHELPER(path, wBuffer, sizeof(wBuffer));
2651 return _waccess(PerlDir_mapW(wBuffer), mode);
2653 return access(PerlDir_mapA(path), mode);
2657 win32_chmod(const char *path, int mode)
2661 WCHAR wBuffer[MAX_PATH];
2662 A2WHELPER(path, wBuffer, sizeof(wBuffer));
2663 return _wchmod(PerlDir_mapW(wBuffer), mode);
2665 return chmod(PerlDir_mapA(path), mode);
2670 create_command_line(const char* command, const char * const *args)
2674 char *cmd, *ptr, *arg;
2675 STRLEN len = strlen(command) + 1;
2677 for (index = 0; (ptr = (char*)args[index]) != NULL; ++index)
2678 len += strlen(ptr) + 1;
2680 New(1310, cmd, len, char);
2682 strcpy(ptr, command);
2684 for (index = 0; (arg = (char*)args[index]) != NULL; ++index) {
2694 qualified_path(const char *cmd)
2698 char *fullcmd, *curfullcmd;
2704 fullcmd = (char*)cmd;
2706 if (*fullcmd == '/' || *fullcmd == '\\')
2713 pathstr = win32_getenv("PATH");
2714 New(0, fullcmd, MAX_PATH+1, char);
2715 curfullcmd = fullcmd;
2720 /* start by appending the name to the current prefix */
2721 strcpy(curfullcmd, cmd);
2722 curfullcmd += cmdlen;
2724 /* if it doesn't end with '.', or has no extension, try adding
2725 * a trailing .exe first */
2726 if (cmd[cmdlen-1] != '.'
2727 && (cmdlen < 4 || cmd[cmdlen-4] != '.'))
2729 strcpy(curfullcmd, ".exe");
2730 res = GetFileAttributes(fullcmd);
2731 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
2736 /* that failed, try the bare name */
2737 res = GetFileAttributes(fullcmd);
2738 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
2741 /* quit if no other path exists, or if cmd already has path */
2742 if (!pathstr || !*pathstr || has_slash)
2745 /* skip leading semis */
2746 while (*pathstr == ';')
2749 /* build a new prefix from scratch */
2750 curfullcmd = fullcmd;
2751 while (*pathstr && *pathstr != ';') {
2752 if (*pathstr == '"') { /* foo;"baz;etc";bar */
2753 pathstr++; /* skip initial '"' */
2754 while (*pathstr && *pathstr != '"') {
2755 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
2756 *curfullcmd++ = *pathstr;
2760 pathstr++; /* skip trailing '"' */
2763 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
2764 *curfullcmd++ = *pathstr;
2769 pathstr++; /* skip trailing semi */
2770 if (curfullcmd > fullcmd /* append a dir separator */
2771 && curfullcmd[-1] != '/' && curfullcmd[-1] != '\\')
2773 *curfullcmd++ = '\\';
2781 /* The following are just place holders.
2782 * Some hosts may provide and environment that the OS is
2783 * not tracking, therefore, these host must provide that
2784 * environment and the current directory to CreateProcess
2794 free_childenv(void* d)
2803 char szfilename[(MAX_PATH+1)*2];
2805 WCHAR wfilename[MAX_PATH+1];
2806 GetCurrentDirectoryW(MAX_PATH+1, wfilename);
2807 W2AHELPER(wfilename, szfilename, sizeof(szfilename));
2810 GetCurrentDirectoryA(MAX_PATH+1, szfilename);
2813 New(0, ptr, strlen(szfilename)+1, char);
2814 strcpy(ptr, szfilename);
2819 free_childdir(char* d)
2826 /* XXX this needs to be made more compatible with the spawnvp()
2827 * provided by the various RTLs. In particular, searching for
2828 * *.{com,bat,cmd} files (as done by the RTLs) is unimplemented.
2829 * This doesn't significantly affect perl itself, because we
2830 * always invoke things using PERL5SHELL if a direct attempt to
2831 * spawn the executable fails.
2833 * XXX splitting and rejoining the commandline between do_aspawn()
2834 * and win32_spawnvp() could also be avoided.
2838 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
2840 #ifdef USE_RTL_SPAWNVP
2841 return spawnvp(mode, cmdname, (char * const *)argv);
2847 STARTUPINFO StartupInfo;
2848 PROCESS_INFORMATION ProcessInformation;
2851 char *cmd = create_command_line(cmdname, strcmp(cmdname, argv[0]) == 0
2853 char *fullcmd = Nullch;
2855 env = PerlEnv_get_childenv();
2856 dir = PerlEnv_get_childdir();
2859 case P_NOWAIT: /* asynch + remember result */
2860 if (w32_num_children >= MAXIMUM_WAIT_OBJECTS) {
2866 case P_WAIT: /* synchronous execution */
2868 default: /* invalid mode */
2873 memset(&StartupInfo,0,sizeof(StartupInfo));
2874 StartupInfo.cb = sizeof(StartupInfo);
2875 StartupInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
2876 StartupInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
2877 StartupInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
2878 if (StartupInfo.hStdInput != INVALID_HANDLE_VALUE &&
2879 StartupInfo.hStdOutput != INVALID_HANDLE_VALUE &&
2880 StartupInfo.hStdError != INVALID_HANDLE_VALUE)
2882 StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
2885 create |= CREATE_NEW_CONSOLE;
2889 if (!CreateProcess(cmdname, /* search PATH to find executable */
2890 cmd, /* executable, and its arguments */
2891 NULL, /* process attributes */
2892 NULL, /* thread attributes */
2893 TRUE, /* inherit handles */
2894 create, /* creation flags */
2895 (LPVOID)env, /* inherit environment */
2896 dir, /* inherit cwd */
2898 &ProcessInformation))
2900 /* initial NULL argument to CreateProcess() does a PATH
2901 * search, but it always first looks in the directory
2902 * where the current process was started, which behavior
2903 * is undesirable for backward compatibility. So we
2904 * jump through our own hoops by picking out the path
2905 * we really want it to use. */
2907 fullcmd = qualified_path(cmdname);
2918 if (mode == P_NOWAIT) {
2919 /* asynchronous spawn -- store handle, return PID */
2920 w32_child_handles[w32_num_children] = ProcessInformation.hProcess;
2921 w32_child_pids[w32_num_children] = ProcessInformation.dwProcessId;
2922 ret = (int)ProcessInformation.dwProcessId;
2927 WaitForSingleObject(ProcessInformation.hProcess, INFINITE);
2928 GetExitCodeProcess(ProcessInformation.hProcess, &status);
2930 CloseHandle(ProcessInformation.hProcess);
2933 CloseHandle(ProcessInformation.hThread);
2936 PerlEnv_free_childenv(env);
2937 PerlEnv_free_childdir(dir);
2945 win32_execv(const char *cmdname, const char *const *argv)
2949 /* if this is a pseudo-forked child, we just want to spawn
2950 * the new program, and return */
2952 return spawnv(P_WAIT, cmdname, (char *const *)argv);
2954 return execv(cmdname, (char *const *)argv);
2958 win32_execvp(const char *cmdname, const char *const *argv)
2962 /* if this is a pseudo-forked child, we just want to spawn
2963 * the new program, and return */
2965 return win32_spawnvp(P_WAIT, cmdname, (char *const *)argv);
2967 return execvp(cmdname, (char *const *)argv);
2971 win32_perror(const char *str)
2977 win32_setbuf(FILE *pf, char *buf)
2983 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
2985 return setvbuf(pf, buf, type, size);
2989 win32_flushall(void)
2995 win32_fcloseall(void)
3001 win32_fgets(char *s, int n, FILE *pf)
3003 return fgets(s, n, pf);
3013 win32_fgetc(FILE *pf)
3019 win32_putc(int c, FILE *pf)
3025 win32_puts(const char *s)
3037 win32_putchar(int c)
3044 #ifndef USE_PERL_SBRK
3046 static char *committed = NULL;
3047 static char *base = NULL;
3048 static char *reserved = NULL;
3049 static char *brk = NULL;
3050 static DWORD pagesize = 0;
3051 static DWORD allocsize = 0;
3059 GetSystemInfo(&info);
3060 /* Pretend page size is larger so we don't perpetually
3061 * call the OS to commit just one page ...
3063 pagesize = info.dwPageSize << 3;
3064 allocsize = info.dwAllocationGranularity;
3066 /* This scheme fails eventually if request for contiguous
3067 * block is denied so reserve big blocks - this is only
3068 * address space not memory ...
3070 if (brk+need >= reserved)
3072 DWORD size = 64*1024*1024;
3074 if (committed && reserved && committed < reserved)
3076 /* Commit last of previous chunk cannot span allocations */
3077 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
3079 committed = reserved;
3081 /* Reserve some (more) space
3082 * Note this is a little sneaky, 1st call passes NULL as reserved
3083 * so lets system choose where we start, subsequent calls pass
3084 * the old end address so ask for a contiguous block
3086 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
3089 reserved = addr+size;
3104 if (brk > committed)
3106 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
3107 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
3122 win32_malloc(size_t size)
3124 return malloc(size);
3128 win32_calloc(size_t numitems, size_t size)
3130 return calloc(numitems,size);
3134 win32_realloc(void *block, size_t size)
3136 return realloc(block,size);
3140 win32_free(void *block)
3147 win32_open_osfhandle(long handle, int flags)
3149 return _open_osfhandle(handle, flags);
3153 win32_get_osfhandle(int fd)
3155 return _get_osfhandle(fd);
3159 win32_dynaload(const char* filename)
3164 WCHAR wfilename[MAX_PATH];
3165 A2WHELPER(filename, wfilename, sizeof(wfilename));
3166 hModule = LoadLibraryExW(PerlDir_mapW(wfilename), NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
3169 hModule = LoadLibraryExA(PerlDir_mapA(filename), NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
3182 /* Make the host for current directory */
3183 char* ptr = PerlEnv_get_childdir();
3186 * then it worked, set PV valid,
3187 * else return 'undef'
3190 SV *sv = sv_newmortal();
3192 PerlEnv_free_childdir(ptr);
3207 Perl_croak(aTHX_ "usage: Win32::SetCurrentDirectory($cwd)");
3208 if (!PerlDir_chdir(SvPV_nolen(ST(0))))
3215 XS(w32_GetNextAvailDrive)
3219 char root[] = "_:\\";
3224 if (GetDriveType(root) == 1) {
3233 XS(w32_GetLastError)
3237 XSRETURN_IV(GetLastError());
3241 XS(w32_SetLastError)
3245 Perl_croak(aTHX_ "usage: Win32::SetLastError($error)");
3246 SetLastError(SvIV(ST(0)));
3254 char *name = w32_getlogin_buffer;
3255 DWORD size = sizeof(w32_getlogin_buffer);
3257 if (GetUserName(name,&size)) {
3258 /* size includes NULL */
3259 ST(0) = sv_2mortal(newSVpvn(name,size-1));
3269 char name[MAX_COMPUTERNAME_LENGTH+1];
3270 DWORD size = sizeof(name);
3272 if (GetComputerName(name,&size)) {
3273 /* size does NOT include NULL :-( */
3274 ST(0) = sv_2mortal(newSVpvn(name,size));
3285 HINSTANCE hNetApi32 = LoadLibrary("netapi32.dll");
3286 DWORD (__stdcall *pfnNetApiBufferFree)(LPVOID Buffer);
3287 DWORD (__stdcall *pfnNetWkstaGetInfo)(LPWSTR servername, DWORD level,
3291 pfnNetApiBufferFree = (DWORD (__stdcall *)(void *))
3292 GetProcAddress(hNetApi32, "NetApiBufferFree");
3293 pfnNetWkstaGetInfo = (DWORD (__stdcall *)(LPWSTR, DWORD, void *))
3294 GetProcAddress(hNetApi32, "NetWkstaGetInfo");
3297 if (hNetApi32 && pfnNetWkstaGetInfo && pfnNetApiBufferFree) {
3298 /* this way is more reliable, in case user has a local account. */
3300 DWORD dnamelen = sizeof(dname);
3302 DWORD wki100_platform_id;
3303 LPWSTR wki100_computername;
3304 LPWSTR wki100_langroup;
3305 DWORD wki100_ver_major;
3306 DWORD wki100_ver_minor;
3308 /* NERR_Success *is* 0*/
3309 if (0 == pfnNetWkstaGetInfo(NULL, 100, &pwi)) {
3310 if (pwi->wki100_langroup && *(pwi->wki100_langroup)) {
3311 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_langroup,
3312 -1, (LPSTR)dname, dnamelen, NULL, NULL);
3315 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_computername,
3316 -1, (LPSTR)dname, dnamelen, NULL, NULL);
3318 pfnNetApiBufferFree(pwi);
3319 FreeLibrary(hNetApi32);
3322 FreeLibrary(hNetApi32);
3325 /* Win95 doesn't have NetWksta*(), so do it the old way */
3327 DWORD size = sizeof(name);
3329 FreeLibrary(hNetApi32);
3330 if (GetUserName(name,&size)) {
3331 char sid[ONE_K_BUFSIZE];
3332 DWORD sidlen = sizeof(sid);
3334 DWORD dnamelen = sizeof(dname);
3336 if (LookupAccountName(NULL, name, (PSID)&sid, &sidlen,
3337 dname, &dnamelen, &snu)) {
3338 XSRETURN_PV(dname); /* all that for this */
3350 DWORD flags, filecomplen;
3351 if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
3352 &flags, fsname, sizeof(fsname))) {
3353 if (GIMME_V == G_ARRAY) {
3354 XPUSHs(sv_2mortal(newSVpvn(fsname,strlen(fsname))));
3355 XPUSHs(sv_2mortal(newSViv(flags)));
3356 XPUSHs(sv_2mortal(newSViv(filecomplen)));
3361 XSRETURN_PV(fsname);
3367 XS(w32_GetOSVersion)
3370 OSVERSIONINFOA osver;
3373 OSVERSIONINFOW osverw;
3374 char szCSDVersion[sizeof(osverw.szCSDVersion)];
3375 osverw.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
3376 if (!GetVersionExW(&osverw)) {
3379 W2AHELPER(osverw.szCSDVersion, szCSDVersion, sizeof(szCSDVersion));
3380 XPUSHs(newSVpvn(szCSDVersion, strlen(szCSDVersion)));
3381 osver.dwMajorVersion = osverw.dwMajorVersion;
3382 osver.dwMinorVersion = osverw.dwMinorVersion;
3383 osver.dwBuildNumber = osverw.dwBuildNumber;
3384 osver.dwPlatformId = osverw.dwPlatformId;
3387 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOA);
3388 if (!GetVersionExA(&osver)) {
3391 XPUSHs(newSVpvn(osver.szCSDVersion, strlen(osver.szCSDVersion)));
3393 XPUSHs(newSViv(osver.dwMajorVersion));
3394 XPUSHs(newSViv(osver.dwMinorVersion));
3395 XPUSHs(newSViv(osver.dwBuildNumber));
3396 XPUSHs(newSViv(osver.dwPlatformId));
3405 XSRETURN_IV(IsWinNT());
3413 XSRETURN_IV(IsWin95());
3417 XS(w32_FormatMessage)
3421 char msgbuf[ONE_K_BUFSIZE];
3424 Perl_croak(aTHX_ "usage: Win32::FormatMessage($errno)");
3427 WCHAR wmsgbuf[ONE_K_BUFSIZE];
3428 if (FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM,
3429 &source, SvIV(ST(0)), 0,
3430 wmsgbuf, ONE_K_BUFSIZE-1, NULL))
3432 W2AHELPER(wmsgbuf, msgbuf, sizeof(msgbuf));
3433 XSRETURN_PV(msgbuf);
3437 if (FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM,
3438 &source, SvIV(ST(0)), 0,
3439 msgbuf, sizeof(msgbuf)-1, NULL))
3440 XSRETURN_PV(msgbuf);
3451 PROCESS_INFORMATION stProcInfo;
3452 STARTUPINFO stStartInfo;
3453 BOOL bSuccess = FALSE;
3456 Perl_croak(aTHX_ "usage: Win32::Spawn($cmdName, $args, $PID)");
3458 cmd = SvPV_nolen(ST(0));
3459 args = SvPV_nolen(ST(1));
3461 memset(&stStartInfo, 0, sizeof(stStartInfo)); /* Clear the block */
3462 stStartInfo.cb = sizeof(stStartInfo); /* Set the structure size */
3463 stStartInfo.dwFlags = STARTF_USESHOWWINDOW; /* Enable wShowWindow control */
3464 stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE; /* Start min (normal) */
3467 cmd, /* Image path */
3468 args, /* Arguments for command line */
3469 NULL, /* Default process security */
3470 NULL, /* Default thread security */
3471 FALSE, /* Must be TRUE to use std handles */
3472 NORMAL_PRIORITY_CLASS, /* No special scheduling */
3473 NULL, /* Inherit our environment block */
3474 NULL, /* Inherit our currrent directory */
3475 &stStartInfo, /* -> Startup info */
3476 &stProcInfo)) /* <- Process info (if OK) */
3478 CloseHandle(stProcInfo.hThread);/* library source code does this. */
3479 sv_setiv(ST(2), stProcInfo.dwProcessId);
3482 XSRETURN_IV(bSuccess);
3486 XS(w32_GetTickCount)
3489 DWORD msec = GetTickCount();
3497 XS(w32_GetShortPathName)
3504 Perl_croak(aTHX_ "usage: Win32::GetShortPathName($longPathName)");
3506 shortpath = sv_mortalcopy(ST(0));
3507 SvUPGRADE(shortpath, SVt_PV);
3508 /* src == target is allowed */
3510 len = GetShortPathName(SvPVX(shortpath),
3513 } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
3515 SvCUR_set(shortpath,len);
3523 XS(w32_GetFullPathName)
3532 Perl_croak(aTHX_ "usage: Win32::GetFullPathName($filename)");
3535 fullpath = sv_mortalcopy(filename);
3536 SvUPGRADE(fullpath, SVt_PV);
3538 len = GetFullPathName(SvPVX(filename),
3542 } while (len >= SvLEN(fullpath) && sv_grow(fullpath,len+1));
3544 if (GIMME_V == G_ARRAY) {
3546 XST_mPV(1,filepart);
3547 len = filepart - SvPVX(fullpath);
3550 SvCUR_set(fullpath,len);
3558 XS(w32_GetLongPathName)
3562 char tmpbuf[MAX_PATH+1];
3567 Perl_croak(aTHX_ "usage: Win32::GetLongPathName($pathname)");
3570 pathstr = SvPV(path,len);
3571 strcpy(tmpbuf, pathstr);
3572 pathstr = win32_longpath(tmpbuf);
3574 ST(0) = sv_2mortal(newSVpvn(pathstr, strlen(pathstr)));
3585 Perl_croak(aTHX_ "usage: Win32::Sleep($milliseconds)");
3596 Perl_croak(aTHX_ "usage: Win32::CopyFile($from, $to, $overwrite)");
3598 WCHAR wSourceFile[MAX_PATH];
3599 WCHAR wDestFile[MAX_PATH];
3600 A2WHELPER(SvPV_nolen(ST(0)), wSourceFile, sizeof(wSourceFile));
3601 wcscpy(wSourceFile, PerlDir_mapW(wSourceFile));
3602 A2WHELPER(SvPV_nolen(ST(1)), wDestFile, sizeof(wDestFile));
3603 bResult = CopyFileW(wSourceFile, PerlDir_mapW(wDestFile), !SvTRUE(ST(2)));
3606 char szSourceFile[MAX_PATH];
3607 strcpy(szSourceFile, PerlDir_mapA(SvPV_nolen(ST(0))));
3608 bResult = CopyFileA(szSourceFile, PerlDir_mapA(SvPV_nolen(ST(1))), !SvTRUE(ST(2)));
3617 Perl_init_os_extras(void)
3620 char *file = __FILE__;
3623 w32_perlshell_tokens = Nullch;
3624 w32_perlshell_items = -1;
3625 w32_fdpid = newAV(); /* XXX needs to be in Perl_win32_init()? */
3626 New(1313, w32_children, 1, child_tab);
3627 w32_num_children = 0;
3628 w32_init_socktype = 0;
3631 New(1313, w32_pseudo_children, 1, child_tab);
3632 w32_num_pseudo_children = 0;
3635 /* these names are Activeware compatible */
3636 newXS("Win32::GetCwd", w32_GetCwd, file);
3637 newXS("Win32::SetCwd", w32_SetCwd, file);
3638 newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
3639 newXS("Win32::GetLastError", w32_GetLastError, file);
3640 newXS("Win32::SetLastError", w32_SetLastError, file);
3641 newXS("Win32::LoginName", w32_LoginName, file);
3642 newXS("Win32::NodeName", w32_NodeName, file);
3643 newXS("Win32::DomainName", w32_DomainName, file);
3644 newXS("Win32::FsType", w32_FsType, file);
3645 newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
3646 newXS("Win32::IsWinNT", w32_IsWinNT, file);
3647 newXS("Win32::IsWin95", w32_IsWin95, file);
3648 newXS("Win32::FormatMessage", w32_FormatMessage, file);
3649 newXS("Win32::Spawn", w32_Spawn, file);
3650 newXS("Win32::GetTickCount", w32_GetTickCount, file);
3651 newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
3652 newXS("Win32::GetFullPathName", w32_GetFullPathName, file);
3653 newXS("Win32::GetLongPathName", w32_GetLongPathName, file);
3654 newXS("Win32::CopyFile", w32_CopyFile, file);
3655 newXS("Win32::Sleep", w32_Sleep, file);
3657 /* XXX Bloat Alert! The following Activeware preloads really
3658 * ought to be part of Win32::Sys::*, so they're not included
3661 /* LookupAccountName
3663 * InitiateSystemShutdown
3664 * AbortSystemShutdown
3665 * ExpandEnvrironmentStrings
3670 Perl_win32_init(int *argcp, char ***argvp)
3672 /* Disable floating point errors, Perl will trap the ones we
3673 * care about. VC++ RTL defaults to switching these off
3674 * already, but the Borland RTL doesn't. Since we don't
3675 * want to be at the vendor's whim on the default, we set
3676 * it explicitly here.
3678 #if !defined(_ALPHA_) && !defined(__GNUC__)
3679 _control87(MCW_EM, MCW_EM);
3684 #ifdef USE_BINMODE_SCRIPTS
3687 win32_strip_return(SV *sv)
3689 char *s = SvPVX(sv);
3690 char *e = s+SvCUR(sv);
3694 if (*s == '\r' && s[1] == '\n')
3704 SvCUR_set(sv,d-SvPVX(sv));
3712 # undef Perl_sys_intern_dup
3713 # define Perl_sys_intern_dup CPerlObj::Perl_sys_intern_dup
3718 Perl_sys_intern_dup(pTHX_ struct interp_intern *src, struct interp_intern *dst)
3720 dst->perlshell_tokens = Nullch;
3721 dst->perlshell_vec = (char**)NULL;
3722 dst->perlshell_items = 0;
3723 dst->fdpid = newAV();
3724 Newz(1313, dst->children, 1, child_tab);
3725 Newz(1313, dst->pseudo_children, 1, child_tab);
3727 dst->children->num = 0;
3728 dst->thr_intern.Winit_socktype = src->thr_intern.Winit_socktype;