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