This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Define setlocale_i() on unsafe threaded builds
[perl5.git] / perl.c
1 #line 2 "perl.c"
2 /*    perl.c
3  *
4  *    Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001
5  *    2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012
6  *    2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023
7  *    by Larry Wall and others
8  *
9  *    You may distribute under the terms of either the GNU General Public
10  *    License or the Artistic License, as specified in the README file.
11  *
12  */
13
14 /*
15  *      A ship then new they built for him
16  *      of mithril and of elven-glass
17  *              --from Bilbo's song of EƤrendil
18  *
19  *     [p.236 of _The Lord of the Rings_, II/i: "Many Meetings"]
20  */
21
22 /* This file contains the top-level functions that are used to create, use
23  * and destroy a perl interpreter, plus the functions used by XS code to
24  * call back into perl. Note that it does not contain the actual main()
25  * function of the interpreter; that can be found in perlmain.c
26  *
27  * Note that at build time this file is also linked to as perlmini.c,
28  * and perlmini.o is then built with PERL_IS_MINIPERL defined, which is
29  * then used to create the miniperl executable, rather than perl.o.
30  */
31
32 #if defined(PERL_IS_MINIPERL) && !defined(USE_SITECUSTOMIZE)
33 #  define USE_SITECUSTOMIZE
34 #endif
35
36 #include "EXTERN.h"
37 #define PERL_IN_PERL_C
38 #include "perl.h"
39 #include "patchlevel.h"                 /* for local_patches */
40 #include "XSUB.h"
41
42 #ifdef DEBUG_LEAKING_SCALARS_FORK_DUMP
43 #  ifdef I_SYSUIO
44 #    include <sys/uio.h>
45 #  endif
46
47 union control_un {
48   struct cmsghdr cm;
49   char control[CMSG_SPACE(sizeof(int))];
50 };
51
52 #endif
53
54 #ifndef HZ
55 #  ifdef CLK_TCK
56 #    define HZ CLK_TCK
57 #  else
58 #    define HZ 60
59 #  endif
60 #endif
61
62 static I32 read_e_script(pTHX_ int idx, SV *buf_sv, int maxlen);
63
64 #ifdef SETUID_SCRIPTS_ARE_SECURE_NOW
65 #  define validate_suid(rsfp) NOOP
66 #else
67 #  define validate_suid(rsfp) S_validate_suid(aTHX_ rsfp)
68 #endif
69
70 #define CALL_LIST_BODY(cv) \
71     PUSHMARK(PL_stack_sp); \
72     call_sv(MUTABLE_SV((cv)), G_EVAL|G_DISCARD|G_VOID);
73
74 static void
75 S_init_tls_and_interp(PerlInterpreter *my_perl)
76 {
77     if (!PL_curinterp) {
78         PERL_SET_INTERP(my_perl);
79 #if defined(USE_ITHREADS)
80         INIT_THREADS;
81         ALLOC_THREAD_KEY;
82         PERL_SET_THX(my_perl);
83         OP_REFCNT_INIT;
84         OP_CHECK_MUTEX_INIT;
85         KEYWORD_PLUGIN_MUTEX_INIT;
86         HINTS_REFCNT_INIT;
87         LOCALE_INIT;
88         USER_PROP_MUTEX_INIT;
89         ENV_INIT;
90         MUTEX_INIT(&PL_dollarzero_mutex);
91         MUTEX_INIT(&PL_my_ctx_mutex);
92 #  endif
93     }
94 #if defined(USE_ITHREADS)
95     else
96 #else
97     /* This always happens for non-ithreads  */
98 #endif
99     {
100         PERL_SET_THX(my_perl);
101     }
102 }
103
104
105 #ifndef PLATFORM_SYS_INIT_
106 #  define PLATFORM_SYS_INIT_  NOOP
107 #endif
108
109 #ifndef PLATFORM_SYS_TERM_
110 #  define PLATFORM_SYS_TERM_  NOOP
111 #endif
112
113 #ifndef PERL_SYS_INIT_BODY
114 #  define PERL_SYS_INIT_BODY(c,v)                               \
115         MALLOC_CHECK_TAINT2(*c,*v) PERL_FPU_INIT; PERLIO_INIT;  \
116         MALLOC_INIT; PLATFORM_SYS_INIT_;
117 #endif
118
119 /* Generally add things last-in first-terminated.  IO and memory terminations
120  * need to be generally last
121  *
122  * BEWARE that using PerlIO in these will be using freed memory, so may appear
123  * to work, but must NOT be retained in production code. */
124 #ifndef PERL_SYS_TERM_BODY
125 #  define PERL_SYS_TERM_BODY()                                          \
126                     ENV_TERM; USER_PROP_MUTEX_TERM; LOCALE_TERM;        \
127                     HINTS_REFCNT_TERM; KEYWORD_PLUGIN_MUTEX_TERM;       \
128                     OP_CHECK_MUTEX_TERM; OP_REFCNT_TERM;                \
129                     PERLIO_TERM; MALLOC_TERM;                           \
130                     PLATFORM_SYS_TERM_;
131 #endif
132
133 /* these implement the PERL_SYS_INIT, PERL_SYS_INIT3, PERL_SYS_TERM macros */
134
135 void
136 Perl_sys_init(int* argc, char*** argv)
137 {
138
139     PERL_ARGS_ASSERT_SYS_INIT;
140
141     PERL_UNUSED_ARG(argc); /* may not be used depending on _BODY macro */
142     PERL_UNUSED_ARG(argv);
143     PERL_SYS_INIT_BODY(argc, argv);
144 }
145
146 void
147 Perl_sys_init3(int* argc, char*** argv, char*** env)
148 {
149
150     PERL_ARGS_ASSERT_SYS_INIT3;
151
152     PERL_UNUSED_ARG(argc); /* may not be used depending on _BODY macro */
153     PERL_UNUSED_ARG(argv);
154     PERL_UNUSED_ARG(env);
155     PERL_SYS_INIT3_BODY(argc, argv, env);
156 }
157
158 void
159 Perl_sys_term(void)
160 {
161     if (!PL_veto_cleanup) {
162         PERL_SYS_TERM_BODY();
163     }
164 }
165
166
167 #ifdef PERL_IMPLICIT_SYS
168 PerlInterpreter *
169 perl_alloc_using(struct IPerlMem* ipM, struct IPerlMem* ipMS,
170                  struct IPerlMem* ipMP, struct IPerlEnv* ipE,
171                  struct IPerlStdIO* ipStd, struct IPerlLIO* ipLIO,
172                  struct IPerlDir* ipD, struct IPerlSock* ipS,
173                  struct IPerlProc* ipP)
174 {
175     PerlInterpreter *my_perl;
176
177     PERL_ARGS_ASSERT_PERL_ALLOC_USING;
178
179     /* Newx() needs interpreter, so call malloc() instead */
180     my_perl = (PerlInterpreter*)(*ipM->pCalloc)(ipM, 1, sizeof(PerlInterpreter));
181     S_init_tls_and_interp(my_perl);
182     PL_Mem = ipM;
183     PL_MemShared = ipMS;
184     PL_MemParse = ipMP;
185     PL_Env = ipE;
186     PL_StdIO = ipStd;
187     PL_LIO = ipLIO;
188     PL_Dir = ipD;
189     PL_Sock = ipS;
190     PL_Proc = ipP;
191     INIT_TRACK_MEMPOOL(PL_memory_debug_header, my_perl);
192
193     return my_perl;
194 }
195 #else
196
197 /*
198 =for apidoc_section $embedding
199
200 =for apidoc perl_alloc
201
202 Allocates a new Perl interpreter.  See L<perlembed>.
203
204 =cut
205 */
206
207 PerlInterpreter *
208 perl_alloc(void)
209 {
210     PerlInterpreter *my_perl = (PerlInterpreter*)PerlMem_calloc(1, sizeof(PerlInterpreter));
211
212     S_init_tls_and_interp(my_perl);
213     INIT_TRACK_MEMPOOL(PL_memory_debug_header, my_perl);
214     return my_perl;
215 }
216 #endif /* PERL_IMPLICIT_SYS */
217
218 /*
219 =for apidoc perl_construct
220
221 Initializes a new Perl interpreter.  See L<perlembed>.
222
223 =cut
224 */
225
226 void
227 perl_construct(pTHXx)
228 {
229
230     PERL_ARGS_ASSERT_PERL_CONSTRUCT;
231
232 #ifdef MULTIPLICITY
233     init_interp();
234     PL_perl_destruct_level = 1;
235 #else
236     PERL_UNUSED_ARG(my_perl);
237    if (PL_perl_destruct_level > 0)
238        init_interp();
239 #endif
240     PL_curcop = &PL_compiling;  /* needed by ckWARN, right away */
241
242 #ifdef PERL_TRACE_OPS
243     Zero(PL_op_exec_cnt, OP_max+2, UV);
244 #endif
245
246     init_constants();
247
248     SvREADONLY_on(&PL_sv_placeholder);
249     SvREFCNT(&PL_sv_placeholder) = SvREFCNT_IMMORTAL;
250
251     PL_sighandlerp  = Perl_sighandler;
252     PL_sighandler1p = Perl_sighandler1;
253     PL_sighandler3p = Perl_sighandler3;
254
255 #ifdef PERL_USES_PL_PIDSTATUS
256     PL_pidstatus = newHV();
257 #endif
258
259     PL_rs = newSVpvs("\n");
260
261     init_stacks();
262
263 #if !defined(NO_PERL_RAND_SEED) || !defined(NO_PERL_INTERNAL_HASH_SEED)
264     bool sensitive_env_vars_allowed =
265             (PerlProc_getuid() == PerlProc_geteuid() &&
266              PerlProc_getgid() == PerlProc_getegid()) ? TRUE : FALSE;
267 #endif
268
269 /* The seed set-up must be after init_stacks because it calls
270  * things that may put SVs on the stack.
271  */
272 #ifndef NO_PERL_RAND_SEED
273     if (sensitive_env_vars_allowed) {
274         UV seed= 0;
275         const char *env_pv;
276         if ((env_pv = PerlEnv_getenv("PERL_RAND_SEED")) &&
277             grok_number(env_pv, strlen(env_pv), &seed) == IS_NUMBER_IN_UV)
278         {
279
280             PL_srand_override_next = seed;
281             PERL_SRAND_OVERRIDE_NEXT_INIT();
282         }
283     }
284 #endif
285
286     /* This is NOT the state used for C<rand()>, this is only
287      * used in internal functionality */
288 #ifdef NO_PERL_INTERNAL_RAND_SEED
289     Perl_drand48_init_r(&PL_internal_random_state, seed());
290 #else
291     {
292         UV seed;
293         const char *env_pv;
294         if (
295             !sensitive_env_vars_allowed ||
296             !(env_pv = PerlEnv_getenv("PERL_INTERNAL_RAND_SEED")) ||
297             grok_number(env_pv, strlen(env_pv), &seed) != IS_NUMBER_IN_UV)
298         {
299             /* use a randomly generated seed */
300             seed = seed();
301         }
302         Perl_drand48_init_r(&PL_internal_random_state, (U32)seed);
303     }
304 #endif
305
306     init_ids();
307
308     JMPENV_BOOTSTRAP;
309     STATUS_ALL_SUCCESS;
310
311     init_uniprops();
312     (void) uvchr_to_utf8_flags((U8 *) PL_TR_SPECIAL_HANDLING_UTF8,
313                                TR_SPECIAL_HANDLING,
314                                UNICODE_ALLOW_ABOVE_IV_MAX);
315
316 #if defined(LOCAL_PATCH_COUNT)
317     PL_localpatches = local_patches;    /* For possible -v */
318 #endif
319
320 #if defined(LIBM_LIB_VERSION)
321     /*
322      * Some BSDs and Cygwin default to POSIX math instead of IEEE.
323      * This switches them over to IEEE.
324      */
325     _LIB_VERSION = _IEEE_;
326 #endif
327
328 #ifdef HAVE_INTERP_INTERN
329     sys_intern_init();
330 #endif
331
332     PerlIO_init(aTHX);                  /* Hook to IO system */
333
334     PL_fdpid = newAV();                 /* for remembering popen pids by fd */
335     PL_modglobal = newHV();             /* pointers to per-interpreter module globals */
336     PL_errors = newSVpvs("");
337     SvPVCLEAR(PERL_DEBUG_PAD(0));        /* For regex debugging. */
338     SvPVCLEAR(PERL_DEBUG_PAD(1));        /* ext/re needs these */
339     SvPVCLEAR(PERL_DEBUG_PAD(2));        /* even without DEBUGGING. */
340 #ifdef USE_ITHREADS
341     /* First entry is a list of empty elements. It needs to be initialised
342        else all hell breaks loose in S_find_uninit_var().  */
343     Perl_av_create_and_push(aTHX_ &PL_regex_padav, newSVpvs(""));
344     PL_regex_pad = AvARRAY(PL_regex_padav);
345     Newxz(PL_stashpad, PL_stashpadmax, HV *);
346 #endif
347 #ifdef USE_REENTRANT_API
348     Perl_reentrant_init(aTHX);
349 #endif
350     if (PL_hash_seed_set == FALSE) {
351         /* Initialize the hash seed and state at startup. This must be
352          * done very early, before ANY hashes are constructed, and once
353          * setup is fixed for the lifetime of the process.
354          *
355          * If you decide to disable the seeding process you should choose
356          * a suitable seed yourself and define PERL_HASH_SEED to a well chosen
357          * string. See hv_func.h for details.
358          */
359 #if defined(USE_HASH_SEED)
360         /* get the hash seed from the environment or from an RNG */
361         Perl_get_hash_seed(aTHX_ PL_hash_seed);
362 #else
363         /* they want a hard coded seed, check that it is long enough */
364         assert( strlen(PERL_HASH_SEED) >= PERL_HASH_SEED_BYTES );
365 #endif
366
367         /* now we use the chosen seed to initialize the state -
368          * in some configurations this may be a relatively speaking
369          * expensive operation, but we only have to do it once at startup */
370         PERL_HASH_SEED_STATE(PERL_HASH_SEED,PL_hash_state);
371
372 #ifdef PERL_USE_SINGLE_CHAR_HASH_CACHE
373         /* we can build a special cache for 0/1 byte keys, if people choose
374          * I suspect most of the time it is not worth it */
375         {
376             char str[2]="\0";
377             int i;
378             for (i=0;i<256;i++) {
379                 str[0]= i;
380                 PERL_HASH_WITH_STATE(PL_hash_state,PL_hash_chars[i],str,1);
381             }
382             PERL_HASH_WITH_STATE(PL_hash_state,PL_hash_chars[256],str,0);
383         }
384 #endif
385         /* at this point we have initialized the hash function, and we can start
386          * constructing hashes */
387         PL_hash_seed_set= TRUE;
388     }
389
390     /* Allow PL_strtab to be pre-initialized before calling perl_construct.
391     * can use a custom optimized PL_strtab hash before calling perl_construct */
392     if (!PL_strtab) {
393         /* Note that strtab is a rather special HV.  Assumptions are made
394            about not iterating on it, and not adding tie magic to it.
395            It is properly deallocated in perl_destruct() */
396         PL_strtab = newHV();
397
398         /* SHAREKEYS tells us that the hash has its keys shared with PL_strtab,
399          * which is not the case with PL_strtab itself */
400         HvSHAREKEYS_off(PL_strtab);                     /* mandatory */
401         hv_ksplit(PL_strtab, 1 << 11);
402     }
403
404 #ifdef USE_ITHREADS
405     PL_compiling.cop_file = NULL;
406     PL_compiling.cop_warnings = NULL;
407 #endif
408
409     Zero(PL_sv_consts, SV_CONSTS_COUNT, SV*);
410
411 #ifdef  USE_ENVIRON_ARRAY
412     if (!PL_origenviron)
413         PL_origenviron = environ;
414 #endif
415
416     /* Use sysconf(_SC_CLK_TCK) if available, if not
417      * available or if the sysconf() fails, use the HZ.
418      * The HZ if not originally defined has been by now
419      * been defined as CLK_TCK, if available. */
420 #if defined(HAS_SYSCONF) && defined(_SC_CLK_TCK)
421     PL_clocktick = sysconf(_SC_CLK_TCK);
422     if (PL_clocktick <= 0)
423 #endif
424          PL_clocktick = HZ;
425
426     PL_stashcache = newHV();
427
428     PL_patchlevel = newSVpvs("v" PERL_VERSION_STRING);
429
430 #ifdef HAS_MMAP
431     if (!PL_mmap_page_size) {
432 #if defined(HAS_SYSCONF) && (defined(_SC_PAGESIZE) || defined(_SC_MMAP_PAGE_SIZE))
433       {
434         SETERRNO(0, SS_NORMAL);
435 #   ifdef _SC_PAGESIZE
436         PL_mmap_page_size = sysconf(_SC_PAGESIZE);
437 #   else
438         PL_mmap_page_size = sysconf(_SC_MMAP_PAGE_SIZE);
439 #   endif
440         if ((long) PL_mmap_page_size < 0) {
441             Perl_croak(aTHX_ "panic: sysconf: %s",
442                 errno ? Strerror(errno) : "pagesize unknown");
443         }
444       }
445 #elif defined(HAS_GETPAGESIZE)
446       PL_mmap_page_size = getpagesize();
447 #elif defined(I_SYS_PARAM) && defined(PAGESIZE)
448       PL_mmap_page_size = PAGESIZE;       /* compiletime, bad */
449 #endif
450       if (PL_mmap_page_size <= 0)
451         Perl_croak(aTHX_ "panic: bad pagesize %" IVdf,
452                    (IV) PL_mmap_page_size);
453     }
454 #endif /* HAS_MMAP */
455
456     PL_osname = Perl_savepvn(aTHX_ STR_WITH_LEN(OSNAME));
457
458     PL_registered_mros = newHV();
459     /* Start with 1 bucket, for DFS.  It's unlikely we'll need more.  */
460     HvMAX(PL_registered_mros) = 0;
461
462     ENTER;
463     init_i18nl10n(1);
464 }
465
466 /*
467 =for apidoc nothreadhook
468
469 Stub that provides thread hook for perl_destruct when there are
470 no threads.
471
472 =cut
473 */
474
475 int
476 Perl_nothreadhook(pTHX)
477 {
478     PERL_UNUSED_CONTEXT;
479     return 0;
480 }
481
482 #ifdef DEBUG_LEAKING_SCALARS_FORK_DUMP
483 void
484 Perl_dump_sv_child(pTHX_ SV *sv)
485 {
486     ssize_t got;
487     const int sock = PL_dumper_fd;
488     const int debug_fd = PerlIO_fileno(Perl_debug_log);
489     union control_un control;
490     struct msghdr msg;
491     struct iovec vec[2];
492     struct cmsghdr *cmptr;
493     int returned_errno;
494     unsigned char buffer[256];
495
496     PERL_ARGS_ASSERT_DUMP_SV_CHILD;
497
498     if(sock == -1 || debug_fd == -1)
499         return;
500
501     PerlIO_flush(Perl_debug_log);
502
503     /* All these shenanigans are to pass a file descriptor over to our child for
504        it to dump out to.  We can't let it hold open the file descriptor when it
505        forks, as the file descriptor it will dump to can turn out to be one end
506        of pipe that some other process will wait on for EOF. (So as it would
507        be open, the wait would be forever.)  */
508
509     msg.msg_control = control.control;
510     msg.msg_controllen = sizeof(control.control);
511     /* We're a connected socket so we don't need a destination  */
512     msg.msg_name = NULL;
513     msg.msg_namelen = 0;
514     msg.msg_iov = vec;
515     msg.msg_iovlen = 1;
516
517     cmptr = CMSG_FIRSTHDR(&msg);
518     cmptr->cmsg_len = CMSG_LEN(sizeof(int));
519     cmptr->cmsg_level = SOL_SOCKET;
520     cmptr->cmsg_type = SCM_RIGHTS;
521     *((int *)CMSG_DATA(cmptr)) = 1;
522
523     vec[0].iov_base = (void*)&sv;
524     vec[0].iov_len = sizeof(sv);
525     got = sendmsg(sock, &msg, 0);
526
527     if(got < 0) {
528         perror("Debug leaking scalars parent sendmsg failed");
529         abort();
530     }
531     if(got < sizeof(sv)) {
532         perror("Debug leaking scalars parent short sendmsg");
533         abort();
534     }
535
536     /* Return protocol is
537        int:             errno value
538        unsigned char:   length of location string (0 for empty)
539        unsigned char*:  string (not terminated)
540     */
541     vec[0].iov_base = (void*)&returned_errno;
542     vec[0].iov_len = sizeof(returned_errno);
543     vec[1].iov_base = buffer;
544     vec[1].iov_len = 1;
545
546     got = readv(sock, vec, 2);
547
548     if(got < 0) {
549         perror("Debug leaking scalars parent read failed");
550         PerlIO_flush(PerlIO_stderr());
551         abort();
552     }
553     if(got < sizeof(returned_errno) + 1) {
554         perror("Debug leaking scalars parent short read");
555         PerlIO_flush(PerlIO_stderr());
556         abort();
557     }
558
559     if (*buffer) {
560         got = read(sock, buffer + 1, *buffer);
561         if(got < 0) {
562             perror("Debug leaking scalars parent read 2 failed");
563             PerlIO_flush(PerlIO_stderr());
564             abort();
565         }
566
567         if(got < *buffer) {
568             perror("Debug leaking scalars parent short read 2");
569             PerlIO_flush(PerlIO_stderr());
570             abort();
571         }
572     }
573
574     if (returned_errno || *buffer) {
575         Perl_warn(aTHX_ "Debug leaking scalars child failed%s%.*s with errno"
576                   " %d: %s", (*buffer ? " at " : ""), (int) *buffer, buffer + 1,
577                   returned_errno, Strerror(returned_errno));
578     }
579 }
580 #endif
581
582 /*
583 =for apidoc perl_destruct
584
585 Shuts down a Perl interpreter.  See L<perlembed> for a tutorial.
586
587 C<my_perl> points to the Perl interpreter.  It must have been previously
588 created through the use of L</perl_alloc> and L</perl_construct>.  It may
589 have been initialised through L</perl_parse>, and may have been used
590 through L</perl_run> and other means.  This function should be called for
591 any Perl interpreter that has been constructed with L</perl_construct>,
592 even if subsequent operations on it failed, for example if L</perl_parse>
593 returned a non-zero value.
594
595 If the interpreter's C<PL_exit_flags> word has the
596 C<PERL_EXIT_DESTRUCT_END> flag set, then this function will execute code
597 in C<END> blocks before performing the rest of destruction.  If it is
598 desired to make any use of the interpreter between L</perl_parse> and
599 L</perl_destruct> other than just calling L</perl_run>, then this flag
600 should be set early on.  This matters if L</perl_run> will not be called,
601 or if anything else will be done in addition to calling L</perl_run>.
602
603 Returns a value be a suitable value to pass to the C library function
604 C<exit> (or to return from C<main>), to serve as an exit code indicating
605 the nature of the way the interpreter terminated.  This takes into account
606 any failure of L</perl_parse> and any early exit from L</perl_run>.
607 The exit code is of the type required by the host operating system,
608 so because of differing exit code conventions it is not portable to
609 interpret specific numeric values as having specific meanings.
610
611 =cut
612 */
613
614 int
615 perl_destruct(pTHXx)
616 {
617     volatile signed char destruct_level;  /* see possible values in intrpvar.h */
618     HV *hv;
619 #ifdef DEBUG_LEAKING_SCALARS_FORK_DUMP
620     pid_t child;
621 #endif
622     int i;
623
624     PERL_ARGS_ASSERT_PERL_DESTRUCT;
625 #ifndef MULTIPLICITY
626     PERL_UNUSED_ARG(my_perl);
627 #endif
628
629     assert(PL_scopestack_ix == 1);
630
631     destruct_level = PL_perl_destruct_level;
632     {
633         const char * const s = PerlEnv_getenv("PERL_DESTRUCT_LEVEL");
634         if (s) {
635             int i;
636             if (strEQ(s, "-1")) { /* Special case: modperl folklore. */
637                 i = -1;
638             } else {
639                 UV uv;
640                 if (grok_atoUV(s, &uv, NULL) && uv <= INT_MAX)
641                     i = (int)uv;
642                 else
643                     i = 0;
644             }
645             if (destruct_level < i) destruct_level = i;
646 #ifdef PERL_TRACK_MEMPOOL
647             /* RT #114496, for perl_free */
648             PL_perl_destruct_level = i;
649 #endif
650         }
651     }
652
653     if (PL_exit_flags & PERL_EXIT_DESTRUCT_END) {
654         dJMPENV;
655         int x = 0;
656
657         JMPENV_PUSH(x);
658         PERL_UNUSED_VAR(x);
659         if (PL_endav && !PL_minus_c) {
660             PERL_SET_PHASE(PERL_PHASE_END);
661             call_list(PL_scopestack_ix, PL_endav);
662         }
663         JMPENV_POP;
664     }
665     LEAVE;
666     FREETMPS;
667     assert(PL_scopestack_ix == 0);
668
669     /* wait for all pseudo-forked children to finish */
670     PERL_WAIT_FOR_CHILDREN;
671
672
673     /* normally when we get here, PL_parser should be null due to having
674      * its original (null) value restored by SAVEt_PARSER during leaving
675      * scope (usually before run-time starts in fact).
676      * But if a thread is created within a BEGIN block, the parser is
677      * duped, but the SAVEt_PARSER savestack entry isn't. So PL_parser
678      * never gets cleaned up.
679      * Clean it up here instead. This is a bit of a hack.
680      */
681     if (PL_parser) {
682         /* stop parser_free() stomping on PL_curcop */
683         PL_parser->saved_curcop = PL_curcop;
684         parser_free(PL_parser);
685     }
686
687
688     /* Need to flush since END blocks can produce output */
689     /* flush stdout separately, since we can identify it */
690 #ifdef USE_PERLIO
691     {
692         PerlIO *stdo = PerlIO_stdout();
693         if (*stdo && PerlIO_flush(stdo)) {
694             PerlIO_restore_errno(stdo);
695             if (errno)
696                 PerlIO_printf(PerlIO_stderr(), "Unable to flush stdout: %s\n",
697                     Strerror(errno));
698             if (!STATUS_UNIX)
699                 STATUS_ALL_FAILURE;
700         }
701     }
702 #endif
703     my_fflush_all();
704
705 #ifdef PERL_TRACE_OPS
706     /* dump OP-counts if $ENV{PERL_TRACE_OPS} > 0 */
707     {
708         const char * const ptoenv = PerlEnv_getenv("PERL_TRACE_OPS");
709         UV uv;
710
711         if (!ptoenv || !Perl_grok_atoUV(ptoenv, &uv, NULL)
712             || !(uv > 0))
713         goto no_trace_out;
714     }
715     PerlIO_printf(Perl_debug_log, "Trace of all OPs executed:\n");
716     for (i = 0; i <= OP_max; ++i) {
717         if (PL_op_exec_cnt[i])
718             PerlIO_printf(Perl_debug_log, "  %s: %" UVuf "\n", PL_op_name[i], PL_op_exec_cnt[i]);
719     }
720     /* Utility slot for easily doing little tracing experiments in the runloop: */
721     if (PL_op_exec_cnt[OP_max+1] != 0)
722         PerlIO_printf(Perl_debug_log, "  SPECIAL: %" UVuf "\n", PL_op_exec_cnt[OP_max+1]);
723     PerlIO_printf(Perl_debug_log, "\n");
724  no_trace_out:
725 #endif
726
727
728     if (PL_threadhook(aTHX)) {
729         /* Threads hook has vetoed further cleanup */
730         PL_veto_cleanup = TRUE;
731         return STATUS_EXIT;
732     }
733
734 #ifdef DEBUG_LEAKING_SCALARS_FORK_DUMP
735     if (destruct_level != 0) {
736         /* Fork here to create a child. Our child's job is to preserve the
737            state of scalars prior to destruction, so that we can instruct it
738            to dump any scalars that we later find have leaked.
739            There's no subtlety in this code - it assumes POSIX, and it doesn't
740            fail gracefully  */
741         int fd[2];
742
743         if(PerlSock_socketpair_cloexec(AF_UNIX, SOCK_STREAM, 0, fd)) {
744             perror("Debug leaking scalars socketpair failed");
745             abort();
746         }
747
748         child = fork();
749         if(child == -1) {
750             perror("Debug leaking scalars fork failed");
751             abort();
752         }
753         if (!child) {
754             /* We are the child */
755             const int sock = fd[1];
756             const int debug_fd = PerlIO_fileno(Perl_debug_log);
757             int f;
758             const char *where;
759             /* Our success message is an integer 0, and a char 0  */
760             static const char success[sizeof(int) + 1] = {0};
761
762             close(fd[0]);
763
764             /* We need to close all other file descriptors otherwise we end up
765                with interesting hangs, where the parent closes its end of a
766                pipe, and sits waiting for (another) child to terminate. Only
767                that child never terminates, because it never gets EOF, because
768                we also have the far end of the pipe open.  We even need to
769                close the debugging fd, because sometimes it happens to be one
770                end of a pipe, and a process is waiting on the other end for
771                EOF. Normally it would be closed at some point earlier in
772                destruction, but if we happen to cause the pipe to remain open,
773                EOF never occurs, and we get an infinite hang. Hence all the
774                games to pass in a file descriptor if it's actually needed.  */
775
776             f = sysconf(_SC_OPEN_MAX);
777             if(f < 0) {
778                 where = "sysconf failed";
779                 goto abort;
780             }
781             while (f--) {
782                 if (f == sock)
783                     continue;
784                 close(f);
785             }
786
787             while (1) {
788                 SV *target;
789                 union control_un control;
790                 struct msghdr msg;
791                 struct iovec vec[1];
792                 struct cmsghdr *cmptr;
793                 ssize_t got;
794                 int got_fd;
795
796                 msg.msg_control = control.control;
797                 msg.msg_controllen = sizeof(control.control);
798                 /* We're a connected socket so we don't need a source  */
799                 msg.msg_name = NULL;
800                 msg.msg_namelen = 0;
801                 msg.msg_iov = vec;
802                 msg.msg_iovlen = C_ARRAY_LENGTH(vec);
803
804                 vec[0].iov_base = (void*)&target;
805                 vec[0].iov_len = sizeof(target);
806
807                 got = recvmsg(sock, &msg, 0);
808
809                 if(got == 0)
810                     break;
811                 if(got < 0) {
812                     where = "recv failed";
813                     goto abort;
814                 }
815                 if(got < sizeof(target)) {
816                     where = "short recv";
817                     goto abort;
818                 }
819
820                 if(!(cmptr = CMSG_FIRSTHDR(&msg))) {
821                     where = "no cmsg";
822                     goto abort;
823                 }
824                 if(cmptr->cmsg_len != CMSG_LEN(sizeof(int))) {
825                     where = "wrong cmsg_len";
826                     goto abort;
827                 }
828                 if(cmptr->cmsg_level != SOL_SOCKET) {
829                     where = "wrong cmsg_level";
830                     goto abort;
831                 }
832                 if(cmptr->cmsg_type != SCM_RIGHTS) {
833                     where = "wrong cmsg_type";
834                     goto abort;
835                 }
836
837                 got_fd = *(int*)CMSG_DATA(cmptr);
838                 /* For our last little bit of trickery, put the file descriptor
839                    back into Perl_debug_log, as if we never actually closed it
840                 */
841                 if(got_fd != debug_fd) {
842                     if (PerlLIO_dup2_cloexec(got_fd, debug_fd) == -1) {
843                         where = "dup2";
844                         goto abort;
845                     }
846                 }
847                 sv_dump(target);
848
849                 PerlIO_flush(Perl_debug_log);
850
851                 got = write(sock, &success, sizeof(success));
852
853                 if(got < 0) {
854                     where = "write failed";
855                     goto abort;
856                 }
857                 if(got < sizeof(success)) {
858                     where = "short write";
859                     goto abort;
860                 }
861             }
862             _exit(0);
863         abort:
864             {
865                 int send_errno = errno;
866                 unsigned char length = (unsigned char) strlen(where);
867                 struct iovec failure[3] = {
868                     {(void*)&send_errno, sizeof(send_errno)},
869                     {&length, 1},
870                     {(void*)where, length}
871                 };
872                 int got = writev(sock, failure, 3);
873                 /* Bad news travels fast. Faster than data. We'll get a SIGPIPE
874                    in the parent if we try to read from the socketpair after the
875                    child has exited, even if there was data to read.
876                    So sleep a bit to give the parent a fighting chance of
877                    reading the data.  */
878                 sleep(2);
879                 _exit((got == -1) ? errno : 0);
880             }
881             /* End of child.  */
882         }
883         PL_dumper_fd = fd[0];
884         close(fd[1]);
885     }
886 #endif
887
888     /* We must account for everything.  */
889
890     /* Destroy the main CV and syntax tree */
891     /* Set PL_curcop now, because destroying ops can cause new SVs
892        to be generated in Perl_pad_swipe, and when running with
893       -DDEBUG_LEAKING_SCALARS they expect PL_curcop to point to a valid
894        op from which the filename structure member is copied.  */
895     PL_curcop = &PL_compiling;
896     if (PL_main_root) {
897         /* ensure comppad/curpad to refer to main's pad */
898         if (CvPADLIST(PL_main_cv)) {
899             PAD_SET_CUR_NOSAVE(CvPADLIST(PL_main_cv), 1);
900             PL_comppad_name = PadlistNAMES(CvPADLIST(PL_main_cv));
901         }
902         op_free(PL_main_root);
903         PL_main_root = NULL;
904     }
905     PL_main_start = NULL;
906     /* note that  PL_main_cv isn't usually actually freed at this point,
907      * due to the CvOUTSIDE refs from subs compiled within it. It will
908      * get freed once all the subs are freed in sv_clean_all(), for
909      * destruct_level > 0 */
910     SvREFCNT_dec(PL_main_cv);
911     PL_main_cv = NULL;
912     PERL_SET_PHASE(PERL_PHASE_DESTRUCT);
913
914     /* Tell PerlIO we are about to tear things apart in case
915        we have layers which are using resources that should
916        be cleaned up now.
917      */
918
919     PerlIO_destruct(aTHX);
920
921     /*
922      * Try to destruct global references.  We do this first so that the
923      * destructors and destructees still exist.  Some sv's might remain.
924      * Non-referenced objects are on their own.
925      */
926     sv_clean_objs();
927
928     /* unhook hooks which will soon be, or use, destroyed data */
929     SvREFCNT_dec(PL_warnhook);
930     PL_warnhook = NULL;
931     SvREFCNT_dec(PL_diehook);
932     PL_diehook = NULL;
933     SvREFCNT_dec(PL_hook__require__before);
934     PL_hook__require__before = NULL;
935     SvREFCNT_dec(PL_hook__require__after);
936     PL_hook__require__after = NULL;
937
938     /* call exit list functions */
939     while (PL_exitlistlen-- > 0)
940         PL_exitlist[PL_exitlistlen].fn(aTHX_ PL_exitlist[PL_exitlistlen].ptr);
941
942     Safefree(PL_exitlist);
943
944     PL_exitlist = NULL;
945     PL_exitlistlen = 0;
946
947     SvREFCNT_dec(PL_registered_mros);
948
949     if (destruct_level == 0) {
950
951         DEBUG_P(debprofdump());
952
953 #if defined(PERLIO_LAYERS)
954         /* No more IO - including error messages ! */
955         PerlIO_cleanup(aTHX);
956 #endif
957
958         CopFILE_free(&PL_compiling);
959
960         /* The exit() function will do everything that needs doing. */
961         return STATUS_EXIT;
962     }
963
964     /* Below, do clean up for when PERL_DESTRUCT_LEVEL is not 0 */
965
966 #ifdef USE_ITHREADS
967     /* the syntax tree is shared between clones
968      * so op_free(PL_main_root) only ReREFCNT_dec's
969      * REGEXPs in the parent interpreter
970      * we need to manually ReREFCNT_dec for the clones
971      */
972     {
973         I32 i = AvFILLp(PL_regex_padav);
974         SV **ary = AvARRAY(PL_regex_padav);
975
976         for (; i; i--) {
977             SvREFCNT_dec(ary[i]);
978             ary[i] = &PL_sv_undef;
979         }
980     }
981 #endif
982
983
984     SvREFCNT_dec(MUTABLE_SV(PL_stashcache));
985     PL_stashcache = NULL;
986
987     /* loosen bonds of global variables */
988
989     /* XXX can PL_parser still be non-null here? */
990     if(PL_parser && PL_parser->rsfp) {
991         (void)PerlIO_close(PL_parser->rsfp);
992         PL_parser->rsfp = NULL;
993     }
994
995     if (PL_minus_F) {
996         Safefree(PL_splitstr);
997         PL_splitstr = NULL;
998     }
999
1000     /* switches */
1001     PL_minus_n      = FALSE;
1002     PL_minus_p      = FALSE;
1003     PL_minus_l      = FALSE;
1004     PL_minus_a      = FALSE;
1005     PL_minus_F      = FALSE;
1006     PL_doswitches   = FALSE;
1007     PL_dowarn       = G_WARN_OFF;
1008 #ifdef PERL_SAWAMPERSAND
1009     PL_sawampersand = 0;        /* must save all match strings */
1010 #endif
1011     PL_unsafe       = FALSE;
1012
1013     Safefree(PL_inplace);
1014     PL_inplace = NULL;
1015     SvREFCNT_dec(PL_patchlevel);
1016
1017     if (PL_e_script) {
1018         SvREFCNT_dec(PL_e_script);
1019         PL_e_script = NULL;
1020     }
1021
1022     PL_perldb = 0;
1023
1024     /* magical thingies */
1025
1026     SvREFCNT_dec(PL_ofsgv);     /* *, */
1027     PL_ofsgv = NULL;
1028
1029     SvREFCNT_dec(PL_ors_sv);    /* $\ */
1030     PL_ors_sv = NULL;
1031
1032     SvREFCNT_dec(PL_rs);        /* $/ */
1033     PL_rs = NULL;
1034
1035     Safefree(PL_osname);        /* $^O */
1036     PL_osname = NULL;
1037
1038     SvREFCNT_dec(PL_statname);
1039     PL_statname = NULL;
1040     PL_statgv = NULL;
1041
1042     /* defgv, aka *_ should be taken care of elsewhere */
1043
1044     /* float buffer */
1045     Safefree(PL_efloatbuf);
1046     PL_efloatbuf = NULL;
1047     PL_efloatsize = 0;
1048
1049     /* startup and shutdown function lists */
1050     SvREFCNT_dec(PL_beginav);
1051     SvREFCNT_dec(PL_beginav_save);
1052     SvREFCNT_dec(PL_endav);
1053     SvREFCNT_dec(PL_checkav);
1054     SvREFCNT_dec(PL_checkav_save);
1055     SvREFCNT_dec(PL_unitcheckav);
1056     SvREFCNT_dec(PL_unitcheckav_save);
1057     SvREFCNT_dec(PL_initav);
1058     PL_beginav = NULL;
1059     PL_beginav_save = NULL;
1060     PL_endav = NULL;
1061     PL_checkav = NULL;
1062     PL_checkav_save = NULL;
1063     PL_unitcheckav = NULL;
1064     PL_unitcheckav_save = NULL;
1065     PL_initav = NULL;
1066
1067     /* shortcuts just get cleared */
1068     PL_hintgv = NULL;
1069     PL_errgv = NULL;
1070     PL_argvoutgv = NULL;
1071     PL_stdingv = NULL;
1072     PL_stderrgv = NULL;
1073     PL_last_in_gv = NULL;
1074     PL_DBsingle = NULL;
1075     PL_DBtrace = NULL;
1076     PL_DBsignal = NULL;
1077     PL_DBsingle_iv = 0;
1078     PL_DBtrace_iv = 0;
1079     PL_DBsignal_iv = 0;
1080     PL_DBcv = NULL;
1081     PL_dbargs = NULL;
1082     PL_debstash = NULL;
1083
1084     SvREFCNT_dec(PL_envgv);
1085     SvREFCNT_dec(PL_incgv);
1086     SvREFCNT_dec(PL_argvgv);
1087     SvREFCNT_dec(PL_replgv);
1088     SvREFCNT_dec(PL_DBgv);
1089     SvREFCNT_dec(PL_DBline);
1090     SvREFCNT_dec(PL_DBsub);
1091     PL_envgv = NULL;
1092     PL_incgv = NULL;
1093     PL_argvgv = NULL;
1094     PL_replgv = NULL;
1095     PL_DBgv = NULL;
1096     PL_DBline = NULL;
1097     PL_DBsub = NULL;
1098
1099     SvREFCNT_dec(PL_argvout_stack);
1100     PL_argvout_stack = NULL;
1101
1102     SvREFCNT_dec(PL_modglobal);
1103     PL_modglobal = NULL;
1104     SvREFCNT_dec(PL_preambleav);
1105     PL_preambleav = NULL;
1106     SvREFCNT_dec(PL_subname);
1107     PL_subname = NULL;
1108 #ifdef PERL_USES_PL_PIDSTATUS
1109     SvREFCNT_dec(PL_pidstatus);
1110     PL_pidstatus = NULL;
1111 #endif
1112     SvREFCNT_dec(PL_toptarget);
1113     PL_toptarget = NULL;
1114     SvREFCNT_dec(PL_bodytarget);
1115     PL_bodytarget = NULL;
1116     PL_formtarget = NULL;
1117
1118     /* free locale stuff */
1119 #ifdef USE_LOCALE_COLLATE
1120     Safefree(PL_collation_name);
1121     PL_collation_name = NULL;
1122 #endif
1123 #if defined(USE_PL_CURLOCALES)
1124     for (i = 0; i < (int) C_ARRAY_LENGTH(PL_curlocales); i++) {
1125         Safefree(PL_curlocales[i]);
1126         PL_curlocales[i] = NULL;
1127     }
1128 #endif
1129 #if defined(USE_POSIX_2008_LOCALE) && defined(USE_THREADS)
1130     {
1131         /* This also makes sure we aren't using a locale object that gets freed
1132          * below */
1133         if (   PL_cur_locale_obj != NULL
1134             && PL_cur_locale_obj != LC_GLOBAL_LOCALE
1135             && PL_cur_locale_obj != PL_C_locale_obj
1136         ) {
1137             locale_t cur_locale = uselocale((locale_t) 0);
1138             if (cur_locale == PL_cur_locale_obj) {
1139                 uselocale(LC_GLOBAL_LOCALE);
1140             }
1141
1142             freelocale(PL_cur_locale_obj);
1143             PL_cur_locale_obj = NULL;
1144         }
1145     }
1146
1147 #  ifdef USE_PL_CUR_LC_ALL
1148
1149     if (PL_cur_LC_ALL) {
1150         DEBUG_L( PerlIO_printf(Perl_debug_log, "PL_cur_LC_ALL=%p\n", PL_cur_LC_ALL));
1151         Safefree(PL_cur_LC_ALL);
1152         PL_cur_LC_ALL = NULL;
1153     }
1154
1155 #  endif
1156
1157     if (PL_scratch_locale_obj) {
1158         freelocale(PL_scratch_locale_obj);
1159         PL_scratch_locale_obj = NULL;
1160     }
1161 #endif
1162 #ifdef USE_LOCALE_NUMERIC
1163     Safefree(PL_numeric_name);
1164     PL_numeric_name = NULL;
1165     SvREFCNT_dec(PL_numeric_radix_sv);
1166     PL_numeric_radix_sv = NULL;
1167     SvREFCNT_dec(PL_underlying_radix_sv);
1168     PL_underlying_radix_sv  = NULL;
1169 #endif
1170 #ifdef USE_LOCALE_CTYPE
1171     Safefree(PL_ctype_name);
1172     PL_ctype_name = NULL;
1173 #endif
1174
1175     if (PL_setlocale_buf) {
1176         Safefree(PL_setlocale_buf);
1177         PL_setlocale_buf = NULL;
1178     }
1179
1180     if (PL_langinfo_buf) {
1181         Safefree(PL_langinfo_buf);
1182         PL_langinfo_buf = NULL;
1183     }
1184
1185 #if defined(USE_LOCALE_THREADS) && ! defined(USE_THREAD_SAFE_LOCALE)
1186     if (PL_less_dicey_locale_buf) {
1187         Safefree(PL_less_dicey_locale_buf);
1188         PL_less_dicey_locale_buf = NULL;
1189     }
1190 #endif
1191
1192 #ifdef USE_LOCALE_CTYPE
1193     SvREFCNT_dec(PL_warn_locale);
1194     PL_warn_locale       = NULL;
1195 #endif
1196
1197     SvREFCNT_dec(PL_AboveLatin1);
1198     PL_AboveLatin1 = NULL;
1199     SvREFCNT_dec(PL_Assigned_invlist);
1200     PL_Assigned_invlist = NULL;
1201     SvREFCNT_dec(PL_GCB_invlist);
1202     PL_GCB_invlist = NULL;
1203     SvREFCNT_dec(PL_HasMultiCharFold);
1204     PL_HasMultiCharFold = NULL;
1205     SvREFCNT_dec(PL_InMultiCharFold);
1206     PL_InMultiCharFold = NULL;
1207     SvREFCNT_dec(PL_Latin1);
1208     PL_Latin1 = NULL;
1209     SvREFCNT_dec(PL_LB_invlist);
1210     PL_LB_invlist = NULL;
1211     SvREFCNT_dec(PL_SB_invlist);
1212     PL_SB_invlist = NULL;
1213     SvREFCNT_dec(PL_SCX_invlist);
1214     PL_SCX_invlist = NULL;
1215     SvREFCNT_dec(PL_UpperLatin1);
1216     PL_UpperLatin1 = NULL;
1217     SvREFCNT_dec(PL_in_some_fold);
1218     PL_in_some_fold = NULL;
1219     SvREFCNT_dec(PL_utf8_foldclosures);
1220     PL_utf8_foldclosures = NULL;
1221     SvREFCNT_dec(PL_utf8_idcont);
1222     PL_utf8_idcont = NULL;
1223     SvREFCNT_dec(PL_utf8_idstart);
1224     PL_utf8_idstart = NULL;
1225     SvREFCNT_dec(PL_utf8_perl_idcont);
1226     PL_utf8_perl_idcont = NULL;
1227     SvREFCNT_dec(PL_utf8_perl_idstart);
1228     PL_utf8_perl_idstart = NULL;
1229     SvREFCNT_dec(PL_utf8_xidcont);
1230     PL_utf8_xidcont = NULL;
1231     SvREFCNT_dec(PL_utf8_xidstart);
1232     PL_utf8_xidstart = NULL;
1233     SvREFCNT_dec(PL_WB_invlist);
1234     PL_WB_invlist = NULL;
1235     SvREFCNT_dec(PL_utf8_toupper);
1236     PL_utf8_toupper = NULL;
1237     SvREFCNT_dec(PL_utf8_totitle);
1238     PL_utf8_totitle = NULL;
1239     SvREFCNT_dec(PL_utf8_tolower);
1240     PL_utf8_tolower = NULL;
1241     SvREFCNT_dec(PL_utf8_tofold);
1242     PL_utf8_tofold = NULL;
1243     SvREFCNT_dec(PL_utf8_tosimplefold);
1244     PL_utf8_tosimplefold = NULL;
1245     SvREFCNT_dec(PL_utf8_charname_begin);
1246     PL_utf8_charname_begin = NULL;
1247     SvREFCNT_dec(PL_utf8_charname_continue);
1248     PL_utf8_charname_continue = NULL;
1249     SvREFCNT_dec(PL_utf8_mark);
1250     PL_utf8_mark = NULL;
1251     SvREFCNT_dec(PL_InBitmap);
1252     PL_InBitmap = NULL;
1253     SvREFCNT_dec(PL_CCC_non0_non230);
1254     PL_CCC_non0_non230 = NULL;
1255     SvREFCNT_dec(PL_Private_Use);
1256     PL_Private_Use = NULL;
1257
1258     for (i = 0; i < POSIX_CC_COUNT; i++) {
1259         SvREFCNT_dec(PL_XPosix_ptrs[i]);
1260         PL_XPosix_ptrs[i] = NULL;
1261
1262         if (i != CC_CASED_) {   /* A copy of Alpha */
1263             SvREFCNT_dec(PL_Posix_ptrs[i]);
1264             PL_Posix_ptrs[i] = NULL;
1265         }
1266     }
1267
1268     free_and_set_cop_warnings(&PL_compiling, NULL);
1269     cophh_free(CopHINTHASH_get(&PL_compiling));
1270     CopHINTHASH_set(&PL_compiling, cophh_new_empty());
1271     CopFILE_free(&PL_compiling);
1272
1273     /* Prepare to destruct main symbol table.  */
1274
1275     hv = PL_defstash;
1276     /* break ref loop  *:: <=> %:: */
1277     (void)hv_deletes(hv, "main::", G_DISCARD);
1278     PL_defstash = 0;
1279     SvREFCNT_dec(hv);
1280     SvREFCNT_dec(PL_curstname);
1281     PL_curstname = NULL;
1282
1283     /* clear queued errors */
1284     SvREFCNT_dec(PL_errors);
1285     PL_errors = NULL;
1286
1287     SvREFCNT_dec(PL_isarev);
1288
1289     FREETMPS;
1290     if (destruct_level >= 2) {
1291         if (PL_scopestack_ix != 0)
1292             Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL),
1293                              "Unbalanced scopes: %ld more ENTERs than LEAVEs\n",
1294                              (long)PL_scopestack_ix);
1295         if (PL_savestack_ix != 0)
1296             Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL),
1297                              "Unbalanced saves: %ld more saves than restores\n",
1298                              (long)PL_savestack_ix);
1299         if (PL_tmps_floor != -1)
1300             Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL),"Unbalanced tmps: %ld more allocs than frees\n",
1301                              (long)PL_tmps_floor + 1);
1302         if (cxstack_ix != -1)
1303             Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL),"Unbalanced context: %ld more PUSHes than POPs\n",
1304                              (long)cxstack_ix + 1);
1305     }
1306
1307 #ifdef USE_ITHREADS
1308     SvREFCNT_dec(PL_regex_padav);
1309     PL_regex_padav = NULL;
1310     PL_regex_pad = NULL;
1311 #endif
1312
1313 #ifdef MULTIPLICITY
1314     /* the entries in this list are allocated via SV PVX's, so get freed
1315      * in sv_clean_all */
1316     Safefree(PL_my_cxt_list);
1317 #endif
1318
1319     /* Now absolutely destruct everything, somehow or other, loops or no. */
1320
1321     /* the 2 is for PL_fdpid and PL_strtab */
1322     while (sv_clean_all() > 2)
1323         ;
1324
1325 #ifdef USE_ITHREADS
1326     Safefree(PL_stashpad); /* must come after sv_clean_all */
1327 #endif
1328
1329     AvREAL_off(PL_fdpid);               /* no surviving entries */
1330     SvREFCNT_dec(PL_fdpid);             /* needed in io_close() */
1331     PL_fdpid = NULL;
1332
1333 #ifdef HAVE_INTERP_INTERN
1334     sys_intern_clear();
1335 #endif
1336
1337     /* constant strings */
1338     for (i = 0; i < SV_CONSTS_COUNT; i++) {
1339         SvREFCNT_dec(PL_sv_consts[i]);
1340         PL_sv_consts[i] = NULL;
1341     }
1342
1343     /* Destruct the global string table. */
1344     {
1345         /* Yell and reset the HeVAL() slots that are still holding refcounts,
1346          * so that sv_free() won't fail on them.
1347          * Now that the global string table is using a single hunk of memory
1348          * for both HE and HEK, we either need to explicitly unshare it the
1349          * correct way, or actually free things here.
1350          */
1351         I32 riter = 0;
1352         const I32 max = HvMAX(PL_strtab);
1353         HE * const * const array = HvARRAY(PL_strtab);
1354         HE *hent = array[0];
1355
1356         for (;;) {
1357             if (hent && ckWARN_d(WARN_INTERNAL)) {
1358                 HE * const next = HeNEXT(hent);
1359                 Perl_warner(aTHX_ packWARN(WARN_INTERNAL),
1360                      "Unbalanced string table refcount: (%ld) for \"%s\"",
1361                      (long)hent->he_valu.hent_refcount, HeKEY(hent));
1362                 Safefree(hent);
1363                 hent = next;
1364             }
1365             if (!hent) {
1366                 if (++riter > max)
1367                     break;
1368                 hent = array[riter];
1369             }
1370         }
1371
1372         Safefree(array);
1373         HvARRAY(PL_strtab) = 0;
1374         HvTOTALKEYS(PL_strtab) = 0;
1375     }
1376     SvREFCNT_dec(PL_strtab);
1377
1378 #ifdef USE_ITHREADS
1379     /* free the pointer tables used for cloning */
1380     ptr_table_free(PL_ptr_table);
1381     PL_ptr_table = (PTR_TBL_t*)NULL;
1382 #endif
1383
1384     /* free special SVs */
1385
1386     SvREFCNT(&PL_sv_yes) = 0;
1387     sv_clear(&PL_sv_yes);
1388     SvANY(&PL_sv_yes) = NULL;
1389     SvFLAGS(&PL_sv_yes) = 0;
1390
1391     SvREFCNT(&PL_sv_no) = 0;
1392     sv_clear(&PL_sv_no);
1393     SvANY(&PL_sv_no) = NULL;
1394     SvFLAGS(&PL_sv_no) = 0;
1395
1396     SvREFCNT(&PL_sv_zero) = 0;
1397     sv_clear(&PL_sv_zero);
1398     SvANY(&PL_sv_zero) = NULL;
1399     SvFLAGS(&PL_sv_zero) = 0;
1400
1401     {
1402         int i;
1403         for (i=0; i<=2; i++) {
1404             SvREFCNT(PERL_DEBUG_PAD(i)) = 0;
1405             sv_clear(PERL_DEBUG_PAD(i));
1406             SvANY(PERL_DEBUG_PAD(i)) = NULL;
1407             SvFLAGS(PERL_DEBUG_PAD(i)) = 0;
1408         }
1409     }
1410
1411     if (PL_sv_count != 0 && ckWARN_d(WARN_INTERNAL))
1412         Perl_warner(aTHX_ packWARN(WARN_INTERNAL),"Scalars leaked: %ld\n", (long)PL_sv_count);
1413
1414 #ifdef DEBUG_LEAKING_SCALARS
1415     if (PL_sv_count != 0) {
1416         SV* sva;
1417         SV* sv;
1418         SV* svend;
1419
1420         for (sva = PL_sv_arenaroot; sva; sva = MUTABLE_SV(SvANY(sva))) {
1421             svend = &sva[SvREFCNT(sva)];
1422             for (sv = sva + 1; sv < svend; ++sv) {
1423                 if (!SvIS_FREED(sv)) {
1424                     PerlIO_printf(Perl_debug_log, "leaked: sv=0x%p"
1425                         " flags=0x%" UVxf
1426                         " refcnt=%" UVuf pTHX__FORMAT "\n"
1427                         "\tallocated at %s:%d %s %s (parent 0x%" UVxf ");"
1428                         "serial %" UVuf "\n",
1429                         (void*)sv, (UV)sv->sv_flags, (UV)sv->sv_refcnt
1430                         pTHX__VALUE,
1431                         sv->sv_debug_file ? sv->sv_debug_file : "(unknown)",
1432                         sv->sv_debug_line,
1433                         sv->sv_debug_inpad ? "for" : "by",
1434                         sv->sv_debug_optype ?
1435                             PL_op_name[sv->sv_debug_optype]: "(none)",
1436                         PTR2UV(sv->sv_debug_parent),
1437                         sv->sv_debug_serial
1438                     );
1439 #ifdef DEBUG_LEAKING_SCALARS_FORK_DUMP
1440                     Perl_dump_sv_child(aTHX_ sv);
1441 #endif
1442                 }
1443             }
1444         }
1445     }
1446 #ifdef DEBUG_LEAKING_SCALARS_FORK_DUMP
1447     {
1448         int status;
1449         fd_set rset;
1450         /* Wait for up to 4 seconds for child to terminate.
1451            This seems to be the least effort way of timing out on reaping
1452            its exit status.  */
1453         struct timeval waitfor = {4, 0};
1454         int sock = PL_dumper_fd;
1455
1456         shutdown(sock, 1);
1457         FD_ZERO(&rset);
1458         FD_SET(sock, &rset);
1459         select(sock + 1, &rset, NULL, NULL, &waitfor);
1460         waitpid(child, &status, WNOHANG);
1461         close(sock);
1462     }
1463 #endif
1464 #endif
1465 #ifdef DEBUG_LEAKING_SCALARS_ABORT
1466     if (PL_sv_count)
1467         abort();
1468 #endif
1469     PL_sv_count = 0;
1470
1471 #if defined(PERLIO_LAYERS)
1472     /* No more IO - including error messages ! */
1473     PerlIO_cleanup(aTHX);
1474 #endif
1475
1476     /* sv_undef needs to stay immortal until after PerlIO_cleanup
1477        as currently layers use it rather than NULL as a marker
1478        for no arg - and will try and SvREFCNT_dec it.
1479      */
1480     SvREFCNT(&PL_sv_undef) = 0;
1481     SvREADONLY_off(&PL_sv_undef);
1482
1483     Safefree(PL_origfilename);
1484     PL_origfilename = NULL;
1485     Safefree(PL_reg_curpm);
1486     free_tied_hv_pool();
1487     Safefree(PL_op_mask);
1488     Safefree(PL_psig_name);
1489     PL_psig_name = (SV**)NULL;
1490     PL_psig_ptr = (SV**)NULL;
1491     {
1492         /* We need to NULL PL_psig_pend first, so that
1493            signal handlers know not to use it */
1494         int *psig_save = PL_psig_pend;
1495         PL_psig_pend = (int*)NULL;
1496         Safefree(psig_save);
1497     }
1498     nuke_stacks();
1499     TAINTING_set(FALSE);
1500     TAINT_WARN_set(FALSE);
1501     PL_hints = 0;               /* Reset hints. Should hints be per-interpreter ? */
1502
1503     DEBUG_P(debprofdump());
1504
1505     PL_debug = 0;
1506
1507 #ifdef USE_REENTRANT_API
1508     Perl_reentrant_free(aTHX);
1509 #endif
1510
1511     /* These all point to HVs that are about to be blown away.
1512        Code in core and on CPAN assumes that if the interpreter is re-started
1513        that they will be cleanly NULL or pointing to a valid HV.  */
1514     PL_custom_op_names = NULL;
1515     PL_custom_op_descs = NULL;
1516     PL_custom_ops = NULL;
1517
1518     sv_free_arenas();
1519
1520     while (PL_regmatch_slab) {
1521         regmatch_slab  *s = PL_regmatch_slab;
1522         PL_regmatch_slab = PL_regmatch_slab->next;
1523         Safefree(s);
1524     }
1525
1526     /* As the absolutely last thing, free the non-arena SV for mess() */
1527
1528     if (PL_mess_sv) {
1529         /* we know that type == SVt_PVMG */
1530
1531         /* it could have accumulated taint magic */
1532         MAGIC* mg;
1533         MAGIC* moremagic;
1534         for (mg = SvMAGIC(PL_mess_sv); mg; mg = moremagic) {
1535             moremagic = mg->mg_moremagic;
1536             if (mg->mg_ptr && mg->mg_type != PERL_MAGIC_regex_global
1537                 && mg->mg_len >= 0)
1538                 Safefree(mg->mg_ptr);
1539             Safefree(mg);
1540         }
1541
1542         /* we know that type >= SVt_PV */
1543         SvPV_free(PL_mess_sv);
1544         Safefree(SvANY(PL_mess_sv));
1545         Safefree(PL_mess_sv);
1546         PL_mess_sv = NULL;
1547     }
1548     return STATUS_EXIT;
1549 }
1550
1551 /*
1552 =for apidoc perl_free
1553
1554 Releases a Perl interpreter.  See L<perlembed>.
1555
1556 =cut
1557 */
1558
1559 void
1560 perl_free(pTHXx)
1561 {
1562
1563     PERL_ARGS_ASSERT_PERL_FREE;
1564
1565     if (PL_veto_cleanup)
1566         return;
1567
1568 #ifdef PERL_TRACK_MEMPOOL
1569     {
1570         /*
1571          * Don't free thread memory if PERL_DESTRUCT_LEVEL is set to a non-zero
1572          * value as we're probably hunting memory leaks then
1573          */
1574         if (PL_perl_destruct_level == 0) {
1575             const U32 old_debug = PL_debug;
1576             /* Emulate the PerlHost behaviour of free()ing all memory allocated in this
1577                thread at thread exit.  */
1578             if (DEBUG_m_TEST) {
1579                 PerlIO_puts(Perl_debug_log, "Disabling memory debugging as we "
1580                             "free this thread's memory\n");
1581                 PL_debug &= ~ DEBUG_m_FLAG;
1582             }
1583             while(aTHXx->Imemory_debug_header.next != &(aTHXx->Imemory_debug_header)){
1584                 char * next = (char *)(aTHXx->Imemory_debug_header.next);
1585                 Malloc_t ptr = PERL_MEMORY_DEBUG_HEADER_SIZE + next;
1586                 safesysfree(ptr);
1587             }
1588             PL_debug = old_debug;
1589         }
1590     }
1591 #endif
1592
1593 #if defined(WIN32)
1594 #  if defined(PERL_IMPLICIT_SYS)
1595     {
1596         void *host = w32_internal_host;
1597         PerlMem_free(aTHXx);
1598         win32_delete_internal_host(host);
1599     }
1600 #  else
1601     PerlMem_free(aTHXx);
1602 #  endif
1603 #else
1604     PerlMem_free(aTHXx);
1605 #endif
1606 }
1607
1608 #if defined(USE_ITHREADS)
1609 /* provide destructors to clean up the thread key when libperl is unloaded */
1610 #ifndef WIN32 /* handled during DLL_PROCESS_DETACH in win32/perllib.c */
1611
1612 #if defined(__hpux) && !(defined(__ux_version) && __ux_version <= 1020) && !defined(__GNUC__)
1613 #pragma fini "perl_fini"
1614 #elif defined(__sun) && !defined(__GNUC__)
1615 #pragma fini (perl_fini)
1616 #endif
1617
1618 static void
1619 #if defined(__GNUC__)
1620 __attribute__((destructor))
1621 #endif
1622 perl_fini(void)
1623 {
1624     if (
1625         PL_curinterp && !PL_veto_cleanup)
1626         FREE_THREAD_KEY;
1627 }
1628
1629 #endif /* WIN32 */
1630 #endif /* THREADS */
1631
1632 /*
1633 =for apidoc call_atexit
1634
1635 Add a function C<fn> to the list of functions to be called at global
1636 destruction.  C<ptr> will be passed as an argument to C<fn>; it can point to a
1637 C<struct> so that you can pass anything you want.
1638
1639 Note that under threads, C<fn> may run multiple times.  This is because the
1640 list is executed each time the current or any descendent thread terminates.
1641
1642 =cut
1643 */
1644
1645 void
1646 Perl_call_atexit(pTHX_ ATEXIT_t fn, void *ptr)
1647 {
1648     Renew(PL_exitlist, PL_exitlistlen+1, PerlExitListEntry);
1649     PL_exitlist[PL_exitlistlen].fn = fn;
1650     PL_exitlist[PL_exitlistlen].ptr = ptr;
1651     ++PL_exitlistlen;
1652 }
1653
1654 #ifdef USE_ENVIRON_ARRAY
1655 static void
1656 dup_environ(pTHX)
1657 {
1658 #  ifdef USE_ITHREADS
1659     if (aTHX != PL_curinterp)
1660         return;
1661 #  endif
1662     if (!environ)
1663         return;
1664
1665     size_t n_entries = 0, vars_size = 0;
1666
1667     for (char **ep = environ; *ep; ++ep) {
1668         ++n_entries;
1669         vars_size += strlen(*ep) + 1;
1670     }
1671
1672     /* To save memory, we store both the environ array and its values in a
1673      * single memory block. */
1674     char **new_environ = (char**)PerlMemShared_malloc(
1675         (sizeof(char*) * (n_entries + 1)) + vars_size
1676     );
1677     char *vars = (char*)(new_environ + n_entries + 1);
1678
1679     for (size_t i = 0, copied = 0; n_entries > i; ++i) {
1680         size_t len = strlen(environ[i]) + 1;
1681         new_environ[i] = (char *) CopyD(environ[i], vars + copied, len, char);
1682         copied += len;
1683     }
1684     new_environ[n_entries] = NULL;
1685
1686     environ = new_environ;
1687     /* Store a pointer in a global variable to ensure it's always reachable so
1688      * LeakSanitizer/Valgrind won't complain about it. We can't ever free it.
1689      * Even if libc allocates a new environ, it's possible that some of its
1690      * values will still be pointing to the old environ.
1691      */
1692     PL_my_environ = new_environ;
1693 }
1694 #endif
1695
1696 /*
1697 =for apidoc perl_parse
1698
1699 Tells a Perl interpreter to parse a Perl script.  This performs most
1700 of the initialisation of a Perl interpreter.  See L<perlembed> for
1701 a tutorial.
1702
1703 C<my_perl> points to the Perl interpreter that is to parse the script.
1704 It must have been previously created through the use of L</perl_alloc>
1705 and L</perl_construct>.  C<xsinit> points to a callback function that
1706 will be called to set up the ability for this Perl interpreter to load
1707 XS extensions, or may be null to perform no such setup.
1708
1709 C<argc> and C<argv> supply a set of command-line arguments to the Perl
1710 interpreter, as would normally be passed to the C<main> function of
1711 a C program.  C<argv[argc]> must be null.  These arguments are where
1712 the script to parse is specified, either by naming a script file or by
1713 providing a script in a C<-e> option.
1714 If L<C<$0>|perlvar/$0> will be written to in the Perl interpreter, then
1715 the argument strings must be in writable memory, and so mustn't just be
1716 string constants.
1717
1718 C<env> specifies a set of environment variables that will be used by
1719 this Perl interpreter.  If non-null, it must point to a null-terminated
1720 array of environment strings.  If null, the Perl interpreter will use
1721 the environment supplied by the C<environ> global variable.
1722
1723 This function initialises the interpreter, and parses and compiles the
1724 script specified by the command-line arguments.  This includes executing
1725 code in C<BEGIN>, C<UNITCHECK>, and C<CHECK> blocks.  It does not execute
1726 C<INIT> blocks or the main program.
1727
1728 Returns an integer of slightly tricky interpretation.  The correct
1729 use of the return value is as a truth value indicating whether there
1730 was a failure in initialisation.  If zero is returned, this indicates
1731 that initialisation was successful, and it is safe to proceed to call
1732 L</perl_run> and make other use of it.  If a non-zero value is returned,
1733 this indicates some problem that means the interpreter wants to terminate.
1734 The interpreter should not be just abandoned upon such failure; the caller
1735 should proceed to shut the interpreter down cleanly with L</perl_destruct>
1736 and free it with L</perl_free>.
1737
1738 For historical reasons, the non-zero return value also attempts to
1739 be a suitable value to pass to the C library function C<exit> (or to
1740 return from C<main>), to serve as an exit code indicating the nature
1741 of the way initialisation terminated.  However, this isn't portable,
1742 due to differing exit code conventions.  An attempt is made to return
1743 an exit code of the type required by the host operating system, but
1744 because it is constrained to be non-zero, it is not necessarily possible
1745 to indicate every type of exit.  It is only reliable on Unix, where a
1746 zero exit code can be augmented with a set bit that will be ignored.
1747 In any case, this function is not the correct place to acquire an exit
1748 code: one should get that from L</perl_destruct>.
1749
1750 =cut
1751 */
1752
1753 #define SET_CURSTASH(newstash)                       \
1754         if (PL_curstash != newstash) {                \
1755             SvREFCNT_dec(PL_curstash);                 \
1756             PL_curstash = (HV *)SvREFCNT_inc(newstash); \
1757         }
1758
1759 int
1760 perl_parse(pTHXx_ XSINIT_t xsinit, int argc, char **argv, char **env)
1761 {
1762     I32 oldscope;
1763     int ret;
1764     dJMPENV;
1765
1766     PERL_ARGS_ASSERT_PERL_PARSE;
1767 #ifndef MULTIPLICITY
1768     PERL_UNUSED_ARG(my_perl);
1769 #endif
1770     debug_hash_seed(false);
1771 #ifdef __amigaos4__
1772     {
1773         struct NameTranslationInfo nti;
1774         __translate_amiga_to_unix_path_name(&argv[0],&nti);
1775     }
1776 #endif
1777
1778     {
1779         int i;
1780         assert(argc >= 0);
1781         for(i = 0; i != argc; i++)
1782             assert(argv[i]);
1783         assert(!argv[argc]);
1784     }
1785     PL_origargc = argc;
1786     PL_origargv = argv;
1787
1788     if (PL_origalen != 0) {
1789         PL_origalen = 1; /* don't use old PL_origalen if perl_parse() is called again */
1790     }
1791     else {
1792         /* Set PL_origalen be the sum of the contiguous argv[]
1793          * elements plus the size of the env in case that it is
1794          * contiguous with the argv[].  This is used in mg.c:Perl_magic_set()
1795          * as the maximum modifiable length of $0.  In the worst case
1796          * the area we are able to modify is limited to the size of
1797          * the original argv[0].  (See below for 'contiguous', though.)
1798          * --jhi */
1799          const char *s = NULL;
1800          const UV mask = ~(UV)(PTRSIZE-1);
1801          /* Do the mask check only if the args seem like aligned. */
1802          const UV aligned =
1803            (mask < ~(UV)0) && ((PTR2UV(argv[0]) & mask) == PTR2UV(argv[0]));
1804
1805          /* See if all the arguments are contiguous in memory.  Note
1806           * that 'contiguous' is a loose term because some platforms
1807           * align the argv[] and the envp[].  If the arguments look
1808           * like non-aligned, assume that they are 'strictly' or
1809           * 'traditionally' contiguous.  If the arguments look like
1810           * aligned, we just check that they are within aligned
1811           * PTRSIZE bytes.  As long as no system has something bizarre
1812           * like the argv[] interleaved with some other data, we are
1813           * fine.  (Did I just evoke Murphy's Law?)  --jhi */
1814          if (PL_origargv && PL_origargc >= 1 && (s = PL_origargv[0])) {
1815               int i;
1816               while (*s) s++;
1817               for (i = 1; i < PL_origargc; i++) {
1818                    if ((PL_origargv[i] == s + 1
1819 #ifdef OS2
1820                         || PL_origargv[i] == s + 2
1821 #endif
1822                             )
1823                        ||
1824                        (aligned &&
1825                         (PL_origargv[i] >  s &&
1826                          PL_origargv[i] <=
1827                          INT2PTR(char *, PTR2UV(s + PTRSIZE) & mask)))
1828                         )
1829                    {
1830                         s = PL_origargv[i];
1831                         while (*s) s++;
1832                    }
1833                    else
1834                         break;
1835               }
1836          }
1837
1838 #ifdef USE_ENVIRON_ARRAY
1839          /* Can we grab env area too to be used as the area for $0? */
1840          if (s && PL_origenviron) {
1841               if ((PL_origenviron[0] == s + 1)
1842                   ||
1843                   (aligned &&
1844                    (PL_origenviron[0] >  s &&
1845                     PL_origenviron[0] <=
1846                     INT2PTR(char *, PTR2UV(s + PTRSIZE) & mask)))
1847                  )
1848               {
1849                    int i;
1850 #ifndef OS2             /* ENVIRON is read by the kernel too. */
1851                    s = PL_origenviron[0];
1852                    while (*s) s++;
1853 #endif
1854
1855                    /* Force copy of environment. */
1856                    if (PL_origenviron == environ)
1857                        dup_environ(aTHX);
1858
1859                    for (i = 1; PL_origenviron[i]; i++) {
1860                         if (PL_origenviron[i] == s + 1
1861                             ||
1862                             (aligned &&
1863                              (PL_origenviron[i] >  s &&
1864                               PL_origenviron[i] <=
1865                               INT2PTR(char *, PTR2UV(s + PTRSIZE) & mask)))
1866                            )
1867                         {
1868                              s = PL_origenviron[i];
1869                              while (*s) s++;
1870                         }
1871                         else
1872                              break;
1873                    }
1874               }
1875          }
1876 #endif /* USE_ENVIRON_ARRAY */
1877
1878          PL_origalen = s ? s - PL_origargv[0] + 1 : 0;
1879     }
1880
1881     if (PL_do_undump) {
1882
1883         /* Come here if running an undumped a.out. */
1884
1885         PL_origfilename = savepv(argv[0]);
1886         PL_do_undump = FALSE;
1887         cxstack_ix = -1;                /* start label stack again */
1888         init_ids();
1889         assert (!TAINT_get);
1890         TAINT;
1891         set_caret_X();
1892         TAINT_NOT;
1893         init_postdump_symbols(argc,argv,env);
1894         return 0;
1895     }
1896
1897     op_free(PL_main_root);
1898     PL_main_root = NULL;
1899
1900     PL_main_start = NULL;
1901     SvREFCNT_dec(PL_main_cv);
1902     PL_main_cv = NULL;
1903
1904     time(&PL_basetime);
1905     oldscope = PL_scopestack_ix;
1906     PL_dowarn = G_WARN_OFF;
1907
1908     JMPENV_PUSH(ret);
1909     switch (ret) {
1910     case 0:
1911         parse_body(env,xsinit);
1912         if (PL_unitcheckav) {
1913             call_list(oldscope, PL_unitcheckav);
1914         }
1915         if (PL_checkav) {
1916             PERL_SET_PHASE(PERL_PHASE_CHECK);
1917             call_list(oldscope, PL_checkav);
1918         }
1919         ret = 0;
1920         break;
1921     case 1:
1922         STATUS_ALL_FAILURE;
1923         /* FALLTHROUGH */
1924     case 2:
1925         /* my_exit() was called */
1926         while (PL_scopestack_ix > oldscope)
1927             LEAVE;
1928         FREETMPS;
1929         SET_CURSTASH(PL_defstash);
1930         if (PL_unitcheckav) {
1931             call_list(oldscope, PL_unitcheckav);
1932         }
1933         if (PL_checkav) {
1934             PERL_SET_PHASE(PERL_PHASE_CHECK);
1935             call_list(oldscope, PL_checkav);
1936         }
1937         ret = STATUS_EXIT;
1938         if (ret == 0) {
1939             /*
1940              * We do this here to avoid [perl #2754].
1941              * Note this may cause trouble with Module::Install.
1942              * See: [perl #132577].
1943              */
1944             ret = 0x100;
1945         }
1946         break;
1947     case 3:
1948         PerlIO_printf(Perl_error_log, "panic: top_env\n");
1949         ret = 1;
1950         break;
1951     }
1952     JMPENV_POP;
1953     return ret;
1954 }
1955
1956 /* This needs to stay in perl.c, as perl.c is compiled with different flags for
1957    miniperl, and we need to see those flags reflected in the values here.  */
1958
1959 /* What this returns is subject to change.  Use the public interface in Config.
1960  */
1961
1962 static void
1963 S_Internals_V(pTHX_ CV *cv)
1964 {
1965     dXSARGS;
1966 #ifdef LOCAL_PATCH_COUNT
1967     const int local_patch_count = LOCAL_PATCH_COUNT;
1968 #else
1969     const int local_patch_count = 0;
1970 #endif
1971     const int entries = 3 + local_patch_count;
1972     int i;
1973     /* NOTE - This list must remain sorted. Do not put any settings here
1974      * which affect binary compatibility */
1975     static const char non_bincompat_options[] =
1976 #  ifdef DEBUGGING
1977                              " DEBUGGING"
1978 #  endif
1979 #  ifdef HAS_LONG_DOUBLE
1980                              " HAS_LONG_DOUBLE"
1981 #  endif
1982 #  ifdef HAS_STRTOLD
1983                              " HAS_STRTOLD"
1984 #  endif
1985 #  ifdef NO_MATHOMS
1986                              " NO_MATHOMS"
1987 #  endif
1988 #  ifdef NO_PERL_INTERNAL_RAND_SEED
1989                              " NO_PERL_INTERNAL_RAND_SEED"
1990 #  endif
1991 #  ifdef NO_PERL_RAND_SEED
1992                              " NO_PERL_RAND_SEED"
1993 #  endif
1994 #  ifdef NO_TAINT_SUPPORT
1995                              " NO_TAINT_SUPPORT"
1996 #  endif
1997 #  ifdef PERL_COPY_ON_WRITE
1998                              " PERL_COPY_ON_WRITE"
1999 #  endif
2000 #  ifdef PERL_DISABLE_PMC
2001                              " PERL_DISABLE_PMC"
2002 #  endif
2003 #  ifdef PERL_DONT_CREATE_GVSV
2004                              " PERL_DONT_CREATE_GVSV"
2005 #  endif
2006 #  ifdef PERL_EXTERNAL_GLOB
2007                              " PERL_EXTERNAL_GLOB"
2008 #  endif
2009 #  ifdef PERL_IS_MINIPERL
2010                              " PERL_IS_MINIPERL"
2011 #  endif
2012 #  ifdef PERL_MALLOC_WRAP
2013                              " PERL_MALLOC_WRAP"
2014 #  endif
2015 #  ifdef PERL_MEM_LOG
2016                              " PERL_MEM_LOG"
2017 #  endif
2018 #  ifdef PERL_MEM_LOG_NOIMPL
2019                              " PERL_MEM_LOG_NOIMPL"
2020 #  endif
2021 #  ifdef PERL_OP_PARENT
2022                              " PERL_OP_PARENT"
2023 #  endif
2024 #  ifdef PERL_PERTURB_KEYS_DETERMINISTIC
2025                              " PERL_PERTURB_KEYS_DETERMINISTIC"
2026 #  endif
2027 #  ifdef PERL_PERTURB_KEYS_DISABLED
2028                              " PERL_PERTURB_KEYS_DISABLED"
2029 #  endif
2030 #  ifdef PERL_PERTURB_KEYS_RANDOM
2031                              " PERL_PERTURB_KEYS_RANDOM"
2032 #  endif
2033 #  ifdef PERL_PRESERVE_IVUV
2034                              " PERL_PRESERVE_IVUV"
2035 #  endif
2036 #  ifdef PERL_RC_STACK
2037                              " PERL_RC_STACK"
2038 #  endif
2039 #  ifdef PERL_RELOCATABLE_INCPUSH
2040                              " PERL_RELOCATABLE_INCPUSH"
2041 #  endif
2042 #  ifdef PERL_USE_DEVEL
2043                              " PERL_USE_DEVEL"
2044 #  endif
2045 #  ifdef PERL_USE_SAFE_PUTENV
2046                              " PERL_USE_SAFE_PUTENV"
2047 #  endif
2048
2049 #  ifdef PERL_USE_UNSHARED_KEYS_IN_LARGE_HASHES
2050                              " PERL_USE_UNSHARED_KEYS_IN_LARGE_HASHES"
2051 #  endif
2052 #  ifdef SILENT_NO_TAINT_SUPPORT
2053                              " SILENT_NO_TAINT_SUPPORT"
2054 #  endif
2055 #  ifdef UNLINK_ALL_VERSIONS
2056                              " UNLINK_ALL_VERSIONS"
2057 #  endif
2058 #  ifdef USE_ATTRIBUTES_FOR_PERLIO
2059                              " USE_ATTRIBUTES_FOR_PERLIO"
2060 #  endif
2061 #  ifdef USE_FAST_STDIO
2062                              " USE_FAST_STDIO"
2063 #  endif
2064 #  ifdef USE_LOCALE
2065                              " USE_LOCALE"
2066 #  endif
2067 #  ifdef USE_LOCALE_CTYPE
2068                              " USE_LOCALE_CTYPE"
2069 #  endif
2070 #  ifdef WIN32_NO_REGISTRY
2071                              " USE_NO_REGISTRY"
2072 #  endif
2073 #  ifdef USE_PERL_ATOF
2074                              " USE_PERL_ATOF"
2075 #  endif
2076 #  ifdef USE_SITECUSTOMIZE
2077                              " USE_SITECUSTOMIZE"
2078 #  endif
2079 #  ifdef USE_THREAD_SAFE_LOCALE
2080                              " USE_THREAD_SAFE_LOCALE"
2081 #  endif
2082     ""; /* keep this on a line by itself, WITH the empty string */
2083
2084     PERL_UNUSED_ARG(cv);
2085     PERL_UNUSED_VAR(items);
2086
2087     EXTEND(SP, entries);
2088
2089     PUSHs(newSVpvn_flags(PL_bincompat_options, strlen(PL_bincompat_options),
2090                               SVs_TEMP));
2091     PUSHs(Perl_newSVpvn_flags(aTHX_ non_bincompat_options,
2092                               sizeof(non_bincompat_options) - 1, SVs_TEMP));
2093
2094 #ifndef PERL_BUILD_DATE
2095 #  ifdef __DATE__
2096 #    ifdef __TIME__
2097 #      define PERL_BUILD_DATE __DATE__ " " __TIME__
2098 #    else
2099 #      define PERL_BUILD_DATE __DATE__
2100 #    endif
2101 #  endif
2102 #endif
2103
2104 #ifdef PERL_BUILD_DATE
2105     PUSHs(Perl_newSVpvn_flags(aTHX_
2106                               STR_WITH_LEN("Compiled at " PERL_BUILD_DATE),
2107                               SVs_TEMP));
2108 #else
2109     PUSHs(&PL_sv_undef);
2110 #endif
2111
2112     for (i = 1; i <= local_patch_count; i++) {
2113         /* This will be an undef, if PL_localpatches[i] is NULL.  */
2114         PUSHs(newSVpvn_flags(PL_localpatches[i],
2115             PL_localpatches[i] == NULL ? 0 : strlen(PL_localpatches[i]),
2116             SVs_TEMP));
2117     }
2118
2119     XSRETURN(entries);
2120 }
2121
2122 #define INCPUSH_UNSHIFT                 0x01
2123 #define INCPUSH_ADD_OLD_VERS            0x02
2124 #define INCPUSH_ADD_VERSIONED_SUB_DIRS  0x04
2125 #define INCPUSH_ADD_ARCHONLY_SUB_DIRS   0x08
2126 #define INCPUSH_NOT_BASEDIR             0x10
2127 #define INCPUSH_CAN_RELOCATE            0x20
2128 #define INCPUSH_ADD_SUB_DIRS    \
2129     (INCPUSH_ADD_VERSIONED_SUB_DIRS|INCPUSH_ADD_ARCHONLY_SUB_DIRS)
2130
2131 STATIC void *
2132 S_parse_body(pTHX_ char **env, XSINIT_t xsinit)
2133 {
2134     PerlIO *rsfp;
2135     int argc = PL_origargc;
2136     char **argv = PL_origargv;
2137     const char *scriptname = NULL;
2138     bool dosearch = FALSE;
2139     char c;
2140     bool doextract = FALSE;
2141     const char *cddir = NULL;
2142     bool minus_e = FALSE; /* both -e and -E */
2143 #ifdef USE_SITECUSTOMIZE
2144     bool minus_f = FALSE;
2145 #endif
2146     SV *linestr_sv = NULL;
2147     bool add_read_e_script = FALSE;
2148     U32 lex_start_flags = 0;
2149
2150     PERL_SET_PHASE(PERL_PHASE_START);
2151
2152     init_main_stash();
2153
2154     {
2155         const char *s;
2156     for (argc--,argv++; argc > 0; argc--,argv++) {
2157         if (argv[0][0] != '-' || !argv[0][1])
2158             break;
2159         s = argv[0]+1;
2160       reswitch:
2161         switch ((c = *s)) {
2162         case 'C':
2163 #ifndef PERL_STRICT_CR
2164         case '\r':
2165 #endif
2166         case ' ':
2167         case '0':
2168         case 'F':
2169         case 'a':
2170         case 'c':
2171         case 'd':
2172         case 'D':
2173         case 'g':
2174         case '?':
2175         case 'h':
2176         case 'i':
2177         case 'l':
2178         case 'M':
2179         case 'm':
2180         case 'n':
2181         case 'p':
2182         case 's':
2183         case 'u':
2184         case 'U':
2185         case 'v':
2186         case 'W':
2187         case 'X':
2188         case 'w':
2189             if ((s = moreswitches(s)))
2190                 goto reswitch;
2191             break;
2192
2193         case 't':
2194 #if defined(SILENT_NO_TAINT_SUPPORT)
2195             /* silently ignore */
2196 #elif defined(NO_TAINT_SUPPORT)
2197             Perl_croak_nocontext("This perl was compiled without taint support. "
2198                        "Cowardly refusing to run with -t or -T flags");
2199 #else
2200             CHECK_MALLOC_TOO_LATE_FOR('t');
2201             if( !TAINTING_get ) {
2202                  TAINT_WARN_set(TRUE);
2203                  TAINTING_set(TRUE);
2204             }
2205 #endif
2206             s++;
2207             goto reswitch;
2208         case 'T':
2209 #if defined(SILENT_NO_TAINT_SUPPORT)
2210             /* silently ignore */
2211 #elif defined(NO_TAINT_SUPPORT)
2212             Perl_croak_nocontext("This perl was compiled without taint support. "
2213                        "Cowardly refusing to run with -t or -T flags");
2214 #else
2215             CHECK_MALLOC_TOO_LATE_FOR('T');
2216             TAINTING_set(TRUE);
2217             TAINT_WARN_set(FALSE);
2218 #endif
2219             s++;
2220             goto reswitch;
2221
2222         case 'E':
2223             PL_minus_E = TRUE;
2224             /* FALLTHROUGH */
2225         case 'e':
2226             forbid_setid('e', FALSE);
2227         minus_e = TRUE;
2228             if (!PL_e_script) {
2229                 PL_e_script = newSVpvs("");
2230                 add_read_e_script = TRUE;
2231             }
2232             if (*++s)
2233                 sv_catpv(PL_e_script, s);
2234             else if (argv[1]) {
2235                 sv_catpv(PL_e_script, argv[1]);
2236                 argc--,argv++;
2237             }
2238             else
2239                 Perl_croak(aTHX_ "No code specified for -%c", c);
2240             sv_catpvs(PL_e_script, "\n");
2241             break;
2242
2243         case 'f':
2244 #ifdef USE_SITECUSTOMIZE
2245             minus_f = TRUE;
2246 #endif
2247             s++;
2248             goto reswitch;
2249
2250         case 'I':       /* -I handled both here and in moreswitches() */
2251             forbid_setid('I', FALSE);
2252             if (!*++s && (s=argv[1]) != NULL) {
2253                 argc--,argv++;
2254             }
2255             if (s && *s) {
2256                 STRLEN len = strlen(s);
2257                 incpush(s, len, INCPUSH_ADD_SUB_DIRS|INCPUSH_ADD_OLD_VERS);
2258             }
2259             else
2260                 Perl_croak(aTHX_ "No directory specified for -I");
2261             break;
2262         case 'S':
2263             forbid_setid('S', FALSE);
2264             dosearch = TRUE;
2265             s++;
2266             goto reswitch;
2267         case 'V':
2268             {
2269                 SV *opts_prog;
2270
2271                 if (*++s != ':')  {
2272                     opts_prog = newSVpvs("use Config; Config::_V()");
2273                 }
2274                 else {
2275                     ++s;
2276                     opts_prog = Perl_newSVpvf(aTHX_
2277                                               "use Config; Config::config_vars(qw%c%s%c)",
2278                                               0, s, 0);
2279                     s += strlen(s);
2280                 }
2281                 Perl_av_create_and_push(aTHX_ &PL_preambleav, opts_prog);
2282                 /* don't look for script or read stdin */
2283                 scriptname = BIT_BUCKET;
2284                 goto reswitch;
2285             }
2286         case 'x':
2287             doextract = TRUE;
2288             s++;
2289             if (*s)
2290                 cddir = s;
2291             break;
2292         case 0:
2293             break;
2294         case '-':
2295             if (!*++s || isSPACE(*s)) {
2296                 argc--,argv++;
2297                 goto switch_end;
2298             }
2299             /* catch use of gnu style long options.
2300                Both of these exit immediately.  */
2301             if (strEQ(s, "version"))
2302                 minus_v();
2303             if (strEQ(s, "help"))
2304                 usage();
2305             s--;
2306             /* FALLTHROUGH */
2307         default:
2308             Perl_croak(aTHX_ "Unrecognized switch: -%s  (-h will show valid options)",s);
2309         }
2310     }
2311     }
2312
2313   switch_end:
2314
2315     {
2316         char *s;
2317
2318     if (
2319 #ifndef SECURE_INTERNAL_GETENV
2320         !TAINTING_get &&
2321 #endif
2322         (s = PerlEnv_getenv("PERL5OPT")))
2323     {
2324         while (isSPACE(*s))
2325             s++;
2326         if (*s == '-' && *(s+1) == 'T') {
2327 #if defined(SILENT_NO_TAINT_SUPPORT)
2328             /* silently ignore */
2329 #elif defined(NO_TAINT_SUPPORT)
2330             Perl_croak_nocontext("This perl was compiled without taint support. "
2331                        "Cowardly refusing to run with -t or -T flags");
2332 #else
2333             CHECK_MALLOC_TOO_LATE_FOR('T');
2334             TAINTING_set(TRUE);
2335             TAINT_WARN_set(FALSE);
2336 #endif
2337         }
2338         else {
2339             char *popt_copy = NULL;
2340             while (s && *s) {
2341                 const char *d;
2342                 while (isSPACE(*s))
2343                     s++;
2344                 if (*s == '-') {
2345                     s++;
2346                     if (isSPACE(*s))
2347                         continue;
2348                 }
2349                 d = s;
2350                 if (!*s)
2351                     break;
2352                 if (!memCHRs("CDIMUdmtwW", *s))
2353                     Perl_croak(aTHX_ "Illegal switch in PERL5OPT: -%c", *s);
2354                 while (++s && *s) {
2355                     if (isSPACE(*s)) {
2356                         if (!popt_copy) {
2357                             popt_copy = SvPVX(newSVpvn_flags(d, strlen(d), SVs_TEMP));
2358                             s = popt_copy + (s - d);
2359                             d = popt_copy;
2360                         }
2361                         *s++ = '\0';
2362                         break;
2363                     }
2364                 }
2365                 if (*d == 't') {
2366 #if defined(SILENT_NO_TAINT_SUPPORT)
2367             /* silently ignore */
2368 #elif defined(NO_TAINT_SUPPORT)
2369                     Perl_croak_nocontext("This perl was compiled without taint support. "
2370                                "Cowardly refusing to run with -t or -T flags");
2371 #else
2372                     if( !TAINTING_get) {
2373                         TAINT_WARN_set(TRUE);
2374                         TAINTING_set(TRUE);
2375                     }
2376 #endif
2377                 } else {
2378                     moreswitches(d);
2379                 }
2380             }
2381         }
2382     }
2383     }
2384
2385 #ifndef NO_PERL_INTERNAL_RAND_SEED
2386     /* If we're not set[ug]id, we might have honored
2387        PERL_INTERNAL_RAND_SEED in perl_construct().
2388        At this point command-line options have been parsed, so if
2389        we're now tainting and not set[ug]id re-seed.
2390        This could possibly be wasteful if PERL_INTERNAL_RAND_SEED is invalid,
2391        but avoids duplicating the logic from perl_construct().
2392     */
2393     if (TAINT_get &&
2394         PerlProc_getuid() == PerlProc_geteuid() &&
2395         PerlProc_getgid() == PerlProc_getegid()) {
2396         Perl_drand48_init_r(&PL_internal_random_state, seed());
2397     }
2398 #endif
2399     if (DEBUG_h_TEST)
2400         debug_hash_seed(true);
2401
2402     /* Set $^X early so that it can be used for relocatable paths in @INC  */
2403     /* and for SITELIB_EXP in USE_SITECUSTOMIZE                            */
2404     assert (!TAINT_get);
2405     TAINT;
2406     set_caret_X();
2407     TAINT_NOT;
2408
2409 #if defined(USE_SITECUSTOMIZE)
2410     if (!minus_f) {
2411         /* The games with local $! are to avoid setting errno if there is no
2412            sitecustomize script.  "q%c...%c", 0, ..., 0 becomes "q\0...\0",
2413            ie a q() operator with a NUL byte as a the delimiter. This avoids
2414            problems with pathnames containing (say) '  */
2415 #  ifdef PERL_IS_MINIPERL
2416         AV *const inc = GvAV(PL_incgv);
2417         SV **const inc0 = inc ? av_fetch(inc, 0, FALSE) : NULL;
2418
2419         if (inc0) {
2420             /* if lib/buildcustomize.pl exists, it should not fail. If it does,
2421                it should be reported immediately as a build failure.  */
2422             (void)Perl_av_create_and_unshift_one(aTHX_ &PL_preambleav,
2423                                                  Perl_newSVpvf(aTHX_
2424                 "BEGIN { my $f = q%c%s%" SVf "/buildcustomize.pl%c; "
2425                         "do {local $!; -f $f }"
2426                         " and do $f || die $@ || qq '$f: $!' }",
2427                                 0, (TAINTING_get ? "./" : ""), SVfARG(*inc0), 0));
2428         }
2429 #  else
2430         /* SITELIB_EXP is a function call on Win32.  */
2431         const char *const raw_sitelib = SITELIB_EXP;
2432         if (raw_sitelib) {
2433             /* process .../.. if PERL_RELOCATABLE_INC is defined */
2434             SV *sitelib_sv = mayberelocate(raw_sitelib, strlen(raw_sitelib),
2435                                            INCPUSH_CAN_RELOCATE);
2436             const char *const sitelib = SvPVX(sitelib_sv);
2437             (void)Perl_av_create_and_unshift_one(aTHX_ &PL_preambleav,
2438                                                  Perl_newSVpvf(aTHX_
2439                                                                "BEGIN { do {local $!; -f q%c%s/sitecustomize.pl%c} && do q%c%s/sitecustomize.pl%c }",
2440                                                                0, sitelib, 0,
2441                                                                0, sitelib, 0));
2442             assert (SvREFCNT(sitelib_sv) == 1);
2443             SvREFCNT_dec(sitelib_sv);
2444         }
2445 #  endif
2446     }
2447 #endif
2448
2449     if (!scriptname)
2450         scriptname = argv[0];
2451     if (PL_e_script) {
2452         argc++,argv--;
2453         scriptname = BIT_BUCKET;        /* don't look for script or read stdin */
2454     }
2455     else if (scriptname == NULL) {
2456         scriptname = "-";
2457     }
2458
2459     assert (!TAINT_get);
2460     init_perllib();
2461
2462     {
2463         bool suidscript = FALSE;
2464
2465         rsfp = open_script(scriptname, dosearch, &suidscript);
2466         if (!rsfp) {
2467             rsfp = PerlIO_stdin();
2468             lex_start_flags = LEX_DONT_CLOSE_RSFP;
2469         }
2470
2471         validate_suid(rsfp);
2472
2473 #if defined(SIGCHLD) || defined(SIGCLD)
2474         {
2475 #ifndef SIGCHLD
2476 #  define SIGCHLD SIGCLD
2477 #endif
2478             Sighandler_t sigstate = rsignal_state(SIGCHLD);
2479             if (sigstate == (Sighandler_t) SIG_IGN) {
2480                 Perl_ck_warner(aTHX_ packWARN(WARN_SIGNAL),
2481                                "Can't ignore signal CHLD, forcing to default");
2482                 (void)rsignal(SIGCHLD, (Sighandler_t)SIG_DFL);
2483             }
2484         }
2485 #endif
2486
2487         if (doextract) {
2488
2489             /* This will croak if suidscript is true, as -x cannot be used with
2490                setuid scripts.  */
2491             forbid_setid('x', suidscript);
2492             /* Hence you can't get here if suidscript is true */
2493
2494             linestr_sv = newSV_type(SVt_PV);
2495             lex_start_flags |= LEX_START_COPIED;
2496             find_beginning(linestr_sv, rsfp);
2497             if (cddir && PerlDir_chdir( (char *)cddir ) < 0)
2498                 Perl_croak(aTHX_ "Can't chdir to %s",cddir);
2499         }
2500     }
2501
2502     PL_main_cv = PL_compcv = MUTABLE_CV(newSV_type(SVt_PVCV));
2503     CvUNIQUE_on(PL_compcv);
2504
2505     CvPADLIST_set(PL_compcv, pad_new(0));
2506
2507     PL_isarev = newHV();
2508
2509     boot_core_PerlIO();
2510     boot_core_UNIVERSAL();
2511     boot_core_builtin();
2512     boot_core_mro();
2513     newXS("Internals::V", S_Internals_V, __FILE__);
2514
2515     if (xsinit)
2516         (*xsinit)(aTHX);        /* in case linked C routines want magical variables */
2517 #if defined(VMS) || defined(WIN32) || defined(__CYGWIN__)
2518     init_os_extras();
2519 #endif
2520
2521 #ifdef USE_SOCKS
2522 #   ifdef HAS_SOCKS5_INIT
2523     socks5_init(argv[0]);
2524 #   else
2525     SOCKSinit(argv[0]);
2526 #   endif
2527 #endif
2528
2529     init_predump_symbols();
2530     /* init_postdump_symbols not currently designed to be called */
2531     /* more than once (ENV isn't cleared first, for example)     */
2532     /* But running with -u leaves %ENV & @ARGV undefined!    XXX */
2533     if (!PL_do_undump)
2534         init_postdump_symbols(argc,argv,env);
2535
2536     /* PL_unicode is turned on by -C, or by $ENV{PERL_UNICODE},
2537      * or explicitly in some platforms.
2538      * PL_utf8locale is conditionally turned on by
2539      * locale.c:Perl_init_i18nl10n() if the environment
2540      * look like the user wants to use UTF-8. */
2541 #  ifndef PERL_IS_MINIPERL
2542     if (PL_unicode) {
2543          /* Requires init_predump_symbols(). */
2544          if (!(PL_unicode & PERL_UNICODE_LOCALE_FLAG) || PL_utf8locale) {
2545               IO* io;
2546               PerlIO* fp;
2547               SV* sv;
2548
2549               /* Turn on UTF-8-ness on STDIN, STDOUT, STDERR
2550                * and the default open disciplines. */
2551               if ((PL_unicode & PERL_UNICODE_STDIN_FLAG) &&
2552                   PL_stdingv  && (io = GvIO(PL_stdingv)) &&
2553                   (fp = IoIFP(io)))
2554                    PerlIO_binmode(aTHX_ fp, IoTYPE(io), 0, ":utf8");
2555               if ((PL_unicode & PERL_UNICODE_STDOUT_FLAG) &&
2556                   PL_defoutgv && (io = GvIO(PL_defoutgv)) &&
2557                   (fp = IoOFP(io)))
2558                    PerlIO_binmode(aTHX_ fp, IoTYPE(io), 0, ":utf8");
2559               if ((PL_unicode & PERL_UNICODE_STDERR_FLAG) &&
2560                   PL_stderrgv && (io = GvIO(PL_stderrgv)) &&
2561                   (fp = IoOFP(io)))
2562                    PerlIO_binmode(aTHX_ fp, IoTYPE(io), 0, ":utf8");
2563               if ((PL_unicode & PERL_UNICODE_INOUT_FLAG) &&
2564                   (sv = GvSV(gv_fetchpvs("\017PEN", GV_ADD|GV_NOTQUAL,
2565                                          SVt_PV)))) {
2566                    U32 in  = PL_unicode & PERL_UNICODE_IN_FLAG;
2567                    U32 out = PL_unicode & PERL_UNICODE_OUT_FLAG;
2568                    if (in) {
2569                         if (out)
2570                              sv_setpvs(sv, ":utf8\0:utf8");
2571                         else
2572                              sv_setpvs(sv, ":utf8\0");
2573                    }
2574                    else if (out)
2575                         sv_setpvs(sv, "\0:utf8");
2576                    SvSETMAGIC(sv);
2577               }
2578          }
2579     }
2580 #endif
2581
2582     {
2583         const char *s;
2584     if ((s = PerlEnv_getenv("PERL_SIGNALS"))) {
2585          if (strEQ(s, "unsafe"))
2586               PL_signals |=  PERL_SIGNALS_UNSAFE_FLAG;
2587          else if (strEQ(s, "safe"))
2588               PL_signals &= ~PERL_SIGNALS_UNSAFE_FLAG;
2589          else
2590               Perl_croak(aTHX_ "PERL_SIGNALS illegal: \"%s\"", s);
2591     }
2592     }
2593
2594
2595     lex_start(linestr_sv, rsfp, lex_start_flags);
2596     SvREFCNT_dec(linestr_sv);
2597
2598     PL_subname = newSVpvs("main");
2599
2600     if (add_read_e_script)
2601         filter_add(read_e_script, NULL);
2602
2603     /* now parse the script */
2604     if (minus_e == FALSE)
2605         PL_hints |= HINTS_DEFAULT; /* after init_main_stash ; need to be after init_predump_symbols */
2606
2607     SETERRNO(0,SS_NORMAL);
2608     if (yyparse(GRAMPROG) || PL_parser->error_count) {
2609         abort_execution(NULL, PL_origfilename);
2610     }
2611     CopLINE_set(PL_curcop, 0);
2612     SET_CURSTASH(PL_defstash);
2613     if (PL_e_script) {
2614         SvREFCNT_dec(PL_e_script);
2615         PL_e_script = NULL;
2616     }
2617
2618     if (PL_do_undump)
2619         my_unexec();
2620
2621     if (isWARN_ONCE) {
2622         SAVECOPFILE(PL_curcop);
2623         SAVECOPLINE(PL_curcop);
2624         gv_check(PL_defstash);
2625     }
2626
2627     LEAVE;
2628     FREETMPS;
2629
2630 #ifdef MYMALLOC
2631     {
2632         const char *s;
2633         UV uv;
2634         s = PerlEnv_getenv("PERL_DEBUG_MSTATS");
2635         if (s && grok_atoUV(s, &uv, NULL) && uv >= 2)
2636             dump_mstats("after compilation:");
2637     }
2638 #endif
2639
2640     ENTER;
2641     PL_restartjmpenv = NULL;
2642     PL_restartop = 0;
2643     return NULL;
2644 }
2645
2646 /*
2647 =for apidoc perl_run
2648
2649 Tells a Perl interpreter to run its main program.  See L<perlembed>
2650 for a tutorial.
2651
2652 C<my_perl> points to the Perl interpreter.  It must have been previously
2653 created through the use of L</perl_alloc> and L</perl_construct>, and
2654 initialised through L</perl_parse>.  This function should not be called
2655 if L</perl_parse> returned a non-zero value, indicating a failure in
2656 initialisation or compilation.
2657
2658 This function executes code in C<INIT> blocks, and then executes the
2659 main program.  The code to be executed is that established by the prior
2660 call to L</perl_parse>.  If the interpreter's C<PL_exit_flags> word
2661 does not have the C<PERL_EXIT_DESTRUCT_END> flag set, then this function
2662 will also execute code in C<END> blocks.  If it is desired to make any
2663 further use of the interpreter after calling this function, then C<END>
2664 blocks should be postponed to L</perl_destruct> time by setting that flag.
2665
2666 Returns an integer of slightly tricky interpretation.  The correct use
2667 of the return value is as a truth value indicating whether the program
2668 terminated non-locally.  If zero is returned, this indicates that
2669 the program ran to completion, and it is safe to make other use of the
2670 interpreter (provided that the C<PERL_EXIT_DESTRUCT_END> flag was set as
2671 described above).  If a non-zero value is returned, this indicates that
2672 the interpreter wants to terminate early.  The interpreter should not be
2673 just abandoned because of this desire to terminate; the caller should
2674 proceed to shut the interpreter down cleanly with L</perl_destruct>
2675 and free it with L</perl_free>.
2676
2677 For historical reasons, the non-zero return value also attempts to
2678 be a suitable value to pass to the C library function C<exit> (or to
2679 return from C<main>), to serve as an exit code indicating the nature of
2680 the way the program terminated.  However, this isn't portable, due to
2681 differing exit code conventions.  An attempt is made to return an exit
2682 code of the type required by the host operating system, but because
2683 it is constrained to be non-zero, it is not necessarily possible to
2684 indicate every type of exit.  It is only reliable on Unix, where a zero
2685 exit code can be augmented with a set bit that will be ignored.  In any
2686 case, this function is not the correct place to acquire an exit code:
2687 one should get that from L</perl_destruct>.
2688
2689 =cut
2690 */
2691
2692 int
2693 perl_run(pTHXx)
2694 {
2695     I32 oldscope;
2696     int ret = 0;
2697     dJMPENV;
2698
2699     PERL_ARGS_ASSERT_PERL_RUN;
2700 #ifndef MULTIPLICITY
2701     PERL_UNUSED_ARG(my_perl);
2702 #endif
2703
2704     oldscope = PL_scopestack_ix;
2705 #ifdef VMS
2706     VMSISH_HUSHED = 0;
2707 #endif
2708
2709     JMPENV_PUSH(ret);
2710     switch (ret) {
2711     case 1:
2712         cxstack_ix = -1;                /* start context stack again */
2713         goto redo_body;
2714     case 0:                             /* normal completion */
2715  redo_body:
2716         run_body(oldscope);
2717         /* FALLTHROUGH */
2718     case 2:                             /* my_exit() */
2719         while (PL_scopestack_ix > oldscope)
2720             LEAVE;
2721         FREETMPS;
2722         SET_CURSTASH(PL_defstash);
2723         if (!(PL_exit_flags & PERL_EXIT_DESTRUCT_END) &&
2724             PL_endav && !PL_minus_c) {
2725             PERL_SET_PHASE(PERL_PHASE_END);
2726             call_list(oldscope, PL_endav);
2727         }
2728 #ifdef MYMALLOC
2729         if (PerlEnv_getenv("PERL_DEBUG_MSTATS"))
2730             dump_mstats("after execution:  ");
2731 #endif
2732         ret = STATUS_EXIT;
2733         break;
2734     case 3:
2735         if (PL_restartop) {
2736             POPSTACK_TO(PL_mainstack);
2737             goto redo_body;
2738         }
2739         PerlIO_printf(Perl_error_log, "panic: restartop in perl_run\n");
2740         FREETMPS;
2741         ret = 1;
2742         break;
2743     }
2744
2745     JMPENV_POP;
2746     return ret;
2747 }
2748
2749 STATIC void
2750 S_run_body(pTHX_ I32 oldscope)
2751 {
2752     DEBUG_r(PerlIO_printf(Perl_debug_log, "%s $` $& $' support (0x%x).\n",
2753                     PL_sawampersand ? "Enabling" : "Omitting",
2754                     (unsigned int)(PL_sawampersand)));
2755
2756     if (!PL_restartop) {
2757 #ifdef DEBUGGING
2758         if (DEBUG_x_TEST || DEBUG_B_TEST)
2759             dump_all_perl(!DEBUG_B_TEST);
2760         if (!DEBUG_q_TEST)
2761           PERL_DEBUG(PerlIO_printf(Perl_debug_log, "\nEXECUTING...\n\n"));
2762 #endif
2763
2764         if (PL_minus_c) {
2765             PerlIO_printf(Perl_error_log, "%s syntax OK\n", PL_origfilename);
2766             my_exit(0);
2767         }
2768         if (PERLDB_SINGLE && PL_DBsingle)
2769             PL_DBsingle_iv = 1;
2770         if (PL_initav) {
2771             PERL_SET_PHASE(PERL_PHASE_INIT);
2772             call_list(oldscope, PL_initav);
2773         }
2774 #ifdef PERL_DEBUG_READONLY_OPS
2775         if (PL_main_root && PL_main_root->op_slabbed)
2776             Slab_to_ro(OpSLAB(PL_main_root));
2777 #endif
2778     }
2779
2780     /* do it */
2781
2782     PERL_SET_PHASE(PERL_PHASE_RUN);
2783
2784     if (PL_restartop) {
2785 #ifdef DEBUGGING
2786         /* this complements the "EXECUTING..." debug we emit above.
2787          * it will show up when an eval fails in the main program level
2788          * and the code continues after the error.
2789          */
2790         if (!DEBUG_q_TEST)
2791           PERL_DEBUG(PerlIO_printf(Perl_debug_log, "\nCONTINUING...\n\n"));
2792 #endif
2793         PL_restartjmpenv = NULL;
2794         PL_op = PL_restartop;
2795         PL_restartop = 0;
2796         CALLRUNOPS(aTHX);
2797     }
2798     else if (PL_main_start) {
2799         CvDEPTH(PL_main_cv) = 1;
2800         PL_op = PL_main_start;
2801         CALLRUNOPS(aTHX);
2802     }
2803     my_exit(0);
2804     NOT_REACHED; /* NOTREACHED */
2805 }
2806
2807 /*
2808 =for apidoc_section $SV
2809
2810 =for apidoc get_sv
2811
2812 Returns the SV of the specified Perl scalar.  C<flags> are passed to
2813 L</C<gv_fetchpv>>.  If C<GV_ADD> is set and the
2814 Perl variable does not exist then it will be created.  If C<flags> is zero
2815 and the variable does not exist then NULL is returned.
2816
2817 =cut
2818 */
2819
2820 SV*
2821 Perl_get_sv(pTHX_ const char *name, I32 flags)
2822 {
2823     GV *gv;
2824
2825     PERL_ARGS_ASSERT_GET_SV;
2826
2827     gv = gv_fetchpv(name, flags, SVt_PV);
2828     if (gv)
2829         return GvSV(gv);
2830     return NULL;
2831 }
2832
2833 /*
2834 =for apidoc_section $AV
2835
2836 =for apidoc get_av
2837
2838 Returns the AV of the specified Perl global or package array with the given
2839 name (so it won't work on lexical variables).  C<flags> are passed
2840 to C<gv_fetchpv>.  If C<GV_ADD> is set and the
2841 Perl variable does not exist then it will be created.  If C<flags> is zero
2842 (ignoring C<SVf_UTF8>) and the variable does not exist then C<NULL> is
2843 returned.
2844
2845 Perl equivalent: C<@{"$name"}>.
2846
2847 =cut
2848 */
2849
2850 AV*
2851 Perl_get_av(pTHX_ const char *name, I32 flags)
2852 {
2853     GV* const gv = gv_fetchpv(name, flags, SVt_PVAV);
2854
2855     PERL_ARGS_ASSERT_GET_AV;
2856
2857     if (flags & ~SVf_UTF8)
2858         return GvAVn(gv);
2859     if (gv)
2860         return GvAV(gv);
2861     return NULL;
2862 }
2863
2864 /*
2865 =for apidoc_section $HV
2866
2867 =for apidoc get_hv
2868
2869 Returns the HV of the specified Perl hash.  C<flags> are passed to
2870 C<gv_fetchpv>.  If C<GV_ADD> is set and the
2871 Perl variable does not exist then it will be created.  If C<flags> is zero
2872 (ignoring C<SVf_UTF8>) and the variable does not exist then C<NULL> is
2873 returned.
2874
2875 =cut
2876 */
2877
2878 HV*
2879 Perl_get_hv(pTHX_ const char *name, I32 flags)
2880 {
2881     GV* const gv = gv_fetchpv(name, flags, SVt_PVHV);
2882
2883     PERL_ARGS_ASSERT_GET_HV;
2884
2885     if (flags & ~SVf_UTF8)
2886         return GvHVn(gv);
2887     if (gv)
2888         return GvHV(gv);
2889     return NULL;
2890 }
2891
2892 /*
2893 =for apidoc_section $CV
2894
2895 =for apidoc            get_cv
2896 =for apidoc_item       get_cvn_flags
2897 =for apidoc_item |CV *|get_cvs|"string"|I32 flags
2898
2899 These return the CV of the specified Perl subroutine.  C<flags> are passed to
2900 C<gv_fetchpvn_flags>.  If C<GV_ADD> is set and the Perl subroutine does not
2901 exist then it will be declared (which has the same effect as saying
2902 C<sub name;>).  If C<GV_ADD> is not set and the subroutine does not exist,
2903 then NULL is returned.
2904
2905 The forms differ only in how the subroutine is specified..  With C<get_cvs>,
2906 the name is a literal C string, enclosed in double quotes.  With C<get_cv>, the
2907 name is given by the C<name> parameter, which must be a NUL-terminated C
2908 string.  With C<get_cvn_flags>, the name is also given by the C<name>
2909 parameter, but it is a Perl string (possibly containing embedded NUL bytes),
2910 and its length in bytes is contained in the C<len> parameter.
2911
2912 =for apidoc Amnh||GV_ADD
2913
2914 =cut
2915 */
2916
2917 CV*
2918 Perl_get_cvn_flags(pTHX_ const char *name, STRLEN len, I32 flags)
2919 {
2920     GV* const gv = gv_fetchpvn_flags(name, len, flags, SVt_PVCV);
2921
2922     PERL_ARGS_ASSERT_GET_CVN_FLAGS;
2923
2924     if (gv && UNLIKELY(SvROK(gv)) && SvTYPE(SvRV((SV *)gv)) == SVt_PVCV)
2925         return (CV*)SvRV((SV *)gv);
2926
2927     /* XXX this is probably not what they think they're getting.
2928      * It has the same effect as "sub name;", i.e. just a forward
2929      * declaration! */
2930     if ((flags & ~GV_NOADD_MASK) && !GvCVu(gv)) {
2931         return newSTUB(gv,0);
2932     }
2933     if (gv)
2934         return GvCVu(gv);
2935     return NULL;
2936 }
2937
2938 /* Nothing in core calls this now, but we can't replace it with a macro and
2939    move it to mathoms.c as a macro would evaluate name twice.  */
2940 CV*
2941 Perl_get_cv(pTHX_ const char *name, I32 flags)
2942 {
2943     PERL_ARGS_ASSERT_GET_CV;
2944
2945     return get_cvn_flags(name, strlen(name), flags);
2946 }
2947
2948 /* Be sure to refetch the stack pointer after calling these routines. */
2949
2950 /*
2951
2952 =for apidoc_section $callback
2953
2954 =for apidoc call_argv
2955
2956 Performs a callback to the specified named and package-scoped Perl subroutine
2957 with C<argv> (a C<NULL>-terminated array of strings) as arguments.  See
2958 L<perlcall>.
2959
2960 Approximate Perl equivalent: C<&{"$sub_name"}(@$argv)>.
2961
2962 =cut
2963 */
2964
2965 SSize_t
2966 Perl_call_argv(pTHX_ const char *sub_name, I32 flags, char **argv)
2967
2968                         /* See G_* flags in cop.h */
2969                         /* null terminated arg list */
2970 {
2971     PERL_ARGS_ASSERT_CALL_ARGV;
2972
2973     bool is_rc =
2974 #ifdef PERL_RC_STACK
2975                 rpp_stack_is_rc();
2976 #else
2977                 0;
2978 #endif
2979     PUSHMARK(PL_stack_sp);
2980     while (*argv) {
2981         SV *newsv = newSVpv(*argv,0);
2982         rpp_extend(1);
2983         *++PL_stack_sp = newsv;
2984         if (!is_rc)
2985             sv_2mortal(newsv);
2986         argv++;
2987     }
2988     return call_pv(sub_name, flags);
2989 }
2990
2991 /*
2992 =for apidoc call_pv
2993
2994 Performs a callback to the specified Perl sub.  See L<perlcall>.
2995
2996 =cut
2997 */
2998
2999 SSize_t
3000 Perl_call_pv(pTHX_ const char *sub_name, I32 flags)
3001                         /* name of the subroutine */
3002                         /* See G_* flags in cop.h */
3003 {
3004     PERL_ARGS_ASSERT_CALL_PV;
3005
3006     return call_sv(MUTABLE_SV(get_cv(sub_name, GV_ADD)), flags);
3007 }
3008
3009 /*
3010 =for apidoc call_method
3011
3012 Performs a callback to the specified Perl method.  The blessed object must
3013 be on the stack.  See L<perlcall>.
3014
3015 =cut
3016 */
3017
3018 SSize_t
3019 Perl_call_method(pTHX_ const char *methname, I32 flags)
3020                         /* name of the subroutine */
3021                         /* See G_* flags in cop.h */
3022 {
3023     STRLEN len;
3024     SV* sv;
3025     PERL_ARGS_ASSERT_CALL_METHOD;
3026
3027     len = strlen(methname);
3028     sv = flags & G_METHOD_NAMED
3029         ? sv_2mortal(newSVpvn_share(methname, len,0))
3030         : newSVpvn_flags(methname, len, SVs_TEMP);
3031
3032     return call_sv(sv, flags | G_METHOD);
3033 }
3034
3035 /* May be called with any of a CV, a GV, or an SV containing the name. */
3036 /*
3037 =for apidoc call_sv
3038
3039 Performs a callback to the Perl sub specified by the SV.
3040
3041 If neither the C<G_METHOD> nor C<G_METHOD_NAMED> flag is supplied, the
3042 SV may be any of a CV, a GV, a reference to a CV, a reference to a GV
3043 or C<SvPV(sv)> will be used as the name of the sub to call.
3044
3045 If the C<G_METHOD> flag is supplied, the SV may be a reference to a CV or
3046 C<SvPV(sv)> will be used as the name of the method to call.
3047
3048 If the C<G_METHOD_NAMED> flag is supplied, C<SvPV(sv)> will be used as
3049 the name of the method to call.
3050
3051 Some other values are treated specially for internal use and should
3052 not be depended on.
3053
3054 See L<perlcall>.
3055
3056 =for apidoc Amnh||G_METHOD
3057 =for apidoc Amnh||G_METHOD_NAMED
3058
3059 =cut
3060 */
3061
3062 SSize_t
3063 Perl_call_sv(pTHX_ SV *sv, I32 arg_flags)
3064                         /* See G_* flags in cop.h */
3065 {
3066     LOGOP myop;         /* fake syntax tree node */
3067     METHOP method_op;
3068     SSize_t oldmark;
3069     volatile SSize_t retval = 0;
3070     bool oldcatch = CATCH_GET;
3071     int ret;
3072     OP* const oldop = PL_op;
3073     /* Since we don't modify flags after setjmp() we don't really need to make
3074        flags volatile, but gcc complains that it could be clobbered anyway.
3075      */
3076     volatile I32 flags = arg_flags;
3077     dJMPENV;
3078
3079     PERL_ARGS_ASSERT_CALL_SV;
3080
3081     if (flags & G_DISCARD) {
3082         ENTER;
3083         SAVETMPS;
3084     }
3085     if (!(flags & G_WANT)) {
3086         /* Backwards compatibility - as G_SCALAR was 0, it could be omitted.
3087          */
3088         flags |= G_SCALAR;
3089     }
3090
3091     Zero(&myop, 1, LOGOP);
3092     if (!(flags & G_NOARGS))
3093         myop.op_flags |= OPf_STACKED;
3094     myop.op_flags |= OP_GIMME_REVERSE(flags);
3095     myop.op_ppaddr = PL_ppaddr[OP_ENTERSUB];
3096     myop.op_type = OP_ENTERSUB;
3097     SAVEOP();
3098     PL_op = (OP*)&myop;
3099
3100     if (!(flags & G_METHOD_NAMED)) {
3101         rpp_extend(1);
3102         *++PL_stack_sp = sv;
3103 #ifdef PERL_RC_STACK
3104         if (rpp_stack_is_rc())
3105             SvREFCNT_inc_simple_void_NN(sv);
3106 #endif
3107     }
3108     oldmark = TOPMARK;
3109
3110     if (PERLDB_SUB && PL_curstash != PL_debstash
3111            /* Handle first BEGIN of -d. */
3112           && (PL_DBcv || (PL_DBcv = GvCV(PL_DBsub)))
3113            /* Try harder, since this may have been a sighandler, thus
3114             * curstash may be meaningless. */
3115           && (SvTYPE(sv) != SVt_PVCV || CvSTASH((const CV *)sv) != PL_debstash)
3116           && !(flags & G_NODEBUG))
3117         myop.op_private |= OPpENTERSUB_DB;
3118
3119     if (flags & (G_METHOD|G_METHOD_NAMED)) {
3120         Zero(&method_op, 1, METHOP);
3121         method_op.op_next = (OP*)&myop;
3122         PL_op = (OP*)&method_op;
3123         if ( flags & G_METHOD_NAMED ) {
3124             method_op.op_ppaddr = PL_ppaddr[OP_METHOD_NAMED];
3125             method_op.op_type = OP_METHOD_NAMED;
3126             method_op.op_u.op_meth_sv = sv;
3127         } else {
3128             method_op.op_ppaddr = PL_ppaddr[OP_METHOD];
3129             method_op.op_type = OP_METHOD;
3130         }
3131     }
3132
3133     if (!(flags & G_EVAL)) {
3134         CATCH_SET(TRUE);
3135         CALLRUNOPS(aTHX);
3136         retval = PL_stack_sp - (PL_stack_base + oldmark);
3137         CATCH_SET(oldcatch);
3138     }
3139     else {
3140         I32 old_cxix;
3141         myop.op_other = (OP*)&myop;
3142         (void)POPMARK;
3143         old_cxix = cxstack_ix;
3144         create_eval_scope( NULL, PL_stack_base + oldmark, flags|G_FAKINGEVAL);
3145         INCMARK;
3146
3147         JMPENV_PUSH(ret);
3148
3149         switch (ret) {
3150         case 0:
3151  redo_body:
3152             CALLRUNOPS(aTHX);
3153             retval = PL_stack_sp - (PL_stack_base + oldmark);
3154             if (!(flags & G_KEEPERR)) {
3155                 CLEAR_ERRSV();
3156             }
3157             break;
3158         case 1:
3159             STATUS_ALL_FAILURE;
3160             /* FALLTHROUGH */
3161         case 2:
3162             /* my_exit() was called */
3163             SET_CURSTASH(PL_defstash);
3164             FREETMPS;
3165             JMPENV_POP;
3166             my_exit_jump();
3167             NOT_REACHED; /* NOTREACHED */
3168         case 3:
3169             if (PL_restartop) {
3170                 PL_restartjmpenv = NULL;
3171                 PL_op = PL_restartop;
3172                 PL_restartop = 0;
3173                 goto redo_body;
3174             }
3175             /* Should be nothing left in stack frame apart from a possible
3176              * scalar context undef. Assert it's safe to reset the stack */
3177             assert(     PL_stack_sp == PL_stack_base + oldmark
3178                     || (PL_stack_sp == PL_stack_base + oldmark + 1
3179                         && *PL_stack_sp == &PL_sv_undef));
3180             PL_stack_sp = PL_stack_base + oldmark;
3181             if ((flags & G_WANT) == G_LIST)
3182                 retval = 0;
3183             else {
3184                 retval = 1;
3185                 *++PL_stack_sp = &PL_sv_undef;
3186             }
3187             break;
3188         }
3189
3190         /* if we croaked, depending on how we croaked the eval scope
3191          * may or may not have already been popped */
3192         if (cxstack_ix > old_cxix) {
3193             assert(cxstack_ix == old_cxix + 1);
3194             assert(CxTYPE(CX_CUR()) == CXt_EVAL);
3195             delete_eval_scope();
3196         }
3197         JMPENV_POP;
3198     }
3199
3200     if (flags & G_DISCARD) {
3201 #ifdef PERL_RC_STACK
3202         if (rpp_stack_is_rc())
3203             rpp_popfree_to(PL_stack_base + oldmark);
3204         else
3205 #endif
3206             PL_stack_sp = PL_stack_base + oldmark;
3207         retval = 0;
3208         FREETMPS;
3209         LEAVE;
3210     }
3211     PL_op = oldop;
3212     return retval;
3213 }
3214
3215 /* Eval a string. The G_EVAL flag is always assumed. */
3216
3217 /*
3218 =for apidoc eval_sv
3219
3220 Tells Perl to C<eval> the string in the SV.  It supports the same flags
3221 as C<call_sv>, with the obvious exception of C<G_EVAL>.  See L<perlcall>.
3222
3223 The C<G_RETHROW> flag can be used if you only need eval_sv() to
3224 execute code specified by a string, but not catch any errors.
3225
3226 By default the code is compiled and executed with the default hints,
3227 such as strict and features.  Set C<G_USEHINTS> in flags to use the
3228 current hints from C<PL_curcop>.
3229
3230 =for apidoc Amnh||G_RETHROW
3231 =for apidoc Amnh||G_USEHINTS
3232 =cut
3233 */
3234
3235 SSize_t
3236 Perl_eval_sv(pTHX_ SV *sv, I32 flags)
3237
3238                         /* See G_* flags in cop.h */
3239 {
3240     UNOP myop;          /* fake syntax tree node */
3241     volatile SSize_t oldmark;
3242     volatile SSize_t retval = 0;
3243     int ret;
3244     OP* const oldop = PL_op;
3245     dJMPENV;
3246
3247     PERL_ARGS_ASSERT_EVAL_SV;
3248
3249     if (flags & G_DISCARD) {
3250         ENTER;
3251         SAVETMPS;
3252     }
3253
3254     SAVEOP();
3255     PL_op = (OP*)&myop;
3256     Zero(&myop, 1, UNOP);
3257     myop.op_ppaddr = PL_ppaddr[OP_ENTEREVAL];
3258     myop.op_type = OP_ENTEREVAL;
3259
3260     oldmark = PL_stack_sp - PL_stack_base;
3261     rpp_extend(1);
3262     *++PL_stack_sp = sv;
3263 #ifdef PERL_RC_STACK
3264     if (rpp_stack_is_rc())
3265         SvREFCNT_inc_simple_void_NN(sv);
3266 #endif
3267
3268     if (!(flags & G_NOARGS))
3269         myop.op_flags = OPf_STACKED;
3270     myop.op_type = OP_ENTEREVAL;
3271     myop.op_flags |= OP_GIMME_REVERSE(flags);
3272     if (flags & G_KEEPERR)
3273         myop.op_flags |= OPf_SPECIAL;
3274
3275     myop.op_private = (OPpEVAL_EVALSV); /* tell pp_entereval we're the caller */
3276     if (flags & G_RE_REPARSING)
3277         myop.op_private |= (OPpEVAL_COPHH | OPpEVAL_RE_REPARSING);
3278
3279     if (flags & G_USEHINTS)
3280         myop.op_private |= OPpEVAL_COPHH;
3281
3282     /* fail now; otherwise we could fail after the JMPENV_PUSH but
3283      * before a cx_pusheval(), which corrupts the stack after a croak */
3284     TAINT_PROPER("eval_sv()");
3285
3286     JMPENV_PUSH(ret);
3287     switch (ret) {
3288     case 0:
3289         CALLRUNOPS(aTHX);
3290         if (!*PL_stack_sp) {
3291             /* In the presence of the OPpEVAL_EVALSV flag,
3292              * pp_entereval() pushes a NULL pointer onto the stack to
3293              * indicate compilation failure. Otherwise, the top slot on
3294              * the stack will be a non-NULL pointer to whatever scalar or
3295              * list value(s) the eval returned. In void context it will
3296              * be whatever our caller has at the top of stack at the time,
3297              * or the &PL_sv_undef guard at PL_stack_base[0]. Note that
3298              * NULLs are not pushed on the stack except in a few very
3299              * specific circumstances (such as this) to flag something
3300              * special. */
3301             PL_stack_sp--;
3302             goto fail;
3303         }
3304      redone_body:
3305         retval = PL_stack_sp - (PL_stack_base + oldmark);
3306         if (!(flags & G_KEEPERR)) {
3307             CLEAR_ERRSV();
3308         }
3309         break;
3310     case 1:
3311         STATUS_ALL_FAILURE;
3312         /* FALLTHROUGH */
3313     case 2:
3314         /* my_exit() was called */
3315         SET_CURSTASH(PL_defstash);
3316         FREETMPS;
3317         JMPENV_POP;
3318         my_exit_jump();
3319         NOT_REACHED; /* NOTREACHED */
3320     case 3:
3321         if (PL_restartop) {
3322             PL_restartjmpenv = NULL;
3323             PL_op = PL_restartop;
3324             PL_restartop = 0;
3325             CALLRUNOPS(aTHX);
3326             goto redone_body;
3327         }
3328       fail:
3329         if (flags & G_RETHROW) {
3330             JMPENV_POP;
3331             croak_sv(ERRSV);
3332         }
3333         /* Should be nothing left in stack frame apart from a possible
3334          * scalar context undef. Assert it's safe to reset the stack */
3335         assert(     PL_stack_sp == PL_stack_base + oldmark
3336                 || (PL_stack_sp == PL_stack_base + oldmark + 1
3337                     && *PL_stack_sp == &PL_sv_undef));
3338         PL_stack_sp = PL_stack_base + oldmark;
3339         if ((flags & G_WANT) == G_LIST)
3340             retval = 0;
3341         else {
3342             retval = 1;
3343             *++PL_stack_sp = &PL_sv_undef;
3344         }
3345         break;
3346     }
3347
3348     JMPENV_POP;
3349     if (flags & G_DISCARD) {
3350 #ifdef PERL_RC_STACK
3351         if (rpp_stack_is_rc())
3352             rpp_popfree_to(PL_stack_base + oldmark);
3353         else
3354 #endif
3355             PL_stack_sp = PL_stack_base + oldmark;
3356         retval = 0;
3357         FREETMPS;
3358         LEAVE;
3359     }
3360     PL_op = oldop;
3361     return retval;
3362 }
3363
3364 /*
3365 =for apidoc eval_pv
3366
3367 Tells Perl to C<eval> the given string in scalar context and return an SV* result.
3368
3369 =cut
3370 */
3371
3372 SV*
3373 Perl_eval_pv(pTHX_ const char *p, I32 croak_on_error)
3374 {
3375     SV* sv = newSVpv(p, 0);
3376
3377     PERL_ARGS_ASSERT_EVAL_PV;
3378
3379     if (croak_on_error) {
3380         sv_2mortal(sv);
3381         eval_sv(sv, G_SCALAR | G_RETHROW);
3382     }
3383     else {
3384         eval_sv(sv, G_SCALAR);
3385         SvREFCNT_dec(sv);
3386     }
3387
3388     sv = *PL_stack_sp;
3389
3390 #ifdef PERL_RC_STACK
3391     if (rpp_stack_is_rc()) {
3392         SvREFCNT_inc_NN(sv_2mortal(sv));
3393         rpp_popfree_1();
3394     }
3395     else
3396 #endif
3397         PL_stack_sp--;
3398
3399     return sv;
3400 }
3401
3402 /* Require a module. */
3403
3404 /*
3405 =for apidoc_section $embedding
3406
3407 =for apidoc require_pv
3408
3409 Tells Perl to C<require> the file named by the string argument.  It is
3410 analogous to the Perl code C<eval "require '$file'">.  It's even
3411 implemented that way; consider using load_module instead.
3412
3413 =cut */
3414
3415 void
3416 Perl_require_pv(pTHX_ const char *pv)
3417 {
3418     dSP;
3419     SV* sv;
3420
3421     PERL_ARGS_ASSERT_REQUIRE_PV;
3422
3423     PUSHSTACKi(PERLSI_REQUIRE);
3424     sv = Perl_newSVpvf(aTHX_ "require q%c%s%c", 0, pv, 0);
3425     eval_sv(sv_2mortal(sv), G_DISCARD);
3426     POPSTACK;
3427 }
3428
3429 STATIC void
3430 S_usage(pTHX)           /* XXX move this out into a module ? */
3431 {
3432     /* This message really ought to be max 23 lines.
3433      * Removed -h because the user already knows that option. Others? */
3434
3435     /* Grouped as 6 lines per C string literal, to keep under the ANSI C 89
3436        minimum of 509 character string literals.  */
3437     static const char * const usage_msg[] = {
3438 "  -0[octal/hexadecimal] specify record separator (\\0, if no argument)\n"
3439 "  -a                    autosplit mode with -n or -p (splits $_ into @F)\n"
3440 "  -C[number/list]       enables the listed Unicode features\n"
3441 "  -c                    check syntax only (runs BEGIN and CHECK blocks)\n"
3442 "  -d[t][:MOD]           run program under debugger or module Devel::MOD\n"
3443 "  -D[number/letters]    set debugging flags (argument is a bit mask or alphabets)\n",
3444 "  -e commandline        one line of program (several -e's allowed, omit programfile)\n"
3445 "  -E commandline        like -e, but enables all optional features\n"
3446 "  -f                    don't do $sitelib/sitecustomize.pl at startup\n"
3447 "  -F/pattern/           split() pattern for -a switch (//'s are optional)\n"
3448 "  -g                    read all input in one go (slurp), rather than line-by-line (alias for -0777)\n"
3449 "  -i[extension]         edit <> files in place (makes backup if extension supplied)\n"
3450 "  -Idirectory           specify @INC/#include directory (several -I's allowed)\n",
3451 "  -l[octnum]            enable line ending processing, specifies line terminator\n"
3452 "  -[mM][-]module        execute \"use/no module...\" before executing program\n"
3453 "  -n                    assume \"while (<>) { ... }\" loop around program\n"
3454 "  -p                    assume loop like -n but print line also, like sed\n"
3455 "  -s                    enable rudimentary parsing for switches after programfile\n"
3456 "  -S                    look for programfile using PATH environment variable\n",
3457 "  -t                    enable tainting warnings\n"
3458 "  -T                    enable tainting checks\n"
3459 "  -u                    dump core after parsing program\n"
3460 "  -U                    allow unsafe operations\n"
3461 "  -v                    print version, patchlevel and license\n"
3462 "  -V[:configvar]        print configuration summary (or a single Config.pm variable)\n",
3463 "  -w                    enable many useful warnings\n"
3464 "  -W                    enable all warnings\n"
3465 "  -x[directory]         ignore text before #!perl line (optionally cd to directory)\n"
3466 "  -X                    disable all warnings\n"
3467 "  \n"
3468 "Run 'perldoc perl' for more help with Perl.\n\n",
3469 NULL
3470 };
3471     const char * const *p = usage_msg;
3472     PerlIO *out = PerlIO_stdout();
3473
3474     PerlIO_printf(out,
3475                   "\nUsage: %s [switches] [--] [programfile] [arguments]\n",
3476                   PL_origargv[0]);
3477     while (*p)
3478         PerlIO_puts(out, *p++);
3479     my_exit(0);
3480 }
3481
3482 /* convert a string of -D options (or digits) into an int.
3483  * sets *s to point to the char after the options */
3484
3485 #ifdef DEBUGGING
3486 int
3487 Perl_get_debug_opts(pTHX_ const char **s, bool givehelp)
3488 {
3489     static const char * const usage_msgd[] = {
3490       " Debugging flag values: (see also -d)\n"
3491       "  p  Tokenizing and parsing (with v, displays parse stack)\n"
3492       "  s  Stack snapshots (with v, displays all stacks)\n"
3493       "  l  Context (loop) stack processing\n"
3494       "  t  Trace execution\n"
3495       "  o  Method and overloading resolution\n",
3496       "  c  String/numeric conversions\n"
3497       "  P  Print profiling info, source file input state\n"
3498       "  m  Memory and SV allocation\n"
3499       "  f  Format processing\n"
3500       "  r  Regular expression parsing and execution\n"
3501       "  x  Syntax tree dump\n",
3502       "  u  Tainting checks\n"
3503       "  X  Scratchpad allocation\n"
3504       "  D  Cleaning up\n"
3505       "  S  Op slab allocation\n"
3506       "  T  Tokenising\n"
3507       "  R  Include reference counts of dumped variables (eg when using -Ds)\n",
3508       "  J  Do not s,t,P-debug (Jump over) opcodes within package DB\n"
3509       "  v  Verbose: use in conjunction with other flags\n"
3510       "  C  Copy On Write\n"
3511       "  A  Consistency checks on internal structures\n"
3512       "  q  quiet - currently only suppresses the 'EXECUTING' message\n"
3513       "  M  trace smart match resolution\n"
3514       "  B  dump suBroutine definitions, including special Blocks like BEGIN\n",
3515       "  L  trace some locale setting information--for Perl core development\n",
3516       "  i  trace PerlIO layer processing\n",
3517       "  y  trace y///, tr/// compilation and execution\n",
3518       "  h  Show (h)ash randomization debug output"
3519                 " (changes to PL_hash_rand_bits)\n",
3520       NULL
3521     };
3522     UV uv = 0;
3523
3524     PERL_ARGS_ASSERT_GET_DEBUG_OPTS;
3525
3526     if (isALPHA(**s)) {
3527         /* NOTE:
3528          * If adding new options add them to the END of debopts[].
3529          * If you remove an option replace it with a '?'.
3530          * If there is a free slot available marked with '?' feel
3531          * free to reuse it for something else.
3532          *
3533          * Regardless remember to update DEBUG_MASK in perl.h, and
3534          * update the documentation above AND in pod/perlrun.pod.
3535          *
3536          * Note that the ? indicates an unused slot. As the code below
3537          * indicates the position in this list is important. You cannot
3538          * change the order or delete a character from the list without
3539          * impacting the definitions of all the other flags in perl.h
3540          * However because the logic is guarded by isWORDCHAR we can
3541          * fill in holes with non-wordchar characters instead. */
3542         static const char debopts[] = "psltocPmfrxuUhXDSTRJvCAqMBLiy";
3543
3544         for (; isWORDCHAR(**s); (*s)++) {
3545             const char * const d = strchr(debopts,**s);
3546             if (d)
3547                 uv |= 1 << (d - debopts);
3548             else if (ckWARN_d(WARN_DEBUGGING))
3549                 Perl_warner(aTHX_ packWARN(WARN_DEBUGGING),
3550                     "invalid option -D%c, use -D'' to see choices\n", **s);
3551         }
3552     }
3553     else if (isDIGIT(**s)) {
3554         const char* e = *s + strlen(*s);
3555         if (grok_atoUV(*s, &uv, &e))
3556             *s = e;
3557         for (; isWORDCHAR(**s); (*s)++) ;
3558     }
3559     else if (givehelp) {
3560       const char *const *p = usage_msgd;
3561       while (*p) PerlIO_puts(PerlIO_stdout(), *p++);
3562     }
3563     return (int)uv; /* ignore any UV->int conversion loss */
3564 }
3565 #endif
3566
3567 /* This routine handles any switches that can be given during run */
3568
3569 const char *
3570 Perl_moreswitches(pTHX_ const char *s)
3571 {
3572     UV rschar;
3573     const char option = *s; /* used to remember option in -m/-M code */
3574
3575     PERL_ARGS_ASSERT_MORESWITCHES;
3576
3577     switch (*s) {
3578     case '0':
3579     {
3580          I32 flags = 0;
3581          STRLEN numlen;
3582
3583          SvREFCNT_dec(PL_rs);
3584          if (s[1] == 'x' && s[2]) {
3585               const char *e = s+=2;
3586               U8 *tmps;
3587
3588               while (*e)
3589                 e++;
3590               numlen = e - s;
3591               flags = PERL_SCAN_SILENT_ILLDIGIT;
3592               rschar = (U32)grok_hex(s, &numlen, &flags, NULL);
3593               if (s + numlen < e) {
3594                   /* Continue to treat -0xFOO as -0 -xFOO
3595                    * (ie NUL as the input record separator, and -x with FOO
3596                    *  as the directory argument)
3597                    *
3598                    * hex support for -0 was only added in 5.8.1, hence this
3599                    * heuristic to distinguish between it and '-0' clustered with
3600                    * '-x' with an argument. The text following '-0x' is only
3601                    * processed as the IRS specified in hexadecimal if all
3602                    * characters are valid hex digits. */
3603                    rschar = 0;
3604                    numlen = 0;
3605                    s--;
3606               }
3607               PL_rs = newSV((STRLEN)(UVCHR_SKIP(rschar) + 1));
3608               tmps = (U8*)SvPVCLEAR_FRESH(PL_rs);
3609               uvchr_to_utf8(tmps, rschar);
3610               SvCUR_set(PL_rs, UVCHR_SKIP(rschar));
3611               SvUTF8_on(PL_rs);
3612          }
3613          else {
3614               numlen = 4;
3615               rschar = (U32)grok_oct(s, &numlen, &flags, NULL);
3616               if (rschar & ~((U8)~0))
3617                    PL_rs = &PL_sv_undef;
3618               else if (!rschar && numlen >= 2)
3619                    PL_rs = newSVpvs("");
3620               else {
3621                    char ch = (char)rschar;
3622                    PL_rs = newSVpvn(&ch, 1);
3623               }
3624          }
3625          sv_setsv(get_sv("/", GV_ADD), PL_rs);
3626          return s + numlen;
3627     }
3628     case 'C':
3629         s++;
3630         PL_unicode = parse_unicode_opts( (const char **)&s );
3631         if (PL_unicode & PERL_UNICODE_UTF8CACHEASSERT_FLAG)
3632             PL_utf8cache = -1;
3633         return s;
3634     case 'F':
3635         PL_minus_a = TRUE;
3636         PL_minus_F = TRUE;
3637         PL_minus_n = TRUE;
3638         {
3639             const char *start = ++s;
3640             while (*s && !isSPACE(*s)) ++s;
3641             Safefree(PL_splitstr);
3642             PL_splitstr = savepvn(start, s - start);
3643         }
3644         return s;
3645     case 'a':
3646         PL_minus_a = TRUE;
3647         PL_minus_n = TRUE;
3648         s++;
3649         return s;
3650     case 'c':
3651         PL_minus_c = TRUE;
3652         s++;
3653         return s;
3654     case 'd':
3655         forbid_setid('d', FALSE);
3656         s++;
3657
3658         /* -dt indicates to the debugger that threads will be used */
3659         if (*s == 't' && !isWORDCHAR(s[1])) {
3660             ++s;
3661             my_setenv("PERL5DB_THREADED", "1");
3662         }
3663
3664         /* The following permits -d:Mod to accepts arguments following an =
3665            in the fashion that -MSome::Mod does. */
3666         if (*s == ':' || *s == '=') {
3667             const char *start;
3668             const char *end;
3669             SV *sv;
3670
3671             if (*++s == '-') {
3672                 ++s;
3673                 sv = newSVpvs("no Devel::");
3674             } else {
3675                 sv = newSVpvs("use Devel::");
3676             }
3677
3678             start = s;
3679             end = s + strlen(s);
3680
3681             /* We now allow -d:Module=Foo,Bar and -d:-Module */
3682             while(isWORDCHAR(*s) || *s==':') ++s;
3683             if (*s != '=')
3684                 sv_catpvn(sv, start, end - start);
3685             else {
3686                 sv_catpvn(sv, start, s-start);
3687                 /* Don't use NUL as q// delimiter here, this string goes in the
3688                  * environment. */
3689                 Perl_sv_catpvf(aTHX_ sv, " split(/,/,q{%s});", ++s);
3690             }
3691             s = end;
3692             my_setenv("PERL5DB", SvPV_nolen_const(sv));
3693             SvREFCNT_dec(sv);
3694         }
3695         if (!PL_perldb) {
3696             PL_perldb = PERLDB_ALL;
3697             init_debugger();
3698         }
3699         return s;
3700     case 'D':
3701     {
3702 #ifdef DEBUGGING
3703         forbid_setid('D', FALSE);
3704         s++;
3705         PL_debug = get_debug_opts( (const char **)&s, 1) | DEBUG_TOP_FLAG;
3706 #else /* !DEBUGGING */
3707         if (ckWARN_d(WARN_DEBUGGING))
3708             Perl_warner(aTHX_ packWARN(WARN_DEBUGGING),
3709                    "Recompile perl with -DDEBUGGING to use -D switch (did you mean -d ?)\n");
3710         for (s++; isWORDCHAR(*s); s++) ;
3711 #endif
3712         return s;
3713         NOT_REACHED; /* NOTREACHED */
3714     }
3715     case 'g':
3716         SvREFCNT_dec(PL_rs);
3717         PL_rs = &PL_sv_undef;
3718         sv_setsv(get_sv("/", GV_ADD), PL_rs);
3719         return ++s;
3720
3721     case '?':
3722         /* FALLTHROUGH */
3723     case 'h':
3724         usage();
3725         NOT_REACHED; /* NOTREACHED */
3726
3727     case 'i':
3728         Safefree(PL_inplace);
3729         {
3730             const char * const start = ++s;
3731             while (*s && !isSPACE(*s))
3732                 ++s;
3733
3734             PL_inplace = savepvn(start, s - start);
3735         }
3736         return s;
3737     case 'I':   /* -I handled both here and in parse_body() */
3738         forbid_setid('I', FALSE);
3739         ++s;
3740         while (*s && isSPACE(*s))
3741             ++s;
3742         if (*s) {
3743             const char *e, *p;
3744             p = s;
3745             /* ignore trailing spaces (possibly followed by other switches) */
3746             do {
3747                 for (e = p; *e && !isSPACE(*e); e++) ;
3748                 p = e;
3749                 while (isSPACE(*p))
3750                     p++;
3751             } while (*p && *p != '-');
3752             incpush(s, e-s,
3753                     INCPUSH_ADD_SUB_DIRS|INCPUSH_ADD_OLD_VERS|INCPUSH_UNSHIFT);
3754             s = p;
3755             if (*s == '-')
3756                 s++;
3757         }
3758         else
3759             Perl_croak(aTHX_ "No directory specified for -I");
3760         return s;
3761     case 'l':
3762         PL_minus_l = TRUE;
3763         s++;
3764         if (PL_ors_sv) {
3765             SvREFCNT_dec(PL_ors_sv);
3766             PL_ors_sv = NULL;
3767         }
3768         if (isDIGIT(*s)) {
3769             I32 flags = 0;
3770             STRLEN numlen;
3771             PL_ors_sv = newSVpvs("\n");
3772             numlen = 3 + (*s == '0');
3773             *SvPVX(PL_ors_sv) = (char)grok_oct(s, &numlen, &flags, NULL);
3774             s += numlen;
3775         }
3776         else {
3777             if (RsPARA(PL_rs)) {
3778                 PL_ors_sv = newSVpvs("\n\n");
3779             }
3780             else {
3781                 PL_ors_sv = newSVsv(PL_rs);
3782             }
3783         }
3784         return s;
3785     case 'M':
3786         forbid_setid('M', FALSE);       /* XXX ? */
3787         /* FALLTHROUGH */
3788     case 'm':
3789         forbid_setid('m', FALSE);       /* XXX ? */
3790         if (*++s) {
3791             const char *start;
3792             const char *end;
3793             SV *sv;
3794             const char *use = "use ";
3795             bool colon = FALSE;
3796             /* -M-foo == 'no foo'       */
3797             /* Leading space on " no " is deliberate, to make both
3798                possibilities the same length.  */
3799             if (*s == '-') { use = " no "; ++s; }
3800             sv = newSVpvn(use,4);
3801             start = s;
3802             /* We allow -M'Module qw(Foo Bar)'  */
3803             while(isWORDCHAR(*s) || *s==':') {
3804                 if( *s++ == ':' ) {
3805                     if( *s == ':' )
3806                         s++;
3807                     else
3808                         colon = TRUE;
3809                 }
3810             }
3811             if (s == start)
3812                 Perl_croak(aTHX_ "Module name required with -%c option",
3813                                     option);
3814             if (colon)
3815                 Perl_croak(aTHX_ "Invalid module name %.*s with -%c option: "
3816                                     "contains single ':'",
3817                                     (int)(s - start), start, option);
3818             end = s + strlen(s);
3819             if (*s != '=') {
3820                 sv_catpvn(sv, start, end - start);
3821                 if (option == 'm') {
3822                     if (*s != '\0')
3823                         Perl_croak(aTHX_ "Can't use '%c' after -mname", *s);
3824                     sv_catpvs( sv, " ()");
3825                 }
3826             } else {
3827                 sv_catpvn(sv, start, s-start);
3828                 /* Use NUL as q''-delimiter.  */
3829                 sv_catpvs(sv, " split(/,/,q\0");
3830                 ++s;
3831                 sv_catpvn(sv, s, end - s);
3832                 sv_catpvs(sv,  "\0)");
3833             }
3834             s = end;
3835             Perl_av_create_and_push(aTHX_ &PL_preambleav, sv);
3836         }
3837         else
3838             Perl_croak(aTHX_ "Missing argument to -%c", option);
3839         return s;
3840     case 'n':
3841         PL_minus_n = TRUE;
3842         s++;
3843         return s;
3844     case 'p':
3845         PL_minus_p = TRUE;
3846         s++;
3847         return s;
3848     case 's':
3849         forbid_setid('s', FALSE);
3850         PL_doswitches = TRUE;
3851         s++;
3852         return s;
3853     case 't':
3854     case 'T':
3855 #if defined(SILENT_NO_TAINT_SUPPORT)
3856             /* silently ignore */
3857 #elif defined(NO_TAINT_SUPPORT)
3858         Perl_croak_nocontext("This perl was compiled without taint support. "
3859                    "Cowardly refusing to run with -t or -T flags");
3860 #else
3861         if (!TAINTING_get)
3862             TOO_LATE_FOR(*s);
3863 #endif
3864         s++;
3865         return s;
3866     case 'u':
3867         PL_do_undump = TRUE;
3868         s++;
3869         return s;
3870     case 'U':
3871         PL_unsafe = TRUE;
3872         s++;
3873         return s;
3874     case 'v':
3875         minus_v();
3876     case 'w':
3877         if (! (PL_dowarn & G_WARN_ALL_MASK)) {
3878             PL_dowarn |= G_WARN_ON;
3879         }
3880         s++;
3881         return s;
3882     case 'W':
3883         PL_dowarn = G_WARN_ALL_ON|G_WARN_ON;
3884         free_and_set_cop_warnings(&PL_compiling, pWARN_ALL);
3885         s++;
3886         return s;
3887     case 'X':
3888         PL_dowarn = G_WARN_ALL_OFF;
3889         free_and_set_cop_warnings(&PL_compiling, pWARN_NONE);
3890         s++;
3891         return s;
3892     case '*':
3893     case ' ':
3894         while( *s == ' ' )
3895           ++s;
3896         if (s[0] == '-')        /* Additional switches on #! line. */
3897             return s+1;
3898         break;
3899     case '-':
3900     case 0:
3901 #if defined(WIN32) || !defined(PERL_STRICT_CR)
3902     case '\r':
3903 #endif
3904     case '\n':
3905     case '\t':
3906         break;
3907 #ifdef ALTERNATE_SHEBANG
3908     case 'S':                   /* OS/2 needs -S on "extproc" line. */
3909         break;
3910 #endif
3911     case 'e': case 'f': case 'x': case 'E':
3912 #ifndef ALTERNATE_SHEBANG
3913     case 'S':
3914 #endif
3915     case 'V':
3916         Perl_croak(aTHX_ "Can't emulate -%.1s on #! line",s);
3917     default:
3918         Perl_croak(aTHX_
3919             "Unrecognized switch: -%.1s  (-h will show valid options)",s
3920         );
3921     }
3922     return NULL;
3923 }
3924
3925
3926 STATIC void
3927 S_minus_v(pTHX)
3928 {
3929         PerlIO * PIO_stdout;
3930         {
3931             const char * const level_str = "v" PERL_VERSION_STRING;
3932             const STRLEN level_len = sizeof("v" PERL_VERSION_STRING)-1;
3933 #ifdef PERL_PATCHNUM
3934             SV* level;
3935 #  ifdef PERL_GIT_UNCOMMITTED_CHANGES
3936             static const char num [] = PERL_PATCHNUM "*";
3937 #  else
3938             static const char num [] = PERL_PATCHNUM;
3939 #  endif
3940             {
3941                 const STRLEN num_len = sizeof(num)-1;
3942                 /* A very advanced compiler would fold away the strnEQ
3943                    and this whole conditional, but most (all?) won't do it.
3944                    SV level could also be replaced by with preprocessor
3945                    catenation.
3946                 */
3947                 if (num_len >= level_len && strnEQ(num,level_str,level_len)) {
3948                     /* per 46807d8e80, PERL_PATCHNUM is outside of the control
3949                        of the interp so it might contain format characters
3950                     */
3951                     level = newSVpvn(num, num_len);
3952                 } else {
3953                     level = Perl_newSVpvf_nocontext("%s (%s)", level_str, num);
3954                 }
3955             }
3956 #else
3957         SV* level = newSVpvn(level_str, level_len);
3958 #endif /* #ifdef PERL_PATCHNUM */
3959         PIO_stdout =  PerlIO_stdout();
3960             PerlIO_printf(PIO_stdout,
3961                 "\nThis is perl "       STRINGIFY(PERL_REVISION)
3962                 ", version "            STRINGIFY(PERL_VERSION)
3963                 ", subversion "         STRINGIFY(PERL_SUBVERSION)
3964                 " (%" SVf ") built for "        ARCHNAME, SVfARG(level)
3965                 );
3966             SvREFCNT_dec_NN(level);
3967         }
3968 #if defined(LOCAL_PATCH_COUNT)
3969         if (LOCAL_PATCH_COUNT > 0)
3970             PerlIO_printf(PIO_stdout,
3971                           "\n(with %d registered patch%s, "
3972                           "see perl -V for more detail)",
3973                           LOCAL_PATCH_COUNT,
3974                           (LOCAL_PATCH_COUNT!=1) ? "es" : "");
3975 #endif
3976
3977         PerlIO_printf(PIO_stdout,
3978                       "\n\nCopyright 1987-2023, Larry Wall\n");
3979 #ifdef OS2
3980         PerlIO_printf(PIO_stdout,
3981                       "\n\nOS/2 port Copyright (c) 1990, 1991, Raymond Chen, Kai Uwe Rommel\n"
3982                       "Version 5 port Copyright (c) 1994-2002, Andreas Kaiser, Ilya Zakharevich\n");
3983 #endif
3984 #ifdef OEMVS
3985         PerlIO_printf(PIO_stdout,
3986                       "MVS (OS390) port by Mortice Kern Systems, 1997-1999\n");
3987 #endif
3988 #ifdef __VOS__
3989         PerlIO_printf(PIO_stdout,
3990                       "Stratus OpenVOS port by Paul.Green@stratus.com, 1997-2013\n");
3991 #endif
3992 #ifdef POSIX_BC
3993         PerlIO_printf(PIO_stdout,
3994                       "BS2000 (POSIX) port by Start Amadeus GmbH, 1998-1999\n");
3995 #endif
3996 #ifdef BINARY_BUILD_NOTICE
3997         BINARY_BUILD_NOTICE;
3998 #endif
3999         PerlIO_printf(PIO_stdout,
4000                       "\n\
4001 Perl may be copied only under the terms of either the Artistic License or the\n\
4002 GNU General Public License, which may be found in the Perl 5 source kit.\n\n\
4003 Complete documentation for Perl, including FAQ lists, should be found on\n\
4004 this system using \"man perl\" or \"perldoc perl\".  If you have access to the\n\
4005 Internet, point your browser at https://www.perl.org/, the Perl Home Page.\n\n");
4006         my_exit(0);
4007 }
4008
4009 /* compliments of Tom Christiansen */
4010
4011 /* unexec() can be found in the Gnu emacs distribution */
4012 /* Known to work with -DUNEXEC and using unexelf.c from GNU emacs-20.2 */
4013
4014 #ifdef VMS
4015 #include <lib$routines.h>
4016 #endif
4017
4018 void
4019 Perl_my_unexec(pTHX)
4020 {
4021 #ifdef UNEXEC
4022     SV *    prog = newSVpv(BIN_EXP, 0);
4023     SV *    file = newSVpv(PL_origfilename, 0);
4024     int    status = 1;
4025     extern int etext;
4026
4027     sv_catpvs(prog, "/perl");
4028     sv_catpvs(file, ".perldump");
4029
4030     unexec(SvPVX(file), SvPVX(prog), &etext, sbrk(0), 0);
4031     /* unexec prints msg to stderr in case of failure */
4032     PerlProc_exit(status);
4033 #else
4034     PERL_UNUSED_CONTEXT;
4035 #  ifdef VMS
4036      lib$signal(SS$_DEBUG);  /* ssdef.h #included from vmsish.h */
4037 #  elif defined(WIN32) || defined(__CYGWIN__)
4038     Perl_croak_nocontext("dump is not supported");
4039 #  else
4040     ABORT();            /* for use with undump */
4041 #  endif
4042 #endif
4043 }
4044
4045 /* initialize curinterp */
4046 STATIC void
4047 S_init_interp(pTHX)
4048 {
4049 #ifdef MULTIPLICITY
4050 #  define PERLVAR(prefix,var,type)
4051 #  define PERLVARA(prefix,var,n,type)
4052 #  if defined(MULTIPLICITY)
4053 #    define PERLVARI(prefix,var,type,init)      aTHX->prefix##var = init;
4054 #    define PERLVARIC(prefix,var,type,init)     aTHX->prefix##var = init;
4055 #  else
4056 #    define PERLVARI(prefix,var,type,init)      PERL_GET_INTERP->var = init;
4057 #    define PERLVARIC(prefix,var,type,init)     PERL_GET_INTERP->var = init;
4058 #  endif
4059 #  include "intrpvar.h"
4060 #  undef PERLVAR
4061 #  undef PERLVARA
4062 #  undef PERLVARI
4063 #  undef PERLVARIC
4064 #else
4065 #  define PERLVAR(prefix,var,type)
4066 #  define PERLVARA(prefix,var,n,type)
4067 #  define PERLVARI(prefix,var,type,init)        PL_##var = init;
4068 #  define PERLVARIC(prefix,var,type,init)       PL_##var = init;
4069 #  include "intrpvar.h"
4070 #  undef PERLVAR
4071 #  undef PERLVARA
4072 #  undef PERLVARI
4073 #  undef PERLVARIC
4074 #endif
4075
4076 }
4077
4078 STATIC void
4079 S_init_main_stash(pTHX)
4080 {
4081     GV *gv;
4082     HV *hv = newHV();
4083
4084     PL_curstash = PL_defstash = (HV *)SvREFCNT_inc_simple_NN(hv);
4085     /* We know that the string "main" will be in the global shared string
4086        table, so it's a small saving to use it rather than allocate another
4087        8 bytes.  */
4088     PL_curstname = newSVpvs_share("main");
4089     gv = gv_fetchpvs("main::", GV_ADD|GV_NOTQUAL, SVt_PVHV);
4090     /* If we hadn't caused another reference to "main" to be in the shared
4091        string table above, then it would be worth reordering these two,
4092        because otherwise all we do is delete "main" from it as a consequence
4093        of the SvREFCNT_dec, only to add it again with hv_name_set */
4094     SvREFCNT_dec(GvHV(gv));
4095     hv_name_sets(PL_defstash, "main", 0);
4096     GvHV(gv) = MUTABLE_HV(SvREFCNT_inc_simple(PL_defstash));
4097     SvREADONLY_on(gv);
4098     PL_incgv = gv_HVadd(gv_AVadd(gv_fetchpvs("INC", GV_ADD|GV_NOTQUAL,
4099                                              SVt_PVAV)));
4100     SvREFCNT_inc_simple_void(PL_incgv); /* Don't allow it to be freed */
4101     GvMULTI_on(PL_incgv);
4102     PL_hintgv = gv_fetchpvs("\010", GV_ADD|GV_NOTQUAL, SVt_PV); /* ^H */
4103     SvREFCNT_inc_simple_void(PL_hintgv);
4104     GvMULTI_on(PL_hintgv);
4105     PL_defgv = gv_fetchpvs("_", GV_ADD|GV_NOTQUAL, SVt_PVAV);
4106     SvREFCNT_inc_simple_void(PL_defgv);
4107     PL_errgv = gv_fetchpvs("@", GV_ADD|GV_NOTQUAL, SVt_PV);
4108     SvREFCNT_inc_simple_void(PL_errgv);
4109     GvMULTI_on(PL_errgv);
4110     PL_replgv = gv_fetchpvs("\022", GV_ADD|GV_NOTQUAL, SVt_PV); /* ^R */
4111     SvREFCNT_inc_simple_void(PL_replgv);
4112     GvMULTI_on(PL_replgv);
4113     (void)Perl_form(aTHX_ "%240s","");  /* Preallocate temp - for immediate signals. */
4114 #ifdef PERL_DONT_CREATE_GVSV
4115     (void)gv_SVadd(PL_errgv);
4116 #endif
4117     sv_grow(ERRSV, 240);        /* Preallocate - for immediate signals. */
4118     CLEAR_ERRSV();
4119     CopSTASH_set(&PL_compiling, PL_defstash);
4120     PL_debstash = GvHV(gv_fetchpvs("DB::", GV_ADDMULTI, SVt_PVHV));
4121     PL_globalstash = GvHV(gv_fetchpvs("CORE::GLOBAL::", GV_ADDMULTI,
4122                                       SVt_PVHV));
4123     /* We must init $/ before switches are processed. */
4124     sv_setpvs(get_sv("/", GV_ADD), "\n");
4125 }
4126
4127 STATIC PerlIO *
4128 S_open_script(pTHX_ const char *scriptname, bool dosearch, bool *suidscript)
4129 {
4130     int fdscript = -1;
4131     PerlIO *rsfp = NULL;
4132     Stat_t tmpstatbuf;
4133     int fd;
4134
4135     PERL_ARGS_ASSERT_OPEN_SCRIPT;
4136
4137     if (PL_e_script) {
4138         PL_origfilename = savepvs("-e");
4139     }
4140     else {
4141         const char *s;
4142         UV uv;
4143         /* if find_script() returns, it returns a malloc()-ed value */
4144         scriptname = PL_origfilename = find_script(scriptname, dosearch, NULL, 1);
4145         s = scriptname + strlen(scriptname);
4146
4147         if (strBEGINs(scriptname, "/dev/fd/")
4148             && isDIGIT(scriptname[8])
4149             && grok_atoUV(scriptname + 8, &uv, &s)
4150             && uv <= PERL_INT_MAX
4151         ) {
4152             fdscript = (int)uv;
4153             if (*s) {
4154                 /* PSz 18 Feb 04
4155                  * Tell apart "normal" usage of fdscript, e.g.
4156                  * with bash on FreeBSD:
4157                  *   perl <( echo '#!perl -DA'; echo 'print "$0\n"')
4158                  * from usage in suidperl.
4159                  * Does any "normal" usage leave garbage after the number???
4160                  * Is it a mistake to use a similar /dev/fd/ construct for
4161                  * suidperl?
4162                  */
4163                 *suidscript = TRUE;
4164                 /* PSz 20 Feb 04
4165                  * Be supersafe and do some sanity-checks.
4166                  * Still, can we be sure we got the right thing?
4167                  */
4168                 if (*s != '/') {
4169                     Perl_croak(aTHX_ "Wrong syntax (suid) fd script name \"%s\"\n", s);
4170                 }
4171                 if (! *(s+1)) {
4172                     Perl_croak(aTHX_ "Missing (suid) fd script name\n");
4173                 }
4174                 scriptname = savepv(s + 1);
4175                 Safefree(PL_origfilename);
4176                 PL_origfilename = (char *)scriptname;
4177             }
4178         }
4179     }
4180
4181     CopFILE_free(PL_curcop);
4182     CopFILE_set(PL_curcop, PL_origfilename);
4183     if (*PL_origfilename == '-' && PL_origfilename[1] == '\0')
4184         scriptname = (char *)"";
4185     if (fdscript >= 0) {
4186         rsfp = PerlIO_fdopen(fdscript,PERL_SCRIPT_MODE);
4187     }
4188     else if (!*scriptname) {
4189         forbid_setid(0, *suidscript);
4190         return NULL;
4191     }
4192     else {
4193 #ifdef FAKE_BIT_BUCKET
4194         /* This hack allows one not to have /dev/null (or BIT_BUCKET as it
4195          * is called) and still have the "-e" work.  (Believe it or not,
4196          * a /dev/null is required for the "-e" to work because source
4197          * filter magic is used to implement it. ) This is *not* a general
4198          * replacement for a /dev/null.  What we do here is create a temp
4199          * file (an empty file), open up that as the script, and then
4200          * immediately close and unlink it.  Close enough for jazz. */
4201 #define FAKE_BIT_BUCKET_PREFIX "/tmp/perlnull-"
4202 #define FAKE_BIT_BUCKET_SUFFIX "XXXXXXXX"
4203 #define FAKE_BIT_BUCKET_TEMPLATE FAKE_BIT_BUCKET_PREFIX FAKE_BIT_BUCKET_SUFFIX
4204         char tmpname[sizeof(FAKE_BIT_BUCKET_TEMPLATE)] = {
4205             FAKE_BIT_BUCKET_TEMPLATE
4206         };
4207         const char * const err = "Failed to create a fake bit bucket";
4208         if (strEQ(scriptname, BIT_BUCKET)) {
4209             int tmpfd = Perl_my_mkstemp_cloexec(tmpname);
4210             if (tmpfd > -1) {
4211                 scriptname = tmpname;
4212                 close(tmpfd);
4213             } else
4214                 Perl_croak(aTHX_ err);
4215         }
4216 #endif
4217         rsfp = PerlIO_open(scriptname,PERL_SCRIPT_MODE);
4218 #ifdef FAKE_BIT_BUCKET
4219         if (   strBEGINs(scriptname, FAKE_BIT_BUCKET_PREFIX)
4220             && strlen(scriptname) == sizeof(tmpname) - 1)
4221         {
4222             unlink(scriptname);
4223         }
4224         scriptname = BIT_BUCKET;
4225 #endif
4226     }
4227     if (!rsfp) {
4228         /* PSz 16 Sep 03  Keep neat error message */
4229         if (PL_e_script)
4230             Perl_croak(aTHX_ "Can't open " BIT_BUCKET ": %s\n", Strerror(errno));
4231         else
4232             Perl_croak(aTHX_ "Can't open perl script \"%s\": %s\n",
4233                     CopFILE(PL_curcop), Strerror(errno));
4234     }
4235     fd = PerlIO_fileno(rsfp);
4236
4237     if (fd < 0 ||
4238         (PerlLIO_fstat(fd, &tmpstatbuf) >= 0
4239          && S_ISDIR(tmpstatbuf.st_mode)))
4240         Perl_croak(aTHX_ "Can't open perl script \"%s\": %s\n",
4241             CopFILE(PL_curcop),
4242             Strerror(EISDIR));
4243
4244     return rsfp;
4245 }
4246
4247 /* In the days of suidperl, we refused to execute a setuid script stored on
4248  * a filesystem mounted nosuid and/or noexec. This meant that we probed for the
4249  * existence of the appropriate filesystem-statting function, and behaved
4250  * accordingly. But even though suidperl is long gone, we must still include
4251  * those probes for the benefit of modules like Filesys::Df, which expect the
4252  * results of those probes to be stored in %Config; see RT#126368. So mention
4253  * the relevant cpp symbols here, to ensure that metaconfig will include their
4254  * probes in the generated Configure:
4255  *
4256  * I_SYSSTATVFS HAS_FSTATVFS
4257  * I_SYSMOUNT
4258  * I_STATFS     HAS_FSTATFS     HAS_GETFSSTAT
4259  * I_MNTENT     HAS_GETMNTENT   HAS_HASMNTOPT
4260  */
4261
4262
4263 #ifdef SETUID_SCRIPTS_ARE_SECURE_NOW
4264 /* Don't even need this function.  */
4265 #else
4266 STATIC void
4267 S_validate_suid(pTHX_ PerlIO *rsfp)
4268 {
4269     const Uid_t  my_uid = PerlProc_getuid();
4270     const Uid_t my_euid = PerlProc_geteuid();
4271     const Gid_t  my_gid = PerlProc_getgid();
4272     const Gid_t my_egid = PerlProc_getegid();
4273
4274     PERL_ARGS_ASSERT_VALIDATE_SUID;
4275
4276     if (my_euid != my_uid || my_egid != my_gid) {       /* (suidperl doesn't exist, in fact) */
4277         int fd = PerlIO_fileno(rsfp);
4278         Stat_t statbuf;
4279         if (fd < 0 || PerlLIO_fstat(fd, &statbuf) < 0) { /* may be either wrapped or real suid */
4280             Perl_croak_nocontext( "Illegal suidscript");
4281         }
4282         if ((my_euid != my_uid && my_euid == statbuf.st_uid && statbuf.st_mode & S_ISUID)
4283             ||
4284             (my_egid != my_gid && my_egid == statbuf.st_gid && statbuf.st_mode & S_ISGID)
4285             )
4286             if (!PL_do_undump)
4287                 Perl_croak(aTHX_ "YOU HAVEN'T DISABLED SET-ID SCRIPTS IN THE KERNEL YET!\n\
4288 FIX YOUR KERNEL, PUT A C WRAPPER AROUND THIS SCRIPT, OR USE -u AND UNDUMP!\n");
4289         /* not set-id, must be wrapped */
4290     }
4291 }
4292 #endif /* SETUID_SCRIPTS_ARE_SECURE_NOW */
4293
4294 STATIC void
4295 S_find_beginning(pTHX_ SV* linestr_sv, PerlIO *rsfp)
4296 {
4297     const char *s;
4298     const char *s2;
4299
4300     PERL_ARGS_ASSERT_FIND_BEGINNING;
4301
4302     /* skip forward in input to the real script? */
4303
4304     do {
4305         if ((s = sv_gets(linestr_sv, rsfp, 0)) == NULL)
4306             Perl_croak(aTHX_ "No Perl script found in input\n");
4307         s2 = s;
4308     } while (!(*s == '#' && s[1] == '!' && ((s = instr(s,"perl")) || (s = instr(s2,"PERL")))));
4309     PerlIO_ungetc(rsfp, '\n');          /* to keep line count right */
4310     while (*s && !(isSPACE (*s) || *s == '#')) s++;
4311     s2 = s;
4312     while (*s == ' ' || *s == '\t') s++;
4313     if (*s++ == '-') {
4314         while (isDIGIT(s2[-1]) || s2[-1] == '-' || s2[-1] == '.'
4315                || s2[-1] == '_') s2--;
4316         if (strBEGINs(s2-4,"perl"))
4317             while ((s = moreswitches(s)))
4318                 ;
4319     }
4320 }
4321
4322
4323 STATIC void
4324 S_init_ids(pTHX)
4325 {
4326     /* no need to do anything here any more if we don't
4327      * do tainting. */
4328 #ifndef NO_TAINT_SUPPORT
4329     const Uid_t my_uid = PerlProc_getuid();
4330     const Uid_t my_euid = PerlProc_geteuid();
4331     const Gid_t my_gid = PerlProc_getgid();
4332     const Gid_t my_egid = PerlProc_getegid();
4333
4334     PERL_UNUSED_CONTEXT;
4335
4336     /* Should not happen: */
4337     CHECK_MALLOC_TAINT(my_uid && (my_euid != my_uid || my_egid != my_gid));
4338     TAINTING_set( TAINTING_get | (my_uid && (my_euid != my_uid || my_egid != my_gid)) );
4339 #endif
4340     /* BUG */
4341     /* PSz 27 Feb 04
4342      * Should go by suidscript, not uid!=euid: why disallow
4343      * system("ls") in scripts run from setuid things?
4344      * Or, is this run before we check arguments and set suidscript?
4345      * What about SETUID_SCRIPTS_ARE_SECURE_NOW: could we use fdscript then?
4346      * (We never have suidscript, can we be sure to have fdscript?)
4347      * Or must then go by UID checks? See comments in forbid_setid also.
4348      */
4349 }
4350
4351 /* This is used very early in the lifetime of the program,
4352  * before even the options are parsed, so PL_tainting has
4353  * not been initialized properly.  */
4354 bool
4355 Perl_doing_taint(int argc, char *argv[], char *envp[])
4356 {
4357 #ifndef PERL_IMPLICIT_SYS
4358     /* If we have PERL_IMPLICIT_SYS we can't call getuid() et alia
4359      * before we have an interpreter-- and the whole point of this
4360      * function is to be called at such an early stage.  If you are on
4361      * a system with PERL_IMPLICIT_SYS but you do have a concept of
4362      * "tainted because running with altered effective ids', you'll
4363      * have to add your own checks somewhere in here.  The most known
4364      * sample of 'implicitness' is Win32, which doesn't have much of
4365      * concept of 'uids'. */
4366     Uid_t uid  = PerlProc_getuid();
4367     Uid_t euid = PerlProc_geteuid();
4368     Gid_t gid  = PerlProc_getgid();
4369     Gid_t egid = PerlProc_getegid();
4370     (void)envp;
4371
4372 #ifdef VMS
4373     uid  |=  gid << 16;
4374     euid |= egid << 16;
4375 #endif
4376     if (uid && (euid != uid || egid != gid))
4377         return 1;
4378 #endif /* !PERL_IMPLICIT_SYS */
4379     /* This is a really primitive check; environment gets ignored only
4380      * if -T are the first chars together; otherwise one gets
4381      *  "Too late" message. */
4382     if ( argc > 1 && argv[1][0] == '-'
4383          && isALPHA_FOLD_EQ(argv[1][1], 't'))
4384         return 1;
4385     return 0;
4386 }
4387
4388 /* Passing the flag as a single char rather than a string is a slight space
4389    optimisation.  The only message that isn't /^-.$/ is
4390    "program input from stdin", which is substituted in place of '\0', which
4391    could never be a command line flag.  */
4392 STATIC void
4393 S_forbid_setid(pTHX_ const char flag, const bool suidscript) /* g */
4394 {
4395     char string[3] = "-x";
4396     const char *message = "program input from stdin";
4397
4398     PERL_UNUSED_CONTEXT;
4399     if (flag) {
4400         string[1] = flag;
4401         message = string;
4402     }
4403
4404 #ifdef SETUID_SCRIPTS_ARE_SECURE_NOW
4405     if (PerlProc_getuid() != PerlProc_geteuid())
4406         Perl_croak(aTHX_ "No %s allowed while running setuid", message);
4407     if (PerlProc_getgid() != PerlProc_getegid())
4408         Perl_croak(aTHX_ "No %s allowed while running setgid", message);
4409 #endif /* SETUID_SCRIPTS_ARE_SECURE_NOW */
4410     if (suidscript)
4411         Perl_croak(aTHX_ "No %s allowed with (suid) fdscript", message);
4412 }
4413
4414 void
4415 Perl_init_dbargs(pTHX)
4416 {
4417     AV *const args = PL_dbargs = GvAV(gv_AVadd((gv_fetchpvs("DB::args",
4418                                                             GV_ADDMULTI,
4419                                                             SVt_PVAV))));
4420
4421     if (AvREAL(args)) {
4422         /* Someone has already created it.
4423            It might have entries, and if we just turn off AvREAL(), they will
4424            "leak" until global destruction.  */
4425         av_clear(args);
4426         if (SvTIED_mg((const SV *)args, PERL_MAGIC_tied))
4427             Perl_croak(aTHX_ "Cannot set tied @DB::args");
4428     }
4429     AvREIFY_only(PL_dbargs);
4430 }
4431
4432 void
4433 Perl_init_debugger(pTHX)
4434 {
4435     HV * const ostash = PL_curstash;
4436     MAGIC *mg;
4437
4438     PL_curstash = (HV *)SvREFCNT_inc_simple(PL_debstash);
4439
4440     Perl_init_dbargs(aTHX);
4441     PL_DBgv = MUTABLE_GV(
4442         SvREFCNT_inc(gv_fetchpvs("DB::DB", GV_ADDMULTI, SVt_PVGV))
4443     );
4444     PL_DBline = MUTABLE_GV(
4445         SvREFCNT_inc(gv_fetchpvs("DB::dbline", GV_ADDMULTI, SVt_PVAV))
4446     );
4447     PL_DBsub = MUTABLE_GV(SvREFCNT_inc(
4448         gv_HVadd(gv_fetchpvs("DB::sub", GV_ADDMULTI, SVt_PVHV))
4449     ));
4450     PL_DBsingle = GvSV((gv_fetchpvs("DB::single", GV_ADDMULTI, SVt_PV)));
4451     if (!SvIOK(PL_DBsingle))
4452         sv_setiv(PL_DBsingle, 0);
4453     mg = sv_magicext(PL_DBsingle, NULL, PERL_MAGIC_debugvar, &PL_vtbl_debugvar, 0, 0);
4454     mg->mg_private = DBVARMG_SINGLE;
4455     SvSETMAGIC(PL_DBsingle);
4456
4457     PL_DBtrace = GvSV((gv_fetchpvs("DB::trace", GV_ADDMULTI, SVt_PV)));
4458     if (!SvIOK(PL_DBtrace))
4459         sv_setiv(PL_DBtrace, 0);
4460     mg = sv_magicext(PL_DBtrace, NULL, PERL_MAGIC_debugvar, &PL_vtbl_debugvar, 0, 0);
4461     mg->mg_private = DBVARMG_TRACE;
4462     SvSETMAGIC(PL_DBtrace);
4463
4464     PL_DBsignal = GvSV((gv_fetchpvs("DB::signal", GV_ADDMULTI, SVt_PV)));
4465     if (!SvIOK(PL_DBsignal))
4466         sv_setiv(PL_DBsignal, 0);
4467     mg = sv_magicext(PL_DBsignal, NULL, PERL_MAGIC_debugvar, &PL_vtbl_debugvar, 0, 0);
4468     mg->mg_private = DBVARMG_SIGNAL;
4469     SvSETMAGIC(PL_DBsignal);
4470
4471     SvREFCNT_dec(PL_curstash);
4472     PL_curstash = ostash;
4473 }
4474
4475 #ifndef STRESS_REALLOC
4476 #define REASONABLE(size) (size)
4477 #define REASONABLE_but_at_least(size,min) (size)
4478 #else
4479 #define REASONABLE(size) (1) /* unreasonable */
4480 #define REASONABLE_but_at_least(size,min) (min)
4481 #endif
4482
4483 void
4484 Perl_init_stacks(pTHX)
4485 {
4486     SSize_t size;
4487
4488 #ifdef PERL_RC_STACK
4489     const UV make_real = 1;
4490 #else
4491     const UV make_real = 0;
4492 #endif
4493     /* start with 128-item stack and 8K cxstack */
4494     PL_curstackinfo = new_stackinfo_flags(REASONABLE(128),
4495                                  REASONABLE(8192/sizeof(PERL_CONTEXT) - 1),
4496                                  make_real);
4497     PL_curstackinfo->si_type = PERLSI_MAIN;
4498 #if defined DEBUGGING && !defined DEBUGGING_RE_ONLY
4499     PL_curstackinfo->si_stack_hwm = 0;
4500 #endif
4501     PL_curstack = PL_curstackinfo->si_stack;
4502     PL_mainstack = PL_curstack;         /* remember in case we switch stacks */
4503
4504     PL_stack_base = AvARRAY(PL_curstack);
4505     PL_stack_sp = PL_stack_base;
4506     PL_stack_max = PL_stack_base + AvMAX(PL_curstack);
4507
4508     Newxz(PL_tmps_stack,REASONABLE(128),SV*);
4509     PL_tmps_floor = -1;
4510     PL_tmps_ix = -1;
4511     PL_tmps_max = REASONABLE(128);
4512
4513     Newxz(PL_markstack, REASONABLE(32), Stack_off_t);
4514     PL_markstack_ptr = PL_markstack;
4515     PL_markstack_max = PL_markstack + REASONABLE(32);
4516
4517     SET_MARK_OFFSET;
4518
4519     Newxz(PL_scopestack,REASONABLE(32),I32);
4520 #ifdef DEBUGGING
4521     Newxz(PL_scopestack_name,REASONABLE(32),const char*);
4522 #endif
4523     PL_scopestack_ix = 0;
4524     PL_scopestack_max = REASONABLE(32);
4525
4526     size = REASONABLE_but_at_least(128,SS_MAXPUSH);
4527     Newxz(PL_savestack, size, ANY);
4528     PL_savestack_ix = 0;
4529     /*PL_savestack_max lies: it always has SS_MAXPUSH more than it claims */
4530     PL_savestack_max = size - SS_MAXPUSH;
4531 }
4532
4533 #undef REASONABLE
4534
4535 STATIC void
4536 S_nuke_stacks(pTHX)
4537 {
4538     while (PL_curstackinfo->si_next)
4539         PL_curstackinfo = PL_curstackinfo->si_next;
4540     while (PL_curstackinfo) {
4541         PERL_SI *p = PL_curstackinfo->si_prev;
4542         /* curstackinfo->si_stack got nuked by sv_free_arenas() */
4543         Safefree(PL_curstackinfo->si_cxstack);
4544         Safefree(PL_curstackinfo);
4545         PL_curstackinfo = p;
4546     }
4547     Safefree(PL_tmps_stack);
4548     Safefree(PL_markstack);
4549     Safefree(PL_scopestack);
4550 #ifdef DEBUGGING
4551     Safefree(PL_scopestack_name);
4552 #endif
4553     Safefree(PL_savestack);
4554 }
4555
4556 void
4557 Perl_populate_isa(pTHX_ const char *name, STRLEN len, ...)
4558 {
4559     GV *const gv = gv_fetchpvn(name, len, GV_ADD | GV_ADDMULTI, SVt_PVAV);
4560     AV *const isa = GvAVn(gv);
4561     va_list args;
4562
4563     PERL_ARGS_ASSERT_POPULATE_ISA;
4564
4565     if(AvFILLp(isa) != -1)
4566         return;
4567
4568     /* NOTE: No support for tied ISA */
4569
4570     va_start(args, len);
4571     do {
4572         const char *const parent = va_arg(args, const char*);
4573         size_t parent_len;
4574
4575         if (!parent)
4576             break;
4577         parent_len = va_arg(args, size_t);
4578
4579         /* Arguments are supplied with a trailing ::  */
4580         assert(parent_len > 2);
4581         assert(parent[parent_len - 1] == ':');
4582         assert(parent[parent_len - 2] == ':');
4583         av_push(isa, newSVpvn(parent, parent_len - 2));
4584         (void) gv_fetchpvn(parent, parent_len, GV_ADD, SVt_PVGV);
4585     } while (1);
4586     va_end(args);
4587 }
4588
4589
4590 STATIC void
4591 S_init_predump_symbols(pTHX)
4592 {
4593     GV *tmpgv;
4594     IO *io;
4595
4596     sv_setpvs(get_sv("\"", GV_ADD), " ");
4597     PL_ofsgv = (GV*)SvREFCNT_inc(gv_fetchpvs(",", GV_ADD|GV_NOTQUAL, SVt_PV));
4598
4599
4600     /* Historically, PVIOs were blessed into IO::Handle, unless
4601        FileHandle was loaded, in which case they were blessed into
4602        that. Action at a distance.
4603        However, if we simply bless into IO::Handle, we break code
4604        that assumes that PVIOs will have (among others) a seek
4605        method. IO::File inherits from IO::Handle and IO::Seekable,
4606        and provides the needed methods. But if we simply bless into
4607        it, then we break code that assumed that by loading
4608        IO::Handle, *it* would work.
4609        So a compromise is to set up the correct @IO::File::ISA,
4610        so that code that does C<use IO::Handle>; will still work.
4611     */
4612
4613     Perl_populate_isa(aTHX_ STR_WITH_LEN("IO::File::ISA"),
4614                       STR_WITH_LEN("IO::Handle::"),
4615                       STR_WITH_LEN("IO::Seekable::"),
4616                       STR_WITH_LEN("Exporter::"),
4617                       NULL);
4618
4619     PL_stdingv = gv_fetchpvs("STDIN", GV_ADD|GV_NOTQUAL, SVt_PVIO);
4620     GvMULTI_on(PL_stdingv);
4621     io = GvIOp(PL_stdingv);
4622     IoTYPE(io) = IoTYPE_RDONLY;
4623     IoIFP(io) = PerlIO_stdin();
4624     tmpgv = gv_fetchpvs("stdin", GV_ADD|GV_NOTQUAL, SVt_PV);
4625     GvMULTI_on(tmpgv);
4626     GvIOp(tmpgv) = MUTABLE_IO(SvREFCNT_inc_simple(io));
4627
4628     tmpgv = gv_fetchpvs("STDOUT", GV_ADD|GV_NOTQUAL, SVt_PVIO);
4629     GvMULTI_on(tmpgv);
4630     io = GvIOp(tmpgv);
4631     IoTYPE(io) = IoTYPE_WRONLY;
4632     IoOFP(io) = IoIFP(io) = PerlIO_stdout();
4633     setdefout(tmpgv);
4634     tmpgv = gv_fetchpvs("stdout", GV_ADD|GV_NOTQUAL, SVt_PV);
4635     GvMULTI_on(tmpgv);
4636     GvIOp(tmpgv) = MUTABLE_IO(SvREFCNT_inc_simple(io));
4637
4638     PL_stderrgv = gv_fetchpvs("STDERR", GV_ADD|GV_NOTQUAL, SVt_PVIO);
4639     GvMULTI_on(PL_stderrgv);
4640     io = GvIOp(PL_stderrgv);
4641     IoTYPE(io) = IoTYPE_WRONLY;
4642     IoOFP(io) = IoIFP(io) = PerlIO_stderr();
4643     tmpgv = gv_fetchpvs("stderr", GV_ADD|GV_NOTQUAL, SVt_PV);
4644     GvMULTI_on(tmpgv);
4645     GvIOp(tmpgv) = MUTABLE_IO(SvREFCNT_inc_simple(io));
4646
4647     PL_statname = newSVpvs("");         /* last filename we did stat on */
4648 }
4649
4650 void
4651 Perl_init_argv_symbols(pTHX_ int argc, char **argv)
4652 {
4653     PERL_ARGS_ASSERT_INIT_ARGV_SYMBOLS;
4654
4655     argc--,argv++;      /* skip name of script */
4656     if (PL_doswitches) {
4657         for (; argc > 0 && **argv == '-'; argc--,argv++) {
4658             char *s;
4659             if (!argv[0][1])
4660                 break;
4661             if (argv[0][1] == '-' && !argv[0][2]) {
4662                 argc--,argv++;
4663                 break;
4664             }
4665             if ((s = strchr(argv[0], '='))) {
4666                 const char *const start_name = argv[0] + 1;
4667                 sv_setpv(GvSV(gv_fetchpvn_flags(start_name, s - start_name,
4668                                                 TRUE, SVt_PV)), s + 1);
4669             }
4670             else
4671                 sv_setiv(GvSV(gv_fetchpv(argv[0]+1, GV_ADD, SVt_PV)),1);
4672         }
4673     }
4674     if ((PL_argvgv = gv_fetchpvs("ARGV", GV_ADD|GV_NOTQUAL, SVt_PVAV))) {
4675         SvREFCNT_inc_simple_void_NN(PL_argvgv);
4676         GvMULTI_on(PL_argvgv);
4677         av_clear(GvAVn(PL_argvgv));
4678         for (; argc > 0; argc--,argv++) {
4679             SV * const sv = newSVpv(argv[0],0);
4680             av_push(GvAV(PL_argvgv),sv);
4681             if (!(PL_unicode & PERL_UNICODE_LOCALE_FLAG) || PL_utf8locale) {
4682                  if (PL_unicode & PERL_UNICODE_ARGV_FLAG)
4683                       SvUTF8_on(sv);
4684             }
4685             if (PL_unicode & PERL_UNICODE_WIDESYSCALLS_FLAG) /* Sarathy? */
4686                  (void)sv_utf8_decode(sv);
4687         }
4688     }
4689
4690     if (PL_inplace && (!PL_argvgv || AvFILL(GvAV(PL_argvgv)) == -1))
4691         Perl_ck_warner_d(aTHX_ packWARN(WARN_INPLACE),
4692                          "-i used with no filenames on the command line, "
4693                          "reading from STDIN");
4694 }
4695
4696 STATIC void
4697 S_init_postdump_symbols(pTHX_ int argc, char **argv, char **env)
4698 {
4699     GV* tmpgv;
4700
4701     PERL_ARGS_ASSERT_INIT_POSTDUMP_SYMBOLS;
4702
4703     PL_toptarget = newSV_type(SVt_PVIV);
4704     SvPVCLEAR(PL_toptarget);
4705     PL_bodytarget = newSV_type(SVt_PVIV);
4706     SvPVCLEAR(PL_bodytarget);
4707     PL_formtarget = PL_bodytarget;
4708
4709     TAINT;
4710
4711     init_argv_symbols(argc,argv);
4712
4713     if ((tmpgv = gv_fetchpvs("0", GV_ADD|GV_NOTQUAL, SVt_PV))) {
4714         sv_setpv(GvSV(tmpgv),PL_origfilename);
4715     }
4716     if ((PL_envgv = gv_fetchpvs("ENV", GV_ADD|GV_NOTQUAL, SVt_PVHV))) {
4717         HV *hv;
4718         bool env_is_not_environ;
4719         SvREFCNT_inc_simple_void_NN(PL_envgv);
4720         GvMULTI_on(PL_envgv);
4721         hv = GvHVn(PL_envgv);
4722         hv_magic(hv, NULL, PERL_MAGIC_env);
4723 #if defined(USE_ENVIRON_ARRAY) || defined(WIN32)
4724         /* Note that if the supplied env parameter is actually a copy
4725            of the global environ then it may now point to free'd memory
4726            if the environment has been modified since. To avoid this
4727            problem we treat env==NULL as meaning 'use the default'
4728         */
4729         if (!env)
4730             env = environ;
4731         env_is_not_environ = env != environ;
4732         if (env_is_not_environ
4733 #  ifdef USE_ITHREADS
4734             && PL_curinterp == aTHX
4735 #  endif
4736            )
4737         {
4738             environ[0] = NULL;
4739         }
4740         if (env) {
4741           HV *dups = newHV();
4742           char **env_copy = env;
4743           size_t count;
4744
4745           while (*env_copy) {
4746               ++env_copy;
4747           }
4748
4749           count = env_copy - env;
4750
4751           if (count > PERL_HASH_DEFAULT_HvMAX) {
4752               /* This might be an over-estimate (due to dups and other skips),
4753                * but if so, likely it won't hurt much.
4754                * A straw poll of login environments I have suggests that
4755                * between 23 and 52 environment variables are typical (and no
4756                * dups). As the default hash size is 8 buckets, expanding in
4757                * advance saves between 2 and 3 splits in the loop below. */
4758               hv_ksplit(hv, count);
4759           }
4760
4761
4762           for (; *env; env++) {
4763               char *old_var = *env;
4764               char *s = strchr(old_var, '=');
4765               STRLEN nlen;
4766               SV *sv;
4767
4768               if (!s || s == old_var)
4769                   continue;
4770
4771               nlen = s - old_var;
4772
4773               /* It's tempting to think that this hv_exists/hv_store pair should
4774                * be replaced with a single hv_fetch with the LVALUE flag true.
4775                * However, hv has magic, and if you follow the code in hv_common
4776                * then for LVALUE fetch it recurses once, whereas exists and
4777                * store do not recurse. Hence internally there would be no
4778                * difference in the complexity of the code run. Moreover, all
4779                * calls pass through "is there magic?" special case code, which
4780                * in turn has its own #ifdef ENV_IS_CASELESS special case special
4781                * case. Hence this code shouldn't change, as doing so won't give
4782                * any meaningful speedup, and might well add bugs. */
4783
4784             if (hv_exists(hv, old_var, nlen)) {
4785                 SV **dup;
4786                 const char *name = savepvn(old_var, nlen);
4787
4788                 /* make sure we use the same value as getenv(), otherwise code that
4789                    uses getenv() (like setlocale()) might see a different value to %ENV
4790                  */
4791                 sv = newSVpv(PerlEnv_getenv(name), 0);
4792
4793                 /* keep a count of the dups of this name so we can de-dup environ later */
4794                 dup = hv_fetch(dups, name, nlen, TRUE);
4795                 if (*dup) {
4796                     sv_inc(*dup);
4797                 }
4798
4799                 Safefree(name);
4800             }
4801             else {
4802                 sv = newSVpv(s+1, 0);
4803             }
4804             (void)hv_store(hv, old_var, nlen, sv, 0);
4805             if (env_is_not_environ)
4806                 mg_set(sv);
4807           }
4808           if (HvTOTALKEYS(dups)) {
4809               /* environ has some duplicate definitions, remove them */
4810               HE *entry;
4811               hv_iterinit(dups);
4812               while ((entry = hv_iternext_flags(dups, 0))) {
4813                   STRLEN nlen;
4814                   const char *name = HePV(entry, nlen);
4815                   IV count = SvIV(HeVAL(entry));
4816                   IV i;
4817                   SV **valp = hv_fetch(hv, name, nlen, 0);
4818
4819                   assert(valp);
4820
4821                   /* try to remove any duplicate names, depending on the
4822                    * implementation used in my_setenv() the iteration might
4823                    * not be necessary, but let's be safe.
4824                    */
4825                   for (i = 0; i < count; ++i)
4826                       my_setenv(name, 0);
4827
4828                   /* and set it back to the value we set $ENV{name} to */
4829                   my_setenv(name, SvPV_nolen(*valp));
4830               }
4831           }
4832           SvREFCNT_dec_NN(dups);
4833       }
4834 #endif /* USE_ENVIRON_ARRAY */
4835     }
4836     TAINT_NOT;
4837
4838     /* touch @F array to prevent spurious warnings 20020415 MJD */
4839     if (PL_minus_a) {
4840       (void) get_av("main::F", GV_ADD | GV_ADDMULTI);
4841     }
4842 }
4843
4844 STATIC void
4845 S_init_perllib(pTHX)
4846 {
4847 #ifndef VMS
4848     const char *perl5lib = NULL;
4849 #endif
4850     const char *s;
4851 #if defined(WIN32) && !defined(PERL_IS_MINIPERL)
4852     STRLEN len;
4853 #endif
4854
4855     if (!TAINTING_get) {
4856 #ifndef VMS
4857         perl5lib = PerlEnv_getenv("PERL5LIB");
4858         if (perl5lib && *perl5lib != '\0')
4859             incpush_use_sep(perl5lib, 0, INCPUSH_ADD_SUB_DIRS);
4860         else {
4861             s = PerlEnv_getenv("PERLLIB");
4862             if (s)
4863                 incpush_use_sep(s, 0, 0);
4864         }
4865 #else /* VMS */
4866         /* Treat PERL5?LIB as a possible search list logical name -- the
4867          * "natural" VMS idiom for a Unix path string.  We allow each
4868          * element to be a set of |-separated directories for compatibility.
4869          */
4870         char buf[256];
4871         int idx = 0;
4872         if (vmstrnenv("PERL5LIB",buf,0,NULL,0))
4873             do {
4874                 incpush_use_sep(buf, 0, INCPUSH_ADD_SUB_DIRS);
4875             } while (vmstrnenv("PERL5LIB",buf,++idx,NULL,0));
4876         else {
4877             while (vmstrnenv("PERLLIB",buf,idx++,NULL,0))
4878                 incpush_use_sep(buf, 0, 0);
4879         }
4880 #endif /* VMS */
4881     }
4882
4883 #ifndef PERL_IS_MINIPERL
4884     /* miniperl gets just -I..., the split of $ENV{PERL5LIB}, and "." in @INC
4885        (and not the architecture specific directories from $ENV{PERL5LIB}) */
4886
4887 #include "perl_inc_macro.h"
4888 /* Use the ~-expanded versions of APPLLIB (undocumented),
4889     SITEARCH, SITELIB, VENDORARCH, VENDORLIB, ARCHLIB and PRIVLIB
4890 */
4891     INCPUSH_APPLLIB_EXP
4892     INCPUSH_SITEARCH_EXP
4893     INCPUSH_SITELIB_EXP
4894     INCPUSH_PERL_VENDORARCH_EXP
4895     INCPUSH_PERL_VENDORLIB_EXP
4896     INCPUSH_ARCHLIB_EXP
4897     INCPUSH_PRIVLIB_EXP
4898     INCPUSH_PERL_OTHERLIBDIRS
4899     INCPUSH_PERL5LIB
4900     INCPUSH_APPLLIB_OLD_EXP
4901     INCPUSH_SITELIB_STEM
4902     INCPUSH_PERL_VENDORLIB_STEM
4903     INCPUSH_PERL_OTHERLIBDIRS_ARCHONLY
4904
4905 #endif /* !PERL_IS_MINIPERL */
4906
4907     if (!TAINTING_get) {
4908 #if !defined(PERL_IS_MINIPERL) && defined(DEFAULT_INC_EXCLUDES_DOT)
4909         const char * const unsafe = PerlEnv_getenv("PERL_USE_UNSAFE_INC");
4910         if (unsafe && strEQ(unsafe, "1"))
4911 #endif
4912           S_incpush(aTHX_ STR_WITH_LEN("."), 0);
4913     }
4914 }
4915
4916 #if defined(DOSISH)
4917 #    define PERLLIB_SEP ';'
4918 #elif defined(__VMS)
4919 #    define PERLLIB_SEP PL_perllib_sep
4920 #else
4921 #    define PERLLIB_SEP ':'
4922 #endif
4923 #ifndef PERLLIB_MANGLE
4924 #  define PERLLIB_MANGLE(s,n) (s)
4925 #endif
4926
4927 #ifndef PERL_IS_MINIPERL
4928 /* Push a directory onto @INC if it exists.
4929    Generate a new SV if we do this, to save needing to copy the SV we push
4930    onto @INC  */
4931 STATIC SV *
4932 S_incpush_if_exists(pTHX_ AV *const av, SV *dir, SV *const stem)
4933 {
4934     Stat_t tmpstatbuf;
4935
4936     PERL_ARGS_ASSERT_INCPUSH_IF_EXISTS;
4937
4938     if (PerlLIO_stat(SvPVX_const(dir), &tmpstatbuf) >= 0 &&
4939         S_ISDIR(tmpstatbuf.st_mode)) {
4940         av_push(av, dir);
4941         dir = newSVsv(stem);
4942     } else {
4943         /* Truncate dir back to stem.  */
4944         SvCUR_set(dir, SvCUR(stem));
4945     }
4946     return dir;
4947 }
4948 #endif
4949
4950 STATIC SV *
4951 S_mayberelocate(pTHX_ const char *const dir, STRLEN len, U32 flags)
4952 {
4953     const U8 canrelocate = (U8)flags & INCPUSH_CAN_RELOCATE;
4954     SV *libdir;
4955
4956     PERL_ARGS_ASSERT_MAYBERELOCATE;
4957     assert(len > 0);
4958
4959     /* I am not convinced that this is valid when PERLLIB_MANGLE is
4960        defined to so something (in os2/os2.c), but the code has been
4961        this way, ignoring any possible changed of length, since
4962        760ac839baf413929cd31cc32ffd6dba6b781a81 (5.003_02) so I'll leave
4963        it be.  */
4964     libdir = newSVpvn(PERLLIB_MANGLE(dir, len), len);
4965
4966 #ifdef VMS
4967     {
4968         char *unix;
4969
4970         if ((unix = tounixspec_ts(SvPV(libdir,len),NULL)) != NULL) {
4971             len = strlen(unix);
4972             while (len > 1 && unix[len-1] == '/') len--;  /* Cosmetic */
4973             sv_usepvn(libdir,unix,len);
4974         }
4975         else
4976             PerlIO_printf(Perl_error_log,
4977                           "Failed to unixify @INC element \"%s\"\n",
4978                           SvPV_nolen_const(libdir));
4979     }
4980 #endif
4981
4982         /* Do the if() outside the #ifdef to avoid warnings about an unused
4983            parameter.  */
4984         if (canrelocate) {
4985 #ifdef PERL_RELOCATABLE_INC
4986         /*
4987          * Relocatable include entries are marked with a leading .../
4988          *
4989          * The algorithm is
4990          * 0: Remove that leading ".../"
4991          * 1: Remove trailing executable name (anything after the last '/')
4992          *    from the perl path to give a perl prefix
4993          * Then
4994          * While the @INC element starts "../" and the prefix ends with a real
4995          * directory (ie not . or ..) chop that real directory off the prefix
4996          * and the leading "../" from the @INC element. ie a logical "../"
4997          * cleanup
4998          * Finally concatenate the prefix and the remainder of the @INC element
4999          * The intent is that /usr/local/bin/perl and .../../lib/perl5
5000          * generates /usr/local/lib/perl5
5001          */
5002             const char *libpath = SvPVX(libdir);
5003             STRLEN libpath_len = SvCUR(libdir);
5004             if (memBEGINs(libpath, libpath_len, ".../")) {
5005                 /* Game on!  */
5006                 SV * const caret_X = get_sv("\030", 0);
5007                 /* Going to use the SV just as a scratch buffer holding a C
5008                    string:  */
5009                 SV *prefix_sv;
5010                 char *prefix;
5011                 char *lastslash;
5012
5013                 /* $^X is *the* source of taint if tainting is on, hence
5014                    SvPOK() won't be true.  */
5015                 assert(caret_X);
5016                 assert(SvPOKp(caret_X));
5017                 prefix_sv = newSVpvn_flags(SvPVX(caret_X), SvCUR(caret_X),
5018                                            SvUTF8(caret_X));
5019                 /* Firstly take off the leading .../
5020                    If all else fail we'll do the paths relative to the current
5021                    directory.  */
5022                 sv_chop(libdir, libpath + 4);
5023                 /* Don't use SvPV as we're intentionally bypassing taining,
5024                    mortal copies that the mg_get of tainting creates, and
5025                    corruption that seems to come via the save stack.
5026                    I guess that the save stack isn't correctly set up yet.  */
5027                 libpath = SvPVX(libdir);
5028                 libpath_len = SvCUR(libdir);
5029
5030                 prefix = SvPVX(prefix_sv);
5031                 lastslash = (char *) my_memrchr(prefix, '/',
5032                              SvEND(prefix_sv) - prefix);
5033
5034                 /* First time in with the *lastslash = '\0' we just wipe off
5035                    the trailing /perl from (say) /usr/foo/bin/perl
5036                 */
5037                 if (lastslash) {
5038                     SV *tempsv;
5039                     while ((*lastslash = '\0'), /* Do that, come what may.  */
5040                            (   memBEGINs(libpath, libpath_len, "../")
5041                             && (lastslash =
5042                                   (char *) my_memrchr(prefix, '/',
5043                                                    SvEND(prefix_sv) - prefix))))
5044                     {
5045                         if (lastslash[1] == '\0'
5046                             || (lastslash[1] == '.'
5047                                 && (lastslash[2] == '/' /* ends "/."  */
5048                                     || (lastslash[2] == '/'
5049                                         && lastslash[3] == '/' /* or "/.."  */
5050                                         )))) {
5051                             /* Prefix ends "/" or "/." or "/..", any of which
5052                                are fishy, so don't do any more logical cleanup.
5053                             */
5054                             break;
5055                         }
5056                         /* Remove leading "../" from path  */
5057                         libpath += 3;
5058                         libpath_len -= 3;
5059                         /* Next iteration round the loop removes the last
5060                            directory name from prefix by writing a '\0' in
5061                            the while clause.  */
5062                     }
5063                     /* prefix has been terminated with a '\0' to the correct
5064                        length. libpath points somewhere into the libdir SV.
5065                        We need to join the 2 with '/' and drop the result into
5066                        libdir.  */
5067                     tempsv = Perl_newSVpvf(aTHX_ "%s/%s", prefix, libpath);
5068                     SvREFCNT_dec(libdir);
5069                     /* And this is the new libdir.  */
5070                     libdir = tempsv;
5071                     if (TAINTING_get &&
5072                         (PerlProc_getuid() != PerlProc_geteuid() ||
5073                          PerlProc_getgid() != PerlProc_getegid())) {
5074                         /* Need to taint relocated paths if running set ID  */
5075                         SvTAINTED_on(libdir);
5076                     }
5077                 }
5078                 SvREFCNT_dec(prefix_sv);
5079             }
5080 #endif
5081         }
5082     return libdir;
5083 }
5084
5085 STATIC void
5086 S_incpush(pTHX_ const char *const dir, STRLEN len, U32 flags)
5087 {
5088 #ifndef PERL_IS_MINIPERL
5089     const U8 using_sub_dirs
5090         = (U8)flags & (INCPUSH_ADD_VERSIONED_SUB_DIRS
5091                        |INCPUSH_ADD_ARCHONLY_SUB_DIRS|INCPUSH_ADD_OLD_VERS);
5092     const U8 add_versioned_sub_dirs
5093         = (U8)flags & INCPUSH_ADD_VERSIONED_SUB_DIRS;
5094     const U8 add_archonly_sub_dirs
5095         = (U8)flags & INCPUSH_ADD_ARCHONLY_SUB_DIRS;
5096 #ifdef PERL_INC_VERSION_LIST
5097     const U8 addoldvers  = (U8)flags & INCPUSH_ADD_OLD_VERS;
5098 #endif
5099 #endif
5100     const U8 unshift     = (U8)flags & INCPUSH_UNSHIFT;
5101     const U8 push_basedir = (flags & INCPUSH_NOT_BASEDIR) ? 0 : 1;
5102     AV *const inc = GvAVn(PL_incgv);
5103
5104     PERL_ARGS_ASSERT_INCPUSH;
5105     assert(len > 0);
5106
5107     /* Could remove this vestigial extra block, if we don't mind a lot of
5108        re-indenting diff noise.  */
5109     {
5110         SV *const libdir = mayberelocate(dir, len, flags);
5111         /* Change 20189146be79a0596543441fa369c6bf7f85103f, to fix RT#6665,
5112            arranged to unshift #! line -I onto the front of @INC. However,
5113            -I can add version and architecture specific libraries, and they
5114            need to go first. The old code assumed that it was always
5115            pushing. Hence to make it work, need to push the architecture
5116            (etc) libraries onto a temporary array, then "unshift" that onto
5117            the front of @INC.  */
5118 #ifndef PERL_IS_MINIPERL
5119         AV *const av = (using_sub_dirs) ? (unshift ? newAV() : inc) : NULL;
5120
5121         /*
5122          * BEFORE pushing libdir onto @INC we may first push version- and
5123          * archname-specific sub-directories.
5124          */
5125         if (using_sub_dirs) {
5126             SV *subdir = newSVsv(libdir);
5127 #ifdef PERL_INC_VERSION_LIST
5128             /* Configure terminates PERL_INC_VERSION_LIST with a NULL */
5129             const char * const incverlist[] = { PERL_INC_VERSION_LIST };
5130             const char * const *incver;
5131 #endif
5132
5133             if (add_versioned_sub_dirs) {
5134                 /* .../version/archname if -d .../version/archname */
5135                 sv_catpvs(subdir, "/" PERL_FS_VERSION "/" ARCHNAME);
5136                 subdir = S_incpush_if_exists(aTHX_ av, subdir, libdir);
5137
5138                 /* .../version if -d .../version */
5139                 sv_catpvs(subdir, "/" PERL_FS_VERSION);
5140                 subdir = S_incpush_if_exists(aTHX_ av, subdir, libdir);
5141             }
5142
5143 #ifdef PERL_INC_VERSION_LIST
5144             if (addoldvers) {
5145                 for (incver = incverlist; *incver; incver++) {
5146                     /* .../xxx if -d .../xxx */
5147                     Perl_sv_catpvf(aTHX_ subdir, "/%s", *incver);
5148                     subdir = S_incpush_if_exists(aTHX_ av, subdir, libdir);
5149                 }
5150             }
5151 #endif
5152
5153             if (add_archonly_sub_dirs) {
5154                 /* .../archname if -d .../archname */
5155                 sv_catpvs(subdir, "/" ARCHNAME);
5156                 subdir = S_incpush_if_exists(aTHX_ av, subdir, libdir);
5157
5158             }
5159
5160             assert (SvREFCNT(subdir) == 1);
5161             SvREFCNT_dec(subdir);
5162         }
5163 #endif /* !PERL_IS_MINIPERL */
5164         /* finally add this lib directory at the end of @INC */
5165         if (unshift) {
5166 #ifdef PERL_IS_MINIPERL
5167             const Size_t extra = 0;
5168 #else
5169             Size_t extra = av_count(av);
5170 #endif
5171             av_unshift(inc, extra + push_basedir);
5172             if (push_basedir)
5173                 av_store(inc, extra, libdir);
5174 #ifndef PERL_IS_MINIPERL
5175             while (extra--) {
5176                 /* av owns a reference, av_store() expects to be donated a
5177                    reference, and av expects to be sane when it's cleared.
5178                    If I wanted to be naughty and wrong, I could peek inside the
5179                    implementation of av_clear(), realise that it uses
5180                    SvREFCNT_dec() too, so av's array could be a run of NULLs,
5181                    and so directly steal from it (with a memcpy() to inc, and
5182                    then memset() to NULL them out. But people copy code from the
5183                    core expecting it to be best practise, so let's use the API.
5184                    Although studious readers will note that I'm not checking any
5185                    return codes.  */
5186                 av_store(inc, extra, SvREFCNT_inc(*av_fetch(av, extra, FALSE)));
5187             }
5188             SvREFCNT_dec(av);
5189 #endif
5190         }
5191         else if (push_basedir) {
5192             av_push(inc, libdir);
5193         }
5194
5195         if (!push_basedir) {
5196             assert (SvREFCNT(libdir) == 1);
5197             SvREFCNT_dec(libdir);
5198         }
5199     }
5200 }
5201
5202 STATIC void
5203 S_incpush_use_sep(pTHX_ const char *p, STRLEN len, U32 flags)
5204 {
5205     const char *s;
5206     const char *end;
5207     /* This logic has been broken out from S_incpush(). It may be possible to
5208        simplify it.  */
5209
5210     PERL_ARGS_ASSERT_INCPUSH_USE_SEP;
5211
5212     /* perl compiled with -DPERL_RELOCATABLE_INCPUSH will ignore the len
5213      * argument to incpush_use_sep.  This allows creation of relocatable
5214      * Perl distributions that patch the binary at install time.  Those
5215      * distributions will have to provide their own relocation tools; this
5216      * is not a feature otherwise supported by core Perl.
5217      */
5218 #ifndef PERL_RELOCATABLE_INCPUSH
5219     if (!len)
5220 #endif
5221         len = strlen(p);
5222
5223     end = p + len;
5224
5225     /* Break at all separators */
5226     while ((s = (const char*)memchr(p, PERLLIB_SEP, end - p))) {
5227         if (s == p) {
5228             /* skip any consecutive separators */
5229
5230             /* Uncomment the next line for PATH semantics */
5231             /* But you'll need to write tests */
5232             /* av_push(GvAVn(PL_incgv), newSVpvs(".")); */
5233         } else {
5234             incpush(p, (STRLEN)(s - p), flags);
5235         }
5236         p = s + 1;
5237     }
5238     if (p != end)
5239         incpush(p, (STRLEN)(end - p), flags);
5240
5241 }
5242
5243 void
5244 Perl_call_list(pTHX_ I32 oldscope, AV *paramList)
5245 {
5246     SV *atsv;
5247     volatile const line_t oldline = PL_curcop ? CopLINE(PL_curcop) : 0;
5248     CV *cv;
5249     STRLEN len;
5250     int ret;
5251     dJMPENV;
5252
5253     PERL_ARGS_ASSERT_CALL_LIST;
5254
5255     while (av_count(paramList) > 0) {
5256         cv = MUTABLE_CV(av_shift(paramList));
5257         if (PL_savebegin) {
5258             if (paramList == PL_beginav) {
5259                 /* save PL_beginav for compiler */
5260                 Perl_av_create_and_push(aTHX_ &PL_beginav_save, MUTABLE_SV(cv));
5261             }
5262             else if (paramList == PL_checkav) {
5263                 /* save PL_checkav for compiler */
5264                 Perl_av_create_and_push(aTHX_ &PL_checkav_save, MUTABLE_SV(cv));
5265             }
5266             else if (paramList == PL_unitcheckav) {
5267                 /* save PL_unitcheckav for compiler */
5268                 Perl_av_create_and_push(aTHX_ &PL_unitcheckav_save, MUTABLE_SV(cv));
5269             }
5270         } else {
5271             SAVEFREESV(cv);
5272         }
5273         JMPENV_PUSH(ret);
5274         switch (ret) {
5275         case 0:
5276             CALL_LIST_BODY(cv);
5277             atsv = ERRSV;
5278             (void)SvPV_const(atsv, len);
5279             if (len) {
5280                 PL_curcop = &PL_compiling;
5281                 CopLINE_set(PL_curcop, oldline);
5282                 if (paramList == PL_beginav)
5283                     sv_catpvs(atsv, "BEGIN failed--compilation aborted");
5284                 else
5285                     Perl_sv_catpvf(aTHX_ atsv,
5286                                    "%s failed--call queue aborted",
5287                                    paramList == PL_checkav ? "CHECK"
5288                                    : paramList == PL_initav ? "INIT"
5289                                    : paramList == PL_unitcheckav ? "UNITCHECK"
5290                                    : "END");
5291                 while (PL_scopestack_ix > oldscope)
5292                     LEAVE;
5293                 JMPENV_POP;
5294                 Perl_croak(aTHX_ "%" SVf, SVfARG(atsv));
5295             }
5296             break;
5297         case 1:
5298             STATUS_ALL_FAILURE;
5299             /* FALLTHROUGH */
5300         case 2:
5301             /* my_exit() was called */
5302             while (PL_scopestack_ix > oldscope)
5303                 LEAVE;
5304             FREETMPS;
5305             SET_CURSTASH(PL_defstash);
5306             PL_curcop = &PL_compiling;
5307             CopLINE_set(PL_curcop, oldline);
5308             JMPENV_POP;
5309             my_exit_jump();
5310             NOT_REACHED; /* NOTREACHED */
5311         case 3:
5312             if (PL_restartop) {
5313                 PL_curcop = &PL_compiling;
5314                 CopLINE_set(PL_curcop, oldline);
5315                 JMPENV_JUMP(3);
5316             }
5317             PerlIO_printf(Perl_error_log, "panic: restartop in call_list\n");
5318             FREETMPS;
5319             break;
5320         }
5321         JMPENV_POP;
5322     }
5323 }
5324
5325 /*
5326 =for apidoc my_exit
5327
5328 A wrapper for the C library L<exit(3)>, honoring what L<perlapi/PL_exit_flags>
5329 say to do.
5330
5331 =cut
5332 */
5333
5334 void
5335 Perl_my_exit(pTHX_ U32 status)
5336 {
5337     if (PL_exit_flags & PERL_EXIT_ABORT) {
5338         abort();
5339     }
5340     if (PL_exit_flags & PERL_EXIT_WARN) {
5341         PL_exit_flags |= PERL_EXIT_ABORT; /* Protect against reentrant calls */
5342         Perl_warn(aTHX_ "Unexpected exit %lu", (unsigned long)status);
5343         PL_exit_flags &= ~PERL_EXIT_ABORT;
5344     }
5345     switch (status) {
5346     case 0:
5347         STATUS_ALL_SUCCESS;
5348         break;
5349     case 1:
5350         STATUS_ALL_FAILURE;
5351         break;
5352     default:
5353         STATUS_EXIT_SET(status);
5354         break;
5355     }
5356     my_exit_jump();
5357 }
5358
5359 /*
5360 =for apidoc my_failure_exit
5361
5362 Exit the running Perl process with an error.
5363
5364 On non-VMS platforms, this is essentially equivalent to L</C<my_exit>>, using
5365 C<errno>, but forces an en error code of 255 if C<errno> is 0.
5366
5367 On VMS, it takes care to set the appropriate severity bits in the exit status.
5368
5369 =cut
5370 */
5371
5372 void
5373 Perl_my_failure_exit(pTHX)
5374 {
5375 #ifdef VMS
5376      /* We have been called to fall on our sword.  The desired exit code
5377       * should be already set in STATUS_UNIX, but could be shifted over
5378       * by 8 bits.  STATUS_UNIX_EXIT_SET will handle the cases where a
5379       * that code is set.
5380       *
5381       * If an error code has not been set, then force the issue.
5382       */
5383     if (MY_POSIX_EXIT) {
5384
5385         /* According to the die_exit.t tests, if errno is non-zero */
5386         /* It should be used for the error status. */
5387
5388         if (errno == EVMSERR) {
5389             STATUS_NATIVE = vaxc$errno;
5390         } else {
5391
5392             /* According to die_exit.t tests, if the child_exit code is */
5393             /* also zero, then we need to exit with a code of 255 */
5394             if ((errno != 0) && (errno < 256))
5395                 STATUS_UNIX_EXIT_SET(errno);
5396             else if (STATUS_UNIX < 255) {
5397                 STATUS_UNIX_EXIT_SET(255);
5398             }
5399
5400         }
5401
5402         /* The exit code could have been set by $? or vmsish which
5403          * means that it may not have fatal set.  So convert
5404          * success/warning codes to fatal with out changing
5405          * the POSIX status code.  The severity makes VMS native
5406          * status handling work, while UNIX mode programs use the
5407          * POSIX exit codes.
5408          */
5409          if ((STATUS_NATIVE & (STS$K_SEVERE|STS$K_ERROR)) == 0) {
5410             STATUS_NATIVE &= STS$M_COND_ID;
5411             STATUS_NATIVE |= STS$K_ERROR | STS$M_INHIB_MSG;
5412          }
5413     }
5414     else {
5415         /* Traditionally Perl on VMS always expects a Fatal Error. */
5416         if (vaxc$errno & 1) {
5417
5418             /* So force success status to failure */
5419             if (STATUS_NATIVE & 1)
5420                 STATUS_ALL_FAILURE;
5421         }
5422         else {
5423             if (!vaxc$errno) {
5424                 STATUS_UNIX = EINTR; /* In case something cares */
5425                 STATUS_ALL_FAILURE;
5426             }
5427             else {
5428                 int severity;
5429                 STATUS_NATIVE = vaxc$errno; /* Should already be this */
5430
5431                 /* Encode the severity code */
5432                 severity = STATUS_NATIVE & STS$M_SEVERITY;
5433                 STATUS_UNIX = (severity ? severity : 1) << 8;
5434
5435                 /* Perl expects this to be a fatal error */
5436                 if (severity != STS$K_SEVERE)
5437                     STATUS_ALL_FAILURE;
5438             }
5439         }
5440     }
5441
5442 #else
5443     int exitstatus;
5444     int eno = errno;
5445     if (eno & 255)
5446         STATUS_UNIX_SET(eno);
5447     else {
5448         exitstatus = STATUS_UNIX >> 8;
5449         if (exitstatus & 255)
5450             STATUS_UNIX_SET(exitstatus);
5451         else
5452             STATUS_UNIX_SET(255);
5453     }
5454 #endif
5455     if (PL_exit_flags & PERL_EXIT_ABORT) {
5456         abort();
5457     }
5458     if (PL_exit_flags & PERL_EXIT_WARN) {
5459         PL_exit_flags |= PERL_EXIT_ABORT; /* Protect against reentrant calls */
5460         Perl_warn(aTHX_ "Unexpected exit failure %ld", (long)PL_statusvalue);
5461         PL_exit_flags &= ~PERL_EXIT_ABORT;
5462     }
5463     my_exit_jump();
5464 }
5465
5466 STATIC void
5467 S_my_exit_jump(pTHX)
5468 {
5469     if (PL_e_script) {
5470         SvREFCNT_dec(PL_e_script);
5471         PL_e_script = NULL;
5472     }
5473
5474     POPSTACK_TO(PL_mainstack);
5475     if (cxstack_ix >= 0) {
5476         dounwind(-1);
5477     }
5478     rpp_obliterate_stack_to(0);
5479     LEAVE_SCOPE(0);
5480
5481     JMPENV_JUMP(2);
5482 }
5483
5484 static I32
5485 read_e_script(pTHX_ int idx, SV *buf_sv, int maxlen)
5486 {
5487     const char * const p  = SvPVX_const(PL_e_script);
5488     const char * const e  = SvEND(PL_e_script);
5489     const char *nl = (char *) memchr(p, '\n', e - p);
5490
5491     PERL_UNUSED_ARG(idx);
5492     PERL_UNUSED_ARG(maxlen);
5493
5494     nl = (nl) ? nl+1 : e;
5495     if (nl-p == 0) {
5496         filter_del(read_e_script);
5497         return 0;
5498     }
5499     sv_catpvn(buf_sv, p, nl-p);
5500     sv_chop(PL_e_script, nl);
5501     return 1;
5502 }
5503
5504 /* removes boilerplate code at the end of each boot_Module xsub */
5505 void
5506 Perl_xs_boot_epilog(pTHX_ const SSize_t ax)
5507 {
5508   if (PL_unitcheckav)
5509         call_list(PL_scopestack_ix, PL_unitcheckav);
5510     XSRETURN_YES;
5511 }
5512
5513 /*
5514  * ex: set ts=8 sts=4 sw=4 et:
5515  */