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