flush all open output buffers before fork(), exec(), system, qx//
[p5sagit/p5-mst-13.2.git] / win32 / win32.c
CommitLineData
68dc0745 1/* WIN32.C
2 *
3 * (c) 1995 Microsoft Corporation. All rights reserved.
4 * Developed by hip communications inc., http://info.hip.com/info/
5 * Portions (c) 1993 Intergraph Corporation. All rights reserved.
6 *
7 * You may distribute under the terms of either the GNU General Public
8 * License or the Artistic License, as specified in the README file.
9 */
0a753a76 10
11#define WIN32_LEAN_AND_MEAN
12#define WIN32IO_IS_STDIO
13#include <tchar.h>
a835ef8a 14#ifdef __GNUC__
15#define Win32_Winsock
16#endif
0a753a76 17#include <windows.h>
18
e56670dd 19#ifndef __MINGW32__
9404a519 20#include <lmcons.h>
21#include <lmerr.h>
22/* ugliness to work around a buggy struct definition in lmwksta.h */
23#undef LPTSTR
24#define LPTSTR LPWSTR
25#include <lmwksta.h>
26#undef LPTSTR
27#define LPTSTR LPSTR
e56670dd 28#include <lmapibuf.h>
29#endif /* __MINGW32__ */
9404a519 30
68dc0745 31/* #include "config.h" */
0a753a76 32
33#define PERLIO_NOT_STDIO 0
34#if !defined(PERLIO_IS_STDIO) && !defined(USE_SFIO)
35#define PerlIO FILE
36#endif
37
38#include "EXTERN.h"
39#include "perl.h"
c69f6586 40
41#define NO_XSLOCKS
42#ifdef PERL_OBJECT
43extern CPerlObj* pPerl;
44#endif
ad2e33dc 45#include "XSUB.h"
c69f6586 46
47#include "Win32iop.h"
0a753a76 48#include <fcntl.h>
49#include <sys/stat.h>
5b0d9cbe 50#ifndef __GNUC__
51/* assert.h conflicts with #define of assert in perl.h */
0a753a76 52#include <assert.h>
5b0d9cbe 53#endif
0a753a76 54#include <string.h>
55#include <stdarg.h>
ad2e33dc 56#include <float.h>
ad0751ec 57#include <time.h>
3730b96e 58#if defined(_MSC_VER) || defined(__MINGW32__)
ad0751ec 59#include <sys/utime.h>
60#else
61#include <utime.h>
62#endif
0a753a76 63
5b0d9cbe 64#ifdef __GNUC__
65/* Mingw32 defaults to globing command line
66 * So we turn it off like this:
67 */
68int _CRT_glob = 0;
69#endif
70
6890e559 71#define EXECF_EXEC 1
72#define EXECF_SPAWN 2
73#define EXECF_SPAWN_NOWAIT 3
74
c69f6586 75#if defined(PERL_OBJECT)
e5a95ffb 76#undef win32_get_privlib
77#define win32_get_privlib g_win32_get_privlib
00dc2f4f 78#undef win32_get_sitelib
79#define win32_get_sitelib g_win32_get_sitelib
c69f6586 80#undef do_aspawn
81#define do_aspawn g_do_aspawn
82#undef do_spawn
83#define do_spawn g_do_spawn
84#undef do_exec
85#define do_exec g_do_exec
c69f6586 86#undef getlogin
87#define getlogin g_getlogin
88#endif
89
2d7a9237 90static DWORD os_id(void);
ce1da67e 91static void get_shell(void);
92static long tokenize(char *str, char **dest, char ***destv);
c69f6586 93 int do_spawn2(char *cmd, int exectype);
e200fe59 94static BOOL has_shell_metachars(char *ptr);
2d7a9237 95static long filetime_to_clock(PFILETIME ft);
ad0751ec 96static BOOL filetime_from_time(PFILETIME ft, time_t t);
e5a95ffb 97static char * get_emd_part(char *leading, char *trailing, ...);
0aaad0ff 98static void remove_dead_process(long deceased);
99static long find_pid(int pid);
100static char * qualified_path(const char *cmd);
c69f6586 101
2d7a9237 102HANDLE w32_perldll_handle = INVALID_HANDLE_VALUE;
4b556e6c 103static DWORD w32_platform = (DWORD)-1;
50892819 104
26618a56 105#ifdef USE_THREADS
106# ifdef USE_DECLSPEC_THREAD
107__declspec(thread) char strerror_buffer[512];
e34ffe5a 108__declspec(thread) char getlogin_buffer[128];
4b556e6c 109__declspec(thread) char w32_perllib_root[MAX_PATH+1];
26618a56 110# ifdef HAVE_DES_FCRYPT
111__declspec(thread) char crypt_buffer[30];
112# endif
113# else
114# define strerror_buffer (thr->i.Wstrerror_buffer)
e34ffe5a 115# define getlogin_buffer (thr->i.Wgetlogin_buffer)
4b556e6c 116# define w32_perllib_root (thr->i.Ww32_perllib_root)
26618a56 117# define crypt_buffer (thr->i.Wcrypt_buffer)
118# endif
119#else
4b556e6c 120static char strerror_buffer[512];
121static char getlogin_buffer[128];
122static char w32_perllib_root[MAX_PATH+1];
26618a56 123# ifdef HAVE_DES_FCRYPT
4b556e6c 124static char crypt_buffer[30];
26618a56 125# endif
126#endif
127
3fe9a6f1 128int
129IsWin95(void) {
2d7a9237 130 return (os_id() == VER_PLATFORM_WIN32_WINDOWS);
3fe9a6f1 131}
132
133int
134IsWinNT(void) {
2d7a9237 135 return (os_id() == VER_PLATFORM_WIN32_NT);
3fe9a6f1 136}
0a753a76 137
00dc2f4f 138char*
139GetRegStrFromKey(HKEY hkey, const char *lpszValueName, char** ptr, DWORD* lpDataLen)
140{ /* Retrieve a REG_SZ or REG_EXPAND_SZ from the registry */
141 HKEY handle;
142 DWORD type;
143 const char *subkey = "Software\\Perl";
144 long retval;
145
146 retval = RegOpenKeyEx(hkey, subkey, 0, KEY_READ, &handle);
ba3eb2af 147 if (retval == ERROR_SUCCESS){
00dc2f4f 148 retval = RegQueryValueEx(handle, lpszValueName, 0, &type, NULL, lpDataLen);
ba3eb2af 149 if (retval == ERROR_SUCCESS && type == REG_SZ) {
c934e9d4 150 if (*ptr) {
00dc2f4f 151 Renew(*ptr, *lpDataLen, char);
152 }
153 else {
154 New(1312, *ptr, *lpDataLen, char);
155 }
156 retval = RegQueryValueEx(handle, lpszValueName, 0, NULL, (PBYTE)*ptr, lpDataLen);
ba3eb2af 157 if (retval != ERROR_SUCCESS) {
e5a95ffb 158 Safefree(*ptr);
c934e9d4 159 *ptr = Nullch;
00dc2f4f 160 }
161 }
162 RegCloseKey(handle);
163 }
164 return *ptr;
165}
166
167char*
168GetRegStr(const char *lpszValueName, char** ptr, DWORD* lpDataLen)
169{
170 *ptr = GetRegStrFromKey(HKEY_CURRENT_USER, lpszValueName, ptr, lpDataLen);
c934e9d4 171 if (*ptr == Nullch)
00dc2f4f 172 {
173 *ptr = GetRegStrFromKey(HKEY_LOCAL_MACHINE, lpszValueName, ptr, lpDataLen);
174 }
175 return *ptr;
176}
177
e5a95ffb 178static char *
179get_emd_part(char *prev_path, char *trailing_path, ...)
00dc2f4f 180{
dc9e4912 181 char base[10];
e5a95ffb 182 va_list ap;
e24c7c18 183 char mod_name[MAX_PATH+1];
00dc2f4f 184 char *ptr;
e5a95ffb 185 char *optr;
186 char *strip;
187 int oldsize, newsize;
188
189 va_start(ap, trailing_path);
190 strip = va_arg(ap, char *);
191
cceca5ed 192 sprintf(base, "%5.3f",
193 (double)PERL_REVISION + ((double)PERL_VERSION / (double)1000));
dc9e4912 194
80252599 195 GetModuleFileName((HMODULE)((w32_perldll_handle == INVALID_HANDLE_VALUE)
196 ? GetModuleHandle(NULL) : w32_perldll_handle),
197 mod_name, sizeof(mod_name));
95140b98 198 /* try to get full path to binary (which may be mangled when perl is
199 * run from a 16-bit app */
200 (void)GetFullPathName(mod_name, sizeof(mod_name), mod_name, &ptr);
201 ptr = mod_name;
202 /* normalize to forward slashes */
203 while (*ptr) {
204 if (*ptr == '\\')
205 *ptr = '/';
206 ++ptr;
207 }
208 ptr = strrchr(mod_name, '/');
e5a95ffb 209 while (ptr && strip) {
210 /* look for directories to skip back */
211 optr = ptr;
00dc2f4f 212 *ptr = '\0';
95140b98 213 ptr = strrchr(mod_name, '/');
e5a95ffb 214 if (!ptr || stricmp(ptr+1, strip) != 0) {
95140b98 215 if(!(*strip == '5' && *(ptr+1) == '5'
216 && strncmp(strip, base, 5) == 0
217 && strncmp(ptr+1, base, 5) == 0))
218 {
219 *optr = '/';
80252599 220 ptr = optr;
221 }
00dc2f4f 222 }
e5a95ffb 223 strip = va_arg(ap, char *);
00dc2f4f 224 }
e5a95ffb 225 if (!ptr) {
226 ptr = mod_name;
227 *ptr++ = '.';
95140b98 228 *ptr = '/';
00dc2f4f 229 }
e5a95ffb 230 va_end(ap);
231 strcpy(++ptr, trailing_path);
232
dc9e4912 233 /* only add directory if it exists */
234 if(GetFileAttributes(mod_name) != (DWORD) -1) {
235 /* directory exists */
236 newsize = strlen(mod_name) + 1;
237 if (prev_path) {
238 oldsize = strlen(prev_path) + 1;
239 newsize += oldsize; /* includes plus 1 for ';' */
240 Renew(prev_path, newsize, char);
241 prev_path[oldsize-1] = ';';
242 strcpy(&prev_path[oldsize], mod_name);
243 }
244 else {
245 New(1311, prev_path, newsize, char);
246 strcpy(prev_path, mod_name);
247 }
00dc2f4f 248 }
00dc2f4f 249
e5a95ffb 250 return prev_path;
00dc2f4f 251}
252
253char *
e5a95ffb 254win32_get_privlib(char *pl)
00dc2f4f 255{
e5a95ffb 256 char *stdlib = "lib";
257 char buffer[MAX_PATH+1];
258 char *path = Nullch;
259 DWORD datalen;
00dc2f4f 260
e5a95ffb 261 /* $stdlib = $HKCU{"lib-$]"} || $HKLM{"lib-$]"} || $HKCU{"lib"} || $HKLM{"lib"} || ""; */
262 sprintf(buffer, "%s-%s", stdlib, pl);
263 path = GetRegStr(buffer, &path, &datalen);
c934e9d4 264 if (!path)
e5a95ffb 265 path = GetRegStr(stdlib, &path, &datalen);
00dc2f4f 266
e5a95ffb 267 /* $stdlib .= ";$EMD/../../lib" */
268 return get_emd_part(path, stdlib, ARCHNAME, "bin", Nullch);
00dc2f4f 269}
270
68dc0745 271char *
00dc2f4f 272win32_get_sitelib(char *pl)
273{
e5a95ffb 274 char *sitelib = "sitelib";
275 char regstr[40];
e24c7c18 276 char pathstr[MAX_PATH+1];
e5a95ffb 277 DWORD datalen;
278 char *path1 = Nullch;
279 char *path2 = Nullch;
280 int len, newsize;
00dc2f4f 281
282 /* $HKCU{"sitelib-$]"} || $HKLM{"sitelib-$]"} . ---; */
e5a95ffb 283 sprintf(regstr, "%s-%s", sitelib, pl);
284 path1 = GetRegStr(regstr, &path1, &datalen);
285
286 /* $sitelib .=
287 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/site/$]/lib"; */
95140b98 288 sprintf(pathstr, "site/%s/lib", pl);
e5a95ffb 289 path1 = get_emd_part(path1, pathstr, ARCHNAME, "bin", pl, Nullch);
00dc2f4f 290
291 /* $HKCU{'sitelib'} || $HKLM{'sitelib'} . ---; */
e5a95ffb 292 path2 = GetRegStr(sitelib, &path2, &datalen);
00dc2f4f 293
e5a95ffb 294 /* $sitelib .=
295 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/site/lib"; */
95140b98 296 path2 = get_emd_part(path2, "site/lib", ARCHNAME, "bin", pl, Nullch);
00dc2f4f 297
e5a95ffb 298 if (!path1)
299 return path2;
00dc2f4f 300
e5a95ffb 301 if (!path2)
302 return path1;
303
304 len = strlen(path1);
305 newsize = len + strlen(path2) + 2; /* plus one for ';' */
306
307 Renew(path1, newsize, char);
308 path1[len++] = ';';
309 strcpy(&path1[len], path2);
310
311 Safefree(path2);
312 return path1;
68dc0745 313}
0a753a76 314
b4793f7f 315
2d7a9237 316static BOOL
e200fe59 317has_shell_metachars(char *ptr)
68dc0745 318{
319 int inquote = 0;
320 char quote = '\0';
321
322 /*
323 * Scan string looking for redirection (< or >) or pipe
e200fe59 324 * characters (|) that are not in a quoted string.
325 * Shell variable interpolation (%VAR%) can also happen inside strings.
68dc0745 326 */
9404a519 327 while (*ptr) {
68dc0745 328 switch(*ptr) {
e200fe59 329 case '%':
330 return TRUE;
68dc0745 331 case '\'':
332 case '\"':
9404a519 333 if (inquote) {
334 if (quote == *ptr) {
68dc0745 335 inquote = 0;
336 quote = '\0';
0a753a76 337 }
68dc0745 338 }
339 else {
340 quote = *ptr;
341 inquote++;
342 }
343 break;
344 case '>':
345 case '<':
346 case '|':
9404a519 347 if (!inquote)
68dc0745 348 return TRUE;
349 default:
350 break;
0a753a76 351 }
68dc0745 352 ++ptr;
353 }
354 return FALSE;
0a753a76 355}
356
c69f6586 357#if !defined(PERL_OBJECT)
68dc0745 358/* since the current process environment is being updated in util.c
359 * the library functions will get the correct environment
360 */
361PerlIO *
362my_popen(char *cmd, char *mode)
0a753a76 363{
364#ifdef FIXCMD
68dc0745 365#define fixcmd(x) { \
366 char *pspace = strchr((x),' '); \
367 if (pspace) { \
368 char *p = (x); \
369 while (p < pspace) { \
370 if (*p == '/') \
371 *p = '\\'; \
372 p++; \
373 } \
374 } \
375 }
0a753a76 376#else
377#define fixcmd(x)
378#endif
68dc0745 379 fixcmd(cmd);
45bc9206 380 PERL_FLUSHALL_FOR_CHILD;
0a753a76 381 return win32_popen(cmd, mode);
0a753a76 382}
383
68dc0745 384long
385my_pclose(PerlIO *fp)
0a753a76 386{
387 return win32_pclose(fp);
388}
c69f6586 389#endif
0a753a76 390
8b10511d 391static DWORD
2d7a9237 392os_id(void)
0a753a76 393{
8b10511d 394 static OSVERSIONINFO osver;
0a753a76 395
2d7a9237 396 if (osver.dwPlatformId != w32_platform) {
8b10511d 397 memset(&osver, 0, sizeof(OSVERSIONINFO));
398 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
399 GetVersionEx(&osver);
2d7a9237 400 w32_platform = osver.dwPlatformId;
8b10511d 401 }
2d7a9237 402 return (w32_platform);
0a753a76 403}
404
ce1da67e 405/* Tokenize a string. Words are null-separated, and the list
406 * ends with a doubled null. Any character (except null and
407 * including backslash) may be escaped by preceding it with a
408 * backslash (the backslash will be stripped).
409 * Returns number of words in result buffer.
410 */
411static long
412tokenize(char *str, char **dest, char ***destv)
413{
414 char *retstart = Nullch;
415 char **retvstart = 0;
416 int items = -1;
417 if (str) {
418 int slen = strlen(str);
419 register char *ret;
420 register char **retv;
421 New(1307, ret, slen+2, char);
422 New(1308, retv, (slen+3)/2, char*);
423
424 retstart = ret;
425 retvstart = retv;
426 *retv = ret;
427 items = 0;
428 while (*str) {
429 *ret = *str++;
430 if (*ret == '\\' && *str)
431 *ret = *str++;
432 else if (*ret == ' ') {
433 while (*str == ' ')
434 str++;
435 if (ret == retstart)
436 ret--;
437 else {
438 *ret = '\0';
439 ++items;
440 if (*str)
441 *++retv = ret+1;
442 }
443 }
444 else if (!*str)
445 ++items;
446 ret++;
447 }
448 retvstart[items] = Nullch;
449 *ret++ = '\0';
450 *ret = '\0';
451 }
452 *dest = retstart;
453 *destv = retvstart;
454 return items;
455}
456
457static void
2d7a9237 458get_shell(void)
0a753a76 459{
ce1da67e 460 if (!w32_perlshell_tokens) {
174c211a 461 /* we don't use COMSPEC here for two reasons:
462 * 1. the same reason perl on UNIX doesn't use SHELL--rampant and
463 * uncontrolled unportability of the ensuing scripts.
464 * 2. PERL5SHELL could be set to a shell that may not be fit for
465 * interactive use (which is what most programs look in COMSPEC
466 * for).
467 */
ce1da67e 468 char* defaultshell = (IsWinNT() ? "cmd.exe /x/c" : "command.com /c");
469 char *usershell = getenv("PERL5SHELL");
470 w32_perlshell_items = tokenize(usershell ? usershell : defaultshell,
471 &w32_perlshell_tokens,
472 &w32_perlshell_vec);
68dc0745 473 }
0a753a76 474}
475
68dc0745 476int
2d7a9237 477do_aspawn(void *vreally, void **vmark, void **vsp)
0a753a76 478{
2d7a9237 479 SV *really = (SV*)vreally;
480 SV **mark = (SV**)vmark;
481 SV **sp = (SV**)vsp;
68dc0745 482 char **argv;
2d7a9237 483 char *str;
68dc0745 484 int status;
2d7a9237 485 int flag = P_WAIT;
68dc0745 486 int index = 0;
68dc0745 487
2d7a9237 488 if (sp <= mark)
489 return -1;
68dc0745 490
ce1da67e 491 get_shell();
492 New(1306, argv, (sp - mark) + w32_perlshell_items + 2, char*);
2d7a9237 493
494 if (SvNIOKp(*(mark+1)) && !SvPOKp(*(mark+1))) {
495 ++mark;
496 flag = SvIVx(*mark);
68dc0745 497 }
498
9404a519 499 while (++mark <= sp) {
bb897dfc 500 if (*mark && (str = SvPV_nolen(*mark)))
2d7a9237 501 argv[index++] = str;
502 else
503 argv[index++] = "";
68dc0745 504 }
505 argv[index++] = 0;
506
2d7a9237 507 status = win32_spawnvp(flag,
bb897dfc 508 (const char*)(really ? SvPV_nolen(really) : argv[0]),
2d7a9237 509 (const char* const*)argv);
510
80252599 511 if (status < 0 && (errno == ENOEXEC || errno == ENOENT)) {
2d7a9237 512 /* possible shell-builtin, invoke with shell */
ce1da67e 513 int sh_items;
514 sh_items = w32_perlshell_items;
2d7a9237 515 while (--index >= 0)
516 argv[index+sh_items] = argv[index];
ce1da67e 517 while (--sh_items >= 0)
518 argv[sh_items] = w32_perlshell_vec[sh_items];
2d7a9237 519
520 status = win32_spawnvp(flag,
bb897dfc 521 (const char*)(really ? SvPV_nolen(really) : argv[0]),
2d7a9237 522 (const char* const*)argv);
523 }
68dc0745 524
50892819 525 if (flag != P_NOWAIT) {
526 if (status < 0) {
b28d0864 527 if (PL_dowarn)
50892819 528 warn("Can't spawn \"%s\": %s", argv[0], strerror(errno));
529 status = 255 * 256;
530 }
531 else
532 status *= 256;
b28d0864 533 PL_statusvalue = status;
5aabfad6 534 }
ce1da67e 535 Safefree(argv);
50892819 536 return (status);
68dc0745 537}
538
c69f6586 539int
6890e559 540do_spawn2(char *cmd, int exectype)
68dc0745 541{
542 char **a;
543 char *s;
544 char **argv;
545 int status = -1;
546 BOOL needToTry = TRUE;
2d7a9237 547 char *cmd2;
68dc0745 548
2d7a9237 549 /* Save an extra exec if possible. See if there are shell
550 * metacharacters in it */
e200fe59 551 if (!has_shell_metachars(cmd)) {
fc36a67e 552 New(1301,argv, strlen(cmd) / 2 + 2, char*);
553 New(1302,cmd2, strlen(cmd) + 1, char);
68dc0745 554 strcpy(cmd2, cmd);
555 a = argv;
556 for (s = cmd2; *s;) {
557 while (*s && isspace(*s))
558 s++;
559 if (*s)
560 *(a++) = s;
9404a519 561 while (*s && !isspace(*s))
68dc0745 562 s++;
9404a519 563 if (*s)
68dc0745 564 *s++ = '\0';
0a753a76 565 }
68dc0745 566 *a = Nullch;
ce1da67e 567 if (argv[0]) {
6890e559 568 switch (exectype) {
569 case EXECF_SPAWN:
570 status = win32_spawnvp(P_WAIT, argv[0],
571 (const char* const*)argv);
572 break;
573 case EXECF_SPAWN_NOWAIT:
574 status = win32_spawnvp(P_NOWAIT, argv[0],
575 (const char* const*)argv);
576 break;
577 case EXECF_EXEC:
578 status = win32_execvp(argv[0], (const char* const*)argv);
579 break;
580 }
2d7a9237 581 if (status != -1 || errno == 0)
68dc0745 582 needToTry = FALSE;
0a753a76 583 }
0a753a76 584 Safefree(argv);
68dc0745 585 Safefree(cmd2);
586 }
2d7a9237 587 if (needToTry) {
ce1da67e 588 char **argv;
589 int i = -1;
590 get_shell();
591 New(1306, argv, w32_perlshell_items + 2, char*);
592 while (++i < w32_perlshell_items)
593 argv[i] = w32_perlshell_vec[i];
2d7a9237 594 argv[i++] = cmd;
595 argv[i] = Nullch;
6890e559 596 switch (exectype) {
597 case EXECF_SPAWN:
598 status = win32_spawnvp(P_WAIT, argv[0],
599 (const char* const*)argv);
600 break;
601 case EXECF_SPAWN_NOWAIT:
602 status = win32_spawnvp(P_NOWAIT, argv[0],
603 (const char* const*)argv);
604 break;
605 case EXECF_EXEC:
606 status = win32_execvp(argv[0], (const char* const*)argv);
607 break;
608 }
ce1da67e 609 cmd = argv[0];
610 Safefree(argv);
68dc0745 611 }
50892819 612 if (exectype != EXECF_SPAWN_NOWAIT) {
613 if (status < 0) {
b28d0864 614 if (PL_dowarn)
50892819 615 warn("Can't %s \"%s\": %s",
616 (exectype == EXECF_EXEC ? "exec" : "spawn"),
617 cmd, strerror(errno));
618 status = 255 * 256;
619 }
620 else
621 status *= 256;
b28d0864 622 PL_statusvalue = status;
5aabfad6 623 }
50892819 624 return (status);
0a753a76 625}
626
6890e559 627int
628do_spawn(char *cmd)
629{
630 return do_spawn2(cmd, EXECF_SPAWN);
631}
632
2d7a9237 633int
634do_spawn_nowait(char *cmd)
635{
636 return do_spawn2(cmd, EXECF_SPAWN_NOWAIT);
637}
638
6890e559 639bool
640do_exec(char *cmd)
641{
642 do_spawn2(cmd, EXECF_EXEC);
643 return FALSE;
644}
645
68dc0745 646/* The idea here is to read all the directory names into a string table
647 * (separated by nulls) and when one of the other dir functions is called
648 * return the pointer to the current file name.
649 */
650DIR *
ce2e26e5 651win32_opendir(char *filename)
0a753a76 652{
9404a519 653 DIR *p;
654 long len;
655 long idx;
656 char scanname[MAX_PATH+3];
657 struct stat sbuf;
658 WIN32_FIND_DATA FindData;
659 HANDLE fh;
660
661 len = strlen(filename);
662 if (len > MAX_PATH)
663 return NULL;
68dc0745 664
665 /* check to see if filename is a directory */
69d3ab13 666 if (win32_stat(filename, &sbuf) < 0 || !S_ISDIR(sbuf.st_mode))
24caa93f 667 return NULL;
68dc0745 668
68dc0745 669 /* Get us a DIR structure */
fc36a67e 670 Newz(1303, p, 1, DIR);
9404a519 671 if (p == NULL)
68dc0745 672 return NULL;
673
674 /* Create the search pattern */
675 strcpy(scanname, filename);
9404a519 676 if (scanname[len-1] != '/' && scanname[len-1] != '\\')
677 scanname[len++] = '/';
678 scanname[len++] = '*';
679 scanname[len] = '\0';
68dc0745 680
681 /* do the FindFirstFile call */
682 fh = FindFirstFile(scanname, &FindData);
9404a519 683 if (fh == INVALID_HANDLE_VALUE) {
21e72512 684 /* FindFirstFile() fails on empty drives! */
685 if (GetLastError() == ERROR_FILE_NOT_FOUND)
686 return p;
687 Safefree( p);
68dc0745 688 return NULL;
689 }
690
691 /* now allocate the first part of the string table for
692 * the filenames that we find.
693 */
694 idx = strlen(FindData.cFileName)+1;
fc36a67e 695 New(1304, p->start, idx, char);
9404a519 696 if (p->start == NULL)
65e48ea9 697 croak("opendir: malloc failed!\n");
68dc0745 698 strcpy(p->start, FindData.cFileName);
68dc0745 699 p->nfiles++;
700
701 /* loop finding all the files that match the wildcard
702 * (which should be all of them in this directory!).
703 * the variable idx should point one past the null terminator
704 * of the previous string found.
705 */
706 while (FindNextFile(fh, &FindData)) {
707 len = strlen(FindData.cFileName);
708 /* bump the string table size by enough for the
709 * new name and it's null terminator
710 */
711 Renew(p->start, idx+len+1, char);
9404a519 712 if (p->start == NULL)
65e48ea9 713 croak("opendir: malloc failed!\n");
68dc0745 714 strcpy(&p->start[idx], FindData.cFileName);
9404a519 715 p->nfiles++;
716 idx += len+1;
717 }
718 FindClose(fh);
719 p->size = idx;
720 p->curr = p->start;
721 return p;
0a753a76 722}
723
724
68dc0745 725/* Readdir just returns the current string pointer and bumps the
726 * string pointer to the nDllExport entry.
727 */
728struct direct *
ce2e26e5 729win32_readdir(DIR *dirp)
0a753a76 730{
68dc0745 731 int len;
732 static int dummy = 0;
0a753a76 733
68dc0745 734 if (dirp->curr) {
735 /* first set up the structure to return */
736 len = strlen(dirp->curr);
737 strcpy(dirp->dirstr.d_name, dirp->curr);
738 dirp->dirstr.d_namlen = len;
0a753a76 739
68dc0745 740 /* Fake an inode */
741 dirp->dirstr.d_ino = dummy++;
0a753a76 742
68dc0745 743 /* Now set up for the nDllExport call to readdir */
744 dirp->curr += len + 1;
745 if (dirp->curr >= (dirp->start + dirp->size)) {
746 dirp->curr = NULL;
747 }
0a753a76 748
68dc0745 749 return &(dirp->dirstr);
750 }
751 else
752 return NULL;
0a753a76 753}
754
68dc0745 755/* Telldir returns the current string pointer position */
756long
ce2e26e5 757win32_telldir(DIR *dirp)
0a753a76 758{
759 return (long) dirp->curr;
760}
761
762
68dc0745 763/* Seekdir moves the string pointer to a previously saved position
764 *(Saved by telldir).
765 */
766void
ce2e26e5 767win32_seekdir(DIR *dirp, long loc)
0a753a76 768{
769 dirp->curr = (char *)loc;
770}
771
68dc0745 772/* Rewinddir resets the string pointer to the start */
773void
ce2e26e5 774win32_rewinddir(DIR *dirp)
0a753a76 775{
776 dirp->curr = dirp->start;
777}
778
68dc0745 779/* free the memory allocated by opendir */
780int
ce2e26e5 781win32_closedir(DIR *dirp)
0a753a76 782{
783 Safefree(dirp->start);
784 Safefree(dirp);
68dc0745 785 return 1;
0a753a76 786}
787
788
68dc0745 789/*
790 * various stubs
791 */
0a753a76 792
793
68dc0745 794/* Ownership
795 *
796 * Just pretend that everyone is a superuser. NT will let us know if
797 * we don\'t really have permission to do something.
798 */
0a753a76 799
800#define ROOT_UID ((uid_t)0)
801#define ROOT_GID ((gid_t)0)
802
68dc0745 803uid_t
804getuid(void)
0a753a76 805{
68dc0745 806 return ROOT_UID;
0a753a76 807}
808
68dc0745 809uid_t
810geteuid(void)
0a753a76 811{
68dc0745 812 return ROOT_UID;
0a753a76 813}
814
68dc0745 815gid_t
816getgid(void)
0a753a76 817{
68dc0745 818 return ROOT_GID;
0a753a76 819}
820
68dc0745 821gid_t
822getegid(void)
0a753a76 823{
68dc0745 824 return ROOT_GID;
0a753a76 825}
826
68dc0745 827int
22239a37 828setuid(uid_t auid)
0a753a76 829{
22239a37 830 return (auid == ROOT_UID ? 0 : -1);
0a753a76 831}
832
68dc0745 833int
22239a37 834setgid(gid_t agid)
0a753a76 835{
22239a37 836 return (agid == ROOT_GID ? 0 : -1);
0a753a76 837}
838
e34ffe5a 839char *
840getlogin(void)
841{
842 dTHR;
843 char *buf = getlogin_buffer;
844 DWORD size = sizeof(getlogin_buffer);
845 if (GetUserName(buf,&size))
846 return buf;
847 return (char*)NULL;
848}
849
b990f8c8 850int
851chown(const char *path, uid_t owner, gid_t group)
852{
853 /* XXX noop */
1c1c7f20 854 return 0;
b990f8c8 855}
856
0aaad0ff 857static long
858find_pid(int pid)
0a753a76 859{
0aaad0ff 860 long child;
f55ee38a 861 for (child = 0 ; child < w32_num_children ; ++child) {
0aaad0ff 862 if (w32_child_pids[child] == pid)
863 return child;
864 }
865 return -1;
866}
867
868static void
869remove_dead_process(long child)
870{
871 if (child >= 0) {
872 CloseHandle(w32_child_handles[child]);
873 Copy(&w32_child_handles[child+1], &w32_child_handles[child],
874 (w32_num_children-child-1), HANDLE);
875 Copy(&w32_child_pids[child+1], &w32_child_pids[child],
876 (w32_num_children-child-1), DWORD);
877 w32_num_children--;
f55ee38a 878 }
f55ee38a 879}
880
881DllExport int
882win32_kill(int pid, int sig)
883{
0aaad0ff 884 HANDLE hProcess;
885 hProcess = OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid);
886 if (hProcess && TerminateProcess(hProcess, sig))
68dc0745 887 CloseHandle(hProcess);
0aaad0ff 888 else {
889 errno = EINVAL;
890 return -1;
68dc0745 891 }
892 return 0;
0a753a76 893}
fbbbcc48 894
68dc0745 895/*
896 * File system stuff
897 */
0a753a76 898
f3986ebb 899DllExport unsigned int
900win32_sleep(unsigned int t)
0a753a76 901{
68dc0745 902 Sleep(t*1000);
903 return 0;
0a753a76 904}
905
68dc0745 906DllExport int
907win32_stat(const char *path, struct stat *buffer)
0a753a76 908{
24caa93f 909 char t[MAX_PATH+1];
68dc0745 910 int l = strlen(path);
67fbe06e 911 int res;
0a753a76 912
68dc0745 913 if (l > 1) {
914 switch(path[l - 1]) {
e1dbac94 915 /* FindFirstFile() and stat() are buggy with a trailing
916 * backslash, so change it to a forward slash :-( */
68dc0745 917 case '\\':
e1dbac94 918 strncpy(t, path, l-1);
919 t[l - 1] = '/';
920 t[l] = '\0';
921 path = t;
922 break;
923 /* FindFirstFile() is buggy with "x:", so add a slash :-( */
924 case ':':
925 if (l == 2 && isALPHA(path[0])) {
926 t[0] = path[0]; t[1] = ':'; t[2] = '/'; t[3] = '\0';
927 l = 3;
928 path = t;
929 }
930 break;
68dc0745 931 }
932 }
e1dbac94 933 res = stat(path,buffer);
24caa93f 934 if (res < 0) {
935 /* CRT is buggy on sharenames, so make sure it really isn't.
936 * XXX using GetFileAttributesEx() will enable us to set
937 * buffer->st_*time (but note that's not available on the
938 * Windows of 1995) */
e1dbac94 939 DWORD r = GetFileAttributes(path);
24caa93f 940 if (r != 0xffffffff && (r & FILE_ATTRIBUTE_DIRECTORY)) {
e1dbac94 941 /* buffer may still contain old garbage since stat() failed */
942 Zero(buffer, 1, struct stat);
943 buffer->st_mode = S_IFDIR | S_IREAD;
24caa93f 944 errno = 0;
945 if (!(r & FILE_ATTRIBUTE_READONLY))
946 buffer->st_mode |= S_IWRITE | S_IEXEC;
947 return 0;
948 }
949 }
24caa93f 950 else {
e1dbac94 951 if (l == 3 && isALPHA(path[0]) && path[1] == ':'
952 && (path[2] == '\\' || path[2] == '/'))
2293b0e9 953 {
954 /* The drive can be inaccessible, some _stat()s are buggy */
955 if (!GetVolumeInformation(path,NULL,0,NULL,NULL,NULL,NULL,0)) {
956 errno = ENOENT;
957 return -1;
958 }
959 }
960#ifdef __BORLANDC__
67fbe06e 961 if (S_ISDIR(buffer->st_mode))
962 buffer->st_mode |= S_IWRITE | S_IEXEC;
963 else if (S_ISREG(buffer->st_mode)) {
964 if (l >= 4 && path[l-4] == '.') {
965 const char *e = path + l - 3;
966 if (strnicmp(e,"exe",3)
967 && strnicmp(e,"bat",3)
968 && strnicmp(e,"com",3)
969 && (IsWin95() || strnicmp(e,"cmd",3)))
970 buffer->st_mode &= ~S_IEXEC;
971 else
972 buffer->st_mode |= S_IEXEC;
973 }
974 else
975 buffer->st_mode &= ~S_IEXEC;
976 }
67fbe06e 977#endif
2293b0e9 978 }
67fbe06e 979 return res;
0a753a76 980}
981
0551aaa8 982#ifndef USE_WIN32_RTL_ENV
983
984DllExport char *
985win32_getenv(const char *name)
986{
c934e9d4 987 static char *curitem = Nullch; /* XXX threadead */
46124e9e 988 static DWORD curlen = 0; /* XXX threadead */
0551aaa8 989 DWORD needlen;
46124e9e 990 if (!curitem) {
991 curlen = 512;
0551aaa8 992 New(1305,curitem,curlen,char);
46124e9e 993 }
58a50f62 994
995 needlen = GetEnvironmentVariable(name,curitem,curlen);
996 if (needlen != 0) {
997 while (needlen > curlen) {
998 Renew(curitem,needlen,char);
999 curlen = needlen;
1000 needlen = GetEnvironmentVariable(name,curitem,curlen);
1001 }
0551aaa8 1002 }
c934e9d4 1003 else {
7a5f8e82 1004 /* allow any environment variables that begin with 'PERL'
c934e9d4 1005 to be stored in the registry */
1006 if (curitem)
58a50f62 1007 *curitem = '\0';
1008
7a5f8e82 1009 if (strncmp(name, "PERL", 4) == 0) {
c934e9d4 1010 if (curitem) {
58a50f62 1011 Safefree(curitem);
c934e9d4 1012 curitem = Nullch;
46124e9e 1013 curlen = 0;
58a50f62 1014 }
00dc2f4f 1015 curitem = GetRegStr(name, &curitem, &curlen);
58a50f62 1016 }
c69f6586 1017 }
c934e9d4 1018 if (curitem && *curitem == '\0')
58a50f62 1019 return Nullch;
1020
0551aaa8 1021 return curitem;
1022}
1023
ac5c734f 1024DllExport int
1025win32_putenv(const char *name)
1026{
1027 char* curitem;
1028 char* val;
1029 int relval = -1;
1030 if(name) {
1031 New(1309,curitem,strlen(name)+1,char);
1032 strcpy(curitem, name);
1033 val = strchr(curitem, '=');
1034 if(val) {
1035 /* The sane way to deal with the environment.
1036 * Has these advantages over putenv() & co.:
1037 * * enables us to store a truly empty value in the
1038 * environment (like in UNIX).
1039 * * we don't have to deal with RTL globals, bugs and leaks.
1040 * * Much faster.
1041 * Why you may want to enable USE_WIN32_RTL_ENV:
1042 * * environ[] and RTL functions will not reflect changes,
1043 * which might be an issue if extensions want to access
1044 * the env. via RTL. This cuts both ways, since RTL will
1045 * not see changes made by extensions that call the Win32
1046 * functions directly, either.
1047 * GSAR 97-06-07
1048 */
1049 *val++ = '\0';
1050 if(SetEnvironmentVariable(curitem, *val ? val : NULL))
1051 relval = 0;
1052 }
1053 Safefree(curitem);
1054 }
1055 return relval;
1056}
1057
0551aaa8 1058#endif
1059
d55594ae 1060static long
2d7a9237 1061filetime_to_clock(PFILETIME ft)
d55594ae 1062{
1063 __int64 qw = ft->dwHighDateTime;
1064 qw <<= 32;
1065 qw |= ft->dwLowDateTime;
1066 qw /= 10000; /* File time ticks at 0.1uS, clock at 1mS */
1067 return (long) qw;
1068}
1069
f3986ebb 1070DllExport int
1071win32_times(struct tms *timebuf)
0a753a76 1072{
d55594ae 1073 FILETIME user;
1074 FILETIME kernel;
1075 FILETIME dummy;
1076 if (GetProcessTimes(GetCurrentProcess(), &dummy, &dummy,
1077 &kernel,&user)) {
2d7a9237 1078 timebuf->tms_utime = filetime_to_clock(&user);
1079 timebuf->tms_stime = filetime_to_clock(&kernel);
d55594ae 1080 timebuf->tms_cutime = 0;
1081 timebuf->tms_cstime = 0;
1082
1083 } else {
1084 /* That failed - e.g. Win95 fallback to clock() */
1085 clock_t t = clock();
1086 timebuf->tms_utime = t;
1087 timebuf->tms_stime = 0;
1088 timebuf->tms_cutime = 0;
1089 timebuf->tms_cstime = 0;
1090 }
68dc0745 1091 return 0;
0a753a76 1092}
1093
ad0751ec 1094/* fix utime() so it works on directories in NT
1095 * thanks to Jan Dubois <jan.dubois@ibm.net>
1096 */
1097static BOOL
1098filetime_from_time(PFILETIME pFileTime, time_t Time)
1099{
1100 struct tm *pTM = gmtime(&Time);
1101 SYSTEMTIME SystemTime;
1102
1103 if (pTM == NULL)
1104 return FALSE;
1105
1106 SystemTime.wYear = pTM->tm_year + 1900;
1107 SystemTime.wMonth = pTM->tm_mon + 1;
1108 SystemTime.wDay = pTM->tm_mday;
1109 SystemTime.wHour = pTM->tm_hour;
1110 SystemTime.wMinute = pTM->tm_min;
1111 SystemTime.wSecond = pTM->tm_sec;
1112 SystemTime.wMilliseconds = 0;
1113
1114 return SystemTimeToFileTime(&SystemTime, pFileTime);
1115}
1116
1117DllExport int
3b405fc5 1118win32_utime(const char *filename, struct utimbuf *times)
ad0751ec 1119{
1120 HANDLE handle;
1121 FILETIME ftCreate;
1122 FILETIME ftAccess;
1123 FILETIME ftWrite;
1124 struct utimbuf TimeBuffer;
1125
1126 int rc = utime(filename,times);
1127 /* EACCES: path specifies directory or readonly file */
1128 if (rc == 0 || errno != EACCES /* || !IsWinNT() */)
1129 return rc;
1130
1131 if (times == NULL) {
1132 times = &TimeBuffer;
1133 time(&times->actime);
1134 times->modtime = times->actime;
1135 }
1136
1137 /* This will (and should) still fail on readonly files */
1138 handle = CreateFile(filename, GENERIC_READ | GENERIC_WRITE,
1139 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1140 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1141 if (handle == INVALID_HANDLE_VALUE)
1142 return rc;
1143
1144 if (GetFileTime(handle, &ftCreate, &ftAccess, &ftWrite) &&
1145 filetime_from_time(&ftAccess, times->actime) &&
1146 filetime_from_time(&ftWrite, times->modtime) &&
1147 SetFileTime(handle, &ftCreate, &ftAccess, &ftWrite))
1148 {
1149 rc = 0;
1150 }
1151
1152 CloseHandle(handle);
1153 return rc;
1154}
1155
2d7a9237 1156DllExport int
b2af26b1 1157win32_uname(struct utsname *name)
1158{
1159 struct hostent *hep;
1160 STRLEN nodemax = sizeof(name->nodename)-1;
1161 OSVERSIONINFO osver;
1162
1163 memset(&osver, 0, sizeof(OSVERSIONINFO));
1164 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1165 if (GetVersionEx(&osver)) {
1166 /* sysname */
1167 switch (osver.dwPlatformId) {
1168 case VER_PLATFORM_WIN32_WINDOWS:
1169 strcpy(name->sysname, "Windows");
1170 break;
1171 case VER_PLATFORM_WIN32_NT:
1172 strcpy(name->sysname, "Windows NT");
1173 break;
1174 case VER_PLATFORM_WIN32s:
1175 strcpy(name->sysname, "Win32s");
1176 break;
1177 default:
1178 strcpy(name->sysname, "Win32 Unknown");
1179 break;
1180 }
1181
cf6cacac 1182 /* release */
1183 sprintf(name->release, "%d.%d",
b2af26b1 1184 osver.dwMajorVersion, osver.dwMinorVersion);
1185
cf6cacac 1186 /* version */
1187 sprintf(name->version, "Build %d",
b2af26b1 1188 osver.dwPlatformId == VER_PLATFORM_WIN32_NT
1189 ? osver.dwBuildNumber : (osver.dwBuildNumber & 0xffff));
1190 if (osver.szCSDVersion[0]) {
cf6cacac 1191 char *buf = name->version + strlen(name->version);
b2af26b1 1192 sprintf(buf, " (%s)", osver.szCSDVersion);
1193 }
1194 }
1195 else {
1196 *name->sysname = '\0';
1197 *name->version = '\0';
1198 *name->release = '\0';
1199 }
1200
1201 /* nodename */
1202 hep = win32_gethostbyname("localhost");
1203 if (hep) {
1204 STRLEN len = strlen(hep->h_name);
1205 if (len <= nodemax) {
1206 strcpy(name->nodename, hep->h_name);
1207 }
1208 else {
1209 strncpy(name->nodename, hep->h_name, nodemax);
1210 name->nodename[nodemax] = '\0';
1211 }
1212 }
1213 else {
1214 DWORD sz = nodemax;
1215 if (!GetComputerName(name->nodename, &sz))
1216 *name->nodename = '\0';
1217 }
1218
1219 /* machine (architecture) */
1220 {
1221 SYSTEM_INFO info;
1222 char *arch;
1223 GetSystemInfo(&info);
1224 switch (info.wProcessorArchitecture) {
1225 case PROCESSOR_ARCHITECTURE_INTEL:
1226 arch = "x86"; break;
1227 case PROCESSOR_ARCHITECTURE_MIPS:
1228 arch = "mips"; break;
1229 case PROCESSOR_ARCHITECTURE_ALPHA:
1230 arch = "alpha"; break;
1231 case PROCESSOR_ARCHITECTURE_PPC:
1232 arch = "ppc"; break;
1233 default:
1234 arch = "unknown"; break;
1235 }
1236 strcpy(name->machine, arch);
1237 }
1238 return 0;
1239}
1240
1241DllExport int
f55ee38a 1242win32_waitpid(int pid, int *status, int flags)
1243{
0aaad0ff 1244 int retval = -1;
f55ee38a 1245 if (pid == -1)
0aaad0ff 1246 return win32_wait(status);
f55ee38a 1247 else {
0aaad0ff 1248 long child = find_pid(pid);
1249 if (child >= 0) {
1250 HANDLE hProcess = w32_child_handles[child];
1251 DWORD waitcode = WaitForSingleObject(hProcess, INFINITE);
1252 if (waitcode != WAIT_FAILED) {
1253 if (GetExitCodeProcess(hProcess, &waitcode)) {
1254 *status = (int)((waitcode & 0xff) << 8);
1255 retval = (int)w32_child_pids[child];
1256 remove_dead_process(child);
1257 return retval;
1258 }
1259 }
1260 else
1261 errno = ECHILD;
1262 }
1263 else {
1264 retval = cwait(status, pid, WAIT_CHILD);
1265 /* cwait() returns "correctly" on Borland */
8f1e745d 1266#ifndef __BORLANDC__
0aaad0ff 1267 if (status)
1268 *status *= 256;
f55ee38a 1269#endif
0aaad0ff 1270 }
f55ee38a 1271 }
0aaad0ff 1272 return retval >= 0 ? pid : retval;
f55ee38a 1273}
1274
1275DllExport int
2d7a9237 1276win32_wait(int *status)
1277{
2d7a9237 1278 /* XXX this wait emulation only knows about processes
1279 * spawned via win32_spawnvp(P_NOWAIT, ...).
1280 */
1281 int i, retval;
1282 DWORD exitcode, waitcode;
1283
1284 if (!w32_num_children) {
1285 errno = ECHILD;
1286 return -1;
1287 }
1288
1289 /* if a child exists, wait for it to die */
1290 waitcode = WaitForMultipleObjects(w32_num_children,
0aaad0ff 1291 w32_child_handles,
2d7a9237 1292 FALSE,
1293 INFINITE);
1294 if (waitcode != WAIT_FAILED) {
1295 if (waitcode >= WAIT_ABANDONED_0
1296 && waitcode < WAIT_ABANDONED_0 + w32_num_children)
1297 i = waitcode - WAIT_ABANDONED_0;
1298 else
1299 i = waitcode - WAIT_OBJECT_0;
0aaad0ff 1300 if (GetExitCodeProcess(w32_child_handles[i], &exitcode) ) {
2d7a9237 1301 *status = (int)((exitcode & 0xff) << 8);
1302 retval = (int)w32_child_pids[i];
0aaad0ff 1303 remove_dead_process(i);
2d7a9237 1304 return retval;
1305 }
1306 }
1307
1308FAILED:
1309 errno = GetLastError();
1310 return -1;
2d7a9237 1311}
d55594ae 1312
2d7a9237 1313static UINT timerid = 0;
d55594ae 1314
1315static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
1316{
1317 KillTimer(NULL,timerid);
1318 timerid=0;
1319 sighandler(14);
1320}
1321
f3986ebb 1322DllExport unsigned int
1323win32_alarm(unsigned int sec)
0a753a76 1324{
d55594ae 1325 /*
1326 * the 'obvious' implentation is SetTimer() with a callback
1327 * which does whatever receiving SIGALRM would do
1328 * we cannot use SIGALRM even via raise() as it is not
1329 * one of the supported codes in <signal.h>
1330 *
1331 * Snag is unless something is looking at the message queue
1332 * nothing happens :-(
1333 */
1334 if (sec)
1335 {
1336 timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
1337 if (!timerid)
1338 croak("Cannot set timer");
1339 }
1340 else
1341 {
1342 if (timerid)
1343 {
1344 KillTimer(NULL,timerid);
1345 timerid=0;
1346 }
1347 }
68dc0745 1348 return 0;
0a753a76 1349}
1350
ff95b63e 1351#if defined(HAVE_DES_FCRYPT) || defined(PERL_OBJECT)
26618a56 1352#ifdef HAVE_DES_FCRYPT
2d77217b 1353extern char * des_fcrypt(const char *txt, const char *salt, char *cbuf);
ff95b63e 1354#endif
26618a56 1355
1356DllExport char *
1357win32_crypt(const char *txt, const char *salt)
1358{
ff95b63e 1359#ifdef HAVE_DES_FCRYPT
26618a56 1360 dTHR;
2d77217b 1361 return des_fcrypt(txt, salt, crypt_buffer);
ff95b63e 1362#else
1363 die("The crypt() function is unimplemented due to excessive paranoia.");
b8957cf1 1364 return Nullch;
ff95b63e 1365#endif
26618a56 1366}
1367#endif
1368
f3986ebb 1369#ifdef USE_FIXED_OSFHANDLE
390b85e7 1370
1371EXTERN_C int __cdecl _alloc_osfhnd(void);
1372EXTERN_C int __cdecl _set_osfhnd(int fh, long value);
1373EXTERN_C void __cdecl _lock_fhandle(int);
1374EXTERN_C void __cdecl _unlock_fhandle(int);
1375EXTERN_C void __cdecl _unlock(int);
1376
1377#if (_MSC_VER >= 1000)
1378typedef struct {
1379 long osfhnd; /* underlying OS file HANDLE */
1380 char osfile; /* attributes of file (e.g., open in text mode?) */
1381 char pipech; /* one char buffer for handles opened on pipes */
1382#if defined (_MT) && !defined (DLL_FOR_WIN32S)
1383 int lockinitflag;
1384 CRITICAL_SECTION lock;
1385#endif /* defined (_MT) && !defined (DLL_FOR_WIN32S) */
1386} ioinfo;
1387
1388EXTERN_C ioinfo * __pioinfo[];
1389
1390#define IOINFO_L2E 5
1391#define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
1392#define _pioinfo(i) (__pioinfo[i >> IOINFO_L2E] + (i & (IOINFO_ARRAY_ELTS - 1)))
1393#define _osfile(i) (_pioinfo(i)->osfile)
1394
1395#else /* (_MSC_VER >= 1000) */
1396extern char _osfile[];
1397#endif /* (_MSC_VER >= 1000) */
1398
1399#define FOPEN 0x01 /* file handle open */
1400#define FAPPEND 0x20 /* file handle opened O_APPEND */
1401#define FDEV 0x40 /* file handle refers to device */
1402#define FTEXT 0x80 /* file handle is in text mode */
1403
1404#define _STREAM_LOCKS 26 /* Table of stream locks */
1405#define _LAST_STREAM_LOCK (_STREAM_LOCKS+_NSTREAM_-1) /* Last stream lock */
1406#define _FH_LOCKS (_LAST_STREAM_LOCK+1) /* Table of fh locks */
1407
1408/***
1409*int my_open_osfhandle(long osfhandle, int flags) - open C Runtime file handle
1410*
1411*Purpose:
1412* This function allocates a free C Runtime file handle and associates
1413* it with the Win32 HANDLE specified by the first parameter. This is a
1414* temperary fix for WIN95's brain damage GetFileType() error on socket
1415* we just bypass that call for socket
1416*
1417*Entry:
1418* long osfhandle - Win32 HANDLE to associate with C Runtime file handle.
1419* int flags - flags to associate with C Runtime file handle.
1420*
1421*Exit:
1422* returns index of entry in fh, if successful
1423* return -1, if no free entry is found
1424*
1425*Exceptions:
1426*
1427*******************************************************************************/
1428
1429static int
1430my_open_osfhandle(long osfhandle, int flags)
1431{
1432 int fh;
1433 char fileflags; /* _osfile flags */
1434
1435 /* copy relevant flags from second parameter */
1436 fileflags = FDEV;
1437
9404a519 1438 if (flags & O_APPEND)
390b85e7 1439 fileflags |= FAPPEND;
1440
9404a519 1441 if (flags & O_TEXT)
390b85e7 1442 fileflags |= FTEXT;
1443
1444 /* attempt to allocate a C Runtime file handle */
9404a519 1445 if ((fh = _alloc_osfhnd()) == -1) {
390b85e7 1446 errno = EMFILE; /* too many open files */
1447 _doserrno = 0L; /* not an OS error */
1448 return -1; /* return error to caller */
1449 }
1450
1451 /* the file is open. now, set the info in _osfhnd array */
1452 _set_osfhnd(fh, osfhandle);
1453
1454 fileflags |= FOPEN; /* mark as open */
1455
1456#if (_MSC_VER >= 1000)
1457 _osfile(fh) = fileflags; /* set osfile entry */
1458 _unlock_fhandle(fh);
1459#else
1460 _osfile[fh] = fileflags; /* set osfile entry */
1461 _unlock(fh+_FH_LOCKS); /* unlock handle */
1462#endif
1463
1464 return fh; /* return handle */
1465}
1466
1467#define _open_osfhandle my_open_osfhandle
f3986ebb 1468#endif /* USE_FIXED_OSFHANDLE */
390b85e7 1469
1470/* simulate flock by locking a range on the file */
1471
1472#define LK_ERR(f,i) ((f) ? (i = 0) : (errno = GetLastError()))
1473#define LK_LEN 0xffff0000
1474
f3986ebb 1475DllExport int
1476win32_flock(int fd, int oper)
390b85e7 1477{
1478 OVERLAPPED o;
1479 int i = -1;
1480 HANDLE fh;
1481
f3986ebb 1482 if (!IsWinNT()) {
1483 croak("flock() unimplemented on this platform");
1484 return -1;
1485 }
390b85e7 1486 fh = (HANDLE)_get_osfhandle(fd);
1487 memset(&o, 0, sizeof(o));
1488
1489 switch(oper) {
1490 case LOCK_SH: /* shared lock */
1491 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
1492 break;
1493 case LOCK_EX: /* exclusive lock */
1494 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
1495 break;
1496 case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
1497 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
1498 break;
1499 case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
1500 LK_ERR(LockFileEx(fh,
1501 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
1502 0, LK_LEN, 0, &o),i);
1503 break;
1504 case LOCK_UN: /* unlock lock */
1505 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, 0, &o),i);
1506 break;
1507 default: /* unknown */
1508 errno = EINVAL;
1509 break;
1510 }
1511 return i;
1512}
1513
1514#undef LK_ERR
1515#undef LK_LEN
1516
68dc0745 1517/*
1518 * redirected io subsystem for all XS modules
1519 *
1520 */
0a753a76 1521
68dc0745 1522DllExport int *
1523win32_errno(void)
0a753a76 1524{
390b85e7 1525 return (&errno);
0a753a76 1526}
1527
dcb2879a 1528DllExport char ***
1529win32_environ(void)
1530{
390b85e7 1531 return (&(_environ));
dcb2879a 1532}
1533
68dc0745 1534/* the rest are the remapped stdio routines */
1535DllExport FILE *
1536win32_stderr(void)
0a753a76 1537{
390b85e7 1538 return (stderr);
0a753a76 1539}
1540
68dc0745 1541DllExport FILE *
1542win32_stdin(void)
0a753a76 1543{
390b85e7 1544 return (stdin);
0a753a76 1545}
1546
68dc0745 1547DllExport FILE *
1548win32_stdout()
0a753a76 1549{
390b85e7 1550 return (stdout);
0a753a76 1551}
1552
68dc0745 1553DllExport int
1554win32_ferror(FILE *fp)
0a753a76 1555{
390b85e7 1556 return (ferror(fp));
0a753a76 1557}
1558
1559
68dc0745 1560DllExport int
1561win32_feof(FILE *fp)
0a753a76 1562{
390b85e7 1563 return (feof(fp));
0a753a76 1564}
1565
68dc0745 1566/*
1567 * Since the errors returned by the socket error function
1568 * WSAGetLastError() are not known by the library routine strerror
1569 * we have to roll our own.
1570 */
0a753a76 1571
68dc0745 1572DllExport char *
1573win32_strerror(int e)
0a753a76 1574{
3e3baf6d 1575#ifndef __BORLANDC__ /* Borland intolerance */
68dc0745 1576 extern int sys_nerr;
3e3baf6d 1577#endif
68dc0745 1578 DWORD source = 0;
0a753a76 1579
9404a519 1580 if (e < 0 || e > sys_nerr) {
c53bd28a 1581 dTHR;
9404a519 1582 if (e < 0)
68dc0745 1583 e = GetLastError();
0a753a76 1584
9404a519 1585 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
68dc0745 1586 strerror_buffer, sizeof(strerror_buffer), NULL) == 0)
1587 strcpy(strerror_buffer, "Unknown Error");
0a753a76 1588
68dc0745 1589 return strerror_buffer;
1590 }
390b85e7 1591 return strerror(e);
0a753a76 1592}
1593
22fae026 1594DllExport void
3730b96e 1595win32_str_os_error(void *sv, DWORD dwErr)
22fae026 1596{
1597 DWORD dwLen;
1598 char *sMsg;
1599 dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
1600 |FORMAT_MESSAGE_IGNORE_INSERTS
1601 |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
1602 dwErr, 0, (char *)&sMsg, 1, NULL);
1603 if (0 < dwLen) {
1604 while (0 < dwLen && isspace(sMsg[--dwLen]))
1605 ;
1606 if ('.' != sMsg[dwLen])
1607 dwLen++;
1608 sMsg[dwLen]= '\0';
1609 }
1610 if (0 == dwLen) {
c69f6586 1611 sMsg = (char*)LocalAlloc(0, 64/**sizeof(TCHAR)*/);
22fae026 1612 dwLen = sprintf(sMsg,
1613 "Unknown error #0x%lX (lookup 0x%lX)",
1614 dwErr, GetLastError());
1615 }
3730b96e 1616 sv_setpvn((SV*)sv, sMsg, dwLen);
22fae026 1617 LocalFree(sMsg);
1618}
1619
1620
68dc0745 1621DllExport int
1622win32_fprintf(FILE *fp, const char *format, ...)
0a753a76 1623{
68dc0745 1624 va_list marker;
1625 va_start(marker, format); /* Initialize variable arguments. */
0a753a76 1626
390b85e7 1627 return (vfprintf(fp, format, marker));
0a753a76 1628}
1629
68dc0745 1630DllExport int
1631win32_printf(const char *format, ...)
0a753a76 1632{
68dc0745 1633 va_list marker;
1634 va_start(marker, format); /* Initialize variable arguments. */
0a753a76 1635
390b85e7 1636 return (vprintf(format, marker));
0a753a76 1637}
1638
68dc0745 1639DllExport int
1640win32_vfprintf(FILE *fp, const char *format, va_list args)
0a753a76 1641{
390b85e7 1642 return (vfprintf(fp, format, args));
0a753a76 1643}
1644
96e4d5b1 1645DllExport int
1646win32_vprintf(const char *format, va_list args)
1647{
390b85e7 1648 return (vprintf(format, args));
96e4d5b1 1649}
1650
68dc0745 1651DllExport size_t
1652win32_fread(void *buf, size_t size, size_t count, FILE *fp)
0a753a76 1653{
390b85e7 1654 return fread(buf, size, count, fp);
0a753a76 1655}
1656
68dc0745 1657DllExport size_t
1658win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
0a753a76 1659{
390b85e7 1660 return fwrite(buf, size, count, fp);
0a753a76 1661}
1662
68dc0745 1663DllExport FILE *
1664win32_fopen(const char *filename, const char *mode)
0a753a76 1665{
68dc0745 1666 if (stricmp(filename, "/dev/null")==0)
390b85e7 1667 return fopen("NUL", mode);
1668 return fopen(filename, mode);
0a753a76 1669}
1670
f3986ebb 1671#ifndef USE_SOCKETS_AS_HANDLES
1672#undef fdopen
1673#define fdopen my_fdopen
1674#endif
1675
68dc0745 1676DllExport FILE *
1677win32_fdopen( int handle, const char *mode)
0a753a76 1678{
390b85e7 1679 return fdopen(handle, (char *) mode);
0a753a76 1680}
1681
68dc0745 1682DllExport FILE *
1683win32_freopen( const char *path, const char *mode, FILE *stream)
0a753a76 1684{
68dc0745 1685 if (stricmp(path, "/dev/null")==0)
390b85e7 1686 return freopen("NUL", mode, stream);
1687 return freopen(path, mode, stream);
0a753a76 1688}
1689
68dc0745 1690DllExport int
1691win32_fclose(FILE *pf)
0a753a76 1692{
f3986ebb 1693 return my_fclose(pf); /* defined in win32sck.c */
0a753a76 1694}
1695
68dc0745 1696DllExport int
1697win32_fputs(const char *s,FILE *pf)
0a753a76 1698{
390b85e7 1699 return fputs(s, pf);
0a753a76 1700}
1701
68dc0745 1702DllExport int
1703win32_fputc(int c,FILE *pf)
0a753a76 1704{
390b85e7 1705 return fputc(c,pf);
0a753a76 1706}
1707
68dc0745 1708DllExport int
1709win32_ungetc(int c,FILE *pf)
0a753a76 1710{
390b85e7 1711 return ungetc(c,pf);
0a753a76 1712}
1713
68dc0745 1714DllExport int
1715win32_getc(FILE *pf)
0a753a76 1716{
390b85e7 1717 return getc(pf);
0a753a76 1718}
1719
68dc0745 1720DllExport int
1721win32_fileno(FILE *pf)
0a753a76 1722{
390b85e7 1723 return fileno(pf);
0a753a76 1724}
1725
68dc0745 1726DllExport void
1727win32_clearerr(FILE *pf)
0a753a76 1728{
390b85e7 1729 clearerr(pf);
68dc0745 1730 return;
0a753a76 1731}
1732
68dc0745 1733DllExport int
1734win32_fflush(FILE *pf)
0a753a76 1735{
390b85e7 1736 return fflush(pf);
0a753a76 1737}
1738
68dc0745 1739DllExport long
1740win32_ftell(FILE *pf)
0a753a76 1741{
390b85e7 1742 return ftell(pf);
0a753a76 1743}
1744
68dc0745 1745DllExport int
1746win32_fseek(FILE *pf,long offset,int origin)
0a753a76 1747{
390b85e7 1748 return fseek(pf, offset, origin);
0a753a76 1749}
1750
68dc0745 1751DllExport int
1752win32_fgetpos(FILE *pf,fpos_t *p)
0a753a76 1753{
390b85e7 1754 return fgetpos(pf, p);
0a753a76 1755}
1756
68dc0745 1757DllExport int
1758win32_fsetpos(FILE *pf,const fpos_t *p)
0a753a76 1759{
390b85e7 1760 return fsetpos(pf, p);
0a753a76 1761}
1762
68dc0745 1763DllExport void
1764win32_rewind(FILE *pf)
0a753a76 1765{
390b85e7 1766 rewind(pf);
68dc0745 1767 return;
0a753a76 1768}
1769
68dc0745 1770DllExport FILE*
1771win32_tmpfile(void)
0a753a76 1772{
390b85e7 1773 return tmpfile();
0a753a76 1774}
1775
68dc0745 1776DllExport void
1777win32_abort(void)
0a753a76 1778{
390b85e7 1779 abort();
68dc0745 1780 return;
0a753a76 1781}
1782
68dc0745 1783DllExport int
22239a37 1784win32_fstat(int fd,struct stat *sbufptr)
0a753a76 1785{
22239a37 1786 return fstat(fd,sbufptr);
0a753a76 1787}
1788
68dc0745 1789DllExport int
1790win32_pipe(int *pfd, unsigned int size, int mode)
0a753a76 1791{
390b85e7 1792 return _pipe(pfd, size, mode);
0a753a76 1793}
1794
50892819 1795/*
1796 * a popen() clone that respects PERL5SHELL
1797 */
1798
68dc0745 1799DllExport FILE*
1800win32_popen(const char *command, const char *mode)
0a753a76 1801{
4b556e6c 1802#ifdef USE_RTL_POPEN
390b85e7 1803 return _popen(command, mode);
50892819 1804#else
1805 int p[2];
1806 int parent, child;
1807 int stdfd, oldfd;
1808 int ourmode;
1809 int childpid;
1810
1811 /* establish which ends read and write */
1812 if (strchr(mode,'w')) {
1813 stdfd = 0; /* stdin */
1814 parent = 1;
1815 child = 0;
1816 }
1817 else if (strchr(mode,'r')) {
1818 stdfd = 1; /* stdout */
1819 parent = 0;
1820 child = 1;
1821 }
1822 else
1823 return NULL;
1824
1825 /* set the correct mode */
1826 if (strchr(mode,'b'))
1827 ourmode = O_BINARY;
1828 else if (strchr(mode,'t'))
1829 ourmode = O_TEXT;
1830 else
1831 ourmode = _fmode & (O_TEXT | O_BINARY);
1832
1833 /* the child doesn't inherit handles */
1834 ourmode |= O_NOINHERIT;
1835
1836 if (win32_pipe( p, 512, ourmode) == -1)
1837 return NULL;
1838
1839 /* save current stdfd */
1840 if ((oldfd = win32_dup(stdfd)) == -1)
1841 goto cleanup;
1842
1843 /* make stdfd go to child end of pipe (implicitly closes stdfd) */
1844 /* stdfd will be inherited by the child */
1845 if (win32_dup2(p[child], stdfd) == -1)
1846 goto cleanup;
1847
1848 /* close the child end in parent */
1849 win32_close(p[child]);
1850
1851 /* start the child */
1852 if ((childpid = do_spawn_nowait((char*)command)) == -1)
1853 goto cleanup;
1854
1855 /* revert stdfd to whatever it was before */
1856 if (win32_dup2(oldfd, stdfd) == -1)
1857 goto cleanup;
1858
1859 /* close saved handle */
1860 win32_close(oldfd);
1861
4b556e6c 1862 sv_setiv(*av_fetch(w32_fdpid, p[parent], TRUE), childpid);
50892819 1863
1864 /* we have an fd, return a file stream */
1865 return (win32_fdopen(p[parent], (char *)mode));
1866
1867cleanup:
1868 /* we don't need to check for errors here */
1869 win32_close(p[0]);
1870 win32_close(p[1]);
1871 if (oldfd != -1) {
1872 win32_dup2(oldfd, stdfd);
1873 win32_close(oldfd);
1874 }
1875 return (NULL);
1876
4b556e6c 1877#endif /* USE_RTL_POPEN */
0a753a76 1878}
1879
50892819 1880/*
1881 * pclose() clone
1882 */
1883
68dc0745 1884DllExport int
1885win32_pclose(FILE *pf)
0a753a76 1886{
4b556e6c 1887#ifdef USE_RTL_POPEN
390b85e7 1888 return _pclose(pf);
50892819 1889#else
50892819 1890
e17cb2a9 1891 int childpid, status;
1892 SV *sv;
1893
4b556e6c 1894 sv = *av_fetch(w32_fdpid, win32_fileno(pf), TRUE);
e17cb2a9 1895 if (SvIOK(sv))
1896 childpid = SvIVX(sv);
1897 else
1898 childpid = 0;
50892819 1899
1900 if (!childpid) {
1901 errno = EBADF;
1902 return -1;
1903 }
1904
1905 win32_fclose(pf);
e17cb2a9 1906 SvIVX(sv) = 0;
1907
0aaad0ff 1908 if (win32_waitpid(childpid, &status, 0) == -1)
1909 return -1;
50892819 1910
0aaad0ff 1911 return status;
50892819 1912
4b556e6c 1913#endif /* USE_RTL_POPEN */
0a753a76 1914}
1915
68dc0745 1916DllExport int
8d9b2e3c 1917win32_rename(const char *oname, const char *newname)
e24c7c18 1918{
80252599 1919 /* XXX despite what the documentation says about MoveFileEx(),
1920 * it doesn't work under Windows95!
1921 */
1922 if (IsWinNT()) {
1923 if (!MoveFileEx(oname,newname,
1924 MOVEFILE_COPY_ALLOWED|MOVEFILE_REPLACE_EXISTING)) {
1925 DWORD err = GetLastError();
1926 switch (err) {
1927 case ERROR_BAD_NET_NAME:
1928 case ERROR_BAD_NETPATH:
1929 case ERROR_BAD_PATHNAME:
1930 case ERROR_FILE_NOT_FOUND:
1931 case ERROR_FILENAME_EXCED_RANGE:
1932 case ERROR_INVALID_DRIVE:
1933 case ERROR_NO_MORE_FILES:
1934 case ERROR_PATH_NOT_FOUND:
1935 errno = ENOENT;
1936 break;
1937 default:
1938 errno = EACCES;
1939 break;
1940 }
1941 return -1;
1942 }
1943 return 0;
e24c7c18 1944 }
80252599 1945 else {
1946 int retval = 0;
1947 char tmpname[MAX_PATH+1];
1948 char dname[MAX_PATH+1];
1949 char *endname = Nullch;
1950 STRLEN tmplen = 0;
1951 DWORD from_attr, to_attr;
1952
1953 /* if oname doesn't exist, do nothing */
1954 from_attr = GetFileAttributes(oname);
1955 if (from_attr == 0xFFFFFFFF) {
1956 errno = ENOENT;
1957 return -1;
1958 }
1959
1960 /* if newname exists, rename it to a temporary name so that we
1961 * don't delete it in case oname happens to be the same file
1962 * (but perhaps accessed via a different path)
1963 */
1964 to_attr = GetFileAttributes(newname);
1965 if (to_attr != 0xFFFFFFFF) {
1966 /* if newname is a directory, we fail
1967 * XXX could overcome this with yet more convoluted logic */
1968 if (to_attr & FILE_ATTRIBUTE_DIRECTORY) {
1969 errno = EACCES;
1970 return -1;
1971 }
1972 tmplen = strlen(newname);
1973 strcpy(tmpname,newname);
1974 endname = tmpname+tmplen;
1975 for (; endname > tmpname ; --endname) {
1976 if (*endname == '/' || *endname == '\\') {
1977 *endname = '\0';
1978 break;
1979 }
1980 }
1981 if (endname > tmpname)
1982 endname = strcpy(dname,tmpname);
e24c7c18 1983 else
80252599 1984 endname = ".";
1985
1986 /* get a temporary filename in same directory
1987 * XXX is this really the best we can do? */
1988 if (!GetTempFileName((LPCTSTR)endname, "plr", 0, tmpname)) {
1989 errno = ENOENT;
1990 return -1;
1991 }
1992 DeleteFile(tmpname);
1993
1994 retval = rename(newname, tmpname);
1995 if (retval != 0) {
1996 errno = EACCES;
1997 return retval;
e24c7c18 1998 }
1999 }
80252599 2000
2001 /* rename oname to newname */
2002 retval = rename(oname, newname);
2003
2004 /* if we created a temporary file before ... */
2005 if (endname != Nullch) {
2006 /* ...and rename succeeded, delete temporary file/directory */
2007 if (retval == 0)
2008 DeleteFile(tmpname);
2009 /* else restore it to what it was */
2010 else
2011 (void)rename(tmpname, newname);
2012 }
2013 return retval;
e24c7c18 2014 }
e24c7c18 2015}
2016
2017DllExport int
68dc0745 2018win32_setmode(int fd, int mode)
0a753a76 2019{
390b85e7 2020 return setmode(fd, mode);
0a753a76 2021}
2022
96e4d5b1 2023DllExport long
2024win32_lseek(int fd, long offset, int origin)
2025{
390b85e7 2026 return lseek(fd, offset, origin);
96e4d5b1 2027}
2028
2029DllExport long
2030win32_tell(int fd)
2031{
390b85e7 2032 return tell(fd);
96e4d5b1 2033}
2034
68dc0745 2035DllExport int
2036win32_open(const char *path, int flag, ...)
0a753a76 2037{
68dc0745 2038 va_list ap;
2039 int pmode;
0a753a76 2040
2041 va_start(ap, flag);
2042 pmode = va_arg(ap, int);
2043 va_end(ap);
2044
68dc0745 2045 if (stricmp(path, "/dev/null")==0)
390b85e7 2046 return open("NUL", flag, pmode);
2047 return open(path,flag,pmode);
0a753a76 2048}
2049
68dc0745 2050DllExport int
2051win32_close(int fd)
0a753a76 2052{
390b85e7 2053 return close(fd);
0a753a76 2054}
2055
68dc0745 2056DllExport int
96e4d5b1 2057win32_eof(int fd)
2058{
390b85e7 2059 return eof(fd);
96e4d5b1 2060}
2061
2062DllExport int
68dc0745 2063win32_dup(int fd)
0a753a76 2064{
390b85e7 2065 return dup(fd);
0a753a76 2066}
2067
68dc0745 2068DllExport int
2069win32_dup2(int fd1,int fd2)
0a753a76 2070{
390b85e7 2071 return dup2(fd1,fd2);
0a753a76 2072}
2073
68dc0745 2074DllExport int
3e3baf6d 2075win32_read(int fd, void *buf, unsigned int cnt)
0a753a76 2076{
390b85e7 2077 return read(fd, buf, cnt);
0a753a76 2078}
2079
68dc0745 2080DllExport int
3e3baf6d 2081win32_write(int fd, const void *buf, unsigned int cnt)
0a753a76 2082{
390b85e7 2083 return write(fd, buf, cnt);
0a753a76 2084}
2085
68dc0745 2086DllExport int
5aabfad6 2087win32_mkdir(const char *dir, int mode)
2088{
390b85e7 2089 return mkdir(dir); /* just ignore mode */
5aabfad6 2090}
96e4d5b1 2091
5aabfad6 2092DllExport int
2093win32_rmdir(const char *dir)
2094{
390b85e7 2095 return rmdir(dir);
5aabfad6 2096}
96e4d5b1 2097
5aabfad6 2098DllExport int
2099win32_chdir(const char *dir)
2100{
390b85e7 2101 return chdir(dir);
5aabfad6 2102}
96e4d5b1 2103
0aaad0ff 2104static char *
2105create_command_line(const char* command, const char * const *args)
2106{
2107 int index;
2108 char *cmd, *ptr, *arg;
2109 STRLEN len = strlen(command) + 1;
2110
2111 for (index = 0; (ptr = (char*)args[index]) != NULL; ++index)
2112 len += strlen(ptr) + 1;
2113
2114 New(1310, cmd, len, char);
2115 ptr = cmd;
2116 strcpy(ptr, command);
0aaad0ff 2117
2118 for (index = 0; (arg = (char*)args[index]) != NULL; ++index) {
0aaad0ff 2119 ptr += strlen(ptr);
18a945d4 2120 *ptr++ = ' ';
2121 strcpy(ptr, arg);
0aaad0ff 2122 }
2123
2124 return cmd;
2125}
2126
2127static char *
2128qualified_path(const char *cmd)
2129{
2130 char *pathstr;
2131 char *fullcmd, *curfullcmd;
2132 STRLEN cmdlen = 0;
2133 int has_slash = 0;
2134
2135 if (!cmd)
2136 return Nullch;
2137 fullcmd = (char*)cmd;
2138 while (*fullcmd) {
2139 if (*fullcmd == '/' || *fullcmd == '\\')
2140 has_slash++;
2141 fullcmd++;
2142 cmdlen++;
2143 }
2144
2145 /* look in PATH */
2146 pathstr = win32_getenv("PATH");
2147 New(0, fullcmd, MAX_PATH+1, char);
2148 curfullcmd = fullcmd;
2149
2150 while (1) {
2151 DWORD res;
2152
2153 /* start by appending the name to the current prefix */
2154 strcpy(curfullcmd, cmd);
2155 curfullcmd += cmdlen;
2156
2157 /* if it doesn't end with '.', or has no extension, try adding
2158 * a trailing .exe first */
2159 if (cmd[cmdlen-1] != '.'
2160 && (cmdlen < 4 || cmd[cmdlen-4] != '.'))
2161 {
2162 strcpy(curfullcmd, ".exe");
2163 res = GetFileAttributes(fullcmd);
2164 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
2165 return fullcmd;
2166 *curfullcmd = '\0';
2167 }
2168
2169 /* that failed, try the bare name */
2170 res = GetFileAttributes(fullcmd);
2171 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
2172 return fullcmd;
2173
2174 /* quit if no other path exists, or if cmd already has path */
2175 if (!pathstr || !*pathstr || has_slash)
2176 break;
2177
2178 /* skip leading semis */
2179 while (*pathstr == ';')
2180 pathstr++;
2181
2182 /* build a new prefix from scratch */
2183 curfullcmd = fullcmd;
2184 while (*pathstr && *pathstr != ';') {
2185 if (*pathstr == '"') { /* foo;"baz;etc";bar */
2186 pathstr++; /* skip initial '"' */
2187 while (*pathstr && *pathstr != '"') {
2188 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
2189 *curfullcmd++ = *pathstr;
2190 pathstr++;
2191 }
2192 if (*pathstr)
2193 pathstr++; /* skip trailing '"' */
2194 }
2195 else {
2196 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
2197 *curfullcmd++ = *pathstr;
2198 pathstr++;
2199 }
2200 }
2201 if (*pathstr)
2202 pathstr++; /* skip trailing semi */
2203 if (curfullcmd > fullcmd /* append a dir separator */
2204 && curfullcmd[-1] != '/' && curfullcmd[-1] != '\\')
2205 {
2206 *curfullcmd++ = '\\';
2207 }
2208 }
2209GIVE_UP:
2210 Safefree(fullcmd);
2211 return Nullch;
2212}
2213
2214/* XXX this needs to be made more compatible with the spawnvp()
2215 * provided by the various RTLs. In particular, searching for
2216 * *.{com,bat,cmd} files (as done by the RTLs) is unimplemented.
2217 * This doesn't significantly affect perl itself, because we
2218 * always invoke things using PERL5SHELL if a direct attempt to
2219 * spawn the executable fails.
2220 *
2221 * XXX splitting and rejoining the commandline between do_aspawn()
2222 * and win32_spawnvp() could also be avoided.
2223 */
2224
5aabfad6 2225DllExport int
3e3baf6d 2226win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
0a753a76 2227{
0aaad0ff 2228#ifdef USE_RTL_SPAWNVP
2229 return spawnvp(mode, cmdname, (char * const *)argv);
2230#else
2231 DWORD ret;
2232 STARTUPINFO StartupInfo;
2233 PROCESS_INFORMATION ProcessInformation;
2234 DWORD create = 0;
2235
2236 char *cmd = create_command_line(cmdname, strcmp(cmdname, argv[0]) == 0
2237 ? &argv[1] : argv);
2238 char *fullcmd = Nullch;
2239
2240 switch(mode) {
2241 case P_NOWAIT: /* asynch + remember result */
2242 if (w32_num_children >= MAXIMUM_WAIT_OBJECTS) {
2243 errno = EAGAIN;
2244 ret = -1;
2245 goto RETVAL;
2246 }
2247 /* FALL THROUGH */
2248 case P_WAIT: /* synchronous execution */
2249 break;
2250 default: /* invalid mode */
2251 errno = EINVAL;
2252 ret = -1;
2253 goto RETVAL;
2254 }
2255 memset(&StartupInfo,0,sizeof(StartupInfo));
2256 StartupInfo.cb = sizeof(StartupInfo);
2257 StartupInfo.wShowWindow = SW_SHOWDEFAULT;
2258
2259RETRY:
2260 if (!CreateProcess(cmdname, /* search PATH to find executable */
2261 cmd, /* executable, and its arguments */
2262 NULL, /* process attributes */
2263 NULL, /* thread attributes */
2264 TRUE, /* inherit handles */
2265 create, /* creation flags */
2266 NULL, /* inherit environment */
2267 NULL, /* inherit cwd */
2268 &StartupInfo,
2269 &ProcessInformation))
2270 {
2271 /* initial NULL argument to CreateProcess() does a PATH
2272 * search, but it always first looks in the directory
2273 * where the current process was started, which behavior
2274 * is undesirable for backward compatibility. So we
2275 * jump through our own hoops by picking out the path
2276 * we really want it to use. */
2277 if (!fullcmd) {
2278 fullcmd = qualified_path(cmdname);
2279 if (fullcmd) {
2280 cmdname = fullcmd;
2281 goto RETRY;
2282 }
2283 }
2284 errno = ENOENT;
2285 ret = -1;
2286 goto RETVAL;
2287 }
2d7a9237 2288
0aaad0ff 2289 if (mode == P_NOWAIT) {
2290 /* asynchronous spawn -- store handle, return PID */
2291 w32_child_handles[w32_num_children] = ProcessInformation.hProcess;
2292 ret = w32_child_pids[w32_num_children] = ProcessInformation.dwProcessId;
2293 ++w32_num_children;
2294 }
2295 else {
2296 WaitForSingleObject(ProcessInformation.hProcess, INFINITE);
2297 GetExitCodeProcess(ProcessInformation.hProcess, &ret);
2298 CloseHandle(ProcessInformation.hProcess);
2299 }
e17cb2a9 2300
0aaad0ff 2301 CloseHandle(ProcessInformation.hThread);
2302RETVAL:
2303 Safefree(cmd);
2304 Safefree(fullcmd);
2305 return (int)ret;
2d7a9237 2306#endif
0a753a76 2307}
2308
6890e559 2309DllExport int
eb62e965 2310win32_execv(const char *cmdname, const char *const *argv)
2311{
2312 return execv(cmdname, (char *const *)argv);
2313}
2314
2315DllExport int
6890e559 2316win32_execvp(const char *cmdname, const char *const *argv)
2317{
390b85e7 2318 return execvp(cmdname, (char *const *)argv);
6890e559 2319}
2320
84902520 2321DllExport void
2322win32_perror(const char *str)
2323{
390b85e7 2324 perror(str);
84902520 2325}
2326
2327DllExport void
2328win32_setbuf(FILE *pf, char *buf)
2329{
390b85e7 2330 setbuf(pf, buf);
84902520 2331}
2332
2333DllExport int
2334win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
2335{
390b85e7 2336 return setvbuf(pf, buf, type, size);
84902520 2337}
2338
2339DllExport int
2340win32_flushall(void)
2341{
390b85e7 2342 return flushall();
84902520 2343}
2344
2345DllExport int
2346win32_fcloseall(void)
2347{
390b85e7 2348 return fcloseall();
84902520 2349}
2350
2351DllExport char*
2352win32_fgets(char *s, int n, FILE *pf)
2353{
390b85e7 2354 return fgets(s, n, pf);
84902520 2355}
2356
2357DllExport char*
2358win32_gets(char *s)
2359{
390b85e7 2360 return gets(s);
84902520 2361}
2362
2363DllExport int
2364win32_fgetc(FILE *pf)
2365{
390b85e7 2366 return fgetc(pf);
84902520 2367}
2368
2369DllExport int
2370win32_putc(int c, FILE *pf)
2371{
390b85e7 2372 return putc(c,pf);
84902520 2373}
2374
2375DllExport int
2376win32_puts(const char *s)
2377{
390b85e7 2378 return puts(s);
84902520 2379}
2380
2381DllExport int
2382win32_getchar(void)
2383{
390b85e7 2384 return getchar();
84902520 2385}
2386
2387DllExport int
2388win32_putchar(int c)
2389{
390b85e7 2390 return putchar(c);
84902520 2391}
2392
bbc8f9de 2393#ifdef MYMALLOC
2394
2395#ifndef USE_PERL_SBRK
2396
2397static char *committed = NULL;
2398static char *base = NULL;
2399static char *reserved = NULL;
2400static char *brk = NULL;
2401static DWORD pagesize = 0;
2402static DWORD allocsize = 0;
2403
2404void *
2405sbrk(int need)
2406{
2407 void *result;
2408 if (!pagesize)
2409 {SYSTEM_INFO info;
2410 GetSystemInfo(&info);
2411 /* Pretend page size is larger so we don't perpetually
2412 * call the OS to commit just one page ...
2413 */
2414 pagesize = info.dwPageSize << 3;
2415 allocsize = info.dwAllocationGranularity;
2416 }
2417 /* This scheme fails eventually if request for contiguous
2418 * block is denied so reserve big blocks - this is only
2419 * address space not memory ...
2420 */
2421 if (brk+need >= reserved)
2422 {
2423 DWORD size = 64*1024*1024;
2424 char *addr;
2425 if (committed && reserved && committed < reserved)
2426 {
2427 /* Commit last of previous chunk cannot span allocations */
161b471a 2428 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
bbc8f9de 2429 if (addr)
2430 committed = reserved;
2431 }
2432 /* Reserve some (more) space
2433 * Note this is a little sneaky, 1st call passes NULL as reserved
2434 * so lets system choose where we start, subsequent calls pass
2435 * the old end address so ask for a contiguous block
2436 */
161b471a 2437 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
bbc8f9de 2438 if (addr)
2439 {
2440 reserved = addr+size;
2441 if (!base)
2442 base = addr;
2443 if (!committed)
2444 committed = base;
2445 if (!brk)
2446 brk = committed;
2447 }
2448 else
2449 {
2450 return (void *) -1;
2451 }
2452 }
2453 result = brk;
2454 brk += need;
2455 if (brk > committed)
2456 {
2457 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
161b471a 2458 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
bbc8f9de 2459 if (addr)
2460 {
2461 committed += size;
2462 }
2463 else
2464 return (void *) -1;
2465 }
2466 return result;
2467}
2468
2469#endif
2470#endif
2471
84902520 2472DllExport void*
2473win32_malloc(size_t size)
2474{
390b85e7 2475 return malloc(size);
84902520 2476}
2477
2478DllExport void*
2479win32_calloc(size_t numitems, size_t size)
2480{
390b85e7 2481 return calloc(numitems,size);
84902520 2482}
2483
2484DllExport void*
2485win32_realloc(void *block, size_t size)
2486{
390b85e7 2487 return realloc(block,size);
84902520 2488}
2489
2490DllExport void
2491win32_free(void *block)
2492{
390b85e7 2493 free(block);
84902520 2494}
2495
bbc8f9de 2496
68dc0745 2497int
65e48ea9 2498win32_open_osfhandle(long handle, int flags)
0a753a76 2499{
390b85e7 2500 return _open_osfhandle(handle, flags);
0a753a76 2501}
2502
68dc0745 2503long
65e48ea9 2504win32_get_osfhandle(int fd)
0a753a76 2505{
390b85e7 2506 return _get_osfhandle(fd);
0a753a76 2507}
7bac28a0 2508
7bac28a0 2509/*
2510 * Extras.
2511 */
2512
ad2e33dc 2513static
2514XS(w32_GetCwd)
2515{
2516 dXSARGS;
2517 SV *sv = sv_newmortal();
2518 /* Make one call with zero size - return value is required size */
2519 DWORD len = GetCurrentDirectory((DWORD)0,NULL);
2520 SvUPGRADE(sv,SVt_PV);
2521 SvGROW(sv,len);
2522 SvCUR(sv) = GetCurrentDirectory((DWORD) SvLEN(sv), SvPVX(sv));
2523 /*
2524 * If result != 0
2525 * then it worked, set PV valid,
2526 * else leave it 'undef'
2527 */
3467312b 2528 EXTEND(SP,1);
bb897dfc 2529 if (SvCUR(sv)) {
ad2e33dc 2530 SvPOK_on(sv);
bb897dfc 2531 ST(0) = sv;
2532 XSRETURN(1);
2533 }
3467312b 2534 XSRETURN_UNDEF;
ad2e33dc 2535}
2536
2537static
2538XS(w32_SetCwd)
2539{
2540 dXSARGS;
2541 if (items != 1)
2542 croak("usage: Win32::SetCurrentDirectory($cwd)");
bb897dfc 2543 if (SetCurrentDirectory(SvPV_nolen(ST(0))))
ad2e33dc 2544 XSRETURN_YES;
2545
2546 XSRETURN_NO;
2547}
2548
2549static
2550XS(w32_GetNextAvailDrive)
2551{
2552 dXSARGS;
2553 char ix = 'C';
2554 char root[] = "_:\\";
3467312b 2555
2556 EXTEND(SP,1);
ad2e33dc 2557 while (ix <= 'Z') {
2558 root[0] = ix++;
2559 if (GetDriveType(root) == 1) {
2560 root[2] = '\0';
2561 XSRETURN_PV(root);
2562 }
2563 }
3467312b 2564 XSRETURN_UNDEF;
ad2e33dc 2565}
2566
2567static
2568XS(w32_GetLastError)
2569{
2570 dXSARGS;
bb897dfc 2571 EXTEND(SP,1);
ad2e33dc 2572 XSRETURN_IV(GetLastError());
2573}
2574
2575static
ca135624 2576XS(w32_SetLastError)
2577{
2578 dXSARGS;
2579 if (items != 1)
2580 croak("usage: Win32::SetLastError($error)");
2581 SetLastError(SvIV(ST(0)));
bb897dfc 2582 XSRETURN_EMPTY;
ca135624 2583}
2584
2585static
ad2e33dc 2586XS(w32_LoginName)
2587{
2588 dXSARGS;
e34ffe5a 2589 char *name = getlogin_buffer;
2590 DWORD size = sizeof(getlogin_buffer);
3467312b 2591 EXTEND(SP,1);
ad2e33dc 2592 if (GetUserName(name,&size)) {
2593 /* size includes NULL */
79cb57f6 2594 ST(0) = sv_2mortal(newSVpvn(name,size-1));
ad2e33dc 2595 XSRETURN(1);
2596 }
3467312b 2597 XSRETURN_UNDEF;
ad2e33dc 2598}
2599
2600static
2601XS(w32_NodeName)
2602{
2603 dXSARGS;
2604 char name[MAX_COMPUTERNAME_LENGTH+1];
2605 DWORD size = sizeof(name);
3467312b 2606 EXTEND(SP,1);
ad2e33dc 2607 if (GetComputerName(name,&size)) {
2608 /* size does NOT include NULL :-( */
79cb57f6 2609 ST(0) = sv_2mortal(newSVpvn(name,size));
ad2e33dc 2610 XSRETURN(1);
2611 }
3467312b 2612 XSRETURN_UNDEF;
ad2e33dc 2613}
2614
2615
2616static
2617XS(w32_DomainName)
2618{
2619 dXSARGS;
8c9208bc 2620#ifndef HAS_NETWKSTAGETINFO
2621 /* mingw32 (and Win95) don't have NetWksta*(), so do it the old way */
ad2e33dc 2622 char name[256];
2623 DWORD size = sizeof(name);
3467312b 2624 EXTEND(SP,1);
ad2e33dc 2625 if (GetUserName(name,&size)) {
2626 char sid[1024];
2627 DWORD sidlen = sizeof(sid);
2628 char dname[256];
2629 DWORD dnamelen = sizeof(dname);
2630 SID_NAME_USE snu;
db15561c 2631 if (LookupAccountName(NULL, name, (PSID)&sid, &sidlen,
ad2e33dc 2632 dname, &dnamelen, &snu)) {
2633 XSRETURN_PV(dname); /* all that for this */
2634 }
2635 }
e56670dd 2636#else
8c9208bc 2637 /* this way is more reliable, in case user has a local account.
2638 * XXX need dynamic binding of netapi32.dll symbols or this will fail on
2639 * Win95. Probably makes more sense to move it into libwin32. */
9404a519 2640 char dname[256];
2641 DWORD dnamelen = sizeof(dname);
0a2408cf 2642 PWKSTA_INFO_100 pwi;
3467312b 2643 EXTEND(SP,1);
0a2408cf 2644 if (NERR_Success == NetWkstaGetInfo(NULL, 100, (LPBYTE*)&pwi)) {
2645 if (pwi->wki100_langroup && *(pwi->wki100_langroup)) {
2646 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_langroup,
2647 -1, (LPSTR)dname, dnamelen, NULL, NULL);
2648 }
2649 else {
2650 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_computername,
2651 -1, (LPSTR)dname, dnamelen, NULL, NULL);
2652 }
2653 NetApiBufferFree(pwi);
9404a519 2654 XSRETURN_PV(dname);
2655 }
e56670dd 2656#endif
3467312b 2657 XSRETURN_UNDEF;
ad2e33dc 2658}
2659
2660static
2661XS(w32_FsType)
2662{
2663 dXSARGS;
2664 char fsname[256];
2665 DWORD flags, filecomplen;
2666 if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
2667 &flags, fsname, sizeof(fsname))) {
bb897dfc 2668 if (GIMME_V == G_ARRAY) {
79cb57f6 2669 XPUSHs(sv_2mortal(newSVpvn(fsname,strlen(fsname))));
ad2e33dc 2670 XPUSHs(sv_2mortal(newSViv(flags)));
2671 XPUSHs(sv_2mortal(newSViv(filecomplen)));
2672 PUTBACK;
2673 return;
2674 }
bb897dfc 2675 EXTEND(SP,1);
ad2e33dc 2676 XSRETURN_PV(fsname);
2677 }
bb897dfc 2678 XSRETURN_EMPTY;
ad2e33dc 2679}
2680
2681static
2682XS(w32_GetOSVersion)
2683{
2684 dXSARGS;
2685 OSVERSIONINFO osver;
2686
2687 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
2688 if (GetVersionEx(&osver)) {
79cb57f6 2689 XPUSHs(newSVpvn(osver.szCSDVersion, strlen(osver.szCSDVersion)));
ad2e33dc 2690 XPUSHs(newSViv(osver.dwMajorVersion));
2691 XPUSHs(newSViv(osver.dwMinorVersion));
2692 XPUSHs(newSViv(osver.dwBuildNumber));
2693 XPUSHs(newSViv(osver.dwPlatformId));
2694 PUTBACK;
2695 return;
2696 }
bb897dfc 2697 XSRETURN_EMPTY;
ad2e33dc 2698}
2699
2700static
2701XS(w32_IsWinNT)
2702{
2703 dXSARGS;
bb897dfc 2704 EXTEND(SP,1);
ad2e33dc 2705 XSRETURN_IV(IsWinNT());
2706}
2707
2708static
2709XS(w32_IsWin95)
2710{
2711 dXSARGS;
bb897dfc 2712 EXTEND(SP,1);
ad2e33dc 2713 XSRETURN_IV(IsWin95());
2714}
2715
2716static
2717XS(w32_FormatMessage)
2718{
2719 dXSARGS;
2720 DWORD source = 0;
2721 char msgbuf[1024];
2722
2723 if (items != 1)
2724 croak("usage: Win32::FormatMessage($errno)");
2725
2726 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
2727 &source, SvIV(ST(0)), 0,
2728 msgbuf, sizeof(msgbuf)-1, NULL))
2729 XSRETURN_PV(msgbuf);
2730
3467312b 2731 XSRETURN_UNDEF;
ad2e33dc 2732}
2733
2734static
2735XS(w32_Spawn)
2736{
2737 dXSARGS;
2738 char *cmd, *args;
2739 PROCESS_INFORMATION stProcInfo;
2740 STARTUPINFO stStartInfo;
2741 BOOL bSuccess = FALSE;
2742
9404a519 2743 if (items != 3)
ad2e33dc 2744 croak("usage: Win32::Spawn($cmdName, $args, $PID)");
2745
bb897dfc 2746 cmd = SvPV_nolen(ST(0));
2747 args = SvPV_nolen(ST(1));
ad2e33dc 2748
2749 memset(&stStartInfo, 0, sizeof(stStartInfo)); /* Clear the block */
2750 stStartInfo.cb = sizeof(stStartInfo); /* Set the structure size */
2751 stStartInfo.dwFlags = STARTF_USESHOWWINDOW; /* Enable wShowWindow control */
2752 stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE; /* Start min (normal) */
2753
9404a519 2754 if (CreateProcess(
ad2e33dc 2755 cmd, /* Image path */
2756 args, /* Arguments for command line */
2757 NULL, /* Default process security */
2758 NULL, /* Default thread security */
2759 FALSE, /* Must be TRUE to use std handles */
2760 NORMAL_PRIORITY_CLASS, /* No special scheduling */
2761 NULL, /* Inherit our environment block */
2762 NULL, /* Inherit our currrent directory */
2763 &stStartInfo, /* -> Startup info */
2764 &stProcInfo)) /* <- Process info (if OK) */
2765 {
2766 CloseHandle(stProcInfo.hThread);/* library source code does this. */
2767 sv_setiv(ST(2), stProcInfo.dwProcessId);
2768 bSuccess = TRUE;
2769 }
2770 XSRETURN_IV(bSuccess);
2771}
2772
2773static
2774XS(w32_GetTickCount)
2775{
2776 dXSARGS;
bb897dfc 2777 EXTEND(SP,1);
fdb068fa 2778 DWORD msec = GetTickCount();
2779 if ((IV)msec > 0)
2780 XSRETURN_IV(msec);
2781 XSRETURN_NV(msec);
ad2e33dc 2782}
2783
2784static
2785XS(w32_GetShortPathName)
2786{
2787 dXSARGS;
2788 SV *shortpath;
e8bab181 2789 DWORD len;
ad2e33dc 2790
9404a519 2791 if (items != 1)
ad2e33dc 2792 croak("usage: Win32::GetShortPathName($longPathName)");
2793
2794 shortpath = sv_mortalcopy(ST(0));
2795 SvUPGRADE(shortpath, SVt_PV);
2796 /* src == target is allowed */
e8bab181 2797 do {
2798 len = GetShortPathName(SvPVX(shortpath),
2799 SvPVX(shortpath),
2800 SvLEN(shortpath));
2801 } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
2802 if (len) {
2803 SvCUR_set(shortpath,len);
ad2e33dc 2804 ST(0) = shortpath;
bb897dfc 2805 XSRETURN(1);
e8bab181 2806 }
3467312b 2807 XSRETURN_UNDEF;
ad2e33dc 2808}
2809
ad0751ec 2810static
ca135624 2811XS(w32_GetFullPathName)
2812{
2813 dXSARGS;
2814 SV *filename;
2815 SV *fullpath;
2816 char *filepart;
2817 DWORD len;
2818
2819 if (items != 1)
2820 croak("usage: Win32::GetFullPathName($filename)");
2821
2822 filename = ST(0);
2823 fullpath = sv_mortalcopy(filename);
2824 SvUPGRADE(fullpath, SVt_PV);
2825 do {
2826 len = GetFullPathName(SvPVX(filename),
2827 SvLEN(fullpath),
2828 SvPVX(fullpath),
2829 &filepart);
2830 } while (len >= SvLEN(fullpath) && sv_grow(fullpath,len+1));
2831 if (len) {
2832 if (GIMME_V == G_ARRAY) {
2833 EXTEND(SP,1);
bb897dfc 2834 XST_mPV(1,filepart);
ca135624 2835 len = filepart - SvPVX(fullpath);
2836 items = 2;
2837 }
2838 SvCUR_set(fullpath,len);
2839 ST(0) = fullpath;
bb897dfc 2840 XSRETURN(items);
ca135624 2841 }
bb897dfc 2842 XSRETURN_EMPTY;
ca135624 2843}
2844
2845static
ad0751ec 2846XS(w32_Sleep)
2847{
2848 dXSARGS;
2849 if (items != 1)
2850 croak("usage: Win32::Sleep($milliseconds)");
2851 Sleep(SvIV(ST(0)));
2852 XSRETURN_YES;
2853}
2854
ad2e33dc 2855void
f3986ebb 2856Perl_init_os_extras()
ad2e33dc 2857{
2858 char *file = __FILE__;
2859 dXSUB_SYS;
2860
4b556e6c 2861 w32_perlshell_tokens = Nullch;
2862 w32_perlshell_items = -1;
2863 w32_fdpid = newAV(); /* XXX needs to be in Perl_win32_init()? */
0aaad0ff 2864 New(1313, w32_children, 1, child_tab);
4b556e6c 2865 w32_num_children = 0;
4b556e6c 2866
ad2e33dc 2867 /* these names are Activeware compatible */
2868 newXS("Win32::GetCwd", w32_GetCwd, file);
2869 newXS("Win32::SetCwd", w32_SetCwd, file);
2870 newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
2871 newXS("Win32::GetLastError", w32_GetLastError, file);
ca135624 2872 newXS("Win32::SetLastError", w32_SetLastError, file);
ad2e33dc 2873 newXS("Win32::LoginName", w32_LoginName, file);
2874 newXS("Win32::NodeName", w32_NodeName, file);
2875 newXS("Win32::DomainName", w32_DomainName, file);
2876 newXS("Win32::FsType", w32_FsType, file);
2877 newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
2878 newXS("Win32::IsWinNT", w32_IsWinNT, file);
2879 newXS("Win32::IsWin95", w32_IsWin95, file);
2880 newXS("Win32::FormatMessage", w32_FormatMessage, file);
2881 newXS("Win32::Spawn", w32_Spawn, file);
2882 newXS("Win32::GetTickCount", w32_GetTickCount, file);
2883 newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
ca135624 2884 newXS("Win32::GetFullPathName", w32_GetFullPathName, file);
ad0751ec 2885 newXS("Win32::Sleep", w32_Sleep, file);
ad2e33dc 2886
2887 /* XXX Bloat Alert! The following Activeware preloads really
2888 * ought to be part of Win32::Sys::*, so they're not included
2889 * here.
2890 */
2891 /* LookupAccountName
2892 * LookupAccountSID
2893 * InitiateSystemShutdown
2894 * AbortSystemShutdown
2895 * ExpandEnvrironmentStrings
2896 */
2897}
2898
2899void
2900Perl_win32_init(int *argcp, char ***argvp)
2901{
2902 /* Disable floating point errors, Perl will trap the ones we
2903 * care about. VC++ RTL defaults to switching these off
2904 * already, but the Borland RTL doesn't. Since we don't
2905 * want to be at the vendor's whim on the default, we set
2906 * it explicitly here.
2907 */
a835ef8a 2908#if !defined(_ALPHA_) && !defined(__GNUC__)
ad2e33dc 2909 _control87(MCW_EM, MCW_EM);
3dc9191e 2910#endif
4b556e6c 2911 MALLOC_INIT;
ad2e33dc 2912}
d55594ae 2913
a868473f 2914#ifdef USE_BINMODE_SCRIPTS
2915
2916void
2917win32_strip_return(SV *sv)
2918{
2919 char *s = SvPVX(sv);
2920 char *e = s+SvCUR(sv);
2921 char *d = s;
2922 while (s < e)
2923 {
2924 if (*s == '\r' && s[1] == '\n')
2925 {
2926 *d++ = '\n';
2927 s += 2;
2928 }
2929 else
2930 {
2931 *d++ = *s++;
2932 }
2933 }
2934 SvCUR_set(sv,d-SvPVX(sv));
2935}
2936
2937#endif