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