This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Need to pass a my_perl to S_my_localtime to make threaded builds build.
[perl5.git] / perl.c
CommitLineData
a0d0e21e
LW
1/* perl.c
2 *
4bb101f2 3 * Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999,
770526c1 4 * 2000, 2001, 2002, 2003, 2004, 2005, by Larry Wall and others
a687059c 5 *
352d5a3a
LW
6 * You may distribute under the terms of either the GNU General Public
7 * License or the Artistic License, as specified in the README file.
a687059c 8 *
8d063cd8
LW
9 */
10
a0d0e21e
LW
11/*
12 * "A ship then new they built for him/of mithril and of elven glass" --Bilbo
13 */
45d8adaa 14
166f8a29
DM
15/* This file contains the top-level functions that are used to create, use
16 * and destroy a perl interpreter, plus the functions used by XS code to
17 * call back into perl. Note that it does not contain the actual main()
ddfa107c 18 * function of the interpreter; that can be found in perlmain.c
166f8a29
DM
19 */
20
ae3f3efd
PS
21/* PSz 12 Nov 03
22 *
23 * Be proud that perl(1) may proclaim:
24 * Setuid Perl scripts are safer than C programs ...
25 * Do not abandon (deprecate) suidperl. Do not advocate C wrappers.
26 *
27 * The flow was: perl starts, notices script is suid, execs suidperl with same
28 * arguments; suidperl opens script, checks many things, sets itself with
29 * right UID, execs perl with similar arguments but with script pre-opened on
30 * /dev/fd/xxx; perl checks script is as should be and does work. This was
31 * insecure: see perlsec(1) for many problems with this approach.
32 *
33 * The "correct" flow should be: perl starts, opens script and notices it is
34 * suid, checks many things, execs suidperl with similar arguments but with
35 * script on /dev/fd/xxx; suidperl checks script and /dev/fd/xxx object are
36 * same, checks arguments match #! line, sets itself with right UID, execs
37 * perl with same arguments; perl checks many things and does work.
38 *
39 * (Opening the script in perl instead of suidperl, we "lose" scripts that
40 * are readable to the target UID but not to the invoker. Where did
41 * unreadable scripts work anyway?)
42 *
43 * For now, suidperl and perl are pretty much the same large and cumbersome
44 * program, so suidperl can check its argument list (see comments elsewhere).
45 *
46 * References:
47 * Original bug report:
48 * http://bugs.perl.org/index.html?req=bug_id&bug_id=20010322.218
49 * http://rt.perl.org/rt2/Ticket/Display.html?id=6511
50 * Comments and discussion with Debian:
51 * http://bugs.debian.org/203426
52 * http://bugs.debian.org/220486
53 * Debian Security Advisory DSA 431-1 (does not fully fix problem):
54 * http://www.debian.org/security/2004/dsa-431
55 * CVE candidate:
56 * http://cve.mitre.org/cgi-bin/cvename.cgi?name=CAN-2003-0618
57 * Previous versions of this patch sent to perl5-porters:
58 * http://www.mail-archive.com/perl5-porters@perl.org/msg71953.html
59 * http://www.mail-archive.com/perl5-porters@perl.org/msg75245.html
60 * http://www.mail-archive.com/perl5-porters@perl.org/msg75563.html
61 * http://www.mail-archive.com/perl5-porters@perl.org/msg75635.html
62 *
63Paul Szabo - psz@maths.usyd.edu.au http://www.maths.usyd.edu.au:8000/u/psz/
64School of Mathematics and Statistics University of Sydney 2006 Australia
65 *
66 */
67/* PSz 13 Nov 03
68 * Use truthful, neat, specific error messages.
69 * Cannot always hide the truth; security must not depend on doing so.
70 */
71
72/* PSz 18 Feb 04
73 * Use global(?), thread-local fdscript for easier checks.
74 * (I do not understand how we could possibly get a thread race:
75 * do not all threads go through the same initialization? Or in
76 * fact, are not threads started only after we get the script and
77 * so know what to do? Oh well, make things super-safe...)
78 */
79
378cc40b 80#include "EXTERN.h"
864dbfa3 81#define PERL_IN_PERL_C
378cc40b 82#include "perl.h"
e3321bb0 83#include "patchlevel.h" /* for local_patches */
378cc40b 84
011f1a1a
JH
85#ifdef NETWARE
86#include "nwutil.h"
87char *nw_get_sitelib(const char *pl);
88#endif
89
df5cef82 90/* XXX If this causes problems, set i_unistd=undef in the hint file. */
a0d0e21e
LW
91#ifdef I_UNISTD
92#include <unistd.h>
93#endif
a0d0e21e 94
2aa47728
NC
95#ifdef DEBUG_LEAKING_SCALARS_FORK_DUMP
96# ifdef I_SYS_WAIT
97# include <sys/wait.h>
98# endif
99#endif
100
5311654c
JH
101#ifdef __BEOS__
102# define HZ 1000000
103#endif
104
105#ifndef HZ
106# ifdef CLK_TCK
107# define HZ CLK_TCK
108# else
109# define HZ 60
110# endif
111#endif
112
7114a2d2 113#if !defined(STANDARD_C) && !defined(HAS_GETENV_PROTOTYPE) && !defined(PERL_MICRO)
20ce7b12 114char *getenv (char *); /* Usually in <stdlib.h> */
54310121 115#endif
116
acfe0abc 117static I32 read_e_script(pTHX_ int idx, SV *buf_sv, int maxlen);
0cb96387 118
a687059c
LW
119#ifdef IAMSUID
120#ifndef DOSUID
121#define DOSUID
122#endif
ae3f3efd 123#endif /* IAMSUID */
378cc40b 124
a687059c
LW
125#ifdef SETUID_SCRIPTS_ARE_SECURE_NOW
126#ifdef DOSUID
127#undef DOSUID
128#endif
129#endif
8d063cd8 130
e6827a76 131static void
daa7d858 132S_init_tls_and_interp(PerlInterpreter *my_perl)
e6827a76 133{
27da23d5 134 dVAR;
e6827a76
NC
135 if (!PL_curinterp) {
136 PERL_SET_INTERP(my_perl);
3db8f154 137#if defined(USE_ITHREADS)
e6827a76
NC
138 INIT_THREADS;
139 ALLOC_THREAD_KEY;
140 PERL_SET_THX(my_perl);
141 OP_REFCNT_INIT;
142 MUTEX_INIT(&PL_dollarzero_mutex);
06d86050 143# endif
e6827a76
NC
144 }
145 else {
146 PERL_SET_THX(my_perl);
147 }
148}
06d86050 149
32e30700
GS
150#ifdef PERL_IMPLICIT_SYS
151PerlInterpreter *
7766f137
GS
152perl_alloc_using(struct IPerlMem* ipM, struct IPerlMem* ipMS,
153 struct IPerlMem* ipMP, struct IPerlEnv* ipE,
32e30700
GS
154 struct IPerlStdIO* ipStd, struct IPerlLIO* ipLIO,
155 struct IPerlDir* ipD, struct IPerlSock* ipS,
156 struct IPerlProc* ipP)
157{
158 PerlInterpreter *my_perl;
32e30700
GS
159 /* New() needs interpreter, so call malloc() instead */
160 my_perl = (PerlInterpreter*)(*ipM->pMalloc)(ipM, sizeof(PerlInterpreter));
e6827a76 161 S_init_tls_and_interp(my_perl);
32e30700
GS
162 Zero(my_perl, 1, PerlInterpreter);
163 PL_Mem = ipM;
7766f137
GS
164 PL_MemShared = ipMS;
165 PL_MemParse = ipMP;
32e30700
GS
166 PL_Env = ipE;
167 PL_StdIO = ipStd;
168 PL_LIO = ipLIO;
169 PL_Dir = ipD;
170 PL_Sock = ipS;
171 PL_Proc = ipP;
7766f137 172
32e30700
GS
173 return my_perl;
174}
175#else
954c1994
GS
176
177/*
ccfc67b7
JH
178=head1 Embedding Functions
179
954c1994
GS
180=for apidoc perl_alloc
181
182Allocates a new Perl interpreter. See L<perlembed>.
183
184=cut
185*/
186
93a17b20 187PerlInterpreter *
cea2e8a9 188perl_alloc(void)
79072805 189{
cea2e8a9 190 PerlInterpreter *my_perl;
79072805 191
54aff467 192 /* New() needs interpreter, so call malloc() instead */
e8ee3774 193 my_perl = (PerlInterpreter*)PerlMem_malloc(sizeof(PerlInterpreter));
ba869deb 194
e6827a76 195 S_init_tls_and_interp(my_perl);
07409e01 196 return (PerlInterpreter *) ZeroD(my_perl, 1, PerlInterpreter);
79072805 197}
32e30700 198#endif /* PERL_IMPLICIT_SYS */
79072805 199
954c1994
GS
200/*
201=for apidoc perl_construct
202
203Initializes a new Perl interpreter. See L<perlembed>.
204
205=cut
206*/
207
79072805 208void
0cb96387 209perl_construct(pTHXx)
79072805 210{
27da23d5 211 dVAR;
8990e307 212#ifdef MULTIPLICITY
54aff467 213 init_interp();
ac27b0f5 214 PL_perl_destruct_level = 1;
54aff467
GS
215#else
216 if (PL_perl_destruct_level > 0)
217 init_interp();
218#endif
33f46ff6 219 /* Init the real globals (and main thread)? */
3280af22 220 if (!PL_linestr) {
2aea9f8a
GS
221 PL_curcop = &PL_compiling; /* needed by ckWARN, right away */
222
3280af22
NIS
223 PL_linestr = NEWSV(65,79);
224 sv_upgrade(PL_linestr,SVt_PVIV);
79072805 225
3280af22 226 if (!SvREADONLY(&PL_sv_undef)) {
d689ffdd
JP
227 /* set read-only and try to insure than we wont see REFCNT==0
228 very often */
229
3280af22
NIS
230 SvREADONLY_on(&PL_sv_undef);
231 SvREFCNT(&PL_sv_undef) = (~(U32)0)/2;
79072805 232
3280af22 233 sv_setpv(&PL_sv_no,PL_No);
0309f36e
NC
234 /* value lookup in void context - happens to have the side effect
235 of caching the numeric forms. */
236 SvIV(&PL_sv_no);
3280af22
NIS
237 SvNV(&PL_sv_no);
238 SvREADONLY_on(&PL_sv_no);
239 SvREFCNT(&PL_sv_no) = (~(U32)0)/2;
79072805 240
3280af22 241 sv_setpv(&PL_sv_yes,PL_Yes);
0309f36e 242 SvIV(&PL_sv_yes);
3280af22
NIS
243 SvNV(&PL_sv_yes);
244 SvREADONLY_on(&PL_sv_yes);
245 SvREFCNT(&PL_sv_yes) = (~(U32)0)/2;
7996736c
MHM
246
247 SvREADONLY_on(&PL_sv_placeholder);
248 SvREFCNT(&PL_sv_placeholder) = (~(U32)0)/2;
6e72f9df 249 }
79072805 250
cea2e8a9 251 PL_sighandlerp = Perl_sighandler;
3280af22 252 PL_pidstatus = newHV();
79072805
LW
253 }
254
8bfdd7d9 255 PL_rs = newSVpvn("\n", 1);
dc92893f 256
cea2e8a9 257 init_stacks();
79072805 258
748a9306 259 init_ids();
3280af22 260 PL_lex_state = LEX_NOTPARSING;
a5f75d66 261
312caa8e 262 JMPENV_BOOTSTRAP;
f86702cc 263 STATUS_ALL_SUCCESS;
264
0672f40e 265 init_i18nl10n(1);
36477c24 266 SET_NUMERIC_STANDARD();
0b5b802d 267
ab821d7f 268#if defined(LOCAL_PATCH_COUNT)
3280af22 269 PL_localpatches = local_patches; /* For possible -v */
ab821d7f 270#endif
271
52853b95
GS
272#ifdef HAVE_INTERP_INTERN
273 sys_intern_init();
274#endif
275
3a1ee7e8 276 PerlIO_init(aTHX); /* Hook to IO system */
760ac839 277
3280af22
NIS
278 PL_fdpid = newAV(); /* for remembering popen pids by fd */
279 PL_modglobal = newHV(); /* pointers to per-interpreter module globals */
24944567 280 PL_errors = newSVpvn("",0);
48c6b404 281 sv_setpvn(PERL_DEBUG_PAD(0), "", 0); /* For regex debugging. */
1f483ca1
JH
282 sv_setpvn(PERL_DEBUG_PAD(1), "", 0); /* ext/re needs these */
283 sv_setpvn(PERL_DEBUG_PAD(2), "", 0); /* even without DEBUGGING. */
1fcf4c12 284#ifdef USE_ITHREADS
13137afc
AB
285 PL_regex_padav = newAV();
286 av_push(PL_regex_padav,(SV*)newAV()); /* First entry is an array of empty elements */
287 PL_regex_pad = AvARRAY(PL_regex_padav);
1fcf4c12 288#endif
e5dd39fc 289#ifdef USE_REENTRANT_API
59bd0823 290 Perl_reentrant_init(aTHX);
e5dd39fc 291#endif
3d47000e
AB
292
293 /* Note that strtab is a rather special HV. Assumptions are made
294 about not iterating on it, and not adding tie magic to it.
295 It is properly deallocated in perl_destruct() */
296 PL_strtab = newHV();
297
3d47000e
AB
298 HvSHAREKEYS_off(PL_strtab); /* mandatory */
299 hv_ksplit(PL_strtab, 512);
300
0631ea03
AB
301#if defined(__DYNAMIC__) && (defined(NeXT) || defined(__NeXT__))
302 _dyld_lookup_and_bind
303 ("__environ", (unsigned long *) &environ_pointer, NULL);
304#endif /* environ */
305
2f42fcb0
JH
306#ifndef PERL_MICRO
307# ifdef USE_ENVIRON_ARRAY
0631ea03 308 PL_origenviron = environ;
2f42fcb0 309# endif
0631ea03
AB
310#endif
311
5311654c 312 /* Use sysconf(_SC_CLK_TCK) if available, if not
dbc1d986 313 * available or if the sysconf() fails, use the HZ.
27da23d5
JH
314 * BeOS has those, but returns the wrong value.
315 * The HZ if not originally defined has been by now
316 * been defined as CLK_TCK, if available. */
dbc1d986 317#if defined(HAS_SYSCONF) && defined(_SC_CLK_TCK) && !defined(__BEOS__)
5311654c
JH
318 PL_clocktick = sysconf(_SC_CLK_TCK);
319 if (PL_clocktick <= 0)
320#endif
321 PL_clocktick = HZ;
322
081fc587
AB
323 PL_stashcache = newHV();
324
d7aa5382
JP
325 PL_patchlevel = newSVpv(
326 Perl_form(aTHX_ "%d.%d.%d",
327 (int)PERL_REVISION,
328 (int)PERL_VERSION,
329 (int)PERL_SUBVERSION ), 0
330 );
331
27da23d5
JH
332#ifdef HAS_MMAP
333 if (!PL_mmap_page_size) {
334#if defined(HAS_SYSCONF) && (defined(_SC_PAGESIZE) || defined(_SC_MMAP_PAGE_SIZE))
335 {
336 SETERRNO(0, SS_NORMAL);
337# ifdef _SC_PAGESIZE
338 PL_mmap_page_size = sysconf(_SC_PAGESIZE);
339# else
340 PL_mmap_page_size = sysconf(_SC_MMAP_PAGE_SIZE);
341# endif
342 if ((long) PL_mmap_page_size < 0) {
343 if (errno) {
344 SV *error = ERRSV;
27da23d5 345 (void) SvUPGRADE(error, SVt_PV);
0510663f 346 Perl_croak(aTHX_ "panic: sysconf: %s", SvPV_nolen_const(error));
27da23d5
JH
347 }
348 else
349 Perl_croak(aTHX_ "panic: sysconf: pagesize unknown");
350 }
351 }
352#else
353# ifdef HAS_GETPAGESIZE
354 PL_mmap_page_size = getpagesize();
355# else
356# if defined(I_SYS_PARAM) && defined(PAGESIZE)
357 PL_mmap_page_size = PAGESIZE; /* compiletime, bad */
358# endif
359# endif
360#endif
361 if (PL_mmap_page_size <= 0)
362 Perl_croak(aTHX_ "panic: bad pagesize %" IVdf,
363 (IV) PL_mmap_page_size);
364 }
365#endif /* HAS_MMAP */
366
367#if defined(HAS_TIMES) && defined(PERL_NEED_TIMESBASE)
368 PL_timesbase.tms_utime = 0;
369 PL_timesbase.tms_stime = 0;
370 PL_timesbase.tms_cutime = 0;
371 PL_timesbase.tms_cstime = 0;
372#endif
373
8990e307 374 ENTER;
79072805
LW
375}
376
954c1994 377/*
62375a60
NIS
378=for apidoc nothreadhook
379
380Stub that provides thread hook for perl_destruct when there are
381no threads.
382
383=cut
384*/
385
386int
4e9e3734 387Perl_nothreadhook(pTHX)
62375a60
NIS
388{
389 return 0;
390}
391
41e4abd8
NC
392#ifdef DEBUG_LEAKING_SCALARS_FORK_DUMP
393void
394Perl_dump_sv_child(pTHX_ SV *sv)
395{
396 ssize_t got;
397 int sock = PL_dumper_fd;
398 SV *target;
399
400 if(sock == -1)
401 return;
402
403 PerlIO_flush(Perl_debug_log);
404
405 got = write(sock, &sv, sizeof(sv));
406
407 if(got < 0) {
408 perror("Debug leaking scalars parent write failed");
409 abort();
410 }
411 if(got < sizeof(target)) {
412 perror("Debug leaking scalars parent short write");
413 abort();
414 }
415
416 got = read(sock, &target, sizeof(target));
417
418 if(got < 0) {
419 perror("Debug leaking scalars parent read failed");
420 abort();
421 }
422 if(got < sizeof(target)) {
423 perror("Debug leaking scalars parent short read");
424 abort();
425 }
426
427 if (target != sv) {
428 perror("Debug leaking scalars parent target != sv");
429 abort();
430 }
431}
432#endif
433
62375a60 434/*
954c1994
GS
435=for apidoc perl_destruct
436
437Shuts down a Perl interpreter. See L<perlembed>.
438
439=cut
440*/
441
31d77e54 442int
0cb96387 443perl_destruct(pTHXx)
79072805 444{
27da23d5 445 dVAR;
7c474504 446 volatile int destruct_level; /* 0=none, 1=full, 2=full with checks */
a0d0e21e 447 HV *hv;
2aa47728 448#ifdef DEBUG_LEAKING_SCALARS_FORK_DUMP
2aa47728
NC
449 pid_t child;
450#endif
8990e307 451
7766f137
GS
452 /* wait for all pseudo-forked children to finish */
453 PERL_WAIT_FOR_CHILDREN;
454
3280af22 455 destruct_level = PL_perl_destruct_level;
4633a7c4
LW
456#ifdef DEBUGGING
457 {
b7787f18 458 const char *s;
155aba94 459 if ((s = PerlEnv_getenv("PERL_DESTRUCT_LEVEL"))) {
e1ec3a88 460 const int i = atoi(s);
5f05dabc 461 if (destruct_level < i)
462 destruct_level = i;
463 }
4633a7c4
LW
464 }
465#endif
466
27da23d5 467 if (PL_exit_flags & PERL_EXIT_DESTRUCT_END) {
f3faeb53
AB
468 dJMPENV;
469 int x = 0;
470
471 JMPENV_PUSH(x);
1b6737cc 472 PERL_UNUSED_VAR(x);
f3faeb53
AB
473 if (PL_endav && !PL_minus_c)
474 call_list(PL_scopestack_ix, PL_endav);
475 JMPENV_POP;
26f423df 476 }
f3faeb53 477 LEAVE;
a0d0e21e
LW
478 FREETMPS;
479
e00b64d4 480 /* Need to flush since END blocks can produce output */
f13a2bc0 481 my_fflush_all();
e00b64d4 482
62375a60
NIS
483 if (CALL_FPTR(PL_threadhook)(aTHX)) {
484 /* Threads hook has vetoed further cleanup */
b47cad08 485 return STATUS_NATIVE_EXPORT;
62375a60
NIS
486 }
487
2aa47728
NC
488#ifdef DEBUG_LEAKING_SCALARS_FORK_DUMP
489 if (destruct_level != 0) {
490 /* Fork here to create a child. Our child's job is to preserve the
491 state of scalars prior to destruction, so that we can instruct it
492 to dump any scalars that we later find have leaked.
493 There's no subtlety in this code - it assumes POSIX, and it doesn't
494 fail gracefully */
495 int fd[2];
496
497 if(socketpair(AF_UNIX, SOCK_STREAM, 0, fd)) {
498 perror("Debug leaking scalars socketpair failed");
499 abort();
500 }
501
502 child = fork();
503 if(child == -1) {
504 perror("Debug leaking scalars fork failed");
505 abort();
506 }
507 if (!child) {
508 /* We are the child */
3125a5a4
NC
509
510 const int sock = fd[1];
511 const int debug_fd = PerlIO_fileno(Perl_debug_log);
512 int f;
513
2aa47728 514 close(fd[0]);
2aa47728 515
3125a5a4
NC
516 /* We need to close all other file descriptors otherwise we end up
517 with interesting hangs, where the parent closes its end of a
518 pipe, and sits waiting for (another) child to terminate. Only
519 that child never terminates, because it never gets EOF, because
520 we also have the far end of the pipe open. */
521
522 f = sysconf(_SC_OPEN_MAX);
523 if(f < 0) {
524 perror("Debug leaking scalars sysconf failed");
525 abort();
526 }
527 while (f--) {
528 if (f == sock)
529 continue;
530 if (f == debug_fd)
531 continue;
532 close(f);
533 }
534
2aa47728
NC
535 while (1) {
536 SV *target;
537 ssize_t got = read(sock, &target, sizeof(target));
538
539 if(got == 0)
540 break;
541 if(got < 0) {
542 perror("Debug leaking scalars child read failed");
543 abort();
544 }
545 if(got < sizeof(target)) {
546 perror("Debug leaking scalars child short read");
547 abort();
548 }
549 sv_dump(target);
550 PerlIO_flush(Perl_debug_log);
551
552 /* Write something back as synchronisation. */
553 got = write(sock, &target, sizeof(target));
554
555 if(got < 0) {
556 perror("Debug leaking scalars child write failed");
557 abort();
558 }
559 if(got < sizeof(target)) {
560 perror("Debug leaking scalars child short write");
561 abort();
562 }
563 }
564 _exit(0);
565 }
41e4abd8 566 PL_dumper_fd = fd[0];
2aa47728
NC
567 close(fd[1]);
568 }
569#endif
570
ff0cee69 571 /* We must account for everything. */
572
573 /* Destroy the main CV and syntax tree */
17fbfdf6
NC
574 /* Do this now, because destroying ops can cause new SVs to be generated
575 in Perl_pad_swipe, and when running with -DDEBUG_LEAKING_SCALARS they
576 PL_curcop to point to a valid op from which the filename structure
577 member is copied. */
578 PL_curcop = &PL_compiling;
3280af22 579 if (PL_main_root) {
4e380990
DM
580 /* ensure comppad/curpad to refer to main's pad */
581 if (CvPADLIST(PL_main_cv)) {
582 PAD_SET_CUR_NOSAVE(CvPADLIST(PL_main_cv), 1);
583 }
3280af22
NIS
584 op_free(PL_main_root);
585 PL_main_root = Nullop;
a0d0e21e 586 }
3280af22
NIS
587 PL_main_start = Nullop;
588 SvREFCNT_dec(PL_main_cv);
589 PL_main_cv = Nullcv;
24d3c518 590 PL_dirty = TRUE;
ff0cee69 591
13621cfb
NIS
592 /* Tell PerlIO we are about to tear things apart in case
593 we have layers which are using resources that should
594 be cleaned up now.
595 */
596
597 PerlIO_destruct(aTHX);
598
3280af22 599 if (PL_sv_objcount) {
a0d0e21e
LW
600 /*
601 * Try to destruct global references. We do this first so that the
602 * destructors and destructees still exist. Some sv's might remain.
603 * Non-referenced objects are on their own.
604 */
a0d0e21e 605 sv_clean_objs();
bf9cdc68 606 PL_sv_objcount = 0;
8990e307
LW
607 }
608
5cd24f17 609 /* unhook hooks which will soon be, or use, destroyed data */
3280af22
NIS
610 SvREFCNT_dec(PL_warnhook);
611 PL_warnhook = Nullsv;
612 SvREFCNT_dec(PL_diehook);
613 PL_diehook = Nullsv;
5cd24f17 614
4b556e6c 615 /* call exit list functions */
3280af22 616 while (PL_exitlistlen-- > 0)
acfe0abc 617 PL_exitlist[PL_exitlistlen].fn(aTHX_ PL_exitlist[PL_exitlistlen].ptr);
4b556e6c 618
3280af22 619 Safefree(PL_exitlist);
4b556e6c 620
1c4916e5
CB
621 PL_exitlist = NULL;
622 PL_exitlistlen = 0;
623
a0d0e21e 624 if (destruct_level == 0){
8990e307 625
a0d0e21e 626 DEBUG_P(debprofdump());
ac27b0f5 627
56a2bab7
NIS
628#if defined(PERLIO_LAYERS)
629 /* No more IO - including error messages ! */
630 PerlIO_cleanup(aTHX);
631#endif
632
a0d0e21e 633 /* The exit() function will do everything that needs doing. */
b47cad08 634 return STATUS_NATIVE_EXPORT;
a0d0e21e 635 }
5dd60ef7 636
551a8b83 637 /* jettison our possibly duplicated environment */
4b647fb0
DM
638 /* if PERL_USE_SAFE_PUTENV is defined environ will not have been copied
639 * so we certainly shouldn't free it here
640 */
2f42fcb0 641#ifndef PERL_MICRO
4b647fb0 642#if defined(USE_ENVIRON_ARRAY) && !defined(PERL_USE_SAFE_PUTENV)
50acdf95 643 if (environ != PL_origenviron && !PL_use_safe_putenv
4efc5df6
GS
644#ifdef USE_ITHREADS
645 /* only main thread can free environ[0] contents */
646 && PL_curinterp == aTHX
647#endif
648 )
649 {
551a8b83
JH
650 I32 i;
651
652 for (i = 0; environ[i]; i++)
4b420006 653 safesysfree(environ[i]);
0631ea03 654
4b420006
JH
655 /* Must use safesysfree() when working with environ. */
656 safesysfree(environ);
551a8b83
JH
657
658 environ = PL_origenviron;
659 }
660#endif
2f42fcb0 661#endif /* !PERL_MICRO */
551a8b83 662
804ffa60
DM
663 /* reset so print() ends up where we expect */
664 setdefout(Nullgv);
665
5f8cb046
DM
666#ifdef USE_ITHREADS
667 /* the syntax tree is shared between clones
668 * so op_free(PL_main_root) only ReREFCNT_dec's
669 * REGEXPs in the parent interpreter
670 * we need to manually ReREFCNT_dec for the clones
671 */
672 {
673 I32 i = AvFILLp(PL_regex_padav) + 1;
674 SV **ary = AvARRAY(PL_regex_padav);
675
676 while (i) {
35061a7e 677 SV *resv = ary[--i];
35061a7e
DM
678
679 if (SvFLAGS(resv) & SVf_BREAK) {
577e12cc 680 /* this is PL_reg_curpm, already freed
35061a7e
DM
681 * flag is set in regexec.c:S_regtry
682 */
683 SvFLAGS(resv) &= ~SVf_BREAK;
3a1ee7e8 684 }
1cc8b4c5
AB
685 else if(SvREPADTMP(resv)) {
686 SvREPADTMP_off(resv);
687 }
a560f29b
NC
688 else if(SvIOKp(resv)) {
689 REGEXP *re = INT2PTR(REGEXP *,SvIVX(resv));
5f8cb046
DM
690 ReREFCNT_dec(re);
691 }
692 }
693 }
694 SvREFCNT_dec(PL_regex_padav);
695 PL_regex_padav = Nullav;
696 PL_regex_pad = NULL;
697#endif
698
081fc587
AB
699 SvREFCNT_dec((SV*) PL_stashcache);
700 PL_stashcache = NULL;
701
5f05dabc 702 /* loosen bonds of global variables */
703
3280af22
NIS
704 if(PL_rsfp) {
705 (void)PerlIO_close(PL_rsfp);
706 PL_rsfp = Nullfp;
8ebc5c01 707 }
708
709 /* Filters for program text */
3280af22
NIS
710 SvREFCNT_dec(PL_rsfp_filters);
711 PL_rsfp_filters = Nullav;
8ebc5c01 712
713 /* switches */
3280af22
NIS
714 PL_preprocess = FALSE;
715 PL_minus_n = FALSE;
716 PL_minus_p = FALSE;
717 PL_minus_l = FALSE;
718 PL_minus_a = FALSE;
719 PL_minus_F = FALSE;
720 PL_doswitches = FALSE;
599cee73 721 PL_dowarn = G_WARN_OFF;
3280af22
NIS
722 PL_doextract = FALSE;
723 PL_sawampersand = FALSE; /* must save all match strings */
3280af22
NIS
724 PL_unsafe = FALSE;
725
726 Safefree(PL_inplace);
727 PL_inplace = Nullch;
a7cb1f99 728 SvREFCNT_dec(PL_patchlevel);
3280af22
NIS
729
730 if (PL_e_script) {
731 SvREFCNT_dec(PL_e_script);
732 PL_e_script = Nullsv;
8ebc5c01 733 }
734
bf9cdc68
RG
735 PL_perldb = 0;
736
8ebc5c01 737 /* magical thingies */
738
7889fe52
NIS
739 SvREFCNT_dec(PL_ofs_sv); /* $, */
740 PL_ofs_sv = Nullsv;
5f05dabc 741
7889fe52
NIS
742 SvREFCNT_dec(PL_ors_sv); /* $\ */
743 PL_ors_sv = Nullsv;
8ebc5c01 744
3280af22
NIS
745 SvREFCNT_dec(PL_rs); /* $/ */
746 PL_rs = Nullsv;
dc92893f 747
d33b2eba
GS
748 PL_multiline = 0; /* $* */
749 Safefree(PL_osname); /* $^O */
750 PL_osname = Nullch;
5f05dabc 751
3280af22
NIS
752 SvREFCNT_dec(PL_statname);
753 PL_statname = Nullsv;
754 PL_statgv = Nullgv;
5f05dabc 755
8ebc5c01 756 /* defgv, aka *_ should be taken care of elsewhere */
757
8ebc5c01 758 /* clean up after study() */
3280af22
NIS
759 SvREFCNT_dec(PL_lastscream);
760 PL_lastscream = Nullsv;
761 Safefree(PL_screamfirst);
762 PL_screamfirst = 0;
763 Safefree(PL_screamnext);
764 PL_screamnext = 0;
8ebc5c01 765
7d5ea4e7
GS
766 /* float buffer */
767 Safefree(PL_efloatbuf);
768 PL_efloatbuf = Nullch;
769 PL_efloatsize = 0;
770
8ebc5c01 771 /* startup and shutdown function lists */
3280af22 772 SvREFCNT_dec(PL_beginav);
5a837c8f 773 SvREFCNT_dec(PL_beginav_save);
3280af22 774 SvREFCNT_dec(PL_endav);
7d30b5c4 775 SvREFCNT_dec(PL_checkav);
ece599bd 776 SvREFCNT_dec(PL_checkav_save);
3280af22
NIS
777 SvREFCNT_dec(PL_initav);
778 PL_beginav = Nullav;
5a837c8f 779 PL_beginav_save = Nullav;
3280af22 780 PL_endav = Nullav;
7d30b5c4 781 PL_checkav = Nullav;
ece599bd 782 PL_checkav_save = Nullav;
3280af22 783 PL_initav = Nullav;
5618dfe8 784
8ebc5c01 785 /* shortcuts just get cleared */
3280af22 786 PL_envgv = Nullgv;
3280af22
NIS
787 PL_incgv = Nullgv;
788 PL_hintgv = Nullgv;
789 PL_errgv = Nullgv;
790 PL_argvgv = Nullgv;
791 PL_argvoutgv = Nullgv;
792 PL_stdingv = Nullgv;
bf49b057 793 PL_stderrgv = Nullgv;
3280af22
NIS
794 PL_last_in_gv = Nullgv;
795 PL_replgv = Nullgv;
bf9cdc68
RG
796 PL_DBgv = Nullgv;
797 PL_DBline = Nullgv;
798 PL_DBsub = Nullgv;
799 PL_DBsingle = Nullsv;
800 PL_DBtrace = Nullsv;
801 PL_DBsignal = Nullsv;
802 PL_DBassertion = Nullsv;
803 PL_DBcv = Nullcv;
804 PL_dbargs = Nullav;
5c831c24 805 PL_debstash = Nullhv;
8ebc5c01 806
7a1c5554
GS
807 SvREFCNT_dec(PL_argvout_stack);
808 PL_argvout_stack = Nullav;
8ebc5c01 809
5c831c24
GS
810 SvREFCNT_dec(PL_modglobal);
811 PL_modglobal = Nullhv;
812 SvREFCNT_dec(PL_preambleav);
813 PL_preambleav = Nullav;
814 SvREFCNT_dec(PL_subname);
815 PL_subname = Nullsv;
816 SvREFCNT_dec(PL_linestr);
817 PL_linestr = Nullsv;
818 SvREFCNT_dec(PL_pidstatus);
819 PL_pidstatus = Nullhv;
820 SvREFCNT_dec(PL_toptarget);
821 PL_toptarget = Nullsv;
822 SvREFCNT_dec(PL_bodytarget);
823 PL_bodytarget = Nullsv;
824 PL_formtarget = Nullsv;
825
d33b2eba 826 /* free locale stuff */
b9582b6a 827#ifdef USE_LOCALE_COLLATE
d33b2eba
GS
828 Safefree(PL_collation_name);
829 PL_collation_name = Nullch;
b9582b6a 830#endif
d33b2eba 831
b9582b6a 832#ifdef USE_LOCALE_NUMERIC
d33b2eba
GS
833 Safefree(PL_numeric_name);
834 PL_numeric_name = Nullch;
a453c169 835 SvREFCNT_dec(PL_numeric_radix_sv);
bf9cdc68 836 PL_numeric_radix_sv = Nullsv;
b9582b6a 837#endif
d33b2eba 838
5c831c24
GS
839 /* clear utf8 character classes */
840 SvREFCNT_dec(PL_utf8_alnum);
841 SvREFCNT_dec(PL_utf8_alnumc);
842 SvREFCNT_dec(PL_utf8_ascii);
843 SvREFCNT_dec(PL_utf8_alpha);
844 SvREFCNT_dec(PL_utf8_space);
845 SvREFCNT_dec(PL_utf8_cntrl);
846 SvREFCNT_dec(PL_utf8_graph);
847 SvREFCNT_dec(PL_utf8_digit);
848 SvREFCNT_dec(PL_utf8_upper);
849 SvREFCNT_dec(PL_utf8_lower);
850 SvREFCNT_dec(PL_utf8_print);
851 SvREFCNT_dec(PL_utf8_punct);
852 SvREFCNT_dec(PL_utf8_xdigit);
853 SvREFCNT_dec(PL_utf8_mark);
854 SvREFCNT_dec(PL_utf8_toupper);
4dbdbdc2 855 SvREFCNT_dec(PL_utf8_totitle);
5c831c24 856 SvREFCNT_dec(PL_utf8_tolower);
b4e400f9 857 SvREFCNT_dec(PL_utf8_tofold);
82686b01
JH
858 SvREFCNT_dec(PL_utf8_idstart);
859 SvREFCNT_dec(PL_utf8_idcont);
5c831c24
GS
860 PL_utf8_alnum = Nullsv;
861 PL_utf8_alnumc = Nullsv;
862 PL_utf8_ascii = Nullsv;
863 PL_utf8_alpha = Nullsv;
864 PL_utf8_space = Nullsv;
865 PL_utf8_cntrl = Nullsv;
866 PL_utf8_graph = Nullsv;
867 PL_utf8_digit = Nullsv;
868 PL_utf8_upper = Nullsv;
869 PL_utf8_lower = Nullsv;
870 PL_utf8_print = Nullsv;
871 PL_utf8_punct = Nullsv;
872 PL_utf8_xdigit = Nullsv;
873 PL_utf8_mark = Nullsv;
874 PL_utf8_toupper = Nullsv;
875 PL_utf8_totitle = Nullsv;
876 PL_utf8_tolower = Nullsv;
b4e400f9 877 PL_utf8_tofold = Nullsv;
82686b01
JH
878 PL_utf8_idstart = Nullsv;
879 PL_utf8_idcont = Nullsv;
5c831c24 880
971a9dd3
GS
881 if (!specialWARN(PL_compiling.cop_warnings))
882 SvREFCNT_dec(PL_compiling.cop_warnings);
5c831c24 883 PL_compiling.cop_warnings = Nullsv;
ac27b0f5
NIS
884 if (!specialCopIO(PL_compiling.cop_io))
885 SvREFCNT_dec(PL_compiling.cop_io);
886 PL_compiling.cop_io = Nullsv;
05ec9bb3
NIS
887 CopFILE_free(&PL_compiling);
888 CopSTASH_free(&PL_compiling);
5c831c24 889
a0d0e21e 890 /* Prepare to destruct main symbol table. */
5f05dabc 891
3280af22
NIS
892 hv = PL_defstash;
893 PL_defstash = 0;
a0d0e21e 894 SvREFCNT_dec(hv);
5c831c24
GS
895 SvREFCNT_dec(PL_curstname);
896 PL_curstname = Nullsv;
a0d0e21e 897
5a844595
GS
898 /* clear queued errors */
899 SvREFCNT_dec(PL_errors);
900 PL_errors = Nullsv;
901
a0d0e21e 902 FREETMPS;
0453d815 903 if (destruct_level >= 2 && ckWARN_d(WARN_INTERNAL)) {
3280af22 904 if (PL_scopestack_ix != 0)
9014280d 905 Perl_warner(aTHX_ packWARN(WARN_INTERNAL),
0453d815 906 "Unbalanced scopes: %ld more ENTERs than LEAVEs\n",
3280af22
NIS
907 (long)PL_scopestack_ix);
908 if (PL_savestack_ix != 0)
9014280d 909 Perl_warner(aTHX_ packWARN(WARN_INTERNAL),
0453d815 910 "Unbalanced saves: %ld more saves than restores\n",
3280af22
NIS
911 (long)PL_savestack_ix);
912 if (PL_tmps_floor != -1)
9014280d 913 Perl_warner(aTHX_ packWARN(WARN_INTERNAL),"Unbalanced tmps: %ld more allocs than frees\n",
3280af22 914 (long)PL_tmps_floor + 1);
a0d0e21e 915 if (cxstack_ix != -1)
9014280d 916 Perl_warner(aTHX_ packWARN(WARN_INTERNAL),"Unbalanced context: %ld more PUSHes than POPs\n",
ff0cee69 917 (long)cxstack_ix + 1);
a0d0e21e 918 }
8990e307
LW
919
920 /* Now absolutely destruct everything, somehow or other, loops or no. */
d33b2eba 921 SvFLAGS(PL_fdpid) |= SVTYPEMASK; /* don't clean out pid table now */
3280af22 922 SvFLAGS(PL_strtab) |= SVTYPEMASK; /* don't clean out strtab now */
5226ed68
JH
923
924 /* the 2 is for PL_fdpid and PL_strtab */
925 while (PL_sv_count > 2 && sv_clean_all())
926 ;
927
d33b2eba
GS
928 SvFLAGS(PL_fdpid) &= ~SVTYPEMASK;
929 SvFLAGS(PL_fdpid) |= SVt_PVAV;
3280af22
NIS
930 SvFLAGS(PL_strtab) &= ~SVTYPEMASK;
931 SvFLAGS(PL_strtab) |= SVt_PVHV;
d33b2eba 932
d4777f27
GS
933 AvREAL_off(PL_fdpid); /* no surviving entries */
934 SvREFCNT_dec(PL_fdpid); /* needed in io_close() */
d33b2eba
GS
935 PL_fdpid = Nullav;
936
6c644e78
GS
937#ifdef HAVE_INTERP_INTERN
938 sys_intern_clear();
939#endif
940
6e72f9df 941 /* Destruct the global string table. */
942 {
943 /* Yell and reset the HeVAL() slots that are still holding refcounts,
944 * so that sv_free() won't fail on them.
80459961
NC
945 * Now that the global string table is using a single hunk of memory
946 * for both HE and HEK, we either need to explicitly unshare it the
947 * correct way, or actually free things here.
6e72f9df 948 */
80459961
NC
949 I32 riter = 0;
950 const I32 max = HvMAX(PL_strtab);
951 HE **array = HvARRAY(PL_strtab);
952 HE *hent = array[0];
953
6e72f9df 954 for (;;) {
0453d815 955 if (hent && ckWARN_d(WARN_INTERNAL)) {
80459961 956 HE *next = HeNEXT(hent);
9014280d 957 Perl_warner(aTHX_ packWARN(WARN_INTERNAL),
0453d815 958 "Unbalanced string table refcount: (%d) for \"%s\"",
6e72f9df 959 HeVAL(hent) - Nullsv, HeKEY(hent));
80459961
NC
960 Safefree(hent);
961 hent = next;
6e72f9df 962 }
963 if (!hent) {
964 if (++riter > max)
965 break;
966 hent = array[riter];
967 }
968 }
80459961
NC
969
970 Safefree(array);
971 HvARRAY(PL_strtab) = 0;
972 HvTOTALKEYS(PL_strtab) = 0;
973 HvFILL(PL_strtab) = 0;
6e72f9df 974 }
3280af22 975 SvREFCNT_dec(PL_strtab);
6e72f9df 976
e652bb2f 977#ifdef USE_ITHREADS
c21d1a0f 978 /* free the pointer tables used for cloning */
a0739874 979 ptr_table_free(PL_ptr_table);
bf9cdc68 980 PL_ptr_table = (PTR_TBL_t*)NULL;
53186e96 981#endif
a0739874 982
d33b2eba
GS
983 /* free special SVs */
984
985 SvREFCNT(&PL_sv_yes) = 0;
986 sv_clear(&PL_sv_yes);
987 SvANY(&PL_sv_yes) = NULL;
4c5e2b0d 988 SvFLAGS(&PL_sv_yes) = 0;
d33b2eba
GS
989
990 SvREFCNT(&PL_sv_no) = 0;
991 sv_clear(&PL_sv_no);
992 SvANY(&PL_sv_no) = NULL;
4c5e2b0d 993 SvFLAGS(&PL_sv_no) = 0;
01724ea0 994
9f375a43
DM
995 {
996 int i;
997 for (i=0; i<=2; i++) {
998 SvREFCNT(PERL_DEBUG_PAD(i)) = 0;
999 sv_clear(PERL_DEBUG_PAD(i));
1000 SvANY(PERL_DEBUG_PAD(i)) = NULL;
1001 SvFLAGS(PERL_DEBUG_PAD(i)) = 0;
1002 }
1003 }
1004
0453d815 1005 if (PL_sv_count != 0 && ckWARN_d(WARN_INTERNAL))
9014280d 1006 Perl_warner(aTHX_ packWARN(WARN_INTERNAL),"Scalars leaked: %ld\n", (long)PL_sv_count);
6e72f9df 1007
eba0f806
DM
1008#ifdef DEBUG_LEAKING_SCALARS
1009 if (PL_sv_count != 0) {
1010 SV* sva;
1011 SV* sv;
1012 register SV* svend;
1013
1014 for (sva = PL_sv_arenaroot; sva; sva = (SV*)SvANY(sva)) {
1015 svend = &sva[SvREFCNT(sva)];
1016 for (sv = sva + 1; sv < svend; ++sv) {
1017 if (SvTYPE(sv) != SVTYPEMASK) {
a548cda8 1018 PerlIO_printf(Perl_debug_log, "leaked: sv=0x%p"
61b61456 1019 " flags=0x%"UVxf
fd0854ff
DM
1020 " refcnt=%"UVuf pTHX__FORMAT "\n"
1021 "\tallocated at %s:%d %s %s%s\n",
1022 sv, sv->sv_flags, sv->sv_refcnt pTHX__VALUE,
1023 sv->sv_debug_file ? sv->sv_debug_file : "(unknown)",
1024 sv->sv_debug_line,
1025 sv->sv_debug_inpad ? "for" : "by",
1026 sv->sv_debug_optype ?
1027 PL_op_name[sv->sv_debug_optype]: "(none)",
1028 sv->sv_debug_cloned ? " (cloned)" : ""
1029 );
2aa47728 1030#ifdef DEBUG_LEAKING_SCALARS_FORK_DUMP
41e4abd8 1031 Perl_dump_sv_child(aTHX_ sv);
2aa47728 1032#endif
eba0f806
DM
1033 }
1034 }
1035 }
1036 }
2aa47728
NC
1037#ifdef DEBUG_LEAKING_SCALARS_FORK_DUMP
1038 {
1039 int status;
1040 fd_set rset;
1041 /* Wait for up to 4 seconds for child to terminate.
1042 This seems to be the least effort way of timing out on reaping
1043 its exit status. */
1044 struct timeval waitfor = {4, 0};
41e4abd8 1045 int sock = PL_dumper_fd;
2aa47728
NC
1046
1047 shutdown(sock, 1);
1048 FD_ZERO(&rset);
1049 FD_SET(sock, &rset);
1050 select(sock + 1, &rset, NULL, NULL, &waitfor);
1051 waitpid(child, &status, WNOHANG);
1052 close(sock);
1053 }
1054#endif
eba0f806 1055#endif
bf9cdc68 1056 PL_sv_count = 0;
eba0f806
DM
1057
1058
56a2bab7 1059#if defined(PERLIO_LAYERS)
3a1ee7e8
NIS
1060 /* No more IO - including error messages ! */
1061 PerlIO_cleanup(aTHX);
1062#endif
1063
9f4bd222
NIS
1064 /* sv_undef needs to stay immortal until after PerlIO_cleanup
1065 as currently layers use it rather than Nullsv as a marker
1066 for no arg - and will try and SvREFCNT_dec it.
1067 */
1068 SvREFCNT(&PL_sv_undef) = 0;
1069 SvREADONLY_off(&PL_sv_undef);
1070
3280af22 1071 Safefree(PL_origfilename);
bf9cdc68 1072 PL_origfilename = Nullch;
3280af22 1073 Safefree(PL_reg_start_tmp);
bf9cdc68
RG
1074 PL_reg_start_tmp = (char**)NULL;
1075 PL_reg_start_tmpl = 0;
5c5e4c24
IZ
1076 if (PL_reg_curpm)
1077 Safefree(PL_reg_curpm);
82ba1be6 1078 Safefree(PL_reg_poscache);
dd28f7bb 1079 free_tied_hv_pool();
3280af22 1080 Safefree(PL_op_mask);
cf36064f 1081 Safefree(PL_psig_ptr);
bf9cdc68 1082 PL_psig_ptr = (SV**)NULL;
cf36064f 1083 Safefree(PL_psig_name);
bf9cdc68 1084 PL_psig_name = (SV**)NULL;
2c2666fc 1085 Safefree(PL_bitcount);
bf9cdc68 1086 PL_bitcount = Nullch;
ce08f86c 1087 Safefree(PL_psig_pend);
bf9cdc68
RG
1088 PL_psig_pend = (int*)NULL;
1089 PL_formfeed = Nullsv;
6e72f9df 1090 nuke_stacks();
bf9cdc68
RG
1091 PL_tainting = FALSE;
1092 PL_taint_warn = FALSE;
3280af22 1093 PL_hints = 0; /* Reset hints. Should hints be per-interpreter ? */
bf9cdc68 1094 PL_debug = 0;
ac27b0f5 1095
a0d0e21e 1096 DEBUG_P(debprofdump());
d33b2eba 1097
e5dd39fc 1098#ifdef USE_REENTRANT_API
10bc17b6 1099 Perl_reentrant_free(aTHX);
e5dd39fc
AB
1100#endif
1101
612f20c3
GS
1102 sv_free_arenas();
1103
fc36a67e 1104 /* As the absolutely last thing, free the non-arena SV for mess() */
1105
3280af22 1106 if (PL_mess_sv) {
f350b448
NC
1107 /* we know that type == SVt_PVMG */
1108
9c63abab 1109 /* it could have accumulated taint magic */
f350b448
NC
1110 MAGIC* mg;
1111 MAGIC* moremagic;
1112 for (mg = SvMAGIC(PL_mess_sv); mg; mg = moremagic) {
1113 moremagic = mg->mg_moremagic;
1114 if (mg->mg_ptr && mg->mg_type != PERL_MAGIC_regex_global
1115 && mg->mg_len >= 0)
1116 Safefree(mg->mg_ptr);
1117 Safefree(mg);
9c63abab 1118 }
f350b448 1119
fc36a67e 1120 /* we know that type >= SVt_PV */
8bd4d4c5 1121 SvPV_free(PL_mess_sv);
3280af22
NIS
1122 Safefree(SvANY(PL_mess_sv));
1123 Safefree(PL_mess_sv);
1124 PL_mess_sv = Nullsv;
fc36a67e 1125 }
31d77e54 1126 return STATUS_NATIVE_EXPORT;
79072805
LW
1127}
1128
954c1994
GS
1129/*
1130=for apidoc perl_free
1131
1132Releases a Perl interpreter. See L<perlembed>.
1133
1134=cut
1135*/
1136
79072805 1137void
0cb96387 1138perl_free(pTHXx)
79072805 1139{
acfe0abc 1140#if defined(WIN32) || defined(NETWARE)
ce3e5b80 1141# if defined(PERL_IMPLICIT_SYS)
acfe0abc
GS
1142# ifdef NETWARE
1143 void *host = nw_internal_host;
1144# else
1145 void *host = w32_internal_host;
1146# endif
ce3e5b80 1147 PerlMem_free(aTHXx);
acfe0abc 1148# ifdef NETWARE
011f1a1a 1149 nw_delete_internal_host(host);
acfe0abc
GS
1150# else
1151 win32_delete_internal_host(host);
1152# endif
1c0ca838
GS
1153# else
1154 PerlMem_free(aTHXx);
1155# endif
acfe0abc
GS
1156#else
1157 PerlMem_free(aTHXx);
76e3520e 1158#endif
79072805
LW
1159}
1160
aebd1ac7
GA
1161#if defined(USE_5005THREADS) || defined(USE_ITHREADS)
1162/* provide destructors to clean up the thread key when libperl is unloaded */
1163#ifndef WIN32 /* handled during DLL_PROCESS_DETACH in win32/perllib.c */
1164
110d3f98 1165#if defined(__hpux) && __ux_version > 1020 && !defined(__GNUC__)
aebd1ac7
GA
1166#pragma fini "perl_fini"
1167#endif
1168
0dbb1585
AL
1169static void
1170#if defined(__GNUC__)
1171__attribute__((destructor))
aebd1ac7 1172#endif
de009b76 1173perl_fini(void)
aebd1ac7 1174{
27da23d5 1175 dVAR;
aebd1ac7
GA
1176 if (PL_curinterp)
1177 FREE_THREAD_KEY;
1178}
1179
1180#endif /* WIN32 */
1181#endif /* THREADS */
1182
4b556e6c 1183void
864dbfa3 1184Perl_call_atexit(pTHX_ ATEXIT_t fn, void *ptr)
4b556e6c 1185{
3280af22
NIS
1186 Renew(PL_exitlist, PL_exitlistlen+1, PerlExitListEntry);
1187 PL_exitlist[PL_exitlistlen].fn = fn;
1188 PL_exitlist[PL_exitlistlen].ptr = ptr;
1189 ++PL_exitlistlen;
4b556e6c
JD
1190}
1191
56cf6df8
RGS
1192#ifdef HAS_PROCSELFEXE
1193/* This is a function so that we don't hold on to MAXPATHLEN
1194 bytes of stack longer than necessary
1195 */
1196STATIC void
e1ec3a88 1197S_procself_val(pTHX_ SV *sv, const char *arg0)
56cf6df8
RGS
1198{
1199 char buf[MAXPATHLEN];
1200 int len = readlink(PROCSELFEXE_PATH, buf, sizeof(buf) - 1);
1201
1202 /* On Playstation2 Linux V1.0 (kernel 2.2.1) readlink(/proc/self/exe)
1203 includes a spurious NUL which will cause $^X to fail in system
1204 or backticks (this will prevent extensions from being built and
1205 many tests from working). readlink is not meant to add a NUL.
1206 Normal readlink works fine.
1207 */
1208 if (len > 0 && buf[len-1] == '\0') {
1209 len--;
1210 }
1211
1212 /* FreeBSD's implementation is acknowledged to be imperfect, sometimes
1213 returning the text "unknown" from the readlink rather than the path
1214 to the executable (or returning an error from the readlink). Any valid
1215 path has a '/' in it somewhere, so use that to validate the result.
1216 See http://www.freebsd.org/cgi/query-pr.cgi?pr=35703
1217 */
1218 if (len > 0 && memchr(buf, '/', len)) {
1219 sv_setpvn(sv,buf,len);
1220 }
1221 else {
1222 sv_setpv(sv,arg0);
1223 }
1224}
1225#endif /* HAS_PROCSELFEXE */
b7975bdd
NC
1226
1227STATIC void
1228S_set_caret_X(pTHX) {
1229 GV* tmpgv = gv_fetchpv("\030",TRUE, SVt_PV); /* $^X */
1230 if (tmpgv) {
1231#ifdef HAS_PROCSELFEXE
1232 S_procself_val(aTHX_ GvSV(tmpgv), PL_origargv[0]);
1233#else
1234#ifdef OS2
1235 sv_setpv(GvSV(tmpgv), os2_execname(aTHX));
1236#else
1237 sv_setpv(GvSV(tmpgv),PL_origargv[0]);
1238#endif
1239#endif
1240 }
1241}
1242
954c1994
GS
1243/*
1244=for apidoc perl_parse
1245
1246Tells a Perl interpreter to parse a Perl script. See L<perlembed>.
1247
1248=cut
1249*/
1250
79072805 1251int
0cb96387 1252perl_parse(pTHXx_ XSINIT_t xsinit, int argc, char **argv, char **env)
8d063cd8 1253{
27da23d5 1254 dVAR;
6224f72b 1255 I32 oldscope;
6224f72b 1256 int ret;
db36c5a1 1257 dJMPENV;
8d063cd8 1258
a687059c
LW
1259#ifdef SETUID_SCRIPTS_ARE_SECURE_NOW
1260#ifdef IAMSUID
1261#undef IAMSUID
cea2e8a9 1262 Perl_croak(aTHX_ "suidperl is no longer needed since the kernel can now execute\n\
a687059c 1263setuid perl scripts securely.\n");
ae3f3efd 1264#endif /* IAMSUID */
a687059c
LW
1265#endif
1266
b0891165
JH
1267#if defined(USE_HASH_SEED) || defined(USE_HASH_SEED_EXPLICIT)
1268 /* [perl #22371] Algorimic Complexity Attack on Perl 5.6.1, 5.8.0
103dd899 1269 * This MUST be done before any hash stores or fetches take place.
008fb0c0
NC
1270 * If you set PL_rehash_seed (and assumedly also PL_rehash_seed_set)
1271 * yourself, it is your responsibility to provide a good random seed!
830b38bd 1272 * You can also define PERL_HASH_SEED in compile time, see hv.h. */
008fb0c0
NC
1273 if (!PL_rehash_seed_set)
1274 PL_rehash_seed = get_hash_seed();
b0891165 1275 {
1b6737cc 1276 const char *s = PerlEnv_getenv("PERL_HASH_SEED_DEBUG");
bed60192 1277
1b6737cc
AL
1278 if (s && (atoi(s) == 1))
1279 PerlIO_printf(Perl_debug_log, "HASH_SEED = %"UVuf"\n", PL_rehash_seed);
b0891165
JH
1280 }
1281#endif /* #if defined(USE_HASH_SEED) || defined(USE_HASH_SEED_EXPLICIT) */
1282
3280af22 1283 PL_origargc = argc;
e2975953 1284 PL_origargv = argv;
a0d0e21e 1285
54bfe034 1286 {
3cb9023d
JH
1287 /* Set PL_origalen be the sum of the contiguous argv[]
1288 * elements plus the size of the env in case that it is
e9137a8e 1289 * contiguous with the argv[]. This is used in mg.c:Perl_magic_set()
3cb9023d
JH
1290 * as the maximum modifiable length of $0. In the worst case
1291 * the area we are able to modify is limited to the size of
43c32782 1292 * the original argv[0]. (See below for 'contiguous', though.)
3cb9023d 1293 * --jhi */
e1ec3a88 1294 const char *s = NULL;
54bfe034 1295 int i;
1b6737cc 1296 const UV mask =
7d8e7db3 1297 ~(UV)(PTRSIZE == 4 ? 3 : PTRSIZE == 8 ? 7 : PTRSIZE == 16 ? 15 : 0);
43c32782 1298 /* Do the mask check only if the args seem like aligned. */
1b6737cc 1299 const UV aligned =
43c32782
JH
1300 (mask < ~(UV)0) && ((PTR2UV(argv[0]) & mask) == PTR2UV(argv[0]));
1301
1302 /* See if all the arguments are contiguous in memory. Note
1303 * that 'contiguous' is a loose term because some platforms
1304 * align the argv[] and the envp[]. If the arguments look
1305 * like non-aligned, assume that they are 'strictly' or
1306 * 'traditionally' contiguous. If the arguments look like
1307 * aligned, we just check that they are within aligned
1308 * PTRSIZE bytes. As long as no system has something bizarre
1309 * like the argv[] interleaved with some other data, we are
1310 * fine. (Did I just evoke Murphy's Law?) --jhi */
c8941eeb
JH
1311 if (PL_origargv && PL_origargc >= 1 && (s = PL_origargv[0])) {
1312 while (*s) s++;
1313 for (i = 1; i < PL_origargc; i++) {
1314 if ((PL_origargv[i] == s + 1
43c32782 1315#ifdef OS2
c8941eeb 1316 || PL_origargv[i] == s + 2
43c32782 1317#endif
c8941eeb
JH
1318 )
1319 ||
1320 (aligned &&
1321 (PL_origargv[i] > s &&
1322 PL_origargv[i] <=
1323 INT2PTR(char *, PTR2UV(s + PTRSIZE) & mask)))
1324 )
1325 {
1326 s = PL_origargv[i];
1327 while (*s) s++;
1328 }
1329 else
1330 break;
54bfe034 1331 }
54bfe034 1332 }
3cb9023d 1333 /* Can we grab env area too to be used as the area for $0? */
43c32782
JH
1334 if (PL_origenviron) {
1335 if ((PL_origenviron[0] == s + 1
1336#ifdef OS2
1337 || (PL_origenviron[0] == s + 9 && (s += 8))
1338#endif
1339 )
1340 ||
1341 (aligned &&
1342 (PL_origenviron[0] > s &&
1343 PL_origenviron[0] <=
1344 INT2PTR(char *, PTR2UV(s + PTRSIZE) & mask)))
1345 )
1346 {
1347#ifndef OS2
1348 s = PL_origenviron[0];
1349 while (*s) s++;
1350#endif
1351 my_setenv("NoNe SuCh", Nullch);
1352 /* Force copy of environment. */
1353 for (i = 1; PL_origenviron[i]; i++) {
1354 if (PL_origenviron[i] == s + 1
1355 ||
1356 (aligned &&
1357 (PL_origenviron[i] > s &&
1358 PL_origenviron[i] <=
1359 INT2PTR(char *, PTR2UV(s + PTRSIZE) & mask)))
1360 )
1361 {
1362 s = PL_origenviron[i];
1363 while (*s) s++;
1364 }
1365 else
1366 break;
54bfe034 1367 }
43c32782 1368 }
54bfe034 1369 }
284e1220 1370 PL_origalen = s - PL_origargv[0] + 1;
54bfe034
JH
1371 }
1372
3280af22 1373 if (PL_do_undump) {
a0d0e21e
LW
1374
1375 /* Come here if running an undumped a.out. */
1376
3280af22
NIS
1377 PL_origfilename = savepv(argv[0]);
1378 PL_do_undump = FALSE;
a0d0e21e 1379 cxstack_ix = -1; /* start label stack again */
748a9306 1380 init_ids();
b7975bdd
NC
1381 assert (!PL_tainted);
1382 TAINT;
1383 S_set_caret_X(aTHX);
1384 TAINT_NOT;
a0d0e21e
LW
1385 init_postdump_symbols(argc,argv,env);
1386 return 0;
1387 }
1388
3280af22 1389 if (PL_main_root) {
3280af22
NIS
1390 op_free(PL_main_root);
1391 PL_main_root = Nullop;
ff0cee69 1392 }
3280af22
NIS
1393 PL_main_start = Nullop;
1394 SvREFCNT_dec(PL_main_cv);
1395 PL_main_cv = Nullcv;
79072805 1396
3280af22
NIS
1397 time(&PL_basetime);
1398 oldscope = PL_scopestack_ix;
599cee73 1399 PL_dowarn = G_WARN_OFF;
f86702cc 1400
14dd3ad8 1401 JMPENV_PUSH(ret);
6224f72b 1402 switch (ret) {
312caa8e 1403 case 0:
14dd3ad8 1404 parse_body(env,xsinit);
7d30b5c4
GS
1405 if (PL_checkav)
1406 call_list(oldscope, PL_checkav);
14dd3ad8
GS
1407 ret = 0;
1408 break;
6224f72b
GS
1409 case 1:
1410 STATUS_ALL_FAILURE;
1411 /* FALL THROUGH */
1412 case 2:
1413 /* my_exit() was called */
3280af22 1414 while (PL_scopestack_ix > oldscope)
6224f72b
GS
1415 LEAVE;
1416 FREETMPS;
3280af22 1417 PL_curstash = PL_defstash;
7d30b5c4
GS
1418 if (PL_checkav)
1419 call_list(oldscope, PL_checkav);
14dd3ad8
GS
1420 ret = STATUS_NATIVE_EXPORT;
1421 break;
6224f72b 1422 case 3:
bf49b057 1423 PerlIO_printf(Perl_error_log, "panic: top_env\n");
14dd3ad8
GS
1424 ret = 1;
1425 break;
6224f72b 1426 }
14dd3ad8
GS
1427 JMPENV_POP;
1428 return ret;
1429}
1430
312caa8e 1431STATIC void *
14dd3ad8 1432S_parse_body(pTHX_ char **env, XSINIT_t xsinit)
312caa8e 1433{
27da23d5 1434 dVAR;
312caa8e 1435 int argc = PL_origargc;
8f42b153 1436 char **argv = PL_origargv;
e1ec3a88 1437 const char *scriptname = NULL;
312caa8e 1438 VOL bool dosearch = FALSE;
e1ec3a88 1439 const char *validarg = "";
312caa8e
CS
1440 register SV *sv;
1441 register char *s;
e1ec3a88 1442 const char *cddir = Nullch;
ab019eaa 1443#ifdef USE_SITECUSTOMIZE
20ef40cf 1444 bool minus_f = FALSE;
ab019eaa 1445#endif
312caa8e 1446
ae3f3efd
PS
1447 PL_fdscript = -1;
1448 PL_suidscript = -1;
3280af22 1449 sv_setpvn(PL_linestr,"",0);
79cb57f6 1450 sv = newSVpvn("",0); /* first used for -I flags */
6224f72b
GS
1451 SAVEFREESV(sv);
1452 init_main_stash();
54310121 1453
6224f72b
GS
1454 for (argc--,argv++; argc > 0; argc--,argv++) {
1455 if (argv[0][0] != '-' || !argv[0][1])
1456 break;
1457#ifdef DOSUID
1458 if (*validarg)
1459 validarg = " PHOOEY ";
1460 else
1461 validarg = argv[0];
ae3f3efd
PS
1462 /*
1463 * Can we rely on the kernel to start scripts with argv[1] set to
1464 * contain all #! line switches (the whole line)? (argv[0] is set to
1465 * the interpreter name, argv[2] to the script name; argv[3] and
1466 * above may contain other arguments.)
1467 */
13281fa4 1468#endif
6224f72b
GS
1469 s = argv[0]+1;
1470 reswitch:
1471 switch (*s) {
729a02f2 1472 case 'C':
1d5472a9
GS
1473#ifndef PERL_STRICT_CR
1474 case '\r':
1475#endif
6224f72b
GS
1476 case ' ':
1477 case '0':
1478 case 'F':
1479 case 'a':
1480 case 'c':
1481 case 'd':
1482 case 'D':
1483 case 'h':
1484 case 'i':
1485 case 'l':
1486 case 'M':
1487 case 'm':
1488 case 'n':
1489 case 'p':
1490 case 's':
1491 case 'u':
1492 case 'U':
1493 case 'v':
599cee73
PM
1494 case 'W':
1495 case 'X':
6224f72b 1496 case 'w':
06492da6 1497 case 'A':
155aba94 1498 if ((s = moreswitches(s)))
6224f72b
GS
1499 goto reswitch;
1500 break;
33b78306 1501
1dbad523 1502 case 't':
22f7c9c9 1503 CHECK_MALLOC_TOO_LATE_FOR('t');
317ea90d
MS
1504 if( !PL_tainting ) {
1505 PL_taint_warn = TRUE;
1506 PL_tainting = TRUE;
1507 }
1508 s++;
1509 goto reswitch;
6224f72b 1510 case 'T':
22f7c9c9 1511 CHECK_MALLOC_TOO_LATE_FOR('T');
3280af22 1512 PL_tainting = TRUE;
317ea90d 1513 PL_taint_warn = FALSE;
6224f72b
GS
1514 s++;
1515 goto reswitch;
f86702cc 1516
6224f72b 1517 case 'e':
bf4acbe4
GS
1518#ifdef MACOS_TRADITIONAL
1519 /* ignore -e for Dev:Pseudo argument */
1520 if (argv[1] && !strcmp(argv[1], "Dev:Pseudo"))
e55ac0fa 1521 break;
bf4acbe4 1522#endif
ae3f3efd 1523 forbid_setid("-e");
3280af22 1524 if (!PL_e_script) {
79cb57f6 1525 PL_e_script = newSVpvn("",0);
0cb96387 1526 filter_add(read_e_script, NULL);
6224f72b
GS
1527 }
1528 if (*++s)
3280af22 1529 sv_catpv(PL_e_script, s);
6224f72b 1530 else if (argv[1]) {
3280af22 1531 sv_catpv(PL_e_script, argv[1]);
6224f72b
GS
1532 argc--,argv++;
1533 }
1534 else
cea2e8a9 1535 Perl_croak(aTHX_ "No code specified for -e");
3280af22 1536 sv_catpv(PL_e_script, "\n");
6224f72b 1537 break;
afe37c7d 1538
20ef40cf 1539 case 'f':
f5542d3a 1540#ifdef USE_SITECUSTOMIZE
20ef40cf 1541 minus_f = TRUE;
f5542d3a 1542#endif
20ef40cf
GA
1543 s++;
1544 goto reswitch;
1545
6224f72b
GS
1546 case 'I': /* -I handled both here and in moreswitches() */
1547 forbid_setid("-I");
1548 if (!*++s && (s=argv[1]) != Nullch) {
1549 argc--,argv++;
1550 }
6224f72b 1551 if (s && *s) {
0df16ed7
GS
1552 char *p;
1553 STRLEN len = strlen(s);
1554 p = savepvn(s, len);
88fe16b2 1555 incpush(p, TRUE, TRUE, FALSE, FALSE);
0df16ed7
GS
1556 sv_catpvn(sv, "-I", 2);
1557 sv_catpvn(sv, p, len);
1558 sv_catpvn(sv, " ", 1);
6224f72b 1559 Safefree(p);
0df16ed7
GS
1560 }
1561 else
a67e862a 1562 Perl_croak(aTHX_ "No directory specified for -I");
6224f72b
GS
1563 break;
1564 case 'P':
1565 forbid_setid("-P");
3280af22 1566 PL_preprocess = TRUE;
6224f72b
GS
1567 s++;
1568 goto reswitch;
1569 case 'S':
1570 forbid_setid("-S");
1571 dosearch = TRUE;
1572 s++;
1573 goto reswitch;
1574 case 'V':
3280af22
NIS
1575 if (!PL_preambleav)
1576 PL_preambleav = newAV();
1577 av_push(PL_preambleav, newSVpv("use Config qw(myconfig config_vars)",0));
6224f72b 1578 if (*++s != ':') {
efcaa95b
YST
1579 STRLEN opts;
1580
3280af22 1581 PL_Sv = newSVpv("print myconfig();",0);
6224f72b 1582#ifdef VMS
6b88bc9c 1583 sv_catpv(PL_Sv,"print \"\\nCharacteristics of this PERLSHR image: \\n\",");
6224f72b 1584#else
3280af22 1585 sv_catpv(PL_Sv,"print \"\\nCharacteristics of this binary (from libperl): \\n\",");
6224f72b 1586#endif
efcaa95b
YST
1587 opts = SvCUR(PL_Sv);
1588
3280af22 1589 sv_catpv(PL_Sv,"\" Compile-time options:");
6224f72b 1590# ifdef DEBUGGING
3280af22 1591 sv_catpv(PL_Sv," DEBUGGING");
6224f72b 1592# endif
6224f72b 1593# ifdef MULTIPLICITY
8f872242 1594 sv_catpv(PL_Sv," MULTIPLICITY");
6224f72b 1595# endif
4d1ff10f
AB
1596# ifdef USE_5005THREADS
1597 sv_catpv(PL_Sv," USE_5005THREADS");
b363f7ed 1598# endif
ac5e8965
JH
1599# ifdef USE_ITHREADS
1600 sv_catpv(PL_Sv," USE_ITHREADS");
1601# endif
10cc9d2a
JH
1602# ifdef USE_64_BIT_INT
1603 sv_catpv(PL_Sv," USE_64_BIT_INT");
1604# endif
1605# ifdef USE_64_BIT_ALL
1606 sv_catpv(PL_Sv," USE_64_BIT_ALL");
ac5e8965
JH
1607# endif
1608# ifdef USE_LONG_DOUBLE
1609 sv_catpv(PL_Sv," USE_LONG_DOUBLE");
1610# endif
53430762
JH
1611# ifdef USE_LARGE_FILES
1612 sv_catpv(PL_Sv," USE_LARGE_FILES");
1613# endif
ac5e8965
JH
1614# ifdef USE_SOCKS
1615 sv_catpv(PL_Sv," USE_SOCKS");
1616# endif
20ef40cf
GA
1617# ifdef USE_SITECUSTOMIZE
1618 sv_catpv(PL_Sv," USE_SITECUSTOMIZE");
1619# endif
b363f7ed
GS
1620# ifdef PERL_IMPLICIT_CONTEXT
1621 sv_catpv(PL_Sv," PERL_IMPLICIT_CONTEXT");
1622# endif
1623# ifdef PERL_IMPLICIT_SYS
1624 sv_catpv(PL_Sv," PERL_IMPLICIT_SYS");
1625# endif
efcaa95b
YST
1626
1627 while (SvCUR(PL_Sv) > opts+76) {
1628 /* find last space after "options: " and before col 76 */
1629
dd374669
AL
1630 const char *space;
1631 char *pv = SvPV_nolen(PL_Sv);
1632 const char c = pv[opts+76];
efcaa95b
YST
1633 pv[opts+76] = '\0';
1634 space = strrchr(pv+opts+26, ' ');
1635 pv[opts+76] = c;
1636 if (!space) break; /* "Can't happen" */
1637
1638 /* break the line before that space */
1639
1640 opts = space - pv;
1641 sv_insert(PL_Sv, opts, 0,
1642 "\\n ", 25);
1643 }
1644
3280af22 1645 sv_catpv(PL_Sv,"\\n\",");
b363f7ed 1646
6224f72b
GS
1647#if defined(LOCAL_PATCH_COUNT)
1648 if (LOCAL_PATCH_COUNT > 0) {
1649 int i;
3280af22 1650 sv_catpv(PL_Sv,"\" Locally applied patches:\\n\",");
6224f72b 1651 for (i = 1; i <= LOCAL_PATCH_COUNT; i++) {
3280af22 1652 if (PL_localpatches[i])
acb03d05
AB
1653 Perl_sv_catpvf(aTHX_ PL_Sv,"q%c\t%s\n%c,",
1654 0, PL_localpatches[i], 0);
6224f72b
GS
1655 }
1656 }
1657#endif
cea2e8a9 1658 Perl_sv_catpvf(aTHX_ PL_Sv,"\" Built under %s\\n\"",OSNAME);
6224f72b
GS
1659#ifdef __DATE__
1660# ifdef __TIME__
cea2e8a9 1661 Perl_sv_catpvf(aTHX_ PL_Sv,",\" Compiled at %s %s\\n\"",__DATE__,__TIME__);
6224f72b 1662# else
cea2e8a9 1663 Perl_sv_catpvf(aTHX_ PL_Sv,",\" Compiled on %s\\n\"",__DATE__);
6224f72b
GS
1664# endif
1665#endif
3280af22 1666 sv_catpv(PL_Sv, "; \
6224f72b 1667$\"=\"\\n \"; \
69fcd688
JH
1668@env = map { \"$_=\\\"$ENV{$_}\\\"\" } sort grep {/^PERL/} keys %ENV; ");
1669#ifdef __CYGWIN__
1670 sv_catpv(PL_Sv,"\
1671push @env, \"CYGWIN=\\\"$ENV{CYGWIN}\\\"\";");
1672#endif
1673 sv_catpv(PL_Sv, "\
6224f72b
GS
1674print \" \\%ENV:\\n @env\\n\" if @env; \
1675print \" \\@INC:\\n @INC\\n\";");
1676 }
1677 else {
3280af22
NIS
1678 PL_Sv = newSVpv("config_vars(qw(",0);
1679 sv_catpv(PL_Sv, ++s);
1680 sv_catpv(PL_Sv, "))");
6224f72b
GS
1681 s += strlen(s);
1682 }
3280af22 1683 av_push(PL_preambleav, PL_Sv);
6224f72b
GS
1684 scriptname = BIT_BUCKET; /* don't look for script or read stdin */
1685 goto reswitch;
1686 case 'x':
3280af22 1687 PL_doextract = TRUE;
6224f72b
GS
1688 s++;
1689 if (*s)
f4c556ac 1690 cddir = s;
6224f72b
GS
1691 break;
1692 case 0:
1693 break;
1694 case '-':
1695 if (!*++s || isSPACE(*s)) {
1696 argc--,argv++;
1697 goto switch_end;
1698 }
1699 /* catch use of gnu style long options */
1700 if (strEQ(s, "version")) {
dd374669 1701 s = (char *)"v";
6224f72b
GS
1702 goto reswitch;
1703 }
1704 if (strEQ(s, "help")) {
dd374669 1705 s = (char *)"h";
6224f72b
GS
1706 goto reswitch;
1707 }
1708 s--;
1709 /* FALL THROUGH */
1710 default:
cea2e8a9 1711 Perl_croak(aTHX_ "Unrecognized switch: -%s (-h will show valid options)",s);
8d063cd8
LW
1712 }
1713 }
6224f72b 1714 switch_end:
54310121 1715
f675dbe5
CB
1716 if (
1717#ifndef SECURE_INTERNAL_GETENV
1718 !PL_tainting &&
1719#endif
cf756827 1720 (s = PerlEnv_getenv("PERL5OPT")))
0df16ed7 1721 {
e1ec3a88 1722 const char *popt = s;
74288ac8
GS
1723 while (isSPACE(*s))
1724 s++;
317ea90d 1725 if (*s == '-' && *(s+1) == 'T') {
22f7c9c9 1726 CHECK_MALLOC_TOO_LATE_FOR('T');
74288ac8 1727 PL_tainting = TRUE;
317ea90d
MS
1728 PL_taint_warn = FALSE;
1729 }
74288ac8 1730 else {
cf756827 1731 char *popt_copy = Nullch;
74288ac8 1732 while (s && *s) {
4ea8f8fb 1733 char *d;
74288ac8
GS
1734 while (isSPACE(*s))
1735 s++;
1736 if (*s == '-') {
1737 s++;
1738 if (isSPACE(*s))
1739 continue;
1740 }
4ea8f8fb 1741 d = s;
74288ac8
GS
1742 if (!*s)
1743 break;
06492da6 1744 if (!strchr("DIMUdmtwA", *s))
cea2e8a9 1745 Perl_croak(aTHX_ "Illegal switch in PERL5OPT: -%c", *s);
4ea8f8fb
MS
1746 while (++s && *s) {
1747 if (isSPACE(*s)) {
cf756827
GS
1748 if (!popt_copy) {
1749 popt_copy = SvPVX(sv_2mortal(newSVpv(popt,0)));
1750 s = popt_copy + (s - popt);
1751 d = popt_copy + (d - popt);
1752 }
4ea8f8fb
MS
1753 *s++ = '\0';
1754 break;
1755 }
1756 }
1c4db469 1757 if (*d == 't') {
317ea90d
MS
1758 if( !PL_tainting ) {
1759 PL_taint_warn = TRUE;
1760 PL_tainting = TRUE;
1761 }
1c4db469
RGS
1762 } else {
1763 moreswitches(d);
1764 }
6224f72b 1765 }
6224f72b
GS
1766 }
1767 }
a0d0e21e 1768
20ef40cf
GA
1769#ifdef USE_SITECUSTOMIZE
1770 if (!minus_f) {
1771 if (!PL_preambleav)
1772 PL_preambleav = newAV();
1773 av_unshift(PL_preambleav, 1);
1774 (void)av_store(PL_preambleav, 0, Perl_newSVpvf(aTHX_ "BEGIN { do '%s/sitecustomize.pl' }", SITELIB_EXP));
1775 }
1776#endif
1777
317ea90d
MS
1778 if (PL_taint_warn && PL_dowarn != G_WARN_ALL_OFF) {
1779 PL_compiling.cop_warnings = newSVpvn(WARN_TAINTstring, WARNsize);
1780 }
1781
6224f72b
GS
1782 if (!scriptname)
1783 scriptname = argv[0];
3280af22 1784 if (PL_e_script) {
6224f72b
GS
1785 argc++,argv--;
1786 scriptname = BIT_BUCKET; /* don't look for script or read stdin */
1787 }
1788 else if (scriptname == Nullch) {
1789#ifdef MSDOS
1790 if ( PerlLIO_isatty(PerlIO_fileno(PerlIO_stdin())) )
1791 moreswitches("h");
1792#endif
1793 scriptname = "-";
1794 }
1795
b7975bdd
NC
1796 /* Set $^X early so that it can be used for relocatable paths in @INC */
1797 assert (!PL_tainted);
1798 TAINT;
1799 S_set_caret_X(aTHX);
1800 TAINT_NOT;
6224f72b
GS
1801 init_perllib();
1802
c5cccb17 1803 open_script(scriptname,dosearch,sv);
6224f72b 1804
c5cccb17 1805 validate_suid(validarg, scriptname);
6224f72b 1806
64ca3a65 1807#ifndef PERL_MICRO
0b5b802d
GS
1808#if defined(SIGCHLD) || defined(SIGCLD)
1809 {
1810#ifndef SIGCHLD
1811# define SIGCHLD SIGCLD
1812#endif
1813 Sighandler_t sigstate = rsignal_state(SIGCHLD);
1814 if (sigstate == SIG_IGN) {
1815 if (ckWARN(WARN_SIGNAL))
9014280d 1816 Perl_warner(aTHX_ packWARN(WARN_SIGNAL),
0b5b802d
GS
1817 "Can't ignore signal CHLD, forcing to default");
1818 (void)rsignal(SIGCHLD, (Sighandler_t)SIG_DFL);
1819 }
1820 }
1821#endif
64ca3a65 1822#endif
0b5b802d 1823
bf4acbe4
GS
1824#ifdef MACOS_TRADITIONAL
1825 if (PL_doextract || gMacPerl_AlwaysExtract) {
1826#else
f4c556ac 1827 if (PL_doextract) {
bf4acbe4 1828#endif
6224f72b 1829 find_beginning();
dd374669 1830 if (cddir && PerlDir_chdir( (char *)cddir ) < 0)
f4c556ac
GS
1831 Perl_croak(aTHX_ "Can't chdir to %s",cddir);
1832
1833 }
6224f72b 1834
3280af22
NIS
1835 PL_main_cv = PL_compcv = (CV*)NEWSV(1104,0);
1836 sv_upgrade((SV *)PL_compcv, SVt_PVCV);
1837 CvUNIQUE_on(PL_compcv);
1838
dd2155a4 1839 CvPADLIST(PL_compcv) = pad_new(0);
4d1ff10f 1840#ifdef USE_5005THREADS
533c011a
NIS
1841 CvOWNER(PL_compcv) = 0;
1842 New(666, CvMUTEXP(PL_compcv), 1, perl_mutex);
1843 MUTEX_INIT(CvMUTEXP(PL_compcv));
4d1ff10f 1844#endif /* USE_5005THREADS */
6224f72b 1845
0c4f7ff0 1846 boot_core_PerlIO();
6224f72b 1847 boot_core_UNIVERSAL();
09bef843 1848 boot_core_xsutils();
6224f72b
GS
1849
1850 if (xsinit)
acfe0abc 1851 (*xsinit)(aTHX); /* in case linked C routines want magical variables */
64ca3a65 1852#ifndef PERL_MICRO
ed79a026 1853#if defined(VMS) || defined(WIN32) || defined(DJGPP) || defined(__CYGWIN__) || defined(EPOC)
c5be433b 1854 init_os_extras();
6224f72b 1855#endif
64ca3a65 1856#endif
6224f72b 1857
29209bc5 1858#ifdef USE_SOCKS
1b9c9cf5
DH
1859# ifdef HAS_SOCKS5_INIT
1860 socks5_init(argv[0]);
1861# else
29209bc5 1862 SOCKSinit(argv[0]);
1b9c9cf5 1863# endif
ac27b0f5 1864#endif
29209bc5 1865
6224f72b
GS
1866 init_predump_symbols();
1867 /* init_postdump_symbols not currently designed to be called */
1868 /* more than once (ENV isn't cleared first, for example) */
1869 /* But running with -u leaves %ENV & @ARGV undefined! XXX */
3280af22 1870 if (!PL_do_undump)
6224f72b
GS
1871 init_postdump_symbols(argc,argv,env);
1872
27da23d5
JH
1873 /* PL_unicode is turned on by -C, or by $ENV{PERL_UNICODE},
1874 * or explicitly in some platforms.
085a54d9 1875 * locale.c:Perl_init_i18nl10n() if the environment
a05d7ebb 1876 * look like the user wants to use UTF-8. */
27da23d5
JH
1877#if defined(SYMBIAN)
1878 PL_unicode = PERL_UNICODE_STD_FLAG; /* See PERL_SYMBIAN_CONSOLE_UTF8. */
1879#endif
06e66572
JH
1880 if (PL_unicode) {
1881 /* Requires init_predump_symbols(). */
a05d7ebb 1882 if (!(PL_unicode & PERL_UNICODE_LOCALE_FLAG) || PL_utf8locale) {
06e66572
JH
1883 IO* io;
1884 PerlIO* fp;
1885 SV* sv;
1886
a05d7ebb 1887 /* Turn on UTF-8-ness on STDIN, STDOUT, STDERR
06e66572 1888 * and the default open disciplines. */
a05d7ebb
JH
1889 if ((PL_unicode & PERL_UNICODE_STDIN_FLAG) &&
1890 PL_stdingv && (io = GvIO(PL_stdingv)) &&
1891 (fp = IoIFP(io)))
1892 PerlIO_binmode(aTHX_ fp, IoTYPE(io), 0, ":utf8");
1893 if ((PL_unicode & PERL_UNICODE_STDOUT_FLAG) &&
1894 PL_defoutgv && (io = GvIO(PL_defoutgv)) &&
1895 (fp = IoOFP(io)))
1896 PerlIO_binmode(aTHX_ fp, IoTYPE(io), 0, ":utf8");
1897 if ((PL_unicode & PERL_UNICODE_STDERR_FLAG) &&
1898 PL_stderrgv && (io = GvIO(PL_stderrgv)) &&
1899 (fp = IoOFP(io)))
1900 PerlIO_binmode(aTHX_ fp, IoTYPE(io), 0, ":utf8");
1901 if ((PL_unicode & PERL_UNICODE_INOUT_FLAG) &&
1902 (sv = GvSV(gv_fetchpv("\017PEN", TRUE, SVt_PV)))) {
1903 U32 in = PL_unicode & PERL_UNICODE_IN_FLAG;
1904 U32 out = PL_unicode & PERL_UNICODE_OUT_FLAG;
1905 if (in) {
1906 if (out)
1907 sv_setpvn(sv, ":utf8\0:utf8", 11);
1908 else
1909 sv_setpvn(sv, ":utf8\0", 6);
1910 }
1911 else if (out)
1912 sv_setpvn(sv, "\0:utf8", 6);
1913 SvSETMAGIC(sv);
1914 }
b310b053
JH
1915 }
1916 }
1917
4ffa73a3
JH
1918 if ((s = PerlEnv_getenv("PERL_SIGNALS"))) {
1919 if (strEQ(s, "unsafe"))
1920 PL_signals |= PERL_SIGNALS_UNSAFE_FLAG;
1921 else if (strEQ(s, "safe"))
1922 PL_signals &= ~PERL_SIGNALS_UNSAFE_FLAG;
1923 else
1924 Perl_croak(aTHX_ "PERL_SIGNALS illegal: \"%s\"", s);
1925 }
1926
6224f72b
GS
1927 init_lexer();
1928
1929 /* now parse the script */
1930
93189314 1931 SETERRNO(0,SS_NORMAL);
3280af22 1932 PL_error_count = 0;
bf4acbe4
GS
1933#ifdef MACOS_TRADITIONAL
1934 if (gMacPerl_SyntaxError = (yyparse() || PL_error_count)) {
1935 if (PL_minus_c)
1936 Perl_croak(aTHX_ "%s had compilation errors.\n", MacPerl_MPWFileName(PL_origfilename));
1937 else {
1938 Perl_croak(aTHX_ "Execution of %s aborted due to compilation errors.\n",
1939 MacPerl_MPWFileName(PL_origfilename));
1940 }
1941 }
1942#else
3280af22
NIS
1943 if (yyparse() || PL_error_count) {
1944 if (PL_minus_c)
cea2e8a9 1945 Perl_croak(aTHX_ "%s had compilation errors.\n", PL_origfilename);
6224f72b 1946 else {
cea2e8a9 1947 Perl_croak(aTHX_ "Execution of %s aborted due to compilation errors.\n",
097ee67d 1948 PL_origfilename);
6224f72b
GS
1949 }
1950 }
bf4acbe4 1951#endif
57843af0 1952 CopLINE_set(PL_curcop, 0);
3280af22
NIS
1953 PL_curstash = PL_defstash;
1954 PL_preprocess = FALSE;
1955 if (PL_e_script) {
1956 SvREFCNT_dec(PL_e_script);
1957 PL_e_script = Nullsv;
6224f72b
GS
1958 }
1959
3280af22 1960 if (PL_do_undump)
6224f72b
GS
1961 my_unexec();
1962
57843af0
GS
1963 if (isWARN_ONCE) {
1964 SAVECOPFILE(PL_curcop);
1965 SAVECOPLINE(PL_curcop);
3280af22 1966 gv_check(PL_defstash);
57843af0 1967 }
6224f72b
GS
1968
1969 LEAVE;
1970 FREETMPS;
1971
1972#ifdef MYMALLOC
1973 if ((s=PerlEnv_getenv("PERL_DEBUG_MSTATS")) && atoi(s) >= 2)
1974 dump_mstats("after compilation:");
1975#endif
1976
1977 ENTER;
3280af22 1978 PL_restartop = 0;
312caa8e 1979 return NULL;
6224f72b
GS
1980}
1981
954c1994
GS
1982/*
1983=for apidoc perl_run
1984
1985Tells a Perl interpreter to run. See L<perlembed>.
1986
1987=cut
1988*/
1989
6224f72b 1990int
0cb96387 1991perl_run(pTHXx)
6224f72b 1992{
6224f72b 1993 I32 oldscope;
14dd3ad8 1994 int ret = 0;
db36c5a1 1995 dJMPENV;
6224f72b 1996
3280af22 1997 oldscope = PL_scopestack_ix;
96e176bf
CL
1998#ifdef VMS
1999 VMSISH_HUSHED = 0;
2000#endif
6224f72b 2001
14dd3ad8 2002 JMPENV_PUSH(ret);
6224f72b
GS
2003 switch (ret) {
2004 case 1:
2005 cxstack_ix = -1; /* start context stack again */
312caa8e 2006 goto redo_body;
14dd3ad8 2007 case 0: /* normal completion */
14dd3ad8
GS
2008 redo_body:
2009 run_body(oldscope);
14dd3ad8
GS
2010 /* FALL THROUGH */
2011 case 2: /* my_exit() */
3280af22 2012 while (PL_scopestack_ix > oldscope)
6224f72b
GS
2013 LEAVE;
2014 FREETMPS;
3280af22 2015 PL_curstash = PL_defstash;
3a1ee7e8 2016 if (!(PL_exit_flags & PERL_EXIT_DESTRUCT_END) &&
31d77e54
AB
2017 PL_endav && !PL_minus_c)
2018 call_list(oldscope, PL_endav);
6224f72b
GS
2019#ifdef MYMALLOC
2020 if (PerlEnv_getenv("PERL_DEBUG_MSTATS"))
2021 dump_mstats("after execution: ");
2022#endif
14dd3ad8
GS
2023 ret = STATUS_NATIVE_EXPORT;
2024 break;
6224f72b 2025 case 3:
312caa8e
CS
2026 if (PL_restartop) {
2027 POPSTACK_TO(PL_mainstack);
2028 goto redo_body;
6224f72b 2029 }
bf49b057 2030 PerlIO_printf(Perl_error_log, "panic: restartop\n");
312caa8e 2031 FREETMPS;
14dd3ad8
GS
2032 ret = 1;
2033 break;
6224f72b
GS
2034 }
2035
14dd3ad8
GS
2036 JMPENV_POP;
2037 return ret;
312caa8e
CS
2038}
2039
14dd3ad8 2040
dd374669 2041STATIC void
14dd3ad8
GS
2042S_run_body(pTHX_ I32 oldscope)
2043{
6224f72b 2044 DEBUG_r(PerlIO_printf(Perl_debug_log, "%s $` $& $' support.\n",
3280af22 2045 PL_sawampersand ? "Enabling" : "Omitting"));
6224f72b 2046
3280af22 2047 if (!PL_restartop) {
6224f72b 2048 DEBUG_x(dump_all());
ecae49c0
NC
2049 if (!DEBUG_q_TEST)
2050 PERL_DEBUG(PerlIO_printf(Perl_debug_log, "\nEXECUTING...\n\n"));
b900a521
JH
2051 DEBUG_S(PerlIO_printf(Perl_debug_log, "main thread is 0x%"UVxf"\n",
2052 PTR2UV(thr)));
6224f72b 2053
3280af22 2054 if (PL_minus_c) {
bf4acbe4 2055#ifdef MACOS_TRADITIONAL
e69a2255
JH
2056 PerlIO_printf(Perl_error_log, "%s%s syntax OK\n",
2057 (gMacPerl_ErrorFormat ? "# " : ""),
2058 MacPerl_MPWFileName(PL_origfilename));
bf4acbe4 2059#else
bf49b057 2060 PerlIO_printf(Perl_error_log, "%s syntax OK\n", PL_origfilename);
bf4acbe4 2061#endif
6224f72b
GS
2062 my_exit(0);
2063 }
3280af22 2064 if (PERLDB_SINGLE && PL_DBsingle)
ac27b0f5 2065 sv_setiv(PL_DBsingle, 1);
3280af22
NIS
2066 if (PL_initav)
2067 call_list(oldscope, PL_initav);
6224f72b
GS
2068 }
2069
2070 /* do it */
2071
3280af22 2072 if (PL_restartop) {
533c011a 2073 PL_op = PL_restartop;
3280af22 2074 PL_restartop = 0;
cea2e8a9 2075 CALLRUNOPS(aTHX);
6224f72b 2076 }
3280af22
NIS
2077 else if (PL_main_start) {
2078 CvDEPTH(PL_main_cv) = 1;
533c011a 2079 PL_op = PL_main_start;
cea2e8a9 2080 CALLRUNOPS(aTHX);
6224f72b 2081 }
f6b3007c
JH
2082 my_exit(0);
2083 /* NOTREACHED */
6224f72b
GS
2084}
2085
954c1994 2086/*
ccfc67b7
JH
2087=head1 SV Manipulation Functions
2088
954c1994
GS
2089=for apidoc p||get_sv
2090
2091Returns the SV of the specified Perl scalar. If C<create> is set and the
2092Perl variable does not exist then it will be created. If C<create> is not
2093set and the variable does not exist then NULL is returned.
2094
2095=cut
2096*/
2097
6224f72b 2098SV*
864dbfa3 2099Perl_get_sv(pTHX_ const char *name, I32 create)
6224f72b
GS
2100{
2101 GV *gv;
4d1ff10f 2102#ifdef USE_5005THREADS
6224f72b
GS
2103 if (name[1] == '\0' && !isALPHA(name[0])) {
2104 PADOFFSET tmp = find_threadsv(name);
411caa50 2105 if (tmp != NOT_IN_PAD)
6224f72b 2106 return THREADSV(tmp);
6224f72b 2107 }
4d1ff10f 2108#endif /* USE_5005THREADS */
6224f72b
GS
2109 gv = gv_fetchpv(name, create, SVt_PV);
2110 if (gv)
2111 return GvSV(gv);
2112 return Nullsv;
2113}
2114
954c1994 2115/*
ccfc67b7
JH
2116=head1 Array Manipulation Functions
2117
954c1994
GS
2118=for apidoc p||get_av
2119
2120Returns the AV of the specified Perl array. If C<create> is set and the
2121Perl variable does not exist then it will be created. If C<create> is not
2122set and the variable does not exist then NULL is returned.
2123
2124=cut
2125*/
2126
6224f72b 2127AV*
864dbfa3 2128Perl_get_av(pTHX_ const char *name, I32 create)
6224f72b
GS
2129{
2130 GV* gv = gv_fetchpv(name, create, SVt_PVAV);
2131 if (create)
2132 return GvAVn(gv);
2133 if (gv)
2134 return GvAV(gv);
2135 return Nullav;
2136}
2137
954c1994 2138/*
ccfc67b7
JH
2139=head1 Hash Manipulation Functions
2140
954c1994
GS
2141=for apidoc p||get_hv
2142
2143Returns the HV of the specified Perl hash. If C<create> is set and the
2144Perl variable does not exist then it will be created. If C<create> is not
2145set and the variable does not exist then NULL is returned.
2146
2147=cut
2148*/
2149
6224f72b 2150HV*
864dbfa3 2151Perl_get_hv(pTHX_ const char *name, I32 create)
6224f72b 2152{
a0d0e21e
LW
2153 GV* gv = gv_fetchpv(name, create, SVt_PVHV);
2154 if (create)
2155 return GvHVn(gv);
2156 if (gv)
2157 return GvHV(gv);
2158 return Nullhv;
2159}
2160
954c1994 2161/*
ccfc67b7
JH
2162=head1 CV Manipulation Functions
2163
954c1994
GS
2164=for apidoc p||get_cv
2165
2166Returns the CV of the specified Perl subroutine. If C<create> is set and
2167the Perl subroutine does not exist then it will be declared (which has the
2168same effect as saying C<sub name;>). If C<create> is not set and the
2169subroutine does not exist then NULL is returned.
2170
2171=cut
2172*/
2173
a0d0e21e 2174CV*
864dbfa3 2175Perl_get_cv(pTHX_ const char *name, I32 create)
a0d0e21e
LW
2176{
2177 GV* gv = gv_fetchpv(name, create, SVt_PVCV);
b099ddc0 2178 /* XXX unsafe for threads if eval_owner isn't held */
f6ec51f7
GS
2179 /* XXX this is probably not what they think they're getting.
2180 * It has the same effect as "sub name;", i.e. just a forward
2181 * declaration! */
8ebc5c01 2182 if (create && !GvCVu(gv))
774d564b 2183 return newSUB(start_subparse(FALSE, 0),
a0d0e21e 2184 newSVOP(OP_CONST, 0, newSVpv(name,0)),
4633a7c4 2185 Nullop,
a0d0e21e
LW
2186 Nullop);
2187 if (gv)
8ebc5c01 2188 return GvCVu(gv);
a0d0e21e
LW
2189 return Nullcv;
2190}
2191
79072805
LW
2192/* Be sure to refetch the stack pointer after calling these routines. */
2193
954c1994 2194/*
ccfc67b7
JH
2195
2196=head1 Callback Functions
2197
954c1994
GS
2198=for apidoc p||call_argv
2199
2200Performs a callback to the specified Perl sub. See L<perlcall>.
2201
2202=cut
2203*/
2204
a0d0e21e 2205I32
8f42b153 2206Perl_call_argv(pTHX_ const char *sub_name, I32 flags, register char **argv)
ac27b0f5 2207
8ac85365
NIS
2208 /* See G_* flags in cop.h */
2209 /* null terminated arg list */
8990e307 2210{
a0d0e21e 2211 dSP;
8990e307 2212
924508f0 2213 PUSHMARK(SP);
a0d0e21e 2214 if (argv) {
8990e307 2215 while (*argv) {
a0d0e21e 2216 XPUSHs(sv_2mortal(newSVpv(*argv,0)));
8990e307
LW
2217 argv++;
2218 }
a0d0e21e 2219 PUTBACK;
8990e307 2220 }
864dbfa3 2221 return call_pv(sub_name, flags);
8990e307
LW
2222}
2223
954c1994
GS
2224/*
2225=for apidoc p||call_pv
2226
2227Performs a callback to the specified Perl sub. See L<perlcall>.
2228
2229=cut
2230*/
2231
a0d0e21e 2232I32
864dbfa3 2233Perl_call_pv(pTHX_ const char *sub_name, I32 flags)
8ac85365
NIS
2234 /* name of the subroutine */
2235 /* See G_* flags in cop.h */
a0d0e21e 2236{
864dbfa3 2237 return call_sv((SV*)get_cv(sub_name, TRUE), flags);
a0d0e21e
LW
2238}
2239
954c1994
GS
2240/*
2241=for apidoc p||call_method
2242
2243Performs a callback to the specified Perl method. The blessed object must
2244be on the stack. See L<perlcall>.
2245
2246=cut
2247*/
2248
a0d0e21e 2249I32
864dbfa3 2250Perl_call_method(pTHX_ const char *methname, I32 flags)
8ac85365
NIS
2251 /* name of the subroutine */
2252 /* See G_* flags in cop.h */
a0d0e21e 2253{
968b3946 2254 return call_sv(sv_2mortal(newSVpv(methname,0)), flags | G_METHOD);
a0d0e21e
LW
2255}
2256
2257/* May be called with any of a CV, a GV, or an SV containing the name. */
954c1994
GS
2258/*
2259=for apidoc p||call_sv
2260
2261Performs a callback to the Perl sub whose name is in the SV. See
2262L<perlcall>.
2263
2264=cut
2265*/
2266
a0d0e21e 2267I32
864dbfa3 2268Perl_call_sv(pTHX_ SV *sv, I32 flags)
8ac85365 2269 /* See G_* flags in cop.h */
a0d0e21e 2270{
27da23d5 2271 dVAR; dSP;
a0d0e21e 2272 LOGOP myop; /* fake syntax tree node */
968b3946 2273 UNOP method_op;
aa689395 2274 I32 oldmark;
13689cfe 2275 volatile I32 retval = 0;
a0d0e21e 2276 I32 oldscope;
54310121 2277 bool oldcatch = CATCH_GET;
6224f72b 2278 int ret;
533c011a 2279 OP* oldop = PL_op;
db36c5a1 2280 dJMPENV;
1e422769 2281
a0d0e21e
LW
2282 if (flags & G_DISCARD) {
2283 ENTER;
2284 SAVETMPS;
2285 }
2286
aa689395 2287 Zero(&myop, 1, LOGOP);
54310121 2288 myop.op_next = Nullop;
f51d4af5 2289 if (!(flags & G_NOARGS))
aa689395 2290 myop.op_flags |= OPf_STACKED;
54310121 2291 myop.op_flags |= ((flags & G_VOID) ? OPf_WANT_VOID :
2292 (flags & G_ARRAY) ? OPf_WANT_LIST :
2293 OPf_WANT_SCALAR);
462e5cf6 2294 SAVEOP();
533c011a 2295 PL_op = (OP*)&myop;
aa689395 2296
3280af22
NIS
2297 EXTEND(PL_stack_sp, 1);
2298 *++PL_stack_sp = sv;
aa689395 2299 oldmark = TOPMARK;
3280af22 2300 oldscope = PL_scopestack_ix;
a0d0e21e 2301
3280af22 2302 if (PERLDB_SUB && PL_curstash != PL_debstash
36477c24 2303 /* Handle first BEGIN of -d. */
3280af22 2304 && (PL_DBcv || (PL_DBcv = GvCV(PL_DBsub)))
36477c24 2305 /* Try harder, since this may have been a sighandler, thus
2306 * curstash may be meaningless. */
3280af22 2307 && (SvTYPE(sv) != SVt_PVCV || CvSTASH((CV*)sv) != PL_debstash)
491527d0 2308 && !(flags & G_NODEBUG))
533c011a 2309 PL_op->op_private |= OPpENTERSUB_DB;
a0d0e21e 2310
968b3946
GS
2311 if (flags & G_METHOD) {
2312 Zero(&method_op, 1, UNOP);
2313 method_op.op_next = PL_op;
2314 method_op.op_ppaddr = PL_ppaddr[OP_METHOD];
2315 myop.op_ppaddr = PL_ppaddr[OP_ENTERSUB];
f39d0b86 2316 PL_op = (OP*)&method_op;
968b3946
GS
2317 }
2318
312caa8e 2319 if (!(flags & G_EVAL)) {
0cdb2077 2320 CATCH_SET(TRUE);
14dd3ad8 2321 call_body((OP*)&myop, FALSE);
312caa8e 2322 retval = PL_stack_sp - (PL_stack_base + oldmark);
0253cb41 2323 CATCH_SET(oldcatch);
312caa8e
CS
2324 }
2325 else {
d78bda3d 2326 myop.op_other = (OP*)&myop;
3280af22 2327 PL_markstack_ptr--;
4633a7c4
LW
2328 /* we're trying to emulate pp_entertry() here */
2329 {
c09156bb 2330 register PERL_CONTEXT *cx;
f54cb97a 2331 const I32 gimme = GIMME_V;
ac27b0f5 2332
4633a7c4
LW
2333 ENTER;
2334 SAVETMPS;
ac27b0f5 2335
1d76a5c3 2336 PUSHBLOCK(cx, (CXt_EVAL|CXp_TRYBLOCK), PL_stack_sp);
4633a7c4 2337 PUSHEVAL(cx, 0, 0);
533c011a 2338 PL_eval_root = PL_op; /* Only needed so that goto works right. */
ac27b0f5 2339
faef0170 2340 PL_in_eval = EVAL_INEVAL;
4633a7c4 2341 if (flags & G_KEEPERR)
faef0170 2342 PL_in_eval |= EVAL_KEEPERR;
4633a7c4 2343 else
c69006e4 2344 sv_setpvn(ERRSV,"",0);
4633a7c4 2345 }
3280af22 2346 PL_markstack_ptr++;
a0d0e21e 2347
14dd3ad8 2348 JMPENV_PUSH(ret);
6224f72b
GS
2349 switch (ret) {
2350 case 0:
14dd3ad8
GS
2351 redo_body:
2352 call_body((OP*)&myop, FALSE);
312caa8e
CS
2353 retval = PL_stack_sp - (PL_stack_base + oldmark);
2354 if (!(flags & G_KEEPERR))
c69006e4 2355 sv_setpvn(ERRSV,"",0);
a0d0e21e 2356 break;
6224f72b 2357 case 1:
f86702cc 2358 STATUS_ALL_FAILURE;
a0d0e21e 2359 /* FALL THROUGH */
6224f72b 2360 case 2:
a0d0e21e 2361 /* my_exit() was called */
3280af22 2362 PL_curstash = PL_defstash;
a0d0e21e 2363 FREETMPS;
14dd3ad8 2364 JMPENV_POP;
cc3604b1 2365 if (PL_statusvalue && !(PL_exit_flags & PERL_EXIT_EXPECTED))
cea2e8a9 2366 Perl_croak(aTHX_ "Callback called exit");
f86702cc 2367 my_exit_jump();
a0d0e21e 2368 /* NOTREACHED */
6224f72b 2369 case 3:
3280af22 2370 if (PL_restartop) {
533c011a 2371 PL_op = PL_restartop;
3280af22 2372 PL_restartop = 0;
312caa8e 2373 goto redo_body;
a0d0e21e 2374 }
3280af22 2375 PL_stack_sp = PL_stack_base + oldmark;
a0d0e21e
LW
2376 if (flags & G_ARRAY)
2377 retval = 0;
2378 else {
2379 retval = 1;
3280af22 2380 *++PL_stack_sp = &PL_sv_undef;
a0d0e21e 2381 }
312caa8e 2382 break;
a0d0e21e 2383 }
a0d0e21e 2384
3280af22 2385 if (PL_scopestack_ix > oldscope) {
a0a2876f
LW
2386 SV **newsp;
2387 PMOP *newpm;
2388 I32 gimme;
c09156bb 2389 register PERL_CONTEXT *cx;
a0a2876f
LW
2390 I32 optype;
2391
2392 POPBLOCK(cx,newpm);
2393 POPEVAL(cx);
3280af22 2394 PL_curpm = newpm;
a0a2876f 2395 LEAVE;
a0d0e21e 2396 }
14dd3ad8 2397 JMPENV_POP;
a0d0e21e 2398 }
1e422769 2399
a0d0e21e 2400 if (flags & G_DISCARD) {
3280af22 2401 PL_stack_sp = PL_stack_base + oldmark;
a0d0e21e
LW
2402 retval = 0;
2403 FREETMPS;
2404 LEAVE;
2405 }
533c011a 2406 PL_op = oldop;
a0d0e21e
LW
2407 return retval;
2408}
2409
312caa8e 2410STATIC void
dd374669 2411S_call_body(pTHX_ const OP *myop, bool is_eval)
312caa8e 2412{
312caa8e
CS
2413 if (PL_op == myop) {
2414 if (is_eval)
f807eda9 2415 PL_op = Perl_pp_entereval(aTHX); /* this doesn't do a POPMARK */
312caa8e 2416 else
f807eda9 2417 PL_op = Perl_pp_entersub(aTHX); /* this does */
312caa8e
CS
2418 }
2419 if (PL_op)
cea2e8a9 2420 CALLRUNOPS(aTHX);
312caa8e
CS
2421}
2422
6e72f9df 2423/* Eval a string. The G_EVAL flag is always assumed. */
8990e307 2424
954c1994
GS
2425/*
2426=for apidoc p||eval_sv
2427
2428Tells Perl to C<eval> the string in the SV.
2429
2430=cut
2431*/
2432
a0d0e21e 2433I32
864dbfa3 2434Perl_eval_sv(pTHX_ SV *sv, I32 flags)
ac27b0f5 2435
8ac85365 2436 /* See G_* flags in cop.h */
a0d0e21e 2437{
924508f0 2438 dSP;
a0d0e21e 2439 UNOP myop; /* fake syntax tree node */
8fa7f367 2440 volatile I32 oldmark = SP - PL_stack_base;
13689cfe 2441 volatile I32 retval = 0;
6224f72b 2442 int ret;
533c011a 2443 OP* oldop = PL_op;
db36c5a1 2444 dJMPENV;
84902520 2445
4633a7c4
LW
2446 if (flags & G_DISCARD) {
2447 ENTER;
2448 SAVETMPS;
2449 }
2450
462e5cf6 2451 SAVEOP();
533c011a
NIS
2452 PL_op = (OP*)&myop;
2453 Zero(PL_op, 1, UNOP);
3280af22
NIS
2454 EXTEND(PL_stack_sp, 1);
2455 *++PL_stack_sp = sv;
79072805 2456
4633a7c4
LW
2457 if (!(flags & G_NOARGS))
2458 myop.op_flags = OPf_STACKED;
79072805 2459 myop.op_next = Nullop;
6e72f9df 2460 myop.op_type = OP_ENTEREVAL;
54310121 2461 myop.op_flags |= ((flags & G_VOID) ? OPf_WANT_VOID :
2462 (flags & G_ARRAY) ? OPf_WANT_LIST :
2463 OPf_WANT_SCALAR);
6e72f9df 2464 if (flags & G_KEEPERR)
2465 myop.op_flags |= OPf_SPECIAL;
4633a7c4 2466
dedbcade
DM
2467 /* fail now; otherwise we could fail after the JMPENV_PUSH but
2468 * before a PUSHEVAL, which corrupts the stack after a croak */
2469 TAINT_PROPER("eval_sv()");
2470
14dd3ad8 2471 JMPENV_PUSH(ret);
6224f72b
GS
2472 switch (ret) {
2473 case 0:
14dd3ad8
GS
2474 redo_body:
2475 call_body((OP*)&myop,TRUE);
312caa8e
CS
2476 retval = PL_stack_sp - (PL_stack_base + oldmark);
2477 if (!(flags & G_KEEPERR))
c69006e4 2478 sv_setpvn(ERRSV,"",0);
4633a7c4 2479 break;
6224f72b 2480 case 1:
f86702cc 2481 STATUS_ALL_FAILURE;
4633a7c4 2482 /* FALL THROUGH */
6224f72b 2483 case 2:
4633a7c4 2484 /* my_exit() was called */
3280af22 2485 PL_curstash = PL_defstash;
4633a7c4 2486 FREETMPS;
14dd3ad8 2487 JMPENV_POP;
cc3604b1 2488 if (PL_statusvalue && !(PL_exit_flags & PERL_EXIT_EXPECTED))
cea2e8a9 2489 Perl_croak(aTHX_ "Callback called exit");
f86702cc 2490 my_exit_jump();
4633a7c4 2491 /* NOTREACHED */
6224f72b 2492 case 3:
3280af22 2493 if (PL_restartop) {
533c011a 2494 PL_op = PL_restartop;
3280af22 2495 PL_restartop = 0;
312caa8e 2496 goto redo_body;
4633a7c4 2497 }
3280af22 2498 PL_stack_sp = PL_stack_base + oldmark;
4633a7c4
LW
2499 if (flags & G_ARRAY)
2500 retval = 0;
2501 else {
2502 retval = 1;
3280af22 2503 *++PL_stack_sp = &PL_sv_undef;
4633a7c4 2504 }
312caa8e 2505 break;
4633a7c4
LW
2506 }
2507
14dd3ad8 2508 JMPENV_POP;
4633a7c4 2509 if (flags & G_DISCARD) {
3280af22 2510 PL_stack_sp = PL_stack_base + oldmark;
4633a7c4
LW
2511 retval = 0;
2512 FREETMPS;
2513 LEAVE;
2514 }
533c011a 2515 PL_op = oldop;
4633a7c4
LW
2516 return retval;
2517}
2518
954c1994
GS
2519/*
2520=for apidoc p||eval_pv
2521
2522Tells Perl to C<eval> the given string and return an SV* result.
2523
2524=cut
2525*/
2526
137443ea 2527SV*
864dbfa3 2528Perl_eval_pv(pTHX_ const char *p, I32 croak_on_error)
137443ea 2529{
2530 dSP;
2531 SV* sv = newSVpv(p, 0);
2532
864dbfa3 2533 eval_sv(sv, G_SCALAR);
137443ea 2534 SvREFCNT_dec(sv);
2535
2536 SPAGAIN;
2537 sv = POPs;
2538 PUTBACK;
2539
2d8e6c8d 2540 if (croak_on_error && SvTRUE(ERRSV)) {
0510663f 2541 Perl_croak(aTHX_ SvPVx_nolen_const(ERRSV));
2d8e6c8d 2542 }
137443ea 2543
2544 return sv;
2545}
2546
4633a7c4
LW
2547/* Require a module. */
2548
954c1994 2549/*
ccfc67b7
JH
2550=head1 Embedding Functions
2551
954c1994
GS
2552=for apidoc p||require_pv
2553
7d3fb230
BS
2554Tells Perl to C<require> the file named by the string argument. It is
2555analogous to the Perl code C<eval "require '$file'">. It's even
2307c6d0 2556implemented that way; consider using load_module instead.
954c1994 2557
7d3fb230 2558=cut */
954c1994 2559
4633a7c4 2560void
864dbfa3 2561Perl_require_pv(pTHX_ const char *pv)
4633a7c4 2562{
d3acc0f7
JP
2563 SV* sv;
2564 dSP;
e788e7d3 2565 PUSHSTACKi(PERLSI_REQUIRE);
d3acc0f7
JP
2566 PUTBACK;
2567 sv = sv_newmortal();
4633a7c4
LW
2568 sv_setpv(sv, "require '");
2569 sv_catpv(sv, pv);
2570 sv_catpv(sv, "'");
864dbfa3 2571 eval_sv(sv, G_DISCARD);
d3acc0f7
JP
2572 SPAGAIN;
2573 POPSTACK;
79072805
LW
2574}
2575
79072805 2576void
e1ec3a88 2577Perl_magicname(pTHX_ const char *sym, const char *name, I32 namlen)
79072805
LW
2578{
2579 register GV *gv;
2580
155aba94 2581 if ((gv = gv_fetchpv(sym,TRUE, SVt_PV)))
14befaf4 2582 sv_magic(GvSV(gv), (SV*)gv, PERL_MAGIC_sv, name, namlen);
79072805
LW
2583}
2584
76e3520e 2585STATIC void
e1ec3a88 2586S_usage(pTHX_ const char *name) /* XXX move this out into a module ? */
4633a7c4 2587{
ab821d7f 2588 /* This message really ought to be max 23 lines.
75c72d73 2589 * Removed -h because the user already knows that option. Others? */
fb73857a 2590
27da23d5 2591 static const char * const usage_msg[] = {
aefc56c5
SF
2592"-0[octal] specify record separator (\\0, if no argument)",
2593"-A[mod][=pattern] activate all/given assertions",
2594"-a autosplit mode with -n or -p (splits $_ into @F)",
2595"-C[number/list] enables the listed Unicode features",
2596"-c check syntax only (runs BEGIN and CHECK blocks)",
2597"-d[:debugger] run program under debugger",
2598"-D[number/list] set debugging flags (argument is a bit mask or alphabets)",
2599"-e program one line of program (several -e's allowed, omit programfile)",
aefc56c5 2600"-f don't do $sitelib/sitecustomize.pl at startup",
aefc56c5
SF
2601"-F/pattern/ split() pattern for -a switch (//'s are optional)",
2602"-i[extension] edit <> files in place (makes backup if extension supplied)",
2603"-Idirectory specify @INC/#include directory (several -I's allowed)",
2604"-l[octal] enable line ending processing, specifies line terminator",
2605"-[mM][-]module execute \"use/no module...\" before executing program",
2606"-n assume \"while (<>) { ... }\" loop around program",
2607"-p assume loop like -n but print line also, like sed",
2608"-P run program through C preprocessor before compilation",
2609"-s enable rudimentary parsing for switches after programfile",
2610"-S look for programfile using PATH environment variable",
2611"-t enable tainting warnings",
2612"-T enable tainting checks",
2613"-u dump core after parsing program",
2614"-U allow unsafe operations",
2615"-v print version, subversion (includes VERY IMPORTANT perl info)",
2616"-V[:variable] print configuration summary (or a single Config.pm variable)",
2617"-w enable many useful warnings (RECOMMENDED)",
2618"-W enable all warnings",
2619"-x[directory] strip off text before #!perl line and perhaps cd to directory",
2620"-X disable all warnings",
fb73857a 2621"\n",
2622NULL
2623};
27da23d5 2624 const char * const *p = usage_msg;
fb73857a 2625
b0e47665
GS
2626 PerlIO_printf(PerlIO_stdout(),
2627 "\nUsage: %s [switches] [--] [programfile] [arguments]",
2628 name);
fb73857a 2629 while (*p)
b0e47665 2630 PerlIO_printf(PerlIO_stdout(), "\n %s", *p++);
4633a7c4
LW
2631}
2632
b4ab917c
DM
2633/* convert a string of -D options (or digits) into an int.
2634 * sets *s to point to the char after the options */
2635
2636#ifdef DEBUGGING
2637int
e1ec3a88 2638Perl_get_debug_opts(pTHX_ const char **s, bool givehelp)
b4ab917c 2639{
27da23d5 2640 static const char * const usage_msgd[] = {
e6e64d9b
JC
2641 " Debugging flag values: (see also -d)",
2642 " p Tokenizing and parsing (with v, displays parse stack)",
3679267a 2643 " s Stack snapshots (with v, displays all stacks)",
e6e64d9b
JC
2644 " l Context (loop) stack processing",
2645 " t Trace execution",
2646 " o Method and overloading resolution",
2647 " c String/numeric conversions",
2648 " P Print profiling info, preprocessor command for -P, source file input state",
2649 " m Memory allocation",
2650 " f Format processing",
2651 " r Regular expression parsing and execution",
2652 " x Syntax tree dump",
3679267a 2653 " u Tainting checks",
e6e64d9b
JC
2654 " H Hash dump -- usurps values()",
2655 " X Scratchpad allocation",
2656 " D Cleaning up",
2657 " S Thread synchronization",
2658 " T Tokenising",
2659 " R Include reference counts of dumped variables (eg when using -Ds)",
2660 " J Do not s,t,P-debug (Jump over) opcodes within package DB",
2661 " v Verbose: use in conjunction with other flags",
2662 " C Copy On Write",
2663 " A Consistency checks on internal structures",
3679267a 2664 " q quiet - currently only suppresses the 'EXECUTING' message",
e6e64d9b
JC
2665 NULL
2666 };
b4ab917c
DM
2667 int i = 0;
2668 if (isALPHA(**s)) {
2669 /* if adding extra options, remember to update DEBUG_MASK */
bfed75c6 2670 static const char debopts[] = "psltocPmfrxu HXDSTRJvCAq";
b4ab917c
DM
2671
2672 for (; isALNUM(**s); (*s)++) {
e1ec3a88 2673 const char *d = strchr(debopts,**s);
b4ab917c
DM
2674 if (d)
2675 i |= 1 << (d - debopts);
2676 else if (ckWARN_d(WARN_DEBUGGING))
e6e64d9b
JC
2677 Perl_warner(aTHX_ packWARN(WARN_DEBUGGING),
2678 "invalid option -D%c, use -D'' to see choices\n", **s);
b4ab917c
DM
2679 }
2680 }
e6e64d9b 2681 else if (isDIGIT(**s)) {
b4ab917c
DM
2682 i = atoi(*s);
2683 for (; isALNUM(**s); (*s)++) ;
2684 }
ddcf8bc1 2685 else if (givehelp) {
aadb217d 2686 char **p = (char **)usage_msgd;
e6e64d9b
JC
2687 while (*p) PerlIO_printf(PerlIO_stdout(), "%s\n", *p++);
2688 }
b4ab917c
DM
2689# ifdef EBCDIC
2690 if ((i & DEBUG_p_FLAG) && ckWARN_d(WARN_DEBUGGING))
2691 Perl_warner(aTHX_ packWARN(WARN_DEBUGGING),
2692 "-Dp not implemented on this platform\n");
2693# endif
2694 return i;
2695}
2696#endif
2697
79072805
LW
2698/* This routine handles any switches that can be given during run */
2699
2700char *
864dbfa3 2701Perl_moreswitches(pTHX_ char *s)
79072805 2702{
27da23d5 2703 dVAR;
84c133a0 2704 UV rschar;
79072805
LW
2705
2706 switch (*s) {
2707 case '0':
a863c7d1 2708 {
f2095865 2709 I32 flags = 0;
a3b680e6 2710 STRLEN numlen;
f2095865
JH
2711
2712 SvREFCNT_dec(PL_rs);
2713 if (s[1] == 'x' && s[2]) {
a3b680e6 2714 const char *e = s+=2;
f2095865
JH
2715 U8 *tmps;
2716
a3b680e6
AL
2717 while (*e)
2718 e++;
f2095865
JH
2719 numlen = e - s;
2720 flags = PERL_SCAN_SILENT_ILLDIGIT;
2721 rschar = (U32)grok_hex(s, &numlen, &flags, NULL);
2722 if (s + numlen < e) {
2723 rschar = 0; /* Grandfather -0xFOO as -0 -xFOO. */
2724 numlen = 0;
2725 s--;
2726 }
2727 PL_rs = newSVpvn("", 0);
c5661c80 2728 SvGROW(PL_rs, (STRLEN)(UNISKIP(rschar) + 1));
f2095865
JH
2729 tmps = (U8*)SvPVX(PL_rs);
2730 uvchr_to_utf8(tmps, rschar);
2731 SvCUR_set(PL_rs, UNISKIP(rschar));
2732 SvUTF8_on(PL_rs);
2733 }
2734 else {
2735 numlen = 4;
2736 rschar = (U32)grok_oct(s, &numlen, &flags, NULL);
2737 if (rschar & ~((U8)~0))
2738 PL_rs = &PL_sv_undef;
2739 else if (!rschar && numlen >= 2)
2740 PL_rs = newSVpvn("", 0);
2741 else {
2742 char ch = (char)rschar;
2743 PL_rs = newSVpvn(&ch, 1);
2744 }
2745 }
800633c3 2746 sv_setsv(get_sv("/", TRUE), PL_rs);
f2095865 2747 return s + numlen;
a863c7d1 2748 }
46487f74 2749 case 'C':
a05d7ebb 2750 s++;
dd374669 2751 PL_unicode = parse_unicode_opts( (const char **)&s );
46487f74 2752 return s;
2304df62 2753 case 'F':
3280af22 2754 PL_minus_F = TRUE;
ebce5377
RGS
2755 PL_splitstr = ++s;
2756 while (*s && !isSPACE(*s)) ++s;
2757 *s = '\0';
2758 PL_splitstr = savepv(PL_splitstr);
2304df62 2759 return s;
79072805 2760 case 'a':
3280af22 2761 PL_minus_a = TRUE;
79072805
LW
2762 s++;
2763 return s;
2764 case 'c':
3280af22 2765 PL_minus_c = TRUE;
79072805
LW
2766 s++;
2767 return s;
2768 case 'd':
bbce6d69 2769 forbid_setid("-d");
4633a7c4 2770 s++;
2cbb2ee1
RGS
2771
2772 /* -dt indicates to the debugger that threads will be used */
2773 if (*s == 't' && !isALNUM(s[1])) {
2774 ++s;
2775 my_setenv("PERL5DB_THREADED", "1");
2776 }
2777
70c94a19
RR
2778 /* The following permits -d:Mod to accepts arguments following an =
2779 in the fashion that -MSome::Mod does. */
2780 if (*s == ':' || *s == '=') {
06b5626a 2781 const char *start;
70c94a19
RR
2782 SV *sv;
2783 sv = newSVpv("use Devel::", 0);
2784 start = ++s;
2785 /* We now allow -d:Module=Foo,Bar */
2786 while(isALNUM(*s) || *s==':') ++s;
2787 if (*s != '=')
2788 sv_catpv(sv, start);
2789 else {
2790 sv_catpvn(sv, start, s-start);
2791 sv_catpv(sv, " split(/,/,q{");
2792 sv_catpv(sv, ++s);
3d27e215 2793 sv_catpv(sv, "})");
70c94a19 2794 }
4633a7c4 2795 s += strlen(s);
70c94a19 2796 my_setenv("PERL5DB", SvPV(sv, PL_na));
4633a7c4 2797 }
ed094faf 2798 if (!PL_perldb) {
3280af22 2799 PL_perldb = PERLDB_ALL;
a0d0e21e 2800 init_debugger();
ed094faf 2801 }
79072805
LW
2802 return s;
2803 case 'D':
0453d815 2804 {
79072805 2805#ifdef DEBUGGING
bbce6d69 2806 forbid_setid("-D");
b4ab917c 2807 s++;
dd374669 2808 PL_debug = get_debug_opts( (const char **)&s, 1) | DEBUG_TOP_FLAG;
12a43e32 2809#else /* !DEBUGGING */
0453d815 2810 if (ckWARN_d(WARN_DEBUGGING))
9014280d 2811 Perl_warner(aTHX_ packWARN(WARN_DEBUGGING),
e6e64d9b 2812 "Recompile perl with -DDEBUGGING to use -D switch (did you mean -d ?)\n");
a0d0e21e 2813 for (s++; isALNUM(*s); s++) ;
79072805 2814#endif
79072805 2815 return s;
0453d815 2816 }
4633a7c4 2817 case 'h':
ac27b0f5 2818 usage(PL_origargv[0]);
7ca617d0 2819 my_exit(0);
79072805 2820 case 'i':
3280af22
NIS
2821 if (PL_inplace)
2822 Safefree(PL_inplace);
c030f24b
GH
2823#if defined(__CYGWIN__) /* do backup extension automagically */
2824 if (*(s+1) == '\0') {
2825 PL_inplace = savepv(".bak");
2826 return s+1;
2827 }
2828#endif /* __CYGWIN__ */
3280af22 2829 PL_inplace = savepv(s+1);
a6e20a40
AL
2830 for (s = PL_inplace; *s && !isSPACE(*s); s++)
2831 ;
7b8d334a 2832 if (*s) {
fb73857a 2833 *s++ = '\0';
7b8d334a
GS
2834 if (*s == '-') /* Additional switches on #! line. */
2835 s++;
2836 }
fb73857a 2837 return s;
4e49a025 2838 case 'I': /* -I handled both here and in parse_body() */
bbce6d69 2839 forbid_setid("-I");
fb73857a 2840 ++s;
2841 while (*s && isSPACE(*s))
2842 ++s;
2843 if (*s) {
774d564b 2844 char *e, *p;
0df16ed7
GS
2845 p = s;
2846 /* ignore trailing spaces (possibly followed by other switches) */
2847 do {
2848 for (e = p; *e && !isSPACE(*e); e++) ;
2849 p = e;
2850 while (isSPACE(*p))
2851 p++;
2852 } while (*p && *p != '-');
2853 e = savepvn(s, e-s);
88fe16b2 2854 incpush(e, TRUE, TRUE, FALSE, FALSE);
0df16ed7
GS
2855 Safefree(e);
2856 s = p;
2857 if (*s == '-')
2858 s++;
79072805
LW
2859 }
2860 else
a67e862a 2861 Perl_croak(aTHX_ "No directory specified for -I");
fb73857a 2862 return s;
79072805 2863 case 'l':
3280af22 2864 PL_minus_l = TRUE;
79072805 2865 s++;
7889fe52
NIS
2866 if (PL_ors_sv) {
2867 SvREFCNT_dec(PL_ors_sv);
2868 PL_ors_sv = Nullsv;
2869 }
79072805 2870 if (isDIGIT(*s)) {
53305cf1 2871 I32 flags = 0;
a3b680e6 2872 STRLEN numlen;
7889fe52 2873 PL_ors_sv = newSVpvn("\n",1);
53305cf1
NC
2874 numlen = 3 + (*s == '0');
2875 *SvPVX(PL_ors_sv) = (char)grok_oct(s, &numlen, &flags, NULL);
79072805
LW
2876 s += numlen;
2877 }
2878 else {
8bfdd7d9 2879 if (RsPARA(PL_rs)) {
7889fe52
NIS
2880 PL_ors_sv = newSVpvn("\n\n",2);
2881 }
2882 else {
8bfdd7d9 2883 PL_ors_sv = newSVsv(PL_rs);
c07a80fd 2884 }
79072805
LW
2885 }
2886 return s;
06492da6
SF
2887 case 'A':
2888 forbid_setid("-A");
930366bd
RGS
2889 if (!PL_preambleav)
2890 PL_preambleav = newAV();
aefc56c5
SF
2891 s++;
2892 {
2893 char *start = s;
2894 SV *sv = newSVpv("use assertions::activate", 24);
2895 while(isALNUM(*s) || *s == ':') ++s;
2896 if (s != start) {
2897 sv_catpvn(sv, "::", 2);
2898 sv_catpvn(sv, start, s-start);
2899 }
2900 if (*s == '=') {
2901 sv_catpvn(sv, " split(/,/,q\0", 13);
2902 sv_catpv(sv, s+1);
2903 sv_catpvn(sv, "\0)", 2);
2904 s+=strlen(s);
2905 }
2906 else if (*s != '\0') {
2907 Perl_croak(aTHX_ "Can't use '%c' after -A%.*s", *s, s-start, start);
2908 }
06492da6 2909 av_push(PL_preambleav, sv);
aefc56c5 2910 return s;
06492da6 2911 }
1a30305b 2912 case 'M':
bbce6d69 2913 forbid_setid("-M"); /* XXX ? */
1a30305b 2914 /* FALL THROUGH */
2915 case 'm':
bbce6d69 2916 forbid_setid("-m"); /* XXX ? */
1a30305b 2917 if (*++s) {
a5f75d66 2918 char *start;
11343788 2919 SV *sv;
e1ec3a88 2920 const char *use = "use ";
a5f75d66
AD
2921 /* -M-foo == 'no foo' */
2922 if (*s == '-') { use = "no "; ++s; }
11343788 2923 sv = newSVpv(use,0);
a5f75d66 2924 start = s;
1a30305b 2925 /* We allow -M'Module qw(Foo Bar)' */
c07a80fd 2926 while(isALNUM(*s) || *s==':') ++s;
2927 if (*s != '=') {
11343788 2928 sv_catpv(sv, start);
c07a80fd 2929 if (*(start-1) == 'm') {
2930 if (*s != '\0')
cea2e8a9 2931 Perl_croak(aTHX_ "Can't use '%c' after -mname", *s);
11343788 2932 sv_catpv( sv, " ()");
c07a80fd 2933 }
2934 } else {
6df41af2 2935 if (s == start)
be98fb35
GS
2936 Perl_croak(aTHX_ "Module name required with -%c option",
2937 s[-1]);
11343788 2938 sv_catpvn(sv, start, s-start);
3d27e215
LM
2939 sv_catpv(sv, " split(/,/,q");
2940 sv_catpvn(sv, "\0)", 1); /* Use NUL as q//-delimiter. */
11343788 2941 sv_catpv(sv, ++s);
3d27e215 2942 sv_catpvn(sv, "\0)", 2);
c07a80fd 2943 }
1a30305b 2944 s += strlen(s);
5c831c24 2945 if (!PL_preambleav)
3280af22
NIS
2946 PL_preambleav = newAV();
2947 av_push(PL_preambleav, sv);
1a30305b 2948 }
2949 else
9e81e6a1 2950 Perl_croak(aTHX_ "Missing argument to -%c", *(s-1));
1a30305b 2951 return s;
79072805 2952 case 'n':
3280af22 2953 PL_minus_n = TRUE;
79072805
LW
2954 s++;
2955 return s;
2956 case 'p':
3280af22 2957 PL_minus_p = TRUE;
79072805
LW
2958 s++;
2959 return s;
2960 case 's':
bbce6d69 2961 forbid_setid("-s");
3280af22 2962 PL_doswitches = TRUE;
79072805
LW
2963 s++;
2964 return s;
6537fe72
MS
2965 case 't':
2966 if (!PL_tainting)
22f7c9c9 2967 TOO_LATE_FOR('t');
6537fe72
MS
2968 s++;
2969 return s;
463ee0b2 2970 case 'T':
3280af22 2971 if (!PL_tainting)
22f7c9c9 2972 TOO_LATE_FOR('T');
463ee0b2
LW
2973 s++;
2974 return s;
79072805 2975 case 'u':
bf4acbe4
GS
2976#ifdef MACOS_TRADITIONAL
2977 Perl_croak(aTHX_ "Believe me, you don't want to use \"-u\" on a Macintosh");
2978#endif
3280af22 2979 PL_do_undump = TRUE;
79072805
LW
2980 s++;
2981 return s;
2982 case 'U':
3280af22 2983 PL_unsafe = TRUE;
79072805
LW
2984 s++;
2985 return s;
2986 case 'v':
d7aa5382
JP
2987 if (!sv_derived_from(PL_patchlevel, "version"))
2988 (void *)upg_version(PL_patchlevel);
8e9464f1 2989#if !defined(DGUX)
b0e47665 2990 PerlIO_printf(PerlIO_stdout(),
52ea0aec 2991 Perl_form(aTHX_ "\nThis is perl, %"SVf" built for %s",
d7aa5382
JP
2992 vstringify(PL_patchlevel),
2993 ARCHNAME));
8e9464f1
JH
2994#else /* DGUX */
2995/* Adjust verbose output as in the perl that ships with the DG/UX OS from EMC */
2996 PerlIO_printf(PerlIO_stdout(),
52ea0aec 2997 Perl_form(aTHX_ "\nThis is perl, %"SVf"\n",
d7aa5382 2998 vstringify(PL_patchlevel)));
8e9464f1
JH
2999 PerlIO_printf(PerlIO_stdout(),
3000 Perl_form(aTHX_ " built under %s at %s %s\n",
3001 OSNAME, __DATE__, __TIME__));
3002 PerlIO_printf(PerlIO_stdout(),
3003 Perl_form(aTHX_ " OS Specific Release: %s\n",
40a39f85 3004 OSVERS));
8e9464f1
JH
3005#endif /* !DGUX */
3006
fb73857a 3007#if defined(LOCAL_PATCH_COUNT)
3008 if (LOCAL_PATCH_COUNT > 0)
b0e47665
GS
3009 PerlIO_printf(PerlIO_stdout(),
3010 "\n(with %d registered patch%s, "
3011 "see perl -V for more detail)",
3012 (int)LOCAL_PATCH_COUNT,
3013 (LOCAL_PATCH_COUNT!=1) ? "es" : "");
a5f75d66 3014#endif
1a30305b 3015
b0e47665 3016 PerlIO_printf(PerlIO_stdout(),
359b00fe 3017 "\n\nCopyright 1987-2005, Larry Wall\n");
eae9c151
JH
3018#ifdef MACOS_TRADITIONAL
3019 PerlIO_printf(PerlIO_stdout(),
be3c0a43 3020 "\nMac OS port Copyright 1991-2002, Matthias Neeracher;\n"
03765510 3021 "maintained by Chris Nandor\n");
eae9c151 3022#endif
79072805 3023#ifdef MSDOS
b0e47665
GS
3024 PerlIO_printf(PerlIO_stdout(),
3025 "\nMS-DOS port Copyright (c) 1989, 1990, Diomidis Spinellis\n");
55497cff 3026#endif
3027#ifdef DJGPP
b0e47665
GS
3028 PerlIO_printf(PerlIO_stdout(),
3029 "djgpp v2 port (jpl5003c) by Hirofumi Watanabe, 1996\n"
3030 "djgpp v2 port (perl5004+) by Laszlo Molnar, 1997-1999\n");
4633a7c4 3031#endif
79072805 3032#ifdef OS2
b0e47665
GS
3033 PerlIO_printf(PerlIO_stdout(),
3034 "\n\nOS/2 port Copyright (c) 1990, 1991, Raymond Chen, Kai Uwe Rommel\n"
be3c0a43 3035 "Version 5 port Copyright (c) 1994-2002, Andreas Kaiser, Ilya Zakharevich\n");
79072805 3036#endif
79072805 3037#ifdef atarist
b0e47665
GS
3038 PerlIO_printf(PerlIO_stdout(),
3039 "atariST series port, ++jrb bammi@cadence.com\n");
79072805 3040#endif
a3f9223b 3041#ifdef __BEOS__
b0e47665
GS
3042 PerlIO_printf(PerlIO_stdout(),
3043 "BeOS port Copyright Tom Spindler, 1997-1999\n");
a3f9223b 3044#endif
1d84e8df 3045#ifdef MPE
b0e47665 3046 PerlIO_printf(PerlIO_stdout(),
e583a879 3047 "MPE/iX port Copyright by Mark Klein and Mark Bixby, 1996-2003\n");
1d84e8df 3048#endif
9d116dd7 3049#ifdef OEMVS
b0e47665
GS
3050 PerlIO_printf(PerlIO_stdout(),
3051 "MVS (OS390) port by Mortice Kern Systems, 1997-1999\n");
9d116dd7 3052#endif
495c5fdc 3053#ifdef __VOS__
b0e47665 3054 PerlIO_printf(PerlIO_stdout(),
94efb9fb 3055 "Stratus VOS port by Paul.Green@stratus.com, 1997-2002\n");
495c5fdc 3056#endif
092bebab 3057#ifdef __OPEN_VM
b0e47665
GS
3058 PerlIO_printf(PerlIO_stdout(),
3059 "VM/ESA port by Neale Ferguson, 1998-1999\n");
092bebab 3060#endif
a1a0e61e 3061#ifdef POSIX_BC
b0e47665
GS
3062 PerlIO_printf(PerlIO_stdout(),
3063 "BS2000 (POSIX) port by Start Amadeus GmbH, 1998-1999\n");
a1a0e61e 3064#endif
61ae2fbf 3065#ifdef __MINT__
b0e47665
GS
3066 PerlIO_printf(PerlIO_stdout(),
3067 "MiNT port by Guido Flohr, 1997-1999\n");
61ae2fbf 3068#endif
f83d2536 3069#ifdef EPOC
b0e47665 3070 PerlIO_printf(PerlIO_stdout(),
be3c0a43 3071 "EPOC port by Olaf Flebbe, 1999-2002\n");
f83d2536 3072#endif
e1caacb4 3073#ifdef UNDER_CE
b475b3e6
JH
3074 PerlIO_printf(PerlIO_stdout(),"WINCE port by Rainer Keuchel, 2001-2002\n");
3075 PerlIO_printf(PerlIO_stdout(),"Built on " __DATE__ " " __TIME__ "\n\n");
e1caacb4
JH
3076 wce_hitreturn();
3077#endif
27da23d5
JH
3078#ifdef SYMBIAN
3079 PerlIO_printf(PerlIO_stdout(),
3080 "Symbian port by Nokia, 2004-2005\n");
3081#endif
baed7233
DL
3082#ifdef BINARY_BUILD_NOTICE
3083 BINARY_BUILD_NOTICE;
3084#endif
b0e47665
GS
3085 PerlIO_printf(PerlIO_stdout(),
3086 "\n\
79072805 3087Perl may be copied only under the terms of either the Artistic License or the\n\
3d6f292d 3088GNU General Public License, which may be found in the Perl 5 source kit.\n\n\
95103687 3089Complete documentation for Perl, including FAQ lists, should be found on\n\
a0288114 3090this system using \"man perl\" or \"perldoc perl\". If you have access to the\n\
c9e30dd8 3091Internet, point your browser at http://www.perl.org/, the Perl Home Page.\n\n");
7ca617d0 3092 my_exit(0);
79072805 3093 case 'w':
599cee73 3094 if (! (PL_dowarn & G_WARN_ALL_MASK))
ac27b0f5 3095 PL_dowarn |= G_WARN_ON;
599cee73
PM
3096 s++;
3097 return s;
3098 case 'W':
ac27b0f5 3099 PL_dowarn = G_WARN_ALL_ON|G_WARN_ON;
317ea90d
MS
3100 if (!specialWARN(PL_compiling.cop_warnings))
3101 SvREFCNT_dec(PL_compiling.cop_warnings);
d3a7d8c7 3102 PL_compiling.cop_warnings = pWARN_ALL ;
599cee73
PM
3103 s++;
3104 return s;
3105 case 'X':
ac27b0f5 3106 PL_dowarn = G_WARN_ALL_OFF;
317ea90d
MS
3107 if (!specialWARN(PL_compiling.cop_warnings))
3108 SvREFCNT_dec(PL_compiling.cop_warnings);
d3a7d8c7 3109 PL_compiling.cop_warnings = pWARN_NONE ;
79072805
LW
3110 s++;
3111 return s;
a0d0e21e 3112 case '*':
79072805
LW
3113 case ' ':
3114 if (s[1] == '-') /* Additional switches on #! line. */
3115 return s+2;
3116 break;
a0d0e21e 3117 case '-':
79072805 3118 case 0:
51882d45 3119#if defined(WIN32) || !defined(PERL_STRICT_CR)
a868473f
NIS
3120 case '\r':
3121#endif
79072805
LW
3122 case '\n':
3123 case '\t':
3124 break;
aa689395 3125#ifdef ALTERNATE_SHEBANG
3126 case 'S': /* OS/2 needs -S on "extproc" line. */
3127 break;
3128#endif
a0d0e21e 3129 case 'P':
3280af22 3130 if (PL_preprocess)
a0d0e21e
LW
3131 return s+1;
3132 /* FALL THROUGH */
79072805 3133 default:
cea2e8a9 3134 Perl_croak(aTHX_ "Can't emulate -%.1s on #! line",s);
79072805
LW
3135 }
3136 return Nullch;
3137}
3138
3139/* compliments of Tom Christiansen */
3140
3141/* unexec() can be found in the Gnu emacs distribution */
ee580363 3142/* Known to work with -DUNEXEC and using unexelf.c from GNU emacs-20.2 */
79072805
LW
3143
3144void
864dbfa3 3145Perl_my_unexec(pTHX)
79072805
LW
3146{
3147#ifdef UNEXEC
46fc3d4c 3148 SV* prog;
3149 SV* file;
ee580363 3150 int status = 1;
79072805
LW
3151 extern int etext;
3152
ee580363 3153 prog = newSVpv(BIN_EXP, 0);
46fc3d4c 3154 sv_catpv(prog, "/perl");
6b88bc9c 3155 file = newSVpv(PL_origfilename, 0);
46fc3d4c 3156 sv_catpv(file, ".perldump");
79072805 3157
ee580363
GS
3158 unexec(SvPVX(file), SvPVX(prog), &etext, sbrk(0), 0);
3159 /* unexec prints msg to stderr in case of failure */
6ad3d225 3160 PerlProc_exit(status);
79072805 3161#else
a5f75d66
AD
3162# ifdef VMS
3163# include <lib$routines.h>
3164 lib$signal(SS$_DEBUG); /* ssdef.h #included from vmsish.h */
aa689395 3165# else
79072805 3166 ABORT(); /* for use with undump */
aa689395 3167# endif
a5f75d66 3168#endif
79072805
LW
3169}
3170
cb68f92d
GS
3171/* initialize curinterp */
3172STATIC void
cea2e8a9 3173S_init_interp(pTHX)
cb68f92d
GS
3174{
3175
acfe0abc
GS
3176#ifdef MULTIPLICITY
3177# define PERLVAR(var,type)
3178# define PERLVARA(var,n,type)
3179# if defined(PERL_IMPLICIT_CONTEXT)
3180# if defined(USE_5005THREADS)
3181# define PERLVARI(var,type,init) PERL_GET_INTERP->var = init;
27da23d5 3182# define PERLVARIC(var,type,init) PERL_GET_INTERP->var = init;
acfe0abc
GS
3183# else /* !USE_5005THREADS */
3184# define PERLVARI(var,type,init) aTHX->var = init;
3185# define PERLVARIC(var,type,init) aTHX->var = init;
3186# endif /* USE_5005THREADS */
3967c732 3187# else
acfe0abc
GS
3188# define PERLVARI(var,type,init) PERL_GET_INTERP->var = init;
3189# define PERLVARIC(var,type,init) PERL_GET_INTERP->var = init;
066ef5b5 3190# endif
acfe0abc
GS
3191# include "intrpvar.h"
3192# ifndef USE_5005THREADS
3193# include "thrdvar.h"
3194# endif
3195# undef PERLVAR
3196# undef PERLVARA
3197# undef PERLVARI
3198# undef PERLVARIC
3199#else
3200# define PERLVAR(var,type)
3201# define PERLVARA(var,n,type)
3202# define PERLVARI(var,type,init) PL_##var = init;
3203# define PERLVARIC(var,type,init) PL_##var = init;
3204# include "intrpvar.h"
3205# ifndef USE_5005THREADS
3206# include "thrdvar.h"
3207# endif
3208# undef PERLVAR
3209# undef PERLVARA
3210# undef PERLVARI
3211# undef PERLVARIC
cb68f92d
GS
3212#endif
3213
cb68f92d
GS
3214}
3215
76e3520e 3216STATIC void
cea2e8a9 3217S_init_main_stash(pTHX)
79072805 3218{
463ee0b2 3219 GV *gv;
6e72f9df 3220
3280af22 3221 PL_curstash = PL_defstash = newHV();
79cb57f6 3222 PL_curstname = newSVpvn("main",4);
adbc6bb1
LW
3223 gv = gv_fetchpv("main::",TRUE, SVt_PVHV);
3224 SvREFCNT_dec(GvHV(gv));
3280af22 3225 GvHV(gv) = (HV*)SvREFCNT_inc(PL_defstash);
463ee0b2 3226 SvREADONLY_on(gv);
bfcb3514 3227 Perl_hv_name_set(aTHX_ PL_defstash, "main", 4, 0);
3280af22
NIS
3228 PL_incgv = gv_HVadd(gv_AVadd(gv_fetchpv("INC",TRUE, SVt_PVAV)));
3229 GvMULTI_on(PL_incgv);
3230 PL_hintgv = gv_fetchpv("\010",TRUE, SVt_PV); /* ^H */
3231 GvMULTI_on(PL_hintgv);
3232 PL_defgv = gv_fetchpv("_",TRUE, SVt_PVAV);
3233 PL_errgv = gv_HVadd(gv_fetchpv("@", TRUE, SVt_PV));
3234 GvMULTI_on(PL_errgv);
3235 PL_replgv = gv_fetchpv("\022", TRUE, SVt_PV); /* ^R */
3236 GvMULTI_on(PL_replgv);
cea2e8a9 3237 (void)Perl_form(aTHX_ "%240s",""); /* Preallocate temp - for immediate signals. */
38a03e6e
MB
3238 sv_grow(ERRSV, 240); /* Preallocate - for immediate signals. */
3239 sv_setpvn(ERRSV, "", 0);
3280af22 3240 PL_curstash = PL_defstash;
11faa288 3241 CopSTASH_set(&PL_compiling, PL_defstash);
ed094faf 3242 PL_debstash = GvHV(gv_fetchpv("DB::", GV_ADDMULTI, SVt_PVHV));
3280af22 3243 PL_globalstash = GvHV(gv_fetchpv("CORE::GLOBAL::", GV_ADDMULTI, SVt_PVHV));
4633a7c4 3244 /* We must init $/ before switches are processed. */
864dbfa3 3245 sv_setpvn(get_sv("/", TRUE), "\n", 1);
79072805
LW
3246}
3247
ae3f3efd 3248/* PSz 18 Nov 03 fdscript now global but do not change prototype */
76e3520e 3249STATIC void
dd374669 3250S_open_script(pTHX_ const char *scriptname, bool dosearch, SV *sv)
79072805 3251{
ae3f3efd 3252#ifndef IAMSUID
e1ec3a88
AL
3253 const char *quote;
3254 const char *code;
3255 const char *cpp_discard_flag;
3256 const char *perl;
ae3f3efd 3257#endif
27da23d5 3258 dVAR;
1b24ed4b 3259
ae3f3efd
PS
3260 PL_fdscript = -1;
3261 PL_suidscript = -1;
79072805 3262
3280af22 3263 if (PL_e_script) {
ff5bdd37 3264 PL_origfilename = savepvn("-e", 2);
96436eeb 3265 }
6c4ab083
GS
3266 else {
3267 /* if find_script() returns, it returns a malloc()-ed value */
dd374669 3268 scriptname = PL_origfilename = find_script(scriptname, dosearch, NULL, 1);
6c4ab083
GS
3269
3270 if (strnEQ(scriptname, "/dev/fd/", 8) && isDIGIT(scriptname[8]) ) {
e1ec3a88 3271 const char *s = scriptname + 8;
ae3f3efd 3272 PL_fdscript = atoi(s);
6c4ab083
GS
3273 while (isDIGIT(*s))
3274 s++;
3275 if (*s) {
ae3f3efd
PS
3276 /* PSz 18 Feb 04
3277 * Tell apart "normal" usage of fdscript, e.g.
3278 * with bash on FreeBSD:
3279 * perl <( echo '#!perl -DA'; echo 'print "$0\n"')
3280 * from usage in suidperl.
3281 * Does any "normal" usage leave garbage after the number???
3282 * Is it a mistake to use a similar /dev/fd/ construct for
3283 * suidperl?
3284 */
3285 PL_suidscript = 1;
3286 /* PSz 20 Feb 04
3287 * Be supersafe and do some sanity-checks.
3288 * Still, can we be sure we got the right thing?
3289 */
3290 if (*s != '/') {
3291 Perl_croak(aTHX_ "Wrong syntax (suid) fd script name \"%s\"\n", s);
3292 }
3293 if (! *(s+1)) {
3294 Perl_croak(aTHX_ "Missing (suid) fd script name\n");
3295 }
6c4ab083 3296 scriptname = savepv(s + 1);
3280af22 3297 Safefree(PL_origfilename);
dd374669 3298 PL_origfilename = (char *)scriptname;
6c4ab083
GS
3299 }
3300 }
3301 }
3302
05ec9bb3 3303 CopFILE_free(PL_curcop);
57843af0 3304 CopFILE_set(PL_curcop, PL_origfilename);
770526c1 3305 if (*PL_origfilename == '-' && PL_origfilename[1] == '\0')
dd374669 3306 scriptname = (char *)"";
ae3f3efd
PS
3307 if (PL_fdscript >= 0) {
3308 PL_rsfp = PerlIO_fdopen(PL_fdscript,PERL_SCRIPT_MODE);
1b24ed4b
MS
3309# if defined(HAS_FCNTL) && defined(F_SETFD)
3310 if (PL_rsfp)
3311 /* ensure close-on-exec */
3312 fcntl(PerlIO_fileno(PL_rsfp),F_SETFD,1);
3313# endif
96436eeb 3314 }
ae3f3efd
PS
3315#ifdef IAMSUID
3316 else {
86207487
NC
3317 Perl_croak(aTHX_ "sperl needs fd script\n"
3318 "You should not call sperl directly; do you need to "
3319 "change a #! line\nfrom sperl to perl?\n");
3320
ae3f3efd
PS
3321/* PSz 11 Nov 03
3322 * Do not open (or do other fancy stuff) while setuid.
3323 * Perl does the open, and hands script to suidperl on a fd;
3324 * suidperl only does some checks, sets up UIDs and re-execs
3325 * perl with that fd as it has always done.
3326 */
3327 }
3328 if (PL_suidscript != 1) {
3329 Perl_croak(aTHX_ "suidperl needs (suid) fd script\n");
3330 }
3331#else /* IAMSUID */
3280af22 3332 else if (PL_preprocess) {
dd374669 3333 const char *cpp_cfg = CPPSTDIN;
79cb57f6 3334 SV *cpp = newSVpvn("",0);
46fc3d4c 3335 SV *cmd = NEWSV(0,0);
3336
ae58f265
JH
3337 if (cpp_cfg[0] == 0) /* PERL_MICRO? */
3338 Perl_croak(aTHX_ "Can't run with cpp -P with CPPSTDIN undefined");
46fc3d4c 3339 if (strEQ(cpp_cfg, "cppstdin"))
cea2e8a9 3340 Perl_sv_catpvf(aTHX_ cpp, "%s/", BIN_EXP);
46fc3d4c 3341 sv_catpv(cpp, cpp_cfg);
79072805 3342
1b24ed4b
MS
3343# ifndef VMS
3344 sv_catpvn(sv, "-I", 2);
3345 sv_catpv(sv,PRIVLIB_EXP);
3346# endif
46fc3d4c 3347
14953ddc
MB
3348 DEBUG_P(PerlIO_printf(Perl_debug_log,
3349 "PL_preprocess: scriptname=\"%s\", cpp=\"%s\", sv=\"%s\", CPPMINUS=\"%s\"\n",
848ef955
NC
3350 scriptname, SvPVX_const (cpp), SvPVX_const (sv),
3351 CPPMINUS));
1b24ed4b
MS
3352
3353# if defined(MSDOS) || defined(WIN32) || defined(VMS)
3354 quote = "\"";
3355# else
3356 quote = "'";
3357# endif
3358
3359# ifdef VMS
3360 cpp_discard_flag = "";
3361# else
3362 cpp_discard_flag = "-C";
3363# endif
3364
3365# ifdef OS2
3366 perl = os2_execname(aTHX);
3367# else
3368 perl = PL_origargv[0];
3369# endif
3370
3371
3372 /* This strips off Perl comments which might interfere with
62375a60
NIS
3373 the C pre-processor, including #!. #line directives are
3374 deliberately stripped to avoid confusion with Perl's version
1b24ed4b
MS
3375 of #line. FWP played some golf with it so it will fit
3376 into VMS's 255 character buffer.
3377 */
3378 if( PL_doextract )
3379 code = "(1../^#!.*perl/i)|/^\\s*#(?!\\s*((ifn?|un)def|(el|end)?if|define|include|else|error|pragma)\\b)/||!($|=1)||print";
3380 else
3381 code = "/^\\s*#(?!\\s*((ifn?|un)def|(el|end)?if|define|include|else|error|pragma)\\b)/||!($|=1)||print";
3382
3383 Perl_sv_setpvf(aTHX_ cmd, "\
3384%s -ne%s%s%s %s | %"SVf" %s %"SVf" %s",
62375a60 3385 perl, quote, code, quote, scriptname, cpp,
1b24ed4b
MS
3386 cpp_discard_flag, sv, CPPMINUS);
3387
3280af22 3388 PL_doextract = FALSE;
0a6c758d 3389
62375a60
NIS
3390 DEBUG_P(PerlIO_printf(Perl_debug_log,
3391 "PL_preprocess: cmd=\"%s\"\n",
848ef955 3392 SvPVX_const(cmd)));
0a6c758d 3393
848ef955 3394 PL_rsfp = PerlProc_popen((char *)SvPVX_const(cmd), (char *)"r");
46fc3d4c 3395 SvREFCNT_dec(cmd);
3396 SvREFCNT_dec(cpp);
79072805
LW
3397 }
3398 else if (!*scriptname) {
bbce6d69 3399 forbid_setid("program input from stdin");
3280af22 3400 PL_rsfp = PerlIO_stdin();
79072805 3401 }
96436eeb 3402 else {
3280af22 3403 PL_rsfp = PerlIO_open(scriptname,PERL_SCRIPT_MODE);
1b24ed4b
MS
3404# if defined(HAS_FCNTL) && defined(F_SETFD)
3405 if (PL_rsfp)
3406 /* ensure close-on-exec */
3407 fcntl(PerlIO_fileno(PL_rsfp),F_SETFD,1);
3408# endif
96436eeb 3409 }
ae3f3efd 3410#endif /* IAMSUID */
3280af22 3411 if (!PL_rsfp) {
447218f8 3412 /* PSz 16 Sep 03 Keep neat error message */
fa3aa65a
JC
3413 Perl_croak(aTHX_ "Can't open perl script \"%s\": %s\n",
3414 CopFILE(PL_curcop), Strerror(errno));
13281fa4 3415 }
79072805 3416}
8d063cd8 3417
7b89560d
JH
3418/* Mention
3419 * I_SYSSTATVFS HAS_FSTATVFS
3420 * I_SYSMOUNT
c890dc6c 3421 * I_STATFS HAS_FSTATFS HAS_GETFSSTAT
7b89560d
JH
3422 * I_MNTENT HAS_GETMNTENT HAS_HASMNTOPT
3423 * here so that metaconfig picks them up. */
3424
104d25b7 3425#ifdef IAMSUID
864dbfa3 3426STATIC int
e688b231 3427S_fd_on_nosuid_fs(pTHX_ int fd)
104d25b7 3428{
ae3f3efd
PS
3429/* PSz 27 Feb 04
3430 * We used to do this as "plain" user (after swapping UIDs with setreuid);
3431 * but is needed also on machines without setreuid.
3432 * Seems safe enough to run as root.
3433 */
0545a864
JH
3434 int check_okay = 0; /* able to do all the required sys/libcalls */
3435 int on_nosuid = 0; /* the fd is on a nosuid fs */
ae3f3efd
PS
3436 /* PSz 12 Nov 03
3437 * Need to check noexec also: nosuid might not be set, the average
3438 * sysadmin would say that nosuid is irrelevant once he sets noexec.
3439 */
3440 int on_noexec = 0; /* the fd is on a noexec fs */
3441
104d25b7 3442/*
ad27e871 3443 * Preferred order: fstatvfs(), fstatfs(), ustat()+getmnt(), getmntent().
e688b231 3444 * fstatvfs() is UNIX98.
0545a864 3445 * fstatfs() is 4.3 BSD.
ad27e871 3446 * ustat()+getmnt() is pre-4.3 BSD.
0545a864
JH
3447 * getmntent() is O(number-of-mounted-filesystems) and can hang on
3448 * an irrelevant filesystem while trying to reach the right one.
104d25b7
JH
3449 */
3450
6439433f
JH
3451#undef FD_ON_NOSUID_CHECK_OKAY /* found the syscalls to do the check? */
3452
3453# if !defined(FD_ON_NOSUID_CHECK_OKAY) && \
3454 defined(HAS_FSTATVFS)
3455# define FD_ON_NOSUID_CHECK_OKAY
104d25b7 3456 struct statvfs stfs;
6439433f 3457
104d25b7
JH
3458 check_okay = fstatvfs(fd, &stfs) == 0;
3459 on_nosuid = check_okay && (stfs.f_flag & ST_NOSUID);
ae3f3efd
PS
3460#ifdef ST_NOEXEC
3461 /* ST_NOEXEC certainly absent on AIX 5.1, and doesn't seem to be documented
3462 on platforms where it is present. */
3463 on_noexec = check_okay && (stfs.f_flag & ST_NOEXEC);
3464#endif
6439433f 3465# endif /* fstatvfs */
ac27b0f5 3466
6439433f
JH
3467# if !defined(FD_ON_NOSUID_CHECK_OKAY) && \
3468 defined(PERL_MOUNT_NOSUID) && \
ae3f3efd 3469 defined(PERL_MOUNT_NOEXEC) && \
6439433f
JH
3470 defined(HAS_FSTATFS) && \
3471 defined(HAS_STRUCT_STATFS) && \
3472 defined(HAS_STRUCT_STATFS_F_FLAGS)
3473# define FD_ON_NOSUID_CHECK_OKAY
e688b231 3474 struct statfs stfs;
6439433f 3475
104d25b7 3476 check_okay = fstatfs(fd, &stfs) == 0;
104d25b7 3477 on_nosuid = check_okay && (stfs.f_flags & PERL_MOUNT_NOSUID);
ae3f3efd 3478 on_noexec = check_okay && (stfs.f_flags & PERL_MOUNT_NOEXEC);
6439433f
JH
3479# endif /* fstatfs */
3480
3481# if !defined(FD_ON_NOSUID_CHECK_OKAY) && \
3482 defined(PERL_MOUNT_NOSUID) && \
ae3f3efd 3483 defined(PERL_MOUNT_NOEXEC) && \
6439433f
JH
3484 defined(HAS_FSTAT) && \
3485 defined(HAS_USTAT) && \
3486 defined(HAS_GETMNT) && \
3487 defined(HAS_STRUCT_FS_DATA) && \
3488 defined(NOSTAT_ONE)
3489# define FD_ON_NOSUID_CHECK_OKAY
c623ac67 3490 Stat_t fdst;
6439433f 3491
0545a864 3492 if (fstat(fd, &fdst) == 0) {
6439433f
JH
3493 struct ustat us;
3494 if (ustat(fdst.st_dev, &us) == 0) {
3495 struct fs_data fsd;
3496 /* NOSTAT_ONE here because we're not examining fields which
3497 * vary between that case and STAT_ONE. */
ad27e871 3498 if (getmnt((int*)0, &fsd, (int)0, NOSTAT_ONE, us.f_fname) == 0) {
6439433f
JH
3499 size_t cmplen = sizeof(us.f_fname);
3500 if (sizeof(fsd.fd_req.path) < cmplen)
3501 cmplen = sizeof(fsd.fd_req.path);
3502 if (strnEQ(fsd.fd_req.path, us.f_fname, cmplen) &&
3503 fdst.st_dev == fsd.fd_req.dev) {
3504 check_okay = 1;
3505 on_nosuid = fsd.fd_req.flags & PERL_MOUNT_NOSUID;
ae3f3efd 3506 on_noexec = fsd.fd_req.flags & PERL_MOUNT_NOEXEC;
6439433f
JH
3507 }
3508 }
3509 }
3510 }
0545a864 3511 }
6439433f
JH
3512# endif /* fstat+ustat+getmnt */
3513
3514# if !defined(FD_ON_NOSUID_CHECK_OKAY) && \
3515 defined(HAS_GETMNTENT) && \
3516 defined(HAS_HASMNTOPT) && \
ae3f3efd
PS
3517 defined(MNTOPT_NOSUID) && \
3518 defined(MNTOPT_NOEXEC)
6439433f
JH
3519# define FD_ON_NOSUID_CHECK_OKAY
3520 FILE *mtab = fopen("/etc/mtab", "r");
3521 struct mntent *entry;
c623ac67 3522 Stat_t stb, fsb;
104d25b7
JH
3523
3524 if (mtab && (fstat(fd, &stb) == 0)) {
6439433f
JH
3525 while (entry = getmntent(mtab)) {
3526 if (stat(entry->mnt_dir, &fsb) == 0
3527 && fsb.st_dev == stb.st_dev)
3528 {
3529 /* found the filesystem */
3530 check_okay = 1;
3531 if (hasmntopt(entry, MNTOPT_NOSUID))
3532 on_nosuid = 1;
ae3f3efd
PS
3533 if (hasmntopt(entry, MNTOPT_NOEXEC))
3534 on_noexec = 1;
6439433f
JH
3535 break;
3536 } /* A single fs may well fail its stat(). */
3537 }
104d25b7
JH
3538 }
3539 if (mtab)
6439433f
JH
3540 fclose(mtab);
3541# endif /* getmntent+hasmntopt */
0545a864 3542
ac27b0f5 3543 if (!check_okay)
ae3f3efd
PS
3544 Perl_croak(aTHX_ "Can't check filesystem of script \"%s\" for nosuid/noexec", PL_origfilename);
3545 if (on_nosuid)
3546 Perl_croak(aTHX_ "Setuid script \"%s\" on nosuid filesystem", PL_origfilename);
3547 if (on_noexec)
3548 Perl_croak(aTHX_ "Setuid script \"%s\" on noexec filesystem", PL_origfilename);
3549 return ((!check_okay) || on_nosuid || on_noexec);
104d25b7
JH
3550}
3551#endif /* IAMSUID */
3552
76e3520e 3553STATIC void
e1ec3a88 3554S_validate_suid(pTHX_ const char *validarg, const char *scriptname)
79072805 3555{
27da23d5 3556 dVAR;
155aba94 3557#ifdef IAMSUID
ae3f3efd
PS
3558 /* int which; */
3559#endif /* IAMSUID */
96436eeb 3560
13281fa4
LW
3561 /* do we need to emulate setuid on scripts? */
3562
3563 /* This code is for those BSD systems that have setuid #! scripts disabled
3564 * in the kernel because of a security problem. Merely defining DOSUID
3565 * in perl will not fix that problem, but if you have disabled setuid
3566 * scripts in the kernel, this will attempt to emulate setuid and setgid
3567 * on scripts that have those now-otherwise-useless bits set. The setuid
27e2fb84
LW
3568 * root version must be called suidperl or sperlN.NNN. If regular perl
3569 * discovers that it has opened a setuid script, it calls suidperl with
3570 * the same argv that it had. If suidperl finds that the script it has
3571 * just opened is NOT setuid root, it sets the effective uid back to the
3572 * uid. We don't just make perl setuid root because that loses the
3573 * effective uid we had before invoking perl, if it was different from the
3574 * uid.
ae3f3efd
PS
3575 * PSz 27 Feb 04
3576 * Description/comments above do not match current workings:
3577 * suidperl must be hardlinked to sperlN.NNN (that is what we exec);
3578 * suidperl called with script open and name changed to /dev/fd/N/X;
3579 * suidperl croaks if script is not setuid;
3580 * making perl setuid would be a huge security risk (and yes, that
3581 * would lose any euid we might have had).
13281fa4
LW
3582 *
3583 * DOSUID must be defined in both perl and suidperl, and IAMSUID must
3584 * be defined in suidperl only. suidperl must be setuid root. The
3585 * Configure script will set this up for you if you want it.
3586 */
a687059c 3587
13281fa4 3588#ifdef DOSUID
dd720ed5 3589 const char *s, *s2;
a0d0e21e 3590
b28d0864 3591 if (PerlLIO_fstat(PerlIO_fileno(PL_rsfp),&PL_statbuf) < 0) /* normal stat is insecure */
cea2e8a9 3592 Perl_croak(aTHX_ "Can't stat script \"%s\"",PL_origfilename);
ae3f3efd 3593 if (PL_statbuf.st_mode & (S_ISUID|S_ISGID)) {
79072805 3594 I32 len;
dd720ed5 3595 const char *linestr;
13281fa4 3596
a687059c 3597#ifdef IAMSUID
ae3f3efd
PS
3598 if (PL_fdscript < 0 || PL_suidscript != 1)
3599 Perl_croak(aTHX_ "Need (suid) fdscript in suidperl\n"); /* We already checked this */
3600 /* PSz 11 Nov 03
3601 * Since the script is opened by perl, not suidperl, some of these
3602 * checks are superfluous. Leaving them in probably does not lower
3603 * security(?!).
3604 */
3605 /* PSz 27 Feb 04
3606 * Do checks even for systems with no HAS_SETREUID.
3607 * We used to swap, then re-swap UIDs with
3608#ifdef HAS_SETREUID
3609 if (setreuid(PL_euid,PL_uid) < 0
3610 || PerlProc_getuid() != PL_euid || PerlProc_geteuid() != PL_uid)
3611 Perl_croak(aTHX_ "Can't swap uid and euid");
3612#endif
3613#ifdef HAS_SETREUID
3614 if (setreuid(PL_uid,PL_euid) < 0
3615 || PerlProc_getuid() != PL_uid || PerlProc_geteuid() != PL_euid)
3616 Perl_croak(aTHX_ "Can't reswap uid and euid");
3617#endif
3618 */
3619
a687059c
LW
3620 /* On this access check to make sure the directories are readable,
3621 * there is actually a small window that the user could use to make
3622 * filename point to an accessible directory. So there is a faint
3623 * chance that someone could execute a setuid script down in a
3624 * non-accessible directory. I don't know what to do about that.
3625 * But I don't think it's too important. The manual lies when
3626 * it says access() is useful in setuid programs.
ae3f3efd
PS
3627 *
3628 * So, access() is pretty useless... but not harmful... do anyway.
a687059c 3629 */
e57400b1 3630 if (PerlLIO_access(CopFILE(PL_curcop),1)) { /*double check*/
ae3f3efd 3631 Perl_croak(aTHX_ "Can't access() script\n");
e57400b1 3632 }
ae3f3efd 3633
a687059c
LW
3634 /* If we can swap euid and uid, then we can determine access rights
3635 * with a simple stat of the file, and then compare device and
3636 * inode to make sure we did stat() on the same file we opened.
3637 * Then we just have to make sure he or she can execute it.
ae3f3efd
PS
3638 *
3639 * PSz 24 Feb 04
3640 * As the script is opened by perl, not suidperl, we do not need to
3641 * care much about access rights.
3642 *
3643 * The 'script changed' check is needed, or we can get lied to
3644 * about $0 with e.g.
3645 * suidperl /dev/fd/4//bin/x 4<setuidscript
3646 * Without HAS_SETREUID, is it safe to stat() as root?
3647 *
3648 * Are there any operating systems that pass /dev/fd/xxx for setuid
3649 * scripts, as suggested/described in perlsec(1)? Surely they do not
3650 * pass the script name as we do, so the "script changed" test would
3651 * fail for them... but we never get here with
3652 * SETUID_SCRIPTS_ARE_SECURE_NOW defined.
3653 *
3654 * This is one place where we must "lie" about return status: not
3655 * say if the stat() failed. We are doing this as root, and could
3656 * be tricked into reporting existence or not of files that the
3657 * "plain" user cannot even see.
a687059c
LW
3658 */
3659 {
c623ac67 3660 Stat_t tmpstatbuf;
ae3f3efd
PS
3661 if (PerlLIO_stat(CopFILE(PL_curcop),&tmpstatbuf) < 0 ||
3662 tmpstatbuf.st_dev != PL_statbuf.st_dev ||
b28d0864 3663 tmpstatbuf.st_ino != PL_statbuf.st_ino) {
ae3f3efd 3664 Perl_croak(aTHX_ "Setuid script changed\n");
a687059c 3665 }
ae3f3efd 3666
a687059c 3667 }
ae3f3efd
PS
3668 if (!cando(S_IXUSR,FALSE,&PL_statbuf)) /* can real uid exec? */
3669 Perl_croak(aTHX_ "Real UID cannot exec script\n");
3670
3671 /* PSz 27 Feb 04
3672 * We used to do this check as the "plain" user (after swapping
3673 * UIDs). But the check for nosuid and noexec filesystem is needed,
3674 * and should be done even without HAS_SETREUID. (Maybe those
3675 * operating systems do not have such mount options anyway...)
3676 * Seems safe enough to do as root.
3677 */
3678#if !defined(NO_NOSUID_CHECK)
3679 if (fd_on_nosuid_fs(PerlIO_fileno(PL_rsfp))) {
3680 Perl_croak(aTHX_ "Setuid script on nosuid or noexec filesystem\n");
3681 }
3682#endif
a687059c
LW
3683#endif /* IAMSUID */
3684
e57400b1 3685 if (!S_ISREG(PL_statbuf.st_mode)) {
ae3f3efd 3686 Perl_croak(aTHX_ "Setuid script not plain file\n");
e57400b1 3687 }
b28d0864 3688 if (PL_statbuf.st_mode & S_IWOTH)
cea2e8a9 3689 Perl_croak(aTHX_ "Setuid/gid script is writable by world");
6b88bc9c 3690 PL_doswitches = FALSE; /* -s is insecure in suid */
ae3f3efd 3691 /* PSz 13 Nov 03 But -s was caught elsewhere ... so unsetting it here is useless(?!) */
57843af0 3692 CopLINE_inc(PL_curcop);
dd720ed5 3693 linestr = SvPV_nolen_const(PL_linestr);
6b88bc9c 3694 if (sv_gets(PL_linestr, PL_rsfp, 0) == Nullch ||
dd720ed5 3695 strnNE(linestr,"#!",2) ) /* required even on Sys V */
cea2e8a9 3696 Perl_croak(aTHX_ "No #! line");
dd720ed5
NC
3697 linestr+=2;
3698 s = linestr;
ae3f3efd
PS
3699 /* PSz 27 Feb 04 */
3700 /* Sanity check on line length */
3701 if (strlen(s) < 1 || strlen(s) > 4000)
3702 Perl_croak(aTHX_ "Very long #! line");
3703 /* Allow more than a single space after #! */
3704 while (isSPACE(*s)) s++;
3705 /* Sanity check on buffer end */
3706 while ((*s) && !isSPACE(*s)) s++;
dd720ed5 3707 for (s2 = s; (s2 > linestr &&
3792a11b
NC
3708 (isDIGIT(s2[-1]) || s2[-1] == '.' || s2[-1] == '_'
3709 || s2[-1] == '-')); s2--) ;
ae3f3efd 3710 /* Sanity check on buffer start */
dd720ed5
NC
3711 if ( (s2-4 < linestr || strnNE(s2-4,"perl",4)) &&
3712 (s-9 < linestr || strnNE(s-9,"perl",4)) )
cea2e8a9 3713 Perl_croak(aTHX_ "Not a perl script");
a687059c 3714 while (*s == ' ' || *s == '\t') s++;
13281fa4
LW
3715 /*
3716 * #! arg must be what we saw above. They can invoke it by
3717 * mentioning suidperl explicitly, but they may not add any strange
3718 * arguments beyond what #! says if they do invoke suidperl that way.
3719 */
ae3f3efd
PS
3720 /*
3721 * The way validarg was set up, we rely on the kernel to start
3722 * scripts with argv[1] set to contain all #! line switches (the
3723 * whole line).
3724 */
3725 /*
3726 * Check that we got all the arguments listed in the #! line (not
3727 * just that there are no extraneous arguments). Might not matter
3728 * much, as switches from #! line seem to be acted upon (also), and
3729 * so may be checked and trapped in perl. But, security checks must
3730 * be done in suidperl and not deferred to perl. Note that suidperl
3731 * does not get around to parsing (and checking) the switches on
3732 * the #! line (but execs perl sooner).
3733 * Allow (require) a trailing newline (which may be of two
3734 * characters on some architectures?) (but no other trailing
3735 * whitespace).
3736 */
13281fa4
LW
3737 len = strlen(validarg);
3738 if (strEQ(validarg," PHOOEY ") ||
ae3f3efd
PS
3739 strnNE(s,validarg,len) || !isSPACE(s[len]) ||
3740 !(strlen(s) == len+1 || (strlen(s) == len+2 && isSPACE(s[len+1]))))
cea2e8a9 3741 Perl_croak(aTHX_ "Args must match #! line");
a687059c
LW
3742
3743#ifndef IAMSUID
ae3f3efd
PS
3744 if (PL_fdscript < 0 &&
3745 PL_euid != PL_uid && (PL_statbuf.st_mode & S_ISUID) &&
b28d0864
NIS
3746 PL_euid == PL_statbuf.st_uid)
3747 if (!PL_do_undump)
cea2e8a9 3748 Perl_croak(aTHX_ "YOU HAVEN'T DISABLED SET-ID SCRIPTS IN THE KERNEL YET!\n\
11fb1898 3749FIX YOUR KERNEL, OR PUT A C WRAPPER AROUND THIS SCRIPT!\n");
a687059c 3750#endif /* IAMSUID */
13281fa4 3751
ae3f3efd
PS
3752 if (PL_fdscript < 0 &&
3753 PL_euid) { /* oops, we're not the setuid root perl */
3754 /* PSz 18 Feb 04
3755 * When root runs a setuid script, we do not go through the same
3756 * steps of execing sperl and then perl with fd scripts, but
3757 * simply set up UIDs within the same perl invocation; so do
3758 * not have the same checks (on options, whatever) that we have
3759 * for plain users. No problem really: would have to be a script
3760 * that does not actually work for plain users; and if root is
3761 * foolish and can be persuaded to run such an unsafe script, he
3762 * might run also non-setuid ones, and deserves what he gets.
3763 *
3764 * Or, we might drop the PL_euid check above (and rely just on
3765 * PL_fdscript to avoid loops), and do the execs
3766 * even for root.
3767 */
13281fa4 3768#ifndef IAMSUID
ae3f3efd
PS
3769 int which;
3770 /* PSz 11 Nov 03
3771 * Pass fd script to suidperl.
3772 * Exec suidperl, substituting fd script for scriptname.
3773 * Pass script name as "subdir" of fd, which perl will grok;
3774 * in fact will use that to distinguish this from "normal"
3775 * usage, see comments above.
3776 */
3777 PerlIO_rewind(PL_rsfp);
3778 PerlLIO_lseek(PerlIO_fileno(PL_rsfp),(Off_t)0,0); /* just in case rewind didn't */
3779 /* PSz 27 Feb 04 Sanity checks on scriptname */
3780 if ((!scriptname) || (!*scriptname) ) {
3781 Perl_croak(aTHX_ "No setuid script name\n");
3782 }
3783 if (*scriptname == '-') {
3784 Perl_croak(aTHX_ "Setuid script name may not begin with dash\n");
3785 /* Or we might confuse it with an option when replacing
3786 * name in argument list, below (though we do pointer, not
3787 * string, comparisons).
3788 */
3789 }
3790 for (which = 1; PL_origargv[which] && PL_origargv[which] != scriptname; which++) ;
3791 if (!PL_origargv[which]) {
3792 Perl_croak(aTHX_ "Can't change argv to have fd script\n");
3793 }
3794 PL_origargv[which] = savepv(Perl_form(aTHX_ "/dev/fd/%d/%s",
3795 PerlIO_fileno(PL_rsfp), PL_origargv[which]));
3796#if defined(HAS_FCNTL) && defined(F_SETFD)
3797 fcntl(PerlIO_fileno(PL_rsfp),F_SETFD,0); /* ensure no close-on-exec */
3798#endif
b35112e7 3799 PERL_FPU_PRE_EXEC
a7cb1f99 3800 PerlProc_execv(Perl_form(aTHX_ "%s/sperl"PERL_FS_VER_FMT, BIN_EXP,
273cf8d1
GS
3801 (int)PERL_REVISION, (int)PERL_VERSION,
3802 (int)PERL_SUBVERSION), PL_origargv);
b35112e7 3803 PERL_FPU_POST_EXEC
ae3f3efd
PS
3804#endif /* IAMSUID */
3805 Perl_croak(aTHX_ "Can't do setuid (cannot exec sperl)\n");
13281fa4
LW
3806 }
3807
b28d0864 3808 if (PL_statbuf.st_mode & S_ISGID && PL_statbuf.st_gid != PL_egid) {
ae3f3efd
PS
3809/* PSz 26 Feb 04
3810 * This seems back to front: we try HAS_SETEGID first; if not available
3811 * then try HAS_SETREGID; as a last chance we try HAS_SETRESGID. May be OK
3812 * in the sense that we only want to set EGID; but are there any machines
3813 * with either of the latter, but not the former? Same with UID, later.
3814 */
fe14fcc3 3815#ifdef HAS_SETEGID
b28d0864 3816 (void)setegid(PL_statbuf.st_gid);
a687059c 3817#else
fe14fcc3 3818#ifdef HAS_SETREGID
b28d0864 3819 (void)setregid((Gid_t)-1,PL_statbuf.st_gid);
85e6fe83
LW
3820#else
3821#ifdef HAS_SETRESGID
b28d0864 3822 (void)setresgid((Gid_t)-1,PL_statbuf.st_gid,(Gid_t)-1);
a687059c 3823#else
b28d0864 3824 PerlProc_setgid(PL_statbuf.st_gid);
a687059c
LW
3825#endif
3826#endif
85e6fe83 3827#endif
b28d0864 3828 if (PerlProc_getegid() != PL_statbuf.st_gid)
cea2e8a9 3829 Perl_croak(aTHX_ "Can't do setegid!\n");
83025b21 3830 }
b28d0864
NIS
3831 if (PL_statbuf.st_mode & S_ISUID) {
3832 if (PL_statbuf.st_uid != PL_euid)
fe14fcc3 3833#ifdef HAS_SETEUID
b28d0864 3834 (void)seteuid(PL_statbuf.st_uid); /* all that for this */
a687059c 3835#else
fe14fcc3 3836#ifdef HAS_SETREUID
b28d0864 3837 (void)setreuid((Uid_t)-1,PL_statbuf.st_uid);
85e6fe83
LW
3838#else
3839#ifdef HAS_SETRESUID
b28d0864 3840 (void)setresuid((Uid_t)-1,PL_statbuf.st_uid,(Uid_t)-1);
a687059c 3841#else
b28d0864 3842 PerlProc_setuid(PL_statbuf.st_uid);
a687059c
LW
3843#endif
3844#endif
85e6fe83 3845#endif
b28d0864 3846 if (PerlProc_geteuid() != PL_statbuf.st_uid)
cea2e8a9 3847 Perl_croak(aTHX_ "Can't do seteuid!\n");
a687059c 3848 }
b28d0864 3849 else if (PL_uid) { /* oops, mustn't run as root */
fe14fcc3 3850#ifdef HAS_SETEUID
b28d0864 3851 (void)seteuid((Uid_t)PL_uid);
a687059c 3852#else
fe14fcc3 3853#ifdef HAS_SETREUID
b28d0864 3854 (void)setreuid((Uid_t)-1,(Uid_t)PL_uid);
a687059c 3855#else
85e6fe83 3856#ifdef HAS_SETRESUID
b28d0864 3857 (void)setresuid((Uid_t)-1,(Uid_t)PL_uid,(Uid_t)-1);
85e6fe83 3858#else
b28d0864 3859 PerlProc_setuid((Uid_t)PL_uid);
85e6fe83 3860#endif
a687059c
LW
3861#endif
3862#endif
b28d0864 3863 if (PerlProc_geteuid() != PL_uid)
cea2e8a9 3864 Perl_croak(aTHX_ "Can't do seteuid!\n");
83025b21 3865 }
748a9306 3866 init_ids();
b28d0864 3867 if (!cando(S_IXUSR,TRUE,&PL_statbuf))
ae3f3efd 3868 Perl_croak(aTHX_ "Effective UID cannot exec script\n"); /* they can't do this */
13281fa4
LW
3869 }
3870#ifdef IAMSUID
ae3f3efd 3871 else if (PL_preprocess) /* PSz 13 Nov 03 Caught elsewhere, useless(?!) here */
cea2e8a9 3872 Perl_croak(aTHX_ "-P not allowed for setuid/setgid script\n");
ae3f3efd
PS
3873 else if (PL_fdscript < 0 || PL_suidscript != 1)
3874 /* PSz 13 Nov 03 Caught elsewhere, useless(?!) here */
3875 Perl_croak(aTHX_ "(suid) fdscript needed in suidperl\n");
e57400b1 3876 else {
ae3f3efd
PS
3877/* PSz 16 Sep 03 Keep neat error message */
3878 Perl_croak(aTHX_ "Script is not setuid/setgid in suidperl\n");
e57400b1 3879 }
96436eeb 3880
3881 /* We absolutely must clear out any saved ids here, so we */
3882 /* exec the real perl, substituting fd script for scriptname. */
3883 /* (We pass script name as "subdir" of fd, which perl will grok.) */
ae3f3efd
PS
3884 /*
3885 * It might be thought that using setresgid and/or setresuid (changed to
3886 * set the saved IDs) above might obviate the need to exec, and we could
3887 * go on to "do the perl thing".
3888 *
3889 * Is there such a thing as "saved GID", and is that set for setuid (but
3890 * not setgid) execution like suidperl? Without exec, it would not be
3891 * cleared for setuid (but not setgid) scripts (or might need a dummy
3892 * setresgid).
3893 *
3894 * We need suidperl to do the exact same argument checking that perl
3895 * does. Thus it cannot be very small; while it could be significantly
3896 * smaller, it is safer (simpler?) to make it essentially the same
3897 * binary as perl (but they are not identical). - Maybe could defer that
3898 * check to the invoked perl, and suidperl be a tiny wrapper instead;
3899 * but prefer to do thorough checks in suidperl itself. Such deferral
3900 * would make suidperl security rely on perl, a design no-no.
3901 *
3902 * Setuid things should be short and simple, thus easy to understand and
3903 * verify. They should do their "own thing", without influence by
3904 * attackers. It may help if their internal execution flow is fixed,
3905 * regardless of platform: it may be best to exec anyway.
3906 *
3907 * Suidperl should at least be conceptually simple: a wrapper only,
3908 * never to do any real perl. Maybe we should put
3909 * #ifdef IAMSUID
3910 * Perl_croak(aTHX_ "Suidperl should never do real perl\n");
3911 * #endif
3912 * into the perly bits.
3913 */
b28d0864
NIS
3914 PerlIO_rewind(PL_rsfp);
3915 PerlLIO_lseek(PerlIO_fileno(PL_rsfp),(Off_t)0,0); /* just in case rewind didn't */
ae3f3efd
PS
3916 /* PSz 11 Nov 03
3917 * Keep original arguments: suidperl already has fd script.
3918 */
3919/* for (which = 1; PL_origargv[which] && PL_origargv[which] != scriptname; which++) ; */
3920/* if (!PL_origargv[which]) { */
3921/* errno = EPERM; */
3922/* Perl_croak(aTHX_ "Permission denied\n"); */
3923/* } */
3924/* PL_origargv[which] = savepv(Perl_form(aTHX_ "/dev/fd/%d/%s", */
3925/* PerlIO_fileno(PL_rsfp), PL_origargv[which])); */
96436eeb 3926#if defined(HAS_FCNTL) && defined(F_SETFD)
b28d0864 3927 fcntl(PerlIO_fileno(PL_rsfp),F_SETFD,0); /* ensure no close-on-exec */
96436eeb 3928#endif
b35112e7 3929 PERL_FPU_PRE_EXEC
a7cb1f99 3930 PerlProc_execv(Perl_form(aTHX_ "%s/perl"PERL_FS_VER_FMT, BIN_EXP,
273cf8d1
GS
3931 (int)PERL_REVISION, (int)PERL_VERSION,
3932 (int)PERL_SUBVERSION), PL_origargv);/* try again */
b35112e7 3933 PERL_FPU_POST_EXEC
ae3f3efd 3934 Perl_croak(aTHX_ "Can't do setuid (suidperl cannot exec perl)\n");
13281fa4 3935#endif /* IAMSUID */
a687059c 3936#else /* !DOSUID */
3280af22 3937 if (PL_euid != PL_uid || PL_egid != PL_gid) { /* (suidperl doesn't exist, in fact) */
a687059c 3938#ifndef SETUID_SCRIPTS_ARE_SECURE_NOW
b28d0864
NIS
3939 PerlLIO_fstat(PerlIO_fileno(PL_rsfp),&PL_statbuf); /* may be either wrapped or real suid */
3940 if ((PL_euid != PL_uid && PL_euid == PL_statbuf.st_uid && PL_statbuf.st_mode & S_ISUID)
a687059c 3941 ||
b28d0864 3942 (PL_egid != PL_gid && PL_egid == PL_statbuf.st_gid && PL_statbuf.st_mode & S_ISGID)
a687059c 3943 )
b28d0864 3944 if (!PL_do_undump)
cea2e8a9 3945 Perl_croak(aTHX_ "YOU HAVEN'T DISABLED SET-ID SCRIPTS IN THE KERNEL YET!\n\
a687059c
LW
3946FIX YOUR KERNEL, PUT A C WRAPPER AROUND THIS SCRIPT, OR USE -u AND UNDUMP!\n");
3947#endif /* SETUID_SCRIPTS_ARE_SECURE_NOW */
3948 /* not set-id, must be wrapped */
a687059c 3949 }
13281fa4 3950#endif /* DOSUID */
dd374669
AL
3951 (void)validarg;
3952 (void)scriptname;
79072805 3953}
13281fa4 3954
76e3520e 3955STATIC void
cea2e8a9 3956S_find_beginning(pTHX)
79072805 3957{
dd374669
AL
3958 register char *s;
3959 register const char *s2;
e55ac0fa
HS
3960#ifdef MACOS_TRADITIONAL
3961 int maclines = 0;
3962#endif
33b78306
LW
3963
3964 /* skip forward in input to the real script? */
3965
bbce6d69 3966 forbid_setid("-x");
bf4acbe4 3967#ifdef MACOS_TRADITIONAL
084592ab 3968 /* Since the Mac OS does not honor #! arguments for us, we do it ourselves */
ac27b0f5 3969
bf4acbe4
GS
3970 while (PL_doextract || gMacPerl_AlwaysExtract) {
3971 if ((s = sv_gets(PL_linestr, PL_rsfp, 0)) == Nullch) {
3972 if (!gMacPerl_AlwaysExtract)
3973 Perl_croak(aTHX_ "No Perl script found in input\n");
e55ac0fa 3974
bf4acbe4
GS
3975 if (PL_doextract) /* require explicit override ? */
3976 if (!OverrideExtract(PL_origfilename))
3977 Perl_croak(aTHX_ "User aborted script\n");
3978 else
3979 PL_doextract = FALSE;
e55ac0fa 3980
bf4acbe4
GS
3981 /* Pater peccavi, file does not have #! */
3982 PerlIO_rewind(PL_rsfp);
e55ac0fa 3983
bf4acbe4
GS
3984 break;
3985 }
3986#else
3280af22
NIS
3987 while (PL_doextract) {
3988 if ((s = sv_gets(PL_linestr, PL_rsfp, 0)) == Nullch)
cea2e8a9 3989 Perl_croak(aTHX_ "No Perl script found in input\n");
bf4acbe4 3990#endif
4f0c37ba
IZ
3991 s2 = s;
3992 if (*s == '#' && s[1] == '!' && ((s = instr(s,"perl")) || (s = instr(s2,"PERL")))) {
3280af22
NIS
3993 PerlIO_ungetc(PL_rsfp, '\n'); /* to keep line count right */
3994 PL_doextract = FALSE;
6e72f9df 3995 while (*s && !(isSPACE (*s) || *s == '#')) s++;
3996 s2 = s;
3997 while (*s == ' ' || *s == '\t') s++;
3998 if (*s++ == '-') {
3792a11b
NC
3999 while (isDIGIT(s2[-1]) || s2[-1] == '-' || s2[-1] == '.'
4000 || s2[-1] == '_') s2--;
6e72f9df 4001 if (strnEQ(s2-4,"perl",4))
155aba94
GS
4002 while ((s = moreswitches(s)))
4003 ;
33b78306 4004 }
95e8664e 4005#ifdef MACOS_TRADITIONAL
e55ac0fa
HS
4006 /* We are always searching for the #!perl line in MacPerl,
4007 * so if we find it, still keep the line count correct
4008 * by counting lines we already skipped over
4009 */
4010 for (; maclines > 0 ; maclines--)
4011 PerlIO_ungetc(PL_rsfp, '\n');
4012
95e8664e 4013 break;
e55ac0fa
HS
4014
4015 /* gMacPerl_AlwaysExtract is false in MPW tool */
4016 } else if (gMacPerl_AlwaysExtract) {
4017 ++maclines;
95e8664e 4018#endif
83025b21
LW
4019 }
4020 }
4021}
4022
afe37c7d 4023
76e3520e 4024STATIC void
cea2e8a9 4025S_init_ids(pTHX)
352d5a3a 4026{
d8eceb89
JH
4027 PL_uid = PerlProc_getuid();
4028 PL_euid = PerlProc_geteuid();
4029 PL_gid = PerlProc_getgid();
4030 PL_egid = PerlProc_getegid();
748a9306 4031#ifdef VMS
b28d0864
NIS
4032 PL_uid |= PL_gid << 16;
4033 PL_euid |= PL_egid << 16;
748a9306 4034#endif
22f7c9c9
JH
4035 /* Should not happen: */
4036 CHECK_MALLOC_TAINT(PL_uid && (PL_euid != PL_uid || PL_egid != PL_gid));
3280af22 4037 PL_tainting |= (PL_uid && (PL_euid != PL_uid || PL_egid != PL_gid));
ae3f3efd
PS
4038 /* BUG */
4039 /* PSz 27 Feb 04
4040 * Should go by suidscript, not uid!=euid: why disallow
4041 * system("ls") in scripts run from setuid things?
4042 * Or, is this run before we check arguments and set suidscript?
4043 * What about SETUID_SCRIPTS_ARE_SECURE_NOW: could we use fdscript then?
4044 * (We never have suidscript, can we be sure to have fdscript?)
4045 * Or must then go by UID checks? See comments in forbid_setid also.
4046 */
748a9306 4047}
79072805 4048
a0643315
JH
4049/* This is used very early in the lifetime of the program,
4050 * before even the options are parsed, so PL_tainting has
b0891165 4051 * not been initialized properly. */
af419de7 4052bool
8f42b153 4053Perl_doing_taint(int argc, char *argv[], char *envp[])
22f7c9c9 4054{
c3446a78
JH
4055#ifndef PERL_IMPLICIT_SYS
4056 /* If we have PERL_IMPLICIT_SYS we can't call getuid() et alia
4057 * before we have an interpreter-- and the whole point of this
4058 * function is to be called at such an early stage. If you are on
4059 * a system with PERL_IMPLICIT_SYS but you do have a concept of
4060 * "tainted because running with altered effective ids', you'll
4061 * have to add your own checks somewhere in here. The two most
4062 * known samples of 'implicitness' are Win32 and NetWare, neither
4063 * of which has much of concept of 'uids'. */
af419de7 4064 int uid = PerlProc_getuid();
22f7c9c9 4065 int euid = PerlProc_geteuid();
af419de7 4066 int gid = PerlProc_getgid();
22f7c9c9 4067 int egid = PerlProc_getegid();
6867be6d 4068 (void)envp;
22f7c9c9
JH
4069
4070#ifdef VMS
af419de7 4071 uid |= gid << 16;
22f7c9c9
JH
4072 euid |= egid << 16;
4073#endif
4074 if (uid && (euid != uid || egid != gid))
4075 return 1;
c3446a78 4076#endif /* !PERL_IMPLICIT_SYS */
af419de7
JH
4077 /* This is a really primitive check; environment gets ignored only
4078 * if -T are the first chars together; otherwise one gets
4079 * "Too late" message. */
22f7c9c9
JH
4080 if ( argc > 1 && argv[1][0] == '-'
4081 && (argv[1][1] == 't' || argv[1][1] == 'T') )
4082 return 1;
4083 return 0;
4084}
22f7c9c9 4085
76e3520e 4086STATIC void
e1ec3a88 4087S_forbid_setid(pTHX_ const char *s)
bbce6d69 4088{
ae3f3efd 4089#ifdef SETUID_SCRIPTS_ARE_SECURE_NOW
3280af22 4090 if (PL_euid != PL_uid)
cea2e8a9 4091 Perl_croak(aTHX_ "No %s allowed while running setuid", s);
3280af22 4092 if (PL_egid != PL_gid)
cea2e8a9 4093 Perl_croak(aTHX_ "No %s allowed while running setgid", s);
ae3f3efd
PS
4094#endif /* SETUID_SCRIPTS_ARE_SECURE_NOW */
4095 /* PSz 29 Feb 04
4096 * Checks for UID/GID above "wrong": why disallow
4097 * perl -e 'print "Hello\n"'
4098 * from within setuid things?? Simply drop them: replaced by
4099 * fdscript/suidscript and #ifdef IAMSUID checks below.
4100 *
4101 * This may be too late for command-line switches. Will catch those on
4102 * the #! line, after finding the script name and setting up
4103 * fdscript/suidscript. Note that suidperl does not get around to
4104 * parsing (and checking) the switches on the #! line, but checks that
4105 * the two sets are identical.
4106 *
4107 * With SETUID_SCRIPTS_ARE_SECURE_NOW, could we use fdscript, also or
4108 * instead, or would that be "too late"? (We never have suidscript, can
4109 * we be sure to have fdscript?)
4110 *
4111 * Catch things with suidscript (in descendant of suidperl), even with
4112 * right UID/GID. Was already checked in suidperl, with #ifdef IAMSUID,
4113 * below; but I am paranoid.
4114 *
4115 * Also see comments about root running a setuid script, elsewhere.
4116 */
4117 if (PL_suidscript >= 0)
4118 Perl_croak(aTHX_ "No %s allowed with (suid) fdscript", s);
4119#ifdef IAMSUID
4120 /* PSz 11 Nov 03 Catch it in suidperl, always! */
4121 Perl_croak(aTHX_ "No %s allowed in suidperl", s);
4122#endif /* IAMSUID */
bbce6d69 4123}
4124
1ee4443e
IZ
4125void
4126Perl_init_debugger(pTHX)
748a9306 4127{
1ee4443e
IZ
4128 HV *ostash = PL_curstash;
4129
3280af22 4130 PL_curstash = PL_debstash;
7619c85e 4131 PL_dbargs = GvAV(gv_AVadd((gv_fetchpv("DB::args", GV_ADDMULTI, SVt_PVAV))));
3280af22 4132 AvREAL_off(PL_dbargs);
7619c85e
RG
4133 PL_DBgv = gv_fetchpv("DB::DB", GV_ADDMULTI, SVt_PVGV);
4134 PL_DBline = gv_fetchpv("DB::dbline", GV_ADDMULTI, SVt_PVAV);
4135 PL_DBsub = gv_HVadd(gv_fetchpv("DB::sub", GV_ADDMULTI, SVt_PVHV));
7619c85e 4136 PL_DBsingle = GvSV((gv_fetchpv("DB::single", GV_ADDMULTI, SVt_PV)));
ac27b0f5 4137 sv_setiv(PL_DBsingle, 0);
7619c85e 4138 PL_DBtrace = GvSV((gv_fetchpv("DB::trace", GV_ADDMULTI, SVt_PV)));
ac27b0f5 4139 sv_setiv(PL_DBtrace, 0);
7619c85e 4140 PL_DBsignal = GvSV((gv_fetchpv("DB::signal", GV_ADDMULTI, SVt_PV)));
ac27b0f5 4141 sv_setiv(PL_DBsignal, 0);
bf9cdc68 4142 PL_DBassertion = GvSV((gv_fetchpv("DB::assertion", GV_ADDMULTI, SVt_PV)));
06492da6 4143 sv_setiv(PL_DBassertion, 0);
1ee4443e 4144 PL_curstash = ostash;
352d5a3a
LW
4145}
4146
2ce36478
SM
4147#ifndef STRESS_REALLOC
4148#define REASONABLE(size) (size)
4149#else
4150#define REASONABLE(size) (1) /* unreasonable */
4151#endif
4152
11343788 4153void
cea2e8a9 4154Perl_init_stacks(pTHX)
79072805 4155{
e336de0d 4156 /* start with 128-item stack and 8K cxstack */
3280af22 4157 PL_curstackinfo = new_stackinfo(REASONABLE(128),
e336de0d 4158 REASONABLE(8192/sizeof(PERL_CONTEXT) - 1));
3280af22
NIS
4159 PL_curstackinfo->si_type = PERLSI_MAIN;
4160 PL_curstack = PL_curstackinfo->si_stack;
4161 PL_mainstack = PL_curstack; /* remember in case we switch stacks */
79072805 4162
3280af22
NIS
4163 PL_stack_base = AvARRAY(PL_curstack);
4164 PL_stack_sp = PL_stack_base;
4165 PL_stack_max = PL_stack_base + AvMAX(PL_curstack);
8990e307 4166
3280af22
NIS
4167 New(50,PL_tmps_stack,REASONABLE(128),SV*);
4168 PL_tmps_floor = -1;
4169 PL_tmps_ix = -1;
4170 PL_tmps_max = REASONABLE(128);
8990e307 4171
3280af22
NIS
4172 New(54,PL_markstack,REASONABLE(32),I32);
4173 PL_markstack_ptr = PL_markstack;
4174 PL_markstack_max = PL_markstack + REASONABLE(32);
79072805 4175
ce2f7c3b 4176 SET_MARK_OFFSET;
e336de0d 4177
3280af22
NIS
4178 New(54,PL_scopestack,REASONABLE(32),I32);
4179 PL_scopestack_ix = 0;
4180 PL_scopestack_max = REASONABLE(32);
79072805 4181
3280af22
NIS
4182 New(54,PL_savestack,REASONABLE(128),ANY);
4183 PL_savestack_ix = 0;
4184 PL_savestack_max = REASONABLE(128);
378cc40b 4185}
33b78306 4186
2ce36478
SM
4187#undef REASONABLE
4188
76e3520e 4189STATIC void
cea2e8a9 4190S_nuke_stacks(pTHX)
6e72f9df 4191{
3280af22
NIS
4192 while (PL_curstackinfo->si_next)
4193 PL_curstackinfo = PL_curstackinfo->si_next;
4194 while (PL_curstackinfo) {
4195 PERL_SI *p = PL_curstackinfo->si_prev;
bac4b2ad 4196 /* curstackinfo->si_stack got nuked by sv_free_arenas() */
3280af22
NIS
4197 Safefree(PL_curstackinfo->si_cxstack);
4198 Safefree(PL_curstackinfo);
4199 PL_curstackinfo = p;
e336de0d 4200 }
3280af22
NIS
4201 Safefree(PL_tmps_stack);
4202 Safefree(PL_markstack);
4203 Safefree(PL_scopestack);
4204 Safefree(PL_savestack);
378cc40b 4205}
33b78306 4206
76e3520e 4207STATIC void
cea2e8a9 4208S_init_lexer(pTHX)
8990e307 4209{
06039172 4210 PerlIO *tmpfp;
3280af22
NIS
4211 tmpfp = PL_rsfp;
4212 PL_rsfp = Nullfp;
4213 lex_start(PL_linestr);
4214 PL_rsfp = tmpfp;
79cb57f6 4215 PL_subname = newSVpvn("main",4);
8990e307
LW
4216}
4217
76e3520e 4218STATIC void
cea2e8a9 4219S_init_predump_symbols(pTHX)
45d8adaa 4220{
93a17b20 4221 GV *tmpgv;
af8c498a 4222 IO *io;
79072805 4223
864dbfa3 4224 sv_setpvn(get_sv("\"", TRUE), " ", 1);
3280af22
NIS
4225 PL_stdingv = gv_fetchpv("STDIN",TRUE, SVt_PVIO);
4226 GvMULTI_on(PL_stdingv);
af8c498a 4227 io = GvIOp(PL_stdingv);
a04651f4 4228 IoTYPE(io) = IoTYPE_RDONLY;
af8c498a 4229 IoIFP(io) = PerlIO_stdin();
adbc6bb1 4230 tmpgv = gv_fetchpv("stdin",TRUE, SVt_PV);
a5f75d66 4231 GvMULTI_on(tmpgv);
af8c498a 4232 GvIOp(tmpgv) = (IO*)SvREFCNT_inc(io);
79072805 4233
85e6fe83 4234 tmpgv = gv_fetchpv("STDOUT",TRUE, SVt_PVIO);
a5f75d66 4235 GvMULTI_on(tmpgv);
af8c498a 4236 io = GvIOp(tmpgv);
a04651f4 4237 IoTYPE(io) = IoTYPE_WRONLY;
af8c498a 4238 IoOFP(io) = IoIFP(io) = PerlIO_stdout();
4633a7c4 4239 setdefout(tmpgv);
adbc6bb1 4240 tmpgv = gv_fetchpv("stdout",TRUE, SVt_PV);
a5f75d66 4241 GvMULTI_on(tmpgv);
af8c498a 4242 GvIOp(tmpgv) = (IO*)SvREFCNT_inc(io);
79072805 4243
bf49b057
GS
4244 PL_stderrgv = gv_fetchpv("STDERR",TRUE, SVt_PVIO);
4245 GvMULTI_on(PL_stderrgv);
4246 io = GvIOp(PL_stderrgv);
a04651f4 4247 IoTYPE(io) = IoTYPE_WRONLY;
af8c498a 4248 IoOFP(io) = IoIFP(io) = PerlIO_stderr();
adbc6bb1 4249 tmpgv = gv_fetchpv("stderr",TRUE, SVt_PV);
a5f75d66 4250 GvMULTI_on(tmpgv);
af8c498a 4251 GvIOp(tmpgv) = (IO*)SvREFCNT_inc(io);
79072805 4252
3280af22 4253 PL_statname = NEWSV(66,0); /* last filename we did stat on */
ab821d7f 4254
bf4acbe4
GS
4255 if (PL_osname)
4256 Safefree(PL_osname);
4257 PL_osname = savepv(OSNAME);
79072805 4258}
33b78306 4259
a11ec5a9 4260void
8f42b153 4261Perl_init_argv_symbols(pTHX_ register int argc, register char **argv)
33b78306 4262{
79072805 4263 char *s;
79072805 4264 argc--,argv++; /* skip name of script */
3280af22 4265 if (PL_doswitches) {
79072805
LW
4266 for (; argc > 0 && **argv == '-'; argc--,argv++) {
4267 if (!argv[0][1])
4268 break;
379d538a 4269 if (argv[0][1] == '-' && !argv[0][2]) {
79072805
LW
4270 argc--,argv++;
4271 break;
4272 }
155aba94 4273 if ((s = strchr(argv[0], '='))) {
79072805 4274 *s++ = '\0';
85e6fe83 4275 sv_setpv(GvSV(gv_fetchpv(argv[0]+1,TRUE, SVt_PV)),s);
79072805
LW
4276 }
4277 else
85e6fe83 4278 sv_setiv(GvSV(gv_fetchpv(argv[0]+1,TRUE, SVt_PV)),1);
fe14fcc3 4279 }
79072805 4280 }
a11ec5a9
RGS
4281 if ((PL_argvgv = gv_fetchpv("ARGV",TRUE, SVt_PVAV))) {
4282 GvMULTI_on(PL_argvgv);
4283 (void)gv_AVadd(PL_argvgv);
4284 av_clear(GvAVn(PL_argvgv));
4285 for (; argc > 0; argc--,argv++) {
4286 SV *sv = newSVpv(argv[0],0);
4287 av_push(GvAVn(PL_argvgv),sv);
ce81ff12
JH
4288 if (!(PL_unicode & PERL_UNICODE_LOCALE_FLAG) || PL_utf8locale) {
4289 if (PL_unicode & PERL_UNICODE_ARGV_FLAG)
4290 SvUTF8_on(sv);
4291 }
a05d7ebb
JH
4292 if (PL_unicode & PERL_UNICODE_WIDESYSCALLS_FLAG) /* Sarathy? */
4293 (void)sv_utf8_decode(sv);
a11ec5a9
RGS
4294 }
4295 }
4296}
4297
4298STATIC void
4299S_init_postdump_symbols(pTHX_ register int argc, register char **argv, register char **env)
4300{
27da23d5 4301 dVAR;
a11ec5a9 4302 GV* tmpgv;
a11ec5a9 4303
3280af22
NIS
4304 PL_toptarget = NEWSV(0,0);
4305 sv_upgrade(PL_toptarget, SVt_PVFM);
4306 sv_setpvn(PL_toptarget, "", 0);
4307 PL_bodytarget = NEWSV(0,0);
4308 sv_upgrade(PL_bodytarget, SVt_PVFM);
4309 sv_setpvn(PL_bodytarget, "", 0);
4310 PL_formtarget = PL_bodytarget;
79072805 4311
bbce6d69 4312 TAINT;
a11ec5a9
RGS
4313
4314 init_argv_symbols(argc,argv);
4315
155aba94 4316 if ((tmpgv = gv_fetchpv("0",TRUE, SVt_PV))) {
bf4acbe4
GS
4317#ifdef MACOS_TRADITIONAL
4318 /* $0 is not majick on a Mac */
4319 sv_setpv(GvSV(tmpgv),MacPerl_MPWFileName(PL_origfilename));
4320#else
3280af22 4321 sv_setpv(GvSV(tmpgv),PL_origfilename);
79072805 4322 magicname("0", "0", 1);
bf4acbe4 4323#endif
79072805 4324 }
155aba94 4325 if ((PL_envgv = gv_fetchpv("ENV",TRUE, SVt_PVHV))) {
79072805 4326 HV *hv;
3280af22
NIS
4327 GvMULTI_on(PL_envgv);
4328 hv = GvHVn(PL_envgv);
14befaf4 4329 hv_magic(hv, Nullgv, PERL_MAGIC_env);
2f42fcb0 4330#ifndef PERL_MICRO
fa6a1c44 4331#ifdef USE_ENVIRON_ARRAY
4633a7c4
LW
4332 /* Note that if the supplied env parameter is actually a copy
4333 of the global environ then it may now point to free'd memory
4334 if the environment has been modified since. To avoid this
4335 problem we treat env==NULL as meaning 'use the default'
4336 */
4337 if (!env)
4338 env = environ;
4efc5df6
GS
4339 if (env != environ
4340# ifdef USE_ITHREADS
4341 && PL_curinterp == aTHX
4342# endif
4343 )
4344 {
79072805 4345 environ[0] = Nullch;
4efc5df6 4346 }
9b4eeda5
MB
4347 if (env) {
4348 char** origenv = environ;
27da23d5
JH
4349 char *s;
4350 SV *sv;
764df951 4351 for (; *env; env++) {
9b4eeda5 4352 if (!(s = strchr(*env,'=')) || s == *env)
79072805 4353 continue;
7da0e383 4354#if defined(MSDOS) && !defined(DJGPP)
61968511 4355 *s = '\0';
137443ea 4356 (void)strupr(*env);
61968511 4357 *s = '=';
137443ea 4358#endif
61968511 4359 sv = newSVpv(s+1, 0);
79072805 4360 (void)hv_store(hv, *env, s - *env, sv, 0);
61968511
GA
4361 if (env != environ)
4362 mg_set(sv);
9b4eeda5
MB
4363 if (origenv != environ) {
4364 /* realloc has shifted us */
4365 env = (env - origenv) + environ;
4366 origenv = environ;
4367 }
764df951 4368 }
9b4eeda5 4369 }
103a7189 4370#endif /* USE_ENVIRON_ARRAY */
2f42fcb0 4371#endif /* !PERL_MICRO */
79072805 4372 }
bbce6d69 4373 TAINT_NOT;
306196c3
MS
4374 if ((tmpgv = gv_fetchpv("$",TRUE, SVt_PV))) {
4375 SvREADONLY_off(GvSV(tmpgv));
7766f137 4376 sv_setiv(GvSV(tmpgv), (IV)PerlProc_getpid());
306196c3
MS
4377 SvREADONLY_on(GvSV(tmpgv));
4378 }
4d76a344
RGS
4379#ifdef THREADS_HAVE_PIDS
4380 PL_ppid = (IV)getppid();
4381#endif
2710853f
MJD
4382
4383 /* touch @F array to prevent spurious warnings 20020415 MJD */
4384 if (PL_minus_a) {
4385 (void) get_av("main::F", TRUE | GV_ADDMULTI);
4386 }
4387 /* touch @- and @+ arrays to prevent spurious warnings 20020415 MJD */
4388 (void) get_av("main::-", TRUE | GV_ADDMULTI);
4389 (void) get_av("main::+", TRUE | GV_ADDMULTI);
33b78306 4390}
34de22dd 4391
76e3520e 4392STATIC void
cea2e8a9 4393S_init_perllib(pTHX)
34de22dd 4394{
85e6fe83 4395 char *s;
3280af22 4396 if (!PL_tainting) {
552a7a9b 4397#ifndef VMS
76e3520e 4398 s = PerlEnv_getenv("PERL5LIB");
85e6fe83 4399 if (s)
88fe16b2 4400 incpush(s, TRUE, TRUE, TRUE, FALSE);
85e6fe83 4401 else
88fe16b2 4402 incpush(PerlEnv_getenv("PERLLIB"), FALSE, FALSE, TRUE, FALSE);
552a7a9b 4403#else /* VMS */
4404 /* Treat PERL5?LIB as a possible search list logical name -- the
4405 * "natural" VMS idiom for a Unix path string. We allow each
4406 * element to be a set of |-separated directories for compatibility.
4407 */
4408 char buf[256];
4409 int idx = 0;
4410 if (my_trnlnm("PERL5LIB",buf,0))
88fe16b2 4411 do { incpush(buf,TRUE,TRUE,TRUE,FALSE); } while (my_trnlnm("PERL5LIB",buf,++idx));
552a7a9b 4412 else
88fe16b2 4413 while (my_trnlnm("PERLLIB",buf,idx++)) incpush(buf,FALSE,FALSE,TRUE,FALSE);
552a7a9b 4414#endif /* VMS */
85e6fe83 4415 }
34de22dd 4416
c90c0ff4 4417/* Use the ~-expanded versions of APPLLIB (undocumented),
65f19062 4418 ARCHLIB PRIVLIB SITEARCH SITELIB VENDORARCH and VENDORLIB
df5cef82 4419*/
4633a7c4 4420#ifdef APPLLIB_EXP
88fe16b2 4421 incpush(APPLLIB_EXP, TRUE, TRUE, TRUE, TRUE);
16d20bd9 4422#endif
4633a7c4 4423
fed7345c 4424#ifdef ARCHLIB_EXP
88fe16b2 4425 incpush(ARCHLIB_EXP, FALSE, FALSE, TRUE, TRUE);
a0d0e21e 4426#endif
bf4acbe4
GS
4427#ifdef MACOS_TRADITIONAL
4428 {
c623ac67 4429 Stat_t tmpstatbuf;
bf4acbe4
GS
4430 SV * privdir = NEWSV(55, 0);
4431 char * macperl = PerlEnv_getenv("MACPERL");
4432
4433 if (!macperl)
4434 macperl = "";
4435
4436 Perl_sv_setpvf(aTHX_ privdir, "%slib:", macperl);
4437 if (PerlLIO_stat(SvPVX(privdir), &tmpstatbuf) >= 0 && S_ISDIR(tmpstatbuf.st_mode))
88fe16b2 4438 incpush(SvPVX(privdir), TRUE, FALSE, TRUE, FALSE);
bf4acbe4
GS
4439 Perl_sv_setpvf(aTHX_ privdir, "%ssite_perl:", macperl);
4440 if (PerlLIO_stat(SvPVX(privdir), &tmpstatbuf) >= 0 && S_ISDIR(tmpstatbuf.st_mode))
88fe16b2 4441 incpush(SvPVX(privdir), TRUE, FALSE, TRUE, FALSE);
ac27b0f5 4442
bf4acbe4
GS
4443 SvREFCNT_dec(privdir);
4444 }
4445 if (!PL_tainting)
88fe16b2 4446 incpush(":", FALSE, FALSE, TRUE, FALSE);
bf4acbe4 4447#else
fed7345c 4448#ifndef PRIVLIB_EXP
65f19062 4449# define PRIVLIB_EXP "/usr/local/lib/perl5:/usr/local/lib/perl"
34de22dd 4450#endif
ac27b0f5 4451#if defined(WIN32)
88fe16b2 4452 incpush(PRIVLIB_EXP, TRUE, FALSE, TRUE, TRUE);
00dc2f4f 4453#else
88fe16b2 4454 incpush(PRIVLIB_EXP, FALSE, FALSE, TRUE, TRUE);
00dc2f4f 4455#endif
4633a7c4 4456
65f19062 4457#ifdef SITEARCH_EXP
3b290362
GS
4458 /* sitearch is always relative to sitelib on Windows for
4459 * DLL-based path intuition to work correctly */
4460# if !defined(WIN32)
88fe16b2 4461 incpush(SITEARCH_EXP, FALSE, FALSE, TRUE, TRUE);
65f19062
GS
4462# endif
4463#endif
4464
4633a7c4 4465#ifdef SITELIB_EXP
65f19062 4466# if defined(WIN32)
574c798a 4467 /* this picks up sitearch as well */
88fe16b2 4468 incpush(SITELIB_EXP, TRUE, FALSE, TRUE, TRUE);
65f19062 4469# else
88fe16b2 4470 incpush(SITELIB_EXP, FALSE, FALSE, TRUE, TRUE);
65f19062
GS
4471# endif
4472#endif
189d1e8d 4473
65f19062 4474#ifdef SITELIB_STEM /* Search for version-specific dirs below here */
88fe16b2 4475 incpush(SITELIB_STEM, FALSE, TRUE, TRUE, TRUE);
81c6dfba 4476#endif
65f19062
GS
4477
4478#ifdef PERL_VENDORARCH_EXP
4ea817c6 4479 /* vendorarch is always relative to vendorlib on Windows for
3b290362
GS
4480 * DLL-based path intuition to work correctly */
4481# if !defined(WIN32)
88fe16b2 4482 incpush(PERL_VENDORARCH_EXP, FALSE, FALSE, TRUE, TRUE);
65f19062 4483# endif
4b03c463 4484#endif
65f19062
GS
4485
4486#ifdef PERL_VENDORLIB_EXP
4487# if defined(WIN32)
88fe16b2 4488 incpush(PERL_VENDORLIB_EXP, TRUE, FALSE, TRUE, TRUE); /* this picks up vendorarch as well */
65f19062 4489# else
88fe16b2 4490 incpush(PERL_VENDORLIB_EXP, FALSE, FALSE, TRUE, TRUE);
65f19062 4491# endif
a3635516 4492#endif
65f19062
GS
4493
4494#ifdef PERL_VENDORLIB_STEM /* Search for version-specific dirs below here */
88fe16b2 4495 incpush(PERL_VENDORLIB_STEM, FALSE, TRUE, TRUE, TRUE);
00dc2f4f 4496#endif
65f19062 4497
3b777bb4 4498#ifdef PERL_OTHERLIBDIRS
88fe16b2 4499 incpush(PERL_OTHERLIBDIRS, TRUE, TRUE, TRUE, TRUE);
3b777bb4
GS
4500#endif
4501
3280af22 4502 if (!PL_tainting)
88fe16b2 4503 incpush(".", FALSE, FALSE, TRUE, FALSE);
bf4acbe4 4504#endif /* MACOS_TRADITIONAL */
774d564b 4505}
4506
27da23d5 4507#if defined(DOSISH) || defined(EPOC) || defined(SYMBIAN)
774d564b 4508# define PERLLIB_SEP ';'
4509#else
4510# if defined(VMS)
4511# define PERLLIB_SEP '|'
4512# else
bf4acbe4
GS
4513# if defined(MACOS_TRADITIONAL)
4514# define PERLLIB_SEP ','
4515# else
4516# define PERLLIB_SEP ':'
4517# endif
774d564b 4518# endif
4519#endif
4520#ifndef PERLLIB_MANGLE
4521# define PERLLIB_MANGLE(s,n) (s)
ac27b0f5 4522#endif
774d564b 4523
ad17a1ae
NC
4524/* Push a directory onto @INC if it exists.
4525 Generate a new SV if we do this, to save needing to copy the SV we push
4526 onto @INC */
4527STATIC SV *
4528S_incpush_if_exists(pTHX_ SV *dir)
4529{
4530 Stat_t tmpstatbuf;
848ef955 4531 if (PerlLIO_stat(SvPVX_const(dir), &tmpstatbuf) >= 0 &&
ad17a1ae
NC
4532 S_ISDIR(tmpstatbuf.st_mode)) {
4533 av_push(GvAVn(PL_incgv), dir);
4534 dir = NEWSV(0,0);
4535 }
4536 return dir;
4537}
4538
76e3520e 4539STATIC void
dd374669
AL
4540S_incpush(pTHX_ const char *dir, bool addsubdirs, bool addoldvers, bool usesep,
4541 bool canrelocate)
774d564b 4542{
4543 SV *subdir = Nullsv;
dd374669 4544 const char *p = dir;
774d564b 4545
3b290362 4546 if (!p || !*p)
774d564b 4547 return;
4548
9c8a64f0 4549 if (addsubdirs || addoldvers) {
ad17a1ae 4550 subdir = NEWSV(0,0);
774d564b 4551 }
4552
4553 /* Break at all separators */
4554 while (p && *p) {
8c52afec 4555 SV *libdir = NEWSV(55,0);
e1ec3a88 4556 const char *s;
774d564b 4557
4558 /* skip any consecutive separators */
574c798a
SR
4559 if (usesep) {
4560 while ( *p == PERLLIB_SEP ) {
4561 /* Uncomment the next line for PATH semantics */
4562 /* av_push(GvAVn(PL_incgv), newSVpvn(".", 1)); */
4563 p++;
4564 }
774d564b 4565 }
4566
574c798a 4567 if ( usesep && (s = strchr(p, PERLLIB_SEP)) != Nullch ) {
774d564b 4568 sv_setpvn(libdir, PERLLIB_MANGLE(p, (STRLEN)(s - p)),
4569 (STRLEN)(s - p));
4570 p = s + 1;
4571 }
4572 else {
4573 sv_setpv(libdir, PERLLIB_MANGLE(p, 0));
4574 p = Nullch; /* break out */
4575 }
bf4acbe4 4576#ifdef MACOS_TRADITIONAL
e69a2255
JH
4577 if (!strchr(SvPVX(libdir), ':')) {
4578 char buf[256];
4579
4580 sv_setpv(libdir, MacPerl_CanonDir(SvPVX(libdir), buf, 0));
4581 }
bf4acbe4
GS
4582 if (SvPVX(libdir)[SvCUR(libdir)-1] != ':')
4583 sv_catpv(libdir, ":");
4584#endif
774d564b 4585
dd374669
AL
4586 /* Do the if() outside the #ifdef to avoid warnings about an unused
4587 parameter. */
4588 if (canrelocate) {
88fe16b2
NC
4589#ifdef PERL_RELOCATABLE_INC
4590 /*
4591 * Relocatable include entries are marked with a leading .../
4592 *
4593 * The algorithm is
4594 * 0: Remove that leading ".../"
4595 * 1: Remove trailing executable name (anything after the last '/')
4596 * from the perl path to give a perl prefix
4597 * Then
4598 * While the @INC element starts "../" and the prefix ends with a real
4599 * directory (ie not . or ..) chop that real directory off the prefix
4600 * and the leading "../" from the @INC element. ie a logical "../"
4601 * cleanup
4602 * Finally concatenate the prefix and the remainder of the @INC element
4603 * The intent is that /usr/local/bin/perl and .../../lib/perl5
4604 * generates /usr/local/lib/perl5
4605 */
88fe16b2
NC
4606 char *libpath = SvPVX(libdir);
4607 STRLEN libpath_len = SvCUR(libdir);
4608 if (libpath_len >= 4 && memEQ (libpath, ".../", 4)) {
4609 /* Game on! */
4610 SV *caret_X = get_sv("\030", 0);
4611 /* Going to use the SV just as a scratch buffer holding a C
4612 string: */
4613 SV *prefix_sv;
4614 char *prefix;
4615 char *lastslash;
4616
4617 /* $^X is *the* source of taint if tainting is on, hence
4618 SvPOK() won't be true. */
4619 assert(caret_X);
4620 assert(SvPOKp(caret_X));
4621 prefix_sv = newSVpvn(SvPVX(caret_X), SvCUR(caret_X));
4622 /* Firstly take off the leading .../
4623 If all else fail we'll do the paths relative to the current
4624 directory. */
4625 sv_chop(libdir, libpath + 4);
4626 /* Don't use SvPV as we're intentionally bypassing taining,
4627 mortal copies that the mg_get of tainting creates, and
4628 corruption that seems to come via the save stack.
4629 I guess that the save stack isn't correctly set up yet. */
4630 libpath = SvPVX(libdir);
4631 libpath_len = SvCUR(libdir);
4632
4633 /* This would work more efficiently with memrchr, but as it's
4634 only a GNU extension we'd need to probe for it and
4635 implement our own. Not hard, but maybe not worth it? */
4636
4637 prefix = SvPVX(prefix_sv);
4638 lastslash = strrchr(prefix, '/');
4639
4640 /* First time in with the *lastslash = '\0' we just wipe off
4641 the trailing /perl from (say) /usr/foo/bin/perl
4642 */
4643 if (lastslash) {
4644 SV *tempsv;
4645 while ((*lastslash = '\0'), /* Do that, come what may. */
4646 (libpath_len >= 3 && memEQ(libpath, "../", 3)
4647 && (lastslash = strrchr(prefix, '/')))) {
4648 if (lastslash[1] == '\0'
4649 || (lastslash[1] == '.'
4650 && (lastslash[2] == '/' /* ends "/." */
4651 || (lastslash[2] == '/'
4652 && lastslash[3] == '/' /* or "/.." */
4653 )))) {
4654 /* Prefix ends "/" or "/." or "/..", any of which
4655 are fishy, so don't do any more logical cleanup.
4656 */
4657 break;
4658 }
4659 /* Remove leading "../" from path */
4660 libpath += 3;
4661 libpath_len -= 3;
4662 /* Next iteration round the loop removes the last
4663 directory name from prefix by writing a '\0' in
4664 the while clause. */
4665 }
4666 /* prefix has been terminated with a '\0' to the correct
4667 length. libpath points somewhere into the libdir SV.
4668 We need to join the 2 with '/' and drop the result into
4669 libdir. */
4670 tempsv = Perl_newSVpvf(aTHX_ "%s/%s", prefix, libpath);
4671 SvREFCNT_dec(libdir);
4672 /* And this is the new libdir. */
4673 libdir = tempsv;
4674 if (PL_tainting &&
4675 (PL_uid != PL_euid || PL_gid != PL_egid)) {
4676 /* Need to taint reloccated paths if running set ID */
4677 SvTAINTED_on(libdir);
4678 }
4679 }
4680 SvREFCNT_dec(prefix_sv);
4681 }
88fe16b2 4682#endif
dd374669 4683 }
774d564b 4684 /*
4685 * BEFORE pushing libdir onto @INC we may first push version- and
4686 * archname-specific sub-directories.
4687 */
9c8a64f0 4688 if (addsubdirs || addoldvers) {
29d82f8d 4689#ifdef PERL_INC_VERSION_LIST
8353b874
GS
4690 /* Configure terminates PERL_INC_VERSION_LIST with a NULL */
4691 const char *incverlist[] = { PERL_INC_VERSION_LIST };
29d82f8d
GS
4692 const char **incver;
4693#endif
aa689395 4694#ifdef VMS
4695 char *unix;
4696 STRLEN len;
774d564b 4697
2d8e6c8d 4698 if ((unix = tounixspec_ts(SvPV(libdir,len),Nullch)) != Nullch) {
aa689395 4699 len = strlen(unix);
4700 while (unix[len-1] == '/') len--; /* Cosmetic */
4701 sv_usepvn(libdir,unix,len);
4702 }
4703 else
bf49b057 4704 PerlIO_printf(Perl_error_log,
aa689395 4705 "Failed to unixify @INC element \"%s\"\n",
2d8e6c8d 4706 SvPV(libdir,len));
aa689395 4707#endif
9c8a64f0 4708 if (addsubdirs) {
bf4acbe4
GS
4709#ifdef MACOS_TRADITIONAL
4710#define PERL_AV_SUFFIX_FMT ""
084592ab
CN
4711#define PERL_ARCH_FMT "%s:"
4712#define PERL_ARCH_FMT_PATH PERL_FS_VER_FMT PERL_AV_SUFFIX_FMT
bf4acbe4
GS
4713#else
4714#define PERL_AV_SUFFIX_FMT "/"
4715#define PERL_ARCH_FMT "/%s"
084592ab 4716#define PERL_ARCH_FMT_PATH PERL_AV_SUFFIX_FMT PERL_FS_VER_FMT
bf4acbe4 4717#endif
9c8a64f0 4718 /* .../version/archname if -d .../version/archname */
084592ab 4719 Perl_sv_setpvf(aTHX_ subdir, "%"SVf PERL_ARCH_FMT_PATH PERL_ARCH_FMT,
9c8a64f0
GS
4720 libdir,
4721 (int)PERL_REVISION, (int)PERL_VERSION,
4722 (int)PERL_SUBVERSION, ARCHNAME);
ad17a1ae 4723 subdir = S_incpush_if_exists(aTHX_ subdir);
4b03c463 4724
9c8a64f0 4725 /* .../version if -d .../version */
084592ab 4726 Perl_sv_setpvf(aTHX_ subdir, "%"SVf PERL_ARCH_FMT_PATH, libdir,
9c8a64f0
GS
4727 (int)PERL_REVISION, (int)PERL_VERSION,
4728 (int)PERL_SUBVERSION);
ad17a1ae 4729 subdir = S_incpush_if_exists(aTHX_ subdir);
9c8a64f0
GS
4730
4731 /* .../archname if -d .../archname */
bf4acbe4 4732 Perl_sv_setpvf(aTHX_ subdir, "%"SVf PERL_ARCH_FMT, libdir, ARCHNAME);
ad17a1ae
NC
4733 subdir = S_incpush_if_exists(aTHX_ subdir);
4734
29d82f8d 4735 }
9c8a64f0 4736
9c8a64f0 4737#ifdef PERL_INC_VERSION_LIST
ccc2aad8 4738 if (addoldvers) {
9c8a64f0
GS
4739 for (incver = incverlist; *incver; incver++) {
4740 /* .../xxx if -d .../xxx */
bf4acbe4 4741 Perl_sv_setpvf(aTHX_ subdir, "%"SVf PERL_ARCH_FMT, libdir, *incver);
ad17a1ae 4742 subdir = S_incpush_if_exists(aTHX_ subdir);
9c8a64f0
GS
4743 }
4744 }
29d82f8d 4745#endif
774d564b 4746 }
4747
4748 /* finally push this lib directory on the end of @INC */
3280af22 4749 av_push(GvAVn(PL_incgv), libdir);
774d564b 4750 }
ad17a1ae 4751 if (subdir) {
ef97f5b3 4752 assert (SvREFCNT(subdir) == 1);
ad17a1ae
NC
4753 SvREFCNT_dec(subdir);
4754 }
34de22dd 4755}
93a17b20 4756
4d1ff10f 4757#ifdef USE_5005THREADS
76e3520e 4758STATIC struct perl_thread *
cea2e8a9 4759S_init_main_thread(pTHX)
199100c8 4760{
c5be433b 4761#if !defined(PERL_IMPLICIT_CONTEXT)
52e1cb5e 4762 struct perl_thread *thr;
cea2e8a9 4763#endif
199100c8
MB
4764 XPV *xpv;
4765
52e1cb5e 4766 Newz(53, thr, 1, struct perl_thread);
533c011a 4767 PL_curcop = &PL_compiling;
c5be433b 4768 thr->interp = PERL_GET_INTERP;
199100c8 4769 thr->cvcache = newHV();
54b9620d 4770 thr->threadsv = newAV();
940cb80d 4771 /* thr->threadsvp is set when find_threadsv is called */
199100c8
MB
4772 thr->specific = newAV();
4773 thr->flags = THRf_R_JOINABLE;
4774 MUTEX_INIT(&thr->mutex);
4775 /* Handcraft thrsv similarly to mess_sv */
533c011a 4776 New(53, PL_thrsv, 1, SV);
199100c8 4777 Newz(53, xpv, 1, XPV);
533c011a
NIS
4778 SvFLAGS(PL_thrsv) = SVt_PV;
4779 SvANY(PL_thrsv) = (void*)xpv;
4780 SvREFCNT(PL_thrsv) = 1 << 30; /* practically infinite */
f880fe2f 4781 SvPV_set(PL_thrsvr, (char*)thr);
533c011a
NIS
4782 SvCUR_set(PL_thrsv, sizeof(thr));
4783 SvLEN_set(PL_thrsv, sizeof(thr));
4784 *SvEND(PL_thrsv) = '\0'; /* in the trailing_nul field */
4785 thr->oursv = PL_thrsv;
4786 PL_chopset = " \n-";
3967c732 4787 PL_dumpindent = 4;
533c011a
NIS
4788
4789 MUTEX_LOCK(&PL_threads_mutex);
4790 PL_nthreads++;
199100c8
MB
4791 thr->tid = 0;
4792 thr->next = thr;
4793 thr->prev = thr;
8dcd6f7b 4794 thr->thr_done = 0;
533c011a 4795 MUTEX_UNLOCK(&PL_threads_mutex);
199100c8 4796
4b026b9e 4797#ifdef HAVE_THREAD_INTERN
4f63d024 4798 Perl_init_thread_intern(thr);
235db74f
GS
4799#endif
4800
4801#ifdef SET_THREAD_SELF
4802 SET_THREAD_SELF(thr);
199100c8
MB
4803#else
4804 thr->self = pthread_self();
235db74f 4805#endif /* SET_THREAD_SELF */
06d86050 4806 PERL_SET_THX(thr);
199100c8
MB
4807
4808 /*
411caa50
JH
4809 * These must come after the thread self setting
4810 * because sv_setpvn does SvTAINT and the taint
4811 * fields thread selfness being set.
199100c8 4812 */
533c011a
NIS
4813 PL_toptarget = NEWSV(0,0);
4814 sv_upgrade(PL_toptarget, SVt_PVFM);
4815 sv_setpvn(PL_toptarget, "", 0);
4816 PL_bodytarget = NEWSV(0,0);
4817 sv_upgrade(PL_bodytarget, SVt_PVFM);
4818 sv_setpvn(PL_bodytarget, "", 0);
4819 PL_formtarget = PL_bodytarget;
79cb57f6 4820 thr->errsv = newSVpvn("", 0);
78857c3c 4821 (void) find_threadsv("@"); /* Ensure $@ is initialised early */
5c0ca799 4822
533c011a 4823 PL_maxscream = -1;
a2efc822 4824 PL_peepp = MEMBER_TO_FPTR(Perl_peep);
0b94c7bb
GS
4825 PL_regcompp = MEMBER_TO_FPTR(Perl_pregcomp);
4826 PL_regexecp = MEMBER_TO_FPTR(Perl_regexec_flags);
4827 PL_regint_start = MEMBER_TO_FPTR(Perl_re_intuit_start);
4828 PL_regint_string = MEMBER_TO_FPTR(Perl_re_intuit_string);
4829 PL_regfree = MEMBER_TO_FPTR(Perl_pregfree);
533c011a
NIS
4830 PL_regindent = 0;
4831 PL_reginterp_cnt = 0;
5c0ca799 4832
199100c8
MB
4833 return thr;
4834}
4d1ff10f 4835#endif /* USE_5005THREADS */
199100c8 4836
93a17b20 4837void
864dbfa3 4838Perl_call_list(pTHX_ I32 oldscope, AV *paramList)
93a17b20 4839{
27da23d5 4840 dVAR;
971a9dd3 4841 SV *atsv;
dd374669 4842 const line_t oldline = CopLINE(PL_curcop);
312caa8e 4843 CV *cv;
22921e25 4844 STRLEN len;
6224f72b 4845 int ret;
db36c5a1 4846 dJMPENV;
93a17b20 4847
e1ec3a88 4848 while (av_len(paramList) >= 0) {
312caa8e 4849 cv = (CV*)av_shift(paramList);
ece599bd
RGS
4850 if (PL_savebegin) {
4851 if (paramList == PL_beginav) {
059a8bb7 4852 /* save PL_beginav for compiler */
ece599bd
RGS
4853 if (! PL_beginav_save)
4854 PL_beginav_save = newAV();
4855 av_push(PL_beginav_save, (SV*)cv);
4856 }
4857 else if (paramList == PL_checkav) {
4858 /* save PL_checkav for compiler */
4859 if (! PL_checkav_save)
4860 PL_checkav_save = newAV();
4861 av_push(PL_checkav_save, (SV*)cv);
4862 }
059a8bb7
JH
4863 } else {
4864 SAVEFREESV(cv);
4865 }
14dd3ad8 4866 JMPENV_PUSH(ret);
6224f72b 4867 switch (ret) {
312caa8e 4868 case 0:
14dd3ad8 4869 call_list_body(cv);
971a9dd3 4870 atsv = ERRSV;
10516c54 4871 (void)SvPV_const(atsv, len);
312caa8e
CS
4872 if (len) {
4873 PL_curcop = &PL_compiling;
57843af0 4874 CopLINE_set(PL_curcop, oldline);
312caa8e
CS
4875 if (paramList == PL_beginav)
4876 sv_catpv(atsv, "BEGIN failed--compilation aborted");
4877 else
4f25aa18
GS
4878 Perl_sv_catpvf(aTHX_ atsv,
4879 "%s failed--call queue aborted",
7d30b5c4 4880 paramList == PL_checkav ? "CHECK"
4f25aa18
GS
4881 : paramList == PL_initav ? "INIT"
4882 : "END");
312caa8e
CS
4883 while (PL_scopestack_ix > oldscope)
4884 LEAVE;
14dd3ad8 4885 JMPENV_POP;
35c1215d 4886 Perl_croak(aTHX_ "%"SVf"", atsv);
a0d0e21e 4887 }
85e6fe83 4888 break;
6224f72b 4889 case 1:
f86702cc 4890 STATUS_ALL_FAILURE;
85e6fe83 4891 /* FALL THROUGH */
6224f72b 4892 case 2:
85e6fe83 4893 /* my_exit() was called */
3280af22 4894 while (PL_scopestack_ix > oldscope)
2ae324a7 4895 LEAVE;
84902520 4896 FREETMPS;
3280af22 4897 PL_curstash = PL_defstash;
3280af22 4898 PL_curcop = &PL_compiling;
57843af0 4899 CopLINE_set(PL_curcop, oldline);
14dd3ad8 4900 JMPENV_POP;
cc3604b1 4901 if (PL_statusvalue && !(PL_exit_flags & PERL_EXIT_EXPECTED)) {
3280af22 4902 if (paramList == PL_beginav)
cea2e8a9 4903 Perl_croak(aTHX_ "BEGIN failed--compilation aborted");
85e6fe83 4904 else
4f25aa18 4905 Perl_croak(aTHX_ "%s failed--call queue aborted",
7d30b5c4 4906 paramList == PL_checkav ? "CHECK"
4f25aa18
GS
4907 : paramList == PL_initav ? "INIT"
4908 : "END");
85e6fe83 4909 }
f86702cc 4910 my_exit_jump();
85e6fe83 4911 /* NOTREACHED */
6224f72b 4912 case 3:
312caa8e
CS
4913 if (PL_restartop) {
4914 PL_curcop = &PL_compiling;
57843af0 4915 CopLINE_set(PL_curcop, oldline);
312caa8e 4916 JMPENV_JUMP(3);
85e6fe83 4917 }
bf49b057 4918 PerlIO_printf(Perl_error_log, "panic: restartop\n");
312caa8e
CS
4919 FREETMPS;
4920 break;
8990e307 4921 }
14dd3ad8 4922 JMPENV_POP;
93a17b20 4923 }
93a17b20 4924}
93a17b20 4925
14dd3ad8
GS
4926STATIC void *
4927S_call_list_body(pTHX_ CV *cv)
4928{
312caa8e 4929 PUSHMARK(PL_stack_sp);
864dbfa3 4930 call_sv((SV*)cv, G_EVAL|G_DISCARD);
312caa8e
CS
4931 return NULL;
4932}
4933
f86702cc 4934void
864dbfa3 4935Perl_my_exit(pTHX_ U32 status)
f86702cc 4936{
8b73bbec 4937 DEBUG_S(PerlIO_printf(Perl_debug_log, "my_exit: thread %p, status %lu\n",
a863c7d1 4938 thr, (unsigned long) status));
f86702cc 4939 switch (status) {
4940 case 0:
4941 STATUS_ALL_SUCCESS;
4942 break;
4943 case 1:
4944 STATUS_ALL_FAILURE;
4945 break;
4946 default:
4947 STATUS_NATIVE_SET(status);
4948 break;
4949 }
4950 my_exit_jump();
4951}
4952
4953void
864dbfa3 4954Perl_my_failure_exit(pTHX)
f86702cc 4955{
4956#ifdef VMS
4957 if (vaxc$errno & 1) {
4fdae800 4958 if (STATUS_NATIVE & 1) /* fortuitiously includes "-1" */
4959 STATUS_NATIVE_SET(44);
f86702cc 4960 }
4961 else {
69232efa 4962 if (!vaxc$errno) /* unlikely */
4fdae800 4963 STATUS_NATIVE_SET(44);
f86702cc 4964 else
4fdae800 4965 STATUS_NATIVE_SET(vaxc$errno);
f86702cc 4966 }
4967#else
9b599b2a 4968 int exitstatus;
f86702cc 4969 if (errno & 255)
e5218da5 4970 STATUS_UNIX_SET(errno);
9b599b2a 4971 else {
e5218da5 4972 exitstatus = STATUS_UNIX >> 8;
9b599b2a 4973 if (exitstatus & 255)
e5218da5 4974 STATUS_UNIX_SET(exitstatus);
9b599b2a 4975 else
e5218da5 4976 STATUS_UNIX_SET(255);
9b599b2a 4977 }
f86702cc 4978#endif
4979 my_exit_jump();
93a17b20
LW
4980}
4981
76e3520e 4982STATIC void
cea2e8a9 4983S_my_exit_jump(pTHX)
f86702cc 4984{
27da23d5 4985 dVAR;
c09156bb 4986 register PERL_CONTEXT *cx;
f86702cc 4987 I32 gimme;
4988 SV **newsp;
4989
3280af22
NIS
4990 if (PL_e_script) {
4991 SvREFCNT_dec(PL_e_script);
4992 PL_e_script = Nullsv;
f86702cc 4993 }
4994
3280af22 4995 POPSTACK_TO(PL_mainstack);
f86702cc 4996 if (cxstack_ix >= 0) {
4997 if (cxstack_ix > 0)
4998 dounwind(0);
3280af22 4999 POPBLOCK(cx,PL_curpm);
f86702cc 5000 LEAVE;
5001 }
ff0cee69 5002
6224f72b 5003 JMPENV_JUMP(2);
f86702cc 5004}
873ef191 5005
0cb96387 5006static I32
acfe0abc 5007read_e_script(pTHX_ int idx, SV *buf_sv, int maxlen)
873ef191 5008{
848ef955 5009 const char *p, *nl;
dd374669
AL
5010 (void)idx;
5011 (void)maxlen;
5012
848ef955 5013 p = SvPVX_const(PL_e_script);
873ef191 5014 nl = strchr(p, '\n');
3280af22 5015 nl = (nl) ? nl+1 : SvEND(PL_e_script);
7dfe3f66 5016 if (nl-p == 0) {
0cb96387 5017 filter_del(read_e_script);
873ef191 5018 return 0;
7dfe3f66 5019 }
873ef191 5020 sv_catpvn(buf_sv, p, nl-p);
3280af22 5021 sv_chop(PL_e_script, nl);
873ef191
GS
5022 return 1;
5023}
66610fdd
RGS
5024
5025/*
5026 * Local variables:
5027 * c-indentation-style: bsd
5028 * c-basic-offset: 4
5029 * indent-tabs-mode: t
5030 * End:
5031 *
37442d52
RGS
5032 * ex: set ts=8 sts=4 sw=4 noet:
5033 */