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