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