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