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 HANDLE w32_perldll_handle = INVALID_HANDLE_VALUE;
100 char w32_module_name[MAX_PATH+1];
101 static DWORD w32_platform = (DWORD)-1;
106 return (win32_os_id() == VER_PLATFORM_WIN32_WINDOWS);
112 return (win32_os_id() == VER_PLATFORM_WIN32_NT);
115 /* *svp (if non-NULL) is expected to be POK (valid allocated SvPVX(*svp)) */
117 get_regstr_from(HKEY hkey, const char *valuename, SV **svp)
119 /* Retrieve a REG_SZ or REG_EXPAND_SZ from the registry */
122 const char *subkey = "Software\\Perl";
126 retval = RegOpenKeyEx(hkey, subkey, 0, KEY_READ, &handle);
127 if (retval == ERROR_SUCCESS) {
129 retval = RegQueryValueEx(handle, valuename, 0, &type, NULL, &datalen);
130 if (retval == ERROR_SUCCESS && type == REG_SZ) {
133 *svp = sv_2mortal(newSVpvn("",0));
134 SvGROW(*svp, datalen);
135 retval = RegQueryValueEx(handle, valuename, 0, NULL,
136 (PBYTE)SvPVX(*svp), &datalen);
137 if (retval == ERROR_SUCCESS) {
139 SvCUR_set(*svp,datalen-1);
147 /* *svp (if non-NULL) is expected to be POK (valid allocated SvPVX(*svp)) */
149 get_regstr(const char *valuename, SV **svp)
151 char *str = get_regstr_from(HKEY_CURRENT_USER, valuename, svp);
153 str = get_regstr_from(HKEY_LOCAL_MACHINE, valuename, svp);
157 /* *prev_pathp (if non-NULL) is expected to be POK (valid allocated SvPVX(sv)) */
159 get_emd_part(SV **prev_pathp, char *trailing_path, ...)
163 char mod_name[MAX_PATH+1];
167 int oldsize, newsize;
169 va_start(ap, trailing_path);
170 strip = va_arg(ap, char *);
172 sprintf(base, "%5.3f",
173 (double)PERL_REVISION + ((double)PERL_VERSION / (double)1000));
175 if (!*w32_module_name) {
176 GetModuleFileName((HMODULE)((w32_perldll_handle == INVALID_HANDLE_VALUE)
177 ? GetModuleHandle(NULL)
178 : w32_perldll_handle),
179 w32_module_name, sizeof(w32_module_name));
181 /* try to get full path to binary (which may be mangled when perl is
182 * run from a 16-bit app) */
183 /*PerlIO_printf(Perl_debug_log, "Before %s\n", w32_module_name);*/
184 (void)win32_longpath(w32_module_name);
185 /*PerlIO_printf(Perl_debug_log, "After %s\n", w32_module_name);*/
187 /* normalize to forward slashes */
188 ptr = w32_module_name;
195 strcpy(mod_name, w32_module_name);
196 ptr = strrchr(mod_name, '/');
197 while (ptr && strip) {
198 /* look for directories to skip back */
201 ptr = strrchr(mod_name, '/');
202 /* avoid stripping component if there is no slash,
203 * or it doesn't match ... */
204 if (!ptr || stricmp(ptr+1, strip) != 0) {
205 /* ... but not if component matches 5.00X* */
206 if (!ptr || !(*strip == '5' && *(ptr+1) == '5'
207 && strncmp(strip, base, 5) == 0
208 && strncmp(ptr+1, base, 5) == 0))
214 strip = va_arg(ap, char *);
222 strcpy(++ptr, trailing_path);
224 /* only add directory if it exists */
225 if (GetFileAttributes(mod_name) != (DWORD) -1) {
226 /* directory exists */
229 *prev_pathp = sv_2mortal(newSVpvn("",0));
230 sv_catpvn(*prev_pathp, ";", 1);
231 sv_catpv(*prev_pathp, mod_name);
232 return SvPVX(*prev_pathp);
239 win32_get_privlib(char *pl)
242 char *stdlib = "lib";
243 char buffer[MAX_PATH+1];
246 /* $stdlib = $HKCU{"lib-$]"} || $HKLM{"lib-$]"} || $HKCU{"lib"} || $HKLM{"lib"} || ""; */
247 sprintf(buffer, "%s-%s", stdlib, pl);
248 if (!get_regstr(buffer, &sv))
249 (void)get_regstr(stdlib, &sv);
251 /* $stdlib .= ";$EMD/../../lib" */
252 return get_emd_part(&sv, stdlib, ARCHNAME, "bin", Nullch);
256 win32_get_sitelib(char *pl)
259 char *sitelib = "sitelib";
261 char pathstr[MAX_PATH+1];
267 /* $HKCU{"sitelib-$]"} || $HKLM{"sitelib-$]"} . ---; */
268 sprintf(regstr, "%s-%s", sitelib, pl);
269 (void)get_regstr(regstr, &sv1);
272 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/site/$]/lib"; */
273 sprintf(pathstr, "site/%s/lib", pl);
274 (void)get_emd_part(&sv1, pathstr, ARCHNAME, "bin", pl, Nullch);
275 if (!sv1 && strlen(pl) == 7) {
276 /* pl may have been SUBVERSION-specific; try again without
278 sprintf(pathstr, "site/%.5s/lib", pl);
279 (void)get_emd_part(&sv1, pathstr, ARCHNAME, "bin", pl, Nullch);
282 /* $HKCU{'sitelib'} || $HKLM{'sitelib'} . ---; */
283 (void)get_regstr(sitelib, &sv2);
286 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/site/lib"; */
287 (void)get_emd_part(&sv2, "site/lib", ARCHNAME, "bin", pl, Nullch);
296 sv_catpvn(sv1, ";", 1);
304 has_shell_metachars(char *ptr)
310 * Scan string looking for redirection (< or >) or pipe
311 * characters (|) that are not in a quoted string.
312 * Shell variable interpolation (%VAR%) can also happen inside strings.
344 #if !defined(PERL_IMPLICIT_SYS)
345 /* since the current process environment is being updated in util.c
346 * the library functions will get the correct environment
349 Perl_my_popen(pTHX_ char *cmd, char *mode)
352 #define fixcmd(x) { \
353 char *pspace = strchr((x),' '); \
356 while (p < pspace) { \
367 PERL_FLUSHALL_FOR_CHILD;
368 return win32_popen(cmd, mode);
372 Perl_my_pclose(pTHX_ PerlIO *fp)
374 return win32_pclose(fp);
378 DllExport unsigned long
381 static OSVERSIONINFO osver;
383 if (osver.dwPlatformId != w32_platform) {
384 memset(&osver, 0, sizeof(OSVERSIONINFO));
385 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
386 GetVersionEx(&osver);
387 w32_platform = osver.dwPlatformId;
389 return (unsigned long)w32_platform;
392 /* Tokenize a string. Words are null-separated, and the list
393 * ends with a doubled null. Any character (except null and
394 * including backslash) may be escaped by preceding it with a
395 * backslash (the backslash will be stripped).
396 * Returns number of words in result buffer.
399 tokenize(const char *str, char **dest, char ***destv)
401 char *retstart = Nullch;
402 char **retvstart = 0;
406 int slen = strlen(str);
408 register char **retv;
409 New(1307, ret, slen+2, char);
410 New(1308, retv, (slen+3)/2, char*);
418 if (*ret == '\\' && *str)
420 else if (*ret == ' ') {
436 retvstart[items] = Nullch;
449 if (!w32_perlshell_tokens) {
450 /* we don't use COMSPEC here for two reasons:
451 * 1. the same reason perl on UNIX doesn't use SHELL--rampant and
452 * uncontrolled unportability of the ensuing scripts.
453 * 2. PERL5SHELL could be set to a shell that may not be fit for
454 * interactive use (which is what most programs look in COMSPEC
457 const char* defaultshell = (IsWinNT()
458 ? "cmd.exe /x/c" : "command.com /c");
459 const char *usershell = getenv("PERL5SHELL");
460 w32_perlshell_items = tokenize(usershell ? usershell : defaultshell,
461 &w32_perlshell_tokens,
467 do_aspawn(void *vreally, void **vmark, void **vsp)
470 SV *really = (SV*)vreally;
471 SV **mark = (SV**)vmark;
483 New(1306, argv, (sp - mark) + w32_perlshell_items + 2, char*);
485 if (SvNIOKp(*(mark+1)) && !SvPOKp(*(mark+1))) {
490 while (++mark <= sp) {
491 if (*mark && (str = SvPV_nolen(*mark)))
498 status = win32_spawnvp(flag,
499 (const char*)(really ? SvPV_nolen(really) : argv[0]),
500 (const char* const*)argv);
502 if (status < 0 && (errno == ENOEXEC || errno == ENOENT)) {
503 /* possible shell-builtin, invoke with shell */
505 sh_items = w32_perlshell_items;
507 argv[index+sh_items] = argv[index];
508 while (--sh_items >= 0)
509 argv[sh_items] = w32_perlshell_vec[sh_items];
511 status = win32_spawnvp(flag,
512 (const char*)(really ? SvPV_nolen(really) : argv[0]),
513 (const char* const*)argv);
516 if (flag != P_NOWAIT) {
519 if (ckWARN(WARN_EXEC))
520 Perl_warner(aTHX_ WARN_EXEC, "Can't spawn \"%s\": %s", argv[0], strerror(errno));
525 PL_statusvalue = status;
532 do_spawn2(char *cmd, int exectype)
539 BOOL needToTry = TRUE;
542 /* Save an extra exec if possible. See if there are shell
543 * metacharacters in it */
544 if (!has_shell_metachars(cmd)) {
545 New(1301,argv, strlen(cmd) / 2 + 2, char*);
546 New(1302,cmd2, strlen(cmd) + 1, char);
549 for (s = cmd2; *s;) {
550 while (*s && isSPACE(*s))
554 while (*s && !isSPACE(*s))
563 status = win32_spawnvp(P_WAIT, argv[0],
564 (const char* const*)argv);
566 case EXECF_SPAWN_NOWAIT:
567 status = win32_spawnvp(P_NOWAIT, argv[0],
568 (const char* const*)argv);
571 status = win32_execvp(argv[0], (const char* const*)argv);
574 if (status != -1 || errno == 0)
584 New(1306, argv, w32_perlshell_items + 2, char*);
585 while (++i < w32_perlshell_items)
586 argv[i] = w32_perlshell_vec[i];
591 status = win32_spawnvp(P_WAIT, argv[0],
592 (const char* const*)argv);
594 case EXECF_SPAWN_NOWAIT:
595 status = win32_spawnvp(P_NOWAIT, argv[0],
596 (const char* const*)argv);
599 status = win32_execvp(argv[0], (const char* const*)argv);
605 if (exectype != EXECF_SPAWN_NOWAIT) {
608 if (ckWARN(WARN_EXEC))
609 Perl_warner(aTHX_ WARN_EXEC, "Can't %s \"%s\": %s",
610 (exectype == EXECF_EXEC ? "exec" : "spawn"),
611 cmd, strerror(errno));
616 PL_statusvalue = status;
624 return do_spawn2(cmd, EXECF_SPAWN);
628 do_spawn_nowait(char *cmd)
630 return do_spawn2(cmd, EXECF_SPAWN_NOWAIT);
634 Perl_do_exec(pTHX_ char *cmd)
636 do_spawn2(cmd, EXECF_EXEC);
640 /* The idea here is to read all the directory names into a string table
641 * (separated by nulls) and when one of the other dir functions is called
642 * return the pointer to the current file name.
645 win32_opendir(char *filename)
651 char scanname[MAX_PATH+3];
653 WIN32_FIND_DATAA aFindData;
654 WIN32_FIND_DATAW wFindData;
656 char buffer[MAX_PATH*2];
657 WCHAR wbuffer[MAX_PATH];
660 len = strlen(filename);
664 /* check to see if filename is a directory */
665 if (win32_stat(filename, &sbuf) < 0 || !S_ISDIR(sbuf.st_mode))
668 /* Get us a DIR structure */
669 Newz(1303, dirp, 1, DIR);
671 /* Create the search pattern */
672 strcpy(scanname, filename);
674 /* bare drive name means look in cwd for drive */
675 if (len == 2 && isALPHA(scanname[0]) && scanname[1] == ':') {
676 scanname[len++] = '.';
677 scanname[len++] = '/';
679 else if (scanname[len-1] != '/' && scanname[len-1] != '\\') {
680 scanname[len++] = '/';
682 scanname[len++] = '*';
683 scanname[len] = '\0';
685 /* do the FindFirstFile call */
687 A2WHELPER(scanname, wbuffer, sizeof(wbuffer));
688 fh = FindFirstFileW(wbuffer, &wFindData);
691 fh = FindFirstFileA(scanname, &aFindData);
694 if (fh == INVALID_HANDLE_VALUE) {
695 DWORD err = GetLastError();
696 /* FindFirstFile() fails on empty drives! */
698 case ERROR_FILE_NOT_FOUND:
700 case ERROR_NO_MORE_FILES:
701 case ERROR_PATH_NOT_FOUND:
704 case ERROR_NOT_ENOUGH_MEMORY:
715 /* now allocate the first part of the string table for
716 * the filenames that we find.
719 W2AHELPER(wFindData.cFileName, buffer, sizeof(buffer));
723 ptr = aFindData.cFileName;
730 New(1304, dirp->start, dirp->size, char);
731 strcpy(dirp->start, ptr);
733 dirp->end = dirp->curr = dirp->start;
739 /* Readdir just returns the current string pointer and bumps the
740 * string pointer to the nDllExport entry.
742 DllExport struct direct *
743 win32_readdir(DIR *dirp)
748 /* first set up the structure to return */
749 len = strlen(dirp->curr);
750 strcpy(dirp->dirstr.d_name, dirp->curr);
751 dirp->dirstr.d_namlen = len;
754 dirp->dirstr.d_ino = dirp->curr - dirp->start;
756 /* Now set up for the next call to readdir */
757 dirp->curr += len + 1;
758 if (dirp->curr >= dirp->end) {
762 WIN32_FIND_DATAW wFindData;
763 WIN32_FIND_DATAA aFindData;
764 char buffer[MAX_PATH*2];
766 /* finding the next file that matches the wildcard
767 * (which should be all of them in this directory!).
770 res = FindNextFileW(dirp->handle, &wFindData);
772 W2AHELPER(wFindData.cFileName, buffer, sizeof(buffer));
777 res = FindNextFileA(dirp->handle, &aFindData);
779 ptr = aFindData.cFileName;
782 long endpos = dirp->end - dirp->start;
783 long newsize = endpos + strlen(ptr) + 1;
784 /* bump the string table size by enough for the
785 * new name and it's null terminator */
786 while (newsize > dirp->size) {
787 long curpos = dirp->curr - dirp->start;
789 Renew(dirp->start, dirp->size, char);
790 dirp->curr = dirp->start + curpos;
792 strcpy(dirp->start + endpos, ptr);
793 dirp->end = dirp->start + newsize;
799 return &(dirp->dirstr);
805 /* Telldir returns the current string pointer position */
807 win32_telldir(DIR *dirp)
809 return (dirp->curr - dirp->start);
813 /* Seekdir moves the string pointer to a previously saved position
814 * (returned by telldir).
817 win32_seekdir(DIR *dirp, long loc)
819 dirp->curr = dirp->start + loc;
822 /* Rewinddir resets the string pointer to the start */
824 win32_rewinddir(DIR *dirp)
826 dirp->curr = dirp->start;
829 /* free the memory allocated by opendir */
831 win32_closedir(DIR *dirp)
834 if (dirp->handle != INVALID_HANDLE_VALUE)
835 FindClose(dirp->handle);
836 Safefree(dirp->start);
849 * Just pretend that everyone is a superuser. NT will let us know if
850 * we don\'t really have permission to do something.
853 #define ROOT_UID ((uid_t)0)
854 #define ROOT_GID ((gid_t)0)
883 return (auid == ROOT_UID ? 0 : -1);
889 return (agid == ROOT_GID ? 0 : -1);
896 char *buf = w32_getlogin_buffer;
897 DWORD size = sizeof(w32_getlogin_buffer);
898 if (GetUserName(buf,&size))
904 chown(const char *path, uid_t owner, gid_t group)
915 for (child = 0 ; child < w32_num_children ; ++child) {
916 if (w32_child_pids[child] == pid)
923 remove_dead_process(long child)
927 CloseHandle(w32_child_handles[child]);
928 Copy(&w32_child_handles[child+1], &w32_child_handles[child],
929 (w32_num_children-child-1), HANDLE);
930 Copy(&w32_child_pids[child+1], &w32_child_pids[child],
931 (w32_num_children-child-1), DWORD);
937 win32_kill(int pid, int sig)
940 hProcess = OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid);
941 if (hProcess && TerminateProcess(hProcess, sig))
942 CloseHandle(hProcess);
954 DllExport unsigned int
955 win32_sleep(unsigned int t)
962 win32_stat(const char *path, struct stat *buffer)
966 int l = strlen(path);
968 WCHAR wbuffer[MAX_PATH];
973 switch(path[l - 1]) {
974 /* FindFirstFile() and stat() are buggy with a trailing
975 * backslash, so change it to a forward slash :-( */
977 strncpy(t, path, l-1);
982 /* FindFirstFile() is buggy with "x:", so add a dot :-( */
984 if (l == 2 && isALPHA(path[0])) {
985 t[0] = path[0]; t[1] = ':'; t[2] = '.'; t[3] = '\0';
993 /* We *must* open & close the file once; otherwise file attribute changes */
994 /* might not yet have propagated to "other" hard links of the same file. */
995 /* This also gives us an opportunity to determine the number of links. */
997 A2WHELPER(path, wbuffer, sizeof(wbuffer));
998 handle = CreateFileW(wbuffer, 0, 0, NULL, OPEN_EXISTING, 0, NULL);
1001 handle = CreateFileA(path, 0, 0, NULL, OPEN_EXISTING, 0, NULL);
1003 if (handle != INVALID_HANDLE_VALUE) {
1004 BY_HANDLE_FILE_INFORMATION bhi;
1005 if (GetFileInformationByHandle(handle, &bhi))
1006 nlink = bhi.nNumberOfLinks;
1007 CloseHandle(handle);
1011 res = _wstat(wbuffer, (struct _stat *)buffer);
1013 res = stat(path, buffer);
1014 buffer->st_nlink = nlink;
1017 /* CRT is buggy on sharenames, so make sure it really isn't.
1018 * XXX using GetFileAttributesEx() will enable us to set
1019 * buffer->st_*time (but note that's not available on the
1020 * Windows of 1995) */
1023 r = GetFileAttributesW(wbuffer);
1026 r = GetFileAttributesA(path);
1028 if (r != 0xffffffff && (r & FILE_ATTRIBUTE_DIRECTORY)) {
1029 /* buffer may still contain old garbage since stat() failed */
1030 Zero(buffer, 1, struct stat);
1031 buffer->st_mode = S_IFDIR | S_IREAD;
1033 if (!(r & FILE_ATTRIBUTE_READONLY))
1034 buffer->st_mode |= S_IWRITE | S_IEXEC;
1039 if (l == 3 && isALPHA(path[0]) && path[1] == ':'
1040 && (path[2] == '\\' || path[2] == '/'))
1042 /* The drive can be inaccessible, some _stat()s are buggy */
1044 ? !GetVolumeInformationW(wbuffer,NULL,0,NULL,NULL,NULL,NULL,0)
1045 : !GetVolumeInformationA(path,NULL,0,NULL,NULL,NULL,NULL,0)) {
1051 if (S_ISDIR(buffer->st_mode))
1052 buffer->st_mode |= S_IWRITE | S_IEXEC;
1053 else if (S_ISREG(buffer->st_mode)) {
1054 if (l >= 4 && path[l-4] == '.') {
1055 const char *e = path + l - 3;
1056 if (strnicmp(e,"exe",3)
1057 && strnicmp(e,"bat",3)
1058 && strnicmp(e,"com",3)
1059 && (IsWin95() || strnicmp(e,"cmd",3)))
1060 buffer->st_mode &= ~S_IEXEC;
1062 buffer->st_mode |= S_IEXEC;
1065 buffer->st_mode &= ~S_IEXEC;
1072 /* Find the longname of a given path. path is destructively modified.
1073 * It should have space for at least MAX_PATH characters. */
1075 win32_longpath(char *path)
1077 WIN32_FIND_DATA fdata;
1079 char tmpbuf[MAX_PATH+1];
1080 char *tmpstart = tmpbuf;
1087 if (isALPHA(path[0]) && path[1] == ':' &&
1088 (path[2] == '/' || path[2] == '\\'))
1091 *tmpstart++ = path[0];
1095 else if ((path[0] == '/' || path[0] == '\\') &&
1096 (path[1] == '/' || path[1] == '\\'))
1099 *tmpstart++ = path[0];
1100 *tmpstart++ = path[1];
1101 /* copy machine name */
1102 while (*start && *start != '/' && *start != '\\')
1103 *tmpstart++ = *start++;
1105 *tmpstart++ = *start;
1107 /* copy share name */
1108 while (*start && *start != '/' && *start != '\\')
1109 *tmpstart++ = *start++;
1113 if (sep == '/' || sep == '\\')
1117 /* walk up to slash */
1118 while (*start && *start != '/' && *start != '\\')
1121 /* discard doubled slashes */
1122 while (*start && (start[1] == '/' || start[1] == '\\'))
1126 /* stop and find full name of component */
1128 fhand = FindFirstFile(path,&fdata);
1129 if (fhand != INVALID_HANDLE_VALUE) {
1130 strcpy(tmpstart, fdata.cFileName);
1131 tmpstart += strlen(fdata.cFileName);
1139 /* failed a step, just return without side effects */
1140 /*PerlIO_printf(Perl_debug_log, "Failed to find %s\n", path);*/
1145 strcpy(path,tmpbuf);
1149 #ifndef USE_WIN32_RTL_ENV
1152 win32_getenv(const char *name)
1155 WCHAR wBuffer[MAX_PATH];
1157 SV *curitem = Nullsv;
1160 A2WHELPER(name, wBuffer, sizeof(wBuffer));
1161 needlen = GetEnvironmentVariableW(wBuffer, NULL, 0);
1164 needlen = GetEnvironmentVariableA(name,NULL,0);
1166 curitem = sv_2mortal(newSVpvn("", 0));
1170 SvGROW(curitem, (needlen+1)*sizeof(WCHAR));
1171 needlen = GetEnvironmentVariableW(wBuffer,
1172 (WCHAR*)SvPVX(curitem),
1174 } while (needlen >= SvLEN(curitem)/sizeof(WCHAR));
1175 SvCUR_set(curitem, (needlen*sizeof(WCHAR))+1);
1176 acuritem = sv_2mortal(newSVsv(curitem));
1177 W2AHELPER((WCHAR*)SvPVX(acuritem), SvPVX(curitem), SvCUR(curitem));
1181 SvGROW(curitem, needlen+1);
1182 needlen = GetEnvironmentVariableA(name,SvPVX(curitem),
1184 } while (needlen >= SvLEN(curitem));
1185 SvCUR_set(curitem, needlen);
1189 /* allow any environment variables that begin with 'PERL'
1190 to be stored in the registry */
1191 if (strncmp(name, "PERL", 4) == 0)
1192 (void)get_regstr(name, &curitem);
1194 if (curitem && SvCUR(curitem))
1195 return SvPVX(curitem);
1201 win32_putenv(const char *name)
1208 int length, relval = -1;
1212 length = strlen(name)+1;
1213 New(1309,wCuritem,length,WCHAR);
1214 A2WHELPER(name, wCuritem, length*sizeof(WCHAR));
1215 wVal = wcschr(wCuritem, '=');
1218 if(SetEnvironmentVariableW(wCuritem, *wVal ? wVal : NULL))
1224 New(1309,curitem,strlen(name)+1,char);
1225 strcpy(curitem, name);
1226 val = strchr(curitem, '=');
1228 /* The sane way to deal with the environment.
1229 * Has these advantages over putenv() & co.:
1230 * * enables us to store a truly empty value in the
1231 * environment (like in UNIX).
1232 * * we don't have to deal with RTL globals, bugs and leaks.
1234 * Why you may want to enable USE_WIN32_RTL_ENV:
1235 * * environ[] and RTL functions will not reflect changes,
1236 * which might be an issue if extensions want to access
1237 * the env. via RTL. This cuts both ways, since RTL will
1238 * not see changes made by extensions that call the Win32
1239 * functions directly, either.
1243 if(SetEnvironmentVariableA(curitem, *val ? val : NULL))
1255 filetime_to_clock(PFILETIME ft)
1257 __int64 qw = ft->dwHighDateTime;
1259 qw |= ft->dwLowDateTime;
1260 qw /= 10000; /* File time ticks at 0.1uS, clock at 1mS */
1265 win32_times(struct tms *timebuf)
1270 if (GetProcessTimes(GetCurrentProcess(), &dummy, &dummy,
1272 timebuf->tms_utime = filetime_to_clock(&user);
1273 timebuf->tms_stime = filetime_to_clock(&kernel);
1274 timebuf->tms_cutime = 0;
1275 timebuf->tms_cstime = 0;
1278 /* That failed - e.g. Win95 fallback to clock() */
1279 clock_t t = clock();
1280 timebuf->tms_utime = t;
1281 timebuf->tms_stime = 0;
1282 timebuf->tms_cutime = 0;
1283 timebuf->tms_cstime = 0;
1288 /* fix utime() so it works on directories in NT */
1290 filetime_from_time(PFILETIME pFileTime, time_t Time)
1292 struct tm *pTM = localtime(&Time);
1293 SYSTEMTIME SystemTime;
1299 SystemTime.wYear = pTM->tm_year + 1900;
1300 SystemTime.wMonth = pTM->tm_mon + 1;
1301 SystemTime.wDay = pTM->tm_mday;
1302 SystemTime.wHour = pTM->tm_hour;
1303 SystemTime.wMinute = pTM->tm_min;
1304 SystemTime.wSecond = pTM->tm_sec;
1305 SystemTime.wMilliseconds = 0;
1307 return SystemTimeToFileTime(&SystemTime, &LocalTime) &&
1308 LocalFileTimeToFileTime(&LocalTime, pFileTime);
1312 win32_utime(const char *filename, struct utimbuf *times)
1319 struct utimbuf TimeBuffer;
1320 WCHAR wbuffer[MAX_PATH];
1324 A2WHELPER(filename, wbuffer, sizeof(wbuffer));
1325 rc = _wutime(wbuffer, (struct _utimbuf*)times);
1328 rc = utime(filename, times);
1330 /* EACCES: path specifies directory or readonly file */
1331 if (rc == 0 || errno != EACCES /* || !IsWinNT() */)
1334 if (times == NULL) {
1335 times = &TimeBuffer;
1336 time(×->actime);
1337 times->modtime = times->actime;
1340 /* This will (and should) still fail on readonly files */
1342 handle = CreateFileW(wbuffer, GENERIC_READ | GENERIC_WRITE,
1343 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1344 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1347 handle = CreateFileA(filename, GENERIC_READ | GENERIC_WRITE,
1348 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1349 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1351 if (handle == INVALID_HANDLE_VALUE)
1354 if (GetFileTime(handle, &ftCreate, &ftAccess, &ftWrite) &&
1355 filetime_from_time(&ftAccess, times->actime) &&
1356 filetime_from_time(&ftWrite, times->modtime) &&
1357 SetFileTime(handle, &ftCreate, &ftAccess, &ftWrite))
1362 CloseHandle(handle);
1367 win32_uname(struct utsname *name)
1369 struct hostent *hep;
1370 STRLEN nodemax = sizeof(name->nodename)-1;
1371 OSVERSIONINFO osver;
1373 memset(&osver, 0, sizeof(OSVERSIONINFO));
1374 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1375 if (GetVersionEx(&osver)) {
1377 switch (osver.dwPlatformId) {
1378 case VER_PLATFORM_WIN32_WINDOWS:
1379 strcpy(name->sysname, "Windows");
1381 case VER_PLATFORM_WIN32_NT:
1382 strcpy(name->sysname, "Windows NT");
1384 case VER_PLATFORM_WIN32s:
1385 strcpy(name->sysname, "Win32s");
1388 strcpy(name->sysname, "Win32 Unknown");
1393 sprintf(name->release, "%d.%d",
1394 osver.dwMajorVersion, osver.dwMinorVersion);
1397 sprintf(name->version, "Build %d",
1398 osver.dwPlatformId == VER_PLATFORM_WIN32_NT
1399 ? osver.dwBuildNumber : (osver.dwBuildNumber & 0xffff));
1400 if (osver.szCSDVersion[0]) {
1401 char *buf = name->version + strlen(name->version);
1402 sprintf(buf, " (%s)", osver.szCSDVersion);
1406 *name->sysname = '\0';
1407 *name->version = '\0';
1408 *name->release = '\0';
1412 hep = win32_gethostbyname("localhost");
1414 STRLEN len = strlen(hep->h_name);
1415 if (len <= nodemax) {
1416 strcpy(name->nodename, hep->h_name);
1419 strncpy(name->nodename, hep->h_name, nodemax);
1420 name->nodename[nodemax] = '\0';
1425 if (!GetComputerName(name->nodename, &sz))
1426 *name->nodename = '\0';
1429 /* machine (architecture) */
1433 GetSystemInfo(&info);
1435 #if defined(__BORLANDC__) || defined(__MINGW32__)
1436 switch (info.u.s.wProcessorArchitecture) {
1438 switch (info.wProcessorArchitecture) {
1440 case PROCESSOR_ARCHITECTURE_INTEL:
1441 arch = "x86"; break;
1442 case PROCESSOR_ARCHITECTURE_MIPS:
1443 arch = "mips"; break;
1444 case PROCESSOR_ARCHITECTURE_ALPHA:
1445 arch = "alpha"; break;
1446 case PROCESSOR_ARCHITECTURE_PPC:
1447 arch = "ppc"; break;
1449 arch = "unknown"; break;
1451 strcpy(name->machine, arch);
1457 win32_waitpid(int pid, int *status, int flags)
1462 return win32_wait(status);
1464 long child = find_pid(pid);
1466 HANDLE hProcess = w32_child_handles[child];
1467 DWORD waitcode = WaitForSingleObject(hProcess, INFINITE);
1468 if (waitcode != WAIT_FAILED) {
1469 if (GetExitCodeProcess(hProcess, &waitcode)) {
1470 *status = (int)((waitcode & 0xff) << 8);
1471 retval = (int)w32_child_pids[child];
1472 remove_dead_process(child);
1480 retval = cwait(status, pid, WAIT_CHILD);
1481 /* cwait() returns "correctly" on Borland */
1482 #ifndef __BORLANDC__
1488 return retval >= 0 ? pid : retval;
1492 win32_wait(int *status)
1494 /* XXX this wait emulation only knows about processes
1495 * spawned via win32_spawnvp(P_NOWAIT, ...).
1499 DWORD exitcode, waitcode;
1501 if (!w32_num_children) {
1506 /* if a child exists, wait for it to die */
1507 waitcode = WaitForMultipleObjects(w32_num_children,
1511 if (waitcode != WAIT_FAILED) {
1512 if (waitcode >= WAIT_ABANDONED_0
1513 && waitcode < WAIT_ABANDONED_0 + w32_num_children)
1514 i = waitcode - WAIT_ABANDONED_0;
1516 i = waitcode - WAIT_OBJECT_0;
1517 if (GetExitCodeProcess(w32_child_handles[i], &exitcode) ) {
1518 *status = (int)((exitcode & 0xff) << 8);
1519 retval = (int)w32_child_pids[i];
1520 remove_dead_process(i);
1526 errno = GetLastError();
1530 static UINT timerid = 0;
1532 static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
1535 KillTimer(NULL,timerid);
1540 DllExport unsigned int
1541 win32_alarm(unsigned int sec)
1544 * the 'obvious' implentation is SetTimer() with a callback
1545 * which does whatever receiving SIGALRM would do
1546 * we cannot use SIGALRM even via raise() as it is not
1547 * one of the supported codes in <signal.h>
1549 * Snag is unless something is looking at the message queue
1550 * nothing happens :-(
1555 timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
1557 Perl_croak_nocontext("Cannot set timer");
1563 KillTimer(NULL,timerid);
1570 #ifdef HAVE_DES_FCRYPT
1571 extern char * des_fcrypt(const char *txt, const char *salt, char *cbuf);
1575 win32_crypt(const char *txt, const char *salt)
1578 #ifdef HAVE_DES_FCRYPT
1580 return des_fcrypt(txt, salt, w32_crypt_buffer);
1582 Perl_croak(aTHX_ "The crypt() function is unimplemented due to excessive paranoia.");
1587 #ifdef USE_FIXED_OSFHANDLE
1589 EXTERN_C int __cdecl _alloc_osfhnd(void);
1590 EXTERN_C int __cdecl _set_osfhnd(int fh, long value);
1591 EXTERN_C void __cdecl _lock_fhandle(int);
1592 EXTERN_C void __cdecl _unlock_fhandle(int);
1593 EXTERN_C void __cdecl _unlock(int);
1595 #if (_MSC_VER >= 1000)
1597 long osfhnd; /* underlying OS file HANDLE */
1598 char osfile; /* attributes of file (e.g., open in text mode?) */
1599 char pipech; /* one char buffer for handles opened on pipes */
1600 #if defined (_MT) && !defined (DLL_FOR_WIN32S)
1602 CRITICAL_SECTION lock;
1603 #endif /* defined (_MT) && !defined (DLL_FOR_WIN32S) */
1606 EXTERN_C ioinfo * __pioinfo[];
1608 #define IOINFO_L2E 5
1609 #define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
1610 #define _pioinfo(i) (__pioinfo[i >> IOINFO_L2E] + (i & (IOINFO_ARRAY_ELTS - 1)))
1611 #define _osfile(i) (_pioinfo(i)->osfile)
1613 #else /* (_MSC_VER >= 1000) */
1614 extern char _osfile[];
1615 #endif /* (_MSC_VER >= 1000) */
1617 #define FOPEN 0x01 /* file handle open */
1618 #define FAPPEND 0x20 /* file handle opened O_APPEND */
1619 #define FDEV 0x40 /* file handle refers to device */
1620 #define FTEXT 0x80 /* file handle is in text mode */
1622 #define _STREAM_LOCKS 26 /* Table of stream locks */
1623 #define _LAST_STREAM_LOCK (_STREAM_LOCKS+_NSTREAM_-1) /* Last stream lock */
1624 #define _FH_LOCKS (_LAST_STREAM_LOCK+1) /* Table of fh locks */
1627 *int my_open_osfhandle(long osfhandle, int flags) - open C Runtime file handle
1630 * This function allocates a free C Runtime file handle and associates
1631 * it with the Win32 HANDLE specified by the first parameter. This is a
1632 * temperary fix for WIN95's brain damage GetFileType() error on socket
1633 * we just bypass that call for socket
1636 * long osfhandle - Win32 HANDLE to associate with C Runtime file handle.
1637 * int flags - flags to associate with C Runtime file handle.
1640 * returns index of entry in fh, if successful
1641 * return -1, if no free entry is found
1645 *******************************************************************************/
1648 my_open_osfhandle(long osfhandle, int flags)
1651 char fileflags; /* _osfile flags */
1653 /* copy relevant flags from second parameter */
1656 if (flags & O_APPEND)
1657 fileflags |= FAPPEND;
1662 /* attempt to allocate a C Runtime file handle */
1663 if ((fh = _alloc_osfhnd()) == -1) {
1664 errno = EMFILE; /* too many open files */
1665 _doserrno = 0L; /* not an OS error */
1666 return -1; /* return error to caller */
1669 /* the file is open. now, set the info in _osfhnd array */
1670 _set_osfhnd(fh, osfhandle);
1672 fileflags |= FOPEN; /* mark as open */
1674 #if (_MSC_VER >= 1000)
1675 _osfile(fh) = fileflags; /* set osfile entry */
1676 _unlock_fhandle(fh);
1678 _osfile[fh] = fileflags; /* set osfile entry */
1679 _unlock(fh+_FH_LOCKS); /* unlock handle */
1682 return fh; /* return handle */
1685 #define _open_osfhandle my_open_osfhandle
1686 #endif /* USE_FIXED_OSFHANDLE */
1688 /* simulate flock by locking a range on the file */
1690 #define LK_ERR(f,i) ((f) ? (i = 0) : (errno = GetLastError()))
1691 #define LK_LEN 0xffff0000
1694 win32_flock(int fd, int oper)
1702 Perl_croak_nocontext("flock() unimplemented on this platform");
1705 fh = (HANDLE)_get_osfhandle(fd);
1706 memset(&o, 0, sizeof(o));
1709 case LOCK_SH: /* shared lock */
1710 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
1712 case LOCK_EX: /* exclusive lock */
1713 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
1715 case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
1716 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
1718 case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
1719 LK_ERR(LockFileEx(fh,
1720 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
1721 0, LK_LEN, 0, &o),i);
1723 case LOCK_UN: /* unlock lock */
1724 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, 0, &o),i);
1726 default: /* unknown */
1737 * redirected io subsystem for all XS modules
1750 return (&(_environ));
1753 /* the rest are the remapped stdio routines */
1773 win32_ferror(FILE *fp)
1775 return (ferror(fp));
1780 win32_feof(FILE *fp)
1786 * Since the errors returned by the socket error function
1787 * WSAGetLastError() are not known by the library routine strerror
1788 * we have to roll our own.
1792 win32_strerror(int e)
1794 #ifndef __BORLANDC__ /* Borland intolerance */
1795 extern int sys_nerr;
1799 if (e < 0 || e > sys_nerr) {
1804 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
1805 w32_strerror_buffer,
1806 sizeof(w32_strerror_buffer), NULL) == 0)
1807 strcpy(w32_strerror_buffer, "Unknown Error");
1809 return w32_strerror_buffer;
1815 win32_str_os_error(void *sv, DWORD dwErr)
1819 dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
1820 |FORMAT_MESSAGE_IGNORE_INSERTS
1821 |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
1822 dwErr, 0, (char *)&sMsg, 1, NULL);
1823 /* strip trailing whitespace and period */
1826 --dwLen; /* dwLen doesn't include trailing null */
1827 } while (0 < dwLen && isSPACE(sMsg[dwLen]));
1828 if ('.' != sMsg[dwLen])
1833 sMsg = (char*)LocalAlloc(0, 64/**sizeof(TCHAR)*/);
1835 dwLen = sprintf(sMsg,
1836 "Unknown error #0x%lX (lookup 0x%lX)",
1837 dwErr, GetLastError());
1841 sv_setpvn((SV*)sv, sMsg, dwLen);
1848 win32_fprintf(FILE *fp, const char *format, ...)
1851 va_start(marker, format); /* Initialize variable arguments. */
1853 return (vfprintf(fp, format, marker));
1857 win32_printf(const char *format, ...)
1860 va_start(marker, format); /* Initialize variable arguments. */
1862 return (vprintf(format, marker));
1866 win32_vfprintf(FILE *fp, const char *format, va_list args)
1868 return (vfprintf(fp, format, args));
1872 win32_vprintf(const char *format, va_list args)
1874 return (vprintf(format, args));
1878 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
1880 return fread(buf, size, count, fp);
1884 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
1886 return fwrite(buf, size, count, fp);
1889 #define MODE_SIZE 10
1892 win32_fopen(const char *filename, const char *mode)
1895 WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH];
1900 if (stricmp(filename, "/dev/null")==0)
1904 A2WHELPER(mode, wMode, sizeof(wMode));
1905 A2WHELPER(filename, wBuffer, sizeof(wBuffer));
1906 return _wfopen(wBuffer, wMode);
1908 return fopen(filename, mode);
1911 #ifndef USE_SOCKETS_AS_HANDLES
1913 #define fdopen my_fdopen
1917 win32_fdopen(int handle, const char *mode)
1920 WCHAR wMode[MODE_SIZE];
1922 A2WHELPER(mode, wMode, sizeof(wMode));
1923 return _wfdopen(handle, wMode);
1925 return fdopen(handle, (char *) mode);
1929 win32_freopen(const char *path, const char *mode, FILE *stream)
1932 WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH];
1933 if (stricmp(path, "/dev/null")==0)
1937 A2WHELPER(mode, wMode, sizeof(wMode));
1938 A2WHELPER(path, wBuffer, sizeof(wBuffer));
1939 return _wfreopen(wBuffer, wMode, stream);
1941 return freopen(path, mode, stream);
1945 win32_fclose(FILE *pf)
1947 return my_fclose(pf); /* defined in win32sck.c */
1951 win32_fputs(const char *s,FILE *pf)
1953 return fputs(s, pf);
1957 win32_fputc(int c,FILE *pf)
1963 win32_ungetc(int c,FILE *pf)
1965 return ungetc(c,pf);
1969 win32_getc(FILE *pf)
1975 win32_fileno(FILE *pf)
1981 win32_clearerr(FILE *pf)
1988 win32_fflush(FILE *pf)
1994 win32_ftell(FILE *pf)
2000 win32_fseek(FILE *pf,long offset,int origin)
2002 return fseek(pf, offset, origin);
2006 win32_fgetpos(FILE *pf,fpos_t *p)
2008 return fgetpos(pf, p);
2012 win32_fsetpos(FILE *pf,const fpos_t *p)
2014 return fsetpos(pf, p);
2018 win32_rewind(FILE *pf)
2038 win32_fstat(int fd,struct stat *sbufptr)
2040 return fstat(fd,sbufptr);
2044 win32_pipe(int *pfd, unsigned int size, int mode)
2046 return _pipe(pfd, size, mode);
2050 * a popen() clone that respects PERL5SHELL
2054 win32_popen(const char *command, const char *mode)
2056 #ifdef USE_RTL_POPEN
2057 return _popen(command, mode);
2065 /* establish which ends read and write */
2066 if (strchr(mode,'w')) {
2067 stdfd = 0; /* stdin */
2071 else if (strchr(mode,'r')) {
2072 stdfd = 1; /* stdout */
2079 /* set the correct mode */
2080 if (strchr(mode,'b'))
2082 else if (strchr(mode,'t'))
2085 ourmode = _fmode & (O_TEXT | O_BINARY);
2087 /* the child doesn't inherit handles */
2088 ourmode |= O_NOINHERIT;
2090 if (win32_pipe( p, 512, ourmode) == -1)
2093 /* save current stdfd */
2094 if ((oldfd = win32_dup(stdfd)) == -1)
2097 /* make stdfd go to child end of pipe (implicitly closes stdfd) */
2098 /* stdfd will be inherited by the child */
2099 if (win32_dup2(p[child], stdfd) == -1)
2102 /* close the child end in parent */
2103 win32_close(p[child]);
2105 /* start the child */
2108 if ((childpid = do_spawn_nowait((char*)command)) == -1)
2111 /* revert stdfd to whatever it was before */
2112 if (win32_dup2(oldfd, stdfd) == -1)
2115 /* close saved handle */
2118 sv_setiv(*av_fetch(w32_fdpid, p[parent], TRUE), childpid);
2120 /* set process id so that it can be returned by perl's open() */
2121 PL_forkprocess = childpid;
2124 /* we have an fd, return a file stream */
2125 return (win32_fdopen(p[parent], (char *)mode));
2128 /* we don't need to check for errors here */
2132 win32_dup2(oldfd, stdfd);
2137 #endif /* USE_RTL_POPEN */
2145 win32_pclose(FILE *pf)
2147 #ifdef USE_RTL_POPEN
2151 int childpid, status;
2154 sv = *av_fetch(w32_fdpid, win32_fileno(pf), TRUE);
2156 childpid = SvIVX(sv);
2168 if (win32_waitpid(childpid, &status, 0) == -1)
2173 #endif /* USE_RTL_POPEN */
2179 LPCWSTR lpExistingFileName,
2180 LPSECURITY_ATTRIBUTES lpSecurityAttributes)
2183 WCHAR wFullName[MAX_PATH+1];
2184 LPVOID lpContext = NULL;
2185 WIN32_STREAM_ID StreamId;
2186 DWORD dwSize = (char*)&StreamId.cStreamName - (char*)&StreamId;
2191 BOOL (__stdcall *pfnBackupWrite)(HANDLE, LPBYTE, DWORD, LPDWORD,
2192 BOOL, BOOL, LPVOID*) =
2193 (BOOL (__stdcall *)(HANDLE, LPBYTE, DWORD, LPDWORD,
2194 BOOL, BOOL, LPVOID*))
2195 GetProcAddress(GetModuleHandle("kernel32.dll"), "BackupWrite");
2196 if (pfnBackupWrite == NULL)
2199 dwLen = GetFullPathNameW(lpFileName, MAX_PATH, wFullName, NULL);
2202 dwLen = (dwLen+1)*sizeof(WCHAR);
2204 handle = CreateFileW(lpExistingFileName, FILE_WRITE_ATTRIBUTES,
2205 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
2206 NULL, OPEN_EXISTING, 0, NULL);
2207 if (handle == INVALID_HANDLE_VALUE)
2210 StreamId.dwStreamId = BACKUP_LINK;
2211 StreamId.dwStreamAttributes = 0;
2212 StreamId.dwStreamNameSize = 0;
2213 StreamId.Size.HighPart = 0;
2214 StreamId.Size.LowPart = dwLen;
2216 bSuccess = pfnBackupWrite(handle, (LPBYTE)&StreamId, dwSize, &dwWritten,
2217 FALSE, FALSE, &lpContext);
2219 bSuccess = pfnBackupWrite(handle, (LPBYTE)wFullName, dwLen, &dwWritten,
2220 FALSE, FALSE, &lpContext);
2221 pfnBackupWrite(handle, NULL, 0, &dwWritten, TRUE, FALSE, &lpContext);
2224 CloseHandle(handle);
2229 win32_link(const char *oldname, const char *newname)
2232 BOOL (__stdcall *pfnCreateHardLinkW)(LPCWSTR,LPCWSTR,LPSECURITY_ATTRIBUTES);
2233 WCHAR wOldName[MAX_PATH];
2234 WCHAR wNewName[MAX_PATH];
2237 Perl_die(aTHX_ PL_no_func, "link");
2239 pfnCreateHardLinkW =
2240 (BOOL (__stdcall *)(LPCWSTR, LPCWSTR, LPSECURITY_ATTRIBUTES))
2241 GetProcAddress(GetModuleHandle("kernel32.dll"), "CreateHardLinkW");
2242 if (pfnCreateHardLinkW == NULL)
2243 pfnCreateHardLinkW = Nt4CreateHardLinkW;
2245 if ((A2WHELPER(oldname, wOldName, sizeof(wOldName))) &&
2246 (A2WHELPER(newname, wNewName, sizeof(wNewName))) &&
2247 pfnCreateHardLinkW(wNewName, wOldName, NULL))
2251 errno = (GetLastError() == ERROR_FILE_NOT_FOUND) ? ENOENT : EINVAL;
2256 win32_rename(const char *oname, const char *newname)
2258 WCHAR wOldName[MAX_PATH];
2259 WCHAR wNewName[MAX_PATH];
2261 /* XXX despite what the documentation says about MoveFileEx(),
2262 * it doesn't work under Windows95!
2267 A2WHELPER(oname, wOldName, sizeof(wOldName));
2268 A2WHELPER(newname, wNewName, sizeof(wNewName));
2269 bResult = MoveFileExW(wOldName,wNewName,
2270 MOVEFILE_COPY_ALLOWED|MOVEFILE_REPLACE_EXISTING);
2273 bResult = MoveFileExA(oname,newname,
2274 MOVEFILE_COPY_ALLOWED|MOVEFILE_REPLACE_EXISTING);
2277 DWORD err = GetLastError();
2279 case ERROR_BAD_NET_NAME:
2280 case ERROR_BAD_NETPATH:
2281 case ERROR_BAD_PATHNAME:
2282 case ERROR_FILE_NOT_FOUND:
2283 case ERROR_FILENAME_EXCED_RANGE:
2284 case ERROR_INVALID_DRIVE:
2285 case ERROR_NO_MORE_FILES:
2286 case ERROR_PATH_NOT_FOUND:
2299 char tmpname[MAX_PATH+1];
2300 char dname[MAX_PATH+1];
2301 char *endname = Nullch;
2303 DWORD from_attr, to_attr;
2305 /* if oname doesn't exist, do nothing */
2306 from_attr = GetFileAttributes(oname);
2307 if (from_attr == 0xFFFFFFFF) {
2312 /* if newname exists, rename it to a temporary name so that we
2313 * don't delete it in case oname happens to be the same file
2314 * (but perhaps accessed via a different path)
2316 to_attr = GetFileAttributes(newname);
2317 if (to_attr != 0xFFFFFFFF) {
2318 /* if newname is a directory, we fail
2319 * XXX could overcome this with yet more convoluted logic */
2320 if (to_attr & FILE_ATTRIBUTE_DIRECTORY) {
2324 tmplen = strlen(newname);
2325 strcpy(tmpname,newname);
2326 endname = tmpname+tmplen;
2327 for (; endname > tmpname ; --endname) {
2328 if (*endname == '/' || *endname == '\\') {
2333 if (endname > tmpname)
2334 endname = strcpy(dname,tmpname);
2338 /* get a temporary filename in same directory
2339 * XXX is this really the best we can do? */
2340 if (!GetTempFileName((LPCTSTR)endname, "plr", 0, tmpname)) {
2344 DeleteFile(tmpname);
2346 retval = rename(newname, tmpname);
2353 /* rename oname to newname */
2354 retval = rename(oname, newname);
2356 /* if we created a temporary file before ... */
2357 if (endname != Nullch) {
2358 /* ...and rename succeeded, delete temporary file/directory */
2360 DeleteFile(tmpname);
2361 /* else restore it to what it was */
2363 (void)rename(tmpname, newname);
2370 win32_setmode(int fd, int mode)
2372 return setmode(fd, mode);
2376 win32_lseek(int fd, long offset, int origin)
2378 return lseek(fd, offset, origin);
2388 win32_open(const char *path, int flag, ...)
2393 WCHAR wBuffer[MAX_PATH];
2396 pmode = va_arg(ap, int);
2399 if (stricmp(path, "/dev/null")==0)
2403 A2WHELPER(path, wBuffer, sizeof(wBuffer));
2404 return _wopen(wBuffer, flag, pmode);
2406 return open(path,flag,pmode);
2428 win32_dup2(int fd1,int fd2)
2430 return dup2(fd1,fd2);
2434 win32_read(int fd, void *buf, unsigned int cnt)
2436 return read(fd, buf, cnt);
2440 win32_write(int fd, const void *buf, unsigned int cnt)
2442 return write(fd, buf, cnt);
2446 win32_mkdir(const char *dir, int mode)
2448 return mkdir(dir); /* just ignore mode */
2452 win32_rmdir(const char *dir)
2458 win32_chdir(const char *dir)
2464 create_command_line(const char* command, const char * const *args)
2468 char *cmd, *ptr, *arg;
2469 STRLEN len = strlen(command) + 1;
2471 for (index = 0; (ptr = (char*)args[index]) != NULL; ++index)
2472 len += strlen(ptr) + 1;
2474 New(1310, cmd, len, char);
2476 strcpy(ptr, command);
2478 for (index = 0; (arg = (char*)args[index]) != NULL; ++index) {
2488 qualified_path(const char *cmd)
2492 char *fullcmd, *curfullcmd;
2498 fullcmd = (char*)cmd;
2500 if (*fullcmd == '/' || *fullcmd == '\\')
2507 pathstr = win32_getenv("PATH");
2508 New(0, fullcmd, MAX_PATH+1, char);
2509 curfullcmd = fullcmd;
2514 /* start by appending the name to the current prefix */
2515 strcpy(curfullcmd, cmd);
2516 curfullcmd += cmdlen;
2518 /* if it doesn't end with '.', or has no extension, try adding
2519 * a trailing .exe first */
2520 if (cmd[cmdlen-1] != '.'
2521 && (cmdlen < 4 || cmd[cmdlen-4] != '.'))
2523 strcpy(curfullcmd, ".exe");
2524 res = GetFileAttributes(fullcmd);
2525 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
2530 /* that failed, try the bare name */
2531 res = GetFileAttributes(fullcmd);
2532 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
2535 /* quit if no other path exists, or if cmd already has path */
2536 if (!pathstr || !*pathstr || has_slash)
2539 /* skip leading semis */
2540 while (*pathstr == ';')
2543 /* build a new prefix from scratch */
2544 curfullcmd = fullcmd;
2545 while (*pathstr && *pathstr != ';') {
2546 if (*pathstr == '"') { /* foo;"baz;etc";bar */
2547 pathstr++; /* skip initial '"' */
2548 while (*pathstr && *pathstr != '"') {
2549 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
2550 *curfullcmd++ = *pathstr;
2554 pathstr++; /* skip trailing '"' */
2557 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
2558 *curfullcmd++ = *pathstr;
2563 pathstr++; /* skip trailing semi */
2564 if (curfullcmd > fullcmd /* append a dir separator */
2565 && curfullcmd[-1] != '/' && curfullcmd[-1] != '\\')
2567 *curfullcmd++ = '\\';
2575 /* The following are just place holders.
2576 * Some hosts may provide and environment that the OS is
2577 * not tracking, therefore, these host must provide that
2578 * environment and the current directory to CreateProcess
2588 free_childenv(void* d)
2599 free_childdir(char* d)
2604 /* XXX this needs to be made more compatible with the spawnvp()
2605 * provided by the various RTLs. In particular, searching for
2606 * *.{com,bat,cmd} files (as done by the RTLs) is unimplemented.
2607 * This doesn't significantly affect perl itself, because we
2608 * always invoke things using PERL5SHELL if a direct attempt to
2609 * spawn the executable fails.
2611 * XXX splitting and rejoining the commandline between do_aspawn()
2612 * and win32_spawnvp() could also be avoided.
2616 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
2618 #ifdef USE_RTL_SPAWNVP
2619 return spawnvp(mode, cmdname, (char * const *)argv);
2625 STARTUPINFO StartupInfo;
2626 PROCESS_INFORMATION ProcessInformation;
2629 char *cmd = create_command_line(cmdname, strcmp(cmdname, argv[0]) == 0
2631 char *fullcmd = Nullch;
2633 env = PerlEnv_get_childenv();
2634 dir = PerlEnv_get_childdir();
2637 case P_NOWAIT: /* asynch + remember result */
2638 if (w32_num_children >= MAXIMUM_WAIT_OBJECTS) {
2644 case P_WAIT: /* synchronous execution */
2646 default: /* invalid mode */
2651 memset(&StartupInfo,0,sizeof(StartupInfo));
2652 StartupInfo.cb = sizeof(StartupInfo);
2653 StartupInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
2654 StartupInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
2655 StartupInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
2656 if (StartupInfo.hStdInput != INVALID_HANDLE_VALUE &&
2657 StartupInfo.hStdOutput != INVALID_HANDLE_VALUE &&
2658 StartupInfo.hStdError != INVALID_HANDLE_VALUE)
2660 StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
2663 create |= CREATE_NEW_CONSOLE;
2667 if (!CreateProcess(cmdname, /* search PATH to find executable */
2668 cmd, /* executable, and its arguments */
2669 NULL, /* process attributes */
2670 NULL, /* thread attributes */
2671 TRUE, /* inherit handles */
2672 create, /* creation flags */
2673 (LPVOID)env, /* inherit environment */
2674 dir, /* inherit cwd */
2676 &ProcessInformation))
2678 /* initial NULL argument to CreateProcess() does a PATH
2679 * search, but it always first looks in the directory
2680 * where the current process was started, which behavior
2681 * is undesirable for backward compatibility. So we
2682 * jump through our own hoops by picking out the path
2683 * we really want it to use. */
2685 fullcmd = qualified_path(cmdname);
2696 if (mode == P_NOWAIT) {
2697 /* asynchronous spawn -- store handle, return PID */
2698 w32_child_handles[w32_num_children] = ProcessInformation.hProcess;
2699 w32_child_pids[w32_num_children] = ProcessInformation.dwProcessId;
2700 ret = (int)ProcessInformation.dwProcessId;
2705 WaitForSingleObject(ProcessInformation.hProcess, INFINITE);
2706 GetExitCodeProcess(ProcessInformation.hProcess, &status);
2708 CloseHandle(ProcessInformation.hProcess);
2711 CloseHandle(ProcessInformation.hThread);
2714 PerlEnv_free_childenv(env);
2715 PerlEnv_free_childdir(dir);
2723 win32_execv(const char *cmdname, const char *const *argv)
2725 return execv(cmdname, (char *const *)argv);
2729 win32_execvp(const char *cmdname, const char *const *argv)
2731 return execvp(cmdname, (char *const *)argv);
2735 win32_perror(const char *str)
2741 win32_setbuf(FILE *pf, char *buf)
2747 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
2749 return setvbuf(pf, buf, type, size);
2753 win32_flushall(void)
2759 win32_fcloseall(void)
2765 win32_fgets(char *s, int n, FILE *pf)
2767 return fgets(s, n, pf);
2777 win32_fgetc(FILE *pf)
2783 win32_putc(int c, FILE *pf)
2789 win32_puts(const char *s)
2801 win32_putchar(int c)
2808 #ifndef USE_PERL_SBRK
2810 static char *committed = NULL;
2811 static char *base = NULL;
2812 static char *reserved = NULL;
2813 static char *brk = NULL;
2814 static DWORD pagesize = 0;
2815 static DWORD allocsize = 0;
2823 GetSystemInfo(&info);
2824 /* Pretend page size is larger so we don't perpetually
2825 * call the OS to commit just one page ...
2827 pagesize = info.dwPageSize << 3;
2828 allocsize = info.dwAllocationGranularity;
2830 /* This scheme fails eventually if request for contiguous
2831 * block is denied so reserve big blocks - this is only
2832 * address space not memory ...
2834 if (brk+need >= reserved)
2836 DWORD size = 64*1024*1024;
2838 if (committed && reserved && committed < reserved)
2840 /* Commit last of previous chunk cannot span allocations */
2841 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
2843 committed = reserved;
2845 /* Reserve some (more) space
2846 * Note this is a little sneaky, 1st call passes NULL as reserved
2847 * so lets system choose where we start, subsequent calls pass
2848 * the old end address so ask for a contiguous block
2850 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
2853 reserved = addr+size;
2868 if (brk > committed)
2870 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
2871 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
2886 win32_malloc(size_t size)
2888 return malloc(size);
2892 win32_calloc(size_t numitems, size_t size)
2894 return calloc(numitems,size);
2898 win32_realloc(void *block, size_t size)
2900 return realloc(block,size);
2904 win32_free(void *block)
2911 win32_open_osfhandle(long handle, int flags)
2913 return _open_osfhandle(handle, flags);
2917 win32_get_osfhandle(int fd)
2919 return _get_osfhandle(fd);
2923 win32_dynaload(const char* filename)
2928 WCHAR wfilename[MAX_PATH];
2929 A2WHELPER(filename, wfilename, sizeof(wfilename));
2930 hModule = LoadLibraryExW(wfilename, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
2933 hModule = LoadLibraryExA(filename, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
2939 win32_add_host(char *nameId, void *data)
2942 * This must be called before the script is parsed,
2943 * therefore no locking of threads is needed
2946 struct host_link *link;
2947 New(1314, link, 1, struct host_link);
2948 link->host_data = data;
2949 link->nameId = nameId;
2950 link->next = w32_host_link;
2951 w32_host_link = link;
2956 win32_get_host_data(char *nameId)
2959 struct host_link *link = w32_host_link;
2961 if(strEQ(link->nameId, nameId))
2962 return link->host_data;
2976 SV *sv = sv_newmortal();
2977 /* Make one call with zero size - return value is required size */
2978 DWORD len = GetCurrentDirectory((DWORD)0,NULL);
2979 SvUPGRADE(sv,SVt_PV);
2981 SvCUR(sv) = GetCurrentDirectory((DWORD) SvLEN(sv), SvPVX(sv));
2984 * then it worked, set PV valid,
2985 * else leave it 'undef'
3001 Perl_croak(aTHX_ "usage: Win32::SetCurrentDirectory($cwd)");
3002 if (SetCurrentDirectory(SvPV_nolen(ST(0))))
3009 XS(w32_GetNextAvailDrive)
3013 char root[] = "_:\\";
3018 if (GetDriveType(root) == 1) {
3027 XS(w32_GetLastError)
3031 XSRETURN_IV(GetLastError());
3035 XS(w32_SetLastError)
3039 Perl_croak(aTHX_ "usage: Win32::SetLastError($error)");
3040 SetLastError(SvIV(ST(0)));
3048 char *name = w32_getlogin_buffer;
3049 DWORD size = sizeof(w32_getlogin_buffer);
3051 if (GetUserName(name,&size)) {
3052 /* size includes NULL */
3053 ST(0) = sv_2mortal(newSVpvn(name,size-1));
3063 char name[MAX_COMPUTERNAME_LENGTH+1];
3064 DWORD size = sizeof(name);
3066 if (GetComputerName(name,&size)) {
3067 /* size does NOT include NULL :-( */
3068 ST(0) = sv_2mortal(newSVpvn(name,size));
3079 HINSTANCE hNetApi32 = LoadLibrary("netapi32.dll");
3080 DWORD (__stdcall *pfnNetApiBufferFree)(LPVOID Buffer);
3081 DWORD (__stdcall *pfnNetWkstaGetInfo)(LPWSTR servername, DWORD level,
3085 pfnNetApiBufferFree = (DWORD (__stdcall *)(void *))
3086 GetProcAddress(hNetApi32, "NetApiBufferFree");
3087 pfnNetWkstaGetInfo = (DWORD (__stdcall *)(LPWSTR, DWORD, void *))
3088 GetProcAddress(hNetApi32, "NetWkstaGetInfo");
3091 if (hNetApi32 && pfnNetWkstaGetInfo && pfnNetApiBufferFree) {
3092 /* this way is more reliable, in case user has a local account. */
3094 DWORD dnamelen = sizeof(dname);
3096 DWORD wki100_platform_id;
3097 LPWSTR wki100_computername;
3098 LPWSTR wki100_langroup;
3099 DWORD wki100_ver_major;
3100 DWORD wki100_ver_minor;
3102 /* NERR_Success *is* 0*/
3103 if (0 == pfnNetWkstaGetInfo(NULL, 100, &pwi)) {
3104 if (pwi->wki100_langroup && *(pwi->wki100_langroup)) {
3105 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_langroup,
3106 -1, (LPSTR)dname, dnamelen, NULL, NULL);
3109 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_computername,
3110 -1, (LPSTR)dname, dnamelen, NULL, NULL);
3112 pfnNetApiBufferFree(pwi);
3113 FreeLibrary(hNetApi32);
3116 FreeLibrary(hNetApi32);
3119 /* Win95 doesn't have NetWksta*(), so do it the old way */
3121 DWORD size = sizeof(name);
3123 FreeLibrary(hNetApi32);
3124 if (GetUserName(name,&size)) {
3126 DWORD sidlen = sizeof(sid);
3128 DWORD dnamelen = sizeof(dname);
3130 if (LookupAccountName(NULL, name, (PSID)&sid, &sidlen,
3131 dname, &dnamelen, &snu)) {
3132 XSRETURN_PV(dname); /* all that for this */
3144 DWORD flags, filecomplen;
3145 if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
3146 &flags, fsname, sizeof(fsname))) {
3147 if (GIMME_V == G_ARRAY) {
3148 XPUSHs(sv_2mortal(newSVpvn(fsname,strlen(fsname))));
3149 XPUSHs(sv_2mortal(newSViv(flags)));
3150 XPUSHs(sv_2mortal(newSViv(filecomplen)));
3155 XSRETURN_PV(fsname);
3161 XS(w32_GetOSVersion)
3164 OSVERSIONINFO osver;
3166 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
3167 if (GetVersionEx(&osver)) {
3168 XPUSHs(newSVpvn(osver.szCSDVersion, strlen(osver.szCSDVersion)));
3169 XPUSHs(newSViv(osver.dwMajorVersion));
3170 XPUSHs(newSViv(osver.dwMinorVersion));
3171 XPUSHs(newSViv(osver.dwBuildNumber));
3172 XPUSHs(newSViv(osver.dwPlatformId));
3184 XSRETURN_IV(IsWinNT());
3192 XSRETURN_IV(IsWin95());
3196 XS(w32_FormatMessage)
3203 Perl_croak(aTHX_ "usage: Win32::FormatMessage($errno)");
3205 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
3206 &source, SvIV(ST(0)), 0,
3207 msgbuf, sizeof(msgbuf)-1, NULL))
3208 XSRETURN_PV(msgbuf);
3218 PROCESS_INFORMATION stProcInfo;
3219 STARTUPINFO stStartInfo;
3220 BOOL bSuccess = FALSE;
3223 Perl_croak(aTHX_ "usage: Win32::Spawn($cmdName, $args, $PID)");
3225 cmd = SvPV_nolen(ST(0));
3226 args = SvPV_nolen(ST(1));
3228 memset(&stStartInfo, 0, sizeof(stStartInfo)); /* Clear the block */
3229 stStartInfo.cb = sizeof(stStartInfo); /* Set the structure size */
3230 stStartInfo.dwFlags = STARTF_USESHOWWINDOW; /* Enable wShowWindow control */
3231 stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE; /* Start min (normal) */
3234 cmd, /* Image path */
3235 args, /* Arguments for command line */
3236 NULL, /* Default process security */
3237 NULL, /* Default thread security */
3238 FALSE, /* Must be TRUE to use std handles */
3239 NORMAL_PRIORITY_CLASS, /* No special scheduling */
3240 NULL, /* Inherit our environment block */
3241 NULL, /* Inherit our currrent directory */
3242 &stStartInfo, /* -> Startup info */
3243 &stProcInfo)) /* <- Process info (if OK) */
3245 CloseHandle(stProcInfo.hThread);/* library source code does this. */
3246 sv_setiv(ST(2), stProcInfo.dwProcessId);
3249 XSRETURN_IV(bSuccess);
3253 XS(w32_GetTickCount)
3256 DWORD msec = GetTickCount();
3264 XS(w32_GetShortPathName)
3271 Perl_croak(aTHX_ "usage: Win32::GetShortPathName($longPathName)");
3273 shortpath = sv_mortalcopy(ST(0));
3274 SvUPGRADE(shortpath, SVt_PV);
3275 /* src == target is allowed */
3277 len = GetShortPathName(SvPVX(shortpath),
3280 } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
3282 SvCUR_set(shortpath,len);
3290 XS(w32_GetFullPathName)
3299 Perl_croak(aTHX_ "usage: Win32::GetFullPathName($filename)");
3302 fullpath = sv_mortalcopy(filename);
3303 SvUPGRADE(fullpath, SVt_PV);
3305 len = GetFullPathName(SvPVX(filename),
3309 } while (len >= SvLEN(fullpath) && sv_grow(fullpath,len+1));
3311 if (GIMME_V == G_ARRAY) {
3313 XST_mPV(1,filepart);
3314 len = filepart - SvPVX(fullpath);
3317 SvCUR_set(fullpath,len);
3325 XS(w32_GetLongPathName)
3329 char tmpbuf[MAX_PATH+1];
3334 Perl_croak(aTHX_ "usage: Win32::GetLongPathName($pathname)");
3337 pathstr = SvPV(path,len);
3338 strcpy(tmpbuf, pathstr);
3339 pathstr = win32_longpath(tmpbuf);
3341 ST(0) = sv_2mortal(newSVpvn(pathstr, strlen(pathstr)));
3352 Perl_croak(aTHX_ "usage: Win32::Sleep($milliseconds)");
3362 Perl_croak(aTHX_ "usage: Win32::CopyFile($from, $to, $overwrite)");
3363 if (CopyFile(SvPV_nolen(ST(0)), SvPV_nolen(ST(1)), !SvTRUE(ST(2))))
3369 Perl_init_os_extras(void)
3372 char *file = __FILE__;
3375 w32_perlshell_tokens = Nullch;
3376 w32_perlshell_items = -1;
3377 w32_fdpid = newAV(); /* XXX needs to be in Perl_win32_init()? */
3378 New(1313, w32_children, 1, child_tab);
3379 w32_num_children = 0;
3381 /* these names are Activeware compatible */
3382 newXS("Win32::GetCwd", w32_GetCwd, file);
3383 newXS("Win32::SetCwd", w32_SetCwd, file);
3384 newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
3385 newXS("Win32::GetLastError", w32_GetLastError, file);
3386 newXS("Win32::SetLastError", w32_SetLastError, file);
3387 newXS("Win32::LoginName", w32_LoginName, file);
3388 newXS("Win32::NodeName", w32_NodeName, file);
3389 newXS("Win32::DomainName", w32_DomainName, file);
3390 newXS("Win32::FsType", w32_FsType, file);
3391 newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
3392 newXS("Win32::IsWinNT", w32_IsWinNT, file);
3393 newXS("Win32::IsWin95", w32_IsWin95, file);
3394 newXS("Win32::FormatMessage", w32_FormatMessage, file);
3395 newXS("Win32::Spawn", w32_Spawn, file);
3396 newXS("Win32::GetTickCount", w32_GetTickCount, file);
3397 newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
3398 newXS("Win32::GetFullPathName", w32_GetFullPathName, file);
3399 newXS("Win32::GetLongPathName", w32_GetLongPathName, file);
3400 newXS("Win32::CopyFile", w32_CopyFile, file);
3401 newXS("Win32::Sleep", w32_Sleep, file);
3403 /* XXX Bloat Alert! The following Activeware preloads really
3404 * ought to be part of Win32::Sys::*, so they're not included
3407 /* LookupAccountName
3409 * InitiateSystemShutdown
3410 * AbortSystemShutdown
3411 * ExpandEnvrironmentStrings
3416 Perl_win32_init(int *argcp, char ***argvp)
3418 /* Disable floating point errors, Perl will trap the ones we
3419 * care about. VC++ RTL defaults to switching these off
3420 * already, but the Borland RTL doesn't. Since we don't
3421 * want to be at the vendor's whim on the default, we set
3422 * it explicitly here.
3424 #if !defined(_ALPHA_) && !defined(__GNUC__)
3425 _control87(MCW_EM, MCW_EM);
3432 Perl_sys_intern_dup(pTHX_ struct interp_intern *src, struct interp_intern *dst)
3434 dst->perlshell_tokens = Nullch;
3435 dst->perlshell_vec = (char**)NULL;
3436 dst->perlshell_items = 0;
3437 dst->fdpid = newAV();
3438 New(1313, dst->children, 1, child_tab);
3439 dst->children->num = 0;
3440 dst->hostlist = src->hostlist; /* XXX */
3441 dst->thr_intern.Winit_socktype = src->thr_intern.Winit_socktype;
3445 #ifdef USE_BINMODE_SCRIPTS
3448 win32_strip_return(SV *sv)
3450 char *s = SvPVX(sv);
3451 char *e = s+SvCUR(sv);
3455 if (*s == '\r' && s[1] == '\n')
3465 SvCUR_set(sv,d-SvPVX(sv));