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