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