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