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