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