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