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