This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
makedef.pl goof
[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
68dc0745 19/* #include "config.h" */
0a753a76
PP
20
21#define PERLIO_NOT_STDIO 0
22#if !defined(PERLIO_IS_STDIO) && !defined(USE_SFIO)
23#define PerlIO FILE
24#endif
25
7a9ec5a3 26#include <sys/stat.h>
0a753a76
PP
27#include "EXTERN.h"
28#include "perl.h"
c69f6586
GS
29
30#define NO_XSLOCKS
c5be433b 31#define PERL_NO_GET_CONTEXT
ad2e33dc 32#include "XSUB.h"
c69f6586
GS
33
34#include "Win32iop.h"
0a753a76 35#include <fcntl.h>
5b0d9cbe
NIS
36#ifndef __GNUC__
37/* assert.h conflicts with #define of assert in perl.h */
0a753a76 38#include <assert.h>
5b0d9cbe 39#endif
0a753a76
PP
40#include <string.h>
41#include <stdarg.h>
ad2e33dc 42#include <float.h>
ad0751ec 43#include <time.h>
3730b96e 44#if defined(_MSC_VER) || defined(__MINGW32__)
ad0751ec
GS
45#include <sys/utime.h>
46#else
47#include <utime.h>
48#endif
0a753a76 49
5b0d9cbe
NIS
50#ifdef __GNUC__
51/* Mingw32 defaults to globing command line
52 * So we turn it off like this:
53 */
54int _CRT_glob = 0;
55#endif
56
2b260de0
GS
57#if defined(__MINGW32__)
58# define _stat stat
59#endif
60
61#if defined(__BORLANDC__)
0b94c7bb
GS
62# define _stat stat
63# define _utimbuf utimbuf
64#endif
65
6890e559
GS
66#define EXECF_EXEC 1
67#define EXECF_SPAWN 2
68#define EXECF_SPAWN_NOWAIT 3
69
32e30700
GS
70#if defined(PERL_IMPLICIT_SYS)
71# undef win32_get_privlib
72# define win32_get_privlib g_win32_get_privlib
73# undef win32_get_sitelib
74# define win32_get_sitelib g_win32_get_sitelib
75# undef do_spawn
76# define do_spawn g_do_spawn
77# undef getlogin
78# define getlogin g_getlogin
79#endif
80
c69f6586 81#if defined(PERL_OBJECT)
32e30700
GS
82# undef do_aspawn
83# define do_aspawn g_do_aspawn
84# undef Perl_do_exec
85# define Perl_do_exec g_do_exec
c69f6586
GS
86#endif
87
ce1da67e 88static void get_shell(void);
dff6d3cd 89static long tokenize(const char *str, char **dest, char ***destv);
c5be433b 90 int do_spawn2(char *cmd, int exectype);
e200fe59 91static BOOL has_shell_metachars(char *ptr);
2d7a9237 92static long filetime_to_clock(PFILETIME ft);
ad0751ec 93static BOOL filetime_from_time(PFILETIME ft, time_t t);
c5be433b 94static char * get_emd_part(SV **leading, char *trailing, ...);
0aaad0ff
GS
95static void remove_dead_process(long deceased);
96static long find_pid(int pid);
97static char * qualified_path(const char *cmd);
c69f6586 98
2d7a9237 99HANDLE w32_perldll_handle = INVALID_HANDLE_VALUE;
8ac9c18d 100char w32_module_name[MAX_PATH+1];
4b556e6c 101static DWORD w32_platform = (DWORD)-1;
50892819 102
3fe9a6f1 103int
ba106d47
GS
104IsWin95(void)
105{
0cb96387 106 return (win32_os_id() == VER_PLATFORM_WIN32_WINDOWS);
3fe9a6f1
PP
107}
108
109int
ba106d47
GS
110IsWinNT(void)
111{
0cb96387 112 return (win32_os_id() == VER_PLATFORM_WIN32_NT);
3fe9a6f1 113}
0a753a76 114
c5be433b 115/* *svp (if non-NULL) is expected to be POK (valid allocated SvPVX(*svp)) */
51371543 116static char*
c5be433b 117get_regstr_from(HKEY hkey, const char *valuename, SV **svp)
349ad1fe
GS
118{
119 /* Retrieve a REG_SZ or REG_EXPAND_SZ from the registry */
00dc2f4f
GS
120 HKEY handle;
121 DWORD type;
122 const char *subkey = "Software\\Perl";
349ad1fe 123 char *str = Nullch;
00dc2f4f
GS
124 long retval;
125
126 retval = RegOpenKeyEx(hkey, subkey, 0, KEY_READ, &handle);
349ad1fe 127 if (retval == ERROR_SUCCESS) {
51371543
GS
128 DWORD datalen;
129 retval = RegQueryValueEx(handle, valuename, 0, &type, NULL, &datalen);
ba3eb2af 130 if (retval == ERROR_SUCCESS && type == REG_SZ) {
c5be433b
GS
131 dTHXo;
132 if (!*svp)
133 *svp = sv_2mortal(newSVpvn("",0));
134 SvGROW(*svp, datalen);
51371543 135 retval = RegQueryValueEx(handle, valuename, 0, NULL,
c5be433b 136 (PBYTE)SvPVX(*svp), &datalen);
51371543 137 if (retval == ERROR_SUCCESS) {
c5be433b
GS
138 str = SvPVX(*svp);
139 SvCUR_set(*svp,datalen-1);
51371543 140 }
00dc2f4f
GS
141 }
142 RegCloseKey(handle);
143 }
349ad1fe 144 return str;
00dc2f4f
GS
145}
146
c5be433b 147/* *svp (if non-NULL) is expected to be POK (valid allocated SvPVX(*svp)) */
51371543 148static char*
c5be433b 149get_regstr(const char *valuename, SV **svp)
00dc2f4f 150{
c5be433b 151 char *str = get_regstr_from(HKEY_CURRENT_USER, valuename, svp);
349ad1fe 152 if (!str)
c5be433b 153 str = get_regstr_from(HKEY_LOCAL_MACHINE, valuename, svp);
349ad1fe 154 return str;
00dc2f4f
GS
155}
156
c5be433b 157/* *prev_pathp (if non-NULL) is expected to be POK (valid allocated SvPVX(sv)) */
e5a95ffb 158static char *
c5be433b 159get_emd_part(SV **prev_pathp, char *trailing_path, ...)
00dc2f4f 160{
dc9e4912 161 char base[10];
e5a95ffb 162 va_list ap;
e24c7c18 163 char mod_name[MAX_PATH+1];
00dc2f4f 164 char *ptr;
e5a95ffb
GS
165 char *optr;
166 char *strip;
167 int oldsize, newsize;
168
169 va_start(ap, trailing_path);
170 strip = va_arg(ap, char *);
171
cceca5ed
GS
172 sprintf(base, "%5.3f",
173 (double)PERL_REVISION + ((double)PERL_VERSION / (double)1000));
dc9e4912 174
8ac9c18d
GS
175 if (!*w32_module_name) {
176 GetModuleFileName((HMODULE)((w32_perldll_handle == INVALID_HANDLE_VALUE)
177 ? GetModuleHandle(NULL)
178 : w32_perldll_handle),
179 w32_module_name, sizeof(w32_module_name));
180
181 /* try to get full path to binary (which may be mangled when perl is
182 * run from a 16-bit app) */
bf49b057 183 /*PerlIO_printf(Perl_debug_log, "Before %s\n", w32_module_name);*/
8ac9c18d 184 (void)win32_longpath(w32_module_name);
bf49b057 185 /*PerlIO_printf(Perl_debug_log, "After %s\n", w32_module_name);*/
8ac9c18d
GS
186
187 /* normalize to forward slashes */
188 ptr = w32_module_name;
189 while (*ptr) {
190 if (*ptr == '\\')
191 *ptr = '/';
192 ++ptr;
193 }
95140b98 194 }
8ac9c18d 195 strcpy(mod_name, w32_module_name);
95140b98 196 ptr = strrchr(mod_name, '/');
e5a95ffb
GS
197 while (ptr && strip) {
198 /* look for directories to skip back */
199 optr = ptr;
00dc2f4f 200 *ptr = '\0';
95140b98 201 ptr = strrchr(mod_name, '/');
1c39adb2
GS
202 /* avoid stripping component if there is no slash,
203 * or it doesn't match ... */
e5a95ffb 204 if (!ptr || stricmp(ptr+1, strip) != 0) {
1c39adb2
GS
205 /* ... but not if component matches 5.00X* */
206 if (!ptr || !(*strip == '5' && *(ptr+1) == '5'
207 && strncmp(strip, base, 5) == 0
208 && strncmp(ptr+1, base, 5) == 0))
95140b98
GS
209 {
210 *optr = '/';
80252599
GS
211 ptr = optr;
212 }
00dc2f4f 213 }
e5a95ffb 214 strip = va_arg(ap, char *);
00dc2f4f 215 }
e5a95ffb
GS
216 if (!ptr) {
217 ptr = mod_name;
218 *ptr++ = '.';
95140b98 219 *ptr = '/';
00dc2f4f 220 }
e5a95ffb
GS
221 va_end(ap);
222 strcpy(++ptr, trailing_path);
223
dc9e4912 224 /* only add directory if it exists */
349ad1fe 225 if (GetFileAttributes(mod_name) != (DWORD) -1) {
dc9e4912 226 /* directory exists */
c5be433b
GS
227 dTHXo;
228 if (!*prev_pathp)
229 *prev_pathp = sv_2mortal(newSVpvn("",0));
230 sv_catpvn(*prev_pathp, ";", 1);
231 sv_catpv(*prev_pathp, mod_name);
232 return SvPVX(*prev_pathp);
00dc2f4f 233 }
00dc2f4f 234
cf11f4bf 235 return Nullch;
00dc2f4f
GS
236}
237
238char *
c5be433b 239win32_get_privlib(char *pl)
00dc2f4f 240{
c5be433b 241 dTHXo;
e5a95ffb
GS
242 char *stdlib = "lib";
243 char buffer[MAX_PATH+1];
51371543 244 SV *sv = Nullsv;
00dc2f4f 245
e5a95ffb
GS
246 /* $stdlib = $HKCU{"lib-$]"} || $HKLM{"lib-$]"} || $HKCU{"lib"} || $HKLM{"lib"} || ""; */
247 sprintf(buffer, "%s-%s", stdlib, pl);
c5be433b
GS
248 if (!get_regstr(buffer, &sv))
249 (void)get_regstr(stdlib, &sv);
00dc2f4f 250
e5a95ffb 251 /* $stdlib .= ";$EMD/../../lib" */
c5be433b 252 return get_emd_part(&sv, stdlib, ARCHNAME, "bin", Nullch);
00dc2f4f
GS
253}
254
68dc0745 255char *
c5be433b 256win32_get_sitelib(char *pl)
00dc2f4f 257{
c5be433b 258 dTHXo;
e5a95ffb
GS
259 char *sitelib = "sitelib";
260 char regstr[40];
e24c7c18 261 char pathstr[MAX_PATH+1];
e5a95ffb 262 DWORD datalen;
e5a95ffb 263 int len, newsize;
51371543
GS
264 SV *sv1 = Nullsv;
265 SV *sv2 = Nullsv;
00dc2f4f
GS
266
267 /* $HKCU{"sitelib-$]"} || $HKLM{"sitelib-$]"} . ---; */
e5a95ffb 268 sprintf(regstr, "%s-%s", sitelib, pl);
c5be433b 269 (void)get_regstr(regstr, &sv1);
e5a95ffb
GS
270
271 /* $sitelib .=
272 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/site/$]/lib"; */
95140b98 273 sprintf(pathstr, "site/%s/lib", pl);
c5be433b 274 (void)get_emd_part(&sv1, pathstr, ARCHNAME, "bin", pl, Nullch);
51371543 275 if (!sv1 && strlen(pl) == 7) {
cf11f4bf
GS
276 /* pl may have been SUBVERSION-specific; try again without
277 * SUBVERSION */
278 sprintf(pathstr, "site/%.5s/lib", pl);
c5be433b 279 (void)get_emd_part(&sv1, pathstr, ARCHNAME, "bin", pl, Nullch);
cf11f4bf 280 }
00dc2f4f
GS
281
282 /* $HKCU{'sitelib'} || $HKLM{'sitelib'} . ---; */
c5be433b 283 (void)get_regstr(sitelib, &sv2);
00dc2f4f 284
e5a95ffb
GS
285 /* $sitelib .=
286 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/site/lib"; */
c5be433b 287 (void)get_emd_part(&sv2, "site/lib", ARCHNAME, "bin", pl, Nullch);
e5a95ffb 288
51371543
GS
289 if (!sv1 && !sv2)
290 return Nullch;
291 if (!sv1)
292 return SvPVX(sv2);
293 if (!sv2)
294 return SvPVX(sv1);
e5a95ffb 295
349ad1fe
GS
296 sv_catpvn(sv1, ";", 1);
297 sv_catsv(sv1, sv2);
e5a95ffb 298
349ad1fe 299 return SvPVX(sv1);
68dc0745 300}
0a753a76 301
b4793f7f 302
2d7a9237 303static BOOL
e200fe59 304has_shell_metachars(char *ptr)
68dc0745
PP
305{
306 int inquote = 0;
307 char quote = '\0';
308
309 /*
310 * Scan string looking for redirection (< or >) or pipe
e200fe59
JD
311 * characters (|) that are not in a quoted string.
312 * Shell variable interpolation (%VAR%) can also happen inside strings.
68dc0745 313 */
9404a519 314 while (*ptr) {
68dc0745 315 switch(*ptr) {
e200fe59
JD
316 case '%':
317 return TRUE;
68dc0745
PP
318 case '\'':
319 case '\"':
9404a519
GS
320 if (inquote) {
321 if (quote == *ptr) {
68dc0745
PP
322 inquote = 0;
323 quote = '\0';
0a753a76 324 }
68dc0745
PP
325 }
326 else {
327 quote = *ptr;
328 inquote++;
329 }
330 break;
331 case '>':
332 case '<':
333 case '|':
9404a519 334 if (!inquote)
68dc0745
PP
335 return TRUE;
336 default:
337 break;
0a753a76 338 }
68dc0745
PP
339 ++ptr;
340 }
341 return FALSE;
0a753a76
PP
342}
343
32e30700 344#if !defined(PERL_IMPLICIT_SYS)
68dc0745
PP
345/* since the current process environment is being updated in util.c
346 * the library functions will get the correct environment
347 */
348PerlIO *
4f63d024 349Perl_my_popen(pTHX_ char *cmd, char *mode)
0a753a76
PP
350{
351#ifdef FIXCMD
68dc0745
PP
352#define fixcmd(x) { \
353 char *pspace = strchr((x),' '); \
354 if (pspace) { \
355 char *p = (x); \
356 while (p < pspace) { \
357 if (*p == '/') \
358 *p = '\\'; \
359 p++; \
360 } \
361 } \
362 }
0a753a76
PP
363#else
364#define fixcmd(x)
365#endif
68dc0745 366 fixcmd(cmd);
45bc9206 367 PERL_FLUSHALL_FOR_CHILD;
0a753a76 368 return win32_popen(cmd, mode);
0a753a76
PP
369}
370
68dc0745 371long
4f63d024 372Perl_my_pclose(pTHX_ PerlIO *fp)
0a753a76
PP
373{
374 return win32_pclose(fp);
375}
c69f6586 376#endif
0a753a76 377
0cb96387
GS
378DllExport unsigned long
379win32_os_id(void)
0a753a76 380{
8b10511d 381 static OSVERSIONINFO osver;
0a753a76 382
2d7a9237 383 if (osver.dwPlatformId != w32_platform) {
8b10511d
GS
384 memset(&osver, 0, sizeof(OSVERSIONINFO));
385 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
386 GetVersionEx(&osver);
2d7a9237 387 w32_platform = osver.dwPlatformId;
8b10511d 388 }
0cb96387 389 return (unsigned long)w32_platform;
0a753a76
PP
390}
391
ce1da67e
GS
392/* Tokenize a string. Words are null-separated, and the list
393 * ends with a doubled null. Any character (except null and
394 * including backslash) may be escaped by preceding it with a
395 * backslash (the backslash will be stripped).
396 * Returns number of words in result buffer.
397 */
398static long
dff6d3cd 399tokenize(const char *str, char **dest, char ***destv)
ce1da67e
GS
400{
401 char *retstart = Nullch;
402 char **retvstart = 0;
403 int items = -1;
404 if (str) {
c5be433b 405 dTHXo;
ce1da67e
GS
406 int slen = strlen(str);
407 register char *ret;
408 register char **retv;
409 New(1307, ret, slen+2, char);
410 New(1308, retv, (slen+3)/2, char*);
411
412 retstart = ret;
413 retvstart = retv;
414 *retv = ret;
415 items = 0;
416 while (*str) {
417 *ret = *str++;
418 if (*ret == '\\' && *str)
419 *ret = *str++;
420 else if (*ret == ' ') {
421 while (*str == ' ')
422 str++;
423 if (ret == retstart)
424 ret--;
425 else {
426 *ret = '\0';
427 ++items;
428 if (*str)
429 *++retv = ret+1;
430 }
431 }
432 else if (!*str)
433 ++items;
434 ret++;
435 }
436 retvstart[items] = Nullch;
437 *ret++ = '\0';
438 *ret = '\0';
439 }
440 *dest = retstart;
441 *destv = retvstart;
442 return items;
443}
444
445static void
2d7a9237 446get_shell(void)
0a753a76 447{
c5be433b 448 dTHXo;
ce1da67e 449 if (!w32_perlshell_tokens) {
174c211a
GS
450 /* we don't use COMSPEC here for two reasons:
451 * 1. the same reason perl on UNIX doesn't use SHELL--rampant and
452 * uncontrolled unportability of the ensuing scripts.
453 * 2. PERL5SHELL could be set to a shell that may not be fit for
454 * interactive use (which is what most programs look in COMSPEC
455 * for).
456 */
dff6d3cd
GS
457 const char* defaultshell = (IsWinNT()
458 ? "cmd.exe /x/c" : "command.com /c");
459 const char *usershell = getenv("PERL5SHELL");
ce1da67e
GS
460 w32_perlshell_items = tokenize(usershell ? usershell : defaultshell,
461 &w32_perlshell_tokens,
462 &w32_perlshell_vec);
68dc0745 463 }
0a753a76
PP
464}
465
68dc0745 466int
c5be433b 467do_aspawn(void *vreally, void **vmark, void **vsp)
0a753a76 468{
c5be433b 469 dTHXo;
2d7a9237
GS
470 SV *really = (SV*)vreally;
471 SV **mark = (SV**)vmark;
472 SV **sp = (SV**)vsp;
68dc0745 473 char **argv;
2d7a9237 474 char *str;
68dc0745 475 int status;
2d7a9237 476 int flag = P_WAIT;
68dc0745 477 int index = 0;
68dc0745 478
2d7a9237
GS
479 if (sp <= mark)
480 return -1;
68dc0745 481
ce1da67e
GS
482 get_shell();
483 New(1306, argv, (sp - mark) + w32_perlshell_items + 2, char*);
2d7a9237
GS
484
485 if (SvNIOKp(*(mark+1)) && !SvPOKp(*(mark+1))) {
486 ++mark;
487 flag = SvIVx(*mark);
68dc0745
PP
488 }
489
9404a519 490 while (++mark <= sp) {
bb897dfc 491 if (*mark && (str = SvPV_nolen(*mark)))
2d7a9237
GS
492 argv[index++] = str;
493 else
494 argv[index++] = "";
68dc0745
PP
495 }
496 argv[index++] = 0;
497
2d7a9237 498 status = win32_spawnvp(flag,
bb897dfc 499 (const char*)(really ? SvPV_nolen(really) : argv[0]),
2d7a9237
GS
500 (const char* const*)argv);
501
80252599 502 if (status < 0 && (errno == ENOEXEC || errno == ENOENT)) {
2d7a9237 503 /* possible shell-builtin, invoke with shell */
ce1da67e
GS
504 int sh_items;
505 sh_items = w32_perlshell_items;
2d7a9237
GS
506 while (--index >= 0)
507 argv[index+sh_items] = argv[index];
ce1da67e
GS
508 while (--sh_items >= 0)
509 argv[sh_items] = w32_perlshell_vec[sh_items];
2d7a9237
GS
510
511 status = win32_spawnvp(flag,
bb897dfc 512 (const char*)(really ? SvPV_nolen(really) : argv[0]),
2d7a9237
GS
513 (const char* const*)argv);
514 }
68dc0745 515
50892819
GS
516 if (flag != P_NOWAIT) {
517 if (status < 0) {
0453d815
PM
518 dTHR;
519 if (ckWARN(WARN_EXEC))
520 Perl_warner(aTHX_ WARN_EXEC, "Can't spawn \"%s\": %s", argv[0], strerror(errno));
50892819
GS
521 status = 255 * 256;
522 }
523 else
524 status *= 256;
b28d0864 525 PL_statusvalue = status;
5aabfad6 526 }
ce1da67e 527 Safefree(argv);
50892819 528 return (status);
68dc0745
PP
529}
530
c69f6586 531int
c5be433b 532do_spawn2(char *cmd, int exectype)
68dc0745 533{
c5be433b 534 dTHXo;
68dc0745
PP
535 char **a;
536 char *s;
537 char **argv;
538 int status = -1;
539 BOOL needToTry = TRUE;
2d7a9237 540 char *cmd2;
68dc0745 541
2d7a9237
GS
542 /* Save an extra exec if possible. See if there are shell
543 * metacharacters in it */
e200fe59 544 if (!has_shell_metachars(cmd)) {
fc36a67e
PP
545 New(1301,argv, strlen(cmd) / 2 + 2, char*);
546 New(1302,cmd2, strlen(cmd) + 1, char);
68dc0745
PP
547 strcpy(cmd2, cmd);
548 a = argv;
549 for (s = cmd2; *s;) {
de030af3 550 while (*s && isSPACE(*s))
68dc0745
PP
551 s++;
552 if (*s)
553 *(a++) = s;
de030af3 554 while (*s && !isSPACE(*s))
68dc0745 555 s++;
9404a519 556 if (*s)
68dc0745 557 *s++ = '\0';
0a753a76 558 }
68dc0745 559 *a = Nullch;
ce1da67e 560 if (argv[0]) {
6890e559
GS
561 switch (exectype) {
562 case EXECF_SPAWN:
563 status = win32_spawnvp(P_WAIT, argv[0],
564 (const char* const*)argv);
565 break;
566 case EXECF_SPAWN_NOWAIT:
567 status = win32_spawnvp(P_NOWAIT, argv[0],
568 (const char* const*)argv);
569 break;
570 case EXECF_EXEC:
571 status = win32_execvp(argv[0], (const char* const*)argv);
572 break;
573 }
2d7a9237 574 if (status != -1 || errno == 0)
68dc0745 575 needToTry = FALSE;
0a753a76 576 }
0a753a76 577 Safefree(argv);
68dc0745
PP
578 Safefree(cmd2);
579 }
2d7a9237 580 if (needToTry) {
ce1da67e
GS
581 char **argv;
582 int i = -1;
583 get_shell();
584 New(1306, argv, w32_perlshell_items + 2, char*);
585 while (++i < w32_perlshell_items)
586 argv[i] = w32_perlshell_vec[i];
2d7a9237
GS
587 argv[i++] = cmd;
588 argv[i] = Nullch;
6890e559
GS
589 switch (exectype) {
590 case EXECF_SPAWN:
591 status = win32_spawnvp(P_WAIT, argv[0],
592 (const char* const*)argv);
593 break;
594 case EXECF_SPAWN_NOWAIT:
595 status = win32_spawnvp(P_NOWAIT, argv[0],
596 (const char* const*)argv);
597 break;
598 case EXECF_EXEC:
599 status = win32_execvp(argv[0], (const char* const*)argv);
600 break;
601 }
ce1da67e
GS
602 cmd = argv[0];
603 Safefree(argv);
68dc0745 604 }
50892819
GS
605 if (exectype != EXECF_SPAWN_NOWAIT) {
606 if (status < 0) {
0453d815
PM
607 dTHR;
608 if (ckWARN(WARN_EXEC))
609 Perl_warner(aTHX_ WARN_EXEC, "Can't %s \"%s\": %s",
50892819
GS
610 (exectype == EXECF_EXEC ? "exec" : "spawn"),
611 cmd, strerror(errno));
612 status = 255 * 256;
613 }
614 else
615 status *= 256;
b28d0864 616 PL_statusvalue = status;
5aabfad6 617 }
50892819 618 return (status);
0a753a76
PP
619}
620
6890e559 621int
c5be433b 622do_spawn(char *cmd)
6890e559 623{
c5be433b 624 return do_spawn2(cmd, EXECF_SPAWN);
6890e559
GS
625}
626
2d7a9237 627int
c5be433b 628do_spawn_nowait(char *cmd)
2d7a9237 629{
c5be433b 630 return do_spawn2(cmd, EXECF_SPAWN_NOWAIT);
2d7a9237
GS
631}
632
6890e559 633bool
4f63d024 634Perl_do_exec(pTHX_ char *cmd)
6890e559 635{
c5be433b 636 do_spawn2(cmd, EXECF_EXEC);
6890e559
GS
637 return FALSE;
638}
639
68dc0745
PP
640/* The idea here is to read all the directory names into a string table
641 * (separated by nulls) and when one of the other dir functions is called
642 * return the pointer to the current file name.
643 */
c5be433b 644DllExport DIR *
ce2e26e5 645win32_opendir(char *filename)
0a753a76 646{
c5be433b 647 dTHXo;
95136add 648 DIR *dirp;
9404a519
GS
649 long len;
650 long idx;
651 char scanname[MAX_PATH+3];
652 struct stat sbuf;
7fac1903
GS
653 WIN32_FIND_DATAA aFindData;
654 WIN32_FIND_DATAW wFindData;
9404a519 655 HANDLE fh;
7fac1903
GS
656 char buffer[MAX_PATH*2];
657 WCHAR wbuffer[MAX_PATH];
95136add 658 char* ptr;
9404a519
GS
659
660 len = strlen(filename);
661 if (len > MAX_PATH)
662 return NULL;
68dc0745
PP
663
664 /* check to see if filename is a directory */
69d3ab13 665 if (win32_stat(filename, &sbuf) < 0 || !S_ISDIR(sbuf.st_mode))
24caa93f 666 return NULL;
68dc0745 667
68dc0745 668 /* Get us a DIR structure */
95136add 669 Newz(1303, dirp, 1, DIR);
68dc0745
PP
670
671 /* Create the search pattern */
672 strcpy(scanname, filename);
23db2e2d
GS
673
674 /* bare drive name means look in cwd for drive */
675 if (len == 2 && isALPHA(scanname[0]) && scanname[1] == ':') {
676 scanname[len++] = '.';
677 scanname[len++] = '/';
678 }
679 else if (scanname[len-1] != '/' && scanname[len-1] != '\\') {
9404a519 680 scanname[len++] = '/';
23db2e2d 681 }
9404a519
GS
682 scanname[len++] = '*';
683 scanname[len] = '\0';
68dc0745
PP
684
685 /* do the FindFirstFile call */
7fac1903 686 if (USING_WIDE()) {
0cb96387 687 A2WHELPER(scanname, wbuffer, sizeof(wbuffer));
7fac1903
GS
688 fh = FindFirstFileW(wbuffer, &wFindData);
689 }
690 else {
691 fh = FindFirstFileA(scanname, &aFindData);
692 }
95136add 693 dirp->handle = fh;
9404a519 694 if (fh == INVALID_HANDLE_VALUE) {
95136add 695 DWORD err = GetLastError();
21e72512 696 /* FindFirstFile() fails on empty drives! */
95136add
GS
697 switch (err) {
698 case ERROR_FILE_NOT_FOUND:
699 return dirp;
700 case ERROR_NO_MORE_FILES:
701 case ERROR_PATH_NOT_FOUND:
702 errno = ENOENT;
703 break;
704 case ERROR_NOT_ENOUGH_MEMORY:
705 errno = ENOMEM;
706 break;
707 default:
708 errno = EINVAL;
709 break;
710 }
711 Safefree(dirp);
68dc0745
PP
712 return NULL;
713 }
714
715 /* now allocate the first part of the string table for
716 * the filenames that we find.
717 */
7fac1903 718 if (USING_WIDE()) {
0cb96387 719 W2AHELPER(wFindData.cFileName, buffer, sizeof(buffer));
7fac1903
GS
720 ptr = buffer;
721 }
722 else {
723 ptr = aFindData.cFileName;
724 }
725 idx = strlen(ptr)+1;
95136add
GS
726 if (idx < 256)
727 dirp->size = 128;
728 else
729 dirp->size = idx;
730 New(1304, dirp->start, dirp->size, char);
731 strcpy(dirp->start, ptr);
732 dirp->nfiles++;
733 dirp->end = dirp->curr = dirp->start;
734 dirp->end += idx;
735 return dirp;
0a753a76
PP
736}
737
738
68dc0745
PP
739/* Readdir just returns the current string pointer and bumps the
740 * string pointer to the nDllExport entry.
741 */
c5be433b 742DllExport struct direct *
ce2e26e5 743win32_readdir(DIR *dirp)
0a753a76 744{
95136add 745 long len;
0a753a76 746
68dc0745
PP
747 if (dirp->curr) {
748 /* first set up the structure to return */
749 len = strlen(dirp->curr);
0f38926b 750 strcpy(dirp->dirstr.d_name, dirp->curr);
68dc0745 751 dirp->dirstr.d_namlen = len;
0a753a76 752
68dc0745 753 /* Fake an inode */
0f38926b 754 dirp->dirstr.d_ino = dirp->curr - dirp->start;
0a753a76 755
95136add 756 /* Now set up for the next call to readdir */
68dc0745 757 dirp->curr += len + 1;
95136add
GS
758 if (dirp->curr >= dirp->end) {
759 dTHXo;
760 char* ptr;
761 BOOL res;
762 WIN32_FIND_DATAW wFindData;
763 WIN32_FIND_DATAA aFindData;
764 char buffer[MAX_PATH*2];
765
766 /* finding the next file that matches the wildcard
767 * (which should be all of them in this directory!).
95136add
GS
768 */
769 if (USING_WIDE()) {
770 res = FindNextFileW(dirp->handle, &wFindData);
771 if (res) {
772 W2AHELPER(wFindData.cFileName, buffer, sizeof(buffer));
773 ptr = buffer;
774 }
775 }
776 else {
777 res = FindNextFileA(dirp->handle, &aFindData);
778 if (res)
779 ptr = aFindData.cFileName;
780 }
781 if (res) {
0f38926b
GS
782 long endpos = dirp->end - dirp->start;
783 long newsize = endpos + strlen(ptr) + 1;
95136add
GS
784 /* bump the string table size by enough for the
785 * new name and it's null terminator */
0f38926b
GS
786 while (newsize > dirp->size) {
787 long curpos = dirp->curr - dirp->start;
95136add
GS
788 dirp->size *= 2;
789 Renew(dirp->start, dirp->size, char);
0f38926b 790 dirp->curr = dirp->start + curpos;
95136add 791 }
0f38926b
GS
792 strcpy(dirp->start + endpos, ptr);
793 dirp->end = dirp->start + newsize;
95136add
GS
794 dirp->nfiles++;
795 }
796 else
797 dirp->curr = NULL;
68dc0745 798 }
68dc0745
PP
799 return &(dirp->dirstr);
800 }
801 else
802 return NULL;
0a753a76
PP
803}
804
68dc0745 805/* Telldir returns the current string pointer position */
c5be433b 806DllExport long
ce2e26e5 807win32_telldir(DIR *dirp)
0a753a76 808{
95136add 809 return (dirp->curr - dirp->start);
0a753a76
PP
810}
811
812
68dc0745 813/* Seekdir moves the string pointer to a previously saved position
95136add 814 * (returned by telldir).
68dc0745 815 */
c5be433b 816DllExport void
ce2e26e5 817win32_seekdir(DIR *dirp, long loc)
0a753a76 818{
95136add 819 dirp->curr = dirp->start + loc;
0a753a76
PP
820}
821
68dc0745 822/* Rewinddir resets the string pointer to the start */
c5be433b 823DllExport void
ce2e26e5 824win32_rewinddir(DIR *dirp)
0a753a76
PP
825{
826 dirp->curr = dirp->start;
827}
828
68dc0745 829/* free the memory allocated by opendir */
c5be433b 830DllExport int
ce2e26e5 831win32_closedir(DIR *dirp)
0a753a76 832{
c5be433b 833 dTHXo;
95136add 834 if (dirp->handle != INVALID_HANDLE_VALUE)
0f38926b 835 FindClose(dirp->handle);
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;
3352bfcb
GS
896 char *buf = w32_getlogin_buffer;
897 DWORD size = sizeof(w32_getlogin_buffer);
e34ffe5a
GS
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
9c51cf4c 1269/* fix utime() so it works on directories in NT */
ad0751ec
GS
1270static BOOL
1271filetime_from_time(PFILETIME pFileTime, time_t Time)
1272{
9c51cf4c 1273 struct tm *pTM = localtime(&Time);
ad0751ec 1274 SYSTEMTIME SystemTime;
9c51cf4c 1275 FILETIME LocalTime;
ad0751ec
GS
1276
1277 if (pTM == NULL)
1278 return FALSE;
1279
1280 SystemTime.wYear = pTM->tm_year + 1900;
1281 SystemTime.wMonth = pTM->tm_mon + 1;
1282 SystemTime.wDay = pTM->tm_mday;
1283 SystemTime.wHour = pTM->tm_hour;
1284 SystemTime.wMinute = pTM->tm_min;
1285 SystemTime.wSecond = pTM->tm_sec;
1286 SystemTime.wMilliseconds = 0;
1287
9c51cf4c
GS
1288 return SystemTimeToFileTime(&SystemTime, &LocalTime) &&
1289 LocalFileTimeToFileTime(&LocalTime, pFileTime);
ad0751ec
GS
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
26618a56 1551#ifdef HAVE_DES_FCRYPT
2d77217b 1552extern char * des_fcrypt(const char *txt, const char *salt, char *cbuf);
ff95b63e 1553#endif
26618a56
GS
1554
1555DllExport char *
1556win32_crypt(const char *txt, const char *salt)
1557{
0b94c7bb 1558 dTHXo;
ff95b63e 1559#ifdef HAVE_DES_FCRYPT
26618a56 1560 dTHR;
3352bfcb 1561 return des_fcrypt(txt, salt, w32_crypt_buffer);
ff95b63e 1562#else
25dbdbbc 1563 Perl_croak(aTHX_ "The crypt() function is unimplemented due to excessive paranoia.");
b8957cf1 1564 return Nullch;
ff95b63e 1565#endif
26618a56 1566}
26618a56 1567
f3986ebb 1568#ifdef USE_FIXED_OSFHANDLE
390b85e7
GS
1569
1570EXTERN_C int __cdecl _alloc_osfhnd(void);
1571EXTERN_C int __cdecl _set_osfhnd(int fh, long value);
1572EXTERN_C void __cdecl _lock_fhandle(int);
1573EXTERN_C void __cdecl _unlock_fhandle(int);
1574EXTERN_C void __cdecl _unlock(int);
1575
1576#if (_MSC_VER >= 1000)
1577typedef struct {
1578 long osfhnd; /* underlying OS file HANDLE */
1579 char osfile; /* attributes of file (e.g., open in text mode?) */
1580 char pipech; /* one char buffer for handles opened on pipes */
1581#if defined (_MT) && !defined (DLL_FOR_WIN32S)
1582 int lockinitflag;
1583 CRITICAL_SECTION lock;
1584#endif /* defined (_MT) && !defined (DLL_FOR_WIN32S) */
1585} ioinfo;
1586
1587EXTERN_C ioinfo * __pioinfo[];
1588
1589#define IOINFO_L2E 5
1590#define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
1591#define _pioinfo(i) (__pioinfo[i >> IOINFO_L2E] + (i & (IOINFO_ARRAY_ELTS - 1)))
1592#define _osfile(i) (_pioinfo(i)->osfile)
1593
1594#else /* (_MSC_VER >= 1000) */
1595extern char _osfile[];
1596#endif /* (_MSC_VER >= 1000) */
1597
1598#define FOPEN 0x01 /* file handle open */
1599#define FAPPEND 0x20 /* file handle opened O_APPEND */
1600#define FDEV 0x40 /* file handle refers to device */
1601#define FTEXT 0x80 /* file handle is in text mode */
1602
1603#define _STREAM_LOCKS 26 /* Table of stream locks */
1604#define _LAST_STREAM_LOCK (_STREAM_LOCKS+_NSTREAM_-1) /* Last stream lock */
1605#define _FH_LOCKS (_LAST_STREAM_LOCK+1) /* Table of fh locks */
1606
1607/***
1608*int my_open_osfhandle(long osfhandle, int flags) - open C Runtime file handle
1609*
1610*Purpose:
1611* This function allocates a free C Runtime file handle and associates
1612* it with the Win32 HANDLE specified by the first parameter. This is a
1613* temperary fix for WIN95's brain damage GetFileType() error on socket
1614* we just bypass that call for socket
1615*
1616*Entry:
1617* long osfhandle - Win32 HANDLE to associate with C Runtime file handle.
1618* int flags - flags to associate with C Runtime file handle.
1619*
1620*Exit:
1621* returns index of entry in fh, if successful
1622* return -1, if no free entry is found
1623*
1624*Exceptions:
1625*
1626*******************************************************************************/
1627
1628static int
1629my_open_osfhandle(long osfhandle, int flags)
1630{
1631 int fh;
1632 char fileflags; /* _osfile flags */
1633
1634 /* copy relevant flags from second parameter */
1635 fileflags = FDEV;
1636
9404a519 1637 if (flags & O_APPEND)
390b85e7
GS
1638 fileflags |= FAPPEND;
1639
9404a519 1640 if (flags & O_TEXT)
390b85e7
GS
1641 fileflags |= FTEXT;
1642
1643 /* attempt to allocate a C Runtime file handle */
9404a519 1644 if ((fh = _alloc_osfhnd()) == -1) {
390b85e7
GS
1645 errno = EMFILE; /* too many open files */
1646 _doserrno = 0L; /* not an OS error */
1647 return -1; /* return error to caller */
1648 }
1649
1650 /* the file is open. now, set the info in _osfhnd array */
1651 _set_osfhnd(fh, osfhandle);
1652
1653 fileflags |= FOPEN; /* mark as open */
1654
1655#if (_MSC_VER >= 1000)
1656 _osfile(fh) = fileflags; /* set osfile entry */
1657 _unlock_fhandle(fh);
1658#else
1659 _osfile[fh] = fileflags; /* set osfile entry */
1660 _unlock(fh+_FH_LOCKS); /* unlock handle */
1661#endif
1662
1663 return fh; /* return handle */
1664}
1665
1666#define _open_osfhandle my_open_osfhandle
f3986ebb 1667#endif /* USE_FIXED_OSFHANDLE */
390b85e7
GS
1668
1669/* simulate flock by locking a range on the file */
1670
1671#define LK_ERR(f,i) ((f) ? (i = 0) : (errno = GetLastError()))
1672#define LK_LEN 0xffff0000
1673
f3986ebb
GS
1674DllExport int
1675win32_flock(int fd, int oper)
390b85e7
GS
1676{
1677 OVERLAPPED o;
1678 int i = -1;
1679 HANDLE fh;
1680
f3986ebb 1681 if (!IsWinNT()) {
c5be433b 1682 dTHXo;
4f63d024 1683 Perl_croak_nocontext("flock() unimplemented on this platform");
f3986ebb
GS
1684 return -1;
1685 }
390b85e7
GS
1686 fh = (HANDLE)_get_osfhandle(fd);
1687 memset(&o, 0, sizeof(o));
1688
1689 switch(oper) {
1690 case LOCK_SH: /* shared lock */
1691 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
1692 break;
1693 case LOCK_EX: /* exclusive lock */
1694 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
1695 break;
1696 case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
1697 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
1698 break;
1699 case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
1700 LK_ERR(LockFileEx(fh,
1701 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
1702 0, LK_LEN, 0, &o),i);
1703 break;
1704 case LOCK_UN: /* unlock lock */
1705 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, 0, &o),i);
1706 break;
1707 default: /* unknown */
1708 errno = EINVAL;
1709 break;
1710 }
1711 return i;
1712}
1713
1714#undef LK_ERR
1715#undef LK_LEN
1716
68dc0745
PP
1717/*
1718 * redirected io subsystem for all XS modules
1719 *
1720 */
0a753a76 1721
68dc0745
PP
1722DllExport int *
1723win32_errno(void)
0a753a76 1724{
390b85e7 1725 return (&errno);
0a753a76
PP
1726}
1727
dcb2879a
GS
1728DllExport char ***
1729win32_environ(void)
1730{
390b85e7 1731 return (&(_environ));
dcb2879a
GS
1732}
1733
68dc0745
PP
1734/* the rest are the remapped stdio routines */
1735DllExport FILE *
1736win32_stderr(void)
0a753a76 1737{
390b85e7 1738 return (stderr);
0a753a76
PP
1739}
1740
68dc0745
PP
1741DllExport FILE *
1742win32_stdin(void)
0a753a76 1743{
390b85e7 1744 return (stdin);
0a753a76
PP
1745}
1746
68dc0745
PP
1747DllExport FILE *
1748win32_stdout()
0a753a76 1749{
390b85e7 1750 return (stdout);
0a753a76
PP
1751}
1752
68dc0745
PP
1753DllExport int
1754win32_ferror(FILE *fp)
0a753a76 1755{
390b85e7 1756 return (ferror(fp));
0a753a76
PP
1757}
1758
1759
68dc0745
PP
1760DllExport int
1761win32_feof(FILE *fp)
0a753a76 1762{
390b85e7 1763 return (feof(fp));
0a753a76
PP
1764}
1765
68dc0745
PP
1766/*
1767 * Since the errors returned by the socket error function
1768 * WSAGetLastError() are not known by the library routine strerror
1769 * we have to roll our own.
1770 */
0a753a76 1771
68dc0745
PP
1772DllExport char *
1773win32_strerror(int e)
0a753a76 1774{
3e3baf6d 1775#ifndef __BORLANDC__ /* Borland intolerance */
68dc0745 1776 extern int sys_nerr;
3e3baf6d 1777#endif
68dc0745 1778 DWORD source = 0;
0a753a76 1779
9404a519 1780 if (e < 0 || e > sys_nerr) {
c5be433b 1781 dTHXo;
9404a519 1782 if (e < 0)
68dc0745 1783 e = GetLastError();
0a753a76 1784
9404a519 1785 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
3352bfcb
GS
1786 w32_strerror_buffer,
1787 sizeof(w32_strerror_buffer), NULL) == 0)
1788 strcpy(w32_strerror_buffer, "Unknown Error");
0a753a76 1789
3352bfcb 1790 return w32_strerror_buffer;
68dc0745 1791 }
390b85e7 1792 return strerror(e);
0a753a76
PP
1793}
1794
22fae026 1795DllExport void
c5be433b 1796win32_str_os_error(void *sv, DWORD dwErr)
22fae026
TM
1797{
1798 DWORD dwLen;
1799 char *sMsg;
1800 dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
1801 |FORMAT_MESSAGE_IGNORE_INSERTS
1802 |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
1803 dwErr, 0, (char *)&sMsg, 1, NULL);
2ce77adf 1804 /* strip trailing whitespace and period */
22fae026 1805 if (0 < dwLen) {
2ce77adf
GS
1806 do {
1807 --dwLen; /* dwLen doesn't include trailing null */
1808 } while (0 < dwLen && isSPACE(sMsg[dwLen]));
22fae026
TM
1809 if ('.' != sMsg[dwLen])
1810 dwLen++;
2ce77adf 1811 sMsg[dwLen] = '\0';
22fae026
TM
1812 }
1813 if (0 == dwLen) {
c69f6586 1814 sMsg = (char*)LocalAlloc(0, 64/**sizeof(TCHAR)*/);
db7c17d7
GS
1815 if (sMsg)
1816 dwLen = sprintf(sMsg,
1817 "Unknown error #0x%lX (lookup 0x%lX)",
1818 dwErr, GetLastError());
1819 }
1820 if (sMsg) {
c5be433b 1821 dTHXo;
db7c17d7
GS
1822 sv_setpvn((SV*)sv, sMsg, dwLen);
1823 LocalFree(sMsg);
22fae026 1824 }
22fae026
TM
1825}
1826
1827
68dc0745
PP
1828DllExport int
1829win32_fprintf(FILE *fp, const char *format, ...)
0a753a76 1830{
68dc0745
PP
1831 va_list marker;
1832 va_start(marker, format); /* Initialize variable arguments. */
0a753a76 1833
390b85e7 1834 return (vfprintf(fp, format, marker));
0a753a76
PP
1835}
1836
68dc0745
PP
1837DllExport int
1838win32_printf(const char *format, ...)
0a753a76 1839{
68dc0745
PP
1840 va_list marker;
1841 va_start(marker, format); /* Initialize variable arguments. */
0a753a76 1842
390b85e7 1843 return (vprintf(format, marker));
0a753a76
PP
1844}
1845
68dc0745
PP
1846DllExport int
1847win32_vfprintf(FILE *fp, const char *format, va_list args)
0a753a76 1848{
390b85e7 1849 return (vfprintf(fp, format, args));
0a753a76
PP
1850}
1851
96e4d5b1
PP
1852DllExport int
1853win32_vprintf(const char *format, va_list args)
1854{
390b85e7 1855 return (vprintf(format, args));
96e4d5b1
PP
1856}
1857
68dc0745
PP
1858DllExport size_t
1859win32_fread(void *buf, size_t size, size_t count, FILE *fp)
0a753a76 1860{
390b85e7 1861 return fread(buf, size, count, fp);
0a753a76
PP
1862}
1863
68dc0745
PP
1864DllExport size_t
1865win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
0a753a76 1866{
390b85e7 1867 return fwrite(buf, size, count, fp);
0a753a76
PP
1868}
1869
7fac1903
GS
1870#define MODE_SIZE 10
1871
68dc0745
PP
1872DllExport FILE *
1873win32_fopen(const char *filename, const char *mode)
0a753a76 1874{
c5be433b 1875 dTHXo;
7fac1903 1876 WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH];
c5be433b
GS
1877
1878 if (!*filename)
1879 return NULL;
1880
68dc0745 1881 if (stricmp(filename, "/dev/null")==0)
7fac1903
GS
1882 filename = "NUL";
1883
1884 if (USING_WIDE()) {
0cb96387
GS
1885 A2WHELPER(mode, wMode, sizeof(wMode));
1886 A2WHELPER(filename, wBuffer, sizeof(wBuffer));
7fac1903
GS
1887 return _wfopen(wBuffer, wMode);
1888 }
390b85e7 1889 return fopen(filename, mode);
0a753a76
PP
1890}
1891
f3986ebb
GS
1892#ifndef USE_SOCKETS_AS_HANDLES
1893#undef fdopen
1894#define fdopen my_fdopen
1895#endif
1896
68dc0745 1897DllExport FILE *
7fac1903 1898win32_fdopen(int handle, const char *mode)
0a753a76 1899{
c5be433b 1900 dTHXo;
51371543 1901 WCHAR wMode[MODE_SIZE];
7fac1903 1902 if (USING_WIDE()) {
0cb96387 1903 A2WHELPER(mode, wMode, sizeof(wMode));
7fac1903
GS
1904 return _wfdopen(handle, wMode);
1905 }
390b85e7 1906 return fdopen(handle, (char *) mode);
0a753a76
PP
1907}
1908
68dc0745 1909DllExport FILE *
7fac1903 1910win32_freopen(const char *path, const char *mode, FILE *stream)
0a753a76 1911{
c5be433b 1912 dTHXo;
51371543 1913 WCHAR wMode[MODE_SIZE], wBuffer[MAX_PATH];
68dc0745 1914 if (stricmp(path, "/dev/null")==0)
7fac1903
GS
1915 path = "NUL";
1916
1917 if (USING_WIDE()) {
0cb96387
GS
1918 A2WHELPER(mode, wMode, sizeof(wMode));
1919 A2WHELPER(path, wBuffer, sizeof(wBuffer));
7fac1903
GS
1920 return _wfreopen(wBuffer, wMode, stream);
1921 }
390b85e7 1922 return freopen(path, mode, stream);
0a753a76
PP
1923}
1924
68dc0745
PP
1925DllExport int
1926win32_fclose(FILE *pf)
0a753a76 1927{
f3986ebb 1928 return my_fclose(pf); /* defined in win32sck.c */
0a753a76
PP
1929}
1930
68dc0745
PP
1931DllExport int
1932win32_fputs(const char *s,FILE *pf)
0a753a76 1933{
390b85e7 1934 return fputs(s, pf);
0a753a76
PP
1935}
1936
68dc0745
PP
1937DllExport int
1938win32_fputc(int c,FILE *pf)
0a753a76 1939{
390b85e7 1940 return fputc(c,pf);
0a753a76
PP
1941}
1942
68dc0745
PP
1943DllExport int
1944win32_ungetc(int c,FILE *pf)
0a753a76 1945{
390b85e7 1946 return ungetc(c,pf);
0a753a76
PP
1947}
1948
68dc0745
PP
1949DllExport int
1950win32_getc(FILE *pf)
0a753a76 1951{
390b85e7 1952 return getc(pf);
0a753a76
PP
1953}
1954
68dc0745
PP
1955DllExport int
1956win32_fileno(FILE *pf)
0a753a76 1957{
390b85e7 1958 return fileno(pf);
0a753a76
PP
1959}
1960
68dc0745
PP
1961DllExport void
1962win32_clearerr(FILE *pf)
0a753a76 1963{
390b85e7 1964 clearerr(pf);
68dc0745 1965 return;
0a753a76
PP
1966}
1967
68dc0745
PP
1968DllExport int
1969win32_fflush(FILE *pf)
0a753a76 1970{
390b85e7 1971 return fflush(pf);
0a753a76
PP
1972}
1973
68dc0745
PP
1974DllExport long
1975win32_ftell(FILE *pf)
0a753a76 1976{
390b85e7 1977 return ftell(pf);
0a753a76
PP
1978}
1979
68dc0745
PP
1980DllExport int
1981win32_fseek(FILE *pf,long offset,int origin)
0a753a76 1982{
390b85e7 1983 return fseek(pf, offset, origin);
0a753a76
PP
1984}
1985
68dc0745
PP
1986DllExport int
1987win32_fgetpos(FILE *pf,fpos_t *p)
0a753a76 1988{
390b85e7 1989 return fgetpos(pf, p);
0a753a76
PP
1990}
1991
68dc0745
PP
1992DllExport int
1993win32_fsetpos(FILE *pf,const fpos_t *p)
0a753a76 1994{
390b85e7 1995 return fsetpos(pf, p);
0a753a76
PP
1996}
1997
68dc0745
PP
1998DllExport void
1999win32_rewind(FILE *pf)
0a753a76 2000{
390b85e7 2001 rewind(pf);
68dc0745 2002 return;
0a753a76
PP
2003}
2004
68dc0745
PP
2005DllExport FILE*
2006win32_tmpfile(void)
0a753a76 2007{
390b85e7 2008 return tmpfile();
0a753a76
PP
2009}
2010
68dc0745
PP
2011DllExport void
2012win32_abort(void)
0a753a76 2013{
390b85e7 2014 abort();
68dc0745 2015 return;
0a753a76
PP
2016}
2017
68dc0745 2018DllExport int
22239a37 2019win32_fstat(int fd,struct stat *sbufptr)
0a753a76 2020{
22239a37 2021 return fstat(fd,sbufptr);
0a753a76
PP
2022}
2023
68dc0745
PP
2024DllExport int
2025win32_pipe(int *pfd, unsigned int size, int mode)
0a753a76 2026{
390b85e7 2027 return _pipe(pfd, size, mode);
0a753a76
PP
2028}
2029
50892819
GS
2030/*
2031 * a popen() clone that respects PERL5SHELL
2032 */
2033
68dc0745
PP
2034DllExport FILE*
2035win32_popen(const char *command, const char *mode)
0a753a76 2036{
4b556e6c 2037#ifdef USE_RTL_POPEN
390b85e7 2038 return _popen(command, mode);
50892819
GS
2039#else
2040 int p[2];
2041 int parent, child;
2042 int stdfd, oldfd;
2043 int ourmode;
2044 int childpid;
2045
2046 /* establish which ends read and write */
2047 if (strchr(mode,'w')) {
2048 stdfd = 0; /* stdin */
2049 parent = 1;
2050 child = 0;
2051 }
2052 else if (strchr(mode,'r')) {
2053 stdfd = 1; /* stdout */
2054 parent = 0;
2055 child = 1;
2056 }
2057 else
2058 return NULL;
2059
2060 /* set the correct mode */
2061 if (strchr(mode,'b'))
2062 ourmode = O_BINARY;
2063 else if (strchr(mode,'t'))
2064 ourmode = O_TEXT;
2065 else
2066 ourmode = _fmode & (O_TEXT | O_BINARY);
2067
2068 /* the child doesn't inherit handles */
2069 ourmode |= O_NOINHERIT;
2070
2071 if (win32_pipe( p, 512, ourmode) == -1)
2072 return NULL;
2073
2074 /* save current stdfd */
2075 if ((oldfd = win32_dup(stdfd)) == -1)
2076 goto cleanup;
2077
2078 /* make stdfd go to child end of pipe (implicitly closes stdfd) */
2079 /* stdfd will be inherited by the child */
2080 if (win32_dup2(p[child], stdfd) == -1)
2081 goto cleanup;
2082
2083 /* close the child end in parent */
2084 win32_close(p[child]);
2085
2086 /* start the child */
4f63d024 2087 {
c5be433b
GS
2088 dTHXo;
2089 if ((childpid = do_spawn_nowait((char*)command)) == -1)
4f63d024 2090 goto cleanup;
50892819 2091
4f63d024
GS
2092 /* revert stdfd to whatever it was before */
2093 if (win32_dup2(oldfd, stdfd) == -1)
2094 goto cleanup;
50892819 2095
4f63d024
GS
2096 /* close saved handle */
2097 win32_close(oldfd);
50892819 2098
4f63d024 2099 sv_setiv(*av_fetch(w32_fdpid, p[parent], TRUE), childpid);
d91d68c1
R
2100
2101 /* set process id so that it can be returned by perl's open() */
2102 PL_forkprocess = childpid;
4f63d024 2103 }
50892819
GS
2104
2105 /* we have an fd, return a file stream */
2106 return (win32_fdopen(p[parent], (char *)mode));
2107
2108cleanup:
2109 /* we don't need to check for errors here */
2110 win32_close(p[0]);
2111 win32_close(p[1]);
2112 if (oldfd != -1) {
2113 win32_dup2(oldfd, stdfd);
2114 win32_close(oldfd);
2115 }
2116 return (NULL);
2117
4b556e6c 2118#endif /* USE_RTL_POPEN */
0a753a76
PP
2119}
2120
50892819
GS
2121/*
2122 * pclose() clone
2123 */
2124
68dc0745
PP
2125DllExport int
2126win32_pclose(FILE *pf)
0a753a76 2127{
4b556e6c 2128#ifdef USE_RTL_POPEN
390b85e7 2129 return _pclose(pf);
50892819 2130#else
c5be433b 2131 dTHXo;
e17cb2a9
JD
2132 int childpid, status;
2133 SV *sv;
2134
4b556e6c 2135 sv = *av_fetch(w32_fdpid, win32_fileno(pf), TRUE);
e17cb2a9
JD
2136 if (SvIOK(sv))
2137 childpid = SvIVX(sv);
2138 else
2139 childpid = 0;
50892819
GS
2140
2141 if (!childpid) {
2142 errno = EBADF;
2143 return -1;
2144 }
2145
2146 win32_fclose(pf);
e17cb2a9
JD
2147 SvIVX(sv) = 0;
2148
0aaad0ff
GS
2149 if (win32_waitpid(childpid, &status, 0) == -1)
2150 return -1;
50892819 2151
0aaad0ff 2152 return status;
50892819 2153
4b556e6c 2154#endif /* USE_RTL_POPEN */
0a753a76
PP
2155}
2156
68dc0745 2157DllExport int
8d9b2e3c 2158win32_rename(const char *oname, const char *newname)
e24c7c18 2159{
7fac1903
GS
2160 WCHAR wOldName[MAX_PATH];
2161 WCHAR wNewName[MAX_PATH];
2162 BOOL bResult;
80252599
GS
2163 /* XXX despite what the documentation says about MoveFileEx(),
2164 * it doesn't work under Windows95!
2165 */
2166 if (IsWinNT()) {
c5be433b 2167 dTHXo;
7fac1903 2168 if (USING_WIDE()) {
0cb96387
GS
2169 A2WHELPER(oname, wOldName, sizeof(wOldName));
2170 A2WHELPER(newname, wNewName, sizeof(wNewName));
7fac1903
GS
2171 bResult = MoveFileExW(wOldName,wNewName,
2172 MOVEFILE_COPY_ALLOWED|MOVEFILE_REPLACE_EXISTING);
2173 }
2174 else {
2175 bResult = MoveFileExA(oname,newname,
2176 MOVEFILE_COPY_ALLOWED|MOVEFILE_REPLACE_EXISTING);
2177 }
2178 if (!bResult) {
80252599
GS
2179 DWORD err = GetLastError();
2180 switch (err) {
2181 case ERROR_BAD_NET_NAME:
2182 case ERROR_BAD_NETPATH:
2183 case ERROR_BAD_PATHNAME:
2184 case ERROR_FILE_NOT_FOUND:
2185 case ERROR_FILENAME_EXCED_RANGE:
2186 case ERROR_INVALID_DRIVE:
2187 case ERROR_NO_MORE_FILES:
2188 case ERROR_PATH_NOT_FOUND:
2189 errno = ENOENT;
2190 break;
2191 default:
2192 errno = EACCES;
2193 break;
2194 }
2195 return -1;
2196 }
2197 return 0;
e24c7c18 2198 }
80252599
GS
2199 else {
2200 int retval = 0;
2201 char tmpname[MAX_PATH+1];
2202 char dname[MAX_PATH+1];
2203 char *endname = Nullch;
2204 STRLEN tmplen = 0;
2205 DWORD from_attr, to_attr;
2206
2207 /* if oname doesn't exist, do nothing */
2208 from_attr = GetFileAttributes(oname);
2209 if (from_attr == 0xFFFFFFFF) {
2210 errno = ENOENT;
2211 return -1;
2212 }
2213
2214 /* if newname exists, rename it to a temporary name so that we
2215 * don't delete it in case oname happens to be the same file
2216 * (but perhaps accessed via a different path)
2217 */
2218 to_attr = GetFileAttributes(newname);
2219 if (to_attr != 0xFFFFFFFF) {
2220 /* if newname is a directory, we fail
2221 * XXX could overcome this with yet more convoluted logic */
2222 if (to_attr & FILE_ATTRIBUTE_DIRECTORY) {
2223 errno = EACCES;
2224 return -1;
2225 }
2226 tmplen = strlen(newname);
2227 strcpy(tmpname,newname);
2228 endname = tmpname+tmplen;
2229 for (; endname > tmpname ; --endname) {
2230 if (*endname == '/' || *endname == '\\') {
2231 *endname = '\0';
2232 break;
2233 }
2234 }
2235 if (endname > tmpname)
2236 endname = strcpy(dname,tmpname);
e24c7c18 2237 else
80252599
GS
2238 endname = ".";
2239
2240 /* get a temporary filename in same directory
2241 * XXX is this really the best we can do? */
2242 if (!GetTempFileName((LPCTSTR)endname, "plr", 0, tmpname)) {
2243 errno = ENOENT;
2244 return -1;
2245 }
2246 DeleteFile(tmpname);
2247
2248 retval = rename(newname, tmpname);
2249 if (retval != 0) {
2250 errno = EACCES;
2251 return retval;
e24c7c18
GS
2252 }
2253 }
80252599
GS
2254
2255 /* rename oname to newname */
2256 retval = rename(oname, newname);
2257
2258 /* if we created a temporary file before ... */
2259 if (endname != Nullch) {
2260 /* ...and rename succeeded, delete temporary file/directory */
2261 if (retval == 0)
2262 DeleteFile(tmpname);
2263 /* else restore it to what it was */
2264 else
2265 (void)rename(tmpname, newname);
2266 }
2267 return retval;
e24c7c18 2268 }
e24c7c18
GS
2269}
2270
2271DllExport int
68dc0745 2272win32_setmode(int fd, int mode)
0a753a76 2273{
390b85e7 2274 return setmode(fd, mode);
0a753a76
PP
2275}
2276
96e4d5b1
PP
2277DllExport long
2278win32_lseek(int fd, long offset, int origin)
2279{
390b85e7 2280 return lseek(fd, offset, origin);
96e4d5b1
PP
2281}
2282
2283DllExport long
2284win32_tell(int fd)
2285{
390b85e7 2286 return tell(fd);
96e4d5b1
PP
2287}
2288
68dc0745
PP
2289DllExport int
2290win32_open(const char *path, int flag, ...)
0a753a76 2291{
c5be433b 2292 dTHXo;
68dc0745
PP
2293 va_list ap;
2294 int pmode;
b9010385 2295 WCHAR wBuffer[MAX_PATH];
0a753a76
PP
2296
2297 va_start(ap, flag);
2298 pmode = va_arg(ap, int);
2299 va_end(ap);
2300
68dc0745 2301 if (stricmp(path, "/dev/null")==0)
7fac1903
GS
2302 path = "NUL";
2303
2304 if (USING_WIDE()) {
0cb96387 2305 A2WHELPER(path, wBuffer, sizeof(wBuffer));
7fac1903
GS
2306 return _wopen(wBuffer, flag, pmode);
2307 }
390b85e7 2308 return open(path,flag,pmode);
0a753a76
PP
2309}
2310
68dc0745
PP
2311DllExport int
2312win32_close(int fd)
0a753a76 2313{
390b85e7 2314 return close(fd);
0a753a76
PP
2315}
2316
68dc0745 2317DllExport int
96e4d5b1
PP
2318win32_eof(int fd)
2319{
390b85e7 2320 return eof(fd);
96e4d5b1
PP
2321}
2322
2323DllExport int
68dc0745 2324win32_dup(int fd)
0a753a76 2325{
390b85e7 2326 return dup(fd);
0a753a76
PP
2327}
2328
68dc0745
PP
2329DllExport int
2330win32_dup2(int fd1,int fd2)
0a753a76 2331{
390b85e7 2332 return dup2(fd1,fd2);
0a753a76
PP
2333}
2334
68dc0745 2335DllExport int
3e3baf6d 2336win32_read(int fd, void *buf, unsigned int cnt)
0a753a76 2337{
390b85e7 2338 return read(fd, buf, cnt);
0a753a76
PP
2339}
2340
68dc0745 2341DllExport int
3e3baf6d 2342win32_write(int fd, const void *buf, unsigned int cnt)
0a753a76 2343{
390b85e7 2344 return write(fd, buf, cnt);
0a753a76
PP
2345}
2346
68dc0745 2347DllExport int
5aabfad6
PP
2348win32_mkdir(const char *dir, int mode)
2349{
390b85e7 2350 return mkdir(dir); /* just ignore mode */
5aabfad6 2351}
96e4d5b1 2352
5aabfad6
PP
2353DllExport int
2354win32_rmdir(const char *dir)
2355{
390b85e7 2356 return rmdir(dir);
5aabfad6 2357}
96e4d5b1 2358
5aabfad6
PP
2359DllExport int
2360win32_chdir(const char *dir)
2361{
390b85e7 2362 return chdir(dir);
5aabfad6 2363}
96e4d5b1 2364
0aaad0ff
GS
2365static char *
2366create_command_line(const char* command, const char * const *args)
2367{
c5be433b 2368 dTHXo;
0aaad0ff
GS
2369 int index;
2370 char *cmd, *ptr, *arg;
2371 STRLEN len = strlen(command) + 1;
2372
2373 for (index = 0; (ptr = (char*)args[index]) != NULL; ++index)
2374 len += strlen(ptr) + 1;
2375
2376 New(1310, cmd, len, char);
2377 ptr = cmd;
2378 strcpy(ptr, command);
0aaad0ff
GS
2379
2380 for (index = 0; (arg = (char*)args[index]) != NULL; ++index) {
0aaad0ff 2381 ptr += strlen(ptr);
18a945d4
GS
2382 *ptr++ = ' ';
2383 strcpy(ptr, arg);
0aaad0ff
GS
2384 }
2385
2386 return cmd;
2387}
2388
2389static char *
2390qualified_path(const char *cmd)
2391{
c5be433b 2392 dTHXo;
0aaad0ff
GS
2393 char *pathstr;
2394 char *fullcmd, *curfullcmd;
2395 STRLEN cmdlen = 0;
2396 int has_slash = 0;
2397
2398 if (!cmd)
2399 return Nullch;
2400 fullcmd = (char*)cmd;
2401 while (*fullcmd) {
2402 if (*fullcmd == '/' || *fullcmd == '\\')
2403 has_slash++;
2404 fullcmd++;
2405 cmdlen++;
2406 }
2407
2408 /* look in PATH */
2409 pathstr = win32_getenv("PATH");
2410 New(0, fullcmd, MAX_PATH+1, char);
2411 curfullcmd = fullcmd;
2412
2413 while (1) {
2414 DWORD res;
2415
2416 /* start by appending the name to the current prefix */
2417 strcpy(curfullcmd, cmd);
2418 curfullcmd += cmdlen;
2419
2420 /* if it doesn't end with '.', or has no extension, try adding
2421 * a trailing .exe first */
2422 if (cmd[cmdlen-1] != '.'
2423 && (cmdlen < 4 || cmd[cmdlen-4] != '.'))
2424 {
2425 strcpy(curfullcmd, ".exe");
2426 res = GetFileAttributes(fullcmd);
2427 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
2428 return fullcmd;
2429 *curfullcmd = '\0';
2430 }
2431
2432 /* that failed, try the bare name */
2433 res = GetFileAttributes(fullcmd);
2434 if (res != 0xFFFFFFFF && !(res & FILE_ATTRIBUTE_DIRECTORY))
2435 return fullcmd;
2436
2437 /* quit if no other path exists, or if cmd already has path */
2438 if (!pathstr || !*pathstr || has_slash)
2439 break;
2440
2441 /* skip leading semis */
2442 while (*pathstr == ';')
2443 pathstr++;
2444
2445 /* build a new prefix from scratch */
2446 curfullcmd = fullcmd;
2447 while (*pathstr && *pathstr != ';') {
2448 if (*pathstr == '"') { /* foo;"baz;etc";bar */
2449 pathstr++; /* skip initial '"' */
2450 while (*pathstr && *pathstr != '"') {
2451 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
2452 *curfullcmd++ = *pathstr;
2453 pathstr++;
2454 }
2455 if (*pathstr)
2456 pathstr++; /* skip trailing '"' */
2457 }
2458 else {
2459 if (curfullcmd-fullcmd < MAX_PATH-cmdlen-5)
2460 *curfullcmd++ = *pathstr;
2461 pathstr++;
2462 }
2463 }
2464 if (*pathstr)
2465 pathstr++; /* skip trailing semi */
2466 if (curfullcmd > fullcmd /* append a dir separator */
2467 && curfullcmd[-1] != '/' && curfullcmd[-1] != '\\')
2468 {
2469 *curfullcmd++ = '\\';
2470 }
2471 }
2472GIVE_UP:
2473 Safefree(fullcmd);
2474 return Nullch;
2475}
2476
3075ddba
GS
2477/* The following are just place holders.
2478 * Some hosts may provide and environment that the OS is
2479 * not tracking, therefore, these host must provide that
2480 * environment and the current directory to CreateProcess
2481 */
2482
2483void*
2484get_childenv(void)
2485{
2486 return NULL;
2487}
2488
2489void
2dd19d29 2490free_childenv(void* d)
3075ddba
GS
2491{
2492}
2493
2494char*
2495get_childdir(void)
2496{
2497 return NULL;
2498}
2499
2500void
2dd19d29 2501free_childdir(char* d)
3075ddba
GS
2502{
2503}
2504
2505
0aaad0ff
GS
2506/* XXX this needs to be made more compatible with the spawnvp()
2507 * provided by the various RTLs. In particular, searching for
2508 * *.{com,bat,cmd} files (as done by the RTLs) is unimplemented.
2509 * This doesn't significantly affect perl itself, because we
2510 * always invoke things using PERL5SHELL if a direct attempt to
2511 * spawn the executable fails.
2512 *
2513 * XXX splitting and rejoining the commandline between do_aspawn()
2514 * and win32_spawnvp() could also be avoided.
2515 */
2516
5aabfad6 2517DllExport int
3e3baf6d 2518win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
0a753a76 2519{
0aaad0ff
GS
2520#ifdef USE_RTL_SPAWNVP
2521 return spawnvp(mode, cmdname, (char * const *)argv);
2522#else
c5be433b 2523 dTHXo;
2b260de0 2524 int ret;
3075ddba
GS
2525 void* env;
2526 char* dir;
0aaad0ff
GS
2527 STARTUPINFO StartupInfo;
2528 PROCESS_INFORMATION ProcessInformation;
2529 DWORD create = 0;
2530
2531 char *cmd = create_command_line(cmdname, strcmp(cmdname, argv[0]) == 0
2532 ? &argv[1] : argv);
2533 char *fullcmd = Nullch;
2534
3075ddba
GS
2535 env = PerlEnv_get_childenv();
2536 dir = PerlEnv_get_childdir();
2537
0aaad0ff
GS
2538 switch(mode) {
2539 case P_NOWAIT: /* asynch + remember result */
2540 if (w32_num_children >= MAXIMUM_WAIT_OBJECTS) {
2541 errno = EAGAIN;
2542 ret = -1;
2543 goto RETVAL;
2544 }
2545 /* FALL THROUGH */
2546 case P_WAIT: /* synchronous execution */
2547 break;
2548 default: /* invalid mode */
2549 errno = EINVAL;
2550 ret = -1;
2551 goto RETVAL;
2552 }
2553 memset(&StartupInfo,0,sizeof(StartupInfo));
2554 StartupInfo.cb = sizeof(StartupInfo);
3ffaa937
GS
2555 StartupInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
2556 StartupInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
2557 StartupInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
2558 if (StartupInfo.hStdInput != INVALID_HANDLE_VALUE &&
2559 StartupInfo.hStdOutput != INVALID_HANDLE_VALUE &&
2560 StartupInfo.hStdError != INVALID_HANDLE_VALUE)
2561 {
2562 StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
2563 }
2564 else {
2565 create |= CREATE_NEW_CONSOLE;
2566 }
2567
0aaad0ff
GS
2568RETRY:
2569 if (!CreateProcess(cmdname, /* search PATH to find executable */
2570 cmd, /* executable, and its arguments */
2571 NULL, /* process attributes */
2572 NULL, /* thread attributes */
2573 TRUE, /* inherit handles */
2574 create, /* creation flags */
3075ddba
GS
2575 (LPVOID)env, /* inherit environment */
2576 dir, /* inherit cwd */
0aaad0ff
GS
2577 &StartupInfo,
2578 &ProcessInformation))
2579 {
2580 /* initial NULL argument to CreateProcess() does a PATH
2581 * search, but it always first looks in the directory
2582 * where the current process was started, which behavior
2583 * is undesirable for backward compatibility. So we
2584 * jump through our own hoops by picking out the path
2585 * we really want it to use. */
2586 if (!fullcmd) {
2587 fullcmd = qualified_path(cmdname);
2588 if (fullcmd) {
2589 cmdname = fullcmd;
2590 goto RETRY;
2591 }
2592 }
2593 errno = ENOENT;
2594 ret = -1;
2595 goto RETVAL;
2596 }
2d7a9237 2597
0aaad0ff
GS
2598 if (mode == P_NOWAIT) {
2599 /* asynchronous spawn -- store handle, return PID */
2600 w32_child_handles[w32_num_children] = ProcessInformation.hProcess;
2b260de0
GS
2601 w32_child_pids[w32_num_children] = ProcessInformation.dwProcessId;
2602 ret = (int)ProcessInformation.dwProcessId;
0aaad0ff
GS
2603 ++w32_num_children;
2604 }
2605 else {
2b260de0 2606 DWORD status;
0aaad0ff 2607 WaitForSingleObject(ProcessInformation.hProcess, INFINITE);
2b260de0
GS
2608 GetExitCodeProcess(ProcessInformation.hProcess, &status);
2609 ret = (int)status;
0aaad0ff
GS
2610 CloseHandle(ProcessInformation.hProcess);
2611 }
e17cb2a9 2612
0aaad0ff 2613 CloseHandle(ProcessInformation.hThread);
3075ddba 2614
0aaad0ff 2615RETVAL:
3075ddba
GS
2616 PerlEnv_free_childenv(env);
2617 PerlEnv_free_childdir(dir);
0aaad0ff
GS
2618 Safefree(cmd);
2619 Safefree(fullcmd);
2b260de0 2620 return ret;
2d7a9237 2621#endif
0a753a76
PP
2622}
2623
6890e559 2624DllExport int
eb62e965
JD
2625win32_execv(const char *cmdname, const char *const *argv)
2626{
2627 return execv(cmdname, (char *const *)argv);
2628}
2629
2630DllExport int
6890e559
GS
2631win32_execvp(const char *cmdname, const char *const *argv)
2632{
390b85e7 2633 return execvp(cmdname, (char *const *)argv);
6890e559
GS
2634}
2635
84902520
TB
2636DllExport void
2637win32_perror(const char *str)
2638{
390b85e7 2639 perror(str);
84902520
TB
2640}
2641
2642DllExport void
2643win32_setbuf(FILE *pf, char *buf)
2644{
390b85e7 2645 setbuf(pf, buf);
84902520
TB
2646}
2647
2648DllExport int
2649win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
2650{
390b85e7 2651 return setvbuf(pf, buf, type, size);
84902520
TB
2652}
2653
2654DllExport int
2655win32_flushall(void)
2656{
390b85e7 2657 return flushall();
84902520
TB
2658}
2659
2660DllExport int
2661win32_fcloseall(void)
2662{
390b85e7 2663 return fcloseall();
84902520
TB
2664}
2665
2666DllExport char*
2667win32_fgets(char *s, int n, FILE *pf)
2668{
390b85e7 2669 return fgets(s, n, pf);
84902520
TB
2670}
2671
2672DllExport char*
2673win32_gets(char *s)
2674{
390b85e7 2675 return gets(s);
84902520
TB
2676}
2677
2678DllExport int
2679win32_fgetc(FILE *pf)
2680{
390b85e7 2681 return fgetc(pf);
84902520
TB
2682}
2683
2684DllExport int
2685win32_putc(int c, FILE *pf)
2686{
390b85e7 2687 return putc(c,pf);
84902520
TB
2688}
2689
2690DllExport int
2691win32_puts(const char *s)
2692{
390b85e7 2693 return puts(s);
84902520
TB
2694}
2695
2696DllExport int
2697win32_getchar(void)
2698{
390b85e7 2699 return getchar();
84902520
TB
2700}
2701
2702DllExport int
2703win32_putchar(int c)
2704{
390b85e7 2705 return putchar(c);
84902520
TB
2706}
2707
bbc8f9de
NIS
2708#ifdef MYMALLOC
2709
2710#ifndef USE_PERL_SBRK
2711
2712static char *committed = NULL;
2713static char *base = NULL;
2714static char *reserved = NULL;
2715static char *brk = NULL;
2716static DWORD pagesize = 0;
2717static DWORD allocsize = 0;
2718
2719void *
2720sbrk(int need)
2721{
2722 void *result;
2723 if (!pagesize)
2724 {SYSTEM_INFO info;
2725 GetSystemInfo(&info);
2726 /* Pretend page size is larger so we don't perpetually
2727 * call the OS to commit just one page ...
2728 */
2729 pagesize = info.dwPageSize << 3;
2730 allocsize = info.dwAllocationGranularity;
2731 }
2732 /* This scheme fails eventually if request for contiguous
2733 * block is denied so reserve big blocks - this is only
2734 * address space not memory ...
2735 */
2736 if (brk+need >= reserved)
2737 {
2738 DWORD size = 64*1024*1024;
2739 char *addr;
2740 if (committed && reserved && committed < reserved)
2741 {
2742 /* Commit last of previous chunk cannot span allocations */
161b471a 2743 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
bbc8f9de
NIS
2744 if (addr)
2745 committed = reserved;
2746 }
2747 /* Reserve some (more) space
2748 * Note this is a little sneaky, 1st call passes NULL as reserved
2749 * so lets system choose where we start, subsequent calls pass
2750 * the old end address so ask for a contiguous block
2751 */
161b471a 2752 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
bbc8f9de
NIS
2753 if (addr)
2754 {
2755 reserved = addr+size;
2756 if (!base)
2757 base = addr;
2758 if (!committed)
2759 committed = base;
2760 if (!brk)
2761 brk = committed;
2762 }
2763 else
2764 {
2765 return (void *) -1;
2766 }
2767 }
2768 result = brk;
2769 brk += need;
2770 if (brk > committed)
2771 {
2772 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
161b471a 2773 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
bbc8f9de
NIS
2774 if (addr)
2775 {
2776 committed += size;
2777 }
2778 else
2779 return (void *) -1;
2780 }
2781 return result;
2782}
2783
2784#endif
2785#endif
2786
84902520
TB
2787DllExport void*
2788win32_malloc(size_t size)
2789{
390b85e7 2790 return malloc(size);
84902520
TB
2791}
2792
2793DllExport void*
2794win32_calloc(size_t numitems, size_t size)
2795{
390b85e7 2796 return calloc(numitems,size);
84902520
TB
2797}
2798
2799DllExport void*
2800win32_realloc(void *block, size_t size)
2801{
390b85e7 2802 return realloc(block,size);
84902520
TB
2803}
2804
2805DllExport void
2806win32_free(void *block)
2807{
390b85e7 2808 free(block);
84902520
TB
2809}
2810
bbc8f9de 2811
68dc0745 2812int
65e48ea9 2813win32_open_osfhandle(long handle, int flags)
0a753a76 2814{
390b85e7 2815 return _open_osfhandle(handle, flags);
0a753a76
PP
2816}
2817
68dc0745 2818long
65e48ea9 2819win32_get_osfhandle(int fd)
0a753a76 2820{
390b85e7 2821 return _get_osfhandle(fd);
0a753a76 2822}
7bac28a0 2823
0cb96387 2824DllExport void*
c5be433b 2825win32_dynaload(const char* filename)
0cb96387 2826{
c5be433b 2827 dTHXo;
51371543 2828 HMODULE hModule;
0cb96387
GS
2829 if (USING_WIDE()) {
2830 WCHAR wfilename[MAX_PATH];
2831 A2WHELPER(filename, wfilename, sizeof(wfilename));
2832 hModule = LoadLibraryExW(wfilename, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
2833 }
2834 else {
2835 hModule = LoadLibraryExA(filename, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
2836 }
2837 return hModule;
2838}
2839
2840DllExport int
2841win32_add_host(char *nameId, void *data)
2842{
2843 /*
2844 * This must be called before the script is parsed,
2845 * therefore no locking of threads is needed
2846 */
c5be433b 2847 dTHXo;
0cb96387
GS
2848 struct host_link *link;
2849 New(1314, link, 1, struct host_link);
2850 link->host_data = data;
2851 link->nameId = nameId;
2852 link->next = w32_host_link;
2853 w32_host_link = link;
2854 return 1;
2855}
2856
2857DllExport void *
2858win32_get_host_data(char *nameId)
2859{
c5be433b 2860 dTHXo;
0cb96387
GS
2861 struct host_link *link = w32_host_link;
2862 while(link) {
2863 if(strEQ(link->nameId, nameId))
2864 return link->host_data;
2865 link = link->next;
2866 }
2867 return Nullch;
2868}
2869
7bac28a0
PP
2870/*
2871 * Extras.
2872 */
2873
ad2e33dc
GS
2874static
2875XS(w32_GetCwd)
2876{
2877 dXSARGS;
2878 SV *sv = sv_newmortal();
2879 /* Make one call with zero size - return value is required size */
2880 DWORD len = GetCurrentDirectory((DWORD)0,NULL);
2881 SvUPGRADE(sv,SVt_PV);
2882 SvGROW(sv,len);
2883 SvCUR(sv) = GetCurrentDirectory((DWORD) SvLEN(sv), SvPVX(sv));
2884 /*
2885 * If result != 0
2886 * then it worked, set PV valid,
2887 * else leave it 'undef'
2888 */
3467312b 2889 EXTEND(SP,1);
bb897dfc 2890 if (SvCUR(sv)) {
ad2e33dc 2891 SvPOK_on(sv);
bb897dfc
JD
2892 ST(0) = sv;
2893 XSRETURN(1);
2894 }
3467312b 2895 XSRETURN_UNDEF;
ad2e33dc
GS
2896}
2897
2898static
2899XS(w32_SetCwd)
2900{
2901 dXSARGS;
2902 if (items != 1)
4f63d024 2903 Perl_croak(aTHX_ "usage: Win32::SetCurrentDirectory($cwd)");
bb897dfc 2904 if (SetCurrentDirectory(SvPV_nolen(ST(0))))
ad2e33dc
GS
2905 XSRETURN_YES;
2906
2907 XSRETURN_NO;
2908}
2909
2910static
2911XS(w32_GetNextAvailDrive)
2912{
2913 dXSARGS;
2914 char ix = 'C';
2915 char root[] = "_:\\";
3467312b
JD
2916
2917 EXTEND(SP,1);
ad2e33dc
GS
2918 while (ix <= 'Z') {
2919 root[0] = ix++;
2920 if (GetDriveType(root) == 1) {
2921 root[2] = '\0';
2922 XSRETURN_PV(root);
2923 }
2924 }
3467312b 2925 XSRETURN_UNDEF;
ad2e33dc
GS
2926}
2927
2928static
2929XS(w32_GetLastError)
2930{
2931 dXSARGS;
bb897dfc 2932 EXTEND(SP,1);
ad2e33dc
GS
2933 XSRETURN_IV(GetLastError());
2934}
2935
2936static
ca135624
JD
2937XS(w32_SetLastError)
2938{
2939 dXSARGS;
2940 if (items != 1)
4f63d024 2941 Perl_croak(aTHX_ "usage: Win32::SetLastError($error)");
ca135624 2942 SetLastError(SvIV(ST(0)));
bb897dfc 2943 XSRETURN_EMPTY;
ca135624
JD
2944}
2945
2946static
ad2e33dc
GS
2947XS(w32_LoginName)
2948{
2949 dXSARGS;
3352bfcb
GS
2950 char *name = w32_getlogin_buffer;
2951 DWORD size = sizeof(w32_getlogin_buffer);
3467312b 2952 EXTEND(SP,1);
ad2e33dc
GS
2953 if (GetUserName(name,&size)) {
2954 /* size includes NULL */
79cb57f6 2955 ST(0) = sv_2mortal(newSVpvn(name,size-1));
ad2e33dc
GS
2956 XSRETURN(1);
2957 }
3467312b 2958 XSRETURN_UNDEF;
ad2e33dc
GS
2959}
2960
2961static
2962XS(w32_NodeName)
2963{
2964 dXSARGS;
2965 char name[MAX_COMPUTERNAME_LENGTH+1];
2966 DWORD size = sizeof(name);
3467312b 2967 EXTEND(SP,1);
ad2e33dc
GS
2968 if (GetComputerName(name,&size)) {
2969 /* size does NOT include NULL :-( */
79cb57f6 2970 ST(0) = sv_2mortal(newSVpvn(name,size));
ad2e33dc
GS
2971 XSRETURN(1);
2972 }
3467312b 2973 XSRETURN_UNDEF;
ad2e33dc
GS
2974}
2975
2976
2977static
2978XS(w32_DomainName)
2979{
2980 dXSARGS;
625a29bd
GS
2981 HINSTANCE hNetApi32 = LoadLibrary("netapi32.dll");
2982 DWORD (__stdcall *pfnNetApiBufferFree)(LPVOID Buffer);
2983 DWORD (__stdcall *pfnNetWkstaGetInfo)(LPWSTR servername, DWORD level,
2984 void *bufptr);
2985
2986 if (hNetApi32) {
2987 pfnNetApiBufferFree = (DWORD (__stdcall *)(void *))
2988 GetProcAddress(hNetApi32, "NetApiBufferFree");
2989 pfnNetWkstaGetInfo = (DWORD (__stdcall *)(LPWSTR, DWORD, void *))
2990 GetProcAddress(hNetApi32, "NetWkstaGetInfo");
2991 }
3467312b 2992 EXTEND(SP,1);
625a29bd
GS
2993 if (hNetApi32 && pfnNetWkstaGetInfo && pfnNetApiBufferFree) {
2994 /* this way is more reliable, in case user has a local account. */
ad2e33dc
GS
2995 char dname[256];
2996 DWORD dnamelen = sizeof(dname);
625a29bd
GS
2997 struct {
2998 DWORD wki100_platform_id;
2999 LPWSTR wki100_computername;
3000 LPWSTR wki100_langroup;
3001 DWORD wki100_ver_major;
3002 DWORD wki100_ver_minor;
3003 } *pwi;
3004 /* NERR_Success *is* 0*/
3005 if (0 == pfnNetWkstaGetInfo(NULL, 100, &pwi)) {
3006 if (pwi->wki100_langroup && *(pwi->wki100_langroup)) {
3007 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_langroup,
3008 -1, (LPSTR)dname, dnamelen, NULL, NULL);
3009 }
3010 else {
3011 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_computername,
3012 -1, (LPSTR)dname, dnamelen, NULL, NULL);
3013 }
3014 pfnNetApiBufferFree(pwi);
3015 FreeLibrary(hNetApi32);
3016 XSRETURN_PV(dname);
ad2e33dc 3017 }
625a29bd 3018 FreeLibrary(hNetApi32);
ad2e33dc 3019 }
625a29bd
GS
3020 else {
3021 /* Win95 doesn't have NetWksta*(), so do it the old way */
3022 char name[256];
3023 DWORD size = sizeof(name);
3024 if (hNetApi32)
3025 FreeLibrary(hNetApi32);
3026 if (GetUserName(name,&size)) {
3027 char sid[1024];
3028 DWORD sidlen = sizeof(sid);
3029 char dname[256];
3030 DWORD dnamelen = sizeof(dname);
3031 SID_NAME_USE snu;
3032 if (LookupAccountName(NULL, name, (PSID)&sid, &sidlen,
3033 dname, &dnamelen, &snu)) {
3034 XSRETURN_PV(dname); /* all that for this */
3035 }
0a2408cf 3036 }
9404a519 3037 }
3467312b 3038 XSRETURN_UNDEF;
ad2e33dc
GS
3039}
3040
3041static
3042XS(w32_FsType)
3043{
3044 dXSARGS;
3045 char fsname[256];
3046 DWORD flags, filecomplen;
3047 if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
3048 &flags, fsname, sizeof(fsname))) {
bb897dfc 3049 if (GIMME_V == G_ARRAY) {
79cb57f6 3050 XPUSHs(sv_2mortal(newSVpvn(fsname,strlen(fsname))));
ad2e33dc
GS
3051 XPUSHs(sv_2mortal(newSViv(flags)));
3052 XPUSHs(sv_2mortal(newSViv(filecomplen)));
3053 PUTBACK;
3054 return;
3055 }
bb897dfc 3056 EXTEND(SP,1);
ad2e33dc
GS
3057 XSRETURN_PV(fsname);
3058 }
bb897dfc 3059 XSRETURN_EMPTY;
ad2e33dc
GS
3060}
3061
3062static
3063XS(w32_GetOSVersion)
3064{
3065 dXSARGS;
3066 OSVERSIONINFO osver;
3067
3068 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
3069 if (GetVersionEx(&osver)) {
79cb57f6 3070 XPUSHs(newSVpvn(osver.szCSDVersion, strlen(osver.szCSDVersion)));
ad2e33dc
GS
3071 XPUSHs(newSViv(osver.dwMajorVersion));
3072 XPUSHs(newSViv(osver.dwMinorVersion));
3073 XPUSHs(newSViv(osver.dwBuildNumber));
3074 XPUSHs(newSViv(osver.dwPlatformId));
3075 PUTBACK;
3076 return;
3077 }
bb897dfc 3078 XSRETURN_EMPTY;
ad2e33dc
GS
3079}
3080
3081static
3082XS(w32_IsWinNT)
3083{
3084 dXSARGS;
bb897dfc 3085 EXTEND(SP,1);
ad2e33dc
GS
3086 XSRETURN_IV(IsWinNT());
3087}
3088
3089static
3090XS(w32_IsWin95)
3091{
3092 dXSARGS;
bb897dfc 3093 EXTEND(SP,1);
ad2e33dc
GS
3094 XSRETURN_IV(IsWin95());
3095}
3096
3097static
3098XS(w32_FormatMessage)
3099{
3100 dXSARGS;
3101 DWORD source = 0;
3102 char msgbuf[1024];
3103
3104 if (items != 1)
4f63d024 3105 Perl_croak(aTHX_ "usage: Win32::FormatMessage($errno)");
ad2e33dc
GS
3106
3107 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
3108 &source, SvIV(ST(0)), 0,
3109 msgbuf, sizeof(msgbuf)-1, NULL))
3110 XSRETURN_PV(msgbuf);
3111
3467312b 3112 XSRETURN_UNDEF;
ad2e33dc
GS
3113}
3114
3115static
3116XS(w32_Spawn)
3117{
3118 dXSARGS;
3119 char *cmd, *args;
3120 PROCESS_INFORMATION stProcInfo;
3121 STARTUPINFO stStartInfo;
3122 BOOL bSuccess = FALSE;
3123
9404a519 3124 if (items != 3)
4f63d024 3125 Perl_croak(aTHX_ "usage: Win32::Spawn($cmdName, $args, $PID)");
ad2e33dc 3126
bb897dfc
JD
3127 cmd = SvPV_nolen(ST(0));
3128 args = SvPV_nolen(ST(1));
ad2e33dc
GS
3129
3130 memset(&stStartInfo, 0, sizeof(stStartInfo)); /* Clear the block */
3131 stStartInfo.cb = sizeof(stStartInfo); /* Set the structure size */
3132 stStartInfo.dwFlags = STARTF_USESHOWWINDOW; /* Enable wShowWindow control */
3133 stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE; /* Start min (normal) */
3134
9404a519 3135 if (CreateProcess(
ad2e33dc
GS
3136 cmd, /* Image path */
3137 args, /* Arguments for command line */
3138 NULL, /* Default process security */
3139 NULL, /* Default thread security */
3140 FALSE, /* Must be TRUE to use std handles */
3141 NORMAL_PRIORITY_CLASS, /* No special scheduling */
3142 NULL, /* Inherit our environment block */
3143 NULL, /* Inherit our currrent directory */
3144 &stStartInfo, /* -> Startup info */
3145 &stProcInfo)) /* <- Process info (if OK) */
3146 {
3147 CloseHandle(stProcInfo.hThread);/* library source code does this. */
3148 sv_setiv(ST(2), stProcInfo.dwProcessId);
3149 bSuccess = TRUE;
3150 }
3151 XSRETURN_IV(bSuccess);
3152}
3153
3154static
3155XS(w32_GetTickCount)
3156{
3157 dXSARGS;
fdb068fa 3158 DWORD msec = GetTickCount();
a6c40364 3159 EXTEND(SP,1);
fdb068fa
JD
3160 if ((IV)msec > 0)
3161 XSRETURN_IV(msec);
3162 XSRETURN_NV(msec);
ad2e33dc
GS
3163}
3164
3165static
3166XS(w32_GetShortPathName)
3167{
3168 dXSARGS;
3169 SV *shortpath;
e8bab181 3170 DWORD len;
ad2e33dc 3171
9404a519 3172 if (items != 1)
4f63d024 3173 Perl_croak(aTHX_ "usage: Win32::GetShortPathName($longPathName)");
ad2e33dc
GS
3174
3175 shortpath = sv_mortalcopy(ST(0));
3176 SvUPGRADE(shortpath, SVt_PV);
3177 /* src == target is allowed */
e8bab181
GS
3178 do {
3179 len = GetShortPathName(SvPVX(shortpath),
3180 SvPVX(shortpath),
3181 SvLEN(shortpath));
3182 } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
3183 if (len) {
3184 SvCUR_set(shortpath,len);
ad2e33dc 3185 ST(0) = shortpath;
bb897dfc 3186 XSRETURN(1);
e8bab181 3187 }
3467312b 3188 XSRETURN_UNDEF;
ad2e33dc
GS
3189}
3190
ad0751ec 3191static
ca135624
JD
3192XS(w32_GetFullPathName)
3193{
3194 dXSARGS;
3195 SV *filename;
3196 SV *fullpath;
3197 char *filepart;
3198 DWORD len;
3199
3200 if (items != 1)
4f63d024 3201 Perl_croak(aTHX_ "usage: Win32::GetFullPathName($filename)");
ca135624
JD
3202
3203 filename = ST(0);
3204 fullpath = sv_mortalcopy(filename);
3205 SvUPGRADE(fullpath, SVt_PV);
3206 do {
3207 len = GetFullPathName(SvPVX(filename),
3208 SvLEN(fullpath),
3209 SvPVX(fullpath),
3210 &filepart);
3211 } while (len >= SvLEN(fullpath) && sv_grow(fullpath,len+1));
3212 if (len) {
3213 if (GIMME_V == G_ARRAY) {
3214 EXTEND(SP,1);
bb897dfc 3215 XST_mPV(1,filepart);
ca135624
JD
3216 len = filepart - SvPVX(fullpath);
3217 items = 2;
3218 }
3219 SvCUR_set(fullpath,len);
3220 ST(0) = fullpath;
bb897dfc 3221 XSRETURN(items);
ca135624 3222 }
bb897dfc 3223 XSRETURN_EMPTY;
ca135624
JD
3224}
3225
3226static
8ac9c18d
GS
3227XS(w32_GetLongPathName)
3228{
3229 dXSARGS;
3230 SV *path;
3231 char tmpbuf[MAX_PATH+1];
3232 char *pathstr;
3233 STRLEN len;
3234
3235 if (items != 1)
4f63d024 3236 Perl_croak(aTHX_ "usage: Win32::GetLongPathName($pathname)");
8ac9c18d
GS
3237
3238 path = ST(0);
3239 pathstr = SvPV(path,len);
3240 strcpy(tmpbuf, pathstr);
3241 pathstr = win32_longpath(tmpbuf);
3242 if (pathstr) {
3243 ST(0) = sv_2mortal(newSVpvn(pathstr, strlen(pathstr)));
3244 XSRETURN(1);
3245 }
3246 XSRETURN_EMPTY;
3247}
3248
3249static
ad0751ec
GS
3250XS(w32_Sleep)
3251{
3252 dXSARGS;
3253 if (items != 1)
4f63d024 3254 Perl_croak(aTHX_ "usage: Win32::Sleep($milliseconds)");
ad0751ec
GS
3255 Sleep(SvIV(ST(0)));
3256 XSRETURN_YES;
3257}
3258
7509b657
GS
3259static
3260XS(w32_CopyFile)
3261{
3262 dXSARGS;
3263 if (items != 3)
4f63d024 3264 Perl_croak(aTHX_ "usage: Win32::CopyFile($from, $to, $overwrite)");
7509b657
GS
3265 if (CopyFile(SvPV_nolen(ST(0)), SvPV_nolen(ST(1)), !SvTRUE(ST(2))))
3266 XSRETURN_YES;
3267 XSRETURN_NO;
3268}
3269
ad2e33dc 3270void
c5be433b 3271Perl_init_os_extras(void)
ad2e33dc 3272{
c5be433b 3273 dTHXo;
ad2e33dc
GS
3274 char *file = __FILE__;
3275 dXSUB_SYS;
3276
4b556e6c
JD
3277 w32_perlshell_tokens = Nullch;
3278 w32_perlshell_items = -1;
3279 w32_fdpid = newAV(); /* XXX needs to be in Perl_win32_init()? */
0aaad0ff 3280 New(1313, w32_children, 1, child_tab);
4b556e6c 3281 w32_num_children = 0;
4b556e6c 3282
ad2e33dc
GS
3283 /* these names are Activeware compatible */
3284 newXS("Win32::GetCwd", w32_GetCwd, file);
3285 newXS("Win32::SetCwd", w32_SetCwd, file);
3286 newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
3287 newXS("Win32::GetLastError", w32_GetLastError, file);
ca135624 3288 newXS("Win32::SetLastError", w32_SetLastError, file);
ad2e33dc
GS
3289 newXS("Win32::LoginName", w32_LoginName, file);
3290 newXS("Win32::NodeName", w32_NodeName, file);
3291 newXS("Win32::DomainName", w32_DomainName, file);
3292 newXS("Win32::FsType", w32_FsType, file);
3293 newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
3294 newXS("Win32::IsWinNT", w32_IsWinNT, file);
3295 newXS("Win32::IsWin95", w32_IsWin95, file);
3296 newXS("Win32::FormatMessage", w32_FormatMessage, file);
3297 newXS("Win32::Spawn", w32_Spawn, file);
3298 newXS("Win32::GetTickCount", w32_GetTickCount, file);
3299 newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
ca135624 3300 newXS("Win32::GetFullPathName", w32_GetFullPathName, file);
8ac9c18d 3301 newXS("Win32::GetLongPathName", w32_GetLongPathName, file);
7509b657 3302 newXS("Win32::CopyFile", w32_CopyFile, file);
ad0751ec 3303 newXS("Win32::Sleep", w32_Sleep, file);
ad2e33dc
GS
3304
3305 /* XXX Bloat Alert! The following Activeware preloads really
3306 * ought to be part of Win32::Sys::*, so they're not included
3307 * here.
3308 */
3309 /* LookupAccountName
3310 * LookupAccountSID
3311 * InitiateSystemShutdown
3312 * AbortSystemShutdown
3313 * ExpandEnvrironmentStrings
3314 */
3315}
3316
3317void
3318Perl_win32_init(int *argcp, char ***argvp)
3319{
3320 /* Disable floating point errors, Perl will trap the ones we
3321 * care about. VC++ RTL defaults to switching these off
3322 * already, but the Borland RTL doesn't. Since we don't
3323 * want to be at the vendor's whim on the default, we set
3324 * it explicitly here.
3325 */
a835ef8a 3326#if !defined(_ALPHA_) && !defined(__GNUC__)
ad2e33dc 3327 _control87(MCW_EM, MCW_EM);
3dc9191e 3328#endif
4b556e6c 3329 MALLOC_INIT;
ad2e33dc 3330}
d55594ae 3331
d18c6117
GS
3332#ifdef USE_ITHREADS
3333void
3334Perl_sys_intern_dup(pTHX_ struct interp_intern *src, struct interp_intern *dst)
3335{
3336 dst->perlshell_tokens = Nullch;
3337 dst->perlshell_vec = (char**)NULL;
3338 dst->perlshell_items = 0;
3339 dst->fdpid = newAV();
3340 New(1313, dst->children, 1, child_tab);
3341 dst->children->num = 0;
3342 dst->hostlist = src->hostlist; /* XXX */
3343 dst->thr_intern.Winit_socktype = src->thr_intern.Winit_socktype;
3344}
3345#endif
3346
a868473f
NIS
3347#ifdef USE_BINMODE_SCRIPTS
3348
3349void
3350win32_strip_return(SV *sv)
3351{
3352 char *s = SvPVX(sv);
3353 char *e = s+SvCUR(sv);
3354 char *d = s;
3355 while (s < e)
3356 {
3357 if (*s == '\r' && s[1] == '\n')
3358 {
3359 *d++ = '\n';
3360 s += 2;
3361 }
3362 else
3363 {
3364 *d++ = *s++;
3365 }
3366 }
3367 SvCUR_set(sv,d-SvPVX(sv));
3368}
3369
3370#endif