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