forked from Perl/perl5
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathperl.c
5328 lines (4714 loc) · 144 KB
/
perl.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#line 2 "perl.c"
/* perl.c
*
* Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001
* 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012
* 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 by Larry Wall and others
*
* You may distribute under the terms of either the GNU General Public
* License or the Artistic License, as specified in the README file.
*
*/
/*
* A ship then new they built for him
* of mithril and of elven-glass
* --from Bilbo's song of Eärendil
*
* [p.236 of _The Lord of the Rings_, II/i: "Many Meetings"]
*/
/* This file contains the top-level functions that are used to create, use
* and destroy a perl interpreter, plus the functions used by XS code to
* call back into perl. Note that it does not contain the actual main()
* function of the interpreter; that can be found in perlmain.c
*
* Note that at build time this file is also linked to as perlmini.c,
* and perlmini.o is then built with PERL_IS_MINIPERL defined, which is
* then used to create the miniperl executable, rather than perl.o.
*/
#if defined(PERL_IS_MINIPERL) && !defined(USE_SITECUSTOMIZE)
# define USE_SITECUSTOMIZE
#endif
#include "EXTERN.h"
#define PERL_IN_PERL_C
#include "perl.h"
#include "patchlevel.h" /* for local_patches */
#include "XSUB.h"
#ifdef NETWARE
#include "nwutil.h"
#endif
#ifdef DEBUG_LEAKING_SCALARS_FORK_DUMP
# ifdef I_SYSUIO
# include <sys/uio.h>
# endif
union control_un {
struct cmsghdr cm;
char control[CMSG_SPACE(sizeof(int))];
};
#endif
#ifndef HZ
# ifdef CLK_TCK
# define HZ CLK_TCK
# else
# define HZ 60
# endif
#endif
static I32 read_e_script(pTHX_ int idx, SV *buf_sv, int maxlen);
#ifdef SETUID_SCRIPTS_ARE_SECURE_NOW
# define validate_suid(rsfp) NOOP
#else
# define validate_suid(rsfp) S_validate_suid(aTHX_ rsfp)
#endif
#define CALL_BODY_SUB(myop) \
if (PL_op == (myop)) \
PL_op = PL_ppaddr[OP_ENTERSUB](aTHX); \
if (PL_op) \
CALLRUNOPS(aTHX);
#define CALL_LIST_BODY(cv) \
PUSHMARK(PL_stack_sp); \
call_sv(MUTABLE_SV((cv)), G_EVAL|G_DISCARD|G_VOID);
static void
S_init_tls_and_interp(PerlInterpreter *my_perl)
{
if (!PL_curinterp) {
PERL_SET_INTERP(my_perl);
#if defined(USE_ITHREADS)
INIT_THREADS;
ALLOC_THREAD_KEY;
PERL_SET_THX(my_perl);
OP_REFCNT_INIT;
OP_CHECK_MUTEX_INIT;
KEYWORD_PLUGIN_MUTEX_INIT;
HINTS_REFCNT_INIT;
LOCALE_INIT;
USER_PROP_MUTEX_INIT;
ENV_INIT;
MUTEX_INIT(&PL_dollarzero_mutex);
MUTEX_INIT(&PL_my_ctx_mutex);
# endif
}
#if defined(USE_ITHREADS)
else
#else
/* This always happens for non-ithreads */
#endif
{
PERL_SET_THX(my_perl);
}
}
/* these implement the PERL_SYS_INIT, PERL_SYS_INIT3, PERL_SYS_TERM macros */
void
Perl_sys_init(int* argc, char*** argv)
{
PERL_ARGS_ASSERT_SYS_INIT;
PERL_UNUSED_ARG(argc); /* may not be used depending on _BODY macro */
PERL_UNUSED_ARG(argv);
PERL_SYS_INIT_BODY(argc, argv);
}
void
Perl_sys_init3(int* argc, char*** argv, char*** env)
{
PERL_ARGS_ASSERT_SYS_INIT3;
PERL_UNUSED_ARG(argc); /* may not be used depending on _BODY macro */
PERL_UNUSED_ARG(argv);
PERL_UNUSED_ARG(env);
PERL_SYS_INIT3_BODY(argc, argv, env);
}
void
Perl_sys_term(void)
{
if (!PL_veto_cleanup) {
PERL_SYS_TERM_BODY();
}
}
#ifdef PERL_IMPLICIT_SYS
PerlInterpreter *
perl_alloc_using(struct IPerlMem* ipM, struct IPerlMem* ipMS,
struct IPerlMem* ipMP, struct IPerlEnv* ipE,
struct IPerlStdIO* ipStd, struct IPerlLIO* ipLIO,
struct IPerlDir* ipD, struct IPerlSock* ipS,
struct IPerlProc* ipP)
{
PerlInterpreter *my_perl;
PERL_ARGS_ASSERT_PERL_ALLOC_USING;
/* Newx() needs interpreter, so call malloc() instead */
my_perl = (PerlInterpreter*)(*ipM->pMalloc)(ipM, sizeof(PerlInterpreter));
S_init_tls_and_interp(my_perl);
Zero(my_perl, 1, PerlInterpreter);
PL_Mem = ipM;
PL_MemShared = ipMS;
PL_MemParse = ipMP;
PL_Env = ipE;
PL_StdIO = ipStd;
PL_LIO = ipLIO;
PL_Dir = ipD;
PL_Sock = ipS;
PL_Proc = ipP;
INIT_TRACK_MEMPOOL(PL_memory_debug_header, my_perl);
return my_perl;
}
#else
/*
=for apidoc_section Embedding and Interpreter Cloning
=for apidoc perl_alloc
Allocates a new Perl interpreter. See L<perlembed>.
=cut
*/
PerlInterpreter *
perl_alloc(void)
{
PerlInterpreter *my_perl;
/* Newx() needs interpreter, so call malloc() instead */
my_perl = (PerlInterpreter*)PerlMem_malloc(sizeof(PerlInterpreter));
S_init_tls_and_interp(my_perl);
#ifndef PERL_TRACK_MEMPOOL
return (PerlInterpreter *) ZeroD(my_perl, 1, PerlInterpreter);
#else
Zero(my_perl, 1, PerlInterpreter);
INIT_TRACK_MEMPOOL(PL_memory_debug_header, my_perl);
return my_perl;
#endif
}
#endif /* PERL_IMPLICIT_SYS */
/*
=for apidoc perl_construct
Initializes a new Perl interpreter. See L<perlembed>.
=cut
*/
void
perl_construct(pTHXx)
{
PERL_ARGS_ASSERT_PERL_CONSTRUCT;
#ifdef MULTIPLICITY
init_interp();
PL_perl_destruct_level = 1;
#else
PERL_UNUSED_ARG(my_perl);
if (PL_perl_destruct_level > 0)
init_interp();
#endif
PL_curcop = &PL_compiling; /* needed by ckWARN, right away */
#ifdef PERL_TRACE_OPS
Zero(PL_op_exec_cnt, OP_max+2, UV);
#endif
init_constants();
SvREADONLY_on(&PL_sv_placeholder);
SvREFCNT(&PL_sv_placeholder) = SvREFCNT_IMMORTAL;
PL_sighandlerp = Perl_sighandler;
PL_sighandler1p = Perl_sighandler1;
PL_sighandler3p = Perl_sighandler3;
#ifdef PERL_USES_PL_PIDSTATUS
PL_pidstatus = newHV();
#endif
PL_rs = newSVpvs("\n");
init_stacks();
/* The PERL_INTERNAL_RAND_SEED set-up must be after init_stacks because it calls
* things that may put SVs on the stack.
*/
#ifdef NO_PERL_INTERNAL_RAND_SEED
Perl_drand48_init_r(&PL_internal_random_state, seed());
#else
{
UV seed;
const char *env_pv;
if (PerlProc_getuid() != PerlProc_geteuid() ||
PerlProc_getgid() != PerlProc_getegid() ||
!(env_pv = PerlEnv_getenv("PERL_INTERNAL_RAND_SEED")) ||
grok_number(env_pv, strlen(env_pv), &seed) != IS_NUMBER_IN_UV) {
seed = seed();
}
Perl_drand48_init_r(&PL_internal_random_state, (U32)seed);
}
#endif
init_ids();
JMPENV_BOOTSTRAP;
STATUS_ALL_SUCCESS;
init_uniprops();
(void) uvchr_to_utf8_flags((U8 *) PL_TR_SPECIAL_HANDLING_UTF8,
TR_SPECIAL_HANDLING,
UNICODE_ALLOW_ABOVE_IV_MAX);
#if defined(LOCAL_PATCH_COUNT)
PL_localpatches = local_patches; /* For possible -v */
#endif
#if defined(LIBM_LIB_VERSION)
/*
* Some BSDs and Cygwin default to POSIX math instead of IEEE.
* This switches them over to IEEE.
*/
_LIB_VERSION = _IEEE_;
#endif
#ifdef HAVE_INTERP_INTERN
sys_intern_init();
#endif
PerlIO_init(aTHX); /* Hook to IO system */
PL_fdpid = newAV(); /* for remembering popen pids by fd */
PL_modglobal = newHV(); /* pointers to per-interpreter module globals */
PL_errors = newSVpvs("");
SvPVCLEAR(PERL_DEBUG_PAD(0)); /* For regex debugging. */
SvPVCLEAR(PERL_DEBUG_PAD(1)); /* ext/re needs these */
SvPVCLEAR(PERL_DEBUG_PAD(2)); /* even without DEBUGGING. */
#ifdef USE_ITHREADS
/* First entry is a list of empty elements. It needs to be initialised
else all hell breaks loose in S_find_uninit_var(). */
Perl_av_create_and_push(aTHX_ &PL_regex_padav, newSVpvs(""));
PL_regex_pad = AvARRAY(PL_regex_padav);
Newxz(PL_stashpad, PL_stashpadmax, HV *);
#endif
#ifdef USE_REENTRANT_API
Perl_reentrant_init(aTHX);
#endif
if (PL_hash_seed_set == FALSE) {
/* Initialize the hash seed and state at startup. This must be
* done very early, before ANY hashes are constructed, and once
* setup is fixed for the lifetime of the process.
*
* If you decide to disable the seeding process you should choose
* a suitable seed yourself and define PERL_HASH_SEED to a well chosen
* string. See hv_func.h for details.
*/
#if defined(USE_HASH_SEED)
/* get the hash seed from the environment or from an RNG */
Perl_get_hash_seed(aTHX_ PL_hash_seed);
#else
/* they want a hard coded seed, check that it is long enough */
assert( strlen(PERL_HASH_SEED) >= PERL_HASH_SEED_BYTES );
#endif
/* now we use the chosen seed to initialize the state -
* in some configurations this may be a relatively speaking
* expensive operation, but we only have to do it once at startup */
PERL_HASH_SEED_STATE(PERL_HASH_SEED,PL_hash_state);
#ifdef PERL_USE_SINGLE_CHAR_HASH_CACHE
/* we can build a special cache for 0/1 byte keys, if people choose
* I suspect most of the time it is not worth it */
{
char str[2]="\0";
int i;
for (i=0;i<256;i++) {
str[0]= i;
PERL_HASH_WITH_STATE(PL_hash_state,PL_hash_chars[i],str,1);
}
PERL_HASH_WITH_STATE(PL_hash_state,PL_hash_chars[256],str,0);
}
#endif
/* at this point we have initialezed the hash function, and we can start
* constructing hashes */
PL_hash_seed_set= TRUE;
}
/* Allow PL_strtab to be pre-initialized before calling perl_construct.
* can use a custom optimized PL_strtab hash before calling perl_construct */
if (!PL_strtab) {
/* Note that strtab is a rather special HV. Assumptions are made
about not iterating on it, and not adding tie magic to it.
It is properly deallocated in perl_destruct() */
PL_strtab = newHV();
/* SHAREKEYS tells us that the hash has its keys shared with PL_strtab,
* which is not the case with PL_strtab itself */
HvSHAREKEYS_off(PL_strtab); /* mandatory */
hv_ksplit(PL_strtab, 1 << 11);
}
Zero(PL_sv_consts, SV_CONSTS_COUNT, SV*);
#ifndef PERL_MICRO
# ifdef USE_ENVIRON_ARRAY
PL_origenviron = environ;
# endif
#endif
/* Use sysconf(_SC_CLK_TCK) if available, if not
* available or if the sysconf() fails, use the HZ.
* The HZ if not originally defined has been by now
* been defined as CLK_TCK, if available. */
#if defined(HAS_SYSCONF) && defined(_SC_CLK_TCK)
PL_clocktick = sysconf(_SC_CLK_TCK);
if (PL_clocktick <= 0)
#endif
PL_clocktick = HZ;
PL_stashcache = newHV();
PL_patchlevel = newSVpvs("v" PERL_VERSION_STRING);
#ifdef HAS_MMAP
if (!PL_mmap_page_size) {
#if defined(HAS_SYSCONF) && (defined(_SC_PAGESIZE) || defined(_SC_MMAP_PAGE_SIZE))
{
SETERRNO(0, SS_NORMAL);
# ifdef _SC_PAGESIZE
PL_mmap_page_size = sysconf(_SC_PAGESIZE);
# else
PL_mmap_page_size = sysconf(_SC_MMAP_PAGE_SIZE);
# endif
if ((long) PL_mmap_page_size < 0) {
Perl_croak(aTHX_ "panic: sysconf: %s",
errno ? Strerror(errno) : "pagesize unknown");
}
}
#elif defined(HAS_GETPAGESIZE)
PL_mmap_page_size = getpagesize();
#elif defined(I_SYS_PARAM) && defined(PAGESIZE)
PL_mmap_page_size = PAGESIZE; /* compiletime, bad */
#endif
if (PL_mmap_page_size <= 0)
Perl_croak(aTHX_ "panic: bad pagesize %" IVdf,
(IV) PL_mmap_page_size);
}
#endif /* HAS_MMAP */
PL_osname = Perl_savepvn(aTHX_ STR_WITH_LEN(OSNAME));
PL_registered_mros = newHV();
/* Start with 1 bucket, for DFS. It's unlikely we'll need more. */
HvMAX(PL_registered_mros) = 0;
#ifdef USE_POSIX_2008_LOCALE
PL_C_locale_obj = newlocale(LC_ALL_MASK, "C", NULL);
#endif
ENTER;
init_i18nl10n(1);
}
/*
=for apidoc nothreadhook
Stub that provides thread hook for perl_destruct when there are
no threads.
=cut
*/
int
Perl_nothreadhook(pTHX)
{
PERL_UNUSED_CONTEXT;
return 0;
}
#ifdef DEBUG_LEAKING_SCALARS_FORK_DUMP
void
Perl_dump_sv_child(pTHX_ SV *sv)
{
ssize_t got;
const int sock = PL_dumper_fd;
const int debug_fd = PerlIO_fileno(Perl_debug_log);
union control_un control;
struct msghdr msg;
struct iovec vec[2];
struct cmsghdr *cmptr;
int returned_errno;
unsigned char buffer[256];
PERL_ARGS_ASSERT_DUMP_SV_CHILD;
if(sock == -1 || debug_fd == -1)
return;
PerlIO_flush(Perl_debug_log);
/* All these shenanigans are to pass a file descriptor over to our child for
it to dump out to. We can't let it hold open the file descriptor when it
forks, as the file descriptor it will dump to can turn out to be one end
of pipe that some other process will wait on for EOF. (So as it would
be open, the wait would be forever.) */
msg.msg_control = control.control;
msg.msg_controllen = sizeof(control.control);
/* We're a connected socket so we don't need a destination */
msg.msg_name = NULL;
msg.msg_namelen = 0;
msg.msg_iov = vec;
msg.msg_iovlen = 1;
cmptr = CMSG_FIRSTHDR(&msg);
cmptr->cmsg_len = CMSG_LEN(sizeof(int));
cmptr->cmsg_level = SOL_SOCKET;
cmptr->cmsg_type = SCM_RIGHTS;
*((int *)CMSG_DATA(cmptr)) = 1;
vec[0].iov_base = (void*)&sv;
vec[0].iov_len = sizeof(sv);
got = sendmsg(sock, &msg, 0);
if(got < 0) {
perror("Debug leaking scalars parent sendmsg failed");
abort();
}
if(got < sizeof(sv)) {
perror("Debug leaking scalars parent short sendmsg");
abort();
}
/* Return protocol is
int: errno value
unsigned char: length of location string (0 for empty)
unsigned char*: string (not terminated)
*/
vec[0].iov_base = (void*)&returned_errno;
vec[0].iov_len = sizeof(returned_errno);
vec[1].iov_base = buffer;
vec[1].iov_len = 1;
got = readv(sock, vec, 2);
if(got < 0) {
perror("Debug leaking scalars parent read failed");
PerlIO_flush(PerlIO_stderr());
abort();
}
if(got < sizeof(returned_errno) + 1) {
perror("Debug leaking scalars parent short read");
PerlIO_flush(PerlIO_stderr());
abort();
}
if (*buffer) {
got = read(sock, buffer + 1, *buffer);
if(got < 0) {
perror("Debug leaking scalars parent read 2 failed");
PerlIO_flush(PerlIO_stderr());
abort();
}
if(got < *buffer) {
perror("Debug leaking scalars parent short read 2");
PerlIO_flush(PerlIO_stderr());
abort();
}
}
if (returned_errno || *buffer) {
Perl_warn(aTHX_ "Debug leaking scalars child failed%s%.*s with errno"
" %d: %s", (*buffer ? " at " : ""), (int) *buffer, buffer + 1,
returned_errno, Strerror(returned_errno));
}
}
#endif
/*
=for apidoc perl_destruct
Shuts down a Perl interpreter. See L<perlembed> for a tutorial.
C<my_perl> points to the Perl interpreter. It must have been previously
created through the use of L</perl_alloc> and L</perl_construct>. It may
have been initialised through L</perl_parse>, and may have been used
through L</perl_run> and other means. This function should be called for
any Perl interpreter that has been constructed with L</perl_construct>,
even if subsequent operations on it failed, for example if L</perl_parse>
returned a non-zero value.
If the interpreter's C<PL_exit_flags> word has the
C<PERL_EXIT_DESTRUCT_END> flag set, then this function will execute code
in C<END> blocks before performing the rest of destruction. If it is
desired to make any use of the interpreter between L</perl_parse> and
L</perl_destruct> other than just calling L</perl_run>, then this flag
should be set early on. This matters if L</perl_run> will not be called,
or if anything else will be done in addition to calling L</perl_run>.
Returns a value be a suitable value to pass to the C library function
C<exit> (or to return from C<main>), to serve as an exit code indicating
the nature of the way the interpreter terminated. This takes into account
any failure of L</perl_parse> and any early exit from L</perl_run>.
The exit code is of the type required by the host operating system,
so because of differing exit code conventions it is not portable to
interpret specific numeric values as having specific meanings.
=cut
*/
int
perl_destruct(pTHXx)
{
volatile signed char destruct_level; /* see possible values in intrpvar.h */
HV *hv;
#ifdef DEBUG_LEAKING_SCALARS_FORK_DUMP
pid_t child;
#endif
int i;
PERL_ARGS_ASSERT_PERL_DESTRUCT;
#ifndef MULTIPLICITY
PERL_UNUSED_ARG(my_perl);
#endif
assert(PL_scopestack_ix == 1);
/* wait for all pseudo-forked children to finish */
PERL_WAIT_FOR_CHILDREN;
destruct_level = PL_perl_destruct_level;
{
const char * const s = PerlEnv_getenv("PERL_DESTRUCT_LEVEL");
if (s) {
int i;
if (strEQ(s, "-1")) { /* Special case: modperl folklore. */
i = -1;
} else {
UV uv;
if (grok_atoUV(s, &uv, NULL) && uv <= INT_MAX)
i = (int)uv;
else
i = 0;
}
if (destruct_level < i) destruct_level = i;
#ifdef PERL_TRACK_MEMPOOL
/* RT #114496, for perl_free */
PL_perl_destruct_level = i;
#endif
}
}
if (PL_exit_flags & PERL_EXIT_DESTRUCT_END) {
dJMPENV;
int x = 0;
JMPENV_PUSH(x);
PERL_UNUSED_VAR(x);
if (PL_endav && !PL_minus_c) {
PERL_SET_PHASE(PERL_PHASE_END);
call_list(PL_scopestack_ix, PL_endav);
}
JMPENV_POP;
}
LEAVE;
FREETMPS;
assert(PL_scopestack_ix == 0);
/* normally when we get here, PL_parser should be null due to having
* its original (null) value restored by SAVEt_PARSER during leaving
* scope (usually before run-time starts in fact).
* But if a thread is created within a BEGIN block, the parser is
* duped, but the SAVEt_PARSER savestack entry isn't. So PL_parser
* never gets cleaned up.
* Clean it up here instead. This is a bit of a hack.
*/
if (PL_parser) {
/* stop parser_free() stomping on PL_curcop */
PL_parser->saved_curcop = PL_curcop;
parser_free(PL_parser);
}
/* Need to flush since END blocks can produce output */
/* flush stdout separately, since we can identify it */
#ifdef USE_PERLIO
{
PerlIO *stdo = PerlIO_stdout();
if (*stdo && PerlIO_flush(stdo)) {
PerlIO_restore_errno(stdo);
if (errno)
PerlIO_printf(PerlIO_stderr(), "Unable to flush stdout: %s\n",
Strerror(errno));
if (!STATUS_UNIX)
STATUS_ALL_FAILURE;
}
}
#endif
my_fflush_all();
#ifdef PERL_TRACE_OPS
/* dump OP-counts if $ENV{PERL_TRACE_OPS} > 0 */
{
const char * const ptoenv = PerlEnv_getenv("PERL_TRACE_OPS");
UV uv;
if (!ptoenv || !Perl_grok_atoUV(ptoenv, &uv, NULL)
|| !(uv > 0))
goto no_trace_out;
}
PerlIO_printf(Perl_debug_log, "Trace of all OPs executed:\n");
for (i = 0; i <= OP_max; ++i) {
if (PL_op_exec_cnt[i])
PerlIO_printf(Perl_debug_log, " %s: %" UVuf "\n", PL_op_name[i], PL_op_exec_cnt[i]);
}
/* Utility slot for easily doing little tracing experiments in the runloop: */
if (PL_op_exec_cnt[OP_max+1] != 0)
PerlIO_printf(Perl_debug_log, " SPECIAL: %" UVuf "\n", PL_op_exec_cnt[OP_max+1]);
PerlIO_printf(Perl_debug_log, "\n");
no_trace_out:
#endif
if (PL_threadhook(aTHX)) {
/* Threads hook has vetoed further cleanup */
PL_veto_cleanup = TRUE;
return STATUS_EXIT;
}
#ifdef DEBUG_LEAKING_SCALARS_FORK_DUMP
if (destruct_level != 0) {
/* Fork here to create a child. Our child's job is to preserve the
state of scalars prior to destruction, so that we can instruct it
to dump any scalars that we later find have leaked.
There's no subtlety in this code - it assumes POSIX, and it doesn't
fail gracefully */
int fd[2];
if(PerlSock_socketpair_cloexec(AF_UNIX, SOCK_STREAM, 0, fd)) {
perror("Debug leaking scalars socketpair failed");
abort();
}
child = fork();
if(child == -1) {
perror("Debug leaking scalars fork failed");
abort();
}
if (!child) {
/* We are the child */
const int sock = fd[1];
const int debug_fd = PerlIO_fileno(Perl_debug_log);
int f;
const char *where;
/* Our success message is an integer 0, and a char 0 */
static const char success[sizeof(int) + 1] = {0};
close(fd[0]);
/* We need to close all other file descriptors otherwise we end up
with interesting hangs, where the parent closes its end of a
pipe, and sits waiting for (another) child to terminate. Only
that child never terminates, because it never gets EOF, because
we also have the far end of the pipe open. We even need to
close the debugging fd, because sometimes it happens to be one
end of a pipe, and a process is waiting on the other end for
EOF. Normally it would be closed at some point earlier in
destruction, but if we happen to cause the pipe to remain open,
EOF never occurs, and we get an infinite hang. Hence all the
games to pass in a file descriptor if it's actually needed. */
f = sysconf(_SC_OPEN_MAX);
if(f < 0) {
where = "sysconf failed";
goto abort;
}
while (f--) {
if (f == sock)
continue;
close(f);
}
while (1) {
SV *target;
union control_un control;
struct msghdr msg;
struct iovec vec[1];
struct cmsghdr *cmptr;
ssize_t got;
int got_fd;
msg.msg_control = control.control;
msg.msg_controllen = sizeof(control.control);
/* We're a connected socket so we don't need a source */
msg.msg_name = NULL;
msg.msg_namelen = 0;
msg.msg_iov = vec;
msg.msg_iovlen = C_ARRAY_LENGTH(vec);
vec[0].iov_base = (void*)⌖
vec[0].iov_len = sizeof(target);
got = recvmsg(sock, &msg, 0);
if(got == 0)
break;
if(got < 0) {
where = "recv failed";
goto abort;
}
if(got < sizeof(target)) {
where = "short recv";
goto abort;
}
if(!(cmptr = CMSG_FIRSTHDR(&msg))) {
where = "no cmsg";
goto abort;
}
if(cmptr->cmsg_len != CMSG_LEN(sizeof(int))) {
where = "wrong cmsg_len";
goto abort;
}
if(cmptr->cmsg_level != SOL_SOCKET) {
where = "wrong cmsg_level";
goto abort;
}
if(cmptr->cmsg_type != SCM_RIGHTS) {
where = "wrong cmsg_type";
goto abort;
}
got_fd = *(int*)CMSG_DATA(cmptr);
/* For our last little bit of trickery, put the file descriptor
back into Perl_debug_log, as if we never actually closed it
*/
if(got_fd != debug_fd) {
if (PerlLIO_dup2_cloexec(got_fd, debug_fd) == -1) {
where = "dup2";
goto abort;
}
}
sv_dump(target);
PerlIO_flush(Perl_debug_log);
got = write(sock, &success, sizeof(success));
if(got < 0) {
where = "write failed";
goto abort;
}
if(got < sizeof(success)) {
where = "short write";
goto abort;
}
}
_exit(0);
abort:
{
int send_errno = errno;
unsigned char length = (unsigned char) strlen(where);
struct iovec failure[3] = {
{(void*)&send_errno, sizeof(send_errno)},
{&length, 1},
{(void*)where, length}
};
int got = writev(sock, failure, 3);
/* Bad news travels fast. Faster than data. We'll get a SIGPIPE
in the parent if we try to read from the socketpair after the
child has exited, even if there was data to read.
So sleep a bit to give the parent a fighting chance of
reading the data. */
sleep(2);
_exit((got == -1) ? errno : 0);
}
/* End of child. */
}
PL_dumper_fd = fd[0];
close(fd[1]);
}
#endif
/* We must account for everything. */
/* Destroy the main CV and syntax tree */
/* Set PL_curcop now, because destroying ops can cause new SVs
to be generated in Perl_pad_swipe, and when running with
-DDEBUG_LEAKING_SCALARS they expect PL_curcop to point to a valid
op from which the filename structure member is copied. */
PL_curcop = &PL_compiling;
if (PL_main_root) {
/* ensure comppad/curpad to refer to main's pad */
if (CvPADLIST(PL_main_cv)) {
PAD_SET_CUR_NOSAVE(CvPADLIST(PL_main_cv), 1);
PL_comppad_name = PadlistNAMES(CvPADLIST(PL_main_cv));
}
op_free(PL_main_root);
PL_main_root = NULL;
}
PL_main_start = NULL;
/* note that PL_main_cv isn't usually actually freed at this point,
* due to the CvOUTSIDE refs from subs compiled within it. It will
* get freed once all the subs are freed in sv_clean_all(), for
* destruct_level > 0 */
SvREFCNT_dec(PL_main_cv);
PL_main_cv = NULL;
PERL_SET_PHASE(PERL_PHASE_DESTRUCT);
/* Tell PerlIO we are about to tear things apart in case
we have layers which are using resources that should
be cleaned up now.
*/
PerlIO_destruct(aTHX);
/*
* Try to destruct global references. We do this first so that the
* destructors and destructees still exist. Some sv's might remain.
* Non-referenced objects are on their own.
*/
sv_clean_objs();
/* unhook hooks which will soon be, or use, destroyed data */
SvREFCNT_dec(PL_warnhook);
PL_warnhook = NULL;
SvREFCNT_dec(PL_diehook);
PL_diehook = NULL;
/* call exit list functions */
while (PL_exitlistlen-- > 0)
PL_exitlist[PL_exitlistlen].fn(aTHX_ PL_exitlist[PL_exitlistlen].ptr);
Safefree(PL_exitlist);
PL_exitlist = NULL;
PL_exitlistlen = 0;
SvREFCNT_dec(PL_registered_mros);
/* jettison our possibly duplicated environment */
/* if PERL_USE_SAFE_PUTENV is defined environ will not have been copied
* so we certainly shouldn't free it here
*/
#ifndef PERL_MICRO
#if defined(USE_ENVIRON_ARRAY) && !defined(PERL_USE_SAFE_PUTENV)
if (environ != PL_origenviron && !PL_use_safe_putenv
#ifdef USE_ITHREADS
/* only main thread can free environ[0] contents */
&& PL_curinterp == aTHX
#endif
)
{
I32 i;
for (i = 0; environ[i]; i++)
safesysfree(environ[i]);
/* Must use safesysfree() when working with environ. */
safesysfree(environ);
environ = PL_origenviron;
}
#endif
#endif /* !PERL_MICRO */
if (destruct_level == 0) {
DEBUG_P(debprofdump());
#if defined(PERLIO_LAYERS)
/* No more IO - including error messages ! */
PerlIO_cleanup(aTHX);
#endif
CopFILE_free(&PL_compiling);
/* The exit() function will do everything that needs doing. */
return STATUS_EXIT;
}
/* Below, do clean up for when PERL_DESTRUCT_LEVEL is not 0 */
#ifdef USE_ITHREADS
/* the syntax tree is shared between clones
* so op_free(PL_main_root) only ReREFCNT_dec's
* REGEXPs in the parent interpreter
* we need to manually ReREFCNT_dec for the clones
*/
{
I32 i = AvFILLp(PL_regex_padav);
SV **ary = AvARRAY(PL_regex_padav);
for (; i; i--) {
SvREFCNT_dec(ary[i]);
ary[i] = &PL_sv_undef;
}
}
#endif
SvREFCNT_dec(MUTABLE_SV(PL_stashcache));
PL_stashcache = NULL;
/* loosen bonds of global variables */
/* XXX can PL_parser still be non-null here? */
if(PL_parser && PL_parser->rsfp) {
(void)PerlIO_close(PL_parser->rsfp);
PL_parser->rsfp = NULL;
}
if (PL_minus_F) {
Safefree(PL_splitstr);
PL_splitstr = NULL;
}
/* switches */
PL_minus_n = FALSE;
PL_minus_p = FALSE;
PL_minus_l = FALSE;
PL_minus_a = FALSE;
PL_minus_F = FALSE;
PL_doswitches = FALSE;
PL_dowarn = G_WARN_OFF;
#ifdef PERL_SAWAMPERSAND
PL_sawampersand = 0; /* must save all match strings */
#endif
PL_unsafe = FALSE;