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