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