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