This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
integrate cfgperl changes into mainline
[perl5.git] / win32 / win32.c
CommitLineData
68dc0745
PP
1/* WIN32.C
2 *
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.
6 *
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.
9 */
0a753a76
PP
10
11#define WIN32_LEAN_AND_MEAN
12#define WIN32IO_IS_STDIO
13#include <tchar.h>
a835ef8a
NIS
14#ifdef __GNUC__
15#define Win32_Winsock
16#endif
0a753a76
PP
17#include <windows.h>
18
e56670dd 19#ifndef __MINGW32__
9404a519
GS
20#include <lmcons.h>
21#include <lmerr.h>
22/* ugliness to work around a buggy struct definition in lmwksta.h */
23#undef LPTSTR
24#define LPTSTR LPWSTR
25#include <lmwksta.h>
26#undef LPTSTR
27#define LPTSTR LPSTR
e56670dd
GS
28#include <lmapibuf.h>
29#endif /* __MINGW32__ */
9404a519 30
68dc0745 31/* #include "config.h" */
0a753a76
PP
32
33#define PERLIO_NOT_STDIO 0
34#if !defined(PERLIO_IS_STDIO) && !defined(USE_SFIO)
35#define PerlIO FILE
36#endif
37
7a9ec5a3 38#include <sys/stat.h>
0a753a76
PP
39#include "EXTERN.h"
40#include "perl.h"
c69f6586
GS
41
42#define NO_XSLOCKS
43#ifdef PERL_OBJECT
44extern CPerlObj* pPerl;
45#endif
ad2e33dc 46#include "XSUB.h"
c69f6586
GS
47
48#include "Win32iop.h"
0a753a76 49#include <fcntl.h>
5b0d9cbe
NIS
50#ifndef __GNUC__
51/* assert.h conflicts with #define of assert in perl.h */
0a753a76 52#include <assert.h>
5b0d9cbe 53#endif
0a753a76
PP
54#include <string.h>
55#include <stdarg.h>
ad2e33dc 56#include <float.h>
ad0751ec 57#include <time.h>
3730b96e 58#if defined(_MSC_VER) || defined(__MINGW32__)
ad0751ec
GS
59#include <sys/utime.h>
60#else
61#include <utime.h>
62#endif
0a753a76 63
5b0d9cbe
NIS
64#ifdef __GNUC__
65/* Mingw32 defaults to globing command line
66 * So we turn it off like this:
67 */
68int _CRT_glob = 0;
69#endif
70
6890e559
GS
71#define EXECF_EXEC 1
72#define EXECF_SPAWN 2
73#define EXECF_SPAWN_NOWAIT 3
74
c69f6586 75#if defined(PERL_OBJECT)
e5a95ffb
GS
76#undef win32_get_privlib
77#define win32_get_privlib g_win32_get_privlib
00dc2f4f
GS
78#undef win32_get_sitelib
79#define win32_get_sitelib g_win32_get_sitelib
c69f6586
GS
80#undef do_aspawn
81#define do_aspawn g_do_aspawn
82#undef do_spawn
83#define do_spawn g_do_spawn
84#undef do_exec
85#define do_exec g_do_exec
c69f6586
GS
86#undef getlogin
87#define getlogin g_getlogin
88#endif
89
2d7a9237 90static DWORD os_id(void);
ce1da67e
GS
91static void get_shell(void);
92static long tokenize(char *str, char **dest, char ***destv);
4f63d024 93 int do_spawn2(pTHX_ char *cmd, int exectype);
e200fe59 94static BOOL has_shell_metachars(char *ptr);
2d7a9237 95static long filetime_to_clock(PFILETIME ft);
ad0751ec 96static BOOL filetime_from_time(PFILETIME ft, time_t t);
349ad1fe 97static char * get_emd_part(char **leading, char *trailing, ...);
0aaad0ff
GS
98static void remove_dead_process(long deceased);
99static long find_pid(int pid);
100static char * qualified_path(const char *cmd);
c69f6586 101
2d7a9237 102HANDLE w32_perldll_handle = INVALID_HANDLE_VALUE;
8ac9c18d 103char w32_module_name[MAX_PATH+1];
4b556e6c 104static DWORD w32_platform = (DWORD)-1;
50892819 105
26618a56
GS
106#ifdef USE_THREADS
107# ifdef USE_DECLSPEC_THREAD
108__declspec(thread) char strerror_buffer[512];
e34ffe5a 109__declspec(thread) char getlogin_buffer[128];
4b556e6c 110__declspec(thread) char w32_perllib_root[MAX_PATH+1];
26618a56
GS
111# ifdef HAVE_DES_FCRYPT
112__declspec(thread) char crypt_buffer[30];
113# endif
114# else
115# define strerror_buffer (thr->i.Wstrerror_buffer)
e34ffe5a 116# define getlogin_buffer (thr->i.Wgetlogin_buffer)
4b556e6c 117# define w32_perllib_root (thr->i.Ww32_perllib_root)
26618a56
GS
118# define crypt_buffer (thr->i.Wcrypt_buffer)
119# endif
120#else
4b556e6c
JD
121static char strerror_buffer[512];
122static char getlogin_buffer[128];
123static char w32_perllib_root[MAX_PATH+1];
26618a56 124# ifdef HAVE_DES_FCRYPT
4b556e6c 125static char crypt_buffer[30];
26618a56
GS
126# endif
127#endif
128
3fe9a6f1 129int
ba106d47
GS
130IsWin95(void)
131{
2d7a9237 132 return (os_id() == VER_PLATFORM_WIN32_WINDOWS);
3fe9a6f1
PP
133}
134
135int
ba106d47
GS
136IsWinNT(void)
137{
2d7a9237 138 return (os_id() == VER_PLATFORM_WIN32_NT);
3fe9a6f1 139}
0a753a76 140
349ad1fe 141/* *ptr is expected to point to valid allocated space (can't be NULL) */
00dc2f4f
GS
142char*
143GetRegStrFromKey(HKEY hkey, const char *lpszValueName, char** ptr, DWORD* lpDataLen)
349ad1fe
GS
144{
145 /* Retrieve a REG_SZ or REG_EXPAND_SZ from the registry */
00dc2f4f
GS
146 HKEY handle;
147 DWORD type;
148 const char *subkey = "Software\\Perl";
349ad1fe 149 char *str = Nullch;
00dc2f4f
GS
150 long retval;
151
152 retval = RegOpenKeyEx(hkey, subkey, 0, KEY_READ, &handle);
349ad1fe 153 if (retval == ERROR_SUCCESS) {
00dc2f4f 154 retval = RegQueryValueEx(handle, lpszValueName, 0, &type, NULL, lpDataLen);
ba3eb2af 155 if (retval == ERROR_SUCCESS && type == REG_SZ) {
349ad1fe
GS
156 Renew(*ptr, *lpDataLen, char);
157 retval = RegQueryValueEx(handle, lpszValueName, 0, NULL,
158 (PBYTE)*ptr, lpDataLen);
159 if (retval == ERROR_SUCCESS)
160 str = *ptr;
00dc2f4f
GS
161 }
162 RegCloseKey(handle);
163 }
349ad1fe 164 return str;
00dc2f4f
GS
165}
166
349ad1fe 167/* *ptr is expected to point to valid allocated space (can't be NULL) */
00dc2f4f
GS
168char*
169GetRegStr(const char *lpszValueName, char** ptr, DWORD* lpDataLen)
170{
349ad1fe
GS
171 char *str = GetRegStrFromKey(HKEY_CURRENT_USER, lpszValueName, ptr, lpDataLen);
172 if (!str)
173 str = GetRegStrFromKey(HKEY_LOCAL_MACHINE, lpszValueName, ptr, lpDataLen);
174 return str;
00dc2f4f
GS
175}
176
349ad1fe 177/* *prev_path is expected to point to valid allocated space (can't be NULL) */
e5a95ffb 178static char *
349ad1fe 179get_emd_part(char **prev_path, char *trailing_path, ...)
00dc2f4f 180{
dc9e4912 181 char base[10];
e5a95ffb 182 va_list ap;
e24c7c18 183 char mod_name[MAX_PATH+1];
00dc2f4f 184 char *ptr;
e5a95ffb
GS
185 char *optr;
186 char *strip;
187 int oldsize, newsize;
188
189 va_start(ap, trailing_path);
190 strip = va_arg(ap, char *);
191
cceca5ed
GS
192 sprintf(base, "%5.3f",
193 (double)PERL_REVISION + ((double)PERL_VERSION / (double)1000));
dc9e4912 194
8ac9c18d
GS
195 if (!*w32_module_name) {
196 GetModuleFileName((HMODULE)((w32_perldll_handle == INVALID_HANDLE_VALUE)
197 ? GetModuleHandle(NULL)
198 : w32_perldll_handle),
199 w32_module_name, sizeof(w32_module_name));
200
201 /* try to get full path to binary (which may be mangled when perl is
202 * run from a 16-bit app) */
203 /*PerlIO_printf(PerlIO_stderr(), "Before %s\n", w32_module_name);*/
204 (void)win32_longpath(w32_module_name);
205 /*PerlIO_printf(PerlIO_stderr(), "After %s\n", w32_module_name);*/
206
207 /* normalize to forward slashes */
208 ptr = w32_module_name;
209 while (*ptr) {
210 if (*ptr == '\\')
211 *ptr = '/';
212 ++ptr;
213 }
95140b98 214 }
8ac9c18d 215 strcpy(mod_name, w32_module_name);
95140b98 216 ptr = strrchr(mod_name, '/');
e5a95ffb
GS
217 while (ptr && strip) {
218 /* look for directories to skip back */
219 optr = ptr;
00dc2f4f 220 *ptr = '\0';
95140b98 221 ptr = strrchr(mod_name, '/');
1c39adb2
GS
222 /* avoid stripping component if there is no slash,
223 * or it doesn't match ... */
e5a95ffb 224 if (!ptr || stricmp(ptr+1, strip) != 0) {
1c39adb2
GS
225 /* ... but not if component matches 5.00X* */
226 if (!ptr || !(*strip == '5' && *(ptr+1) == '5'
227 && strncmp(strip, base, 5) == 0
228 && strncmp(ptr+1, base, 5) == 0))
95140b98
GS
229 {
230 *optr = '/';
80252599
GS
231 ptr = optr;
232 }
00dc2f4f 233 }
e5a95ffb 234 strip = va_arg(ap, char *);
00dc2f4f 235 }
e5a95ffb
GS
236 if (!ptr) {
237 ptr = mod_name;
238 *ptr++ = '.';
95140b98 239 *ptr = '/';
00dc2f4f 240 }
e5a95ffb
GS
241 va_end(ap);
242 strcpy(++ptr, trailing_path);
243
dc9e4912 244 /* only add directory if it exists */
349ad1fe 245 if (GetFileAttributes(mod_name) != (DWORD) -1) {
dc9e4912
GS
246 /* directory exists */
247 newsize = strlen(mod_name) + 1;
349ad1fe
GS
248 oldsize = strlen(*prev_path) + 1;
249 newsize += oldsize; /* includes plus 1 for ';' */
250 Renew(*prev_path, newsize, char);
251 (*prev_path)[oldsize-1] = ';';
252 strcpy(&(*prev_path)[oldsize], mod_name);
cf11f4bf 253 return *prev_path;
00dc2f4f 254 }
00dc2f4f 255
cf11f4bf 256 return Nullch;
00dc2f4f
GS
257}
258
259char *
4f63d024 260win32_get_privlib(pTHX_ char *pl)
00dc2f4f 261{
e5a95ffb
GS
262 char *stdlib = "lib";
263 char buffer[MAX_PATH+1];
349ad1fe 264 char **path;
e5a95ffb 265 DWORD datalen;
349ad1fe 266 SV *sv = sv_2mortal(newSVpvn("",127));
00dc2f4f 267
e5a95ffb
GS
268 /* $stdlib = $HKCU{"lib-$]"} || $HKLM{"lib-$]"} || $HKCU{"lib"} || $HKLM{"lib"} || ""; */
269 sprintf(buffer, "%s-%s", stdlib, pl);
349ad1fe
GS
270 path = &SvPVX(sv);
271 if (!GetRegStr(buffer, path, &datalen))
272 (void)GetRegStr(stdlib, path, &datalen);
00dc2f4f 273
e5a95ffb 274 /* $stdlib .= ";$EMD/../../lib" */
349ad1fe
GS
275 (void)get_emd_part(path, stdlib, ARCHNAME, "bin", Nullch);
276 SvCUR_set(sv, strlen(*path));
277 SvLEN_set(sv, SvCUR(sv)+1);
278 return SvPVX(sv);
00dc2f4f
GS
279}
280
68dc0745 281char *
4f63d024 282win32_get_sitelib(pTHX_ char *pl)
00dc2f4f 283{
e5a95ffb
GS
284 char *sitelib = "sitelib";
285 char regstr[40];
e24c7c18 286 char pathstr[MAX_PATH+1];
e5a95ffb 287 DWORD datalen;
349ad1fe
GS
288 char **path1, *str1 = Nullch;
289 char **path2, *str2 = Nullch;
e5a95ffb 290 int len, newsize;
349ad1fe
GS
291 SV *sv1 = sv_2mortal(newSVpvn("",127));
292 SV *sv2 = sv_2mortal(newSVpvn("",127));
00dc2f4f
GS
293
294 /* $HKCU{"sitelib-$]"} || $HKLM{"sitelib-$]"} . ---; */
e5a95ffb 295 sprintf(regstr, "%s-%s", sitelib, pl);
349ad1fe
GS
296 path1 = &SvPVX(sv1);
297 (void)GetRegStr(regstr, path1, &datalen);
e5a95ffb
GS
298
299 /* $sitelib .=
300 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/site/$]/lib"; */
95140b98 301 sprintf(pathstr, "site/%s/lib", pl);
349ad1fe 302 str1 = get_emd_part(path1, pathstr, ARCHNAME, "bin", pl, Nullch);
cf11f4bf
GS
303 if (!str1 && strlen(pl) == 7) {
304 /* pl may have been SUBVERSION-specific; try again without
305 * SUBVERSION */
306 sprintf(pathstr, "site/%.5s/lib", pl);
307 str1 = get_emd_part(path1, pathstr, ARCHNAME, "bin", pl, Nullch);
308 }
00dc2f4f
GS
309
310 /* $HKCU{'sitelib'} || $HKLM{'sitelib'} . ---; */
349ad1fe
GS
311 path2 = &SvPVX(sv2);
312 (void)GetRegStr(sitelib, path2, &datalen);
00dc2f4f 313
e5a95ffb
GS
314 /* $sitelib .=
315 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/site/lib"; */
349ad1fe 316 str2 = get_emd_part(path2, "site/lib", ARCHNAME, "bin", pl, Nullch);
00dc2f4f 317
349ad1fe
GS
318 SvCUR_set(sv1, strlen(*path1));
319 SvLEN_set(sv1, SvCUR(sv1)+1);
320 SvCUR_set(sv2, strlen(*path2));
321 SvLEN_set(sv2, SvCUR(sv2)+1);
e5a95ffb 322
349ad1fe
GS
323 if (!str1)
324 return *path2;
325 if (!str2)
326 return *path1;
e5a95ffb 327
349ad1fe
GS
328 sv_catpvn(sv1, ";", 1);
329 sv_catsv(sv1, sv2);
e5a95ffb 330
349ad1fe 331 return SvPVX(sv1);
68dc0745 332}
0a753a76 333
b4793f7f 334
2d7a9237 335static BOOL
e200fe59 336has_shell_metachars(char *ptr)
68dc0745
PP
337{
338 int inquote = 0;
339 char quote = '\0';
340
341 /*
342 * Scan string looking for redirection (< or >) or pipe
e200fe59
JD
343 * characters (|) that are not in a quoted string.
344 * Shell variable interpolation (%VAR%) can also happen inside strings.
68dc0745 345 */
9404a519 346 while (*ptr) {
68dc0745 347 switch(*ptr) {
e200fe59
JD
348 case '%':
349 return TRUE;
68dc0745
PP
350 case '\'':
351 case '\"':
9404a519
GS
352 if (inquote) {
353 if (quote == *ptr) {
68dc0745
PP
354 inquote = 0;
355 quote = '\0';
0a753a76 356 }
68dc0745
PP
357 }
358 else {
359 quote = *ptr;
360 inquote++;
361 }
362 break;
363 case '>':
364 case '<':
365 case '|':
9404a519 366 if (!inquote)
68dc0745
PP
367 return TRUE;
368 default:
369 break;
0a753a76 370 }
68dc0745
PP
371 ++ptr;
372 }
373 return FALSE;
0a753a76
PP
374}
375
c69f6586 376#if !defined(PERL_OBJECT)
68dc0745
PP
377/* since the current process environment is being updated in util.c
378 * the library functions will get the correct environment
379 */
380PerlIO *
4f63d024 381Perl_my_popen(pTHX_ char *cmd, char *mode)
0a753a76
PP
382{
383#ifdef FIXCMD
68dc0745
PP
384#define fixcmd(x) { \
385 char *pspace = strchr((x),' '); \
386 if (pspace) { \
387 char *p = (x); \
388 while (p < pspace) { \
389 if (*p == '/') \
390 *p = '\\'; \
391 p++; \
392 } \
393 } \
394 }
0a753a76
PP
395#else
396#define fixcmd(x)
397#endif
68dc0745 398 fixcmd(cmd);
45bc9206 399 PERL_FLUSHALL_FOR_CHILD;
0a753a76 400 return win32_popen(cmd, mode);
0a753a76
PP
401}
402
68dc0745 403long
4f63d024 404Perl_my_pclose(pTHX_ PerlIO *fp)
0a753a76
PP
405{
406 return win32_pclose(fp);
407}
c69f6586 408#endif
0a753a76 409
8b10511d 410static DWORD
2d7a9237 411os_id(void)
0a753a76 412{
8b10511d 413 static OSVERSIONINFO osver;
0a753a76 414
2d7a9237 415 if (osver.dwPlatformId != w32_platform) {
8b10511d
GS
416 memset(&osver, 0, sizeof(OSVERSIONINFO));
417 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
418 GetVersionEx(&osver);
2d7a9237 419 w32_platform = osver.dwPlatformId;
8b10511d 420 }
2d7a9237 421 return (w32_platform);
0a753a76
PP
422}
423
ce1da67e
GS
424/* Tokenize a string. Words are null-separated, and the list
425 * ends with a doubled null. Any character (except null and
426 * including backslash) may be escaped by preceding it with a
427 * backslash (the backslash will be stripped).
428 * Returns number of words in result buffer.
429 */
430static long
431tokenize(char *str, char **dest, char ***destv)
432{
433 char *retstart = Nullch;
434 char **retvstart = 0;
435 int items = -1;
436 if (str) {
437 int slen = strlen(str);
438 register char *ret;
439 register char **retv;
440 New(1307, ret, slen+2, char);
441 New(1308, retv, (slen+3)/2, char*);
442
443 retstart = ret;
444 retvstart = retv;
445 *retv = ret;
446 items = 0;
447 while (*str) {
448 *ret = *str++;
449 if (*ret == '\\' && *str)
450 *ret = *str++;
451 else if (*ret == ' ') {
452 while (*str == ' ')
453 str++;
454 if (ret == retstart)
455 ret--;
456 else {
457 *ret = '\0';
458 ++items;
459 if (*str)
460 *++retv = ret+1;
461 }
462 }
463 else if (!*str)
464 ++items;
465 ret++;
466 }
467 retvstart[items] = Nullch;
468 *ret++ = '\0';
469 *ret = '\0';
470 }
471 *dest = retstart;
472 *destv = retvstart;
473 return items;
474}
475
476static void
2d7a9237 477get_shell(void)
0a753a76 478{
ce1da67e 479 if (!w32_perlshell_tokens) {
174c211a
GS
480 /* we don't use COMSPEC here for two reasons:
481 * 1. the same reason perl on UNIX doesn't use SHELL--rampant and
482 * uncontrolled unportability of the ensuing scripts.
483 * 2. PERL5SHELL could be set to a shell that may not be fit for
484 * interactive use (which is what most programs look in COMSPEC
485 * for).
486 */
ce1da67e
GS
487 char* defaultshell = (IsWinNT() ? "cmd.exe /x/c" : "command.com /c");
488 char *usershell = getenv("PERL5SHELL");
489 w32_perlshell_items = tokenize(usershell ? usershell : defaultshell,
490 &w32_perlshell_tokens,
491 &w32_perlshell_vec);
68dc0745 492 }
0a753a76
PP
493}
494
68dc0745 495int
4f63d024 496do_aspawn(pTHX_ void *vreally, void **vmark, void **vsp)
0a753a76 497{
2d7a9237
GS
498 SV *really = (SV*)vreally;
499 SV **mark = (SV**)vmark;
500 SV **sp = (SV**)vsp;
68dc0745 501 char **argv;
2d7a9237 502 char *str;
68dc0745 503 int status;
2d7a9237 504 int flag = P_WAIT;
68dc0745 505 int index = 0;
68dc0745 506
2d7a9237
GS
507 if (sp <= mark)
508 return -1;
68dc0745 509
ce1da67e
GS
510 get_shell();
511 New(1306, argv, (sp - mark) + w32_perlshell_items + 2, char*);
2d7a9237
GS
512
513 if (SvNIOKp(*(mark+1)) && !SvPOKp(*(mark+1))) {
514 ++mark;
515 flag = SvIVx(*mark);
68dc0745
PP
516 }
517
9404a519 518 while (++mark <= sp) {
bb897dfc 519 if (*mark && (str = SvPV_nolen(*mark)))
2d7a9237
GS
520 argv[index++] = str;
521 else
522 argv[index++] = "";
68dc0745
PP
523 }
524 argv[index++] = 0;
525
2d7a9237 526 status = win32_spawnvp(flag,
bb897dfc 527 (const char*)(really ? SvPV_nolen(really) : argv[0]),
2d7a9237
GS
528 (const char* const*)argv);
529
80252599 530 if (status < 0 && (errno == ENOEXEC || errno == ENOENT)) {
2d7a9237 531 /* possible shell-builtin, invoke with shell */
ce1da67e
GS
532 int sh_items;
533 sh_items = w32_perlshell_items;
2d7a9237
GS
534 while (--index >= 0)
535 argv[index+sh_items] = argv[index];
ce1da67e
GS
536 while (--sh_items >= 0)
537 argv[sh_items] = w32_perlshell_vec[sh_items];
2d7a9237
GS
538
539 status = win32_spawnvp(flag,
bb897dfc 540 (const char*)(really ? SvPV_nolen(really) : argv[0]),
2d7a9237
GS
541 (const char* const*)argv);
542 }
68dc0745 543
50892819
GS
544 if (flag != P_NOWAIT) {
545 if (status < 0) {
b28d0864 546 if (PL_dowarn)
4f63d024 547 Perl_warn(aTHX_ "Can't spawn \"%s\": %s", argv[0], strerror(errno));
50892819
GS
548 status = 255 * 256;
549 }
550 else
551 status *= 256;
b28d0864 552 PL_statusvalue = status;
5aabfad6 553 }
ce1da67e 554 Safefree(argv);
50892819 555 return (status);
68dc0745
PP
556}
557
c69f6586 558int
4f63d024 559do_spawn2(pTHX_ char *cmd, int exectype)
68dc0745
PP
560{
561 char **a;
562 char *s;
563 char **argv;
564 int status = -1;
565 BOOL needToTry = TRUE;
2d7a9237 566 char *cmd2;
68dc0745 567
2d7a9237
GS
568 /* Save an extra exec if possible. See if there are shell
569 * metacharacters in it */
e200fe59 570 if (!has_shell_metachars(cmd)) {
fc36a67e
PP
571 New(1301,argv, strlen(cmd) / 2 + 2, char*);
572 New(1302,cmd2, strlen(cmd) + 1, char);
68dc0745
PP
573 strcpy(cmd2, cmd);
574 a = argv;
575 for (s = cmd2; *s;) {
de030af3 576 while (*s && isSPACE(*s))
68dc0745
PP
577 s++;
578 if (*s)
579 *(a++) = s;
de030af3 580 while (*s && !isSPACE(*s))
68dc0745 581 s++;
9404a519 582 if (*s)
68dc0745 583 *s++ = '\0';
0a753a76 584 }
68dc0745 585 *a = Nullch;
ce1da67e 586 if (argv[0]) {
6890e559
GS
587 switch (exectype) {
588 case EXECF_SPAWN:
589 status = win32_spawnvp(P_WAIT, argv[0],
590 (const char* const*)argv);
591 break;
592 case EXECF_SPAWN_NOWAIT:
593 status = win32_spawnvp(P_NOWAIT, argv[0],
594 (const char* const*)argv);
595 break;
596 case EXECF_EXEC:
597 status = win32_execvp(argv[0], (const char* const*)argv);
598 break;
599 }
2d7a9237 600 if (status != -1 || errno == 0)
68dc0745 601 needToTry = FALSE;
0a753a76 602 }
0a753a76 603 Safefree(argv);
68dc0745
PP
604 Safefree(cmd2);
605 }
2d7a9237 606 if (needToTry) {
ce1da67e
GS
607 char **argv;
608 int i = -1;
609 get_shell();
610 New(1306, argv, w32_perlshell_items + 2, char*);
611 while (++i < w32_perlshell_items)
612 argv[i] = w32_perlshell_vec[i];
2d7a9237
GS
613 argv[i++] = cmd;
614 argv[i] = Nullch;
6890e559
GS
615 switch (exectype) {
616 case EXECF_SPAWN:
617 status = win32_spawnvp(P_WAIT, argv[0],
618 (const char* const*)argv);
619 break;
620 case EXECF_SPAWN_NOWAIT:
621 status = win32_spawnvp(P_NOWAIT, argv[0],
622 (const char* const*)argv);
623 break;
624 case EXECF_EXEC:
625 status = win32_execvp(argv[0], (const char* const*)argv);
626 break;
627 }
ce1da67e
GS
628 cmd = argv[0];
629 Safefree(argv);
68dc0745 630 }
50892819
GS
631 if (exectype != EXECF_SPAWN_NOWAIT) {
632 if (status < 0) {
b28d0864 633 if (PL_dowarn)
4f63d024 634 Perl_warn(aTHX_ "Can't %s \"%s\": %s",
50892819
GS
635 (exectype == EXECF_EXEC ? "exec" : "spawn"),
636 cmd, strerror(errno));
637 status = 255 * 256;
638 }
639 else
640 status *= 256;
b28d0864 641 PL_statusvalue = status;
5aabfad6 642 }
50892819 643 return (status);
0a753a76
PP
644}
645
6890e559 646int
4f63d024 647do_spawn(pTHX_ char *cmd)
6890e559 648{
4f63d024 649 return do_spawn2(aTHX_ cmd, EXECF_SPAWN);
6890e559
GS
650}
651
2d7a9237 652int
4f63d024 653do_spawn_nowait(pTHX_ char *cmd)
2d7a9237 654{
4f63d024 655 return do_spawn2(aTHX_ cmd, EXECF_SPAWN_NOWAIT);
2d7a9237
GS
656}
657
6890e559 658bool
4f63d024 659Perl_do_exec(pTHX_ char *cmd)
6890e559 660{
4f63d024 661 do_spawn2(aTHX_ cmd, EXECF_EXEC);
6890e559
GS
662 return FALSE;
663}
664
68dc0745
PP
665/* The idea here is to read all the directory names into a string table
666 * (separated by nulls) and when one of the other dir functions is called
667 * return the pointer to the current file name.
668 */
669DIR *
ce2e26e5 670win32_opendir(char *filename)
0a753a76 671{
73c4f7a1 672 dTHX;
9404a519
GS
673 DIR *p;
674 long len;
675 long idx;
676 char scanname[MAX_PATH+3];
677 struct stat sbuf;
7fac1903
GS
678 WIN32_FIND_DATAA aFindData;
679 WIN32_FIND_DATAW wFindData;
9404a519 680 HANDLE fh;
7fac1903
GS
681 char buffer[MAX_PATH*2];
682 WCHAR wbuffer[MAX_PATH];
683 char* ptr;
9404a519
GS
684
685 len = strlen(filename);
686 if (len > MAX_PATH)
687 return NULL;
68dc0745
PP
688
689 /* check to see if filename is a directory */
69d3ab13 690 if (win32_stat(filename, &sbuf) < 0 || !S_ISDIR(sbuf.st_mode))
24caa93f 691 return NULL;
68dc0745 692
68dc0745 693 /* Get us a DIR structure */
fc36a67e 694 Newz(1303, p, 1, DIR);
9404a519 695 if (p == NULL)
68dc0745
PP
696 return NULL;
697
698 /* Create the search pattern */
699 strcpy(scanname, filename);
23db2e2d
GS
700
701 /* bare drive name means look in cwd for drive */
702 if (len == 2 && isALPHA(scanname[0]) && scanname[1] == ':') {
703 scanname[len++] = '.';
704 scanname[len++] = '/';
705 }
706 else if (scanname[len-1] != '/' && scanname[len-1] != '\\') {
9404a519 707 scanname[len++] = '/';
23db2e2d 708 }
9404a519
GS
709 scanname[len++] = '*';
710 scanname[len] = '\0';
68dc0745
PP
711
712 /* do the FindFirstFile call */
7fac1903
GS
713 if (USING_WIDE()) {
714 A2WHELPER(scanname, wbuffer, sizeof(wbuffer), GETINTERPMODE());
715 fh = FindFirstFileW(wbuffer, &wFindData);
716 }
717 else {
718 fh = FindFirstFileA(scanname, &aFindData);
719 }
9404a519 720 if (fh == INVALID_HANDLE_VALUE) {
21e72512
AB
721 /* FindFirstFile() fails on empty drives! */
722 if (GetLastError() == ERROR_FILE_NOT_FOUND)
723 return p;
724 Safefree( p);
68dc0745
PP
725 return NULL;
726 }
727
728 /* now allocate the first part of the string table for
729 * the filenames that we find.
730 */
7fac1903
GS
731 if (USING_WIDE()) {
732 W2AHELPER(wFindData.cFileName, buffer, sizeof(buffer), GETINTERPMODE());
733 ptr = buffer;
734 }
735 else {
736 ptr = aFindData.cFileName;
737 }
738 idx = strlen(ptr)+1;
fc36a67e 739 New(1304, p->start, idx, char);
9404a519 740 if (p->start == NULL)
4f63d024 741 Perl_croak_nocontext("opendir: malloc failed!\n");
7fac1903 742 strcpy(p->start, ptr);
68dc0745
PP
743 p->nfiles++;
744
745 /* loop finding all the files that match the wildcard
746 * (which should be all of them in this directory!).
747 * the variable idx should point one past the null terminator
748 * of the previous string found.
749 */
7fac1903
GS
750 while (USING_WIDE()
751 ? FindNextFileW(fh, &wFindData)
752 : FindNextFileA(fh, &aFindData)) {
753 if (USING_WIDE()) {
754 W2AHELPER(wFindData.cFileName, buffer, sizeof(buffer), GETINTERPMODE());
755 }
756 /* ptr is set above to the correct area */
757 len = strlen(ptr);
68dc0745
PP
758 /* bump the string table size by enough for the
759 * new name and it's null terminator
760 */
761 Renew(p->start, idx+len+1, char);
9404a519 762 if (p->start == NULL)
4f63d024 763 Perl_croak_nocontext("opendir: malloc failed!\n");
7fac1903 764 strcpy(&p->start[idx], ptr);
9404a519
GS
765 p->nfiles++;
766 idx += len+1;
767 }
768 FindClose(fh);
769 p->size = idx;
770 p->curr = p->start;
771 return p;
0a753a76
PP
772}
773
774
68dc0745
PP
775/* Readdir just returns the current string pointer and bumps the
776 * string pointer to the nDllExport entry.
777 */
778struct direct *
ce2e26e5 779win32_readdir(DIR *dirp)
0a753a76 780{
68dc0745
PP
781 int len;
782 static int dummy = 0;
0a753a76 783
68dc0745
PP
784 if (dirp->curr) {
785 /* first set up the structure to return */
786 len = strlen(dirp->curr);
787 strcpy(dirp->dirstr.d_name, dirp->curr);
788 dirp->dirstr.d_namlen = len;
0a753a76 789
68dc0745
PP
790 /* Fake an inode */
791 dirp->dirstr.d_ino = dummy++;
0a753a76 792
68dc0745
PP
793 /* Now set up for the nDllExport call to readdir */
794 dirp->curr += len + 1;
795 if (dirp->curr >= (dirp->start + dirp->size)) {
796 dirp->curr = NULL;
797 }
0a753a76 798
68dc0745
PP
799 return &(dirp->dirstr);
800 }
801 else
802 return NULL;
0a753a76
PP
803}
804
68dc0745
PP
805/* Telldir returns the current string pointer position */
806long
ce2e26e5 807win32_telldir(DIR *dirp)
0a753a76
PP
808{
809 return (long) dirp->curr;
810}
811
812
68dc0745
PP
813/* Seekdir moves the string pointer to a previously saved position
814 *(Saved by telldir).
815 */
816void
ce2e26e5 817win32_seekdir(DIR *dirp, long loc)
0a753a76
PP
818{
819 dirp->curr = (char *)loc;
820}
821
68dc0745
PP
822/* Rewinddir resets the string pointer to the start */
823void
ce2e26e5 824win32_rewinddir(DIR *dirp)
0a753a76
PP
825{
826 dirp->curr = dirp->start;
827}
828
68dc0745
PP
829/* free the memory allocated by opendir */
830int
ce2e26e5 831win32_closedir(DIR *dirp)
0a753a76
PP
832{
833 Safefree(dirp->start);
834 Safefree(dirp);
68dc0745 835 return 1;
0a753a76
PP
836}
837
838
68dc0745
PP
839/*
840 * various stubs
841 */
0a753a76
PP
842
843
68dc0745
PP
844/* Ownership
845 *
846 * Just pretend that everyone is a superuser. NT will let us know if
847 * we don\'t really have permission to do something.
848 */
0a753a76
PP
849
850#define ROOT_UID ((uid_t)0)
851#define ROOT_GID ((gid_t)0)
852
68dc0745
PP
853uid_t
854getuid(void)
0a753a76 855{
68dc0745 856 return ROOT_UID;
0a753a76
PP
857}
858
68dc0745
PP
859uid_t
860geteuid(void)
0a753a76 861{
68dc0745 862 return ROOT_UID;
0a753a76
PP
863}
864
68dc0745
PP
865gid_t
866getgid(void)
0a753a76 867{
68dc0745 868 return ROOT_GID;
0a753a76
PP
869}
870
68dc0745
PP
871gid_t
872getegid(void)
0a753a76 873{
68dc0745 874 return ROOT_GID;
0a753a76
PP
875}
876
68dc0745 877int
22239a37 878setuid(uid_t auid)
0a753a76 879{
22239a37 880 return (auid == ROOT_UID ? 0 : -1);
0a753a76
PP
881}
882
68dc0745 883int
22239a37 884setgid(gid_t agid)
0a753a76 885{
22239a37 886 return (agid == ROOT_GID ? 0 : -1);
0a753a76
PP
887}
888
e34ffe5a
GS
889char *
890getlogin(void)
891{
4f63d024 892 dTHX;
e34ffe5a
GS
893 char *buf = getlogin_buffer;
894 DWORD size = sizeof(getlogin_buffer);
895 if (GetUserName(buf,&size))
896 return buf;
897 return (char*)NULL;
898}
899
b990f8c8
GS
900int
901chown(const char *path, uid_t owner, gid_t group)
902{
903 /* XXX noop */
1c1c7f20 904 return 0;
b990f8c8
GS
905}
906
0aaad0ff
GS
907static long
908find_pid(int pid)
0a753a76 909{
0aaad0ff 910 long child;
f55ee38a 911 for (child = 0 ; child < w32_num_children ; ++child) {
0aaad0ff
GS
912 if (w32_child_pids[child] == pid)
913 return child;
914 }
915 return -1;
916}
917
918static void
919remove_dead_process(long child)
920{
921 if (child >= 0) {
922 CloseHandle(w32_child_handles[child]);
923 Copy(&w32_child_handles[child+1], &w32_child_handles[child],
924 (w32_num_children-child-1), HANDLE);
925 Copy(&w32_child_pids[child+1], &w32_child_pids[child],
926 (w32_num_children-child-1), DWORD);
927 w32_num_children--;
f55ee38a 928 }
f55ee38a
GS
929}
930
931DllExport int
932win32_kill(int pid, int sig)
933{
0aaad0ff
GS
934 HANDLE hProcess;
935 hProcess = OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid);
936 if (hProcess && TerminateProcess(hProcess, sig))
68dc0745 937 CloseHandle(hProcess);
0aaad0ff
GS
938 else {
939 errno = EINVAL;
940 return -1;
68dc0745
PP
941 }
942 return 0;
0a753a76 943}
fbbbcc48 944
68dc0745
PP
945/*
946 * File system stuff
947 */
0a753a76 948
f3986ebb
GS
949DllExport unsigned int
950win32_sleep(unsigned int t)
0a753a76 951{
68dc0745
PP
952 Sleep(t*1000);
953 return 0;
0a753a76
PP
954}
955
68dc0745
PP
956DllExport int
957win32_stat(const char *path, struct stat *buffer)
0a753a76 958{
24caa93f 959 char t[MAX_PATH+1];
68dc0745 960 int l = strlen(path);
67fbe06e 961 int res;
7fac1903 962 WCHAR wbuffer[MAX_PATH];
0a753a76 963
68dc0745
PP
964 if (l > 1) {
965 switch(path[l - 1]) {
e1dbac94
GS
966 /* FindFirstFile() and stat() are buggy with a trailing
967 * backslash, so change it to a forward slash :-( */
68dc0745 968 case '\\':
e1dbac94
GS
969 strncpy(t, path, l-1);
970 t[l - 1] = '/';
971 t[l] = '\0';
972 path = t;
973 break;
23db2e2d 974 /* FindFirstFile() is buggy with "x:", so add a dot :-( */
e1dbac94
GS
975 case ':':
976 if (l == 2 && isALPHA(path[0])) {
23db2e2d 977 t[0] = path[0]; t[1] = ':'; t[2] = '.'; t[3] = '\0';
e1dbac94
GS
978 l = 3;
979 path = t;
980 }
981 break;
68dc0745
PP
982 }
983 }
7fac1903 984 if (USING_WIDE()) {
73c4f7a1 985 dTHX;
7fac1903
GS
986 A2WHELPER(path, wbuffer, sizeof(wbuffer), GETINTERPMODE());
987 res = _wstat(wbuffer, (struct _stat *)buffer);
988 }
989 else {
990 res = stat(path, buffer);
991 }
24caa93f
GS
992 if (res < 0) {
993 /* CRT is buggy on sharenames, so make sure it really isn't.
994 * XXX using GetFileAttributesEx() will enable us to set
995 * buffer->st_*time (but note that's not available on the
996 * Windows of 1995) */
7fac1903
GS
997 DWORD r;
998 if (USING_WIDE()) {
999 r = GetFileAttributesW(wbuffer);
1000 }
1001 else {
1002 r = GetFileAttributesA(path);
1003 }
24caa93f 1004 if (r != 0xffffffff && (r & FILE_ATTRIBUTE_DIRECTORY)) {
e1dbac94
GS
1005 /* buffer may still contain old garbage since stat() failed */
1006 Zero(buffer, 1, struct stat);
1007 buffer->st_mode = S_IFDIR | S_IREAD;
24caa93f
GS
1008 errno = 0;
1009 if (!(r & FILE_ATTRIBUTE_READONLY))
1010 buffer->st_mode |= S_IWRITE | S_IEXEC;
1011 return 0;
1012 }
1013 }
24caa93f 1014 else {
e1dbac94
GS
1015 if (l == 3 && isALPHA(path[0]) && path[1] == ':'
1016 && (path[2] == '\\' || path[2] == '/'))
2293b0e9
AB
1017 {
1018 /* The drive can be inaccessible, some _stat()s are buggy */
7fac1903
GS
1019 if (USING_WIDE()
1020 ? !GetVolumeInformationW(wbuffer,NULL,0,NULL,NULL,NULL,NULL,0)
1021 : !GetVolumeInformationA(path,NULL,0,NULL,NULL,NULL,NULL,0)) {
2293b0e9
AB
1022 errno = ENOENT;
1023 return -1;
1024 }
1025 }
1026#ifdef __BORLANDC__
67fbe06e
GS
1027 if (S_ISDIR(buffer->st_mode))
1028 buffer->st_mode |= S_IWRITE | S_IEXEC;
1029 else if (S_ISREG(buffer->st_mode)) {
1030 if (l >= 4 && path[l-4] == '.') {
1031 const char *e = path + l - 3;
1032 if (strnicmp(e,"exe",3)
1033 && strnicmp(e,"bat",3)
1034 && strnicmp(e,"com",3)
1035 && (IsWin95() || strnicmp(e,"cmd",3)))
1036 buffer->st_mode &= ~S_IEXEC;
1037 else
1038 buffer->st_mode |= S_IEXEC;
1039 }
1040 else
1041 buffer->st_mode &= ~S_IEXEC;
1042 }
67fbe06e 1043#endif
2293b0e9 1044 }
67fbe06e 1045 return res;
0a753a76
PP
1046}
1047
8ac9c18d
GS
1048/* Find the longname of a given path. path is destructively modified.
1049 * It should have space for at least MAX_PATH characters. */
1050DllExport char *
1051win32_longpath(char *path)
1052{
1053 WIN32_FIND_DATA fdata;
1054 HANDLE fhand;
1055 char tmpbuf[MAX_PATH+1];
1056 char *tmpstart = tmpbuf;
1057 char *start = path;
1058 char sep;
1059 if (!path)
1060 return Nullch;
1061
1062 /* drive prefix */
1063 if (isALPHA(path[0]) && path[1] == ':' &&
1064 (path[2] == '/' || path[2] == '\\'))
1065 {
1066 start = path + 2;
1067 *tmpstart++ = path[0];
1068 *tmpstart++ = ':';
1069 }
1070 /* UNC prefix */
1071 else if ((path[0] == '/' || path[0] == '\\') &&
1072 (path[1] == '/' || path[1] == '\\'))
1073 {
1074 start = path + 2;
52fcf7ee
GS
1075 *tmpstart++ = path[0];
1076 *tmpstart++ = path[1];
8ac9c18d
GS
1077 /* copy machine name */
1078 while (*start && *start != '/' && *start != '\\')
1079 *tmpstart++ = *start++;
1080 if (*start) {
52fcf7ee 1081 *tmpstart++ = *start;
8ac9c18d
GS
1082 start++;
1083 /* copy share name */
1084 while (*start && *start != '/' && *start != '\\')
1085 *tmpstart++ = *start++;
1086 }
1087 }
1088 sep = *start++;
1089 if (sep == '/' || sep == '\\')
52fcf7ee 1090 *tmpstart++ = sep;
8ac9c18d
GS
1091 *tmpstart = '\0';
1092 while (sep) {
1093 /* walk up to slash */
1094 while (*start && *start != '/' && *start != '\\')
1095 ++start;
1096
1097 /* discard doubled slashes */
1098 while (*start && (start[1] == '/' || start[1] == '\\'))
1099 ++start;
1100 sep = *start;
1101
1102 /* stop and find full name of component */
1103 *start = '\0';
1104 fhand = FindFirstFile(path,&fdata);
1105 if (fhand != INVALID_HANDLE_VALUE) {
1106 strcpy(tmpstart, fdata.cFileName);
1107 tmpstart += strlen(fdata.cFileName);
1108 if (sep)
52fcf7ee 1109 *tmpstart++ = sep;
8ac9c18d
GS
1110 *tmpstart = '\0';
1111 *start++ = sep;
1112 FindClose(fhand);
1113 }
1114 else {
1115 /* failed a step, just return without side effects */
1116 /*PerlIO_printf(PerlIO_stderr(), "Failed to find %s\n", path);*/
1117 *start = sep;
1118 return Nullch;
1119 }
1120 }
1121 strcpy(path,tmpbuf);
1122 return path;
1123}
1124
0551aaa8
GS
1125#ifndef USE_WIN32_RTL_ENV
1126
1127DllExport char *
1128win32_getenv(const char *name)
1129{
73c4f7a1 1130 dTHX;
c934e9d4 1131 static char *curitem = Nullch; /* XXX threadead */
7fac1903
GS
1132 static WCHAR *wCuritem = (WCHAR*)Nullch; /* XXX threadead */
1133 static DWORD curlen = 0, wCurlen = 0;/* XXX threadead */
1134 WCHAR wBuffer[MAX_PATH];
0551aaa8 1135 DWORD needlen;
73c4f7a1 1136
7fac1903
GS
1137 if (USING_WIDE()) {
1138 if (!wCuritem) {
1139 wCurlen = 512;
1140 New(1306,wCuritem,wCurlen,WCHAR);
1141 }
1142 }
46124e9e
GS
1143 if (!curitem) {
1144 curlen = 512;
0551aaa8 1145 New(1305,curitem,curlen,char);
46124e9e 1146 }
58a50f62 1147
7fac1903
GS
1148 if (USING_WIDE()) {
1149 A2WHELPER(name, wBuffer, sizeof(wBuffer), GETINTERPMODE());
1150 needlen = GetEnvironmentVariableW(wBuffer,wCuritem,wCurlen);
1151 }
1152 else
1153 needlen = GetEnvironmentVariableA(name,curitem,curlen);
58a50f62 1154 if (needlen != 0) {
7fac1903
GS
1155 if (USING_WIDE()) {
1156 while (needlen > wCurlen) {
1157 Renew(wCuritem,needlen,WCHAR);
1158 wCurlen = needlen;
1159 needlen = GetEnvironmentVariableW(wBuffer,wCuritem,wCurlen);
1160 }
1161 if (needlen > curlen) {
1162 Renew(curitem,needlen,char);
1163 curlen = needlen;
1164 }
1165 W2AHELPER(wCuritem, curitem, curlen, GETINTERPMODE());
1166 }
1167 else {
1168 while (needlen > curlen) {
1169 Renew(curitem,needlen,char);
1170 curlen = needlen;
1171 needlen = GetEnvironmentVariableA(name,curitem,curlen);
1172 }
58a50f62 1173 }
0551aaa8 1174 }
c934e9d4 1175 else {
7a5f8e82 1176 /* allow any environment variables that begin with 'PERL'
c934e9d4
GS
1177 to be stored in the registry */
1178 if (curitem)
58a50f62
GS
1179 *curitem = '\0';
1180
7a5f8e82 1181 if (strncmp(name, "PERL", 4) == 0) {
c934e9d4 1182 if (curitem) {
58a50f62 1183 Safefree(curitem);
c934e9d4 1184 curitem = Nullch;
46124e9e 1185 curlen = 0;
58a50f62 1186 }
00dc2f4f 1187 curitem = GetRegStr(name, &curitem, &curlen);
58a50f62 1188 }
c69f6586 1189 }
c934e9d4 1190 if (curitem && *curitem == '\0')
58a50f62
GS
1191 return Nullch;
1192
0551aaa8
GS
1193 return curitem;
1194}
1195
ac5c734f
GS
1196DllExport int
1197win32_putenv(const char *name)
1198{
1199 char* curitem;
1200 char* val;
7fac1903
GS
1201 WCHAR* wCuritem;
1202 WCHAR* wVal;
1203 int length, relval = -1;
73c4f7a1 1204 if (name) {
7fac1903 1205 if (USING_WIDE()) {
73c4f7a1 1206 dTHX;
7fac1903
GS
1207 length = strlen(name)+1;
1208 New(1309,wCuritem,length,WCHAR);
1209 A2WHELPER(name, wCuritem, length*2, GETINTERPMODE());
1210 wVal = wcschr(wCuritem, '=');
1211 if(wVal) {
1212 *wVal++ = '\0';
1213 if(SetEnvironmentVariableW(wCuritem, *wVal ? wVal : NULL))
1214 relval = 0;
1215 }
1216 Safefree(wCuritem);
1217 }
1218 else {
1219 New(1309,curitem,strlen(name)+1,char);
1220 strcpy(curitem, name);
1221 val = strchr(curitem, '=');
1222 if(val) {
1223 /* The sane way to deal with the environment.
1224 * Has these advantages over putenv() & co.:
1225 * * enables us to store a truly empty value in the
1226 * environment (like in UNIX).
1227 * * we don't have to deal with RTL globals, bugs and leaks.
1228 * * Much faster.
1229 * Why you may want to enable USE_WIN32_RTL_ENV:
1230 * * environ[] and RTL functions will not reflect changes,
1231 * which might be an issue if extensions want to access
1232 * the env. via RTL. This cuts both ways, since RTL will
1233 * not see changes made by extensions that call the Win32
1234 * functions directly, either.
1235 * GSAR 97-06-07
1236 */
1237 *val++ = '\0';
1238 if(SetEnvironmentVariableA(curitem, *val ? val : NULL))
1239 relval = 0;
1240 }
1241 Safefree(curitem);
ac5c734f 1242 }
ac5c734f
GS
1243 }
1244 return relval;
1245}
1246
0551aaa8
GS
1247#endif
1248
d55594ae 1249static long
2d7a9237 1250filetime_to_clock(PFILETIME ft)
d55594ae
GS
1251{
1252 __int64 qw = ft->dwHighDateTime;
1253 qw <<= 32;
1254 qw |= ft->dwLowDateTime;
1255 qw /= 10000; /* File time ticks at 0.1uS, clock at 1mS */
1256 return (long) qw;
1257}
1258
f3986ebb
GS
1259DllExport int
1260win32_times(struct tms *timebuf)
0a753a76 1261{
d55594ae
GS
1262 FILETIME user;
1263 FILETIME kernel;
1264 FILETIME dummy;
1265 if (GetProcessTimes(GetCurrentProcess(), &dummy, &dummy,
1266 &kernel,&user)) {
2d7a9237
GS
1267 timebuf->tms_utime = filetime_to_clock(&user);
1268 timebuf->tms_stime = filetime_to_clock(&kernel);
d55594ae
GS
1269 timebuf->tms_cutime = 0;
1270 timebuf->tms_cstime = 0;
1271
1272 } else {
1273 /* That failed - e.g. Win95 fallback to clock() */
1274 clock_t t = clock();
1275 timebuf->tms_utime = t;
1276 timebuf->tms_stime = 0;
1277 timebuf->tms_cutime = 0;
1278 timebuf->tms_cstime = 0;
1279 }
68dc0745 1280 return 0;
0a753a76
PP
1281}
1282
ad0751ec
GS
1283/* fix utime() so it works on directories in NT
1284 * thanks to Jan Dubois <jan.dubois@ibm.net>
1285 */
1286static BOOL
1287filetime_from_time(PFILETIME pFileTime, time_t Time)
1288{
1289 struct tm *pTM = gmtime(&Time);
1290 SYSTEMTIME SystemTime;
1291
1292 if (pTM == NULL)
1293 return FALSE;
1294
1295 SystemTime.wYear = pTM->tm_year + 1900;
1296 SystemTime.wMonth = pTM->tm_mon + 1;
1297 SystemTime.wDay = pTM->tm_mday;
1298 SystemTime.wHour = pTM->tm_hour;
1299 SystemTime.wMinute = pTM->tm_min;
1300 SystemTime.wSecond = pTM->tm_sec;
1301 SystemTime.wMilliseconds = 0;
1302
1303 return SystemTimeToFileTime(&SystemTime, pFileTime);
1304}
1305
1306DllExport int
3b405fc5 1307win32_utime(const char *filename, struct utimbuf *times)
ad0751ec
GS
1308{
1309 HANDLE handle;
1310 FILETIME ftCreate;
1311 FILETIME ftAccess;
1312 FILETIME ftWrite;
1313 struct utimbuf TimeBuffer;
7fac1903 1314 WCHAR wbuffer[MAX_PATH];
ad0751ec 1315
7fac1903
GS
1316 int rc;
1317 if (USING_WIDE()) {
73c4f7a1 1318 dTHX;
7fac1903
GS
1319 A2WHELPER(filename, wbuffer, sizeof(wbuffer), GETINTERPMODE());
1320 rc = _wutime(wbuffer, (struct _utimbuf*)times);
1321 }
1322 else {
1323 rc = utime(filename, times);
1324 }
ad0751ec
GS
1325 /* EACCES: path specifies directory or readonly file */
1326 if (rc == 0 || errno != EACCES /* || !IsWinNT() */)
1327 return rc;
1328
1329 if (times == NULL) {
1330 times = &TimeBuffer;
1331 time(&times->actime);
1332 times->modtime = times->actime;
1333 }
1334
1335 /* This will (and should) still fail on readonly files */
7fac1903
GS
1336 if (USING_WIDE()) {
1337 handle = CreateFileW(wbuffer, GENERIC_READ | GENERIC_WRITE,
1338 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1339 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1340 }
1341 else {
1342 handle = CreateFileA(filename, GENERIC_READ | GENERIC_WRITE,
1343 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1344 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1345 }
ad0751ec
GS
1346 if (handle == INVALID_HANDLE_VALUE)
1347 return rc;
1348
1349 if (GetFileTime(handle, &ftCreate, &ftAccess, &ftWrite) &&
1350 filetime_from_time(&ftAccess, times->actime) &&
1351 filetime_from_time(&ftWrite, times->modtime) &&
1352 SetFileTime(handle, &ftCreate, &ftAccess, &ftWrite))
1353 {
1354 rc = 0;
1355 }
1356
1357 CloseHandle(handle);
1358 return rc;
1359}
1360
2d7a9237 1361DllExport int
b2af26b1
GS
1362win32_uname(struct utsname *name)
1363{
1364 struct hostent *hep;
1365 STRLEN nodemax = sizeof(name->nodename)-1;
1366 OSVERSIONINFO osver;
1367
1368 memset(&osver, 0, sizeof(OSVERSIONINFO));
1369 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1370 if (GetVersionEx(&osver)) {
1371 /* sysname */
1372 switch (osver.dwPlatformId) {
1373 case VER_PLATFORM_WIN32_WINDOWS:
1374 strcpy(name->sysname, "Windows");
1375 break;
1376 case VER_PLATFORM_WIN32_NT:
1377 strcpy(name->sysname, "Windows NT");
1378 break;
1379 case VER_PLATFORM_WIN32s:
1380 strcpy(name->sysname, "Win32s");
1381 break;
1382 default:
1383 strcpy(name->sysname, "Win32 Unknown");
1384 break;
1385 }
1386
cf6cacac
GS
1387 /* release */
1388 sprintf(name->release, "%d.%d",
b2af26b1
GS
1389 osver.dwMajorVersion, osver.dwMinorVersion);
1390
cf6cacac
GS
1391 /* version */
1392 sprintf(name->version, "Build %d",
b2af26b1
GS
1393 osver.dwPlatformId == VER_PLATFORM_WIN32_NT
1394 ? osver.dwBuildNumber : (osver.dwBuildNumber & 0xffff));
1395 if (osver.szCSDVersion[0]) {
cf6cacac 1396 char *buf = name->version + strlen(name->version);
b2af26b1
GS
1397 sprintf(buf, " (%s)", osver.szCSDVersion);
1398 }
1399 }
1400 else {
1401 *name->sysname = '\0';
1402 *name->version = '\0';
1403 *name->release = '\0';
1404 }
1405
1406 /* nodename */
1407 hep = win32_gethostbyname("localhost");
1408 if (hep) {
1409 STRLEN len = strlen(hep->h_name);
1410 if (len <= nodemax) {
1411 strcpy(name->nodename, hep->h_name);
1412 }
1413 else {
1414 strncpy(name->nodename, hep->h_name, nodemax);
1415 name->nodename[nodemax] = '\0';
1416 }
1417 }
1418 else {
1419 DWORD sz = nodemax;
1420 if (!GetComputerName(name->nodename, &sz))
1421 *name->nodename = '\0';
1422 }
1423
1424 /* machine (architecture) */
1425 {
1426 SYSTEM_INFO info;
1427 char *arch;
1428 GetSystemInfo(&info);
a6c40364 1429
7a9ec5a3
NIS
1430#ifdef __MINGW32__
1431 switch (info.DUMMYUNIONNAME.DUMMYSTRUCTNAME.wProcessorArchitecture) {
1432#else
a6c40364
GS
1433#ifdef __BORLANDC__
1434 switch (info.u.s.wProcessorArchitecture) {
1435#else
b2af26b1 1436 switch (info.wProcessorArchitecture) {
a6c40364 1437#endif
7a9ec5a3 1438#endif
b2af26b1
GS
1439 case PROCESSOR_ARCHITECTURE_INTEL:
1440 arch = "x86"; break;
1441 case PROCESSOR_ARCHITECTURE_MIPS:
1442 arch = "mips"; break;
1443 case PROCESSOR_ARCHITECTURE_ALPHA:
1444 arch = "alpha"; break;
1445 case PROCESSOR_ARCHITECTURE_PPC:
1446 arch = "ppc"; break;
1447 default:
1448 arch = "unknown"; break;
1449 }
1450 strcpy(name->machine, arch);
1451 }
1452 return 0;
1453}
1454
1455DllExport int
f55ee38a
GS
1456win32_waitpid(int pid, int *status, int flags)
1457{
0aaad0ff 1458 int retval = -1;
f55ee38a 1459 if (pid == -1)
0aaad0ff 1460 return win32_wait(status);
f55ee38a 1461 else {
0aaad0ff
GS
1462 long child = find_pid(pid);
1463 if (child >= 0) {
1464 HANDLE hProcess = w32_child_handles[child];
1465 DWORD waitcode = WaitForSingleObject(hProcess, INFINITE);
1466 if (waitcode != WAIT_FAILED) {
1467 if (GetExitCodeProcess(hProcess, &waitcode)) {
1468 *status = (int)((waitcode & 0xff) << 8);
1469 retval = (int)w32_child_pids[child];
1470 remove_dead_process(child);
1471 return retval;
1472 }
1473 }
1474 else
1475 errno = ECHILD;
1476 }
1477 else {
1478 retval = cwait(status, pid, WAIT_CHILD);
1479 /* cwait() returns "correctly" on Borland */
8f1e745d 1480#ifndef __BORLANDC__
0aaad0ff
GS
1481 if (status)
1482 *status *= 256;
f55ee38a 1483#endif
0aaad0ff 1484 }
f55ee38a 1485 }
0aaad0ff 1486 return retval >= 0 ? pid : retval;
f55ee38a
GS
1487}
1488
1489DllExport int
2d7a9237
GS
1490win32_wait(int *status)
1491{
2d7a9237
GS
1492 /* XXX this wait emulation only knows about processes
1493 * spawned via win32_spawnvp(P_NOWAIT, ...).
1494 */
1495 int i, retval;
1496 DWORD exitcode, waitcode;
1497
1498 if (!w32_num_children) {
1499 errno = ECHILD;
1500 return -1;
1501 }
1502
1503 /* if a child exists, wait for it to die */
1504 waitcode = WaitForMultipleObjects(w32_num_children,
0aaad0ff 1505 w32_child_handles,
2d7a9237
GS
1506 FALSE,
1507 INFINITE);
1508 if (waitcode != WAIT_FAILED) {
1509 if (waitcode >= WAIT_ABANDONED_0
1510 && waitcode < WAIT_ABANDONED_0 + w32_num_children)
1511 i = waitcode - WAIT_ABANDONED_0;
1512 else
1513 i = waitcode - WAIT_OBJECT_0;
0aaad0ff 1514 if (GetExitCodeProcess(w32_child_handles[i], &exitcode) ) {
2d7a9237
GS
1515 *status = (int)((exitcode & 0xff) << 8);
1516 retval = (int)w32_child_pids[i];
0aaad0ff 1517 remove_dead_process(i);
2d7a9237
GS
1518 return retval;
1519 }
1520 }
1521
1522FAILED:
1523 errno = GetLastError();
1524 return -1;
2d7a9237 1525}
d55594ae 1526
2d7a9237 1527static UINT timerid = 0;
d55594ae
GS
1528
1529static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
1530{
1531 KillTimer(NULL,timerid);
1532 timerid=0;
1533 sighandler(14);
1534}
1535
f3986ebb
GS
1536DllExport unsigned int
1537win32_alarm(unsigned int sec)
0a753a76 1538{
d55594ae
GS
1539 /*
1540 * the 'obvious' implentation is SetTimer() with a callback
1541 * which does whatever receiving SIGALRM would do
1542 * we cannot use SIGALRM even via raise() as it is not
1543 * one of the supported codes in <signal.h>
1544 *
1545 * Snag is unless something is looking at the message queue
1546 * nothing happens :-(
1547 */
1548 if (sec)
1549 {
1550 timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
1551 if (!timerid)
4f63d024 1552 Perl_croak_nocontext("Cannot set timer");
d55594ae
GS
1553 }
1554 else
1555 {
1556 if (timerid)
1557 {
1558 KillTimer(NULL,timerid);
1559 timerid=0;
1560 }
1561 }
68dc0745 1562 return 0;
0a753a76
PP
1563}
1564
ff95b63e 1565#if defined(HAVE_DES_FCRYPT) || defined(PERL_OBJECT)
26618a56 1566#ifdef HAVE_DES_FCRYPT
2d77217b 1567extern char * des_fcrypt(const char *txt, const char *salt, char *cbuf);
ff95b63e 1568#endif
26618a56
GS
1569
1570DllExport char *
1571win32_crypt(const char *txt, const char *salt)
1572{
ff95b63e 1573#ifdef HAVE_DES_FCRYPT
26618a56 1574 dTHR;
2d77217b 1575 return des_fcrypt(txt, salt, crypt_buffer);
ff95b63e
DL
1576#else
1577 die("The crypt() function is unimplemented due to excessive paranoia.");
b8957cf1 1578 return Nullch;
ff95b63e 1579#endif
26618a56
GS
1580}
1581#endif
1582
f3986ebb 1583#ifdef USE_FIXED_OSFHANDLE
390b85e7
GS
1584
1585EXTERN_C int __cdecl _alloc_osfhnd(void);
1586EXTERN_C int __cdecl _set_osfhnd(int fh, long value);
1587EXTERN_C void __cdecl _lock_fhandle(int);
1588EXTERN_C void __cdecl _unlock_fhandle(int);
1589EXTERN_C void __cdecl _unlock(int);
1590
1591#if (_MSC_VER >= 1000)
1592typedef struct {
1593 long osfhnd; /* underlying OS file HANDLE */
1594 char osfile; /* attributes of file (e.g., open in text mode?) */
1595 char pipech; /* one char buffer for handles opened on pipes */
1596#if defined (_MT) && !defined (DLL_FOR_WIN32S)
1597 int lockinitflag;
1598 CRITICAL_SECTION lock;
1599#endif /* defined (_MT) && !defined (DLL_FOR_WIN32S) */
1600} ioinfo;
1601
1602EXTERN_C ioinfo * __pioinfo[];
1603
1604#define IOINFO_L2E 5
1605#define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
1606#define _pioinfo(i) (__pioinfo[i >> IOINFO_L2E] + (i & (IOINFO_ARRAY_ELTS - 1)))
1607#define _osfile(i) (_pioinfo(i)->osfile)
1608
1609#else /* (_MSC_VER >= 1000) */
1610extern char _osfile[];
1611#endif /* (_MSC_VER >= 1000) */
1612
1613#define FOPEN 0x01 /* file handle open */
1614#define FAPPEND 0x20 /* file handle opened O_APPEND */
1615#define FDEV 0x40 /* file handle refers to device */
1616#define FTEXT 0x80 /* file handle is in text mode */
1617
1618#define _STREAM_LOCKS 26 /* Table of stream locks */
1619#define _LAST_STREAM_LOCK (_STREAM_LOCKS+_NSTREAM_-1) /* Last stream lock */
1620#define _FH_LOCKS (_LAST_STREAM_LOCK+1) /* Table of fh locks */
1621
1622/***
1623*int my_open_osfhandle(long osfhandle, int flags) - open C Runtime file handle
1624*
1625*Purpose:
1626* This function allocates a free C Runtime file handle and associates
1627* it with the Win32 HANDLE specified by the first parameter. This is a
1628* temperary fix for WIN95's brain damage GetFileType() error on socket
1629* we just bypass that call for socket
1630*
1631*Entry:
1632* long osfhandle - Win32 HANDLE to associate with C Runtime file handle.
1633* int flags - flags to associate with C Runtime file handle.
1634*
1635*Exit:
1636* returns index of entry in fh, if successful
1637* return -1, if no free entry is found
1638*
1639*Exceptions:
1640*
1641*******************************************************************************/
1642
1643static int
1644my_open_osfhandle(long osfhandle, int flags)
1645{
1646 int fh;
1647 char fileflags; /* _osfile flags */
1648
1649 /* copy relevant flags from second parameter */
1650 fileflags = FDEV;
1651
9404a519 1652 if (flags & O_APPEND)
390b85e7
GS
1653 fileflags |= FAPPEND;
1654
9404a519 1655 if (flags & O_TEXT)
390b85e7
GS
1656 fileflags |= FTEXT;
1657
1658 /* attempt to allocate a C Runtime file handle */
9404a519 1659 if ((fh = _alloc_osfhnd()) == -1) {
390b85e7
GS
1660 errno = EMFILE; /* too many open files */
1661 _doserrno = 0L; /* not an OS error */
1662 return -1; /* return error to caller */
1663 }
1664
1665 /* the file is open. now, set the info in _osfhnd array */
1666 _set_osfhnd(fh, osfhandle);
1667
1668 fileflags |= FOPEN; /* mark as open */
1669
1670#if (_MSC_VER >= 1000)
1671 _osfile(fh) = fileflags; /* set osfile entry */
1672 _unlock_fhandle(fh);
1673#else
1674 _osfile[fh] = fileflags; /* set osfile entry */
1675 _unlock(fh+_FH_LOCKS); /* unlock handle */
1676#endif
1677
1678 return fh; /* return handle */
1679}
1680
1681#define _open_osfhandle my_open_osfhandle
f3986ebb 1682#endif /* USE_FIXED_OSFHANDLE */
390b85e7
GS
1683
1684/* simulate flock by locking a range on the file */
1685
1686#define LK_ERR(f,i) ((f) ? (i = 0) : (errno = GetLastError()))
1687#define LK_LEN 0xffff0000
1688
f3986ebb
GS
1689DllExport int
1690win32_flock(int fd, int oper)
390b85e7
GS
1691{
1692 OVERLAPPED o;
1693 int i = -1;
1694 HANDLE fh;
1695
f3986ebb 1696 if (!IsWinNT()) {
4f63d024 1697 Perl_croak_nocontext("flock() unimplemented on this platform");
f3986ebb
GS
1698 return -1;
1699 }
390b85e7
GS
1700 fh = (HANDLE)_get_osfhandle(fd);
1701 memset(&o, 0, sizeof(o));
1702
1703 switch(oper) {
1704 case LOCK_SH: /* shared lock */
1705 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
1706 break;
1707 case LOCK_EX: /* exclusive lock */
1708 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
1709 break;
1710 case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
1711 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
1712 break;
1713 case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
1714 LK_ERR(LockFileEx(fh,
1715 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
1716 0, LK_LEN, 0, &o),i);
1717 break;
1718 case LOCK_UN: /* unlock lock */
1719 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, 0, &o),i);
1720 break;
1721 default: /* unknown */
1722 errno = EINVAL;
1723 break;
1724 }
1725 return i;
1726}
1727
1728#undef LK_ERR
1729#undef LK_LEN
1730
68dc0745
PP
1731/*
1732 * redirected io subsystem for all XS modules
1733 *
1734 */
0a753a76 1735
68dc0745
PP
1736DllExport int *
1737win32_errno(void)
0a753a76 1738{
390b85e7 1739 return (&errno);
0a753a76
PP
1740}
1741
dcb2879a
GS
1742DllExport char ***
1743win32_environ(void)
1744{
390b85e7 1745 return (&(_environ));
dcb2879a
GS
1746}
1747
68dc0745
PP
1748/* the rest are the remapped stdio routines */
1749DllExport FILE *
1750win32_stderr(void)
0a753a76 1751{
390b85e7 1752 return (stderr);
0a753a76
PP
1753}
1754
68dc0745
PP
1755DllExport FILE *
1756win32_stdin(void)
0a753a76 1757{
390b85e7 1758 return (stdin);
0a753a76
PP
1759}
1760
68dc0745
PP
1761DllExport FILE *
1762win32_stdout()
0a753a76 1763{
390b85e7 1764 return (stdout);
0a753a76
PP
1765}
1766
68dc0745
PP
1767DllExport int
1768win32_ferror(FILE *fp)
0a753a76 1769{
390b85e7 1770 return (ferror(fp));
0a753a76
PP
1771}
1772
1773
68dc0745
PP
1774DllExport int
1775win32_feof(FILE *fp)
0a753a76 1776{
390b85e7 1777 return (feof(fp));
0a753a76
PP
1778}
1779
68dc0745
PP
1780/*
1781 * Since the errors returned by the socket error function
1782 * WSAGetLastError() are not known by the library routine strerror
1783 * we have to roll our own.
1784 */
0a753a76 1785
68dc0745
PP
1786DllExport char *
1787win32_strerror(int e)
0a753a76 1788{
3e3baf6d 1789#ifndef __BORLANDC__ /* Borland intolerance */
68dc0745 1790 extern int sys_nerr;
3e3baf6d 1791#endif
68dc0745 1792 DWORD source = 0;
0a753a76 1793
9404a519 1794 if (e < 0 || e > sys_nerr) {
4f63d024 1795 dTHX;
9404a519 1796 if (e < 0)
68dc0745 1797 e = GetLastError();
0a753a76 1798
9404a519 1799 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
68dc0745
PP
1800 strerror_buffer, sizeof(strerror_buffer), NULL) == 0)
1801 strcpy(strerror_buffer, "Unknown Error");
0a753a76 1802
68dc0745
PP
1803 return strerror_buffer;
1804 }
390b85e7 1805 return strerror(e);
0a753a76
PP
1806}
1807
22fae026 1808DllExport void
4f63d024 1809win32_str_os_error(pTHX_ void *sv, DWORD dwErr)
22fae026
TM
1810{
1811 DWORD dwLen;
1812 char *sMsg;
1813 dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
1814 |FORMAT_MESSAGE_IGNORE_INSERTS
1815 |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
1816 dwErr, 0, (char *)&sMsg, 1, NULL);
1817 if (0 < dwLen) {
de030af3 1818 while (0 < dwLen && isSPACE(sMsg[--dwLen]))
22fae026
TM
1819 ;
1820 if ('.' != sMsg[dwLen])
1821 dwLen++;
1822 sMsg[dwLen]= '\0';
1823 }
1824 if (0 == dwLen) {
c69f6586 1825 sMsg = (char*)LocalAlloc(0, 64/**sizeof(TCHAR)*/);
db7c17d7
GS
1826 if (sMsg)
1827 dwLen = sprintf(sMsg,
1828 "Unknown error #0x%lX (lookup 0x%lX)",
1829 dwErr, GetLastError());
1830 }
1831 if (sMsg) {
1832 sv_setpvn((SV*)sv, sMsg, dwLen);
1833 LocalFree(sMsg);
22fae026 1834 }
22fae026
TM
1835}
1836
1837
68dc0745
PP
1838DllExport int
1839win32_fprintf(FILE *fp, const char *format, ...)
0a753a76 1840{
68dc0745
PP
1841 va_list marker;
1842 va_start(marker, format); /* Initialize variable arguments. */
0a753a76 1843
390b85e7 1844 return (vfprintf(fp, format, marker));
0a753a76
PP
1845}
1846
68dc0745
PP
1847DllExport int
1848win32_printf(const char *format, ...)
0a753a76 1849{
68dc0745
PP
1850 va_list marker;
1851 va_start(marker, format); /* Initialize variable arguments. */
0a753a76 1852
390b85e7 1853 return (vprintf(format, marker));
0a753a76
PP
1854}
1855
68dc0745
PP
1856DllExport int
1857win32_vfprintf(FILE *fp, const char *format, va_list args)
0a753a76 1858{
390b85e7 1859 return (vfprintf(fp, format, args));
0a753a76
PP
1860}
1861
96e4d5b1
PP
1862DllExport int
1863win32_vprintf(const char *format, va_list args)
1864{
390b85e7 1865 return (vprintf(format, args));
96e4d5b1
PP
1866}
1867
68dc0745
PP
1868DllExport size_t
1869win32_fread(void *buf, size_t size, size_t count, FILE *fp)
0a753a76 1870{
390b85e7 1871 return fread(buf, size, count, fp);
0a753a76
PP
1872}
1873
68dc0745
PP
1874DllExport size_t
1875win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
0a753a76 1876{
390b85e7 1877 return fwrite(buf, size, count, fp);
0a753a76
PP
1878}
1879
7fac1903
GS
1880#define MODE_SIZE 10
1881
68dc0745
PP
1882DllExport FILE *
1883win32_fopen(const char *filename, const char *mode)
0a753a76 1884{
7fac1903 1885 WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH];
68dc0745 1886 if (stricmp(filename, "/dev/null")==0)
7fac1903
GS
1887 filename = "NUL";
1888
1889 if (USING_WIDE()) {
73c4f7a1 1890 dTHX;
7fac1903
GS
1891 A2WHELPER(mode, wMode, sizeof(wMode), GETINTERPMODE());
1892 A2WHELPER(filename, wBuffer, sizeof(wBuffer), GETINTERPMODE());
1893 return _wfopen(wBuffer, wMode);
1894 }
390b85e7 1895 return fopen(filename, mode);
0a753a76
PP
1896}
1897
f3986ebb
GS
1898#ifndef USE_SOCKETS_AS_HANDLES
1899#undef fdopen
1900#define fdopen my_fdopen
1901#endif
1902
68dc0745 1903DllExport FILE *
7fac1903 1904win32_fdopen(int handle, const char *mode)
0a753a76 1905{
7fac1903
GS
1906 WCHAR wMode[MODE_SIZE];
1907 if (USING_WIDE()) {
73c4f7a1 1908 dTHX;
7fac1903
GS
1909 A2WHELPER(mode, wMode, sizeof(wMode), GETINTERPMODE());
1910 return _wfdopen(handle, wMode);
1911 }
390b85e7 1912 return fdopen(handle, (char *) mode);
0a753a76
PP
1913}
1914
68dc0745 1915DllExport FILE *
7fac1903 1916win32_freopen(const char *path, const char *mode, FILE *stream)
0a753a76 1917{
7fac1903 1918 WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH];
68dc0745 1919 if (stricmp(path, "/dev/null")==0)
7fac1903
GS
1920 path = "NUL";
1921
1922 if (USING_WIDE()) {
73c4f7a1 1923 dTHX;
7fac1903
GS
1924 A2WHELPER(mode, wMode, sizeof(wMode), GETINTERPMODE());
1925 A2WHELPER(path, wBuffer, sizeof(wBuffer), GETINTERPMODE());
1926 return _wfreopen(wBuffer, wMode, stream);
1927 }
390b85e7 1928 return freopen(path, mode, stream);
0a753a76
PP
1929}
1930
68dc0745
PP
1931DllExport int
1932win32_fclose(FILE *pf)
0a753a76 1933{
f3986ebb 1934 return my_fclose(pf); /* defined in win32sck.c */
0a753a76
PP
1935}
1936
68dc0745
PP
1937DllExport int
1938win32_fputs(const char *s,FILE *pf)
0a753a76 1939{
390b85e7 1940 return fputs(s, pf);
0a753a76
PP
1941}
1942
68dc0745
PP
1943DllExport int
1944win32_fputc(int c,FILE *pf)
0a753a76 1945{
390b85e7 1946 return fputc(c,pf);
0a753a76
PP
1947}
1948
68dc0745
PP
1949DllExport int
1950win32_ungetc(int c,FILE *pf)
0a753a76 1951{
390b85e7 1952 return ungetc(c,pf);
0a753a76
PP
1953}
1954
68dc0745
PP
1955DllExport int
1956win32_getc(FILE *pf)
0a753a76 1957{
390b85e7 1958 return getc(pf);
0a753a76
PP
1959}
1960
68dc0745
PP
1961DllExport int
1962win32_fileno(FILE *pf)
0a753a76 1963{
390b85e7 1964 return fileno(pf);
0a753a76
PP
1965}
1966
68dc0745
PP
1967DllExport void
1968win32_clearerr(FILE *pf)
0a753a76 1969{
390b85e7 1970 clearerr(pf);
68dc0745 1971 return;
0a753a76
PP
1972}
1973
68dc0745
PP
1974DllExport int
1975win32_fflush(FILE *pf)
0a753a76 1976{
390b85e7 1977 return fflush(pf);
0a753a76
PP
1978}
1979
68dc0745
PP
1980DllExport long
1981win32_ftell(FILE *pf)
0a753a76 1982{
390b85e7 1983 return ftell(pf);
0a753a76
PP
1984}
1985
68dc0745
PP
1986DllExport int
1987win32_fseek(FILE *pf,long offset,int origin)
0a753a76 1988{
390b85e7 1989 return fseek(pf, offset, origin);
0a753a76
PP
1990}
1991
68dc0745
PP
1992DllExport int
1993win32_fgetpos(FILE *pf,fpos_t *p)
0a753a76 1994{
390b85e7 1995 return fgetpos(pf, p);
0a753a76
PP
1996}
1997
68dc0745
PP
1998DllExport int
1999win32_fsetpos(FILE *pf,const fpos_t *p)
0a753a76 2000{
390b85e7 2001 return fsetpos(pf, p);
0a753a76
PP
2002}
2003
68dc0745
PP
2004DllExport void
2005win32_rewind(FILE *pf)
0a753a76 2006{
390b85e7 2007 rewind(pf);
68dc0745 2008 return;
0a753a76
PP
2009}
2010
68dc0745
PP
2011DllExport FILE*
2012win32_tmpfile(void)
0a753a76 2013{
390b85e7 2014 return tmpfile();
0a753a76
PP
2015}
2016
68dc0745
PP
2017DllExport void
2018win32_abort(void)
0a753a76 2019{
390b85e7 2020 abort();
68dc0745 2021 return;
0a753a76
PP
2022}
2023
68dc0745 2024DllExport int
22239a37 2025win32_fstat(int fd,struct stat *sbufptr)
0a753a76 2026{
22239a37 2027 return fstat(fd,sbufptr);
0a753a76
PP
2028}
2029
68dc0745
PP
2030DllExport int
2031win32_pipe(int *pfd, unsigned int size, int mode)
0a753a76 2032{
390b85e7 2033 return _pipe(pfd, size, mode);
0a753a76
PP
2034}
2035
50892819
GS
2036/*
2037 * a popen() clone that respects PERL5SHELL
2038 */
2039
68dc0745
PP
2040DllExport FILE*
2041win32_popen(const char *command, const char *mode)
0a753a76 2042{
4b556e6c 2043#ifdef USE_RTL_POPEN
390b85e7 2044 return _popen(command, mode);
50892819
GS
2045#else
2046 int p[2];
2047 int parent, child;
2048 int stdfd, oldfd;
2049 int ourmode;
2050 int childpid;
2051
2052 /* establish which ends read and write */
2053 if (strchr(mode,'w')) {
2054 stdfd = 0; /* stdin */
2055 parent = 1;
2056 child = 0;
2057 }
2058 else if (strchr(mode,'r')) {
2059 stdfd = 1; /* stdout */
2060 parent = 0;
2061 child = 1;
2062 }
2063 else
2064 return NULL;
2065
2066 /* set the correct mode */
2067 if (strchr(mode,'b'))
2068 ourmode = O_BINARY;
2069 else if (strchr(mode,'t'))
2070 ourmode = O_TEXT;
2071 else
2072 ourmode = _fmode & (O_TEXT | O_BINARY);
2073
2074 /* the child doesn't inherit handles */
2075 ourmode |= O_NOINHERIT;
2076
2077 if (win32_pipe( p, 512, ourmode) == -1)
2078 return NULL;
2079
2080 /* save current stdfd */
2081 if ((oldfd = win32_dup(stdfd)) == -1)
2082 goto cleanup;
2083
2084 /* make stdfd go to child end of pipe (implicitly closes stdfd) */
2085 /* stdfd will be inherited by the child */
2086 if (win32_dup2(p[child], stdfd) == -1)
2087 goto cleanup;
2088
2089 /* close the child end in parent */
2090 win32_close(p[child]);
2091
2092 /* start the child */
4f63d024
GS
2093 {
2094 dTHX;
2095 if ((childpid = do_spawn_nowait(aTHX_ (char*)command)) == -1)
2096 goto cleanup;
50892819 2097
4f63d024
GS
2098 /* revert stdfd to whatever it was before */
2099 if (win32_dup2(oldfd, stdfd) == -1)
2100 goto cleanup;
50892819 2101
4f63d024
GS
2102 /* close saved handle */
2103 win32_close(oldfd);
50892819 2104
4f63d024
GS
2105 sv_setiv(*av_fetch(w32_fdpid, p[parent], TRUE), childpid);
2106 }
50892819
GS
2107
2108 /* we have an fd, return a file stream */
2109 return (win32_fdopen(p[parent], (char *)mode));
2110
2111cleanup:
2112 /* we don't need to check for errors here */
2113 win32_close(p[0]);
2114 win32_close(p[1]);
2115 if (oldfd != -1) {
2116 win32_dup2(oldfd, stdfd);
2117 win32_close(oldfd);
2118 }
2119 return (NULL);
2120
4b556e6c 2121#endif /* USE_RTL_POPEN */
0a753a76
PP
2122}
2123
50892819
GS
2124/*
2125 * pclose() clone
2126 */
2127
68dc0745
PP
2128DllExport int
2129win32_pclose(FILE *pf)
0a753a76 2130{
4b556e6c 2131#ifdef USE_RTL_POPEN
390b85e7 2132 return _pclose(pf);
50892819 2133#else
4f63d024 2134 dTHX;
e17cb2a9
JD
2135 int childpid, status;
2136 SV *sv;
2137
4b556e6c 2138 sv = *av_fetch(w32_fdpid, win32_fileno(pf), TRUE);
e17cb2a9
JD
2139 if (SvIOK(sv))
2140 childpid = SvIVX(sv);
2141 else
2142 childpid = 0;
50892819
GS
2143
2144 if (!childpid) {
2145 errno = EBADF;
2146 return -1;
2147 }
2148
2149 win32_fclose(pf);
e17cb2a9
JD
2150 SvIVX(sv) = 0;
2151
0aaad0ff
GS
2152 if (win32_waitpid(childpid, &status, 0) == -1)
2153 return -1;
50892819 2154
0aaad0ff 2155 return status;
50892819 2156
4b556e6c 2157#endif /* USE_RTL_POPEN */
0a753a76
PP
2158}
2159
68dc0745 2160DllExport int
8d9b2e3c 2161win32_rename(const char *oname, const char *newname)
e24c7c18 2162{
7fac1903
GS
2163 WCHAR wOldName[MAX_PATH];
2164 WCHAR wNewName[MAX_PATH];
2165 BOOL bResult;
80252599
GS
2166 /* XXX despite what the documentation says about MoveFileEx(),
2167 * it doesn't work under Windows95!
2168 */
2169 if (IsWinNT()) {
7fac1903 2170 if (USING_WIDE()) {
73c4f7a1 2171 dTHX;
7fac1903
GS
2172 A2WHELPER(oname, wOldName, sizeof(wOldName), GETINTERPMODE());
2173 A2WHELPER(newname, wNewName, sizeof(wNewName), GETINTERPMODE());
2174 bResult = MoveFileExW(wOldName,wNewName,
2175 MOVEFILE_COPY_ALLOWED|MOVEFILE_REPLACE_EXISTING);
2176 }
2177 else {
2178 bResult = MoveFileExA(oname,newname,
2179 MOVEFILE_COPY_ALLOWED|MOVEFILE_REPLACE_EXISTING);
2180 }
2181 if (!bResult) {
80252599
GS
2182 DWORD err = GetLastError();
2183 switch (err) {
2184 case ERROR_BAD_NET_NAME:
2185 case ERROR_BAD_NETPATH:
2186 case ERROR_BAD_PATHNAME:
2187 case ERROR_FILE_NOT_FOUND:
2188 case ERROR_FILENAME_EXCED_RANGE:
2189 case ERROR_INVALID_DRIVE:
2190 case ERROR_NO_MORE_FILES:
2191 case ERROR_PATH_NOT_FOUND:
2192 errno = ENOENT;
2193 break;
2194 default:
2195 errno = EACCES;
2196 break;
2197 }
2198 return -1;
2199 }
2200 return 0;
e24c7c18 2201 }
80252599
GS
2202 else {
2203 int retval = 0;
2204 char tmpname[MAX_PATH+1];
2205 char dname[MAX_PATH+1];
2206 char *endname = Nullch;
2207 STRLEN tmplen = 0;
2208 DWORD from_attr, to_attr;
2209
2210 /* if oname doesn't exist, do nothing */
2211 from_attr = GetFileAttributes(oname);
2212 if (from_attr == 0xFFFFFFFF) {
2213 errno = ENOENT;
2214 return -1;
2215 }
2216
2217 /* if newname exists, rename it to a temporary name so that we
2218 * don't delete it in case oname happens to be the same file
2219 * (but perhaps accessed via a different path)
2220 */
2221 to_attr = GetFileAttributes(newname);
2222 if (to_attr != 0xFFFFFFFF) {
2223 /* if newname is a directory, we fail
2224 * XXX could overcome this with yet more convoluted logic */
2225 if (to_attr & FILE_ATTRIBUTE_DIRECTORY) {
2226 errno = EACCES;
2227 return -1;
2228 }
2229 tmplen = strlen(newname);
2230 strcpy(tmpname,newname);
2231 endname = tmpname+tmplen;
2232 for (; endname > tmpname ; --endname) {
2233 if (*endname == '/' || *endname == '\\') {
2234 *endname = '\0';
2235 break;
2236 }
2237 }
2238 if (endname > tmpname)
2239 endname = strcpy(dname,tmpname);
e24c7c18 2240 else
80252599
GS
2241 endname = ".";
2242
2243 /* get a temporary filename in same directory
2244 * XXX is this really the best we can do? */
2245 if (!GetTempFileName((LPCTSTR)endname, "plr", 0, tmpname)) {
2246 errno = ENOENT;
2247 return -1;
2248 }
2249 DeleteFile(tmpname);
2250
2251 retval = rename(newname, tmpname);
2252 if (retval != 0) {
2253 errno = EACCES;
2254 return retval;
e24c7c18
GS
2255 }
2256 }
80252599
GS
2257
2258 /* rename oname to newname */
2259 retval = rename(oname, newname);
2260
2261 /* if we created a temporary file before ... */
2262 if (endname != Nullch) {
2263 /* ...and rename succeeded, delete temporary file/directory */
2264 if (retval == 0)
2265 DeleteFile(tmpname);
2266 /* else restore it to what it was */
2267 else
2268 (void)rename(tmpname, newname);
2269 }
2270 return retval;
e24c7c18 2271 }
e24c7c18
GS
2272}
2273
2274DllExport int
68dc0745 2275win32_setmode(int fd, int mode)
0a753a76 2276{
390b85e7 2277 return setmode(fd, mode);
0a753a76
PP
2278}
2279
96e4d5b1
PP
2280DllExport long
2281win32_lseek(int fd, long offset, int origin)
2282{
390b85e7 2283 return lseek(fd, offset, origin);
96e4d5b1
PP
2284}
2285
2286DllExport long
2287win32_tell(int fd)
2288{
390b85e7 2289 return tell(fd);
96e4d5b1
PP
2290}
2291
68dc0745
PP
2292DllExport int
2293win32_open(const char *path, int flag, ...)
0a753a76 2294{
68dc0745
PP
2295 va_list ap;
2296 int pmode;
b9010385 2297 WCHAR wBuffer[MAX_PATH];
0a753a76
PP
2298
2299 va_start(ap, flag);
2300 pmode = va_arg(ap, int);
2301 va_end(ap);
2302
68dc0745 2303 if (stricmp(path, "/dev/null")==0)
7fac1903
GS
2304 path = "NUL";
2305
2306 if (USING_WIDE()) {
73c4f7a1 2307 dTHX;
7fac1903
GS
2308 A2WHELPER(path, wBuffer, sizeof(wBuffer), GETINTERPMODE());
2309 return _wopen(wBuffer, flag, pmode);
2310 }
390b85e7 2311 return open(path,flag,pmode);
0a753a76
PP
2312}
2313
68dc0745
PP
2314DllExport int
2315win32_close(int fd)
0a753a76 2316{
390b85e7 2317 return close(fd);
0a753a76
PP
2318}
2319
68dc0745 2320DllExport int
96e4d5b1
PP
2321win32_eof(int fd)
2322{
390b85e7 2323 return eof(fd);
96e4d5b1
PP
2324}
2325
2326DllExport int
68dc0745 2327win32_dup(int fd)
0a753a76 2328{
390b85e7 2329 return dup(fd);
0a753a76
PP
2330}
2331
68dc0745
PP
2332DllExport int
2333win32_dup2(int fd1,int fd2)
0a753a76 2334{
390b85e7 2335 return dup2(fd1,fd2);
0a753a76
PP
2336}
2337
68dc0745 2338DllExport int
3e3baf6d 2339win32_read(int fd, void *buf, unsigned int cnt)
0a753a76 2340{
390b85e7 2341 return read(fd, buf, cnt);
0a753a76
PP
2342}
2343
68dc0745 2344DllExport int
3e3baf6d 2345win32_write(int fd, const void *buf, unsigned int cnt)
0a753a76 2346{
390b85e7 2347 return write(fd, buf, cnt);
0a753a76
PP
2348}
2349
68dc0745 2350DllExport int
5aabfad6
PP
2351win32_mkdir(const char *dir, int mode)
2352{
390b85e7 2353 return mkdir(dir); /* just ignore mode */
5aabfad6 2354}
96e4d5b1 2355
5aabfad6
PP
2356DllExport int
2357win32_rmdir(const char *dir)
2358{
390b85e7 2359 return rmdir(dir);
5aabfad6 2360}
96e4d5b1 2361
5aabfad6
PP
2362DllExport int
2363win32_chdir(const char *dir)
2364{
390b85e7 2365 return chdir(dir);
5aabfad6 2366}
96e4d5b1 2367
0aaad0ff
GS
2368static char *
2369create_command_line(const char* command, const char * const *args)
2370{
2371 int index;
2372 char *cmd, *ptr, *arg;
2373 STRLEN len = strlen(command) + 1;
2374
2375 for (index = 0; (ptr = (char*)args[index]) != NULL; ++index)
2376 len += strlen(ptr) + 1;
2377
2378 New(1310, cmd, len, char);
2379 ptr = cmd;
2380 strcpy(ptr, command);
0aaad0ff
GS
2381
2382 for (index = 0; (arg = (char*)args[index]) != NULL; ++index) {
0aaad0ff 2383 ptr += strlen(ptr);
18a945d4
GS
2384 *ptr++ = ' ';
2385 strcpy(ptr, arg);
0aaad0ff
GS
2386 }
2387
2388 return cmd;
2389}
2390
2391static char *
2392qualified_path(const char *cmd)
2393{
2394 char *pathstr;
2395 char *fullcmd, *curfullcmd;
2396 STRLEN cmdlen = 0;
2397 int has_slash = 0;
2398
2399 if (!cmd)
2400 return Nullch;
2401 fullcmd = (char*)cmd;
2402 while (*fullcmd) {
2403 if (*fullcmd == '/' || *fullcmd == '\\')
2404 has_slash++;
2405 fullcmd++;
2406 cmdlen++;
2407 }
2408
2409 /* look in PATH */
2410 pathstr = win32_getenv("PATH");
2411 New(0, fullcmd, MAX_PATH+1, char);
2412 curfullcmd = fullcmd;
2413
2414 while (1) {
2415 DWORD res;
2416
2417 /* start by appending the name to the current prefix */
2418 strcpy(curfullcmd, cmd);
2419 curfullcmd += cmdlen;
2420
2421 /* if it doesn't end with '.', or has no extension, try adding
2422 * a trailing .exe first */
2423 if (cmd[cmdlen-1] != '.'
2424 && (cmdlen < 4 || cmd[cmdlen-4] != '.'))
2425 {
2426 strcpy(curfullcmd, ".exe");
2427 res = GetFileAttributes(fullcmd);
2428 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
2429 return fullcmd;
2430 *curfullcmd = '\0';
2431 }
2432
2433 /* that failed, try the bare name */
2434 res = GetFileAttributes(fullcmd);
2435 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
2436 return fullcmd;
2437
2438 /* quit if no other path exists, or if cmd already has path */
2439 if (!pathstr || !*pathstr || has_slash)
2440 break;
2441
2442 /* skip leading semis */
2443 while (*pathstr == ';')
2444 pathstr++;
2445
2446 /* build a new prefix from scratch */
2447 curfullcmd = fullcmd;
2448 while (*pathstr && *pathstr != ';') {
2449 if (*pathstr == '"') { /* foo;"baz;etc";bar */
2450 pathstr++; /* skip initial '"' */
2451 while (*pathstr && *pathstr != '"') {
2452 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
2453 *curfullcmd++ = *pathstr;
2454 pathstr++;
2455 }
2456 if (*pathstr)
2457 pathstr++; /* skip trailing '"' */
2458 }
2459 else {
2460 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
2461 *curfullcmd++ = *pathstr;
2462 pathstr++;
2463 }
2464 }
2465 if (*pathstr)
2466 pathstr++; /* skip trailing semi */
2467 if (curfullcmd > fullcmd /* append a dir separator */
2468 && curfullcmd[-1] != '/' && curfullcmd[-1] != '\\')
2469 {
2470 *curfullcmd++ = '\\';
2471 }
2472 }
2473GIVE_UP:
2474 Safefree(fullcmd);
2475 return Nullch;
2476}
2477
2478/* XXX this needs to be made more compatible with the spawnvp()
2479 * provided by the various RTLs. In particular, searching for
2480 * *.{com,bat,cmd} files (as done by the RTLs) is unimplemented.
2481 * This doesn't significantly affect perl itself, because we
2482 * always invoke things using PERL5SHELL if a direct attempt to
2483 * spawn the executable fails.
2484 *
2485 * XXX splitting and rejoining the commandline between do_aspawn()
2486 * and win32_spawnvp() could also be avoided.
2487 */
2488
5aabfad6 2489DllExport int
3e3baf6d 2490win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
0a753a76 2491{
0aaad0ff
GS
2492#ifdef USE_RTL_SPAWNVP
2493 return spawnvp(mode, cmdname, (char * const *)argv);
2494#else
2495 DWORD ret;
2496 STARTUPINFO StartupInfo;
2497 PROCESS_INFORMATION ProcessInformation;
2498 DWORD create = 0;
2499
2500 char *cmd = create_command_line(cmdname, strcmp(cmdname, argv[0]) == 0
2501 ? &argv[1] : argv);
2502 char *fullcmd = Nullch;
2503
2504 switch(mode) {
2505 case P_NOWAIT: /* asynch + remember result */
2506 if (w32_num_children >= MAXIMUM_WAIT_OBJECTS) {
2507 errno = EAGAIN;
2508 ret = -1;
2509 goto RETVAL;
2510 }
2511 /* FALL THROUGH */
2512 case P_WAIT: /* synchronous execution */
2513 break;
2514 default: /* invalid mode */
2515 errno = EINVAL;
2516 ret = -1;
2517 goto RETVAL;
2518 }
2519 memset(&StartupInfo,0,sizeof(StartupInfo));
2520 StartupInfo.cb = sizeof(StartupInfo);
3ffaa937
GS
2521 StartupInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
2522 StartupInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
2523 StartupInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
2524 if (StartupInfo.hStdInput != INVALID_HANDLE_VALUE &&
2525 StartupInfo.hStdOutput != INVALID_HANDLE_VALUE &&
2526 StartupInfo.hStdError != INVALID_HANDLE_VALUE)
2527 {
2528 StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
2529 }
2530 else {
2531 create |= CREATE_NEW_CONSOLE;
2532 }
2533
2534#ifndef DEBUGGING
2535 StartupInfo.dwFlags |= STARTF_USESHOWWINDOW;
2536 StartupInfo.wShowWindow = SW_HIDE;
2537#endif
0aaad0ff
GS
2538
2539RETRY:
2540 if (!CreateProcess(cmdname, /* search PATH to find executable */
2541 cmd, /* executable, and its arguments */
2542 NULL, /* process attributes */
2543 NULL, /* thread attributes */
2544 TRUE, /* inherit handles */
2545 create, /* creation flags */
2546 NULL, /* inherit environment */
2547 NULL, /* inherit cwd */
2548 &StartupInfo,
2549 &ProcessInformation))
2550 {
2551 /* initial NULL argument to CreateProcess() does a PATH
2552 * search, but it always first looks in the directory
2553 * where the current process was started, which behavior
2554 * is undesirable for backward compatibility. So we
2555 * jump through our own hoops by picking out the path
2556 * we really want it to use. */
2557 if (!fullcmd) {
2558 fullcmd = qualified_path(cmdname);
2559 if (fullcmd) {
2560 cmdname = fullcmd;
2561 goto RETRY;
2562 }
2563 }
2564 errno = ENOENT;
2565 ret = -1;
2566 goto RETVAL;
2567 }
2d7a9237 2568
0aaad0ff
GS
2569 if (mode == P_NOWAIT) {
2570 /* asynchronous spawn -- store handle, return PID */
2571 w32_child_handles[w32_num_children] = ProcessInformation.hProcess;
2572 ret = w32_child_pids[w32_num_children] = ProcessInformation.dwProcessId;
2573 ++w32_num_children;
2574 }
2575 else {
2576 WaitForSingleObject(ProcessInformation.hProcess, INFINITE);
2577 GetExitCodeProcess(ProcessInformation.hProcess, &ret);
2578 CloseHandle(ProcessInformation.hProcess);
2579 }
e17cb2a9 2580
0aaad0ff
GS
2581 CloseHandle(ProcessInformation.hThread);
2582RETVAL:
2583 Safefree(cmd);
2584 Safefree(fullcmd);
2585 return (int)ret;
2d7a9237 2586#endif
0a753a76
PP
2587}
2588
6890e559 2589DllExport int
eb62e965
JD
2590win32_execv(const char *cmdname, const char *const *argv)
2591{
2592 return execv(cmdname, (char *const *)argv);
2593}
2594
2595DllExport int
6890e559
GS
2596win32_execvp(const char *cmdname, const char *const *argv)
2597{
390b85e7 2598 return execvp(cmdname, (char *const *)argv);
6890e559
GS
2599}
2600
84902520
TB
2601DllExport void
2602win32_perror(const char *str)
2603{
390b85e7 2604 perror(str);
84902520
TB
2605}
2606
2607DllExport void
2608win32_setbuf(FILE *pf, char *buf)
2609{
390b85e7 2610 setbuf(pf, buf);
84902520
TB
2611}
2612
2613DllExport int
2614win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
2615{
390b85e7 2616 return setvbuf(pf, buf, type, size);
84902520
TB
2617}
2618
2619DllExport int
2620win32_flushall(void)
2621{
390b85e7 2622 return flushall();
84902520
TB
2623}
2624
2625DllExport int
2626win32_fcloseall(void)
2627{
390b85e7 2628 return fcloseall();
84902520
TB
2629}
2630
2631DllExport char*
2632win32_fgets(char *s, int n, FILE *pf)
2633{
390b85e7 2634 return fgets(s, n, pf);
84902520
TB
2635}
2636
2637DllExport char*
2638win32_gets(char *s)
2639{
390b85e7 2640 return gets(s);
84902520
TB
2641}
2642
2643DllExport int
2644win32_fgetc(FILE *pf)
2645{
390b85e7 2646 return fgetc(pf);
84902520
TB
2647}
2648
2649DllExport int
2650win32_putc(int c, FILE *pf)
2651{
390b85e7 2652 return putc(c,pf);
84902520
TB
2653}
2654
2655DllExport int
2656win32_puts(const char *s)
2657{
390b85e7 2658 return puts(s);
84902520
TB
2659}
2660
2661DllExport int
2662win32_getchar(void)
2663{
390b85e7 2664 return getchar();
84902520
TB
2665}
2666
2667DllExport int
2668win32_putchar(int c)
2669{
390b85e7 2670 return putchar(c);
84902520
TB
2671}
2672
bbc8f9de
NIS
2673#ifdef MYMALLOC
2674
2675#ifndef USE_PERL_SBRK
2676
2677static char *committed = NULL;
2678static char *base = NULL;
2679static char *reserved = NULL;
2680static char *brk = NULL;
2681static DWORD pagesize = 0;
2682static DWORD allocsize = 0;
2683
2684void *
2685sbrk(int need)
2686{
2687 void *result;
2688 if (!pagesize)
2689 {SYSTEM_INFO info;
2690 GetSystemInfo(&info);
2691 /* Pretend page size is larger so we don't perpetually
2692 * call the OS to commit just one page ...
2693 */
2694 pagesize = info.dwPageSize << 3;
2695 allocsize = info.dwAllocationGranularity;
2696 }
2697 /* This scheme fails eventually if request for contiguous
2698 * block is denied so reserve big blocks - this is only
2699 * address space not memory ...
2700 */
2701 if (brk+need >= reserved)
2702 {
2703 DWORD size = 64*1024*1024;
2704 char *addr;
2705 if (committed && reserved && committed < reserved)
2706 {
2707 /* Commit last of previous chunk cannot span allocations */
161b471a 2708 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
bbc8f9de
NIS
2709 if (addr)
2710 committed = reserved;
2711 }
2712 /* Reserve some (more) space
2713 * Note this is a little sneaky, 1st call passes NULL as reserved
2714 * so lets system choose where we start, subsequent calls pass
2715 * the old end address so ask for a contiguous block
2716 */
161b471a 2717 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
bbc8f9de
NIS
2718 if (addr)
2719 {
2720 reserved = addr+size;
2721 if (!base)
2722 base = addr;
2723 if (!committed)
2724 committed = base;
2725 if (!brk)
2726 brk = committed;
2727 }
2728 else
2729 {
2730 return (void *) -1;
2731 }
2732 }
2733 result = brk;
2734 brk += need;
2735 if (brk > committed)
2736 {
2737 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
161b471a 2738 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
bbc8f9de
NIS
2739 if (addr)
2740 {
2741 committed += size;
2742 }
2743 else
2744 return (void *) -1;
2745 }
2746 return result;
2747}
2748
2749#endif
2750#endif
2751
84902520
TB
2752DllExport void*
2753win32_malloc(size_t size)
2754{
390b85e7 2755 return malloc(size);
84902520
TB
2756}
2757
2758DllExport void*
2759win32_calloc(size_t numitems, size_t size)
2760{
390b85e7 2761 return calloc(numitems,size);
84902520
TB
2762}
2763
2764DllExport void*
2765win32_realloc(void *block, size_t size)
2766{
390b85e7 2767 return realloc(block,size);
84902520
TB
2768}
2769
2770DllExport void
2771win32_free(void *block)
2772{
390b85e7 2773 free(block);
84902520
TB
2774}
2775
bbc8f9de 2776
68dc0745 2777int
65e48ea9 2778win32_open_osfhandle(long handle, int flags)
0a753a76 2779{
390b85e7 2780 return _open_osfhandle(handle, flags);
0a753a76
PP
2781}
2782
68dc0745 2783long
65e48ea9 2784win32_get_osfhandle(int fd)
0a753a76 2785{
390b85e7 2786 return _get_osfhandle(fd);
0a753a76 2787}
7bac28a0 2788
7bac28a0
PP
2789/*
2790 * Extras.
2791 */
2792
ad2e33dc
GS
2793static
2794XS(w32_GetCwd)
2795{
2796 dXSARGS;
2797 SV *sv = sv_newmortal();
2798 /* Make one call with zero size - return value is required size */
2799 DWORD len = GetCurrentDirectory((DWORD)0,NULL);
2800 SvUPGRADE(sv,SVt_PV);
2801 SvGROW(sv,len);
2802 SvCUR(sv) = GetCurrentDirectory((DWORD) SvLEN(sv), SvPVX(sv));
2803 /*
2804 * If result != 0
2805 * then it worked, set PV valid,
2806 * else leave it 'undef'
2807 */
3467312b 2808 EXTEND(SP,1);
bb897dfc 2809 if (SvCUR(sv)) {
ad2e33dc 2810 SvPOK_on(sv);
bb897dfc
JD
2811 ST(0) = sv;
2812 XSRETURN(1);
2813 }
3467312b 2814 XSRETURN_UNDEF;
ad2e33dc
GS
2815}
2816
2817static
2818XS(w32_SetCwd)
2819{
2820 dXSARGS;
2821 if (items != 1)
4f63d024 2822 Perl_croak(aTHX_ "usage: Win32::SetCurrentDirectory($cwd)");
bb897dfc 2823 if (SetCurrentDirectory(SvPV_nolen(ST(0))))
ad2e33dc
GS
2824 XSRETURN_YES;
2825
2826 XSRETURN_NO;
2827}
2828
2829static
2830XS(w32_GetNextAvailDrive)
2831{
2832 dXSARGS;
2833 char ix = 'C';
2834 char root[] = "_:\\";
3467312b
JD
2835
2836 EXTEND(SP,1);
ad2e33dc
GS
2837 while (ix <= 'Z') {
2838 root[0] = ix++;
2839 if (GetDriveType(root) == 1) {
2840 root[2] = '\0';
2841 XSRETURN_PV(root);
2842 }
2843 }
3467312b 2844 XSRETURN_UNDEF;
ad2e33dc
GS
2845}
2846
2847static
2848XS(w32_GetLastError)
2849{
2850 dXSARGS;
bb897dfc 2851 EXTEND(SP,1);
ad2e33dc
GS
2852 XSRETURN_IV(GetLastError());
2853}
2854
2855static
ca135624
JD
2856XS(w32_SetLastError)
2857{
2858 dXSARGS;
2859 if (items != 1)
4f63d024 2860 Perl_croak(aTHX_ "usage: Win32::SetLastError($error)");
ca135624 2861 SetLastError(SvIV(ST(0)));
bb897dfc 2862 XSRETURN_EMPTY;
ca135624
JD
2863}
2864
2865static
ad2e33dc
GS
2866XS(w32_LoginName)
2867{
2868 dXSARGS;
e34ffe5a
GS
2869 char *name = getlogin_buffer;
2870 DWORD size = sizeof(getlogin_buffer);
3467312b 2871 EXTEND(SP,1);
ad2e33dc
GS
2872 if (GetUserName(name,&size)) {
2873 /* size includes NULL */
79cb57f6 2874 ST(0) = sv_2mortal(newSVpvn(name,size-1));
ad2e33dc
GS
2875 XSRETURN(1);
2876 }
3467312b 2877 XSRETURN_UNDEF;
ad2e33dc
GS
2878}
2879
2880static
2881XS(w32_NodeName)
2882{
2883 dXSARGS;
2884 char name[MAX_COMPUTERNAME_LENGTH+1];
2885 DWORD size = sizeof(name);
3467312b 2886 EXTEND(SP,1);
ad2e33dc
GS
2887 if (GetComputerName(name,&size)) {
2888 /* size does NOT include NULL :-( */
79cb57f6 2889 ST(0) = sv_2mortal(newSVpvn(name,size));
ad2e33dc
GS
2890 XSRETURN(1);
2891 }
3467312b 2892 XSRETURN_UNDEF;
ad2e33dc
GS
2893}
2894
2895
2896static
2897XS(w32_DomainName)
2898{
2899 dXSARGS;
8c9208bc
GS
2900#ifndef HAS_NETWKSTAGETINFO
2901 /* mingw32 (and Win95) don't have NetWksta*(), so do it the old way */
ad2e33dc
GS
2902 char name[256];
2903 DWORD size = sizeof(name);
3467312b 2904 EXTEND(SP,1);
ad2e33dc
GS
2905 if (GetUserName(name,&size)) {
2906 char sid[1024];
2907 DWORD sidlen = sizeof(sid);
2908 char dname[256];
2909 DWORD dnamelen = sizeof(dname);
2910 SID_NAME_USE snu;
db15561c 2911 if (LookupAccountName(NULL, name, (PSID)&sid, &sidlen,
ad2e33dc
GS
2912 dname, &dnamelen, &snu)) {
2913 XSRETURN_PV(dname); /* all that for this */
2914 }
2915 }
e56670dd 2916#else
8c9208bc
GS
2917 /* this way is more reliable, in case user has a local account.
2918 * XXX need dynamic binding of netapi32.dll symbols or this will fail on
2919 * Win95. Probably makes more sense to move it into libwin32. */
9404a519
GS
2920 char dname[256];
2921 DWORD dnamelen = sizeof(dname);
0a2408cf 2922 PWKSTA_INFO_100 pwi;
3467312b 2923 EXTEND(SP,1);
0a2408cf
GS
2924 if (NERR_Success == NetWkstaGetInfo(NULL, 100, (LPBYTE*)&pwi)) {
2925 if (pwi->wki100_langroup && *(pwi->wki100_langroup)) {
2926 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_langroup,
2927 -1, (LPSTR)dname, dnamelen, NULL, NULL);
2928 }
2929 else {
2930 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_computername,
2931 -1, (LPSTR)dname, dnamelen, NULL, NULL);
2932 }
2933 NetApiBufferFree(pwi);
9404a519
GS
2934 XSRETURN_PV(dname);
2935 }
e56670dd 2936#endif
3467312b 2937 XSRETURN_UNDEF;
ad2e33dc
GS
2938}
2939
2940static
2941XS(w32_FsType)
2942{
2943 dXSARGS;
2944 char fsname[256];
2945 DWORD flags, filecomplen;
2946 if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
2947 &flags, fsname, sizeof(fsname))) {
bb897dfc 2948 if (GIMME_V == G_ARRAY) {
79cb57f6 2949 XPUSHs(sv_2mortal(newSVpvn(fsname,strlen(fsname))));
ad2e33dc
GS
2950 XPUSHs(sv_2mortal(newSViv(flags)));
2951 XPUSHs(sv_2mortal(newSViv(filecomplen)));
2952 PUTBACK;
2953 return;
2954 }
bb897dfc 2955 EXTEND(SP,1);
ad2e33dc
GS
2956 XSRETURN_PV(fsname);
2957 }
bb897dfc 2958 XSRETURN_EMPTY;
ad2e33dc
GS
2959}
2960
2961static
2962XS(w32_GetOSVersion)
2963{
2964 dXSARGS;
2965 OSVERSIONINFO osver;
2966
2967 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
2968 if (GetVersionEx(&osver)) {
79cb57f6 2969 XPUSHs(newSVpvn(osver.szCSDVersion, strlen(osver.szCSDVersion)));
ad2e33dc
GS
2970 XPUSHs(newSViv(osver.dwMajorVersion));
2971 XPUSHs(newSViv(osver.dwMinorVersion));
2972 XPUSHs(newSViv(osver.dwBuildNumber));
2973 XPUSHs(newSViv(osver.dwPlatformId));
2974 PUTBACK;
2975 return;
2976 }
bb897dfc 2977 XSRETURN_EMPTY;
ad2e33dc
GS
2978}
2979
2980static
2981XS(w32_IsWinNT)
2982{
2983 dXSARGS;
bb897dfc 2984 EXTEND(SP,1);
ad2e33dc
GS
2985 XSRETURN_IV(IsWinNT());
2986}
2987
2988static
2989XS(w32_IsWin95)
2990{
2991 dXSARGS;
bb897dfc 2992 EXTEND(SP,1);
ad2e33dc
GS
2993 XSRETURN_IV(IsWin95());
2994}
2995
2996static
2997XS(w32_FormatMessage)
2998{
2999 dXSARGS;
3000 DWORD source = 0;
3001 char msgbuf[1024];
3002
3003 if (items != 1)
4f63d024 3004 Perl_croak(aTHX_ "usage: Win32::FormatMessage($errno)");
ad2e33dc
GS
3005
3006 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
3007 &source, SvIV(ST(0)), 0,
3008 msgbuf, sizeof(msgbuf)-1, NULL))
3009 XSRETURN_PV(msgbuf);
3010
3467312b 3011 XSRETURN_UNDEF;
ad2e33dc
GS
3012}
3013
3014static
3015XS(w32_Spawn)
3016{
3017 dXSARGS;
3018 char *cmd, *args;
3019 PROCESS_INFORMATION stProcInfo;
3020 STARTUPINFO stStartInfo;
3021 BOOL bSuccess = FALSE;
3022
9404a519 3023 if (items != 3)
4f63d024 3024 Perl_croak(aTHX_ "usage: Win32::Spawn($cmdName, $args, $PID)");
ad2e33dc 3025
bb897dfc
JD
3026 cmd = SvPV_nolen(ST(0));
3027 args = SvPV_nolen(ST(1));
ad2e33dc
GS
3028
3029 memset(&stStartInfo, 0, sizeof(stStartInfo)); /* Clear the block */
3030 stStartInfo.cb = sizeof(stStartInfo); /* Set the structure size */
3031 stStartInfo.dwFlags = STARTF_USESHOWWINDOW; /* Enable wShowWindow control */
3032 stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE; /* Start min (normal) */
3033
9404a519 3034 if (CreateProcess(
ad2e33dc
GS
3035 cmd, /* Image path */
3036 args, /* Arguments for command line */
3037 NULL, /* Default process security */
3038 NULL, /* Default thread security */
3039 FALSE, /* Must be TRUE to use std handles */
3040 NORMAL_PRIORITY_CLASS, /* No special scheduling */
3041 NULL, /* Inherit our environment block */
3042 NULL, /* Inherit our currrent directory */
3043 &stStartInfo, /* -> Startup info */
3044 &stProcInfo)) /* <- Process info (if OK) */
3045 {
3046 CloseHandle(stProcInfo.hThread);/* library source code does this. */
3047 sv_setiv(ST(2), stProcInfo.dwProcessId);
3048 bSuccess = TRUE;
3049 }
3050 XSRETURN_IV(bSuccess);
3051}
3052
3053static
3054XS(w32_GetTickCount)
3055{
3056 dXSARGS;
fdb068fa 3057 DWORD msec = GetTickCount();
a6c40364 3058 EXTEND(SP,1);
fdb068fa
JD
3059 if ((IV)msec > 0)
3060 XSRETURN_IV(msec);
3061 XSRETURN_NV(msec);
ad2e33dc
GS
3062}
3063
3064static
3065XS(w32_GetShortPathName)
3066{
3067 dXSARGS;
3068 SV *shortpath;
e8bab181 3069 DWORD len;
ad2e33dc 3070
9404a519 3071 if (items != 1)
4f63d024 3072 Perl_croak(aTHX_ "usage: Win32::GetShortPathName($longPathName)");
ad2e33dc
GS
3073
3074 shortpath = sv_mortalcopy(ST(0));
3075 SvUPGRADE(shortpath, SVt_PV);
3076 /* src == target is allowed */
e8bab181
GS
3077 do {
3078 len = GetShortPathName(SvPVX(shortpath),
3079 SvPVX(shortpath),
3080 SvLEN(shortpath));
3081 } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
3082 if (len) {
3083 SvCUR_set(shortpath,len);
ad2e33dc 3084 ST(0) = shortpath;
bb897dfc 3085 XSRETURN(1);
e8bab181 3086 }
3467312b 3087 XSRETURN_UNDEF;
ad2e33dc
GS
3088}
3089
ad0751ec 3090static
ca135624
JD
3091XS(w32_GetFullPathName)
3092{
3093 dXSARGS;
3094 SV *filename;
3095 SV *fullpath;
3096 char *filepart;
3097 DWORD len;
3098
3099 if (items != 1)
4f63d024 3100 Perl_croak(aTHX_ "usage: Win32::GetFullPathName($filename)");
ca135624
JD
3101
3102 filename = ST(0);
3103 fullpath = sv_mortalcopy(filename);
3104 SvUPGRADE(fullpath, SVt_PV);
3105 do {
3106 len = GetFullPathName(SvPVX(filename),
3107 SvLEN(fullpath),
3108 SvPVX(fullpath),
3109 &filepart);
3110 } while (len >= SvLEN(fullpath) && sv_grow(fullpath,len+1));
3111 if (len) {
3112 if (GIMME_V == G_ARRAY) {
3113 EXTEND(SP,1);
bb897dfc 3114 XST_mPV(1,filepart);
ca135624
JD
3115 len = filepart - SvPVX(fullpath);
3116 items = 2;
3117 }
3118 SvCUR_set(fullpath,len);
3119 ST(0) = fullpath;
bb897dfc 3120 XSRETURN(items);
ca135624 3121 }
bb897dfc 3122 XSRETURN_EMPTY;
ca135624
JD
3123}
3124
3125static
8ac9c18d
GS
3126XS(w32_GetLongPathName)
3127{
3128 dXSARGS;
3129 SV *path;
3130 char tmpbuf[MAX_PATH+1];
3131 char *pathstr;
3132 STRLEN len;
3133
3134 if (items != 1)
4f63d024 3135 Perl_croak(aTHX_ "usage: Win32::GetLongPathName($pathname)");
8ac9c18d
GS
3136
3137 path = ST(0);
3138 pathstr = SvPV(path,len);
3139 strcpy(tmpbuf, pathstr);
3140 pathstr = win32_longpath(tmpbuf);
3141 if (pathstr) {
3142 ST(0) = sv_2mortal(newSVpvn(pathstr, strlen(pathstr)));
3143 XSRETURN(1);
3144 }
3145 XSRETURN_EMPTY;
3146}
3147
3148static
ad0751ec
GS
3149XS(w32_Sleep)
3150{
3151 dXSARGS;
3152 if (items != 1)
4f63d024 3153 Perl_croak(aTHX_ "usage: Win32::Sleep($milliseconds)");
ad0751ec
GS
3154 Sleep(SvIV(ST(0)));
3155 XSRETURN_YES;
3156}
3157
7509b657
GS
3158static
3159XS(w32_CopyFile)
3160{
3161 dXSARGS;
3162 if (items != 3)
4f63d024 3163 Perl_croak(aTHX_ "usage: Win32::CopyFile($from, $to, $overwrite)");
7509b657
GS
3164 if (CopyFile(SvPV_nolen(ST(0)), SvPV_nolen(ST(1)), !SvTRUE(ST(2))))
3165 XSRETURN_YES;
3166 XSRETURN_NO;
3167}
3168
ad2e33dc 3169void
4f63d024 3170Perl_init_os_extras(pTHX)
ad2e33dc
GS
3171{
3172 char *file = __FILE__;
3173 dXSUB_SYS;
3174
4b556e6c
JD
3175 w32_perlshell_tokens = Nullch;
3176 w32_perlshell_items = -1;
3177 w32_fdpid = newAV(); /* XXX needs to be in Perl_win32_init()? */
0aaad0ff 3178 New(1313, w32_children, 1, child_tab);
4b556e6c 3179 w32_num_children = 0;
4b556e6c 3180
ad2e33dc
GS
3181 /* these names are Activeware compatible */
3182 newXS("Win32::GetCwd", w32_GetCwd, file);
3183 newXS("Win32::SetCwd", w32_SetCwd, file);
3184 newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
3185 newXS("Win32::GetLastError", w32_GetLastError, file);
ca135624 3186 newXS("Win32::SetLastError", w32_SetLastError, file);
ad2e33dc
GS
3187 newXS("Win32::LoginName", w32_LoginName, file);
3188 newXS("Win32::NodeName", w32_NodeName, file);
3189 newXS("Win32::DomainName", w32_DomainName, file);
3190 newXS("Win32::FsType", w32_FsType, file);
3191 newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
3192 newXS("Win32::IsWinNT", w32_IsWinNT, file);
3193 newXS("Win32::IsWin95", w32_IsWin95, file);
3194 newXS("Win32::FormatMessage", w32_FormatMessage, file);
3195 newXS("Win32::Spawn", w32_Spawn, file);
3196 newXS("Win32::GetTickCount", w32_GetTickCount, file);
3197 newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
ca135624 3198 newXS("Win32::GetFullPathName", w32_GetFullPathName, file);
8ac9c18d 3199 newXS("Win32::GetLongPathName", w32_GetLongPathName, file);
7509b657 3200 newXS("Win32::CopyFile", w32_CopyFile, file);
ad0751ec 3201 newXS("Win32::Sleep", w32_Sleep, file);
ad2e33dc
GS
3202
3203 /* XXX Bloat Alert! The following Activeware preloads really
3204 * ought to be part of Win32::Sys::*, so they're not included
3205 * here.
3206 */
3207 /* LookupAccountName
3208 * LookupAccountSID
3209 * InitiateSystemShutdown
3210 * AbortSystemShutdown
3211 * ExpandEnvrironmentStrings
3212 */
3213}
3214
3215void
3216Perl_win32_init(int *argcp, char ***argvp)
3217{
3218 /* Disable floating point errors, Perl will trap the ones we
3219 * care about. VC++ RTL defaults to switching these off
3220 * already, but the Borland RTL doesn't. Since we don't
3221 * want to be at the vendor's whim on the default, we set
3222 * it explicitly here.
3223 */
a835ef8a 3224#if !defined(_ALPHA_) && !defined(__GNUC__)
ad2e33dc 3225 _control87(MCW_EM, MCW_EM);
3dc9191e 3226#endif
4b556e6c 3227 MALLOC_INIT;
ad2e33dc 3228}
d55594ae 3229
a868473f
NIS
3230#ifdef USE_BINMODE_SCRIPTS
3231
3232void
3233win32_strip_return(SV *sv)
3234{
3235 char *s = SvPVX(sv);
3236 char *e = s+SvCUR(sv);
3237 char *d = s;
3238 while (s < e)
3239 {
3240 if (*s == '\r' && s[1] == '\n')
3241 {
3242 *d++ = '\n';
3243 s += 2;
3244 }
3245 else
3246 {
3247 *d++ = *s++;
3248 }
3249 }
3250 SvCUR_set(sv,d-SvPVX(sv));
3251}
3252
3253#endif