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