This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
embed.fnc - remove redundant deprecate_xxx() macro declarations
[perl5.git] / perl.c
CommitLineData
4b88f280 1#line 2 "perl.c"
a0d0e21e
LW
2/* perl.c
3 *
737f4459 4 * Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001
2eee27d7 5 * 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012
81d293c2 6 * 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023
9194fd8b 7 * by Larry Wall and others
a687059c 8 *
352d5a3a
LW
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.
a687059c 11 *
8d063cd8
LW
12 */
13
a0d0e21e 14/*
4ac71550
TC
15 * A ship then new they built for him
16 * of mithril and of elven-glass
cdad3b53 17 * --from Bilbo's song of Eärendil
4ac71550
TC
18 *
19 * [p.236 of _The Lord of the Rings_, II/i: "Many Meetings"]
a0d0e21e 20 */
45d8adaa 21
166f8a29
DM
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()
ddfa107c 25 * function of the interpreter; that can be found in perlmain.c
a1b69980
DM
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.
166f8a29
DM
30 */
31
c44493f1 32#if defined(PERL_IS_MINIPERL) && !defined(USE_SITECUSTOMIZE)
43c0c913
NC
33# define USE_SITECUSTOMIZE
34#endif
35
378cc40b 36#include "EXTERN.h"
864dbfa3 37#define PERL_IN_PERL_C
378cc40b 38#include "perl.h"
e3321bb0 39#include "patchlevel.h" /* for local_patches */
4a5df386 40#include "XSUB.h"
378cc40b 41
2aa47728 42#ifdef DEBUG_LEAKING_SCALARS_FORK_DUMP
bf357333
NC
43# ifdef I_SYSUIO
44# include <sys/uio.h>
45# endif
46
47union control_un {
48 struct cmsghdr cm;
49 char control[CMSG_SPACE(sizeof(int))];
50};
51
2aa47728
NC
52#endif
53
5311654c
JH
54#ifndef HZ
55# ifdef CLK_TCK
56# define HZ CLK_TCK
57# else
58# define HZ 60
59# endif
60#endif
61
acfe0abc 62static I32 read_e_script(pTHX_ int idx, SV *buf_sv, int maxlen);
0cb96387 63
cc69b689 64#ifdef SETUID_SCRIPTS_ARE_SECURE_NOW
b24bc095 65# define validate_suid(rsfp) NOOP
cc69b689 66#else
b24bc095 67# define validate_suid(rsfp) S_validate_suid(aTHX_ rsfp)
a687059c 68#endif
8d063cd8 69
d6f07c05
AL
70#define CALL_LIST_BODY(cv) \
71 PUSHMARK(PL_stack_sp); \
9a8aa25b 72 call_sv(MUTABLE_SV((cv)), G_EVAL|G_DISCARD|G_VOID);
d6f07c05 73
e6827a76 74static void
daa7d858 75S_init_tls_and_interp(PerlInterpreter *my_perl)
e6827a76 76{
1f4fbd3b
MS
77 if (!PL_curinterp) {
78 PERL_SET_INTERP(my_perl);
3db8f154 79#if defined(USE_ITHREADS)
1f4fbd3b
MS
80 INIT_THREADS;
81 ALLOC_THREAD_KEY;
82 PERL_SET_THX(my_perl);
83 OP_REFCNT_INIT;
84 OP_CHECK_MUTEX_INIT;
1e5c5f69 85 KEYWORD_PLUGIN_MUTEX_INIT;
1f4fbd3b 86 HINTS_REFCNT_INIT;
929e1213 87 LOCALE_INIT;
8310e7fa 88 USER_PROP_MUTEX_INIT;
2bc5f86a 89 ENV_INIT;
1f4fbd3b
MS
90 MUTEX_INIT(&PL_dollarzero_mutex);
91 MUTEX_INIT(&PL_my_ctx_mutex);
016af4f1 92# endif
e6827a76 93 }
c0bce9aa
NC
94#if defined(USE_ITHREADS)
95 else
96#else
97 /* This always happens for non-ithreads */
98#endif
99 {
1f4fbd3b 100 PERL_SET_THX(my_perl);
e6827a76
NC
101 }
102}
06d86050 103
cbec8ebe 104
0721b9ab
KW
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
cbec8ebe
DM
133/* these implement the PERL_SYS_INIT, PERL_SYS_INIT3, PERL_SYS_TERM macros */
134
135void
136Perl_sys_init(int* argc, char*** argv)
137{
7918f24d
NC
138
139 PERL_ARGS_ASSERT_SYS_INIT;
140
cbec8ebe
DM
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
146void
147Perl_sys_init3(int* argc, char*** argv, char*** env)
148{
7918f24d
NC
149
150 PERL_ARGS_ASSERT_SYS_INIT3;
151
cbec8ebe
DM
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
158void
88772978 159Perl_sys_term(void)
cbec8ebe 160{
bf81751b 161 if (!PL_veto_cleanup) {
1f4fbd3b 162 PERL_SYS_TERM_BODY();
bf81751b 163 }
cbec8ebe
DM
164}
165
166
32e30700
GS
167#ifdef PERL_IMPLICIT_SYS
168PerlInterpreter *
7766f137 169perl_alloc_using(struct IPerlMem* ipM, struct IPerlMem* ipMS,
1f4fbd3b
MS
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)
32e30700
GS
174{
175 PerlInterpreter *my_perl;
7918f24d
NC
176
177 PERL_ARGS_ASSERT_PERL_ALLOC_USING;
178
9f653bb5 179 /* Newx() needs interpreter, so call malloc() instead */
40385047 180 my_perl = (PerlInterpreter*)(*ipM->pCalloc)(ipM, 1, sizeof(PerlInterpreter));
e6827a76 181 S_init_tls_and_interp(my_perl);
32e30700 182 PL_Mem = ipM;
7766f137
GS
183 PL_MemShared = ipMS;
184 PL_MemParse = ipMP;
32e30700
GS
185 PL_Env = ipE;
186 PL_StdIO = ipStd;
187 PL_LIO = ipLIO;
188 PL_Dir = ipD;
189 PL_Sock = ipS;
190 PL_Proc = ipP;
7cb608b5 191 INIT_TRACK_MEMPOOL(PL_memory_debug_header, my_perl);
7766f137 192
32e30700
GS
193 return my_perl;
194}
195#else
954c1994
GS
196
197/*
3f620621 198=for apidoc_section $embedding
ccfc67b7 199
954c1994
GS
200=for apidoc perl_alloc
201
202Allocates a new Perl interpreter. See L<perlembed>.
203
204=cut
205*/
206
93a17b20 207PerlInterpreter *
cea2e8a9 208perl_alloc(void)
79072805 209{
4fc30d62 210 PerlInterpreter *my_perl = (PerlInterpreter*)PerlMem_calloc(1, sizeof(PerlInterpreter));
ba869deb 211
e6827a76 212 S_init_tls_and_interp(my_perl);
7cb608b5 213 INIT_TRACK_MEMPOOL(PL_memory_debug_header, my_perl);
4fc30d62 214 return my_perl;
79072805 215}
32e30700 216#endif /* PERL_IMPLICIT_SYS */
79072805 217
954c1994
GS
218/*
219=for apidoc perl_construct
220
221Initializes a new Perl interpreter. See L<perlembed>.
222
223=cut
224*/
225
79072805 226void
0cb96387 227perl_construct(pTHXx)
79072805 228{
7918f24d
NC
229
230 PERL_ARGS_ASSERT_PERL_CONSTRUCT;
231
8990e307 232#ifdef MULTIPLICITY
54aff467 233 init_interp();
ac27b0f5 234 PL_perl_destruct_level = 1;
54aff467 235#else
7918f24d 236 PERL_UNUSED_ARG(my_perl);
54aff467
GS
237 if (PL_perl_destruct_level > 0)
238 init_interp();
239#endif
34caed6d
DM
240 PL_curcop = &PL_compiling; /* needed by ckWARN, right away */
241
75d476e2
S
242#ifdef PERL_TRACE_OPS
243 Zero(PL_op_exec_cnt, OP_max+2, UV);
244#endif
245
0d96b528 246 init_constants();
34caed6d 247
e04fc1aa
CB
248 SvREADONLY_on(&PL_sv_placeholder);
249 SvREFCNT(&PL_sv_placeholder) = SvREFCNT_IMMORTAL;
250
dc37125b
DM
251 PL_sighandlerp = Perl_sighandler;
252 PL_sighandler1p = Perl_sighandler1;
253 PL_sighandler3p = Perl_sighandler3;
254
e04fc1aa
CB
255#ifdef PERL_USES_PL_PIDSTATUS
256 PL_pidstatus = newHV();
257#endif
258
259 PL_rs = newSVpvs("\n");
260
261 init_stacks();
262
bf2a3dae
YO
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
e04fc1aa
CB
270 * things that may put SVs on the stack.
271 */
bf2a3dae
YO
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 {
e04fc1aa 279
bf2a3dae
YO
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 */
d6295071 288#ifdef NO_PERL_INTERNAL_RAND_SEED
f26b33bd 289 Perl_drand48_init_r(&PL_internal_random_state, seed());
d6295071
TC
290#else
291 {
292 UV seed;
293 const char *env_pv;
bf2a3dae
YO
294 if (
295 !sensitive_env_vars_allowed ||
d6295071 296 !(env_pv = PerlEnv_getenv("PERL_INTERNAL_RAND_SEED")) ||
bf2a3dae
YO
297 grok_number(env_pv, strlen(env_pv), &seed) != IS_NUMBER_IN_UV)
298 {
299 /* use a randomly generated seed */
d6295071
TC
300 seed = seed();
301 }
302 Perl_drand48_init_r(&PL_internal_random_state, (U32)seed);
303 }
304#endif
f26b33bd 305
748a9306 306 init_ids();
a5f75d66 307
312caa8e 308 JMPENV_BOOTSTRAP;
f86702cc 309 STATUS_ALL_SUCCESS;
310
95e064d9 311 init_uniprops();
8c90d3a9
KW
312 (void) uvchr_to_utf8_flags((U8 *) PL_TR_SPECIAL_HANDLING_UTF8,
313 TR_SPECIAL_HANDLING,
314 UNICODE_ALLOW_ABOVE_IV_MAX);
0b5b802d 315
ab821d7f 316#if defined(LOCAL_PATCH_COUNT)
3280af22 317 PL_localpatches = local_patches; /* For possible -v */
ab821d7f 318#endif
319
fa2e4594
TC
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
52853b95
GS
328#ifdef HAVE_INTERP_INTERN
329 sys_intern_init();
330#endif
331
3a1ee7e8 332 PerlIO_init(aTHX); /* Hook to IO system */
760ac839 333
3280af22
NIS
334 PL_fdpid = newAV(); /* for remembering popen pids by fd */
335 PL_modglobal = newHV(); /* pointers to per-interpreter module globals */
396482e1 336 PL_errors = newSVpvs("");
854da30f
YO
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. */
1fcf4c12 340#ifdef USE_ITHREADS
402d2eb1
NC
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(""));
13137afc 344 PL_regex_pad = AvARRAY(PL_regex_padav);
d4d03940 345 Newxz(PL_stashpad, PL_stashpadmax, HV *);
1fcf4c12 346#endif
e5dd39fc 347#ifdef USE_REENTRANT_API
59bd0823 348 Perl_reentrant_init(aTHX);
e5dd39fc 349#endif
e6a172f3 350 if (PL_hash_seed_set == FALSE) {
9d5e3f1a
YO
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 */
1a237f4f 359#if defined(USE_HASH_SEED)
9d5e3f1a 360 /* get the hash seed from the environment or from an RNG */
7dc86639 361 Perl_get_hash_seed(aTHX_ PL_hash_seed);
1a237f4f 362#else
9d5e3f1a
YO
363 /* they want a hard coded seed, check that it is long enough */
364 assert( strlen(PERL_HASH_SEED) >= PERL_HASH_SEED_BYTES );
1a237f4f 365#endif
e6a172f3 366
9d5e3f1a
YO
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
0c6362ad 385 /* at this point we have initialized the hash function, and we can start
9d5e3f1a
YO
386 * constructing hashes */
387 PL_hash_seed_set= TRUE;
388 }
c82f4881
N
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 }
3d47000e 403
6760f691
YO
404#ifdef USE_ITHREADS
405 PL_compiling.cop_file = NULL;
6848aea2 406 PL_compiling.cop_warnings = NULL;
6760f691
YO
407#endif
408
a38ab475
RZ
409 Zero(PL_sv_consts, SV_CONSTS_COUNT, SV*);
410
2f42fcb0
JH
411#ifndef PERL_MICRO
412# ifdef USE_ENVIRON_ARRAY
66673af5
TK
413 if (!PL_origenviron)
414 PL_origenviron = environ;
2f42fcb0 415# endif
0631ea03
AB
416#endif
417
5311654c 418 /* Use sysconf(_SC_CLK_TCK) if available, if not
dbc1d986 419 * available or if the sysconf() fails, use the HZ.
27da23d5
JH
420 * The HZ if not originally defined has been by now
421 * been defined as CLK_TCK, if available. */
b6c36746 422#if defined(HAS_SYSCONF) && defined(_SC_CLK_TCK)
5311654c
JH
423 PL_clocktick = sysconf(_SC_CLK_TCK);
424 if (PL_clocktick <= 0)
425#endif
1f4fbd3b 426 PL_clocktick = HZ;
5311654c 427
081fc587
AB
428 PL_stashcache = newHV();
429
e8e3635e 430 PL_patchlevel = newSVpvs("v" PERL_VERSION_STRING);
d7aa5382 431
27da23d5
JH
432#ifdef HAS_MMAP
433 if (!PL_mmap_page_size) {
434#if defined(HAS_SYSCONF) && (defined(_SC_PAGESIZE) || defined(_SC_MMAP_PAGE_SIZE))
435 {
1f4fbd3b 436 SETERRNO(0, SS_NORMAL);
27da23d5 437# ifdef _SC_PAGESIZE
1f4fbd3b 438 PL_mmap_page_size = sysconf(_SC_PAGESIZE);
27da23d5 439# else
1f4fbd3b 440 PL_mmap_page_size = sysconf(_SC_MMAP_PAGE_SIZE);
27da23d5 441# endif
1f4fbd3b
MS
442 if ((long) PL_mmap_page_size < 0) {
443 Perl_croak(aTHX_ "panic: sysconf: %s",
444 errno ? Strerror(errno) : "pagesize unknown");
445 }
27da23d5 446 }
39bb759e 447#elif defined(HAS_GETPAGESIZE)
27da23d5 448 PL_mmap_page_size = getpagesize();
39bb759e 449#elif defined(I_SYS_PARAM) && defined(PAGESIZE)
27da23d5 450 PL_mmap_page_size = PAGESIZE; /* compiletime, bad */
27da23d5
JH
451#endif
452 if (PL_mmap_page_size <= 0)
1f4fbd3b
MS
453 Perl_croak(aTHX_ "panic: bad pagesize %" IVdf,
454 (IV) PL_mmap_page_size);
27da23d5
JH
455 }
456#endif /* HAS_MMAP */
457
7d113631
NC
458 PL_osname = Perl_savepvn(aTHX_ STR_WITH_LEN(OSNAME));
459
a3e6e81e 460 PL_registered_mros = newHV();
9e169432
NC
461 /* Start with 1 bucket, for DFS. It's unlikely we'll need more. */
462 HvMAX(PL_registered_mros) = 0;
a3e6e81e 463
8990e307 464 ENTER;
cb3fd6ac 465 init_i18nl10n(1);
79072805
LW
466}
467
954c1994 468/*
62375a60
NIS
469=for apidoc nothreadhook
470
471Stub that provides thread hook for perl_destruct when there are
472no threads.
473
474=cut
475*/
476
477int
4e9e3734 478Perl_nothreadhook(pTHX)
62375a60 479{
96a5add6 480 PERL_UNUSED_CONTEXT;
62375a60
NIS
481 return 0;
482}
483
41e4abd8
NC
484#ifdef DEBUG_LEAKING_SCALARS_FORK_DUMP
485void
486Perl_dump_sv_child(pTHX_ SV *sv)
487{
488 ssize_t got;
bf357333
NC
489 const int sock = PL_dumper_fd;
490 const int debug_fd = PerlIO_fileno(Perl_debug_log);
bf357333
NC
491 union control_un control;
492 struct msghdr msg;
808ad2d0 493 struct iovec vec[2];
bf357333 494 struct cmsghdr *cmptr;
808ad2d0
NC
495 int returned_errno;
496 unsigned char buffer[256];
41e4abd8 497
7918f24d
NC
498 PERL_ARGS_ASSERT_DUMP_SV_CHILD;
499
bf357333 500 if(sock == -1 || debug_fd == -1)
1f4fbd3b 501 return;
41e4abd8
NC
502
503 PerlIO_flush(Perl_debug_log);
504
bf357333
NC
505 /* All these shenanigans are to pass a file descriptor over to our child for
506 it to dump out to. We can't let it hold open the file descriptor when it
507 forks, as the file descriptor it will dump to can turn out to be one end
508 of pipe that some other process will wait on for EOF. (So as it would
b293a5f8 509 be open, the wait would be forever.) */
bf357333
NC
510
511 msg.msg_control = control.control;
512 msg.msg_controllen = sizeof(control.control);
513 /* We're a connected socket so we don't need a destination */
514 msg.msg_name = NULL;
515 msg.msg_namelen = 0;
516 msg.msg_iov = vec;
808ad2d0 517 msg.msg_iovlen = 1;
bf357333
NC
518
519 cmptr = CMSG_FIRSTHDR(&msg);
520 cmptr->cmsg_len = CMSG_LEN(sizeof(int));
521 cmptr->cmsg_level = SOL_SOCKET;
522 cmptr->cmsg_type = SCM_RIGHTS;
523 *((int *)CMSG_DATA(cmptr)) = 1;
524
525 vec[0].iov_base = (void*)&sv;
526 vec[0].iov_len = sizeof(sv);
527 got = sendmsg(sock, &msg, 0);
41e4abd8
NC
528
529 if(got < 0) {
1f4fbd3b
MS
530 perror("Debug leaking scalars parent sendmsg failed");
531 abort();
41e4abd8 532 }
bf357333 533 if(got < sizeof(sv)) {
1f4fbd3b
MS
534 perror("Debug leaking scalars parent short sendmsg");
535 abort();
41e4abd8
NC
536 }
537
808ad2d0
NC
538 /* Return protocol is
539 int: errno value
540 unsigned char: length of location string (0 for empty)
541 unsigned char*: string (not terminated)
542 */
543 vec[0].iov_base = (void*)&returned_errno;
544 vec[0].iov_len = sizeof(returned_errno);
545 vec[1].iov_base = buffer;
546 vec[1].iov_len = 1;
547
548 got = readv(sock, vec, 2);
41e4abd8
NC
549
550 if(got < 0) {
1f4fbd3b
MS
551 perror("Debug leaking scalars parent read failed");
552 PerlIO_flush(PerlIO_stderr());
553 abort();
41e4abd8 554 }
808ad2d0 555 if(got < sizeof(returned_errno) + 1) {
1f4fbd3b
MS
556 perror("Debug leaking scalars parent short read");
557 PerlIO_flush(PerlIO_stderr());
558 abort();
41e4abd8
NC
559 }
560
808ad2d0 561 if (*buffer) {
1f4fbd3b
MS
562 got = read(sock, buffer + 1, *buffer);
563 if(got < 0) {
564 perror("Debug leaking scalars parent read 2 failed");
565 PerlIO_flush(PerlIO_stderr());
566 abort();
567 }
808ad2d0 568
1f4fbd3b
MS
569 if(got < *buffer) {
570 perror("Debug leaking scalars parent short read 2");
571 PerlIO_flush(PerlIO_stderr());
572 abort();
573 }
808ad2d0
NC
574 }
575
576 if (returned_errno || *buffer) {
1f4fbd3b
MS
577 Perl_warn(aTHX_ "Debug leaking scalars child failed%s%.*s with errno"
578 " %d: %s", (*buffer ? " at " : ""), (int) *buffer, buffer + 1,
579 returned_errno, Strerror(returned_errno));
41e4abd8
NC
580 }
581}
582#endif
583
62375a60 584/*
44170c9a 585=for apidoc perl_destruct
0301e899
Z
586
587Shuts down a Perl interpreter. See L<perlembed> for a tutorial.
588
589C<my_perl> points to the Perl interpreter. It must have been previously
590created through the use of L</perl_alloc> and L</perl_construct>. It may
591have been initialised through L</perl_parse>, and may have been used
592through L</perl_run> and other means. This function should be called for
593any Perl interpreter that has been constructed with L</perl_construct>,
594even if subsequent operations on it failed, for example if L</perl_parse>
595returned a non-zero value.
596
597If the interpreter's C<PL_exit_flags> word has the
598C<PERL_EXIT_DESTRUCT_END> flag set, then this function will execute code
599in C<END> blocks before performing the rest of destruction. If it is
600desired to make any use of the interpreter between L</perl_parse> and
601L</perl_destruct> other than just calling L</perl_run>, then this flag
602should be set early on. This matters if L</perl_run> will not be called,
603or if anything else will be done in addition to calling L</perl_run>.
604
605Returns a value be a suitable value to pass to the C library function
606C<exit> (or to return from C<main>), to serve as an exit code indicating
607the nature of the way the interpreter terminated. This takes into account
608any failure of L</perl_parse> and any early exit from L</perl_run>.
609The exit code is of the type required by the host operating system,
610so because of differing exit code conventions it is not portable to
611interpret specific numeric values as having specific meanings.
954c1994
GS
612
613=cut
614*/
615
31d77e54 616int
0cb96387 617perl_destruct(pTHXx)
79072805 618{
8162b70e 619 volatile signed char destruct_level; /* see possible values in intrpvar.h */
a0d0e21e 620 HV *hv;
2aa47728 621#ifdef DEBUG_LEAKING_SCALARS_FORK_DUMP
2aa47728
NC
622 pid_t child;
623#endif
9c0b6888 624 int i;
8990e307 625
7918f24d
NC
626 PERL_ARGS_ASSERT_PERL_DESTRUCT;
627#ifndef MULTIPLICITY
ed6c66dd 628 PERL_UNUSED_ARG(my_perl);
7918f24d 629#endif
9d4ba2ae 630
3d22c4f0
GG
631 assert(PL_scopestack_ix == 1);
632
3280af22 633 destruct_level = PL_perl_destruct_level;
4633a7c4 634 {
1f4fbd3b
MS
635 const char * const s = PerlEnv_getenv("PERL_DESTRUCT_LEVEL");
636 if (s) {
96e440d2
JH
637 int i;
638 if (strEQ(s, "-1")) { /* Special case: modperl folklore. */
639 i = -1;
640 } else {
22ff3130
HS
641 UV uv;
642 if (grok_atoUV(s, &uv, NULL) && uv <= INT_MAX)
643 i = (int)uv;
644 else
645 i = 0;
96e440d2 646 }
1f4fbd3b 647 if (destruct_level < i) destruct_level = i;
36e77d41 648#ifdef PERL_TRACK_MEMPOOL
f5199772
KW
649 /* RT #114496, for perl_free */
650 PL_perl_destruct_level = i;
36e77d41 651#endif
1f4fbd3b 652 }
4633a7c4 653 }
4633a7c4 654
27da23d5 655 if (PL_exit_flags & PERL_EXIT_DESTRUCT_END) {
f3faeb53
AB
656 dJMPENV;
657 int x = 0;
658
659 JMPENV_PUSH(x);
1f4fbd3b 660 PERL_UNUSED_VAR(x);
9ebf26ad 661 if (PL_endav && !PL_minus_c) {
1f4fbd3b 662 PERL_SET_PHASE(PERL_PHASE_END);
f3faeb53 663 call_list(PL_scopestack_ix, PL_endav);
1f4fbd3b 664 }
f3faeb53 665 JMPENV_POP;
26f423df 666 }
f3faeb53 667 LEAVE;
a0d0e21e 668 FREETMPS;
3d22c4f0 669 assert(PL_scopestack_ix == 0);
a0d0e21e 670
127965c0
YO
671 /* wait for all pseudo-forked children to finish */
672 PERL_WAIT_FOR_CHILDREN;
673
674
803bd7c9
DM
675 /* normally when we get here, PL_parser should be null due to having
676 * its original (null) value restored by SAVEt_PARSER during leaving
677 * scope (usually before run-time starts in fact).
678 * But if a thread is created within a BEGIN block, the parser is
679 * duped, but the SAVEt_PARSER savestack entry isn't. So PL_parser
680 * never gets cleaned up.
681 * Clean it up here instead. This is a bit of a hack.
682 */
683 if (PL_parser) {
684 /* stop parser_free() stomping on PL_curcop */
685 PL_parser->saved_curcop = PL_curcop;
686 parser_free(PL_parser);
687 }
688
689
e00b64d4 690 /* Need to flush since END blocks can produce output */
8abddda3
TC
691 /* flush stdout separately, since we can identify it */
692#ifdef USE_PERLIO
693 {
694 PerlIO *stdo = PerlIO_stdout();
695 if (*stdo && PerlIO_flush(stdo)) {
696 PerlIO_restore_errno(stdo);
675c73ca 697 if (errno)
37537123 698 PerlIO_printf(PerlIO_stderr(), "Unable to flush stdout: %s\n",
675c73ca 699 Strerror(errno));
8abddda3
TC
700 if (!STATUS_UNIX)
701 STATUS_ALL_FAILURE;
702 }
703 }
704#endif
f13a2bc0 705 my_fflush_all();
e00b64d4 706
75d476e2 707#ifdef PERL_TRACE_OPS
e71f25b3
JC
708 /* dump OP-counts if $ENV{PERL_TRACE_OPS} > 0 */
709 {
710 const char * const ptoenv = PerlEnv_getenv("PERL_TRACE_OPS");
711 UV uv;
712
713 if (!ptoenv || !Perl_grok_atoUV(ptoenv, &uv, NULL)
714 || !(uv > 0))
715 goto no_trace_out;
716 }
75d476e2
S
717 PerlIO_printf(Perl_debug_log, "Trace of all OPs executed:\n");
718 for (i = 0; i <= OP_max; ++i) {
e71f25b3 719 if (PL_op_exec_cnt[i])
147e3846 720 PerlIO_printf(Perl_debug_log, " %s: %" UVuf "\n", PL_op_name[i], PL_op_exec_cnt[i]);
75d476e2
S
721 }
722 /* Utility slot for easily doing little tracing experiments in the runloop: */
723 if (PL_op_exec_cnt[OP_max+1] != 0)
147e3846 724 PerlIO_printf(Perl_debug_log, " SPECIAL: %" UVuf "\n", PL_op_exec_cnt[OP_max+1]);
75d476e2 725 PerlIO_printf(Perl_debug_log, "\n");
e71f25b3 726 no_trace_out:
75d476e2
S
727#endif
728
729
16c91539 730 if (PL_threadhook(aTHX)) {
62375a60 731 /* Threads hook has vetoed further cleanup */
1f4fbd3b 732 PL_veto_cleanup = TRUE;
37038d91 733 return STATUS_EXIT;
62375a60
NIS
734 }
735
2aa47728
NC
736#ifdef DEBUG_LEAKING_SCALARS_FORK_DUMP
737 if (destruct_level != 0) {
1f4fbd3b
MS
738 /* Fork here to create a child. Our child's job is to preserve the
739 state of scalars prior to destruction, so that we can instruct it
740 to dump any scalars that we later find have leaked.
741 There's no subtlety in this code - it assumes POSIX, and it doesn't
742 fail gracefully */
743 int fd[2];
744
745 if(PerlSock_socketpair_cloexec(AF_UNIX, SOCK_STREAM, 0, fd)) {
746 perror("Debug leaking scalars socketpair failed");
747 abort();
748 }
749
750 child = fork();
751 if(child == -1) {
752 perror("Debug leaking scalars fork failed");
753 abort();
754 }
755 if (!child) {
756 /* We are the child */
757 const int sock = fd[1];
758 const int debug_fd = PerlIO_fileno(Perl_debug_log);
759 int f;
760 const char *where;
761 /* Our success message is an integer 0, and a char 0 */
762 static const char success[sizeof(int) + 1] = {0};
763
764 close(fd[0]);
765
766 /* We need to close all other file descriptors otherwise we end up
767 with interesting hangs, where the parent closes its end of a
768 pipe, and sits waiting for (another) child to terminate. Only
769 that child never terminates, because it never gets EOF, because
770 we also have the far end of the pipe open. We even need to
771 close the debugging fd, because sometimes it happens to be one
772 end of a pipe, and a process is waiting on the other end for
773 EOF. Normally it would be closed at some point earlier in
774 destruction, but if we happen to cause the pipe to remain open,
775 EOF never occurs, and we get an infinite hang. Hence all the
776 games to pass in a file descriptor if it's actually needed. */
777
778 f = sysconf(_SC_OPEN_MAX);
779 if(f < 0) {
780 where = "sysconf failed";
781 goto abort;
782 }
783 while (f--) {
784 if (f == sock)
785 continue;
786 close(f);
787 }
788
789 while (1) {
790 SV *target;
791 union control_un control;
792 struct msghdr msg;
793 struct iovec vec[1];
794 struct cmsghdr *cmptr;
795 ssize_t got;
796 int got_fd;
797
798 msg.msg_control = control.control;
799 msg.msg_controllen = sizeof(control.control);
800 /* We're a connected socket so we don't need a source */
801 msg.msg_name = NULL;
802 msg.msg_namelen = 0;
803 msg.msg_iov = vec;
804 msg.msg_iovlen = C_ARRAY_LENGTH(vec);
805
806 vec[0].iov_base = (void*)&target;
807 vec[0].iov_len = sizeof(target);
808
809 got = recvmsg(sock, &msg, 0);
810
811 if(got == 0)
812 break;
813 if(got < 0) {
814 where = "recv failed";
815 goto abort;
816 }
817 if(got < sizeof(target)) {
818 where = "short recv";
819 goto abort;
820 }
821
822 if(!(cmptr = CMSG_FIRSTHDR(&msg))) {
823 where = "no cmsg";
824 goto abort;
825 }
826 if(cmptr->cmsg_len != CMSG_LEN(sizeof(int))) {
827 where = "wrong cmsg_len";
828 goto abort;
829 }
830 if(cmptr->cmsg_level != SOL_SOCKET) {
831 where = "wrong cmsg_level";
832 goto abort;
833 }
834 if(cmptr->cmsg_type != SCM_RIGHTS) {
835 where = "wrong cmsg_type";
836 goto abort;
837 }
838
839 got_fd = *(int*)CMSG_DATA(cmptr);
840 /* For our last little bit of trickery, put the file descriptor
841 back into Perl_debug_log, as if we never actually closed it
842 */
843 if(got_fd != debug_fd) {
844 if (PerlLIO_dup2_cloexec(got_fd, debug_fd) == -1) {
845 where = "dup2";
846 goto abort;
847 }
848 }
849 sv_dump(target);
850
851 PerlIO_flush(Perl_debug_log);
852
853 got = write(sock, &success, sizeof(success));
854
855 if(got < 0) {
856 where = "write failed";
857 goto abort;
858 }
859 if(got < sizeof(success)) {
860 where = "short write";
861 goto abort;
862 }
863 }
864 _exit(0);
865 abort:
866 {
867 int send_errno = errno;
868 unsigned char length = (unsigned char) strlen(where);
869 struct iovec failure[3] = {
870 {(void*)&send_errno, sizeof(send_errno)},
871 {&length, 1},
872 {(void*)where, length}
873 };
874 int got = writev(sock, failure, 3);
875 /* Bad news travels fast. Faster than data. We'll get a SIGPIPE
876 in the parent if we try to read from the socketpair after the
877 child has exited, even if there was data to read.
878 So sleep a bit to give the parent a fighting chance of
879 reading the data. */
880 sleep(2);
881 _exit((got == -1) ? errno : 0);
882 }
883 /* End of child. */
884 }
885 PL_dumper_fd = fd[0];
886 close(fd[1]);
887 }
888#endif
889
ff0cee69 890 /* We must account for everything. */
891
892 /* Destroy the main CV and syntax tree */
37e77c23
FC
893 /* Set PL_curcop now, because destroying ops can cause new SVs
894 to be generated in Perl_pad_swipe, and when running with
895 -DDEBUG_LEAKING_SCALARS they expect PL_curcop to point to a valid
896 op from which the filename structure member is copied. */
17fbfdf6 897 PL_curcop = &PL_compiling;
3280af22 898 if (PL_main_root) {
1f4fbd3b
MS
899 /* ensure comppad/curpad to refer to main's pad */
900 if (CvPADLIST(PL_main_cv)) {
901 PAD_SET_CUR_NOSAVE(CvPADLIST(PL_main_cv), 1);
902 PL_comppad_name = PadlistNAMES(CvPADLIST(PL_main_cv));
903 }
904 op_free(PL_main_root);
905 PL_main_root = NULL;
a0d0e21e 906 }
5f66b61c 907 PL_main_start = NULL;
aac9d523
DM
908 /* note that PL_main_cv isn't usually actually freed at this point,
909 * due to the CvOUTSIDE refs from subs compiled within it. It will
910 * get freed once all the subs are freed in sv_clean_all(), for
911 * destruct_level > 0 */
3280af22 912 SvREFCNT_dec(PL_main_cv);
601f1833 913 PL_main_cv = NULL;
ca7b837b 914 PERL_SET_PHASE(PERL_PHASE_DESTRUCT);
ff0cee69 915
13621cfb
NIS
916 /* Tell PerlIO we are about to tear things apart in case
917 we have layers which are using resources that should
918 be cleaned up now.
919 */
920
921 PerlIO_destruct(aTHX);
922
ddf23d4a
S
923 /*
924 * Try to destruct global references. We do this first so that the
925 * destructors and destructees still exist. Some sv's might remain.
926 * Non-referenced objects are on their own.
927 */
928 sv_clean_objs();
8990e307 929
5cd24f17 930 /* unhook hooks which will soon be, or use, destroyed data */
3280af22 931 SvREFCNT_dec(PL_warnhook);
a0714e2c 932 PL_warnhook = NULL;
3280af22 933 SvREFCNT_dec(PL_diehook);
a0714e2c 934 PL_diehook = NULL;
93f6f965
YO
935 SvREFCNT_dec(PL_hook__require__before);
936 PL_hook__require__before = NULL;
937 SvREFCNT_dec(PL_hook__require__after);
938 PL_hook__require__after = NULL;
5cd24f17 939
4b556e6c 940 /* call exit list functions */
3280af22 941 while (PL_exitlistlen-- > 0)
1f4fbd3b 942 PL_exitlist[PL_exitlistlen].fn(aTHX_ PL_exitlist[PL_exitlistlen].ptr);
4b556e6c 943
3280af22 944 Safefree(PL_exitlist);
4b556e6c 945
1c4916e5
CB
946 PL_exitlist = NULL;
947 PL_exitlistlen = 0;
948
a3e6e81e
NC
949 SvREFCNT_dec(PL_registered_mros);
950
30985c42
JH
951 if (destruct_level == 0) {
952
1f4fbd3b 953 DEBUG_P(debprofdump());
30985c42
JH
954
955#if defined(PERLIO_LAYERS)
1f4fbd3b
MS
956 /* No more IO - including error messages ! */
957 PerlIO_cleanup(aTHX);
30985c42
JH
958#endif
959
1f4fbd3b 960 CopFILE_free(&PL_compiling);
30985c42 961
1f4fbd3b 962 /* The exit() function will do everything that needs doing. */
30985c42
JH
963 return STATUS_EXIT;
964 }
965
9fa9f06b
KW
966 /* Below, do clean up for when PERL_DESTRUCT_LEVEL is not 0 */
967
5f8cb046
DM
968#ifdef USE_ITHREADS
969 /* the syntax tree is shared between clones
970 * so op_free(PL_main_root) only ReREFCNT_dec's
971 * REGEXPs in the parent interpreter
972 * we need to manually ReREFCNT_dec for the clones
973 */
0547a729 974 {
1f4fbd3b
MS
975 I32 i = AvFILLp(PL_regex_padav);
976 SV **ary = AvARRAY(PL_regex_padav);
0547a729 977
1f4fbd3b
MS
978 for (; i; i--) {
979 SvREFCNT_dec(ary[i]);
980 ary[i] = &PL_sv_undef;
981 }
0547a729 982 }
5f8cb046
DM
983#endif
984
0547a729 985
ad64d0ec 986 SvREFCNT_dec(MUTABLE_SV(PL_stashcache));
081fc587
AB
987 PL_stashcache = NULL;
988
5f05dabc 989 /* loosen bonds of global variables */
990
2f9285f8
DM
991 /* XXX can PL_parser still be non-null here? */
992 if(PL_parser && PL_parser->rsfp) {
1f4fbd3b
MS
993 (void)PerlIO_close(PL_parser->rsfp);
994 PL_parser->rsfp = NULL;
8ebc5c01 995 }
996
84386e14 997 if (PL_minus_F) {
1f4fbd3b
MS
998 Safefree(PL_splitstr);
999 PL_splitstr = NULL;
84386e14
RGS
1000 }
1001
8ebc5c01 1002 /* switches */
3280af22
NIS
1003 PL_minus_n = FALSE;
1004 PL_minus_p = FALSE;
1005 PL_minus_l = FALSE;
1006 PL_minus_a = FALSE;
1007 PL_minus_F = FALSE;
1008 PL_doswitches = FALSE;
599cee73 1009 PL_dowarn = G_WARN_OFF;
1a904fc8 1010#ifdef PERL_SAWAMPERSAND
d3b97530 1011 PL_sawampersand = 0; /* must save all match strings */
1a904fc8 1012#endif
3280af22
NIS
1013 PL_unsafe = FALSE;
1014
1015 Safefree(PL_inplace);
bd61b366 1016 PL_inplace = NULL;
a7cb1f99 1017 SvREFCNT_dec(PL_patchlevel);
3280af22
NIS
1018
1019 if (PL_e_script) {
1f4fbd3b
MS
1020 SvREFCNT_dec(PL_e_script);
1021 PL_e_script = NULL;
8ebc5c01 1022 }
1023
bf9cdc68
RG
1024 PL_perldb = 0;
1025
8ebc5c01 1026 /* magical thingies */
1027
e23d9e2f
CS
1028 SvREFCNT_dec(PL_ofsgv); /* *, */
1029 PL_ofsgv = NULL;
5f05dabc 1030
7889fe52 1031 SvREFCNT_dec(PL_ors_sv); /* $\ */
a0714e2c 1032 PL_ors_sv = NULL;
8ebc5c01 1033
3280af22 1034 SvREFCNT_dec(PL_rs); /* $/ */
a0714e2c 1035 PL_rs = NULL;
dc92893f 1036
d33b2eba 1037 Safefree(PL_osname); /* $^O */
bd61b366 1038 PL_osname = NULL;
5f05dabc 1039
3280af22 1040 SvREFCNT_dec(PL_statname);
a0714e2c
SS
1041 PL_statname = NULL;
1042 PL_statgv = NULL;
5f05dabc 1043
8ebc5c01 1044 /* defgv, aka *_ should be taken care of elsewhere */
1045
7d5ea4e7
GS
1046 /* float buffer */
1047 Safefree(PL_efloatbuf);
bd61b366 1048 PL_efloatbuf = NULL;
7d5ea4e7
GS
1049 PL_efloatsize = 0;
1050
8ebc5c01 1051 /* startup and shutdown function lists */
3280af22 1052 SvREFCNT_dec(PL_beginav);
5a837c8f 1053 SvREFCNT_dec(PL_beginav_save);
3280af22 1054 SvREFCNT_dec(PL_endav);
7d30b5c4 1055 SvREFCNT_dec(PL_checkav);
ece599bd 1056 SvREFCNT_dec(PL_checkav_save);
3c10abe3
AG
1057 SvREFCNT_dec(PL_unitcheckav);
1058 SvREFCNT_dec(PL_unitcheckav_save);
3280af22 1059 SvREFCNT_dec(PL_initav);
7d49f689
NC
1060 PL_beginav = NULL;
1061 PL_beginav_save = NULL;
1062 PL_endav = NULL;
1063 PL_checkav = NULL;
1064 PL_checkav_save = NULL;
3c10abe3
AG
1065 PL_unitcheckav = NULL;
1066 PL_unitcheckav_save = NULL;
7d49f689 1067 PL_initav = NULL;
5618dfe8 1068
8ebc5c01 1069 /* shortcuts just get cleared */
a0714e2c
SS
1070 PL_hintgv = NULL;
1071 PL_errgv = NULL;
a0714e2c
SS
1072 PL_argvoutgv = NULL;
1073 PL_stdingv = NULL;
1074 PL_stderrgv = NULL;
1075 PL_last_in_gv = NULL;
a0714e2c
SS
1076 PL_DBsingle = NULL;
1077 PL_DBtrace = NULL;
1078 PL_DBsignal = NULL;
a6d69523
TC
1079 PL_DBsingle_iv = 0;
1080 PL_DBtrace_iv = 0;
1081 PL_DBsignal_iv = 0;
601f1833 1082 PL_DBcv = NULL;
7d49f689 1083 PL_dbargs = NULL;
5c284bb0 1084 PL_debstash = NULL;
8ebc5c01 1085
cf93a474 1086 SvREFCNT_dec(PL_envgv);
f03015cd 1087 SvREFCNT_dec(PL_incgv);
722fa0e9 1088 SvREFCNT_dec(PL_argvgv);
475b1e90 1089 SvREFCNT_dec(PL_replgv);
8cece913
FC
1090 SvREFCNT_dec(PL_DBgv);
1091 SvREFCNT_dec(PL_DBline);
1092 SvREFCNT_dec(PL_DBsub);
cf93a474 1093 PL_envgv = NULL;
f03015cd 1094 PL_incgv = NULL;
722fa0e9 1095 PL_argvgv = NULL;
475b1e90 1096 PL_replgv = NULL;
8cece913
FC
1097 PL_DBgv = NULL;
1098 PL_DBline = NULL;
1099 PL_DBsub = NULL;
1100
7a1c5554 1101 SvREFCNT_dec(PL_argvout_stack);
7d49f689 1102 PL_argvout_stack = NULL;
8ebc5c01 1103
5c831c24 1104 SvREFCNT_dec(PL_modglobal);
5c284bb0 1105 PL_modglobal = NULL;
5c831c24 1106 SvREFCNT_dec(PL_preambleav);
7d49f689 1107 PL_preambleav = NULL;
5c831c24 1108 SvREFCNT_dec(PL_subname);
a0714e2c 1109 PL_subname = NULL;
ca0c25f6 1110#ifdef PERL_USES_PL_PIDSTATUS
5c831c24 1111 SvREFCNT_dec(PL_pidstatus);
5c284bb0 1112 PL_pidstatus = NULL;
ca0c25f6 1113#endif
5c831c24 1114 SvREFCNT_dec(PL_toptarget);
a0714e2c 1115 PL_toptarget = NULL;
5c831c24 1116 SvREFCNT_dec(PL_bodytarget);
a0714e2c
SS
1117 PL_bodytarget = NULL;
1118 PL_formtarget = NULL;
5c831c24 1119
d33b2eba 1120 /* free locale stuff */
b9582b6a 1121#ifdef USE_LOCALE_COLLATE
d33b2eba 1122 Safefree(PL_collation_name);
bd61b366 1123 PL_collation_name = NULL;
b9582b6a 1124#endif
5e395a7a 1125#if defined(USE_PL_CURLOCALES)
e9bc6d6b
KW
1126 for (i = 0; i < (int) C_ARRAY_LENGTH(PL_curlocales); i++) {
1127 Safefree(PL_curlocales[i]);
1128 PL_curlocales[i] = NULL;
1129 }
1130#endif
4b06b4d0 1131#ifdef USE_POSIX_2008_LOCALE
9fe4122e
KW
1132 {
1133 /* This also makes sure we aren't using a locale object that gets freed
1134 * below */
1094750e
KW
1135 if ( PL_cur_locale_obj != NULL
1136 && PL_cur_locale_obj != LC_GLOBAL_LOCALE
1137 && PL_cur_locale_obj != PL_C_locale_obj
e72200e7 1138 ) {
1094750e
KW
1139 locale_t cur_locale = uselocale((locale_t) 0);
1140 if (cur_locale == PL_cur_locale_obj) {
1141 uselocale(LC_GLOBAL_LOCALE);
1142 }
1143
1144 freelocale(PL_cur_locale_obj);
1145 PL_cur_locale_obj = NULL;
9fe4122e
KW
1146 }
1147 }
6a4065f2
KW
1148
1149# ifdef USE_PL_CUR_LC_ALL
1150
1151 if (PL_cur_LC_ALL) {
1152 DEBUG_L( PerlIO_printf(Perl_debug_log, "PL_cur_LC_ALL=%p\n", PL_cur_LC_ALL));
1153 Safefree(PL_cur_LC_ALL);
1154 PL_cur_LC_ALL = NULL;
1155 }
1156
1157# endif
1158
827a4a05
KW
1159 if (PL_scratch_locale_obj) {
1160 freelocale(PL_scratch_locale_obj);
1161 PL_scratch_locale_obj = NULL;
1162 }
9fe4122e 1163# ifdef USE_LOCALE_NUMERIC
e1aa2579 1164 if (PL_underlying_numeric_obj) {
19ee3daf
KW
1165 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
1166 "%s:%d: Freeing %p\n", __FILE__, __LINE__,
1167 PL_underlying_numeric_obj));
e1aa2579
KW
1168 freelocale(PL_underlying_numeric_obj);
1169 PL_underlying_numeric_obj = (locale_t) NULL;
1170 }
e1aa2579 1171# endif
9fe4122e
KW
1172#endif
1173#ifdef USE_LOCALE_NUMERIC
1174 Safefree(PL_numeric_name);
1175 PL_numeric_name = NULL;
1176 SvREFCNT_dec(PL_numeric_radix_sv);
1177 PL_numeric_radix_sv = NULL;
37b8263e
KW
1178 SvREFCNT_dec(PL_underlying_radix_sv);
1179 PL_underlying_radix_sv = NULL;
e1aa2579 1180#endif
b269edc8
KW
1181#ifdef USE_LOCALE_CTYPE
1182 Safefree(PL_ctype_name);
1183 PL_ctype_name = NULL;
1184#endif
e1aa2579 1185
9aac5db8
KW
1186 if (PL_setlocale_buf) {
1187 Safefree(PL_setlocale_buf);
1188 PL_setlocale_buf = NULL;
1189 }
1190
7e5377f7
KW
1191 if (PL_langinfo_buf) {
1192 Safefree(PL_langinfo_buf);
1193 PL_langinfo_buf = NULL;
1194 }
1195
32899cfb
KW
1196 if (PL_stdize_locale_buf) {
1197 Safefree(PL_stdize_locale_buf);
1198 PL_stdize_locale_buf = NULL;
1199 }
1200
5b7de470 1201#ifdef USE_LOCALE_CTYPE
780fcc9f 1202 SvREFCNT_dec(PL_warn_locale);
780fcc9f 1203 PL_warn_locale = NULL;
5b7de470 1204#endif
5c831c24 1205
a8def808
KW
1206 SvREFCNT_dec(PL_AboveLatin1);
1207 PL_AboveLatin1 = NULL;
1208 SvREFCNT_dec(PL_Assigned_invlist);
1209 PL_Assigned_invlist = NULL;
1210 SvREFCNT_dec(PL_GCB_invlist);
1211 PL_GCB_invlist = NULL;
1212 SvREFCNT_dec(PL_HasMultiCharFold);
1213 PL_HasMultiCharFold = NULL;
1214 SvREFCNT_dec(PL_InMultiCharFold);
1215 PL_InMultiCharFold = NULL;
1216 SvREFCNT_dec(PL_Latin1);
1217 PL_Latin1 = NULL;
1218 SvREFCNT_dec(PL_LB_invlist);
1219 PL_LB_invlist = NULL;
1220 SvREFCNT_dec(PL_SB_invlist);
1221 PL_SB_invlist = NULL;
1222 SvREFCNT_dec(PL_SCX_invlist);
1223 PL_SCX_invlist = NULL;
1224 SvREFCNT_dec(PL_UpperLatin1);
1225 PL_UpperLatin1 = NULL;
1226 SvREFCNT_dec(PL_in_some_fold);
1227 PL_in_some_fold = NULL;
668d1998
KW
1228 SvREFCNT_dec(PL_utf8_foldclosures);
1229 PL_utf8_foldclosures = NULL;
a8def808
KW
1230 SvREFCNT_dec(PL_utf8_idcont);
1231 PL_utf8_idcont = NULL;
1232 SvREFCNT_dec(PL_utf8_idstart);
1233 PL_utf8_idstart = NULL;
1234 SvREFCNT_dec(PL_utf8_perl_idcont);
1235 PL_utf8_perl_idcont = NULL;
1236 SvREFCNT_dec(PL_utf8_perl_idstart);
1237 PL_utf8_perl_idstart = NULL;
1238 SvREFCNT_dec(PL_utf8_xidcont);
1239 PL_utf8_xidcont = NULL;
1240 SvREFCNT_dec(PL_utf8_xidstart);
1241 PL_utf8_xidstart = NULL;
1242 SvREFCNT_dec(PL_WB_invlist);
1243 PL_WB_invlist = NULL;
1244 SvREFCNT_dec(PL_utf8_toupper);
1245 PL_utf8_toupper = NULL;
1246 SvREFCNT_dec(PL_utf8_totitle);
1247 PL_utf8_totitle = NULL;
1248 SvREFCNT_dec(PL_utf8_tolower);
1249 PL_utf8_tolower = NULL;
1250 SvREFCNT_dec(PL_utf8_tofold);
1251 PL_utf8_tofold = NULL;
1252 SvREFCNT_dec(PL_utf8_tosimplefold);
1253 PL_utf8_tosimplefold = NULL;
1254 SvREFCNT_dec(PL_utf8_charname_begin);
1255 PL_utf8_charname_begin = NULL;
1256 SvREFCNT_dec(PL_utf8_charname_continue);
1257 PL_utf8_charname_continue = NULL;
1258 SvREFCNT_dec(PL_utf8_mark);
1259 PL_utf8_mark = NULL;
1260 SvREFCNT_dec(PL_InBitmap);
1261 PL_InBitmap = NULL;
1262 SvREFCNT_dec(PL_CCC_non0_non230);
1263 PL_CCC_non0_non230 = NULL;
1264 SvREFCNT_dec(PL_Private_Use);
1265 PL_Private_Use = NULL;
1266
1267 for (i = 0; i < POSIX_CC_COUNT; i++) {
1268 SvREFCNT_dec(PL_XPosix_ptrs[i]);
1269 PL_XPosix_ptrs[i] = NULL;
1270
91456fff 1271 if (i != CC_CASED_) { /* A copy of Alpha */
a8def808
KW
1272 SvREFCNT_dec(PL_Posix_ptrs[i]);
1273 PL_Posix_ptrs[i] = NULL;
1274 }
1275 }
1276
1943af61 1277 free_and_set_cop_warnings(&PL_compiling, NULL);
20439bc7
Z
1278 cophh_free(CopHINTHASH_get(&PL_compiling));
1279 CopHINTHASH_set(&PL_compiling, cophh_new_empty());
05ec9bb3 1280 CopFILE_free(&PL_compiling);
5c831c24 1281
a0d0e21e 1282 /* Prepare to destruct main symbol table. */
5f05dabc 1283
3280af22 1284 hv = PL_defstash;
ca556bcd 1285 /* break ref loop *:: <=> %:: */
854da30f 1286 (void)hv_deletes(hv, "main::", G_DISCARD);
3280af22 1287 PL_defstash = 0;
a0d0e21e 1288 SvREFCNT_dec(hv);
5c831c24 1289 SvREFCNT_dec(PL_curstname);
a0714e2c 1290 PL_curstname = NULL;
a0d0e21e 1291
5a844595
GS
1292 /* clear queued errors */
1293 SvREFCNT_dec(PL_errors);
a0714e2c 1294 PL_errors = NULL;
5a844595 1295
dd69841b
BB
1296 SvREFCNT_dec(PL_isarev);
1297
a0d0e21e 1298 FREETMPS;
9b387841 1299 if (destruct_level >= 2) {
1f4fbd3b
MS
1300 if (PL_scopestack_ix != 0)
1301 Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL),
1302 "Unbalanced scopes: %ld more ENTERs than LEAVEs\n",
1303 (long)PL_scopestack_ix);
1304 if (PL_savestack_ix != 0)
1305 Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL),
1306 "Unbalanced saves: %ld more saves than restores\n",
1307 (long)PL_savestack_ix);
1308 if (PL_tmps_floor != -1)
1309 Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL),"Unbalanced tmps: %ld more allocs than frees\n",
1310 (long)PL_tmps_floor + 1);
1311 if (cxstack_ix != -1)
1312 Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL),"Unbalanced context: %ld more PUSHes than POPs\n",
1313 (long)cxstack_ix + 1);
a0d0e21e 1314 }
8990e307 1315
0547a729
DM
1316#ifdef USE_ITHREADS
1317 SvREFCNT_dec(PL_regex_padav);
1318 PL_regex_padav = NULL;
1319 PL_regex_pad = NULL;
1320#endif
1321
6e512bc2 1322#ifdef MULTIPLICITY
57bb2458
JH
1323 /* the entries in this list are allocated via SV PVX's, so get freed
1324 * in sv_clean_all */
1325 Safefree(PL_my_cxt_list);
776df701 1326#endif
57bb2458 1327
8990e307 1328 /* Now absolutely destruct everything, somehow or other, loops or no. */
5226ed68
JH
1329
1330 /* the 2 is for PL_fdpid and PL_strtab */
d17ea597 1331 while (sv_clean_all() > 2)
1f4fbd3b 1332 ;
5226ed68 1333
23083432
FC
1334#ifdef USE_ITHREADS
1335 Safefree(PL_stashpad); /* must come after sv_clean_all */
1336#endif
1337
d4777f27
GS
1338 AvREAL_off(PL_fdpid); /* no surviving entries */
1339 SvREFCNT_dec(PL_fdpid); /* needed in io_close() */
7d49f689 1340 PL_fdpid = NULL;
d33b2eba 1341
6c644e78
GS
1342#ifdef HAVE_INTERP_INTERN
1343 sys_intern_clear();
1344#endif
1345
a38ab475
RZ
1346 /* constant strings */
1347 for (i = 0; i < SV_CONSTS_COUNT; i++) {
1348 SvREFCNT_dec(PL_sv_consts[i]);
1349 PL_sv_consts[i] = NULL;
1350 }
1351
6e72f9df 1352 /* Destruct the global string table. */
1353 {
1f4fbd3b
MS
1354 /* Yell and reset the HeVAL() slots that are still holding refcounts,
1355 * so that sv_free() won't fail on them.
1356 * Now that the global string table is using a single hunk of memory
1357 * for both HE and HEK, we either need to explicitly unshare it the
1358 * correct way, or actually free things here.
1359 */
1360 I32 riter = 0;
1361 const I32 max = HvMAX(PL_strtab);
1362 HE * const * const array = HvARRAY(PL_strtab);
1363 HE *hent = array[0];
1364
1365 for (;;) {
1366 if (hent && ckWARN_d(WARN_INTERNAL)) {
1367 HE * const next = HeNEXT(hent);
1368 Perl_warner(aTHX_ packWARN(WARN_INTERNAL),
1369 "Unbalanced string table refcount: (%ld) for \"%s\"",
1370 (long)hent->he_valu.hent_refcount, HeKEY(hent));
1371 Safefree(hent);
1372 hent = next;
1373 }
1374 if (!hent) {
1375 if (++riter > max)
1376 break;
1377 hent = array[riter];
1378 }
1379 }
1380
1381 Safefree(array);
1382 HvARRAY(PL_strtab) = 0;
1383 HvTOTALKEYS(PL_strtab) = 0;
6e72f9df 1384 }
3280af22 1385 SvREFCNT_dec(PL_strtab);
6e72f9df 1386
e652bb2f 1387#ifdef USE_ITHREADS
c21d1a0f 1388 /* free the pointer tables used for cloning */
a0739874 1389 ptr_table_free(PL_ptr_table);
bf9cdc68 1390 PL_ptr_table = (PTR_TBL_t*)NULL;
53186e96 1391#endif
a0739874 1392
d33b2eba
GS
1393 /* free special SVs */
1394
1395 SvREFCNT(&PL_sv_yes) = 0;
1396 sv_clear(&PL_sv_yes);
1397 SvANY(&PL_sv_yes) = NULL;
4c5e2b0d 1398 SvFLAGS(&PL_sv_yes) = 0;
d33b2eba
GS
1399
1400 SvREFCNT(&PL_sv_no) = 0;
1401 sv_clear(&PL_sv_no);
1402 SvANY(&PL_sv_no) = NULL;
4c5e2b0d 1403 SvFLAGS(&PL_sv_no) = 0;
01724ea0 1404
5a6c2837
DM
1405 SvREFCNT(&PL_sv_zero) = 0;
1406 sv_clear(&PL_sv_zero);
1407 SvANY(&PL_sv_zero) = NULL;
1408 SvFLAGS(&PL_sv_zero) = 0;
1409
9f375a43
DM
1410 {
1411 int i;
1412 for (i=0; i<=2; i++) {
1413 SvREFCNT(PERL_DEBUG_PAD(i)) = 0;
1414 sv_clear(PERL_DEBUG_PAD(i));
1415 SvANY(PERL_DEBUG_PAD(i)) = NULL;
1416 SvFLAGS(PERL_DEBUG_PAD(i)) = 0;
1417 }
1418 }
1419
0453d815 1420 if (PL_sv_count != 0 && ckWARN_d(WARN_INTERNAL))
1f4fbd3b 1421 Perl_warner(aTHX_ packWARN(WARN_INTERNAL),"Scalars leaked: %ld\n", (long)PL_sv_count);
6e72f9df 1422
eba0f806
DM
1423#ifdef DEBUG_LEAKING_SCALARS
1424 if (PL_sv_count != 0) {
1f4fbd3b
MS
1425 SV* sva;
1426 SV* sv;
1427 SV* svend;
1428
1429 for (sva = PL_sv_arenaroot; sva; sva = MUTABLE_SV(SvANY(sva))) {
1430 svend = &sva[SvREFCNT(sva)];
1431 for (sv = sva + 1; sv < svend; ++sv) {
1432 if (SvTYPE(sv) != (svtype)SVTYPEMASK) {
1433 PerlIO_printf(Perl_debug_log, "leaked: sv=0x%p"
1434 " flags=0x%" UVxf
1435 " refcnt=%" UVuf pTHX__FORMAT "\n"
1436 "\tallocated at %s:%d %s %s (parent 0x%" UVxf ");"
1437 "serial %" UVuf "\n",
1438 (void*)sv, (UV)sv->sv_flags, (UV)sv->sv_refcnt
1439 pTHX__VALUE,
1440 sv->sv_debug_file ? sv->sv_debug_file : "(unknown)",
1441 sv->sv_debug_line,
1442 sv->sv_debug_inpad ? "for" : "by",
1443 sv->sv_debug_optype ?
1444 PL_op_name[sv->sv_debug_optype]: "(none)",
1445 PTR2UV(sv->sv_debug_parent),
1446 sv->sv_debug_serial
1447 );
2aa47728 1448#ifdef DEBUG_LEAKING_SCALARS_FORK_DUMP
1f4fbd3b 1449 Perl_dump_sv_child(aTHX_ sv);
2aa47728 1450#endif
1f4fbd3b
MS
1451 }
1452 }
1453 }
eba0f806 1454 }
2aa47728
NC
1455#ifdef DEBUG_LEAKING_SCALARS_FORK_DUMP
1456 {
1f4fbd3b
MS
1457 int status;
1458 fd_set rset;
1459 /* Wait for up to 4 seconds for child to terminate.
1460 This seems to be the least effort way of timing out on reaping
1461 its exit status. */
1462 struct timeval waitfor = {4, 0};
1463 int sock = PL_dumper_fd;
2aa47728 1464
1f4fbd3b
MS
1465 shutdown(sock, 1);
1466 FD_ZERO(&rset);
1467 FD_SET(sock, &rset);
1468 select(sock + 1, &rset, NULL, NULL, &waitfor);
1469 waitpid(child, &status, WNOHANG);
1470 close(sock);
2aa47728
NC
1471 }
1472#endif
eba0f806 1473#endif
77abb4c6
NC
1474#ifdef DEBUG_LEAKING_SCALARS_ABORT
1475 if (PL_sv_count)
1f4fbd3b 1476 abort();
77abb4c6 1477#endif
bf9cdc68 1478 PL_sv_count = 0;
eba0f806 1479
56a2bab7 1480#if defined(PERLIO_LAYERS)
3a1ee7e8
NIS
1481 /* No more IO - including error messages ! */
1482 PerlIO_cleanup(aTHX);
1483#endif
1484
9f4bd222 1485 /* sv_undef needs to stay immortal until after PerlIO_cleanup
a0714e2c 1486 as currently layers use it rather than NULL as a marker
9f4bd222
NIS
1487 for no arg - and will try and SvREFCNT_dec it.
1488 */
1489 SvREFCNT(&PL_sv_undef) = 0;
1490 SvREADONLY_off(&PL_sv_undef);
1491
3280af22 1492 Safefree(PL_origfilename);
bd61b366 1493 PL_origfilename = NULL;
43c5f42d 1494 Safefree(PL_reg_curpm);
dd28f7bb 1495 free_tied_hv_pool();
3280af22 1496 Safefree(PL_op_mask);
cf36064f 1497 Safefree(PL_psig_name);
bf9cdc68 1498 PL_psig_name = (SV**)NULL;
d525a7b2 1499 PL_psig_ptr = (SV**)NULL;
31c91b43 1500 {
1f4fbd3b
MS
1501 /* We need to NULL PL_psig_pend first, so that
1502 signal handlers know not to use it */
1503 int *psig_save = PL_psig_pend;
1504 PL_psig_pend = (int*)NULL;
1505 Safefree(psig_save);
31c91b43 1506 }
6e72f9df 1507 nuke_stacks();
284167a5
S
1508 TAINTING_set(FALSE);
1509 TAINT_WARN_set(FALSE);
3280af22 1510 PL_hints = 0; /* Reset hints. Should hints be per-interpreter ? */
ac27b0f5 1511
a0d0e21e 1512 DEBUG_P(debprofdump());
d33b2eba 1513
b173165c
FC
1514 PL_debug = 0;
1515
e5dd39fc 1516#ifdef USE_REENTRANT_API
10bc17b6 1517 Perl_reentrant_free(aTHX);
e5dd39fc
AB
1518#endif
1519
a24da70b
NC
1520 /* These all point to HVs that are about to be blown away.
1521 Code in core and on CPAN assumes that if the interpreter is re-started
1522 that they will be cleanly NULL or pointing to a valid HV. */
1523 PL_custom_op_names = NULL;
1524 PL_custom_op_descs = NULL;
1525 PL_custom_ops = NULL;
1526
612f20c3
GS
1527 sv_free_arenas();
1528
5d9a96ca 1529 while (PL_regmatch_slab) {
1f4fbd3b
MS
1530 regmatch_slab *s = PL_regmatch_slab;
1531 PL_regmatch_slab = PL_regmatch_slab->next;
1532 Safefree(s);
5d9a96ca
DM
1533 }
1534
fc36a67e 1535 /* As the absolutely last thing, free the non-arena SV for mess() */
1536
3280af22 1537 if (PL_mess_sv) {
1f4fbd3b
MS
1538 /* we know that type == SVt_PVMG */
1539
1540 /* it could have accumulated taint magic */
1541 MAGIC* mg;
1542 MAGIC* moremagic;
1543 for (mg = SvMAGIC(PL_mess_sv); mg; mg = moremagic) {
1544 moremagic = mg->mg_moremagic;
1545 if (mg->mg_ptr && mg->mg_type != PERL_MAGIC_regex_global
1546 && mg->mg_len >= 0)
1547 Safefree(mg->mg_ptr);
1548 Safefree(mg);
1549 }
1550
1551 /* we know that type >= SVt_PV */
1552 SvPV_free(PL_mess_sv);
1553 Safefree(SvANY(PL_mess_sv));
1554 Safefree(PL_mess_sv);
1555 PL_mess_sv = NULL;
fc36a67e 1556 }
37038d91 1557 return STATUS_EXIT;
79072805
LW
1558}
1559
954c1994
GS
1560/*
1561=for apidoc perl_free
1562
1563Releases a Perl interpreter. See L<perlembed>.
1564
1565=cut
1566*/
1567
79072805 1568void
0cb96387 1569perl_free(pTHXx)
79072805 1570{
5174512c 1571
7918f24d
NC
1572 PERL_ARGS_ASSERT_PERL_FREE;
1573
c301d606 1574 if (PL_veto_cleanup)
1f4fbd3b 1575 return;
c301d606 1576
7cb608b5 1577#ifdef PERL_TRACK_MEMPOOL
55ef9aae 1578 {
1f4fbd3b
MS
1579 /*
1580 * Don't free thread memory if PERL_DESTRUCT_LEVEL is set to a non-zero
1581 * value as we're probably hunting memory leaks then
1582 */
1583 if (PL_perl_destruct_level == 0) {
1584 const U32 old_debug = PL_debug;
1585 /* Emulate the PerlHost behaviour of free()ing all memory allocated in this
1586 thread at thread exit. */
1587 if (DEBUG_m_TEST) {
1588 PerlIO_puts(Perl_debug_log, "Disabling memory debugging as we "
1589 "free this thread's memory\n");
1590 PL_debug &= ~ DEBUG_m_FLAG;
1591 }
1592 while(aTHXx->Imemory_debug_header.next != &(aTHXx->Imemory_debug_header)){
1593 char * next = (char *)(aTHXx->Imemory_debug_header.next);
1594 Malloc_t ptr = PERL_MEMORY_DEBUG_HEADER_SIZE + next;
1595 safesysfree(ptr);
1596 }
1597 PL_debug = old_debug;
1598 }
55ef9aae 1599 }
7cb608b5
NC
1600#endif
1601
2eb109a4 1602#if defined(WIN32)
ce3e5b80 1603# if defined(PERL_IMPLICIT_SYS)
b36c9a52 1604 {
2eb109a4
DIM
1605 void *host = w32_internal_host;
1606 PerlMem_free(aTHXx);
1607 win32_delete_internal_host(host);
7af12a34 1608 }
1c0ca838
GS
1609# else
1610 PerlMem_free(aTHXx);
1611# endif
acfe0abc
GS
1612#else
1613 PerlMem_free(aTHXx);
76e3520e 1614#endif
79072805
LW
1615}
1616
b7f7fff6 1617#if defined(USE_ITHREADS)
aebd1ac7
GA
1618/* provide destructors to clean up the thread key when libperl is unloaded */
1619#ifndef WIN32 /* handled during DLL_PROCESS_DETACH in win32/perllib.c */
1620
826955bd 1621#if defined(__hpux) && !(defined(__ux_version) && __ux_version <= 1020) && !defined(__GNUC__)
aebd1ac7 1622#pragma fini "perl_fini"
666ad1ec
GA
1623#elif defined(__sun) && !defined(__GNUC__)
1624#pragma fini (perl_fini)
aebd1ac7
GA
1625#endif
1626
0dbb1585
AL
1627static void
1628#if defined(__GNUC__)
1629__attribute__((destructor))
aebd1ac7 1630#endif
de009b76 1631perl_fini(void)
aebd1ac7 1632{
5c64bffd 1633 if (
5c64bffd 1634 PL_curinterp && !PL_veto_cleanup)
1f4fbd3b 1635 FREE_THREAD_KEY;
aebd1ac7
GA
1636}
1637
1638#endif /* WIN32 */
1639#endif /* THREADS */
1640
4de0ce36
KW
1641/*
1642=for apidoc call_atexit
1643
1644Add a function C<fn> to the list of functions to be called at global
1645destruction. C<ptr> will be passed as an argument to C<fn>; it can point to a
1646C<struct> so that you can pass anything you want.
1647
1648Note that under threads, C<fn> may run multiple times. This is because the
1649list is executed each time the current or any descendent thread terminates.
1650
1651=cut
1652*/
1653
4b556e6c 1654void
864dbfa3 1655Perl_call_atexit(pTHX_ ATEXIT_t fn, void *ptr)
4b556e6c 1656{
3280af22
NIS
1657 Renew(PL_exitlist, PL_exitlistlen+1, PerlExitListEntry);
1658 PL_exitlist[PL_exitlistlen].fn = fn;
1659 PL_exitlist[PL_exitlistlen].ptr = ptr;
1660 ++PL_exitlistlen;
4b556e6c
JD
1661}
1662
b95d2334
TK
1663#ifdef USE_ENVIRON_ARRAY
1664static void
1665dup_environ(pTHX)
1666{
1667# ifdef USE_ITHREADS
1668 if (aTHX != PL_curinterp)
1669 return;
1670# endif
1671 if (!environ)
1672 return;
1673
1674 size_t n_entries = 0, vars_size = 0;
1675
1676 for (char **ep = environ; *ep; ++ep) {
1677 ++n_entries;
1678 vars_size += strlen(*ep) + 1;
1679 }
1680
1681 /* To save memory, we store both the environ array and its values in a
1682 * single memory block. */
1683 char **new_environ = (char**)PerlMemShared_malloc(
1684 (sizeof(char*) * (n_entries + 1)) + vars_size
1685 );
1686 char *vars = (char*)(new_environ + n_entries + 1);
1687
1688 for (size_t i = 0, copied = 0; n_entries > i; ++i) {
1689 size_t len = strlen(environ[i]) + 1;
01aede5a 1690 new_environ[i] = (char *) CopyD(environ[i], vars + copied, len, char);
b95d2334
TK
1691 copied += len;
1692 }
1693 new_environ[n_entries] = NULL;
1694
1695 environ = new_environ;
1696 /* Store a pointer in a global variable to ensure it's always reachable so
1697 * LeakSanitizer/Valgrind won't complain about it. We can't ever free it.
1698 * Even if libc allocates a new environ, it's possible that some of its
1699 * values will still be pointing to the old environ.
1700 */
1701 PL_my_environ = new_environ;
1702}
1703#endif
1704
954c1994 1705/*
44170c9a 1706=for apidoc perl_parse
0301e899
Z
1707
1708Tells a Perl interpreter to parse a Perl script. This performs most
1709of the initialisation of a Perl interpreter. See L<perlembed> for
1710a tutorial.
1711
1712C<my_perl> points to the Perl interpreter that is to parse the script.
1713It must have been previously created through the use of L</perl_alloc>
1714and L</perl_construct>. C<xsinit> points to a callback function that
1715will be called to set up the ability for this Perl interpreter to load
1716XS extensions, or may be null to perform no such setup.
1717
1718C<argc> and C<argv> supply a set of command-line arguments to the Perl
1719interpreter, as would normally be passed to the C<main> function of
1720a C program. C<argv[argc]> must be null. These arguments are where
1721the script to parse is specified, either by naming a script file or by
1722providing a script in a C<-e> option.
a3e261d5
Z
1723If L<C<$0>|perlvar/$0> will be written to in the Perl interpreter, then
1724the argument strings must be in writable memory, and so mustn't just be
1725string constants.
0301e899
Z
1726
1727C<env> specifies a set of environment variables that will be used by
1728this Perl interpreter. If non-null, it must point to a null-terminated
1729array of environment strings. If null, the Perl interpreter will use
1730the environment supplied by the C<environ> global variable.
1731
1732This function initialises the interpreter, and parses and compiles the
1733script specified by the command-line arguments. This includes executing
1734code in C<BEGIN>, C<UNITCHECK>, and C<CHECK> blocks. It does not execute
1735C<INIT> blocks or the main program.
1736
1737Returns an integer of slightly tricky interpretation. The correct
1738use of the return value is as a truth value indicating whether there
1739was a failure in initialisation. If zero is returned, this indicates
1740that initialisation was successful, and it is safe to proceed to call
1741L</perl_run> and make other use of it. If a non-zero value is returned,
1742this indicates some problem that means the interpreter wants to terminate.
1743The interpreter should not be just abandoned upon such failure; the caller
1744should proceed to shut the interpreter down cleanly with L</perl_destruct>
1745and free it with L</perl_free>.
1746
1747For historical reasons, the non-zero return value also attempts to
1748be a suitable value to pass to the C library function C<exit> (or to
1749return from C<main>), to serve as an exit code indicating the nature
1750of the way initialisation terminated. However, this isn't portable,
197bb3f4
YO
1751due to differing exit code conventions. An attempt is made to return
1752an exit code of the type required by the host operating system, but
1753because it is constrained to be non-zero, it is not necessarily possible
1754to indicate every type of exit. It is only reliable on Unix, where a
1755zero exit code can be augmented with a set bit that will be ignored.
1756In any case, this function is not the correct place to acquire an exit
1757code: one should get that from L</perl_destruct>.
0301e899 1758
954c1994
GS
1759=cut
1760*/
1761
03d9f026 1762#define SET_CURSTASH(newstash) \
1f4fbd3b
MS
1763 if (PL_curstash != newstash) { \
1764 SvREFCNT_dec(PL_curstash); \
1765 PL_curstash = (HV *)SvREFCNT_inc(newstash); \
1766 }
03d9f026 1767
79072805 1768int
0cb96387 1769perl_parse(pTHXx_ XSINIT_t xsinit, int argc, char **argv, char **env)
8d063cd8 1770{
6224f72b 1771 I32 oldscope;
6224f72b 1772 int ret;
db36c5a1 1773 dJMPENV;
8d063cd8 1774
7918f24d
NC
1775 PERL_ARGS_ASSERT_PERL_PARSE;
1776#ifndef MULTIPLICITY
ed6c66dd 1777 PERL_UNUSED_ARG(my_perl);
7918f24d 1778#endif
c3c9d6b1 1779 debug_hash_seed(false);
ea34f6bd 1780#ifdef __amigaos4__
43238333
AB
1781 {
1782 struct NameTranslationInfo nti;
1f4fbd3b 1783 __translate_amiga_to_unix_path_name(&argv[0],&nti);
43238333
AB
1784 }
1785#endif
1786
cc85e83f 1787 {
1f4fbd3b
MS
1788 int i;
1789 assert(argc >= 0);
1790 for(i = 0; i != argc; i++)
1791 assert(argv[i]);
1792 assert(!argv[argc]);
cc85e83f 1793 }
3280af22 1794 PL_origargc = argc;
e2975953 1795 PL_origargv = argv;
a0d0e21e 1796
a2722ac9 1797 if (PL_origalen != 0) {
1f4fbd3b 1798 PL_origalen = 1; /* don't use old PL_origalen if perl_parse() is called again */
a2722ac9
GA
1799 }
1800 else {
1f4fbd3b
MS
1801 /* Set PL_origalen be the sum of the contiguous argv[]
1802 * elements plus the size of the env in case that it is
1803 * contiguous with the argv[]. This is used in mg.c:Perl_magic_set()
1804 * as the maximum modifiable length of $0. In the worst case
1805 * the area we are able to modify is limited to the size of
1806 * the original argv[0]. (See below for 'contiguous', though.)
1807 * --jhi */
1808 const char *s = NULL;
1809 const UV mask = ~(UV)(PTRSIZE-1);
43c32782 1810 /* Do the mask check only if the args seem like aligned. */
1f4fbd3b
MS
1811 const UV aligned =
1812 (mask < ~(UV)0) && ((PTR2UV(argv[0]) & mask) == PTR2UV(argv[0]));
1813
1814 /* See if all the arguments are contiguous in memory. Note
1815 * that 'contiguous' is a loose term because some platforms
1816 * align the argv[] and the envp[]. If the arguments look
1817 * like non-aligned, assume that they are 'strictly' or
1818 * 'traditionally' contiguous. If the arguments look like
1819 * aligned, we just check that they are within aligned
1820 * PTRSIZE bytes. As long as no system has something bizarre
1821 * like the argv[] interleaved with some other data, we are
1822 * fine. (Did I just evoke Murphy's Law?) --jhi */
1823 if (PL_origargv && PL_origargc >= 1 && (s = PL_origargv[0])) {
19742f39 1824 int i;
1f4fbd3b
MS
1825 while (*s) s++;
1826 for (i = 1; i < PL_origargc; i++) {
1827 if ((PL_origargv[i] == s + 1
43c32782 1828#ifdef OS2
1f4fbd3b
MS
1829 || PL_origargv[i] == s + 2
1830#endif
1831 )
1832 ||
1833 (aligned &&
1834 (PL_origargv[i] > s &&
1835 PL_origargv[i] <=
1836 INT2PTR(char *, PTR2UV(s + PTRSIZE) & mask)))
1837 )
1838 {
1839 s = PL_origargv[i];
1840 while (*s) s++;
1841 }
1842 else
1843 break;
1844 }
1845 }
a4a109c2 1846
ae6b6b71 1847#ifdef USE_ENVIRON_ARRAY
1f4fbd3b 1848 /* Can we grab env area too to be used as the area for $0? */
b95d2334 1849 if (s && PL_origenviron) {
1f4fbd3b
MS
1850 if ((PL_origenviron[0] == s + 1)
1851 ||
1852 (aligned &&
1853 (PL_origenviron[0] > s &&
1854 PL_origenviron[0] <=
1855 INT2PTR(char *, PTR2UV(s + PTRSIZE) & mask)))
1856 )
1857 {
19742f39 1858 int i;
9d419b5f 1859#ifndef OS2 /* ENVIRON is read by the kernel too. */
1f4fbd3b
MS
1860 s = PL_origenviron[0];
1861 while (*s) s++;
1862#endif
b95d2334 1863
1f4fbd3b 1864 /* Force copy of environment. */
b95d2334
TK
1865 if (PL_origenviron == environ)
1866 dup_environ(aTHX);
ae6b6b71 1867
1f4fbd3b
MS
1868 for (i = 1; PL_origenviron[i]; i++) {
1869 if (PL_origenviron[i] == s + 1
1870 ||
1871 (aligned &&
1872 (PL_origenviron[i] > s &&
1873 PL_origenviron[i] <=
1874 INT2PTR(char *, PTR2UV(s + PTRSIZE) & mask)))
1875 )
1876 {
1877 s = PL_origenviron[i];
1878 while (*s) s++;
1879 }
1880 else
1881 break;
1882 }
1883 }
1884 }
ae6b6b71 1885#endif /* USE_ENVIRON_ARRAY */
a4a109c2 1886
1f4fbd3b 1887 PL_origalen = s ? s - PL_origargv[0] + 1 : 0;
54bfe034
JH
1888 }
1889
3280af22 1890 if (PL_do_undump) {
a0d0e21e 1891
1f4fbd3b 1892 /* Come here if running an undumped a.out. */
a0d0e21e 1893
1f4fbd3b
MS
1894 PL_origfilename = savepv(argv[0]);
1895 PL_do_undump = FALSE;
1896 cxstack_ix = -1; /* start label stack again */
1897 init_ids();
1898 assert (!TAINT_get);
1899 TAINT;
1900 set_caret_X();
1901 TAINT_NOT;
1902 init_postdump_symbols(argc,argv,env);
1903 return 0;
a0d0e21e
LW
1904 }
1905
3280af22 1906 if (PL_main_root) {
1f4fbd3b
MS
1907 op_free(PL_main_root);
1908 PL_main_root = NULL;
ff0cee69 1909 }
5f66b61c 1910 PL_main_start = NULL;
3280af22 1911 SvREFCNT_dec(PL_main_cv);
601f1833 1912 PL_main_cv = NULL;
79072805 1913
3280af22
NIS
1914 time(&PL_basetime);
1915 oldscope = PL_scopestack_ix;
599cee73 1916 PL_dowarn = G_WARN_OFF;
f86702cc 1917
14dd3ad8 1918 JMPENV_PUSH(ret);
6224f72b 1919 switch (ret) {
312caa8e 1920 case 0:
1f4fbd3b
MS
1921 parse_body(env,xsinit);
1922 if (PL_unitcheckav) {
1923 call_list(oldscope, PL_unitcheckav);
1924 }
1925 if (PL_checkav) {
1926 PERL_SET_PHASE(PERL_PHASE_CHECK);
1927 call_list(oldscope, PL_checkav);
1928 }
1929 ret = 0;
1930 break;
6224f72b 1931 case 1:
1f4fbd3b
MS
1932 STATUS_ALL_FAILURE;
1933 /* FALLTHROUGH */
6224f72b 1934 case 2:
1f4fbd3b
MS
1935 /* my_exit() was called */
1936 while (PL_scopestack_ix > oldscope)
1937 LEAVE;
1938 FREETMPS;
1939 SET_CURSTASH(PL_defstash);
1940 if (PL_unitcheckav) {
1941 call_list(oldscope, PL_unitcheckav);
1942 }
1943 if (PL_checkav) {
1944 PERL_SET_PHASE(PERL_PHASE_CHECK);
1945 call_list(oldscope, PL_checkav);
1946 }
1947 ret = STATUS_EXIT;
1948 if (ret == 0) {
1949 /*
197bb3f4
YO
1950 * We do this here to avoid [perl #2754].
1951 * Note this may cause trouble with Module::Install.
1952 * See: [perl #132577].
1f4fbd3b 1953 */
197bb3f4 1954 ret = 0x100;
1f4fbd3b
MS
1955 }
1956 break;
6224f72b 1957 case 3:
1f4fbd3b
MS
1958 PerlIO_printf(Perl_error_log, "panic: top_env\n");
1959 ret = 1;
1960 break;
6224f72b 1961 }
14dd3ad8
GS
1962 JMPENV_POP;
1963 return ret;
1964}
1965
4a5df386
NC
1966/* This needs to stay in perl.c, as perl.c is compiled with different flags for
1967 miniperl, and we need to see those flags reflected in the values here. */
1968
1969/* What this returns is subject to change. Use the public interface in Config.
1970 */
86d84dd0 1971
4a5df386
NC
1972static void
1973S_Internals_V(pTHX_ CV *cv)
1974{
1975 dXSARGS;
1976#ifdef LOCAL_PATCH_COUNT
1977 const int local_patch_count = LOCAL_PATCH_COUNT;
1978#else
1979 const int local_patch_count = 0;
1980#endif
2dc296d2 1981 const int entries = 3 + local_patch_count;
4a5df386 1982 int i;
00b42049
YO
1983 /* NOTE - This list must remain sorted. Do not put any settings here
1984 * which affect binary compatibility */
1f4fbd3b 1985 static const char non_bincompat_options[] =
4a5df386 1986# ifdef DEBUGGING
1f4fbd3b 1987 " DEBUGGING"
4a5df386
NC
1988# endif
1989# ifdef NO_MATHOMS
1f4fbd3b 1990 " NO_MATHOMS"
4a5df386 1991# endif
3b0e4ee2 1992# ifdef NO_TAINT_SUPPORT
1f4fbd3b 1993 " NO_TAINT_SUPPORT"
3b0e4ee2 1994# endif
93c10d60 1995# ifdef PERL_COPY_ON_WRITE
1f4fbd3b 1996 " PERL_COPY_ON_WRITE"
93c10d60 1997# endif
4a5df386 1998# ifdef PERL_DISABLE_PMC
1f4fbd3b 1999 " PERL_DISABLE_PMC"
4a5df386
NC
2000# endif
2001# ifdef PERL_DONT_CREATE_GVSV
1f4fbd3b 2002 " PERL_DONT_CREATE_GVSV"
4a5df386 2003# endif
9a044a43 2004# ifdef PERL_EXTERNAL_GLOB
1f4fbd3b 2005 " PERL_EXTERNAL_GLOB"
9a044a43 2006# endif
4a5df386 2007# ifdef PERL_IS_MINIPERL
1f4fbd3b 2008 " PERL_IS_MINIPERL"
4a5df386
NC
2009# endif
2010# ifdef PERL_MALLOC_WRAP
1f4fbd3b 2011 " PERL_MALLOC_WRAP"
4a5df386
NC
2012# endif
2013# ifdef PERL_MEM_LOG
1f4fbd3b 2014 " PERL_MEM_LOG"
4a5df386
NC
2015# endif
2016# ifdef PERL_MEM_LOG_NOIMPL
1f4fbd3b 2017 " PERL_MEM_LOG_NOIMPL"
4a5df386 2018# endif
4e499636 2019# ifdef PERL_OP_PARENT
1f4fbd3b 2020 " PERL_OP_PARENT"
4e499636 2021# endif
59b86f4b 2022# ifdef PERL_PERTURB_KEYS_DETERMINISTIC
1f4fbd3b 2023 " PERL_PERTURB_KEYS_DETERMINISTIC"
59b86f4b
DM
2024# endif
2025# ifdef PERL_PERTURB_KEYS_DISABLED
1f4fbd3b 2026 " PERL_PERTURB_KEYS_DISABLED"
59b86f4b
DM
2027# endif
2028# ifdef PERL_PERTURB_KEYS_RANDOM
1f4fbd3b 2029 " PERL_PERTURB_KEYS_RANDOM"
59b86f4b 2030# endif
c3cf41ec 2031# ifdef PERL_PRESERVE_IVUV
1f4fbd3b 2032 " PERL_PRESERVE_IVUV"
c3cf41ec 2033# endif
c051e30b 2034# ifdef PERL_RELOCATABLE_INCPUSH
1f4fbd3b 2035 " PERL_RELOCATABLE_INCPUSH"
c051e30b 2036# endif
4a5df386 2037# ifdef PERL_USE_DEVEL
1f4fbd3b 2038 " PERL_USE_DEVEL"
4a5df386
NC
2039# endif
2040# ifdef PERL_USE_SAFE_PUTENV
1f4fbd3b 2041 " PERL_USE_SAFE_PUTENV"
4a5df386 2042# endif
86d84dd0 2043
d4c01272
YO
2044# ifdef PERL_USE_UNSHARED_KEYS_IN_LARGE_HASHES
2045 " PERL_USE_UNSHARED_KEYS_IN_LARGE_HASHES"
2046# endif
102b7877 2047# ifdef SILENT_NO_TAINT_SUPPORT
1f4fbd3b 2048 " SILENT_NO_TAINT_SUPPORT"
102b7877 2049# endif
a3749cf3 2050# ifdef UNLINK_ALL_VERSIONS
1f4fbd3b 2051 " UNLINK_ALL_VERSIONS"
a3749cf3 2052# endif
de618ee4 2053# ifdef USE_ATTRIBUTES_FOR_PERLIO
1f4fbd3b 2054 " USE_ATTRIBUTES_FOR_PERLIO"
de618ee4 2055# endif
4a5df386 2056# ifdef USE_FAST_STDIO
1f4fbd3b
MS
2057 " USE_FAST_STDIO"
2058# endif
98548bdf 2059# ifdef USE_LOCALE
1f4fbd3b 2060 " USE_LOCALE"
98548bdf 2061# endif
98548bdf 2062# ifdef USE_LOCALE_CTYPE
1f4fbd3b 2063 " USE_LOCALE_CTYPE"
98548bdf 2064# endif
6937817d 2065# ifdef WIN32_NO_REGISTRY
1f4fbd3b 2066 " USE_NO_REGISTRY"
6937817d 2067# endif
5a8d8935 2068# ifdef USE_PERL_ATOF
1f4fbd3b
MS
2069 " USE_PERL_ATOF"
2070# endif
0d311fbe 2071# ifdef USE_SITECUSTOMIZE
1f4fbd3b
MS
2072 " USE_SITECUSTOMIZE"
2073# endif
25a72d73 2074# ifdef USE_THREAD_SAFE_LOCALE
1f4fbd3b 2075 " USE_THREAD_SAFE_LOCALE"
25a72d73 2076# endif
bf2a3dae
YO
2077# ifdef NO_PERL_RAND_SEED
2078 " NO_PERL_RAND_SEED"
2079# endif
2080# ifdef NO_PERL_INTERNAL_RAND_SEED
2081 " NO_PERL_INTERNAL_RAND_SEED"
2082# endif
1f4fbd3b 2083 ;
4a5df386 2084 PERL_UNUSED_ARG(cv);
d3db1514 2085 PERL_UNUSED_VAR(items);
4a5df386
NC
2086
2087 EXTEND(SP, entries);
2088
c80a8618
RL
2089 PUSHs(newSVpvn_flags(PL_bincompat_options, strlen(PL_bincompat_options),
2090 SVs_TEMP));
4a5df386 2091 PUSHs(Perl_newSVpvn_flags(aTHX_ non_bincompat_options,
1f4fbd3b 2092 sizeof(non_bincompat_options) - 1, SVs_TEMP));
4a5df386 2093
6baa8dbd
NT
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
4a5df386 2105 PUSHs(Perl_newSVpvn_flags(aTHX_
1f4fbd3b
MS
2106 STR_WITH_LEN("Compiled at " PERL_BUILD_DATE),
2107 SVs_TEMP));
4a5df386
NC
2108#else
2109 PUSHs(&PL_sv_undef);
2110#endif
2111
4a5df386 2112 for (i = 1; i <= local_patch_count; i++) {
1f4fbd3b 2113 /* This will be an undef, if PL_localpatches[i] is NULL. */
c80a8618
RL
2114 PUSHs(newSVpvn_flags(PL_localpatches[i],
2115 PL_localpatches[i] == NULL ? 0 : strlen(PL_localpatches[i]),
2116 SVs_TEMP));
4a5df386
NC
2117 }
2118
2119 XSRETURN(entries);
2120}
2121
be71fc8f
NC
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
1e3208d8
NC
2128#define INCPUSH_ADD_SUB_DIRS \
2129 (INCPUSH_ADD_VERSIONED_SUB_DIRS|INCPUSH_ADD_ARCHONLY_SUB_DIRS)
e28f3139 2130
312caa8e 2131STATIC void *
14dd3ad8 2132S_parse_body(pTHX_ char **env, XSINIT_t xsinit)
312caa8e 2133{
2f9285f8 2134 PerlIO *rsfp;
312caa8e 2135 int argc = PL_origargc;
8f42b153 2136 char **argv = PL_origargv;
e1ec3a88 2137 const char *scriptname = NULL;
402582ca 2138 bool dosearch = FALSE;
eb578fdb 2139 char c;
737c24fc 2140 bool doextract = FALSE;
bd61b366 2141 const char *cddir = NULL;
b1cc9c03 2142 bool minus_e = FALSE; /* both -e and -E */
ab019eaa 2143#ifdef USE_SITECUSTOMIZE
20ef40cf 2144 bool minus_f = FALSE;
ab019eaa 2145#endif
95670bde 2146 SV *linestr_sv = NULL;
5486870f 2147 bool add_read_e_script = FALSE;
87606032 2148 U32 lex_start_flags = 0;
009d90df 2149
ca7b837b 2150 PERL_SET_PHASE(PERL_PHASE_START);
9ebf26ad 2151
6224f72b 2152 init_main_stash();
54310121 2153
c7030b81 2154 {
1f4fbd3b 2155 const char *s;
6224f72b 2156 for (argc--,argv++; argc > 0; argc--,argv++) {
1f4fbd3b
MS
2157 if (argv[0][0] != '-' || !argv[0][1])
2158 break;
2159 s = argv[0]+1;
6224f72b 2160 reswitch:
1f4fbd3b
MS
2161 switch ((c = *s)) {
2162 case 'C':
1d5472a9 2163#ifndef PERL_STRICT_CR
1f4fbd3b
MS
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':
9cb26ed2 2173 case 'g':
ace3ef6f 2174 case '?':
1f4fbd3b
MS
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':
dc6d7f5c 2194#if defined(SILENT_NO_TAINT_SUPPORT)
284167a5 2195 /* silently ignore */
dc6d7f5c 2196#elif defined(NO_TAINT_SUPPORT)
3231f579 2197 Perl_croak_nocontext("This perl was compiled without taint support. "
284167a5
S
2198 "Cowardly refusing to run with -t or -T flags");
2199#else
1f4fbd3b
MS
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':
dc6d7f5c 2209#if defined(SILENT_NO_TAINT_SUPPORT)
284167a5 2210 /* silently ignore */
dc6d7f5c 2211#elif defined(NO_TAINT_SUPPORT)
3231f579 2212 Perl_croak_nocontext("This perl was compiled without taint support. "
284167a5
S
2213 "Cowardly refusing to run with -t or -T flags");
2214#else
1f4fbd3b
MS
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);
b1cc9c03 2227 minus_e = TRUE;
1f4fbd3b
MS
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':
f5542d3a 2244#ifdef USE_SITECUSTOMIZE
1f4fbd3b
MS
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 }
8d063cd8 2310 }
c7030b81
NC
2311 }
2312
6224f72b 2313 switch_end:
54310121 2314
c7030b81 2315 {
1f4fbd3b 2316 char *s;
c7030b81 2317
f675dbe5
CB
2318 if (
2319#ifndef SECURE_INTERNAL_GETENV
284167a5 2320 !TAINTING_get &&
f675dbe5 2321#endif
1f4fbd3b 2322 (s = PerlEnv_getenv("PERL5OPT")))
0df16ed7 2323 {
1f4fbd3b
MS
2324 while (isSPACE(*s))
2325 s++;
2326 if (*s == '-' && *(s+1) == 'T') {
dc6d7f5c 2327#if defined(SILENT_NO_TAINT_SUPPORT)
284167a5 2328 /* silently ignore */
dc6d7f5c 2329#elif defined(NO_TAINT_SUPPORT)
3231f579 2330 Perl_croak_nocontext("This perl was compiled without taint support. "
284167a5
S
2331 "Cowardly refusing to run with -t or -T flags");
2332#else
1f4fbd3b
MS
2333 CHECK_MALLOC_TOO_LATE_FOR('T');
2334 TAINTING_set(TRUE);
284167a5
S
2335 TAINT_WARN_set(FALSE);
2336#endif
1f4fbd3b
MS
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) {
c80a8618 2357 popt_copy = SvPVX(newSVpvn_flags(d, strlen(d), SVs_TEMP));
1f4fbd3b
MS
2358 s = popt_copy + (s - d);
2359 d = popt_copy;
2360 }
2361 *s++ = '\0';
2362 break;
2363 }
2364 }
2365 if (*d == 't') {
dc6d7f5c 2366#if defined(SILENT_NO_TAINT_SUPPORT)
284167a5 2367 /* silently ignore */
dc6d7f5c 2368#elif defined(NO_TAINT_SUPPORT)
3231f579 2369 Perl_croak_nocontext("This perl was compiled without taint support. "
284167a5
S
2370 "Cowardly refusing to run with -t or -T flags");
2371#else
1f4fbd3b
MS
2372 if( !TAINTING_get) {
2373 TAINT_WARN_set(TRUE);
2374 TAINTING_set(TRUE);
2375 }
2376#endif
2377 } else {
2378 moreswitches(d);
2379 }
2380 }
2381 }
6224f72b 2382 }
c7030b81 2383 }
a0d0e21e 2384
d6295071
TC
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 */
3337f21a 2393 if (TAINT_get &&
d6295071
TC
2394 PerlProc_getuid() == PerlProc_geteuid() &&
2395 PerlProc_getgid() == PerlProc_getegid()) {
2396 Perl_drand48_init_r(&PL_internal_random_state, seed());
2397 }
2398#endif
c3c9d6b1
YO
2399 if (DEBUG_h_TEST)
2400 debug_hash_seed(true);
d6295071 2401
c29067d7
CH
2402 /* Set $^X early so that it can be used for relocatable paths in @INC */
2403 /* and for SITELIB_EXP in USE_SITECUSTOMIZE */
284167a5 2404 assert (!TAINT_get);
c29067d7 2405 TAINT;
e2051532 2406 set_caret_X();
c29067d7
CH
2407 TAINT_NOT;
2408
43c0c913 2409#if defined(USE_SITECUSTOMIZE)
20ef40cf 2410 if (!minus_f) {
1f4fbd3b
MS
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) ' */
43c0c913 2415# ifdef PERL_IS_MINIPERL
1f4fbd3b
MS
2416 AV *const inc = GvAV(PL_incgv);
2417 SV **const inc0 = inc ? av_fetch(inc, 0, FALSE) : NULL;
43c0c913 2418
1f4fbd3b 2419 if (inc0) {
15870c5c
NC
2420 /* if lib/buildcustomize.pl exists, it should not fail. If it does,
2421 it should be reported immediately as a build failure. */
1f4fbd3b
MS
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: $!' }",
5de87db5 2427 0, (TAINTING_get ? "./" : ""), SVfARG(*inc0), 0));
1f4fbd3b 2428 }
43c0c913 2429# else
1f4fbd3b
MS
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 }
43c0c913 2445# endif
20ef40cf
GA
2446 }
2447#endif
2448
6224f72b 2449 if (!scriptname)
1f4fbd3b 2450 scriptname = argv[0];
3280af22 2451 if (PL_e_script) {
1f4fbd3b
MS
2452 argc++,argv--;
2453 scriptname = BIT_BUCKET; /* don't look for script or read stdin */
6224f72b 2454 }
bd61b366 2455 else if (scriptname == NULL) {
1f4fbd3b 2456 scriptname = "-";
6224f72b
GS
2457 }
2458
284167a5 2459 assert (!TAINT_get);
2cace6ac 2460 init_perllib();
6224f72b 2461
a52eba0e 2462 {
1f4fbd3b 2463 bool suidscript = FALSE;
829372d3 2464
1f4fbd3b
MS
2465 rsfp = open_script(scriptname, dosearch, &suidscript);
2466 if (!rsfp) {
2467 rsfp = PerlIO_stdin();
2468 lex_start_flags = LEX_DONT_CLOSE_RSFP;
2469 }
6224f72b 2470
1f4fbd3b 2471 validate_suid(rsfp);
6224f72b 2472
64ca3a65 2473#ifndef PERL_MICRO
a52eba0e 2474# if defined(SIGCHLD) || defined(SIGCLD)
1f4fbd3b 2475 {
a52eba0e
NC
2476# ifndef SIGCHLD
2477# define SIGCHLD SIGCLD
2478# endif
1f4fbd3b
MS
2479 Sighandler_t sigstate = rsignal_state(SIGCHLD);
2480 if (sigstate == (Sighandler_t) SIG_IGN) {
2481 Perl_ck_warner(aTHX_ packWARN(WARN_SIGNAL),
2482 "Can't ignore signal CHLD, forcing to default");
2483 (void)rsignal(SIGCHLD, (Sighandler_t)SIG_DFL);
2484 }
2485 }
a52eba0e 2486# endif
64ca3a65 2487#endif
0b5b802d 2488
1f4fbd3b 2489 if (doextract) {
faef540c 2490
1f4fbd3b
MS
2491 /* This will croak if suidscript is true, as -x cannot be used with
2492 setuid scripts. */
2493 forbid_setid('x', suidscript);
2494 /* Hence you can't get here if suidscript is true */
faef540c 2495
1f4fbd3b
MS
2496 linestr_sv = newSV_type(SVt_PV);
2497 lex_start_flags |= LEX_START_COPIED;
2498 find_beginning(linestr_sv, rsfp);
2499 if (cddir && PerlDir_chdir( (char *)cddir ) < 0)
2500 Perl_croak(aTHX_ "Can't chdir to %s",cddir);
2501 }
f4c556ac 2502 }
6224f72b 2503
ea726b52 2504 PL_main_cv = PL_compcv = MUTABLE_CV(newSV_type(SVt_PVCV));
3280af22
NIS
2505 CvUNIQUE_on(PL_compcv);
2506
eacbb379 2507 CvPADLIST_set(PL_compcv, pad_new(0));
6224f72b 2508
dd69841b
BB
2509 PL_isarev = newHV();
2510
0c4f7ff0 2511 boot_core_PerlIO();
6224f72b 2512 boot_core_UNIVERSAL();
6a2e756f 2513 boot_core_builtin();
e1a479c5 2514 boot_core_mro();
4a5df386 2515 newXS("Internals::V", S_Internals_V, __FILE__);
6224f72b
GS
2516
2517 if (xsinit)
1f4fbd3b 2518 (*xsinit)(aTHX); /* in case linked C routines want magical variables */
64ca3a65 2519#ifndef PERL_MICRO
4457f3fc 2520#if defined(VMS) || defined(WIN32) || defined(__CYGWIN__)
c5be433b 2521 init_os_extras();
6224f72b 2522#endif
64ca3a65 2523#endif
6224f72b 2524
29209bc5 2525#ifdef USE_SOCKS
1b9c9cf5
DH
2526# ifdef HAS_SOCKS5_INIT
2527 socks5_init(argv[0]);
2528# else
29209bc5 2529 SOCKSinit(argv[0]);
1b9c9cf5 2530# endif
ac27b0f5 2531#endif
29209bc5 2532
6224f72b
GS
2533 init_predump_symbols();
2534 /* init_postdump_symbols not currently designed to be called */
2535 /* more than once (ENV isn't cleared first, for example) */
2536 /* But running with -u leaves %ENV & @ARGV undefined! XXX */
3280af22 2537 if (!PL_do_undump)
1f4fbd3b 2538 init_postdump_symbols(argc,argv,env);
6224f72b 2539
27da23d5
JH
2540 /* PL_unicode is turned on by -C, or by $ENV{PERL_UNICODE},
2541 * or explicitly in some platforms.
73e1bd1a 2542 * PL_utf8locale is conditionally turned on by
085a54d9 2543 * locale.c:Perl_init_i18nl10n() if the environment
a05d7ebb 2544 * look like the user wants to use UTF-8. */
e27b5b51 2545# ifndef PERL_IS_MINIPERL
06e66572 2546 if (PL_unicode) {
1f4fbd3b
MS
2547 /* Requires init_predump_symbols(). */
2548 if (!(PL_unicode & PERL_UNICODE_LOCALE_FLAG) || PL_utf8locale) {
2549 IO* io;
2550 PerlIO* fp;
2551 SV* sv;
2552
2553 /* Turn on UTF-8-ness on STDIN, STDOUT, STDERR
2554 * and the default open disciplines. */
2555 if ((PL_unicode & PERL_UNICODE_STDIN_FLAG) &&
2556 PL_stdingv && (io = GvIO(PL_stdingv)) &&
2557 (fp = IoIFP(io)))
2558 PerlIO_binmode(aTHX_ fp, IoTYPE(io), 0, ":utf8");
2559 if ((PL_unicode & PERL_UNICODE_STDOUT_FLAG) &&
2560 PL_defoutgv && (io = GvIO(PL_defoutgv)) &&
2561 (fp = IoOFP(io)))
2562 PerlIO_binmode(aTHX_ fp, IoTYPE(io), 0, ":utf8");
2563 if ((PL_unicode & PERL_UNICODE_STDERR_FLAG) &&
2564 PL_stderrgv && (io = GvIO(PL_stderrgv)) &&
2565 (fp = IoOFP(io)))
2566 PerlIO_binmode(aTHX_ fp, IoTYPE(io), 0, ":utf8");
2567 if ((PL_unicode & PERL_UNICODE_INOUT_FLAG) &&
2568 (sv = GvSV(gv_fetchpvs("\017PEN", GV_ADD|GV_NOTQUAL,
2569 SVt_PV)))) {
2570 U32 in = PL_unicode & PERL_UNICODE_IN_FLAG;
2571 U32 out = PL_unicode & PERL_UNICODE_OUT_FLAG;
2572 if (in) {
2573 if (out)
2574 sv_setpvs(sv, ":utf8\0:utf8");
2575 else
2576 sv_setpvs(sv, ":utf8\0");
2577 }
2578 else if (out)
2579 sv_setpvs(sv, "\0:utf8");
2580 SvSETMAGIC(sv);
2581 }
2582 }
b310b053 2583 }
e27b5b51 2584#endif
b310b053 2585
c7030b81 2586 {
1f4fbd3b 2587 const char *s;
4ffa73a3 2588 if ((s = PerlEnv_getenv("PERL_SIGNALS"))) {
1f4fbd3b
MS
2589 if (strEQ(s, "unsafe"))
2590 PL_signals |= PERL_SIGNALS_UNSAFE_FLAG;
2591 else if (strEQ(s, "safe"))
2592 PL_signals &= ~PERL_SIGNALS_UNSAFE_FLAG;
2593 else
2594 Perl_croak(aTHX_ "PERL_SIGNALS illegal: \"%s\"", s);
4ffa73a3 2595 }
c7030b81 2596 }
4ffa73a3 2597
81d86705 2598
87606032 2599 lex_start(linestr_sv, rsfp, lex_start_flags);
d2687c98 2600 SvREFCNT_dec(linestr_sv);
95670bde 2601
219f7226 2602 PL_subname = newSVpvs("main");
6224f72b 2603
5486870f 2604 if (add_read_e_script)
1f4fbd3b 2605 filter_add(read_e_script, NULL);
5486870f 2606
6224f72b 2607 /* now parse the script */
b1cc9c03
TR
2608 if (minus_e == FALSE)
2609 PL_hints |= HINTS_DEFAULT; /* after init_main_stash ; need to be after init_predump_symbols */
6224f72b 2610
93189314 2611 SETERRNO(0,SS_NORMAL);
28ac2b49 2612 if (yyparse(GRAMPROG) || PL_parser->error_count) {
eb54d46f 2613 abort_execution(NULL, PL_origfilename);
6224f72b 2614 }
57843af0 2615 CopLINE_set(PL_curcop, 0);
03d9f026 2616 SET_CURSTASH(PL_defstash);
3280af22 2617 if (PL_e_script) {
1f4fbd3b
MS
2618 SvREFCNT_dec(PL_e_script);
2619 PL_e_script = NULL;
6224f72b
GS
2620 }
2621
3280af22 2622 if (PL_do_undump)
1f4fbd3b 2623 my_unexec();
6224f72b 2624
57843af0 2625 if (isWARN_ONCE) {
1f4fbd3b
MS
2626 SAVECOPFILE(PL_curcop);
2627 SAVECOPLINE(PL_curcop);
2628 gv_check(PL_defstash);
57843af0 2629 }
6224f72b
GS
2630
2631 LEAVE;
2632 FREETMPS;
2633
2634#ifdef MYMALLOC
f6a607bc 2635 {
1f4fbd3b 2636 const char *s;
22ff3130
HS
2637 UV uv;
2638 s = PerlEnv_getenv("PERL_DEBUG_MSTATS");
2639 if (s && grok_atoUV(s, &uv, NULL) && uv >= 2)
96e440d2 2640 dump_mstats("after compilation:");
f6a607bc 2641 }
6224f72b
GS
2642#endif
2643
2644 ENTER;
febb3a6d 2645 PL_restartjmpenv = NULL;
3280af22 2646 PL_restartop = 0;
312caa8e 2647 return NULL;
6224f72b
GS
2648}
2649
954c1994 2650/*
44170c9a 2651=for apidoc perl_run
0301e899
Z
2652
2653Tells a Perl interpreter to run its main program. See L<perlembed>
2654for a tutorial.
2655
2656C<my_perl> points to the Perl interpreter. It must have been previously
2657created through the use of L</perl_alloc> and L</perl_construct>, and
2658initialised through L</perl_parse>. This function should not be called
2659if L</perl_parse> returned a non-zero value, indicating a failure in
2660initialisation or compilation.
2661
2662This function executes code in C<INIT> blocks, and then executes the
2663main program. The code to be executed is that established by the prior
2664call to L</perl_parse>. If the interpreter's C<PL_exit_flags> word
2665does not have the C<PERL_EXIT_DESTRUCT_END> flag set, then this function
2666will also execute code in C<END> blocks. If it is desired to make any
2667further use of the interpreter after calling this function, then C<END>
2668blocks should be postponed to L</perl_destruct> time by setting that flag.
2669
2670Returns an integer of slightly tricky interpretation. The correct use
2671of the return value is as a truth value indicating whether the program
2672terminated non-locally. If zero is returned, this indicates that
2673the program ran to completion, and it is safe to make other use of the
2674interpreter (provided that the C<PERL_EXIT_DESTRUCT_END> flag was set as
2675described above). If a non-zero value is returned, this indicates that
2676the interpreter wants to terminate early. The interpreter should not be
2677just abandoned because of this desire to terminate; the caller should
2678proceed to shut the interpreter down cleanly with L</perl_destruct>
2679and free it with L</perl_free>.
2680
2681For historical reasons, the non-zero return value also attempts to
2682be a suitable value to pass to the C library function C<exit> (or to
2683return from C<main>), to serve as an exit code indicating the nature of
2684the way the program terminated. However, this isn't portable, due to
2685differing exit code conventions. An attempt is made to return an exit
2686code of the type required by the host operating system, but because
2687it is constrained to be non-zero, it is not necessarily possible to
2688indicate every type of exit. It is only reliable on Unix, where a zero
2689exit code can be augmented with a set bit that will be ignored. In any
2690case, this function is not the correct place to acquire an exit code:
2691one should get that from L</perl_destruct>.
954c1994
GS
2692
2693=cut
2694*/
2695
6224f72b 2696int
0cb96387 2697perl_run(pTHXx)
6224f72b 2698{
6224f72b 2699 I32 oldscope;
9f960638 2700 int ret = 0;
db36c5a1 2701 dJMPENV;
6224f72b 2702
7918f24d
NC
2703 PERL_ARGS_ASSERT_PERL_RUN;
2704#ifndef MULTIPLICITY
ed6c66dd 2705 PERL_UNUSED_ARG(my_perl);
7918f24d 2706#endif
9d4ba2ae 2707
3280af22 2708 oldscope = PL_scopestack_ix;
96e176bf
CL
2709#ifdef VMS
2710 VMSISH_HUSHED = 0;
2711#endif
6224f72b 2712
14dd3ad8 2713 JMPENV_PUSH(ret);
6224f72b
GS
2714 switch (ret) {
2715 case 1:
1f4fbd3b
MS
2716 cxstack_ix = -1; /* start context stack again */
2717 goto redo_body;
14dd3ad8 2718 case 0: /* normal completion */
14dd3ad8 2719 redo_body:
1f4fbd3b
MS
2720 run_body(oldscope);
2721 /* FALLTHROUGH */
14dd3ad8 2722 case 2: /* my_exit() */
1f4fbd3b
MS
2723 while (PL_scopestack_ix > oldscope)
2724 LEAVE;
2725 FREETMPS;
2726 SET_CURSTASH(PL_defstash);
2727 if (!(PL_exit_flags & PERL_EXIT_DESTRUCT_END) &&
2728 PL_endav && !PL_minus_c) {
2729 PERL_SET_PHASE(PERL_PHASE_END);
2730 call_list(oldscope, PL_endav);
2731 }
6224f72b 2732#ifdef MYMALLOC
1f4fbd3b
MS
2733 if (PerlEnv_getenv("PERL_DEBUG_MSTATS"))
2734 dump_mstats("after execution: ");
6224f72b 2735#endif
1f4fbd3b
MS
2736 ret = STATUS_EXIT;
2737 break;
6224f72b 2738 case 3:
1f4fbd3b
MS
2739 if (PL_restartop) {
2740 POPSTACK_TO(PL_mainstack);
2741 goto redo_body;
2742 }
2743 PerlIO_printf(Perl_error_log, "panic: restartop in perl_run\n");
2744 FREETMPS;
2745 ret = 1;
2746 break;
6224f72b
GS
2747 }
2748
14dd3ad8
GS
2749 JMPENV_POP;
2750 return ret;
312caa8e
CS
2751}
2752
dd374669 2753STATIC void
14dd3ad8
GS
2754S_run_body(pTHX_ I32 oldscope)
2755{
d3b97530
DM
2756 DEBUG_r(PerlIO_printf(Perl_debug_log, "%s $` $& $' support (0x%x).\n",
2757 PL_sawampersand ? "Enabling" : "Omitting",
2758 (unsigned int)(PL_sawampersand)));
6224f72b 2759
3280af22 2760 if (!PL_restartop) {
cf2782cd 2761#ifdef DEBUGGING
1f4fbd3b
MS
2762 if (DEBUG_x_TEST || DEBUG_B_TEST)
2763 dump_all_perl(!DEBUG_B_TEST);
2764 if (!DEBUG_q_TEST)
2765 PERL_DEBUG(PerlIO_printf(Perl_debug_log, "\nEXECUTING...\n\n"));
cf2782cd 2766#endif
6224f72b 2767
1f4fbd3b
MS
2768 if (PL_minus_c) {
2769 PerlIO_printf(Perl_error_log, "%s syntax OK\n", PL_origfilename);
2770 my_exit(0);
2771 }
2772 if (PERLDB_SINGLE && PL_DBsingle)
a6d69523 2773 PL_DBsingle_iv = 1;
1f4fbd3b
MS
2774 if (PL_initav) {
2775 PERL_SET_PHASE(PERL_PHASE_INIT);
2776 call_list(oldscope, PL_initav);
2777 }
f1fac472 2778#ifdef PERL_DEBUG_READONLY_OPS
1f4fbd3b
MS
2779 if (PL_main_root && PL_main_root->op_slabbed)
2780 Slab_to_ro(OpSLAB(PL_main_root));
f1fac472 2781#endif
6224f72b
GS
2782 }
2783
2784 /* do it */
2785
ca7b837b 2786 PERL_SET_PHASE(PERL_PHASE_RUN);
9ebf26ad 2787
3280af22 2788 if (PL_restartop) {
ed06cd5b
YO
2789#ifdef DEBUGGING
2790 /* this complements the "EXECUTING..." debug we emit above.
2791 * it will show up when an eval fails in the main program level
2792 * and the code continues after the error.
2793 */
2794 if (!DEBUG_q_TEST)
2795 PERL_DEBUG(PerlIO_printf(Perl_debug_log, "\nCONTINUING...\n\n"));
2796#endif
1f4fbd3b
MS
2797 PL_restartjmpenv = NULL;
2798 PL_op = PL_restartop;
2799 PL_restartop = 0;
2800 CALLRUNOPS(aTHX);
6224f72b 2801 }
3280af22 2802 else if (PL_main_start) {
1f4fbd3b
MS
2803 CvDEPTH(PL_main_cv) = 1;
2804 PL_op = PL_main_start;
2805 CALLRUNOPS(aTHX);
6224f72b 2806 }
f6b3007c 2807 my_exit(0);
e5964223 2808 NOT_REACHED; /* NOTREACHED */
6224f72b
GS
2809}
2810
954c1994 2811/*
3f620621 2812=for apidoc_section $SV
ccfc67b7 2813
44170c9a 2814=for apidoc get_sv
954c1994 2815
64ace3f8 2816Returns the SV of the specified Perl scalar. C<flags> are passed to
d9f14fbc 2817L</C<gv_fetchpv>>. If C<GV_ADD> is set and the
64ace3f8
NC
2818Perl variable does not exist then it will be created. If C<flags> is zero
2819and the variable does not exist then NULL is returned.
954c1994
GS
2820
2821=cut
2822*/
2823
6224f72b 2824SV*
64ace3f8 2825Perl_get_sv(pTHX_ const char *name, I32 flags)
6224f72b
GS
2826{
2827 GV *gv;
7918f24d
NC
2828
2829 PERL_ARGS_ASSERT_GET_SV;
2830
64ace3f8 2831 gv = gv_fetchpv(name, flags, SVt_PV);
6224f72b 2832 if (gv)
1f4fbd3b 2833 return GvSV(gv);
a0714e2c 2834 return NULL;
6224f72b
GS
2835}
2836
954c1994 2837/*
3f620621 2838=for apidoc_section $AV
ccfc67b7 2839
44170c9a 2840=for apidoc get_av
954c1994 2841
f0b90de1 2842Returns the AV of the specified Perl global or package array with the given
1f4fbd3b 2843name (so it won't work on lexical variables). C<flags> are passed
72d33970 2844to C<gv_fetchpv>. If C<GV_ADD> is set and the
cbfd0a87 2845Perl variable does not exist then it will be created. If C<flags> is zero
54b3381a
PE
2846(ignoring C<SVf_UTF8>) and the variable does not exist then C<NULL> is
2847returned.
954c1994 2848
f0b90de1
SF
2849Perl equivalent: C<@{"$name"}>.
2850
954c1994
GS
2851=cut
2852*/
2853
6224f72b 2854AV*
cbfd0a87 2855Perl_get_av(pTHX_ const char *name, I32 flags)
6224f72b 2856{
cbfd0a87 2857 GV* const gv = gv_fetchpv(name, flags, SVt_PVAV);
7918f24d
NC
2858
2859 PERL_ARGS_ASSERT_GET_AV;
2860
54b3381a 2861 if (flags & ~SVf_UTF8)
1f4fbd3b 2862 return GvAVn(gv);
6224f72b 2863 if (gv)
1f4fbd3b 2864 return GvAV(gv);
7d49f689 2865 return NULL;
6224f72b
GS
2866}
2867
954c1994 2868/*
3f620621 2869=for apidoc_section $HV
ccfc67b7 2870
44170c9a 2871=for apidoc get_hv
954c1994 2872
6673a63c 2873Returns the HV of the specified Perl hash. C<flags> are passed to
72d33970 2874C<gv_fetchpv>. If C<GV_ADD> is set and the
6673a63c 2875Perl variable does not exist then it will be created. If C<flags> is zero
54b3381a
PE
2876(ignoring C<SVf_UTF8>) and the variable does not exist then C<NULL> is
2877returned.
954c1994
GS
2878
2879=cut
2880*/
2881
6224f72b 2882HV*
6673a63c 2883Perl_get_hv(pTHX_ const char *name, I32 flags)
6224f72b 2884{
6673a63c 2885 GV* const gv = gv_fetchpv(name, flags, SVt_PVHV);
7918f24d
NC
2886
2887 PERL_ARGS_ASSERT_GET_HV;
2888
54b3381a 2889 if (flags & ~SVf_UTF8)
1f4fbd3b 2890 return GvHVn(gv);
a0d0e21e 2891 if (gv)
1f4fbd3b 2892 return GvHV(gv);
5c284bb0 2893 return NULL;
a0d0e21e
LW
2894}
2895
954c1994 2896/*
3f620621 2897=for apidoc_section $CV
ccfc67b7 2898
1607e393
KW
2899=for apidoc get_cv
2900=for apidoc_item get_cvn_flags
c69669e6 2901=for apidoc_item |CV *|get_cvs|"string"|I32 flags
780a5241 2902
c69669e6 2903These return the CV of the specified Perl subroutine. C<flags> are passed to
72d33970 2904C<gv_fetchpvn_flags>. If C<GV_ADD> is set and the Perl subroutine does not
780a5241 2905exist then it will be declared (which has the same effect as saying
c69669e6 2906C<sub name;>). If C<GV_ADD> is not set and the subroutine does not exist,
780a5241
NC
2907then NULL is returned.
2908
c69669e6
KW
2909The forms differ only in how the subroutine is specified.. With C<get_cvs>,
2910the name is a literal C string, enclosed in double quotes. With C<get_cv>, the
2911name is given by the C<name> parameter, which must be a NUL-terminated C
2912string. With C<get_cvn_flags>, the name is also given by the C<name>
2913parameter, but it is a Perl string (possibly containing embedded NUL bytes),
2914and its length in bytes is contained in the C<len> parameter.
954c1994 2915
c69669e6 2916=for apidoc Amnh||GV_ADD
954c1994
GS
2917
2918=cut
2919*/
2920
a0d0e21e 2921CV*
780a5241 2922Perl_get_cvn_flags(pTHX_ const char *name, STRLEN len, I32 flags)
a0d0e21e 2923{
780a5241 2924 GV* const gv = gv_fetchpvn_flags(name, len, flags, SVt_PVCV);
7918f24d
NC
2925
2926 PERL_ARGS_ASSERT_GET_CVN_FLAGS;
2927
a385812b 2928 if (gv && UNLIKELY(SvROK(gv)) && SvTYPE(SvRV((SV *)gv)) == SVt_PVCV)
1f4fbd3b 2929 return (CV*)SvRV((SV *)gv);
a385812b 2930
334dda80
FC
2931 /* XXX this is probably not what they think they're getting.
2932 * It has the same effect as "sub name;", i.e. just a forward
2933 * declaration! */
780a5241 2934 if ((flags & ~GV_NOADD_MASK) && !GvCVu(gv)) {
1f4fbd3b 2935 return newSTUB(gv,0);
780a5241 2936 }
a0d0e21e 2937 if (gv)
1f4fbd3b 2938 return GvCVu(gv);
601f1833 2939 return NULL;
a0d0e21e
LW
2940}
2941
2c67934f
NC
2942/* Nothing in core calls this now, but we can't replace it with a macro and
2943 move it to mathoms.c as a macro would evaluate name twice. */
780a5241
NC
2944CV*
2945Perl_get_cv(pTHX_ const char *name, I32 flags)
2946{
7918f24d
NC
2947 PERL_ARGS_ASSERT_GET_CV;
2948
780a5241
NC
2949 return get_cvn_flags(name, strlen(name), flags);
2950}
2951
79072805
LW
2952/* Be sure to refetch the stack pointer after calling these routines. */
2953
954c1994 2954/*
ccfc67b7 2955
3f620621 2956=for apidoc_section $callback
ccfc67b7 2957
44170c9a 2958=for apidoc call_argv
954c1994 2959
1f4fbd3b 2960Performs a callback to the specified named and package-scoped Perl subroutine
796b6530 2961with C<argv> (a C<NULL>-terminated array of strings) as arguments. See
72d33970 2962L<perlcall>.
f0b90de1
SF
2963
2964Approximate Perl equivalent: C<&{"$sub_name"}(@$argv)>.
954c1994
GS
2965
2966=cut
2967*/
2968
a0d0e21e 2969I32
5aaab254 2970Perl_call_argv(pTHX_ const char *sub_name, I32 flags, char **argv)
ac27b0f5 2971
1f4fbd3b
MS
2972 /* See G_* flags in cop.h */
2973 /* null terminated arg list */
8990e307 2974{
a0d0e21e 2975 dSP;
8990e307 2976
7918f24d
NC
2977 PERL_ARGS_ASSERT_CALL_ARGV;
2978
924508f0 2979 PUSHMARK(SP);
3dc78631
DM
2980 while (*argv) {
2981 mXPUSHs(newSVpv(*argv,0));
2982 argv++;
8990e307 2983 }
3dc78631 2984 PUTBACK;
864dbfa3 2985 return call_pv(sub_name, flags);
8990e307
LW
2986}
2987
954c1994 2988/*
44170c9a 2989=for apidoc call_pv
954c1994
GS
2990
2991Performs a callback to the specified Perl sub. See L<perlcall>.
2992
2993=cut
2994*/
2995
a0d0e21e 2996I32
864dbfa3 2997Perl_call_pv(pTHX_ const char *sub_name, I32 flags)
1f4fbd3b
MS
2998 /* name of the subroutine */
2999 /* See G_* flags in cop.h */
a0d0e21e 3000{
7918f24d
NC
3001 PERL_ARGS_ASSERT_CALL_PV;
3002
0da0e728 3003 return call_sv(MUTABLE_SV(get_cv(sub_name, GV_ADD)), flags);
a0d0e21e
LW
3004}
3005
954c1994 3006/*
44170c9a 3007=for apidoc call_method
954c1994
GS
3008
3009Performs a callback to the specified Perl method. The blessed object must
3010be on the stack. See L<perlcall>.
3011
3012=cut
3013*/
3014
a0d0e21e 3015I32
864dbfa3 3016Perl_call_method(pTHX_ const char *methname, I32 flags)
1f4fbd3b
MS
3017 /* name of the subroutine */
3018 /* See G_* flags in cop.h */
a0d0e21e 3019{
46ca9bac 3020 STRLEN len;
c106c2be 3021 SV* sv;
7918f24d
NC
3022 PERL_ARGS_ASSERT_CALL_METHOD;
3023
46ca9bac 3024 len = strlen(methname);
c106c2be
RZ
3025 sv = flags & G_METHOD_NAMED
3026 ? sv_2mortal(newSVpvn_share(methname, len,0))
3027 : newSVpvn_flags(methname, len, SVs_TEMP);
46ca9bac 3028
c106c2be 3029 return call_sv(sv, flags | G_METHOD);
a0d0e21e
LW
3030}
3031
3032/* May be called with any of a CV, a GV, or an SV containing the name. */
954c1994 3033/*
44170c9a 3034=for apidoc call_sv
954c1994 3035
078e2213
TC
3036Performs a callback to the Perl sub specified by the SV.
3037
7c0c544c 3038If neither the C<G_METHOD> nor C<G_METHOD_NAMED> flag is supplied, the
078e2213
TC
3039SV may be any of a CV, a GV, a reference to a CV, a reference to a GV
3040or C<SvPV(sv)> will be used as the name of the sub to call.
3041
3042If the C<G_METHOD> flag is supplied, the SV may be a reference to a CV or
3043C<SvPV(sv)> will be used as the name of the method to call.
3044
3045If the C<G_METHOD_NAMED> flag is supplied, C<SvPV(sv)> will be used as
3046the name of the method to call.
3047
3048Some other values are treated specially for internal use and should
3049not be depended on.
3050
3051See L<perlcall>.
954c1994 3052
11939230
KW
3053=for apidoc Amnh||G_METHOD
3054=for apidoc Amnh||G_METHOD_NAMED
3055
954c1994
GS
3056=cut
3057*/
3058
a0d0e21e 3059I32
8162b70e 3060Perl_call_sv(pTHX_ SV *sv, volatile I32 flags)
1f4fbd3b 3061 /* See G_* flags in cop.h */
a0d0e21e
LW
3062{
3063 LOGOP myop; /* fake syntax tree node */
b46e009d 3064 METHOP method_op;
aa689395 3065 I32 oldmark;
8162b70e 3066 volatile I32 retval = 0;
54310121 3067 bool oldcatch = CATCH_GET;
6224f72b 3068 int ret;
c4420975 3069 OP* const oldop = PL_op;
db36c5a1 3070 dJMPENV;
1e422769 3071
7918f24d
NC
3072 PERL_ARGS_ASSERT_CALL_SV;
3073
a0d0e21e 3074 if (flags & G_DISCARD) {
1f4fbd3b
MS
3075 ENTER;
3076 SAVETMPS;
a0d0e21e 3077 }
2f8edad0 3078 if (!(flags & G_WANT)) {
1f4fbd3b
MS
3079 /* Backwards compatibility - as G_SCALAR was 0, it could be omitted.
3080 */
3081 flags |= G_SCALAR;
2f8edad0 3082 }
a0d0e21e 3083
aa689395 3084 Zero(&myop, 1, LOGOP);
f51d4af5 3085 if (!(flags & G_NOARGS))
1f4fbd3b 3086 myop.op_flags |= OPf_STACKED;
4f911530 3087 myop.op_flags |= OP_GIMME_REVERSE(flags);
214a9432
DM
3088 myop.op_ppaddr = PL_ppaddr[OP_ENTERSUB];
3089 myop.op_type = OP_ENTERSUB;
462e5cf6 3090 SAVEOP();
533c011a 3091 PL_op = (OP*)&myop;
aa689395 3092
8c9009ad 3093 if (!(flags & G_METHOD_NAMED)) {
1f4fbd3b
MS
3094 dSP;
3095 EXTEND(SP, 1);
3096 PUSHs(sv);
3097 PUTBACK;
5b434c73 3098 }
aa689395 3099 oldmark = TOPMARK;
a0d0e21e 3100
3280af22 3101 if (PERLDB_SUB && PL_curstash != PL_debstash
1f4fbd3b
MS
3102 /* Handle first BEGIN of -d. */
3103 && (PL_DBcv || (PL_DBcv = GvCV(PL_DBsub)))
3104 /* Try harder, since this may have been a sighandler, thus
3105 * curstash may be meaningless. */
3106 && (SvTYPE(sv) != SVt_PVCV || CvSTASH((const CV *)sv) != PL_debstash)
3107 && !(flags & G_NODEBUG))
3108 myop.op_private |= OPpENTERSUB_DB;
a0d0e21e 3109
c106c2be 3110 if (flags & (G_METHOD|G_METHOD_NAMED)) {
b46e009d 3111 Zero(&method_op, 1, METHOP);
3112 method_op.op_next = (OP*)&myop;
3113 PL_op = (OP*)&method_op;
c106c2be 3114 if ( flags & G_METHOD_NAMED ) {
b46e009d 3115 method_op.op_ppaddr = PL_ppaddr[OP_METHOD_NAMED];
3116 method_op.op_type = OP_METHOD_NAMED;
3117 method_op.op_u.op_meth_sv = sv;
c106c2be 3118 } else {
b46e009d 3119 method_op.op_ppaddr = PL_ppaddr[OP_METHOD];
3120 method_op.op_type = OP_METHOD;
c106c2be 3121 }
968b3946
GS
3122 }
3123
312caa8e 3124 if (!(flags & G_EVAL)) {
1f4fbd3b 3125 CATCH_SET(TRUE);
214a9432 3126 CALLRUNOPS(aTHX);
1f4fbd3b
MS
3127 retval = PL_stack_sp - (PL_stack_base + oldmark);
3128 CATCH_SET(oldcatch);
312caa8e
CS
3129 }
3130 else {
8e90e786 3131 I32 old_cxix;
1f4fbd3b
MS
3132 myop.op_other = (OP*)&myop;
3133 (void)POPMARK;
8e90e786 3134 old_cxix = cxstack_ix;
1f4fbd3b
MS
3135 create_eval_scope(NULL, flags|G_FAKINGEVAL);
3136 INCMARK;
a0d0e21e 3137
1f4fbd3b 3138 JMPENV_PUSH(ret);
edb2152a 3139
1f4fbd3b
MS
3140 switch (ret) {
3141 case 0:
14dd3ad8 3142 redo_body:
214a9432 3143 CALLRUNOPS(aTHX);
1f4fbd3b
MS
3144 retval = PL_stack_sp - (PL_stack_base + oldmark);
3145 if (!(flags & G_KEEPERR)) {
3146 CLEAR_ERRSV();
3147 }
3148 break;
3149 case 1:
3150 STATUS_ALL_FAILURE;
3151 /* FALLTHROUGH */
3152 case 2:
3153 /* my_exit() was called */
3154 SET_CURSTASH(PL_defstash);
3155 FREETMPS;
3156 JMPENV_POP;
3157 my_exit_jump();
3158 NOT_REACHED; /* NOTREACHED */
3159 case 3:
3160 if (PL_restartop) {
3161 PL_restartjmpenv = NULL;
3162 PL_op = PL_restartop;
3163 PL_restartop = 0;
3164 goto redo_body;
3165 }
3166 PL_stack_sp = PL_stack_base + oldmark;
eb7e169e 3167 if ((flags & G_WANT) == G_LIST)
1f4fbd3b
MS
3168 retval = 0;
3169 else {
3170 retval = 1;
3171 *++PL_stack_sp = &PL_sv_undef;
3172 }
3173 break;
3174 }
a0d0e21e 3175
8e90e786
DM
3176 /* if we croaked, depending on how we croaked the eval scope
3177 * may or may not have already been popped */
1f4fbd3b 3178 if (cxstack_ix > old_cxix) {
8e90e786 3179 assert(cxstack_ix == old_cxix + 1);
4ebe6e95 3180 assert(CxTYPE(CX_CUR()) == CXt_EVAL);
1f4fbd3b 3181 delete_eval_scope();
8e90e786 3182 }
1f4fbd3b 3183 JMPENV_POP;
a0d0e21e 3184 }
1e422769 3185
a0d0e21e 3186 if (flags & G_DISCARD) {
1f4fbd3b
MS
3187 PL_stack_sp = PL_stack_base + oldmark;
3188 retval = 0;
3189 FREETMPS;
3190 LEAVE;
a0d0e21e 3191 }
533c011a 3192 PL_op = oldop;
a0d0e21e
LW
3193 return retval;
3194}
3195
6e72f9df 3196/* Eval a string. The G_EVAL flag is always assumed. */
8990e307 3197
954c1994 3198/*
44170c9a 3199=for apidoc eval_sv
954c1994 3200
72d33970 3201Tells Perl to C<eval> the string in the SV. It supports the same flags
796b6530 3202as C<call_sv>, with the obvious exception of C<G_EVAL>. See L<perlcall>.
954c1994 3203
fb81daf0
TC
3204The C<G_RETHROW> flag can be used if you only need eval_sv() to
3205execute code specified by a string, but not catch any errors.
3206
bd87019b 3207=for apidoc Amnh||G_RETHROW
954c1994
GS
3208=cut
3209*/
3210
a0d0e21e 3211I32
864dbfa3 3212Perl_eval_sv(pTHX_ SV *sv, I32 flags)
ac27b0f5 3213
1f4fbd3b 3214 /* See G_* flags in cop.h */
a0d0e21e
LW
3215{
3216 UNOP myop; /* fake syntax tree node */
8162b70e
AC
3217 volatile I32 oldmark;
3218 volatile I32 retval = 0;
6224f72b 3219 int ret;
c4420975 3220 OP* const oldop = PL_op;
db36c5a1 3221 dJMPENV;
84902520 3222
7918f24d
NC
3223 PERL_ARGS_ASSERT_EVAL_SV;
3224
4633a7c4 3225 if (flags & G_DISCARD) {
1f4fbd3b
MS
3226 ENTER;
3227 SAVETMPS;
4633a7c4
LW
3228 }
3229
462e5cf6 3230 SAVEOP();
533c011a 3231 PL_op = (OP*)&myop;
5ff48db8 3232 Zero(&myop, 1, UNOP);
fecade69
DM
3233 myop.op_ppaddr = PL_ppaddr[OP_ENTEREVAL];
3234 myop.op_type = OP_ENTEREVAL;
3235
5b434c73 3236 {
1f4fbd3b
MS
3237 dSP;
3238 oldmark = SP - PL_stack_base;
3239 EXTEND(SP, 1);
3240 PUSHs(sv);
3241 PUTBACK;
5b434c73 3242 }
79072805 3243
4633a7c4 3244 if (!(flags & G_NOARGS))
1f4fbd3b 3245 myop.op_flags = OPf_STACKED;
6e72f9df 3246 myop.op_type = OP_ENTEREVAL;
4f911530 3247 myop.op_flags |= OP_GIMME_REVERSE(flags);
6e72f9df 3248 if (flags & G_KEEPERR)
1f4fbd3b 3249 myop.op_flags |= OPf_SPECIAL;
a1941760 3250
fecade69 3251 myop.op_private = (OPpEVAL_EVALSV); /* tell pp_entereval we're the caller */
a1941760 3252 if (flags & G_RE_REPARSING)
fecade69 3253 myop.op_private |= (OPpEVAL_COPHH | OPpEVAL_RE_REPARSING);
4633a7c4 3254
dedbcade 3255 /* fail now; otherwise we could fail after the JMPENV_PUSH but
13febba5 3256 * before a cx_pusheval(), which corrupts the stack after a croak */
dedbcade
DM
3257 TAINT_PROPER("eval_sv()");
3258
14dd3ad8 3259 JMPENV_PUSH(ret);
6224f72b
GS
3260 switch (ret) {
3261 case 0:
1f4fbd3b 3262 CALLRUNOPS(aTHX);
fecade69
DM
3263 if (!*PL_stack_sp) {
3264 /* In the presence of the OPpEVAL_EVALSV flag,
3265 * pp_entereval() pushes a NULL pointer onto the stack to
a769d3e6
DM
3266 * indicate compilation failure. Otherwise, the top slot on
3267 * the stack will be a non-NULL pointer to whatever scalar or
3268 * list value(s) the eval returned. In void context it will
3269 * be whatever our caller has at the top of stack at the time,
3270 * or the &PL_sv_undef guard at PL_stack_base[0]. Note that
3271 * NULLs are not pushed on the stack except in a few very
3272 * specific circumstances (such as this) to flag something
3273 * special. */
fecade69
DM
3274 PL_stack_sp--;
3275 goto fail;
3276 }
3277 redone_body:
1f4fbd3b
MS
3278 retval = PL_stack_sp - (PL_stack_base + oldmark);
3279 if (!(flags & G_KEEPERR)) {
3280 CLEAR_ERRSV();
3281 }
3282 break;
6224f72b 3283 case 1:
1f4fbd3b
MS
3284 STATUS_ALL_FAILURE;
3285 /* FALLTHROUGH */
6224f72b 3286 case 2:
1f4fbd3b
MS
3287 /* my_exit() was called */
3288 SET_CURSTASH(PL_defstash);
3289 FREETMPS;
3290 JMPENV_POP;
3291 my_exit_jump();
3292 NOT_REACHED; /* NOTREACHED */
6224f72b 3293 case 3:
1f4fbd3b
MS
3294 if (PL_restartop) {
3295 PL_restartjmpenv = NULL;
3296 PL_op = PL_restartop;
3297 PL_restartop = 0;
fecade69
DM
3298 CALLRUNOPS(aTHX);
3299 goto redone_body;
1f4fbd3b 3300 }
4aca2f62 3301 fail:
fb81daf0
TC
3302 if (flags & G_RETHROW) {
3303 JMPENV_POP;
3304 croak_sv(ERRSV);
3305 }
fecade69
DM
3306 /* Should be nothing left in stack frame apart from a possible
3307 * scalar context undef. Assert it's safe to reset the stack */
3308 assert( PL_stack_sp == PL_stack_base + oldmark
3309 || (PL_stack_sp == PL_stack_base + oldmark + 1
3310 && *PL_stack_sp == &PL_sv_undef));
1f4fbd3b 3311 PL_stack_sp = PL_stack_base + oldmark;
eb7e169e 3312 if ((flags & G_WANT) == G_LIST)
1f4fbd3b
MS
3313 retval = 0;
3314 else {
3315 retval = 1;
3316 *++PL_stack_sp = &PL_sv_undef;
3317 }
3318 break;
4633a7c4
LW
3319 }
3320
14dd3ad8 3321 JMPENV_POP;
4633a7c4 3322 if (flags & G_DISCARD) {
1f4fbd3b
MS
3323 PL_stack_sp = PL_stack_base + oldmark;
3324 retval = 0;
3325 FREETMPS;
3326 LEAVE;
4633a7c4 3327 }
533c011a 3328 PL_op = oldop;
4633a7c4
LW
3329 return retval;
3330}
3331
954c1994 3332/*
44170c9a 3333=for apidoc eval_pv
954c1994 3334
422791e4 3335Tells Perl to C<eval> the given string in scalar context and return an SV* result.
954c1994
GS
3336
3337=cut
3338*/
3339
137443ea 3340SV*
864dbfa3 3341Perl_eval_pv(pTHX_ const char *p, I32 croak_on_error)
137443ea 3342{
137443ea 3343 SV* sv = newSVpv(p, 0);
3344
7918f24d
NC
3345 PERL_ARGS_ASSERT_EVAL_PV;
3346
fb81daf0
TC
3347 if (croak_on_error) {
3348 sv_2mortal(sv);
3349 eval_sv(sv, G_SCALAR | G_RETHROW);
3350 }
3351 else {
3352 eval_sv(sv, G_SCALAR);
3353 SvREFCNT_dec(sv);
3354 }
137443ea 3355
ed1786ad
DD
3356 {
3357 dSP;
3358 sv = POPs;
3359 PUTBACK;
3360 }
137443ea 3361
137443ea 3362 return sv;
3363}
3364
4633a7c4
LW
3365/* Require a module. */
3366
954c1994 3367/*
3f620621 3368=for apidoc_section $embedding
ccfc67b7 3369
44170c9a 3370=for apidoc require_pv
954c1994 3371
7d3fb230
BS
3372Tells Perl to C<require> the file named by the string argument. It is
3373analogous to the Perl code C<eval "require '$file'">. It's even
2307c6d0 3374implemented that way; consider using load_module instead.
954c1994 3375
7d3fb230 3376=cut */
954c1994 3377
4633a7c4 3378void
864dbfa3 3379Perl_require_pv(pTHX_ const char *pv)
4633a7c4 3380{
d3acc0f7 3381 dSP;
97aff369 3382 SV* sv;
7918f24d
NC
3383
3384 PERL_ARGS_ASSERT_REQUIRE_PV;
3385
e788e7d3 3386 PUSHSTACKi(PERLSI_REQUIRE);
be41e5d9
NC
3387 sv = Perl_newSVpvf(aTHX_ "require q%c%s%c", 0, pv, 0);
3388 eval_sv(sv_2mortal(sv), G_DISCARD);
d3acc0f7 3389 POPSTACK;
79072805
LW
3390}
3391
76e3520e 3392STATIC void
b6f82619 3393S_usage(pTHX) /* XXX move this out into a module ? */
4633a7c4 3394{
ab821d7f 3395 /* This message really ought to be max 23 lines.
75c72d73 3396 * Removed -h because the user already knows that option. Others? */
fb73857a 3397
1566c39d
NC
3398 /* Grouped as 6 lines per C string literal, to keep under the ANSI C 89
3399 minimum of 509 character string literals. */
27da23d5 3400 static const char * const usage_msg[] = {
617613e2
DB
3401" -0[octal/hexadecimal] specify record separator (\\0, if no argument)\n"
3402" -a autosplit mode with -n or -p (splits $_ into @F)\n"
3403" -C[number/list] enables the listed Unicode features\n"
3404" -c check syntax only (runs BEGIN and CHECK blocks)\n"
3405" -d[t][:MOD] run program under debugger or module Devel::MOD\n"
3406" -D[number/letters] set debugging flags (argument is a bit mask or alphabets)\n",
3407" -e commandline one line of program (several -e's allowed, omit programfile)\n"
3408" -E commandline like -e, but enables all optional features\n"
3409" -f don't do $sitelib/sitecustomize.pl at startup\n"
3410" -F/pattern/ split() pattern for -a switch (//'s are optional)\n"
feb4200c 3411" -g read all input in one go (slurp), rather than line-by-line (alias for -0777)\n"
617613e2
DB
3412" -i[extension] edit <> files in place (makes backup if extension supplied)\n"
3413" -Idirectory specify @INC/#include directory (several -I's allowed)\n",
3414" -l[octnum] enable line ending processing, specifies line terminator\n"
3415" -[mM][-]module execute \"use/no module...\" before executing program\n"
3416" -n assume \"while (<>) { ... }\" loop around program\n"
3417" -p assume loop like -n but print line also, like sed\n"
3418" -s enable rudimentary parsing for switches after programfile\n"
3419" -S look for programfile using PATH environment variable\n",
3420" -t enable tainting warnings\n"
3421" -T enable tainting checks\n"
3422" -u dump core after parsing program\n"
3423" -U allow unsafe operations\n"
3424" -v print version, patchlevel and license\n"
3425" -V[:configvar] print configuration summary (or a single Config.pm variable)\n",
3426" -w enable many useful warnings\n"
3427" -W enable all warnings\n"
3428" -x[directory] ignore text before #!perl line (optionally cd to directory)\n"
3429" -X disable all warnings\n"
1566c39d
NC
3430" \n"
3431"Run 'perldoc perl' for more help with Perl.\n\n",
fb73857a 3432NULL
3433};
27da23d5 3434 const char * const *p = usage_msg;
1566c39d 3435 PerlIO *out = PerlIO_stdout();
fb73857a 3436
1566c39d 3437 PerlIO_printf(out,
1f4fbd3b
MS
3438 "\nUsage: %s [switches] [--] [programfile] [arguments]\n",
3439 PL_origargv[0]);
fb73857a 3440 while (*p)
1f4fbd3b 3441 PerlIO_puts(out, *p++);
b6f82619 3442 my_exit(0);
4633a7c4
LW
3443}
3444
b4ab917c
DM
3445/* convert a string of -D options (or digits) into an int.
3446 * sets *s to point to the char after the options */
3447
3448#ifdef DEBUGGING
3449int
e1ec3a88 3450Perl_get_debug_opts(pTHX_ const char **s, bool givehelp)
b4ab917c 3451{
27da23d5 3452 static const char * const usage_msgd[] = {
651b8f1a
NC
3453 " Debugging flag values: (see also -d)\n"
3454 " p Tokenizing and parsing (with v, displays parse stack)\n"
3455 " s Stack snapshots (with v, displays all stacks)\n"
3456 " l Context (loop) stack processing\n"
3457 " t Trace execution\n"
3458 " o Method and overloading resolution\n",
3459 " c String/numeric conversions\n"
3460 " P Print profiling info, source file input state\n"
3461 " m Memory and SV allocation\n"
3462 " f Format processing\n"
3463 " r Regular expression parsing and execution\n"
3464 " x Syntax tree dump\n",
3465 " u Tainting checks\n"
651b8f1a
NC
3466 " X Scratchpad allocation\n"
3467 " D Cleaning up\n"
56967202 3468 " S Op slab allocation\n"
651b8f1a
NC
3469 " T Tokenising\n"
3470 " R Include reference counts of dumped variables (eg when using -Ds)\n",
3471 " J Do not s,t,P-debug (Jump over) opcodes within package DB\n"
3472 " v Verbose: use in conjunction with other flags\n"
3473 " C Copy On Write\n"
3474 " A Consistency checks on internal structures\n"
3475 " q quiet - currently only suppresses the 'EXECUTING' message\n"
3476 " M trace smart match resolution\n"
3477 " B dump suBroutine definitions, including special Blocks like BEGIN\n",
69014004 3478 " L trace some locale setting information--for Perl core development\n",
e17bc05a 3479 " i trace PerlIO layer processing\n",
5d7580af 3480 " y trace y///, tr/// compilation and execution\n",
c3c9d6b1
YO
3481 " h Show (h)ash randomization debug output"
3482 " (changes to PL_hash_rand_bits)\n",
e6e64d9b
JC
3483 NULL
3484 };
22ff3130 3485 UV uv = 0;
7918f24d
NC
3486
3487 PERL_ARGS_ASSERT_GET_DEBUG_OPTS;
3488
b4ab917c 3489 if (isALPHA(**s)) {
c3c9d6b1
YO
3490 /* NOTE:
3491 * If adding new options add them to the END of debopts[].
3492 * If you remove an option replace it with a '?'.
3493 * If there is a free slot available marked with '?' feel
3494 * free to reuse it for something else.
3495 *
0c6362ad 3496 * Regardless remember to update DEBUG_MASK in perl.h, and
c3c9d6b1
YO
3497 * update the documentation above AND in pod/perlrun.pod.
3498 *
3499 * Note that the ? indicates an unused slot. As the code below
b9b389c2
YO
3500 * indicates the position in this list is important. You cannot
3501 * change the order or delete a character from the list without
3502 * impacting the definitions of all the other flags in perl.h
3503 * However because the logic is guarded by isWORDCHAR we can
3504 * fill in holes with non-wordchar characters instead. */
c3c9d6b1 3505 static const char debopts[] = "psltocPmfrxuUhXDSTRJvCAqMBLiy";
1f4fbd3b
MS
3506
3507 for (; isWORDCHAR(**s); (*s)++) {
3508 const char * const d = strchr(debopts,**s);
3509 if (d)
3510 uv |= 1 << (d - debopts);
3511 else if (ckWARN_d(WARN_DEBUGGING))
3512 Perl_warner(aTHX_ packWARN(WARN_DEBUGGING),
3513 "invalid option -D%c, use -D'' to see choices\n", **s);
3514 }
b4ab917c 3515 }
e6e64d9b 3516 else if (isDIGIT(**s)) {
5d4a52b5 3517 const char* e = *s + strlen(*s);
1f4fbd3b 3518 if (grok_atoUV(*s, &uv, &e))
96e440d2 3519 *s = e;
1f4fbd3b 3520 for (; isWORDCHAR(**s); (*s)++) ;
b4ab917c 3521 }
ddcf8bc1 3522 else if (givehelp) {
06e869a4 3523 const char *const *p = usage_msgd;
651b8f1a 3524 while (*p) PerlIO_puts(PerlIO_stdout(), *p++);
e6e64d9b 3525 }
22ff3130 3526 return (int)uv; /* ignore any UV->int conversion loss */
b4ab917c
DM
3527}
3528#endif
3529
79072805
LW
3530/* This routine handles any switches that can be given during run */
3531
c7030b81
NC
3532const char *
3533Perl_moreswitches(pTHX_ const char *s)
79072805 3534{
84c133a0 3535 UV rschar;
0544e6df 3536 const char option = *s; /* used to remember option in -m/-M code */
79072805 3537
7918f24d
NC
3538 PERL_ARGS_ASSERT_MORESWITCHES;
3539
79072805
LW
3540 switch (*s) {
3541 case '0':
a863c7d1 3542 {
1f4fbd3b
MS
3543 I32 flags = 0;
3544 STRLEN numlen;
3545
3546 SvREFCNT_dec(PL_rs);
3547 if (s[1] == 'x' && s[2]) {
3548 const char *e = s+=2;
3549 U8 *tmps;
3550
3551 while (*e)
3552 e++;
3553 numlen = e - s;
3554 flags = PERL_SCAN_SILENT_ILLDIGIT;
3555 rschar = (U32)grok_hex(s, &numlen, &flags, NULL);
3556 if (s + numlen < e) {
f48aa24d
NC
3557 /* Continue to treat -0xFOO as -0 -xFOO
3558 * (ie NUL as the input record separator, and -x with FOO
3559 * as the directory argument)
3560 *
3561 * hex support for -0 was only added in 5.8.1, hence this
3562 * heuristic to distinguish between it and '-0' clustered with
3563 * '-x' with an argument. The text following '-0x' is only
3564 * processed as the IRS specified in hexadecimal if all
3565 * characters are valid hex digits. */
3566 rschar = 0;
1f4fbd3b
MS
3567 numlen = 0;
3568 s--;
3569 }
54ca8947
RL
3570 PL_rs = newSV((STRLEN)(UVCHR_SKIP(rschar) + 1));
3571 tmps = (U8*)SvPVCLEAR_FRESH(PL_rs);
1f4fbd3b
MS
3572 uvchr_to_utf8(tmps, rschar);
3573 SvCUR_set(PL_rs, UVCHR_SKIP(rschar));
3574 SvUTF8_on(PL_rs);
3575 }
3576 else {
3577 numlen = 4;
3578 rschar = (U32)grok_oct(s, &numlen, &flags, NULL);
3579 if (rschar & ~((U8)~0))
3580 PL_rs = &PL_sv_undef;
3581 else if (!rschar && numlen >= 2)
3582 PL_rs = newSVpvs("");
3583 else {
3584 char ch = (char)rschar;
3585 PL_rs = newSVpvn(&ch, 1);
3586 }
3587 }
3588 sv_setsv(get_sv("/", GV_ADD), PL_rs);
3589 return s + numlen;
a863c7d1 3590 }
46487f74 3591 case 'C':
a05d7ebb 3592 s++;
dd374669 3593 PL_unicode = parse_unicode_opts( (const char **)&s );
1f4fbd3b
MS
3594 if (PL_unicode & PERL_UNICODE_UTF8CACHEASSERT_FLAG)
3595 PL_utf8cache = -1;
3596 return s;
2304df62 3597 case 'F':
1f4fbd3b
MS
3598 PL_minus_a = TRUE;
3599 PL_minus_F = TRUE;
24ffa309 3600 PL_minus_n = TRUE;
a1aa0ce9
TC
3601 {
3602 const char *start = ++s;