This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
PerlIO fixups for Win32:
[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");
521 const char *usershell = getenv("PERL5SHELL");
ce1da67e
GS
522 w32_perlshell_items = tokenize(usershell ? usershell : defaultshell,
523 &w32_perlshell_tokens,
524 &w32_perlshell_vec);
68dc0745 525 }
0a753a76
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
GS
852 /* bump the string table size by enough for the
853 * new name and it's 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
177a48aa 1655#if (defined(__BORLANDC__)&&(__BORLANDC__<=0x520)) || defined(__MINGW32__)
a6c40364
GS
1656 switch (info.u.s.wProcessorArchitecture) {
1657#else
b2af26b1 1658 switch (info.wProcessorArchitecture) {
a6c40364 1659#endif
b2af26b1
GS
1660 case PROCESSOR_ARCHITECTURE_INTEL:
1661 arch = "x86"; break;
1662 case PROCESSOR_ARCHITECTURE_MIPS:
1663 arch = "mips"; break;
1664 case PROCESSOR_ARCHITECTURE_ALPHA:
1665 arch = "alpha"; break;
1666 case PROCESSOR_ARCHITECTURE_PPC:
1667 arch = "ppc"; break;
1668 default:
1669 arch = "unknown"; break;
1670 }
1671 strcpy(name->machine, arch);
1672 }
1673 return 0;
1674}
1675
1676DllExport int
f55ee38a
GS
1677win32_waitpid(int pid, int *status, int flags)
1678{
c5be433b 1679 dTHXo;
922b1888 1680 DWORD timeout = (flags & WNOHANG) ? 0 : INFINITE;
0aaad0ff 1681 int retval = -1;
c66b022d 1682 long child;
7766f137 1683 if (pid == -1) /* XXX threadid == 1 ? */
0aaad0ff 1684 return win32_wait(status);
7766f137
GS
1685#ifdef USE_ITHREADS
1686 else if (pid < 0) {
c66b022d 1687 child = find_pseudo_pid(-pid);
7766f137
GS
1688 if (child >= 0) {
1689 HANDLE hThread = w32_pseudo_child_handles[child];
2f67576d
BC
1690 DWORD waitcode = WaitForSingleObject(hThread, timeout);
1691 if (waitcode == WAIT_TIMEOUT) {
1692 return 0;
1693 }
1694 else if (waitcode != WAIT_FAILED) {
7766f137
GS
1695 if (GetExitCodeThread(hThread, &waitcode)) {
1696 *status = (int)((waitcode & 0xff) << 8);
1697 retval = (int)w32_pseudo_child_pids[child];
1698 remove_dead_pseudo_process(child);
68a29c53 1699 return -retval;
7766f137
GS
1700 }
1701 }
1702 else
1703 errno = ECHILD;
1704 }
922b1888
GS
1705 else if (IsWin95()) {
1706 pid = -pid;
1707 goto alien_process;
1708 }
7766f137
GS
1709 }
1710#endif
f55ee38a 1711 else {
922b1888
GS
1712 HANDLE hProcess;
1713 DWORD waitcode;
c66b022d 1714 child = find_pid(pid);
0aaad0ff 1715 if (child >= 0) {
922b1888
GS
1716 hProcess = w32_child_handles[child];
1717 waitcode = WaitForSingleObject(hProcess, timeout);
a7867d0a
GS
1718 if (waitcode == WAIT_TIMEOUT) {
1719 return 0;
1720 }
1721 else if (waitcode != WAIT_FAILED) {
922b1888
GS
1722 if (GetExitCodeProcess(hProcess, &waitcode)) {
1723 *status = (int)((waitcode & 0xff) << 8);
1724 retval = (int)w32_child_pids[child];
1725 remove_dead_process(child);
1726 return retval;
1727 }
a7867d0a 1728 }
0aaad0ff
GS
1729 else
1730 errno = ECHILD;
1731 }
1732 else {
922b1888
GS
1733alien_process:
1734 hProcess = OpenProcess(PROCESS_ALL_ACCESS, TRUE,
1735 (IsWin95() ? -pid : pid));
1736 if (hProcess) {
1737 waitcode = WaitForSingleObject(hProcess, timeout);
1738 if (waitcode == WAIT_TIMEOUT) {
1739 return 0;
1740 }
1741 else if (waitcode != WAIT_FAILED) {
1742 if (GetExitCodeProcess(hProcess, &waitcode)) {
1743 *status = (int)((waitcode & 0xff) << 8);
1744 CloseHandle(hProcess);
1745 return pid;
1746 }
1747 }
1748 CloseHandle(hProcess);
1749 }
1750 else
1751 errno = ECHILD;
0aaad0ff 1752 }
f55ee38a 1753 }
0aaad0ff 1754 return retval >= 0 ? pid : retval;
f55ee38a
GS
1755}
1756
1757DllExport int
2d7a9237
GS
1758win32_wait(int *status)
1759{
2d7a9237
GS
1760 /* XXX this wait emulation only knows about processes
1761 * spawned via win32_spawnvp(P_NOWAIT, ...).
1762 */
c5be433b 1763 dTHXo;
2d7a9237
GS
1764 int i, retval;
1765 DWORD exitcode, waitcode;
1766
7766f137
GS
1767#ifdef USE_ITHREADS
1768 if (w32_num_pseudo_children) {
1769 waitcode = WaitForMultipleObjects(w32_num_pseudo_children,
1770 w32_pseudo_child_handles,
1771 FALSE,
1772 INFINITE);
1773 if (waitcode != WAIT_FAILED) {
1774 if (waitcode >= WAIT_ABANDONED_0
1775 && waitcode < WAIT_ABANDONED_0 + w32_num_pseudo_children)
1776 i = waitcode - WAIT_ABANDONED_0;
1777 else
1778 i = waitcode - WAIT_OBJECT_0;
1779 if (GetExitCodeThread(w32_pseudo_child_handles[i], &exitcode)) {
1780 *status = (int)((exitcode & 0xff) << 8);
1781 retval = (int)w32_pseudo_child_pids[i];
1782 remove_dead_pseudo_process(i);
68a29c53 1783 return -retval;
7766f137
GS
1784 }
1785 }
1786 }
1787#endif
1788
2d7a9237
GS
1789 if (!w32_num_children) {
1790 errno = ECHILD;
1791 return -1;
1792 }
1793
1794 /* if a child exists, wait for it to die */
1795 waitcode = WaitForMultipleObjects(w32_num_children,
0aaad0ff 1796 w32_child_handles,
2d7a9237
GS
1797 FALSE,
1798 INFINITE);
1799 if (waitcode != WAIT_FAILED) {
1800 if (waitcode >= WAIT_ABANDONED_0
1801 && waitcode < WAIT_ABANDONED_0 + w32_num_children)
1802 i = waitcode - WAIT_ABANDONED_0;
1803 else
1804 i = waitcode - WAIT_OBJECT_0;
0aaad0ff 1805 if (GetExitCodeProcess(w32_child_handles[i], &exitcode) ) {
2d7a9237
GS
1806 *status = (int)((exitcode & 0xff) << 8);
1807 retval = (int)w32_child_pids[i];
0aaad0ff 1808 remove_dead_process(i);
2d7a9237
GS
1809 return retval;
1810 }
1811 }
1812
1813FAILED:
1814 errno = GetLastError();
1815 return -1;
2d7a9237 1816}
d55594ae 1817
1be9d9c6
GS
1818#ifndef PERL_OBJECT
1819
2d7a9237 1820static UINT timerid = 0;
d55594ae
GS
1821
1822static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
1823{
c5be433b 1824 dTHXo;
0cb96387
GS
1825 KillTimer(NULL,timerid);
1826 timerid=0;
b319cd58 1827 CALL_FPTR(PL_sighandlerp)(14);
d55594ae 1828}
1be9d9c6 1829#endif /* !PERL_OBJECT */
d55594ae 1830
f3986ebb
GS
1831DllExport unsigned int
1832win32_alarm(unsigned int sec)
0a753a76 1833{
1be9d9c6 1834#ifndef PERL_OBJECT
d55594ae
GS
1835 /*
1836 * the 'obvious' implentation is SetTimer() with a callback
1837 * which does whatever receiving SIGALRM would do
1838 * we cannot use SIGALRM even via raise() as it is not
1839 * one of the supported codes in <signal.h>
1840 *
1841 * Snag is unless something is looking at the message queue
1842 * nothing happens :-(
1843 */
c5be433b 1844 dTHXo;
d55594ae
GS
1845 if (sec)
1846 {
1847 timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
1848 if (!timerid)
4f63d024 1849 Perl_croak_nocontext("Cannot set timer");
d55594ae
GS
1850 }
1851 else
1852 {
1853 if (timerid)
1854 {
1855 KillTimer(NULL,timerid);
1856 timerid=0;
1857 }
1858 }
1be9d9c6 1859#endif /* !PERL_OBJECT */
68dc0745 1860 return 0;
0a753a76
PP
1861}
1862
26618a56 1863#ifdef HAVE_DES_FCRYPT
2d77217b 1864extern char * des_fcrypt(const char *txt, const char *salt, char *cbuf);
ff95b63e 1865#endif
26618a56
GS
1866
1867DllExport char *
1868win32_crypt(const char *txt, const char *salt)
1869{
0b94c7bb 1870 dTHXo;
ff95b63e 1871#ifdef HAVE_DES_FCRYPT
3352bfcb 1872 return des_fcrypt(txt, salt, w32_crypt_buffer);
ff95b63e 1873#else
25dbdbbc 1874 Perl_croak(aTHX_ "The crypt() function is unimplemented due to excessive paranoia.");
b8957cf1 1875 return Nullch;
ff95b63e 1876#endif
26618a56 1877}
26618a56 1878
9e5f57de 1879#ifdef USE_FIXED_OSFHANDLE
390b85e7
GS
1880
1881#define FOPEN 0x01 /* file handle open */
b181b6fb 1882#define FNOINHERIT 0x10 /* file handle opened O_NOINHERIT */
390b85e7
GS
1883#define FAPPEND 0x20 /* file handle opened O_APPEND */
1884#define FDEV 0x40 /* file handle refers to device */
1885#define FTEXT 0x80 /* file handle is in text mode */
1886
390b85e7
GS
1887/***
1888*int my_open_osfhandle(long osfhandle, int flags) - open C Runtime file handle
1889*
1890*Purpose:
1891* This function allocates a free C Runtime file handle and associates
1892* it with the Win32 HANDLE specified by the first parameter. This is a
9e5f57de
GS
1893* temperary fix for WIN95's brain damage GetFileType() error on socket
1894* we just bypass that call for socket
1895*
1896* This works with MSVC++ 4.0+ or GCC/Mingw32
390b85e7
GS
1897*
1898*Entry:
1899* long osfhandle - Win32 HANDLE to associate with C Runtime file handle.
1900* int flags - flags to associate with C Runtime file handle.
1901*
1902*Exit:
1903* returns index of entry in fh, if successful
1904* return -1, if no free entry is found
1905*
1906*Exceptions:
1907*
1908*******************************************************************************/
1909
9e5f57de
GS
1910/*
1911 * we fake up some parts of the CRT that aren't exported by MSVCRT.dll
1912 * this lets sockets work on Win9X with GCC and should fix the problems
1913 * with perl95.exe
1914 * -- BKS, 1-23-2000
1915*/
1916
9e5f57de
GS
1917/* create an ioinfo entry, kill its handle, and steal the entry */
1918
b181b6fb
GS
1919static int
1920_alloc_osfhnd(void)
9e5f57de
GS
1921{
1922 HANDLE hF = CreateFile("NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
dd8f4818 1923 int fh = _open_osfhandle((long)hF, 0);
9e5f57de
GS
1924 CloseHandle(hF);
1925 if (fh == -1)
1926 return fh;
1927 EnterCriticalSection(&(_pioinfo(fh)->lock));
1928 return fh;
1929}
1930
390b85e7
GS
1931static int
1932my_open_osfhandle(long osfhandle, int flags)
1933{
1934 int fh;
1935 char fileflags; /* _osfile flags */
1936
1937 /* copy relevant flags from second parameter */
1938 fileflags = FDEV;
1939
9404a519 1940 if (flags & O_APPEND)
390b85e7
GS
1941 fileflags |= FAPPEND;
1942
9404a519 1943 if (flags & O_TEXT)
390b85e7
GS
1944 fileflags |= FTEXT;
1945
b181b6fb
GS
1946 if (flags & O_NOINHERIT)
1947 fileflags |= FNOINHERIT;
1948
390b85e7 1949 /* attempt to allocate a C Runtime file handle */
9404a519 1950 if ((fh = _alloc_osfhnd()) == -1) {
390b85e7
GS
1951 errno = EMFILE; /* too many open files */
1952 _doserrno = 0L; /* not an OS error */
1953 return -1; /* return error to caller */
1954 }
1955
1956 /* the file is open. now, set the info in _osfhnd array */
1957 _set_osfhnd(fh, osfhandle);
1958
1959 fileflags |= FOPEN; /* mark as open */
1960
390b85e7 1961 _osfile(fh) = fileflags; /* set osfile entry */
dd8f4818 1962 LeaveCriticalSection(&_pioinfo(fh)->lock);
390b85e7
GS
1963
1964 return fh; /* return handle */
1965}
1966
f3986ebb 1967#endif /* USE_FIXED_OSFHANDLE */
390b85e7
GS
1968
1969/* simulate flock by locking a range on the file */
1970
1971#define LK_ERR(f,i) ((f) ? (i = 0) : (errno = GetLastError()))
1972#define LK_LEN 0xffff0000
1973
f3986ebb
GS
1974DllExport int
1975win32_flock(int fd, int oper)
390b85e7
GS
1976{
1977 OVERLAPPED o;
1978 int i = -1;
1979 HANDLE fh;
1980
f3986ebb 1981 if (!IsWinNT()) {
c5be433b 1982 dTHXo;
4f63d024 1983 Perl_croak_nocontext("flock() unimplemented on this platform");
f3986ebb
GS
1984 return -1;
1985 }
390b85e7
GS
1986 fh = (HANDLE)_get_osfhandle(fd);
1987 memset(&o, 0, sizeof(o));
1988
1989 switch(oper) {
1990 case LOCK_SH: /* shared lock */
1991 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
1992 break;
1993 case LOCK_EX: /* exclusive lock */
1994 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
1995 break;
1996 case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
1997 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
1998 break;
1999 case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
2000 LK_ERR(LockFileEx(fh,
2001 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
2002 0, LK_LEN, 0, &o),i);
2003 break;
2004 case LOCK_UN: /* unlock lock */
2005 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, 0, &o),i);
2006 break;
2007 default: /* unknown */
2008 errno = EINVAL;
2009 break;
2010 }
2011 return i;
2012}
2013
2014#undef LK_ERR
2015#undef LK_LEN
2016
68dc0745
PP
2017/*
2018 * redirected io subsystem for all XS modules
2019 *
2020 */
0a753a76 2021
68dc0745
PP
2022DllExport int *
2023win32_errno(void)
0a753a76 2024{
390b85e7 2025 return (&errno);
0a753a76
PP
2026}
2027
dcb2879a
GS
2028DllExport char ***
2029win32_environ(void)
2030{
390b85e7 2031 return (&(_environ));
dcb2879a
GS
2032}
2033
68dc0745
PP
2034/* the rest are the remapped stdio routines */
2035DllExport FILE *
2036win32_stderr(void)
0a753a76 2037{
390b85e7 2038 return (stderr);
0a753a76
PP
2039}
2040
68dc0745
PP
2041DllExport FILE *
2042win32_stdin(void)
0a753a76 2043{
390b85e7 2044 return (stdin);
0a753a76
PP
2045}
2046
68dc0745
PP
2047DllExport FILE *
2048win32_stdout()
0a753a76 2049{
390b85e7 2050 return (stdout);
0a753a76
PP
2051}
2052
68dc0745
PP
2053DllExport int
2054win32_ferror(FILE *fp)
0a753a76 2055{
390b85e7 2056 return (ferror(fp));
0a753a76
PP
2057}
2058
2059
68dc0745
PP
2060DllExport int
2061win32_feof(FILE *fp)
0a753a76 2062{
390b85e7 2063 return (feof(fp));
0a753a76
PP
2064}
2065
68dc0745
PP
2066/*
2067 * Since the errors returned by the socket error function
2068 * WSAGetLastError() are not known by the library routine strerror
2069 * we have to roll our own.
2070 */
0a753a76 2071
68dc0745
PP
2072DllExport char *
2073win32_strerror(int e)
0a753a76 2074{
3e3baf6d 2075#ifndef __BORLANDC__ /* Borland intolerance */
68dc0745 2076 extern int sys_nerr;
3e3baf6d 2077#endif
68dc0745 2078 DWORD source = 0;
0a753a76 2079
9404a519 2080 if (e < 0 || e > sys_nerr) {
c5be433b 2081 dTHXo;
9404a519 2082 if (e < 0)
68dc0745 2083 e = GetLastError();
0a753a76 2084
9404a519 2085 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
3352bfcb
GS
2086 w32_strerror_buffer,
2087 sizeof(w32_strerror_buffer), NULL) == 0)
2088 strcpy(w32_strerror_buffer, "Unknown Error");
0a753a76 2089
3352bfcb 2090 return w32_strerror_buffer;
68dc0745 2091 }
390b85e7 2092 return strerror(e);
0a753a76
PP
2093}
2094
22fae026 2095DllExport void
c5be433b 2096win32_str_os_error(void *sv, DWORD dwErr)
22fae026
TM
2097{
2098 DWORD dwLen;
2099 char *sMsg;
2100 dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
2101 |FORMAT_MESSAGE_IGNORE_INSERTS
2102 |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
2103 dwErr, 0, (char *)&sMsg, 1, NULL);
2ce77adf 2104 /* strip trailing whitespace and period */
22fae026 2105 if (0 < dwLen) {
2ce77adf
GS
2106 do {
2107 --dwLen; /* dwLen doesn't include trailing null */
2108 } while (0 < dwLen && isSPACE(sMsg[dwLen]));
22fae026
TM
2109 if ('.' != sMsg[dwLen])
2110 dwLen++;
2ce77adf 2111 sMsg[dwLen] = '\0';
22fae026
TM
2112 }
2113 if (0 == dwLen) {
c69f6586 2114 sMsg = (char*)LocalAlloc(0, 64/**sizeof(TCHAR)*/);
db7c17d7
GS
2115 if (sMsg)
2116 dwLen = sprintf(sMsg,
2117 "Unknown error #0x%lX (lookup 0x%lX)",
2118 dwErr, GetLastError());
2119 }
2120 if (sMsg) {
c5be433b 2121 dTHXo;
db7c17d7
GS
2122 sv_setpvn((SV*)sv, sMsg, dwLen);
2123 LocalFree(sMsg);
22fae026 2124 }
22fae026
TM
2125}
2126
68dc0745
PP
2127DllExport int
2128win32_fprintf(FILE *fp, const char *format, ...)
0a753a76 2129{
68dc0745
PP
2130 va_list marker;
2131 va_start(marker, format); /* Initialize variable arguments. */
0a753a76 2132
390b85e7 2133 return (vfprintf(fp, format, marker));
0a753a76
PP
2134}
2135
68dc0745
PP
2136DllExport int
2137win32_printf(const char *format, ...)
0a753a76 2138{
68dc0745
PP
2139 va_list marker;
2140 va_start(marker, format); /* Initialize variable arguments. */
0a753a76 2141
390b85e7 2142 return (vprintf(format, marker));
0a753a76
PP
2143}
2144
68dc0745
PP
2145DllExport int
2146win32_vfprintf(FILE *fp, const char *format, va_list args)
0a753a76 2147{
390b85e7 2148 return (vfprintf(fp, format, args));
0a753a76
PP
2149}
2150
96e4d5b1
PP
2151DllExport int
2152win32_vprintf(const char *format, va_list args)
2153{
390b85e7 2154 return (vprintf(format, args));
96e4d5b1
PP
2155}
2156
68dc0745
PP
2157DllExport size_t
2158win32_fread(void *buf, size_t size, size_t count, FILE *fp)
0a753a76 2159{
390b85e7 2160 return fread(buf, size, count, fp);
0a753a76
PP
2161}
2162
68dc0745
PP
2163DllExport size_t
2164win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
0a753a76 2165{
390b85e7 2166 return fwrite(buf, size, count, fp);
0a753a76
PP
2167}
2168
7fac1903
GS
2169#define MODE_SIZE 10
2170
68dc0745
PP
2171DllExport FILE *
2172win32_fopen(const char *filename, const char *mode)
0a753a76 2173{
c5be433b 2174 dTHXo;
82867ecf 2175 WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH+1];
1c5905c2 2176 FILE *f;
c5be433b
GS
2177
2178 if (!*filename)
2179 return NULL;
2180
68dc0745 2181 if (stricmp(filename, "/dev/null")==0)
7fac1903
GS
2182 filename = "NUL";
2183
2184 if (USING_WIDE()) {
0cb96387
GS
2185 A2WHELPER(mode, wMode, sizeof(wMode));
2186 A2WHELPER(filename, wBuffer, sizeof(wBuffer));
1c5905c2 2187 f = _wfopen(PerlDir_mapW(wBuffer), wMode);
7fac1903 2188 }
1c5905c2
GS
2189 else
2190 f = fopen(PerlDir_mapA(filename), mode);
2191 /* avoid buffering headaches for child processes */
2192 if (f && *mode == 'a')
2193 win32_fseek(f, 0, SEEK_END);
2194 return f;
0a753a76
PP
2195}
2196
f3986ebb
GS
2197#ifndef USE_SOCKETS_AS_HANDLES
2198#undef fdopen
2199#define fdopen my_fdopen
2200#endif
2201
68dc0745 2202DllExport FILE *
7fac1903 2203win32_fdopen(int handle, const char *mode)
0a753a76 2204{
c5be433b 2205 dTHXo;
51371543 2206 WCHAR wMode[MODE_SIZE];
1c5905c2 2207 FILE *f;
7fac1903 2208 if (USING_WIDE()) {
0cb96387 2209 A2WHELPER(mode, wMode, sizeof(wMode));
1c5905c2 2210 f = _wfdopen(handle, wMode);
7fac1903 2211 }
1c5905c2
GS
2212 else
2213 f = fdopen(handle, (char *) mode);
2214 /* avoid buffering headaches for child processes */
2215 if (f && *mode == 'a')
2216 win32_fseek(f, 0, SEEK_END);
2217 return f;
0a753a76
PP
2218}
2219
68dc0745 2220DllExport FILE *
7fac1903 2221win32_freopen(const char *path, const char *mode, FILE *stream)
0a753a76 2222{
c5be433b 2223 dTHXo;
82867ecf 2224 WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH+1];
68dc0745 2225 if (stricmp(path, "/dev/null")==0)
7fac1903
GS
2226 path = "NUL";
2227
2228 if (USING_WIDE()) {
0cb96387
GS
2229 A2WHELPER(mode, wMode, sizeof(wMode));
2230 A2WHELPER(path, wBuffer, sizeof(wBuffer));
7766f137 2231 return _wfreopen(PerlDir_mapW(wBuffer), wMode, stream);
7fac1903 2232 }
7766f137 2233 return freopen(PerlDir_mapA(path), mode, stream);
0a753a76
PP
2234}
2235
68dc0745
PP
2236DllExport int
2237win32_fclose(FILE *pf)
0a753a76 2238{
f3986ebb 2239 return my_fclose(pf); /* defined in win32sck.c */
0a753a76
PP
2240}
2241
68dc0745
PP
2242DllExport int
2243win32_fputs(const char *s,FILE *pf)
0a753a76 2244{
390b85e7 2245 return fputs(s, pf);
0a753a76
PP
2246}
2247
68dc0745
PP
2248DllExport int
2249win32_fputc(int c,FILE *pf)
0a753a76 2250{
390b85e7 2251 return fputc(c,pf);
0a753a76
PP
2252}
2253
68dc0745
PP
2254DllExport int
2255win32_ungetc(int c,FILE *pf)
0a753a76 2256{
390b85e7 2257 return ungetc(c,pf);
0a753a76
PP
2258}
2259
68dc0745
PP
2260DllExport int
2261win32_getc(FILE *pf)
0a753a76 2262{
390b85e7 2263 return getc(pf);
0a753a76
PP
2264}
2265
68dc0745
PP
2266DllExport int
2267win32_fileno(FILE *pf)
0a753a76 2268{
390b85e7 2269 return fileno(pf);
0a753a76
PP
2270}
2271
68dc0745
PP
2272DllExport void
2273win32_clearerr(FILE *pf)
0a753a76 2274{
390b85e7 2275 clearerr(pf);
68dc0745 2276 return;
0a753a76
PP
2277}
2278
68dc0745
PP
2279DllExport int
2280win32_fflush(FILE *pf)
0a753a76 2281{
390b85e7 2282 return fflush(pf);
0a753a76
PP
2283}
2284
68dc0745
PP
2285DllExport long
2286win32_ftell(FILE *pf)
0a753a76 2287{
390b85e7 2288 return ftell(pf);
0a753a76
PP
2289}
2290
68dc0745
PP
2291DllExport int
2292win32_fseek(FILE *pf,long offset,int origin)
0a753a76 2293{
390b85e7 2294 return fseek(pf, offset, origin);
0a753a76
PP
2295}
2296
68dc0745
PP
2297DllExport int
2298win32_fgetpos(FILE *pf,fpos_t *p)
0a753a76 2299{
390b85e7 2300 return fgetpos(pf, p);
0a753a76
PP
2301}
2302
68dc0745
PP
2303DllExport int
2304win32_fsetpos(FILE *pf,const fpos_t *p)
0a753a76 2305{
390b85e7 2306 return fsetpos(pf, p);
0a753a76
PP
2307}
2308
68dc0745
PP
2309DllExport void
2310win32_rewind(FILE *pf)
0a753a76 2311{
390b85e7 2312 rewind(pf);
68dc0745 2313 return;
0a753a76
PP
2314}
2315
68dc0745
PP
2316DllExport FILE*
2317win32_tmpfile(void)
0a753a76 2318{
390b85e7 2319 return tmpfile();
0a753a76
PP
2320}
2321
68dc0745
PP
2322DllExport void
2323win32_abort(void)
0a753a76 2324{
390b85e7 2325 abort();
68dc0745 2326 return;
0a753a76
PP
2327}
2328
68dc0745 2329DllExport int
22239a37 2330win32_fstat(int fd,struct stat *sbufptr)
0a753a76 2331{
2a07f407
VK
2332#ifdef __BORLANDC__
2333 /* A file designated by filehandle is not shown as accessible
2334 * for write operations, probably because it is opened for reading.
2335 * --Vadim Konovalov
2336 */
2337 int rc = fstat(fd,sbufptr);
2338 BY_HANDLE_FILE_INFORMATION bhfi;
2339 if (GetFileInformationByHandle((HANDLE)_get_osfhandle(fd), &bhfi)) {
2340 sbufptr->st_mode &= 0xFE00;
2341 if (bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
2342 sbufptr->st_mode |= (S_IREAD + (S_IREAD >> 3) + (S_IREAD >> 6));
2343 else
2344 sbufptr->st_mode |= ((S_IREAD|S_IWRITE) + ((S_IREAD|S_IWRITE) >> 3)
2345 + ((S_IREAD|S_IWRITE) >> 6));
2346 }
2347 return rc;
2348#else
ed59ec62 2349 return my_fstat(fd,sbufptr);
2a07f407 2350#endif
0a753a76
PP
2351}
2352
68dc0745
PP
2353DllExport int
2354win32_pipe(int *pfd, unsigned int size, int mode)
0a753a76 2355{
390b85e7 2356 return _pipe(pfd, size, mode);
0a753a76
PP
2357}
2358
8c0134a8
NIS
2359DllExport PerlIO*
2360win32_popenlist(const char *mode, IV narg, SV **args)
2361{
2362 dTHX;
2363 Perl_croak(aTHX_ "List form of pipe open not implemented");
2364 return NULL;
2365}
2366
50892819
GS
2367/*
2368 * a popen() clone that respects PERL5SHELL
00b02797
JH
2369 *
2370 * changed to return PerlIO* rather than FILE * by BKS, 11-11-2000
50892819
GS
2371 */
2372
00b02797 2373DllExport PerlIO*
68dc0745 2374win32_popen(const char *command, const char *mode)
0a753a76 2375{
4b556e6c 2376#ifdef USE_RTL_POPEN
390b85e7 2377 return _popen(command, mode);
50892819
GS
2378#else
2379 int p[2];
2380 int parent, child;
2381 int stdfd, oldfd;
2382 int ourmode;
2383 int childpid;
2384
2385 /* establish which ends read and write */
2386 if (strchr(mode,'w')) {
2387 stdfd = 0; /* stdin */
2388 parent = 1;
2389 child = 0;
2390 }
2391 else if (strchr(mode,'r')) {
2392 stdfd = 1; /* stdout */
2393 parent = 0;
2394 child = 1;
2395 }
2396 else
2397 return NULL;
2398
2399 /* set the correct mode */
2400 if (strchr(mode,'b'))
2401 ourmode = O_BINARY;
2402 else if (strchr(mode,'t'))
2403 ourmode = O_TEXT;
2404 else
2405 ourmode = _fmode & (O_TEXT | O_BINARY);
2406
2407 /* the child doesn't inherit handles */
2408 ourmode |= O_NOINHERIT;
2409
2410 if (win32_pipe( p, 512, ourmode) == -1)
2411 return NULL;
2412
2413 /* save current stdfd */
2414 if ((oldfd = win32_dup(stdfd)) == -1)
2415 goto cleanup;
2416
2417 /* make stdfd go to child end of pipe (implicitly closes stdfd) */
2418 /* stdfd will be inherited by the child */
2419 if (win32_dup2(p[child], stdfd) == -1)
2420 goto cleanup;
2421
2422 /* close the child end in parent */
2423 win32_close(p[child]);
2424
2425 /* start the child */
4f63d024 2426 {
c5be433b
GS
2427 dTHXo;
2428 if ((childpid = do_spawn_nowait((char*)command)) == -1)
4f63d024 2429 goto cleanup;
50892819 2430
4f63d024
GS
2431 /* revert stdfd to whatever it was before */
2432 if (win32_dup2(oldfd, stdfd) == -1)
2433 goto cleanup;
50892819 2434
4f63d024
GS
2435 /* close saved handle */
2436 win32_close(oldfd);
50892819 2437
4755096e 2438 LOCK_FDPID_MUTEX;
4f63d024 2439 sv_setiv(*av_fetch(w32_fdpid, p[parent], TRUE), childpid);
4755096e 2440 UNLOCK_FDPID_MUTEX;
d91d68c1
R
2441
2442 /* set process id so that it can be returned by perl's open() */
2443 PL_forkprocess = childpid;
4f63d024 2444 }
50892819
GS
2445
2446 /* we have an fd, return a file stream */
00b02797 2447 return (PerlIO_fdopen(p[parent], (char *)mode));
50892819
GS
2448
2449cleanup:
2450 /* we don't need to check for errors here */
2451 win32_close(p[0]);
2452 win32_close(p[1]);
2453 if (oldfd != -1) {
2454 win32_dup2(oldfd, stdfd);
2455 win32_close(oldfd);
2456 }
2457 return (NULL);
2458
4b556e6c 2459#endif /* USE_RTL_POPEN */
0a753a76
PP
2460}
2461
50892819
GS
2462/*
2463 * pclose() clone
2464 */
2465
68dc0745 2466DllExport int
00b02797 2467win32_pclose(PerlIO *pf)
0a753a76 2468{
4b556e6c 2469#ifdef USE_RTL_POPEN
390b85e7 2470 return _pclose(pf);
50892819 2471#else
c5be433b 2472 dTHXo;
e17cb2a9
JD
2473 int childpid, status;
2474 SV *sv;
2475
4755096e 2476 LOCK_FDPID_MUTEX;
00b02797 2477 sv = *av_fetch(w32_fdpid, PerlIO_fileno(pf), TRUE);
4755096e 2478
e17cb2a9
JD
2479 if (SvIOK(sv))
2480 childpid = SvIVX(sv);
2481 else
2482 childpid = 0;
50892819
GS
2483
2484 if (!childpid) {
2485 errno = EBADF;
2486 return -1;
2487 }
2488
00b02797
JH
2489#ifdef USE_PERLIO
2490 PerlIO_close(pf);
2491#else
2492 fclose(pf);
2493#endif
e17cb2a9 2494 SvIVX(sv) = 0;
4755096e 2495 UNLOCK_FDPID_MUTEX;
e17cb2a9 2496
0aaad0ff
GS
2497 if (win32_waitpid(childpid, &status, 0) == -1)
2498 return -1;
50892819 2499
0aaad0ff 2500 return status;
50892819 2501
4b556e6c 2502#endif /* USE_RTL_POPEN */
0a753a76 2503}
6b980173
JD
2504
2505static BOOL WINAPI
2506Nt4CreateHardLinkW(
2507 LPCWSTR lpFileName,
2508 LPCWSTR lpExistingFileName,
2509 LPSECURITY_ATTRIBUTES lpSecurityAttributes)
2510{
2511 HANDLE handle;
2512 WCHAR wFullName[MAX_PATH+1];
2513 LPVOID lpContext = NULL;
2514 WIN32_STREAM_ID StreamId;
2515 DWORD dwSize = (char*)&StreamId.cStreamName - (char*)&StreamId;
2516 DWORD dwWritten;
2517 DWORD dwLen;
2518 BOOL bSuccess;
2519
2520 BOOL (__stdcall *pfnBackupWrite)(HANDLE, LPBYTE, DWORD, LPDWORD,
2521 BOOL, BOOL, LPVOID*) =
2522 (BOOL (__stdcall *)(HANDLE, LPBYTE, DWORD, LPDWORD,
2523 BOOL, BOOL, LPVOID*))
2524 GetProcAddress(GetModuleHandle("kernel32.dll"), "BackupWrite");
2525 if (pfnBackupWrite == NULL)
2526 return 0;
2527
2528 dwLen = GetFullPathNameW(lpFileName, MAX_PATH, wFullName, NULL);
2529 if (dwLen == 0)
2530 return 0;
2531 dwLen = (dwLen+1)*sizeof(WCHAR);
2532
2533 handle = CreateFileW(lpExistingFileName, FILE_WRITE_ATTRIBUTES,
2534 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
2535 NULL, OPEN_EXISTING, 0, NULL);
2536 if (handle == INVALID_HANDLE_VALUE)
2537 return 0;
2538
2539 StreamId.dwStreamId = BACKUP_LINK;
2540 StreamId.dwStreamAttributes = 0;
2541 StreamId.dwStreamNameSize = 0;
9eaf016b 2542#if defined(__BORLANDC__) || defined(__MINGW32__)
4ce4f76e
GS
2543 StreamId.Size.u.HighPart = 0;
2544 StreamId.Size.u.LowPart = dwLen;
2545#else
6b980173
JD
2546 StreamId.Size.HighPart = 0;
2547 StreamId.Size.LowPart = dwLen;
4ce4f76e 2548#endif
6b980173
JD
2549
2550 bSuccess = pfnBackupWrite(handle, (LPBYTE)&StreamId, dwSize, &dwWritten,
2551 FALSE, FALSE, &lpContext);
2552 if (bSuccess) {
2553 bSuccess = pfnBackupWrite(handle, (LPBYTE)wFullName, dwLen, &dwWritten,
2554 FALSE, FALSE, &lpContext);
2555 pfnBackupWrite(handle, NULL, 0, &dwWritten, TRUE, FALSE, &lpContext);
2556 }
2557
2558 CloseHandle(handle);
2559 return bSuccess;
2560}
2561
2562DllExport int
2563win32_link(const char *oldname, const char *newname)
2564{
2565 dTHXo;
2566 BOOL (__stdcall *pfnCreateHardLinkW)(LPCWSTR,LPCWSTR,LPSECURITY_ATTRIBUTES);
82867ecf
GS
2567 WCHAR wOldName[MAX_PATH+1];
2568 WCHAR wNewName[MAX_PATH+1];
6b980173
JD
2569
2570 if (IsWin95())
1be9d9c6 2571 Perl_croak(aTHX_ PL_no_func, "link");
6b980173
JD
2572
2573 pfnCreateHardLinkW =
2574 (BOOL (__stdcall *)(LPCWSTR, LPCWSTR, LPSECURITY_ATTRIBUTES))
2575 GetProcAddress(GetModuleHandle("kernel32.dll"), "CreateHardLinkW");
2576 if (pfnCreateHardLinkW == NULL)
2577 pfnCreateHardLinkW = Nt4CreateHardLinkW;
2578
2579 if ((A2WHELPER(oldname, wOldName, sizeof(wOldName))) &&
2580 (A2WHELPER(newname, wNewName, sizeof(wNewName))) &&
7766f137
GS
2581 (wcscpy(wOldName, PerlDir_mapW(wOldName)),
2582 pfnCreateHardLinkW(PerlDir_mapW(wNewName), wOldName, NULL)))
6b980173
JD
2583 {
2584 return 0;
2585 }
2586 errno = (GetLastError() == ERROR_FILE_NOT_FOUND) ? ENOENT : EINVAL;
2587 return -1;
2588}
0a753a76 2589
68dc0745 2590DllExport int
8d9b2e3c 2591win32_rename(const char *oname, const char *newname)
e24c7c18 2592{
65cb15a1
GS
2593 WCHAR wOldName[MAX_PATH+1];
2594 WCHAR wNewName[MAX_PATH+1];
2595 char szOldName[MAX_PATH+1];
2596 char szNewName[MAX_PATH+1];
7fac1903 2597 BOOL bResult;
65cb15a1
GS
2598 dTHXo;
2599
80252599
GS
2600 /* XXX despite what the documentation says about MoveFileEx(),
2601 * it doesn't work under Windows95!
2602 */
2603 if (IsWinNT()) {
65cb15a1 2604 DWORD dwFlags = MOVEFILE_COPY_ALLOWED;
7fac1903 2605 if (USING_WIDE()) {
0cb96387
GS
2606 A2WHELPER(oname, wOldName, sizeof(wOldName));
2607 A2WHELPER(newname, wNewName, sizeof(wNewName));
65cb15a1
GS
2608 if (wcsicmp(wNewName, wOldName))
2609 dwFlags |= MOVEFILE_REPLACE_EXISTING;
7766f137 2610 wcscpy(wOldName, PerlDir_mapW(wOldName));
65cb15a1 2611 bResult = MoveFileExW(wOldName,PerlDir_mapW(wNewName), dwFlags);
7fac1903
GS
2612 }
2613 else {
65cb15a1
GS
2614 if (stricmp(newname, oname))
2615 dwFlags |= MOVEFILE_REPLACE_EXISTING;
2616 strcpy(szOldName, PerlDir_mapA(oname));
2617 bResult = MoveFileExA(szOldName,PerlDir_mapA(newname), dwFlags);
7fac1903
GS
2618 }
2619 if (!bResult) {
80252599
GS
2620 DWORD err = GetLastError();
2621 switch (err) {
2622 case ERROR_BAD_NET_NAME:
2623 case ERROR_BAD_NETPATH:
2624 case ERROR_BAD_PATHNAME:
2625 case ERROR_FILE_NOT_FOUND:
2626 case ERROR_FILENAME_EXCED_RANGE:
2627 case ERROR_INVALID_DRIVE:
2628 case ERROR_NO_MORE_FILES:
2629 case ERROR_PATH_NOT_FOUND:
2630 errno = ENOENT;
2631 break;
2632 default:
2633 errno = EACCES;
2634 break;
2635 }
2636 return -1;
2637 }
2638 return 0;
e24c7c18 2639 }
80252599
GS
2640 else {
2641 int retval = 0;
65cb15a1 2642 char szTmpName[MAX_PATH+1];
80252599
GS
2643 char dname[MAX_PATH+1];
2644 char *endname = Nullch;
2645 STRLEN tmplen = 0;
2646 DWORD from_attr, to_attr;
2647
65cb15a1
GS
2648 strcpy(szOldName, PerlDir_mapA(oname));
2649 strcpy(szNewName, PerlDir_mapA(newname));
2650
80252599 2651 /* if oname doesn't exist, do nothing */
65cb15a1 2652 from_attr = GetFileAttributes(szOldName);
80252599
GS
2653 if (from_attr == 0xFFFFFFFF) {
2654 errno = ENOENT;
2655 return -1;
2656 }
2657
2658 /* if newname exists, rename it to a temporary name so that we
2659 * don't delete it in case oname happens to be the same file
2660 * (but perhaps accessed via a different path)
2661 */
65cb15a1 2662 to_attr = GetFileAttributes(szNewName);
80252599
GS
2663 if (to_attr != 0xFFFFFFFF) {
2664 /* if newname is a directory, we fail
2665 * XXX could overcome this with yet more convoluted logic */
2666 if (to_attr & FILE_ATTRIBUTE_DIRECTORY) {
2667 errno = EACCES;
2668 return -1;
2669 }
65cb15a1
GS
2670 tmplen = strlen(szNewName);
2671 strcpy(szTmpName,szNewName);
2672 endname = szTmpName+tmplen;
2673 for (; endname > szTmpName ; --endname) {
80252599
GS
2674 if (*endname == '/' || *endname == '\\') {
2675 *endname = '\0';
2676 break;
2677 }
2678 }
65cb15a1
GS
2679 if (endname > szTmpName)
2680 endname = strcpy(dname,szTmpName);
e24c7c18 2681 else
80252599
GS
2682 endname = ".";
2683
2684 /* get a temporary filename in same directory
2685 * XXX is this really the best we can do? */
65cb15a1 2686 if (!GetTempFileName((LPCTSTR)endname, "plr", 0, szTmpName)) {
80252599
GS
2687 errno = ENOENT;
2688 return -1;
2689 }
65cb15a1 2690 DeleteFile(szTmpName);
80252599 2691
65cb15a1 2692 retval = rename(szNewName, szTmpName);
80252599
GS
2693 if (retval != 0) {
2694 errno = EACCES;
2695 return retval;
e24c7c18
GS
2696 }
2697 }
80252599
GS
2698
2699 /* rename oname to newname */
65cb15a1 2700 retval = rename(szOldName, szNewName);
80252599
GS
2701
2702 /* if we created a temporary file before ... */
2703 if (endname != Nullch) {
2704 /* ...and rename succeeded, delete temporary file/directory */
2705 if (retval == 0)
65cb15a1 2706 DeleteFile(szTmpName);
80252599
GS
2707 /* else restore it to what it was */
2708 else
65cb15a1 2709 (void)rename(szTmpName, szNewName);
80252599
GS
2710 }
2711 return retval;
e24c7c18 2712 }
e24c7c18
GS
2713}
2714
2715DllExport int
68dc0745 2716win32_setmode(int fd, int mode)
0a753a76 2717{
390b85e7 2718 return setmode(fd, mode);
0a753a76
PP
2719}
2720
96e4d5b1
PP
2721DllExport long
2722win32_lseek(int fd, long offset, int origin)
2723{
390b85e7 2724 return lseek(fd, offset, origin);
96e4d5b1
PP
2725}
2726
2727DllExport long
2728win32_tell(int fd)
2729{
390b85e7 2730 return tell(fd);
96e4d5b1
PP
2731}
2732
68dc0745
PP
2733DllExport int
2734win32_open(const char *path, int flag, ...)
0a753a76 2735{
c5be433b 2736 dTHXo;
68dc0745
PP
2737 va_list ap;
2738 int pmode;
82867ecf 2739 WCHAR wBuffer[MAX_PATH+1];
0a753a76
PP
2740
2741 va_start(ap, flag);
2742 pmode = va_arg(ap, int);
2743 va_end(ap);
2744
68dc0745 2745 if (stricmp(path, "/dev/null")==0)
7fac1903
GS
2746 path = "NUL";
2747
2748 if (USING_WIDE()) {
0cb96387 2749 A2WHELPER(path, wBuffer, sizeof(wBuffer));
7766f137 2750 return _wopen(PerlDir_mapW(wBuffer), flag, pmode);
7fac1903 2751 }
7766f137 2752 return open(PerlDir_mapA(path), flag, pmode);
0a753a76
PP
2753}
2754
00b02797
JH
2755/* close() that understands socket */
2756extern int my_close(int); /* in win32sck.c */
2757
68dc0745
PP
2758DllExport int
2759win32_close(int fd)
0a753a76 2760{
00b02797 2761 return my_close(fd);
0a753a76
PP
2762}
2763
68dc0745 2764DllExport int
96e4d5b1
PP
2765win32_eof(int fd)
2766{
390b85e7 2767 return eof(fd);
96e4d5b1
PP
2768}
2769
2770DllExport int
68dc0745 2771win32_dup(int fd)
0a753a76 2772{
390b85e7 2773 return dup(fd);
0a753a76
PP
2774}
2775
68dc0745
PP
2776DllExport int
2777win32_dup2(int fd1,int fd2)
0a753a76 2778{
390b85e7 2779 return dup2(fd1,fd2);
0a753a76
PP
2780}
2781
f7aeb604
GS
2782#ifdef PERL_MSVCRT_READFIX
2783
2784#define LF 10 /* line feed */
2785#define CR 13 /* carriage return */
2786#define CTRLZ 26 /* ctrl-z means eof for text */
2787#define FOPEN 0x01 /* file handle open */
2788#define FEOFLAG 0x02 /* end of file has been encountered */
2789#define FCRLF 0x04 /* CR-LF across read buffer (in text mode) */
2790#define FPIPE 0x08 /* file handle refers to a pipe */
2791#define FAPPEND 0x20 /* file handle opened O_APPEND */
2792#define FDEV 0x40 /* file handle refers to device */
2793#define FTEXT 0x80 /* file handle is in text mode */
2794#define MAX_DESCRIPTOR_COUNT (64*32) /* this is the maximun that MSVCRT can handle */
2795
b181b6fb
GS
2796int __cdecl
2797_fixed_read(int fh, void *buf, unsigned cnt)
f7aeb604
GS
2798{
2799 int bytes_read; /* number of bytes read */
2800 char *buffer; /* buffer to read to */
2801 int os_read; /* bytes read on OS call */
2802 char *p, *q; /* pointers into buffer */
2803 char peekchr; /* peek-ahead character */
2804 ULONG filepos; /* file position after seek */
2805 ULONG dosretval; /* o.s. return value */
2806
2807 /* validate handle */
2808 if (((unsigned)fh >= (unsigned)MAX_DESCRIPTOR_COUNT) ||
2809 !(_osfile(fh) & FOPEN))
2810 {
2811 /* out of range -- return error */
2812 errno = EBADF;
2813 _doserrno = 0; /* not o.s. error */
2814 return -1;
2815 }
2816
635bbe87
GS
2817 /*
2818 * If lockinitflag is FALSE, assume fd is device
2819 * lockinitflag is set to TRUE by open.
2820 */
2821 if (_pioinfo(fh)->lockinitflag)
2822 EnterCriticalSection(&(_pioinfo(fh)->lock)); /* lock file */
f7aeb604
GS
2823
2824 bytes_read = 0; /* nothing read yet */
2825 buffer = (char*)buf;
2826
2827 if (cnt == 0 || (_osfile(fh) & FEOFLAG)) {
2828 /* nothing to read or at EOF, so return 0 read */
2829 goto functionexit;
2830 }
2831
2832 if ((_osfile(fh) & (FPIPE|FDEV)) && _pipech(fh) != LF) {
2833 /* a pipe/device and pipe lookahead non-empty: read the lookahead
2834 * char */
2835 *buffer++ = _pipech(fh);
2836 ++bytes_read;
2837 --cnt;
2838 _pipech(fh) = LF; /* mark as empty */
2839 }
2840
2841 /* read the data */
2842
2843 if (!ReadFile((HANDLE)_osfhnd(fh), buffer, cnt, (LPDWORD)&os_read, NULL))
2844 {
2845 /* ReadFile has reported an error. recognize two special cases.
2846 *
2847 * 1. map ERROR_ACCESS_DENIED to EBADF
2848 *
2849 * 2. just return 0 if ERROR_BROKEN_PIPE has occurred. it
2850 * means the handle is a read-handle on a pipe for which
2851 * all write-handles have been closed and all data has been
2852 * read. */
2853
2854 if ((dosretval = GetLastError()) == ERROR_ACCESS_DENIED) {
2855 /* wrong read/write mode should return EBADF, not EACCES */
2856 errno = EBADF;
2857 _doserrno = dosretval;
2858 bytes_read = -1;
2859 goto functionexit;
2860 }
2861 else if (dosretval == ERROR_BROKEN_PIPE) {
2862 bytes_read = 0;
2863 goto functionexit;
2864 }
2865 else {
2866 bytes_read = -1;
2867 goto functionexit;
2868 }
2869 }
2870
2871 bytes_read += os_read; /* update bytes read */
2872
2873 if (_osfile(fh) & FTEXT) {
2874 /* now must translate CR-LFs to LFs in the buffer */
2875
2876 /* set CRLF flag to indicate LF at beginning of buffer */
2877 /* if ((os_read != 0) && (*(char *)buf == LF)) */
2878 /* _osfile(fh) |= FCRLF; */
2879 /* else */
2880 /* _osfile(fh) &= ~FCRLF; */
2881
2882 _osfile(fh) &= ~FCRLF;
2883
2884 /* convert chars in the buffer: p is src, q is dest */
2885 p = q = (char*)buf;
2886 while (p < (char *)buf + bytes_read) {
2887 if (*p == CTRLZ) {
2888 /* if fh is not a device, set ctrl-z flag */
2889 if (!(_osfile(fh) & FDEV))
2890 _osfile(fh) |= FEOFLAG;
2891 break; /* stop translating */
2892 }
2893 else if (*p != CR)
2894 *q++ = *p++;
2895 else {
2896 /* *p is CR, so must check next char for LF */
2897 if (p < (char *)buf + bytes_read - 1) {
2898 if (*(p+1) == LF) {
2899 p += 2;
2900 *q++ = LF; /* convert CR-LF to LF */
2901 }
2902 else
2903 *q++ = *p++; /* store char normally */
2904 }
2905 else {
2906 /* This is the hard part. We found a CR at end of
2907 buffer. We must peek ahead to see if next char
2908 is an LF. */
2909 ++p;
2910
2911 dosretval = 0;
2912 if (!ReadFile((HANDLE)_osfhnd(fh), &peekchr, 1,
2913 (LPDWORD)&os_read, NULL))
2914 dosretval = GetLastError();
2915
2916 if (dosretval != 0 || os_read == 0) {
2917 /* couldn't read ahead, store CR */
2918 *q++ = CR;
2919 }
2920 else {
2921 /* peekchr now has the extra character -- we now
2922 have several possibilities:
2923 1. disk file and char is not LF; just seek back
2924 and copy CR
2925 2. disk file and char is LF; store LF, don't seek back
2926 3. pipe/device and char is LF; store LF.
2927 4. pipe/device and char isn't LF, store CR and
2928 put char in pipe lookahead buffer. */
2929 if (_osfile(fh) & (FDEV|FPIPE)) {
2930 /* non-seekable device */
2931 if (peekchr == LF)
2932 *q++ = LF;
2933 else {
2934 *q++ = CR;
2935 _pipech(fh) = peekchr;
2936 }
2937 }
2938 else {
2939 /* disk file */
2940 if (peekchr == LF) {
2941 /* nothing read yet; must make some
2942 progress */
2943 *q++ = LF;
2944 /* turn on this flag for tell routine */
2945 _osfile(fh) |= FCRLF;
2946 }
2947 else {
2948 HANDLE osHandle; /* o.s. handle value */
2949 /* seek back */
2950 if ((osHandle = (HANDLE)_get_osfhandle(fh)) != (HANDLE)-1)
2951 {
2952 if ((filepos = SetFilePointer(osHandle, -1, NULL, FILE_CURRENT)) == -1)
2953 dosretval = GetLastError();
2954 }
2955 if (peekchr != LF)
2956 *q++ = CR;
2957 }
2958 }
2959 }
2960 }
2961 }
2962 }
2963
2964 /* we now change bytes_read to reflect the true number of chars
2965 in the buffer */
2966 bytes_read = q - (char *)buf;
2967 }
2968
2969functionexit:
635bbe87
GS
2970 if (_pioinfo(fh)->lockinitflag)
2971 LeaveCriticalSection(&(_pioinfo(fh)->lock)); /* unlock file */
f7aeb604
GS
2972
2973 return bytes_read;
2974}
2975
2976#endif /* PERL_MSVCRT_READFIX */
2977
68dc0745 2978DllExport int
3e3baf6d 2979win32_read(int fd, void *buf, unsigned int cnt)
0a753a76 2980{
f7aeb604
GS
2981#ifdef PERL_MSVCRT_READFIX
2982 return _fixed_read(fd, buf, cnt);
2983#else
390b85e7 2984 return read(fd, buf, cnt);
f7aeb604 2985#endif
0a753a76
PP
2986}
2987
68dc0745 2988DllExport int
3e3baf6d 2989win32_write(int fd, const void *buf, unsigned int cnt)
0a753a76 2990{
390b85e7 2991 return write(fd, buf, cnt);
0a753a76
PP
2992}
2993
68dc0745 2994DllExport int
5aabfad6
PP
2995win32_mkdir(const char *dir, int mode)
2996{
7766f137
GS
2997 dTHXo;
2998 if (USING_WIDE()) {
82867ecf 2999 WCHAR wBuffer[MAX_PATH+1];
7766f137
GS
3000 A2WHELPER(dir, wBuffer, sizeof(wBuffer));
3001 return _wmkdir(PerlDir_mapW(wBuffer));
3002 }
3003 return mkdir(PerlDir_mapA(dir)); /* just ignore mode */
5aabfad6 3004}
96e4d5b1 3005
5aabfad6
PP
3006DllExport int
3007win32_rmdir(const char *dir)
3008{
7766f137
GS
3009 dTHXo;
3010 if (USING_WIDE()) {
82867ecf 3011 WCHAR wBuffer[MAX_PATH+1];
7766f137
GS
3012 A2WHELPER(dir, wBuffer, sizeof(wBuffer));
3013 return _wrmdir(PerlDir_mapW(wBuffer));
3014 }
3015 return rmdir(PerlDir_mapA(dir));
5aabfad6 3016}
96e4d5b1 3017
5aabfad6
PP
3018DllExport int
3019win32_chdir(const char *dir)
3020{
7766f137
GS
3021 dTHXo;
3022 if (USING_WIDE()) {
82867ecf 3023 WCHAR wBuffer[MAX_PATH+1];
7766f137
GS
3024 A2WHELPER(dir, wBuffer, sizeof(wBuffer));
3025 return _wchdir(wBuffer);
3026 }
390b85e7 3027 return chdir(dir);
5aabfad6 3028}
96e4d5b1 3029
7766f137
GS
3030DllExport int
3031win32_access(const char *path, int mode)
3032{
3033 dTHXo;
3034 if (USING_WIDE()) {
82867ecf 3035 WCHAR wBuffer[MAX_PATH+1];
7766f137
GS
3036 A2WHELPER(path, wBuffer, sizeof(wBuffer));
3037 return _waccess(PerlDir_mapW(wBuffer), mode);
3038 }
3039 return access(PerlDir_mapA(path), mode);
3040}
3041
3042DllExport int
3043win32_chmod(const char *path, int mode)
3044{
3045 dTHXo;
3046 if (USING_WIDE()) {
82867ecf 3047 WCHAR wBuffer[MAX_PATH+1];
7766f137
GS
3048 A2WHELPER(path, wBuffer, sizeof(wBuffer));
3049 return _wchmod(PerlDir_mapW(wBuffer), mode);
3050 }
3051 return chmod(PerlDir_mapA(path), mode);
3052}
3053
3054
0aaad0ff
GS
3055static char *
3056create_command_line(const char* command, const char * const *args)
3057{
c5be433b 3058 dTHXo;
0aaad0ff
GS
3059 int index;
3060 char *cmd, *ptr, *arg;
3061 STRLEN len = strlen(command) + 1;
3062
3063 for (index = 0; (ptr = (char*)args[index]) != NULL; ++index)
3064 len += strlen(ptr) + 1;
3065
3066 New(1310, cmd, len, char);
3067 ptr = cmd;
3068 strcpy(ptr, command);
0aaad0ff
GS
3069
3070 for (index = 0; (arg = (char*)args[index]) != NULL; ++index) {
0aaad0ff 3071 ptr += strlen(ptr);
18a945d4
GS
3072 *ptr++ = ' ';
3073 strcpy(ptr, arg);
0aaad0ff
GS
3074 }
3075
3076 return cmd;
3077}
3078
3079static char *
3080qualified_path(const char *cmd)
3081{
c5be433b 3082 dTHXo;
0aaad0ff
GS
3083 char *pathstr;
3084 char *fullcmd, *curfullcmd;
3085 STRLEN cmdlen = 0;
3086 int has_slash = 0;
3087
3088 if (!cmd)
3089 return Nullch;
3090 fullcmd = (char*)cmd;
3091 while (*fullcmd) {
3092 if (*fullcmd == '/' || *fullcmd == '\\')
3093 has_slash++;
3094 fullcmd++;
3095 cmdlen++;
3096 }
3097
3098 /* look in PATH */
3099 pathstr = win32_getenv("PATH");
3100 New(0, fullcmd, MAX_PATH+1, char);
3101 curfullcmd = fullcmd;
3102
3103 while (1) {
3104 DWORD res;
3105
3106 /* start by appending the name to the current prefix */
3107 strcpy(curfullcmd, cmd);
3108 curfullcmd += cmdlen;
3109
3110 /* if it doesn't end with '.', or has no extension, try adding
3111 * a trailing .exe first */
3112 if (cmd[cmdlen-1] != '.'
3113 && (cmdlen < 4 || cmd[cmdlen-4] != '.'))
3114 {
3115 strcpy(curfullcmd, ".exe");
3116 res = GetFileAttributes(fullcmd);
3117 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
3118 return fullcmd;
3119 *curfullcmd = '\0';
3120 }
3121
3122 /* that failed, try the bare name */
3123 res = GetFileAttributes(fullcmd);
3124 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
3125 return fullcmd;
3126
3127 /* quit if no other path exists, or if cmd already has path */
3128 if (!pathstr || !*pathstr || has_slash)
3129 break;
3130
3131 /* skip leading semis */
3132 while (*pathstr == ';')
3133 pathstr++;
3134
3135 /* build a new prefix from scratch */
3136 curfullcmd = fullcmd;
3137 while (*pathstr && *pathstr != ';') {
3138 if (*pathstr == '"') { /* foo;"baz;etc";bar */
3139 pathstr++; /* skip initial '"' */
3140 while (*pathstr && *pathstr != '"') {
3141 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
3142 *curfullcmd++ = *pathstr;
3143 pathstr++;
3144 }
3145 if (*pathstr)
3146 pathstr++; /* skip trailing '"' */
3147 }
3148 else {
3149 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
3150 *curfullcmd++ = *pathstr;
3151 pathstr++;
3152 }
3153 }
3154 if (*pathstr)
3155 pathstr++; /* skip trailing semi */
3156 if (curfullcmd > fullcmd /* append a dir separator */
3157 && curfullcmd[-1] != '/' && curfullcmd[-1] != '\\')
3158 {
3159 *curfullcmd++ = '\\';
3160 }
3161 }
3162GIVE_UP:
3163 Safefree(fullcmd);
3164 return Nullch;
3165}
3166
3075ddba
GS
3167/* The following are just place holders.
3168 * Some hosts may provide and environment that the OS is
3169 * not tracking, therefore, these host must provide that
3170 * environment and the current directory to CreateProcess
3171 */
3172
3173void*
3174get_childenv(void)
3175{
3176 return NULL;
3177}
3178
3179void
2dd19d29 3180free_childenv(void* d)
3075ddba
GS
3181{
3182}
3183
3184char*
3185get_childdir(void)
3186{
7766f137
GS
3187 dTHXo;
3188 char* ptr;
3189 char szfilename[(MAX_PATH+1)*2];
3190 if (USING_WIDE()) {
3191 WCHAR wfilename[MAX_PATH+1];
3192 GetCurrentDirectoryW(MAX_PATH+1, wfilename);
3193 W2AHELPER(wfilename, szfilename, sizeof(szfilename));
3194 }
3195 else {
3196 GetCurrentDirectoryA(MAX_PATH+1, szfilename);
3197 }
3198
3199 New(0, ptr, strlen(szfilename)+1, char);
3200 strcpy(ptr, szfilename);
3201 return ptr;
3075ddba
GS
3202}
3203
3204void
2dd19d29 3205free_childdir(char* d)
3075ddba 3206{
7766f137
GS
3207 dTHXo;
3208 Safefree(d);
3075ddba
GS
3209}
3210
3211
0aaad0ff
GS
3212/* XXX this needs to be made more compatible with the spawnvp()
3213 * provided by the various RTLs. In particular, searching for
3214 * *.{com,bat,cmd} files (as done by the RTLs) is unimplemented.
3215 * This doesn't significantly affect perl itself, because we
3216 * always invoke things using PERL5SHELL if a direct attempt to
3217 * spawn the executable fails.
3218 *
3219 * XXX splitting and rejoining the commandline between do_aspawn()
3220 * and win32_spawnvp() could also be avoided.
3221 */
3222
5aabfad6 3223DllExport int
3e3baf6d 3224win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
0a753a76 3225{
0aaad0ff
GS
3226#ifdef USE_RTL_SPAWNVP
3227 return spawnvp(mode, cmdname, (char * const *)argv);
3228#else
c5be433b 3229 dTHXo;
2b260de0 3230 int ret;
3075ddba
GS
3231 void* env;
3232 char* dir;
635bbe87 3233 child_IO_table tbl;
0aaad0ff
GS
3234 STARTUPINFO StartupInfo;
3235 PROCESS_INFORMATION ProcessInformation;
3236 DWORD create = 0;
3237
3238 char *cmd = create_command_line(cmdname, strcmp(cmdname, argv[0]) == 0
3239 ? &argv[1] : argv);
3240 char *fullcmd = Nullch;
3241
3075ddba
GS
3242 env = PerlEnv_get_childenv();
3243 dir = PerlEnv_get_childdir();
3244
0aaad0ff
GS
3245 switch(mode) {
3246 case P_NOWAIT: /* asynch + remember result */
3247 if (w32_num_children >= MAXIMUM_WAIT_OBJECTS) {
3248 errno = EAGAIN;
3249 ret = -1;
3250 goto RETVAL;
3251 }
3252 /* FALL THROUGH */
3253 case P_WAIT: /* synchronous execution */
3254 break;
3255 default: /* invalid mode */
3256 errno = EINVAL;
3257 ret = -1;
3258 goto RETVAL;
3259 }
3260 memset(&StartupInfo,0,sizeof(StartupInfo));
3261 StartupInfo.cb = sizeof(StartupInfo);
f83751a7 3262 memset(&tbl,0,sizeof(tbl));
635bbe87 3263 PerlEnv_get_child_IO(&tbl);
f83751a7
GS
3264 StartupInfo.dwFlags = tbl.dwFlags;
3265 StartupInfo.dwX = tbl.dwX;
3266 StartupInfo.dwY = tbl.dwY;
3267 StartupInfo.dwXSize = tbl.dwXSize;
3268 StartupInfo.dwYSize = tbl.dwYSize;
3269 StartupInfo.dwXCountChars = tbl.dwXCountChars;
3270 StartupInfo.dwYCountChars = tbl.dwYCountChars;
3271 StartupInfo.dwFillAttribute = tbl.dwFillAttribute;
3272 StartupInfo.wShowWindow = tbl.wShowWindow;
3273 StartupInfo.hStdInput = tbl.childStdIn;
3274 StartupInfo.hStdOutput = tbl.childStdOut;
3275 StartupInfo.hStdError = tbl.childStdErr;
3ffaa937
GS
3276 if (StartupInfo.hStdInput != INVALID_HANDLE_VALUE &&
3277 StartupInfo.hStdOutput != INVALID_HANDLE_VALUE &&
3278 StartupInfo.hStdError != INVALID_HANDLE_VALUE)
3279 {
3280 StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
3281 }
3282 else {
3283 create |= CREATE_NEW_CONSOLE;
3284 }
3285
0aaad0ff
GS
3286RETRY:
3287 if (!CreateProcess(cmdname, /* search PATH to find executable */
3288 cmd, /* executable, and its arguments */
3289 NULL, /* process attributes */
3290 NULL, /* thread attributes */
3291 TRUE, /* inherit handles */
3292 create, /* creation flags */
3075ddba
GS
3293 (LPVOID)env, /* inherit environment */
3294 dir, /* inherit cwd */
0aaad0ff
GS
3295 &StartupInfo,
3296 &ProcessInformation))
3297 {
3298 /* initial NULL argument to CreateProcess() does a PATH
3299 * search, but it always first looks in the directory
3300 * where the current process was started, which behavior
3301 * is undesirable for backward compatibility. So we
3302 * jump through our own hoops by picking out the path
3303 * we really want it to use. */
3304 if (!fullcmd) {
3305 fullcmd = qualified_path(cmdname);
3306 if (fullcmd) {
3307 cmdname = fullcmd;
3308 goto RETRY;
3309 }
3310 }
3311 errno = ENOENT;
3312 ret = -1;
3313 goto RETVAL;
3314 }
2d7a9237 3315
0aaad0ff
GS
3316 if (mode == P_NOWAIT) {
3317 /* asynchronous spawn -- store handle, return PID */
2b260de0 3318 ret = (int)ProcessInformation.dwProcessId;
922b1888
GS
3319 if (IsWin95() && ret < 0)
3320 ret = -ret;
3321
3322 w32_child_handles[w32_num_children] = ProcessInformation.hProcess;
3323 w32_child_pids[w32_num_children] = (DWORD)ret;
0aaad0ff
GS
3324 ++w32_num_children;
3325 }
3326 else {
2b260de0 3327 DWORD status;
0aaad0ff 3328 WaitForSingleObject(ProcessInformation.hProcess, INFINITE);
2b260de0
GS
3329 GetExitCodeProcess(ProcessInformation.hProcess, &status);
3330 ret = (int)status;
0aaad0ff
GS
3331 CloseHandle(ProcessInformation.hProcess);
3332 }
e17cb2a9 3333
0aaad0ff 3334 CloseHandle(ProcessInformation.hThread);
3075ddba 3335
0aaad0ff 3336RETVAL:
3075ddba
GS
3337 PerlEnv_free_childenv(env);
3338 PerlEnv_free_childdir(dir);
0aaad0ff
GS
3339 Safefree(cmd);
3340 Safefree(fullcmd);
2b260de0 3341 return ret;
2d7a9237 3342#endif
0a753a76
PP
3343}
3344
6890e559 3345DllExport int
eb62e965
JD
3346win32_execv(const char *cmdname, const char *const *argv)
3347{
7766f137
GS
3348#ifdef USE_ITHREADS
3349 dTHXo;
3350 /* if this is a pseudo-forked child, we just want to spawn
3351 * the new program, and return */
3352 if (w32_pseudo_id)
3353 return spawnv(P_WAIT, cmdname, (char *const *)argv);
3354#endif
eb62e965
JD
3355 return execv(cmdname, (char *const *)argv);
3356}
3357
3358DllExport int
6890e559
GS
3359win32_execvp(const char *cmdname, const char *const *argv)
3360{
7766f137
GS
3361#ifdef USE_ITHREADS
3362 dTHXo;
3363 /* if this is a pseudo-forked child, we just want to spawn
3364 * the new program, and return */
3365 if (w32_pseudo_id)
3366 return win32_spawnvp(P_WAIT, cmdname, (char *const *)argv);
3367#endif
390b85e7 3368 return execvp(cmdname, (char *const *)argv);
6890e559
GS
3369}
3370
84902520
TB
3371DllExport void
3372win32_perror(const char *str)
3373{
390b85e7 3374 perror(str);
84902520
TB
3375}
3376
3377DllExport void
3378win32_setbuf(FILE *pf, char *buf)
3379{
390b85e7 3380 setbuf(pf, buf);
84902520
TB
3381}
3382
3383DllExport int
3384win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
3385{
390b85e7 3386 return setvbuf(pf, buf, type, size);
84902520
TB
3387}
3388
3389DllExport int
3390win32_flushall(void)
3391{
390b85e7 3392 return flushall();
84902520
TB
3393}
3394
3395DllExport int
3396win32_fcloseall(void)
3397{
390b85e7 3398 return fcloseall();
84902520
TB
3399}
3400
3401DllExport char*
3402win32_fgets(char *s, int n, FILE *pf)
3403{
390b85e7 3404 return fgets(s, n, pf);
84902520
TB
3405}
3406
3407DllExport char*
3408win32_gets(char *s)
3409{
390b85e7 3410 return gets(s);
84902520
TB
3411}
3412
3413DllExport int
3414win32_fgetc(FILE *pf)
3415{
390b85e7 3416 return fgetc(pf);
84902520
TB
3417}
3418
3419DllExport int
3420win32_putc(int c, FILE *pf)
3421{
390b85e7 3422 return putc(c,pf);
84902520
TB
3423}
3424
3425DllExport int
3426win32_puts(const char *s)
3427{
390b85e7 3428 return puts(s);
84902520
TB
3429}
3430
3431DllExport int
3432win32_getchar(void)
3433{
390b85e7 3434 return getchar();
84902520
TB
3435}
3436
3437DllExport int
3438win32_putchar(int c)
3439{
390b85e7 3440 return putchar(c);
84902520
TB
3441}
3442
bbc8f9de
NIS
3443#ifdef MYMALLOC
3444
3445#ifndef USE_PERL_SBRK
3446
3447static char *committed = NULL;
3448static char *base = NULL;
3449static char *reserved = NULL;
3450static char *brk = NULL;
3451static DWORD pagesize = 0;
3452static DWORD allocsize = 0;
3453
3454void *
3455sbrk(int need)
3456{
3457 void *result;
3458 if (!pagesize)
3459 {SYSTEM_INFO info;
3460 GetSystemInfo(&info);
3461 /* Pretend page size is larger so we don't perpetually
3462 * call the OS to commit just one page ...
3463 */
3464 pagesize = info.dwPageSize << 3;
3465 allocsize = info.dwAllocationGranularity;
3466 }
3467 /* This scheme fails eventually if request for contiguous
3468 * block is denied so reserve big blocks - this is only
3469 * address space not memory ...
3470 */
3471 if (brk+need >= reserved)
3472 {
3473 DWORD size = 64*1024*1024;
3474 char *addr;
3475 if (committed && reserved && committed < reserved)
3476 {
3477 /* Commit last of previous chunk cannot span allocations */
161b471a 3478 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
bbc8f9de
NIS
3479 if (addr)
3480 committed = reserved;
3481 }
3482 /* Reserve some (more) space
3483 * Note this is a little sneaky, 1st call passes NULL as reserved
3484 * so lets system choose where we start, subsequent calls pass
3485 * the old end address so ask for a contiguous block
3486 */
161b471a 3487 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
bbc8f9de
NIS
3488 if (addr)
3489 {
3490 reserved = addr+size;
3491 if (!base)
3492 base = addr;
3493 if (!committed)
3494 committed = base;
3495 if (!brk)
3496 brk = committed;
3497 }
3498 else
3499 {
3500 return (void *) -1;
3501 }
3502 }
3503 result = brk;
3504 brk += need;
3505 if (brk > committed)
3506 {
3507 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
161b471a 3508 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
bbc8f9de
NIS
3509 if (addr)
3510 {
3511 committed += size;
3512 }
3513 else
3514 return (void *) -1;
3515 }
3516 return result;
3517}
3518
3519#endif
3520#endif
3521
84902520
TB
3522DllExport void*
3523win32_malloc(size_t size)
3524{
390b85e7 3525 return malloc(size);
84902520
TB
3526}
3527
3528DllExport void*
3529win32_calloc(size_t numitems, size_t size)
3530{
390b85e7 3531 return calloc(numitems,size);
84902520
TB
3532}
3533
3534DllExport void*
3535win32_realloc(void *block, size_t size)
3536{
390b85e7 3537 return realloc(block,size);
84902520
TB
3538}
3539
3540DllExport void
3541win32_free(void *block)
3542{
390b85e7 3543 free(block);
84902520
TB
3544}
3545
bbc8f9de 3546
68dc0745 3547int
65e48ea9 3548win32_open_osfhandle(long handle, int flags)
0a753a76 3549{
9e5f57de
GS
3550#ifdef USE_FIXED_OSFHANDLE
3551 if (IsWin95())
3552 return my_open_osfhandle(handle, flags);
3553#endif
390b85e7 3554 return _open_osfhandle(handle, flags);
0a753a76
PP
3555}
3556
68dc0745 3557long
65e48ea9 3558win32_get_osfhandle(int fd)
0a753a76 3559{
390b85e7 3560 return _get_osfhandle(fd);
0a753a76 3561}
7bac28a0 3562
0cb96387 3563DllExport void*
c5be433b 3564win32_dynaload(const char* filename)
0cb96387 3565{
c5be433b 3566 dTHXo;
51371543 3567 HMODULE hModule;
32f99636
GS
3568 char buf[MAX_PATH+1];
3569 char *first;
3570
3571 /* LoadLibrary() doesn't recognize forward slashes correctly,
3572 * so turn 'em back. */
3573 first = strchr(filename, '/');
3574 if (first) {
3575 STRLEN len = strlen(filename);
3576 if (len <= MAX_PATH) {
3577 strcpy(buf, filename);
3578 filename = &buf[first - filename];
3579 while (*filename) {
3580 if (*filename == '/')
3581 *(char*)filename = '\\';
3582 ++filename;
3583 }
3584 filename = buf;
3585 }
3586 }
0cb96387 3587 if (USING_WIDE()) {
82867ecf 3588 WCHAR wfilename[MAX_PATH+1];
0cb96387 3589 A2WHELPER(filename, wfilename, sizeof(wfilename));
7766f137 3590 hModule = LoadLibraryExW(PerlDir_mapW(wfilename), NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
0cb96387
GS
3591 }
3592 else {
7766f137 3593 hModule = LoadLibraryExA(PerlDir_mapA(filename), NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
0cb96387
GS
3594 }
3595 return hModule;
3596}
3597
7bac28a0
PP
3598/*
3599 * Extras.
3600 */
3601
ad2e33dc
GS
3602static
3603XS(w32_GetCwd)
3604{
3605 dXSARGS;
7766f137
GS
3606 /* Make the host for current directory */
3607 char* ptr = PerlEnv_get_childdir();
ad2e33dc 3608 /*
7766f137 3609 * If ptr != Nullch
ad2e33dc 3610 * then it worked, set PV valid,
7766f137 3611 * else return 'undef'
ad2e33dc 3612 */
7766f137
GS
3613 if (ptr) {
3614 SV *sv = sv_newmortal();
3615 sv_setpv(sv, ptr);
3616 PerlEnv_free_childdir(ptr);
3617
3618 EXTEND(SP,1);
ad2e33dc 3619 SvPOK_on(sv);
bb897dfc
JD
3620 ST(0) = sv;
3621 XSRETURN(1);
3622 }
3467312b 3623 XSRETURN_UNDEF;
ad2e33dc
GS
3624}
3625
3626static
3627XS(w32_SetCwd)
3628{
3629 dXSARGS;
3630 if (items != 1)
4f63d024 3631 Perl_croak(aTHX_ "usage: Win32::SetCurrentDirectory($cwd)");
7766f137 3632 if (!PerlDir_chdir(SvPV_nolen(ST(0))))
ad2e33dc
GS
3633 XSRETURN_YES;
3634
3635 XSRETURN_NO;
3636}
3637
3638static
3639XS(w32_GetNextAvailDrive)
3640{
3641 dXSARGS;
3642 char ix = 'C';
3643 char root[] = "_:\\";
3467312b
JD
3644
3645 EXTEND(SP,1);
ad2e33dc
GS
3646 while (ix <= 'Z') {
3647 root[0] = ix++;
3648 if (GetDriveType(root) == 1) {
3649 root[2] = '\0';
3650 XSRETURN_PV(root);
3651 }
3652 }
3467312b 3653 XSRETURN_UNDEF;
ad2e33dc
GS
3654}
3655
3656static
3657XS(w32_GetLastError)
3658{
3659 dXSARGS;
bb897dfc 3660 EXTEND(SP,1);
ad2e33dc
GS
3661 XSRETURN_IV(GetLastError());
3662}
3663
3664static
ca135624
JD
3665XS(w32_SetLastError)
3666{
3667 dXSARGS;
3668 if (items != 1)
4f63d024 3669 Perl_croak(aTHX_ "usage: Win32::SetLastError($error)");
ca135624