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