dc6feded70f4a70e52e99a5f95ee0c6ff8d8d421
[p5sagit/p5-mst-13.2.git] / perl.c
1 /*    perl.c
2  *
3  *    Copyright (c) 1987-2001 Larry Wall
4  *
5  *    You may distribute under the terms of either the GNU General Public
6  *    License or the Artistic License, as specified in the README file.
7  *
8  */
9
10 /*
11  * "A ship then new they built for him/of mithril and of elven glass" --Bilbo
12  */
13
14 #include "EXTERN.h"
15 #define PERL_IN_PERL_C
16 #include "perl.h"
17 #include "patchlevel.h"                 /* for local_patches */
18
19 /* XXX If this causes problems, set i_unistd=undef in the hint file.  */
20 #ifdef I_UNISTD
21 #include <unistd.h>
22 #endif
23
24 #if !defined(STANDARD_C) && !defined(HAS_GETENV_PROTOTYPE)
25 char *getenv (char *); /* Usually in <stdlib.h> */
26 #endif
27
28 static I32 read_e_script(pTHXo_ int idx, SV *buf_sv, int maxlen);
29
30 #ifdef IAMSUID
31 #ifndef DOSUID
32 #define DOSUID
33 #endif
34 #endif
35
36 #ifdef SETUID_SCRIPTS_ARE_SECURE_NOW
37 #ifdef DOSUID
38 #undef DOSUID
39 #endif
40 #endif
41
42 #ifdef PERL_OBJECT
43 #define perl_construct  Perl_construct
44 #define perl_parse      Perl_parse
45 #define perl_run        Perl_run
46 #define perl_destruct   Perl_destruct
47 #define perl_free       Perl_free
48 #endif
49
50 #if defined(USE_THREADS)
51 #  define INIT_TLS_AND_INTERP \
52     STMT_START {                                \
53         if (!PL_curinterp) {                    \
54             PERL_SET_INTERP(my_perl);           \
55             INIT_THREADS;                       \
56             ALLOC_THREAD_KEY;                   \
57         }                                       \
58     } STMT_END
59 #else
60 #  if defined(USE_ITHREADS)
61 #  define INIT_TLS_AND_INTERP \
62     STMT_START {                                \
63         if (!PL_curinterp) {                    \
64             PERL_SET_INTERP(my_perl);           \
65             INIT_THREADS;                       \
66             ALLOC_THREAD_KEY;                   \
67             PERL_SET_THX(my_perl);              \
68             OP_REFCNT_INIT;                     \
69         }                                       \
70         else {                                  \
71             PERL_SET_THX(my_perl);              \
72         }                                       \
73     } STMT_END
74 #  else
75 #  define INIT_TLS_AND_INTERP \
76     STMT_START {                                \
77         if (!PL_curinterp) {                    \
78             PERL_SET_INTERP(my_perl);           \
79         }                                       \
80         PERL_SET_THX(my_perl);                  \
81     } STMT_END
82 #  endif
83 #endif
84
85 #ifdef PERL_IMPLICIT_SYS
86 PerlInterpreter *
87 perl_alloc_using(struct IPerlMem* ipM, struct IPerlMem* ipMS,
88                  struct IPerlMem* ipMP, struct IPerlEnv* ipE,
89                  struct IPerlStdIO* ipStd, struct IPerlLIO* ipLIO,
90                  struct IPerlDir* ipD, struct IPerlSock* ipS,
91                  struct IPerlProc* ipP)
92 {
93     PerlInterpreter *my_perl;
94 #ifdef PERL_OBJECT
95     my_perl = (PerlInterpreter*)new(ipM) CPerlObj(ipM, ipMS, ipMP, ipE, ipStd,
96                                                   ipLIO, ipD, ipS, ipP);
97     INIT_TLS_AND_INTERP;
98 #else
99     /* New() needs interpreter, so call malloc() instead */
100     my_perl = (PerlInterpreter*)(*ipM->pMalloc)(ipM, sizeof(PerlInterpreter));
101     INIT_TLS_AND_INTERP;
102     Zero(my_perl, 1, PerlInterpreter);
103     PL_Mem = ipM;
104     PL_MemShared = ipMS;
105     PL_MemParse = ipMP;
106     PL_Env = ipE;
107     PL_StdIO = ipStd;
108     PL_LIO = ipLIO;
109     PL_Dir = ipD;
110     PL_Sock = ipS;
111     PL_Proc = ipP;
112 #endif
113
114     return my_perl;
115 }
116 #else
117
118 /*
119 =for apidoc perl_alloc
120
121 Allocates a new Perl interpreter.  See L<perlembed>.
122
123 =cut
124 */
125
126 PerlInterpreter *
127 perl_alloc(void)
128 {
129     PerlInterpreter *my_perl;
130
131     /* New() needs interpreter, so call malloc() instead */
132     my_perl = (PerlInterpreter*)PerlMem_malloc(sizeof(PerlInterpreter));
133
134     INIT_TLS_AND_INTERP;
135     Zero(my_perl, 1, PerlInterpreter);
136     return my_perl;
137 }
138 #endif /* PERL_IMPLICIT_SYS */
139
140 /*
141 =for apidoc perl_construct
142
143 Initializes a new Perl interpreter.  See L<perlembed>.
144
145 =cut
146 */
147
148 void
149 perl_construct(pTHXx)
150 {
151 #ifdef USE_THREADS
152 #ifndef FAKE_THREADS
153     struct perl_thread *thr = NULL;
154 #endif /* FAKE_THREADS */
155 #endif /* USE_THREADS */
156
157 #ifdef MULTIPLICITY
158     init_interp();
159     PL_perl_destruct_level = 1;
160 #else
161    if (PL_perl_destruct_level > 0)
162        init_interp();
163 #endif
164
165    /* Init the real globals (and main thread)? */
166     if (!PL_linestr) {
167 #ifdef USE_THREADS
168         MUTEX_INIT(&PL_sv_mutex);
169         /*
170          * Safe to use basic SV functions from now on (though
171          * not things like mortals or tainting yet).
172          */
173         MUTEX_INIT(&PL_eval_mutex);
174         COND_INIT(&PL_eval_cond);
175         MUTEX_INIT(&PL_threads_mutex);
176         COND_INIT(&PL_nthreads_cond);
177 #  ifdef EMULATE_ATOMIC_REFCOUNTS
178         MUTEX_INIT(&PL_svref_mutex);
179 #  endif /* EMULATE_ATOMIC_REFCOUNTS */
180         
181         MUTEX_INIT(&PL_cred_mutex);
182         MUTEX_INIT(&PL_sv_lock_mutex);
183         MUTEX_INIT(&PL_fdpid_mutex);
184
185         thr = init_main_thread();
186 #endif /* USE_THREADS */
187
188 #ifdef PERL_FLEXIBLE_EXCEPTIONS
189         PL_protect = MEMBER_TO_FPTR(Perl_default_protect); /* for exceptions */
190 #endif
191
192         PL_curcop = &PL_compiling;      /* needed by ckWARN, right away */
193
194         PL_linestr = NEWSV(65,79);
195         sv_upgrade(PL_linestr,SVt_PVIV);
196
197         if (!SvREADONLY(&PL_sv_undef)) {
198             /* set read-only and try to insure than we wont see REFCNT==0
199                very often */
200
201             SvREADONLY_on(&PL_sv_undef);
202             SvREFCNT(&PL_sv_undef) = (~(U32)0)/2;
203
204             sv_setpv(&PL_sv_no,PL_No);
205             SvNV(&PL_sv_no);
206             SvREADONLY_on(&PL_sv_no);
207             SvREFCNT(&PL_sv_no) = (~(U32)0)/2;
208
209             sv_setpv(&PL_sv_yes,PL_Yes);
210             SvNV(&PL_sv_yes);
211             SvREADONLY_on(&PL_sv_yes);
212             SvREFCNT(&PL_sv_yes) = (~(U32)0)/2;
213         }
214
215 #ifdef PERL_OBJECT
216         /* TODO: */
217         /* PL_sighandlerp = sighandler; */
218 #else
219         PL_sighandlerp = Perl_sighandler;
220 #endif
221         PL_pidstatus = newHV();
222
223 #ifdef MSDOS
224         /*
225          * There is no way we can refer to them from Perl so close them to save
226          * space.  The other alternative would be to provide STDAUX and STDPRN
227          * filehandles.
228          */
229         (void)PerlIO_close(PerlIO_importFILE(stdaux, 0));
230         (void)PerlIO_close(PerlIO_importFILE(stdprn, 0));
231 #endif
232     }
233
234     PL_nrs = newSVpvn("\n", 1);
235     PL_rs = SvREFCNT_inc(PL_nrs);
236
237     init_stacks();
238
239     init_ids();
240     PL_lex_state = LEX_NOTPARSING;
241
242     JMPENV_BOOTSTRAP;
243     STATUS_ALL_SUCCESS;
244
245     init_i18nl10n(1);
246     SET_NUMERIC_STANDARD();
247
248     {
249         U8 *s;
250         PL_patchlevel = NEWSV(0,4);
251         (void)SvUPGRADE(PL_patchlevel, SVt_PVNV);
252         if (PERL_REVISION > 127 || PERL_VERSION > 127 || PERL_SUBVERSION > 127)
253             SvGROW(PL_patchlevel, UTF8_MAXLEN*3+1);
254         s = (U8*)SvPVX(PL_patchlevel);
255         /* Build version strings using "native" characters */
256         s = uvchr_to_utf8(s, (UV)PERL_REVISION);
257         s = uvchr_to_utf8(s, (UV)PERL_VERSION);
258         s = uvchr_to_utf8(s, (UV)PERL_SUBVERSION);
259         *s = '\0';
260         SvCUR_set(PL_patchlevel, s - (U8*)SvPVX(PL_patchlevel));
261         SvPOK_on(PL_patchlevel);
262         SvNVX(PL_patchlevel) = (NV)PERL_REVISION
263                                 + ((NV)PERL_VERSION / (NV)1000)
264 #if defined(PERL_SUBVERSION) && PERL_SUBVERSION > 0
265                                 + ((NV)PERL_SUBVERSION / (NV)1000000)
266 #endif
267                                 ;
268         SvNOK_on(PL_patchlevel);        /* dual valued */
269         SvUTF8_on(PL_patchlevel);
270         SvREADONLY_on(PL_patchlevel);
271     }
272
273 #if defined(LOCAL_PATCH_COUNT)
274     PL_localpatches = local_patches;    /* For possible -v */
275 #endif
276
277 #ifdef HAVE_INTERP_INTERN
278     sys_intern_init();
279 #endif
280
281     PerlIO_init();                      /* Hook to IO system */
282
283     PL_fdpid = newAV();                 /* for remembering popen pids by fd */
284     PL_modglobal = newHV();             /* pointers to per-interpreter module globals */
285     PL_errors = newSVpvn("",0);
286 #ifdef USE_ITHREADS
287         PL_regex_padav = newAV();
288 #endif
289 #ifdef USE_REENTRANT_API
290     New(31337, PL_reentrant_buffer,1, REBUF);
291     New(31337, PL_reentrant_buffer->tmbuff,1, struct tm);
292 #endif
293     ENTER;
294 }
295
296 /*
297 =for apidoc perl_destruct
298
299 Shuts down a Perl interpreter.  See L<perlembed>.
300
301 =cut
302 */
303
304 void
305 perl_destruct(pTHXx)
306 {
307     int destruct_level;  /* 0=none, 1=full, 2=full with checks */
308     HV *hv;
309 #ifdef USE_THREADS
310     Thread t;
311     dTHX;
312 #endif /* USE_THREADS */
313
314     /* wait for all pseudo-forked children to finish */
315     PERL_WAIT_FOR_CHILDREN;
316
317 #ifdef USE_THREADS
318 #ifndef FAKE_THREADS
319     /* Pass 1 on any remaining threads: detach joinables, join zombies */
320   retry_cleanup:
321     MUTEX_LOCK(&PL_threads_mutex);
322     DEBUG_S(PerlIO_printf(Perl_debug_log,
323                           "perl_destruct: waiting for %d threads...\n",
324                           PL_nthreads - 1));
325     for (t = thr->next; t != thr; t = t->next) {
326         MUTEX_LOCK(&t->mutex);
327         switch (ThrSTATE(t)) {
328             AV *av;
329         case THRf_ZOMBIE:
330             DEBUG_S(PerlIO_printf(Perl_debug_log,
331                                   "perl_destruct: joining zombie %p\n", t));
332             ThrSETSTATE(t, THRf_DEAD);
333             MUTEX_UNLOCK(&t->mutex);
334             PL_nthreads--;
335             /*
336              * The SvREFCNT_dec below may take a long time (e.g. av
337              * may contain an object scalar whose destructor gets
338              * called) so we have to unlock threads_mutex and start
339              * all over again.
340              */
341             MUTEX_UNLOCK(&PL_threads_mutex);
342             JOIN(t, &av);
343             SvREFCNT_dec((SV*)av);
344             DEBUG_S(PerlIO_printf(Perl_debug_log,
345                                   "perl_destruct: joined zombie %p OK\n", t));
346             goto retry_cleanup;
347         case THRf_R_JOINABLE:
348             DEBUG_S(PerlIO_printf(Perl_debug_log,
349                                   "perl_destruct: detaching thread %p\n", t));
350             ThrSETSTATE(t, THRf_R_DETACHED);
351             /*
352              * We unlock threads_mutex and t->mutex in the opposite order
353              * from which we locked them just so that DETACH won't
354              * deadlock if it panics. It's only a breach of good style
355              * not a bug since they are unlocks not locks.
356              */
357             MUTEX_UNLOCK(&PL_threads_mutex);
358             DETACH(t);
359             MUTEX_UNLOCK(&t->mutex);
360             goto retry_cleanup;
361         default:
362             DEBUG_S(PerlIO_printf(Perl_debug_log,
363                                   "perl_destruct: ignoring %p (state %u)\n",
364                                   t, ThrSTATE(t)));
365             MUTEX_UNLOCK(&t->mutex);
366             /* fall through and out */
367         }
368     }
369     /* We leave the above "Pass 1" loop with threads_mutex still locked */
370
371     /* Pass 2 on remaining threads: wait for the thread count to drop to one */
372     while (PL_nthreads > 1)
373     {
374         DEBUG_S(PerlIO_printf(Perl_debug_log,
375                               "perl_destruct: final wait for %d threads\n",
376                               PL_nthreads - 1));
377         COND_WAIT(&PL_nthreads_cond, &PL_threads_mutex);
378     }
379     /* At this point, we're the last thread */
380     MUTEX_UNLOCK(&PL_threads_mutex);
381     DEBUG_S(PerlIO_printf(Perl_debug_log, "perl_destruct: armageddon has arrived\n"));
382     MUTEX_DESTROY(&PL_threads_mutex);
383     COND_DESTROY(&PL_nthreads_cond);
384     PL_nthreads--;
385 #endif /* !defined(FAKE_THREADS) */
386 #endif /* USE_THREADS */
387
388     destruct_level = PL_perl_destruct_level;
389 #ifdef DEBUGGING
390     {
391         char *s;
392         if ((s = PerlEnv_getenv("PERL_DESTRUCT_LEVEL"))) {
393             int i = atoi(s);
394             if (destruct_level < i)
395                 destruct_level = i;
396         }
397     }
398 #endif
399
400     {
401         dJMPENV;
402         int x = 0;
403
404         JMPENV_PUSH(x);
405         if (PL_endav && !PL_minus_c)
406             call_list(PL_scopestack_ix, PL_endav);
407         JMPENV_POP;
408     }
409     LEAVE;
410     FREETMPS;
411
412     /* We must account for everything.  */
413
414     /* Destroy the main CV and syntax tree */
415     if (PL_main_root) {
416         PL_curpad = AvARRAY(PL_comppad);
417         op_free(PL_main_root);
418         PL_main_root = Nullop;
419     }
420     PL_curcop = &PL_compiling;
421     PL_main_start = Nullop;
422     SvREFCNT_dec(PL_main_cv);
423     PL_main_cv = Nullcv;
424     PL_dirty = TRUE;
425
426     /* Tell PerlIO we are about to tear things apart in case
427        we have layers which are using resources that should
428        be cleaned up now.
429      */
430
431     PerlIO_destruct(aTHX);
432
433     if (PL_sv_objcount) {
434         /*
435          * Try to destruct global references.  We do this first so that the
436          * destructors and destructees still exist.  Some sv's might remain.
437          * Non-referenced objects are on their own.
438          */
439         sv_clean_objs();
440     }
441
442     /* unhook hooks which will soon be, or use, destroyed data */
443     SvREFCNT_dec(PL_warnhook);
444     PL_warnhook = Nullsv;
445     SvREFCNT_dec(PL_diehook);
446     PL_diehook = Nullsv;
447
448     /* call exit list functions */
449     while (PL_exitlistlen-- > 0)
450         PL_exitlist[PL_exitlistlen].fn(aTHXo_ PL_exitlist[PL_exitlistlen].ptr);
451
452     Safefree(PL_exitlist);
453
454     if (destruct_level == 0){
455
456         DEBUG_P(debprofdump());
457
458         /* The exit() function will do everything that needs doing. */
459         return;
460     }
461
462     /* jettison our possibly duplicated environment */
463
464 #ifdef USE_ENVIRON_ARRAY
465     if (environ != PL_origenviron) {
466         I32 i;
467
468         for (i = 0; environ[i]; i++)
469             safesysfree(environ[i]);
470         /* Must use safesysfree() when working with environ. */
471         safesysfree(environ);           
472
473         environ = PL_origenviron;
474     }
475 #endif
476
477 #ifdef USE_ITHREADS
478     /* the syntax tree is shared between clones
479      * so op_free(PL_main_root) only ReREFCNT_dec's
480      * REGEXPs in the parent interpreter
481      * we need to manually ReREFCNT_dec for the clones
482      */
483     {
484         I32 i = AvFILLp(PL_regex_padav) + 1;
485         SV **ary = AvARRAY(PL_regex_padav);
486
487         while (i) {
488             SV *resv = ary[--i];
489             REGEXP *re = (REGEXP *)SvIVX(resv);
490
491             if (SvFLAGS(resv) & SVf_BREAK) {
492                 /* this is PL_reg_curpm, already freed
493                  * flag is set in regexec.c:S_regtry
494                  */
495                 SvFLAGS(resv) &= ~SVf_BREAK;
496             }
497             else {
498                 ReREFCNT_dec(re);
499             }
500         }
501     }
502     SvREFCNT_dec(PL_regex_padav);
503     PL_regex_padav = Nullav;
504     PL_regex_pad = NULL;
505 #endif
506
507     /* loosen bonds of global variables */
508
509     if(PL_rsfp) {
510         (void)PerlIO_close(PL_rsfp);
511         PL_rsfp = Nullfp;
512     }
513
514     /* Filters for program text */
515     SvREFCNT_dec(PL_rsfp_filters);
516     PL_rsfp_filters = Nullav;
517
518     /* switches */
519     PL_preprocess   = FALSE;
520     PL_minus_n      = FALSE;
521     PL_minus_p      = FALSE;
522     PL_minus_l      = FALSE;
523     PL_minus_a      = FALSE;
524     PL_minus_F      = FALSE;
525     PL_doswitches   = FALSE;
526     PL_dowarn       = G_WARN_OFF;
527     PL_doextract    = FALSE;
528     PL_sawampersand = FALSE;    /* must save all match strings */
529     PL_unsafe       = FALSE;
530
531     Safefree(PL_inplace);
532     PL_inplace = Nullch;
533     SvREFCNT_dec(PL_patchlevel);
534
535     if (PL_e_script) {
536         SvREFCNT_dec(PL_e_script);
537         PL_e_script = Nullsv;
538     }
539
540     while (--PL_origargc >= 0) {
541         Safefree(PL_origargv[PL_origargc]);
542     }
543     Safefree(PL_origargv);
544
545     /* magical thingies */
546
547     SvREFCNT_dec(PL_ofs_sv);    /* $, */
548     PL_ofs_sv = Nullsv;
549
550     SvREFCNT_dec(PL_ors_sv);    /* $\ */
551     PL_ors_sv = Nullsv;
552
553     SvREFCNT_dec(PL_rs);        /* $/ */
554     PL_rs = Nullsv;
555
556     SvREFCNT_dec(PL_nrs);       /* $/ helper */
557     PL_nrs = Nullsv;
558
559     PL_multiline = 0;           /* $* */
560     Safefree(PL_osname);        /* $^O */
561     PL_osname = Nullch;
562
563     SvREFCNT_dec(PL_statname);
564     PL_statname = Nullsv;
565     PL_statgv = Nullgv;
566
567     /* defgv, aka *_ should be taken care of elsewhere */
568
569     /* clean up after study() */
570     SvREFCNT_dec(PL_lastscream);
571     PL_lastscream = Nullsv;
572     Safefree(PL_screamfirst);
573     PL_screamfirst = 0;
574     Safefree(PL_screamnext);
575     PL_screamnext  = 0;
576
577     /* float buffer */
578     Safefree(PL_efloatbuf);
579     PL_efloatbuf = Nullch;
580     PL_efloatsize = 0;
581
582     /* startup and shutdown function lists */
583     SvREFCNT_dec(PL_beginav);
584     SvREFCNT_dec(PL_endav);
585     SvREFCNT_dec(PL_checkav);
586     SvREFCNT_dec(PL_initav);
587     PL_beginav = Nullav;
588     PL_endav = Nullav;
589     PL_checkav = Nullav;
590     PL_initav = Nullav;
591
592     /* shortcuts just get cleared */
593     PL_envgv = Nullgv;
594     PL_incgv = Nullgv;
595     PL_hintgv = Nullgv;
596     PL_errgv = Nullgv;
597     PL_argvgv = Nullgv;
598     PL_argvoutgv = Nullgv;
599     PL_stdingv = Nullgv;
600     PL_stderrgv = Nullgv;
601     PL_last_in_gv = Nullgv;
602     PL_replgv = Nullgv;
603     PL_debstash = Nullhv;
604
605     /* reset so print() ends up where we expect */
606     setdefout(Nullgv);
607
608     SvREFCNT_dec(PL_argvout_stack);
609     PL_argvout_stack = Nullav;
610
611     SvREFCNT_dec(PL_modglobal);
612     PL_modglobal = Nullhv;
613     SvREFCNT_dec(PL_preambleav);
614     PL_preambleav = Nullav;
615     SvREFCNT_dec(PL_subname);
616     PL_subname = Nullsv;
617     SvREFCNT_dec(PL_linestr);
618     PL_linestr = Nullsv;
619     SvREFCNT_dec(PL_pidstatus);
620     PL_pidstatus = Nullhv;
621     SvREFCNT_dec(PL_toptarget);
622     PL_toptarget = Nullsv;
623     SvREFCNT_dec(PL_bodytarget);
624     PL_bodytarget = Nullsv;
625     PL_formtarget = Nullsv;
626
627     /* free locale stuff */
628 #ifdef USE_LOCALE_COLLATE
629     Safefree(PL_collation_name);
630     PL_collation_name = Nullch;
631 #endif
632
633 #ifdef USE_LOCALE_NUMERIC
634     Safefree(PL_numeric_name);
635     PL_numeric_name = Nullch;
636     SvREFCNT_dec(PL_numeric_radix_sv);
637 #endif
638
639     /* clear utf8 character classes */
640     SvREFCNT_dec(PL_utf8_alnum);
641     SvREFCNT_dec(PL_utf8_alnumc);
642     SvREFCNT_dec(PL_utf8_ascii);
643     SvREFCNT_dec(PL_utf8_alpha);
644     SvREFCNT_dec(PL_utf8_space);
645     SvREFCNT_dec(PL_utf8_cntrl);
646     SvREFCNT_dec(PL_utf8_graph);
647     SvREFCNT_dec(PL_utf8_digit);
648     SvREFCNT_dec(PL_utf8_upper);
649     SvREFCNT_dec(PL_utf8_lower);
650     SvREFCNT_dec(PL_utf8_print);
651     SvREFCNT_dec(PL_utf8_punct);
652     SvREFCNT_dec(PL_utf8_xdigit);
653     SvREFCNT_dec(PL_utf8_mark);
654     SvREFCNT_dec(PL_utf8_toupper);
655     SvREFCNT_dec(PL_utf8_tolower);
656     PL_utf8_alnum       = Nullsv;
657     PL_utf8_alnumc      = Nullsv;
658     PL_utf8_ascii       = Nullsv;
659     PL_utf8_alpha       = Nullsv;
660     PL_utf8_space       = Nullsv;
661     PL_utf8_cntrl       = Nullsv;
662     PL_utf8_graph       = Nullsv;
663     PL_utf8_digit       = Nullsv;
664     PL_utf8_upper       = Nullsv;
665     PL_utf8_lower       = Nullsv;
666     PL_utf8_print       = Nullsv;
667     PL_utf8_punct       = Nullsv;
668     PL_utf8_xdigit      = Nullsv;
669     PL_utf8_mark        = Nullsv;
670     PL_utf8_toupper     = Nullsv;
671     PL_utf8_totitle     = Nullsv;
672     PL_utf8_tolower     = Nullsv;
673
674     if (!specialWARN(PL_compiling.cop_warnings))
675         SvREFCNT_dec(PL_compiling.cop_warnings);
676     PL_compiling.cop_warnings = Nullsv;
677     if (!specialCopIO(PL_compiling.cop_io))
678         SvREFCNT_dec(PL_compiling.cop_io);
679     PL_compiling.cop_io = Nullsv;
680 #ifdef USE_ITHREADS
681     Safefree(CopFILE(&PL_compiling));
682     CopFILE(&PL_compiling) = Nullch;
683     Safefree(CopSTASHPV(&PL_compiling));
684 #else
685     SvREFCNT_dec(CopFILEGV(&PL_compiling));
686     CopFILEGV(&PL_compiling) = Nullgv;
687     /* cop_stash is not refcounted */
688 #endif
689
690     /* Prepare to destruct main symbol table.  */
691
692     hv = PL_defstash;
693     PL_defstash = 0;
694     SvREFCNT_dec(hv);
695     SvREFCNT_dec(PL_curstname);
696     PL_curstname = Nullsv;
697
698     /* clear queued errors */
699     SvREFCNT_dec(PL_errors);
700     PL_errors = Nullsv;
701
702     FREETMPS;
703     if (destruct_level >= 2 && ckWARN_d(WARN_INTERNAL)) {
704         if (PL_scopestack_ix != 0)
705             Perl_warner(aTHX_ WARN_INTERNAL,
706                  "Unbalanced scopes: %ld more ENTERs than LEAVEs\n",
707                  (long)PL_scopestack_ix);
708         if (PL_savestack_ix != 0)
709             Perl_warner(aTHX_ WARN_INTERNAL,
710                  "Unbalanced saves: %ld more saves than restores\n",
711                  (long)PL_savestack_ix);
712         if (PL_tmps_floor != -1)
713             Perl_warner(aTHX_ WARN_INTERNAL,"Unbalanced tmps: %ld more allocs than frees\n",
714                  (long)PL_tmps_floor + 1);
715         if (cxstack_ix != -1)
716             Perl_warner(aTHX_ WARN_INTERNAL,"Unbalanced context: %ld more PUSHes than POPs\n",
717                  (long)cxstack_ix + 1);
718     }
719
720     /* Now absolutely destruct everything, somehow or other, loops or no. */
721     SvFLAGS(PL_fdpid) |= SVTYPEMASK;            /* don't clean out pid table now */
722     SvFLAGS(PL_strtab) |= SVTYPEMASK;           /* don't clean out strtab now */
723
724     /* the 2 is for PL_fdpid and PL_strtab */
725     while (PL_sv_count > 2 && sv_clean_all())
726         ;
727
728     SvFLAGS(PL_fdpid) &= ~SVTYPEMASK;
729     SvFLAGS(PL_fdpid) |= SVt_PVAV;
730     SvFLAGS(PL_strtab) &= ~SVTYPEMASK;
731     SvFLAGS(PL_strtab) |= SVt_PVHV;
732
733     AvREAL_off(PL_fdpid);               /* no surviving entries */
734     SvREFCNT_dec(PL_fdpid);             /* needed in io_close() */
735     PL_fdpid = Nullav;
736
737 #ifdef HAVE_INTERP_INTERN
738     sys_intern_clear();
739 #endif
740
741     /* Destruct the global string table. */
742     {
743         /* Yell and reset the HeVAL() slots that are still holding refcounts,
744          * so that sv_free() won't fail on them.
745          */
746         I32 riter;
747         I32 max;
748         HE *hent;
749         HE **array;
750
751         riter = 0;
752         max = HvMAX(PL_strtab);
753         array = HvARRAY(PL_strtab);
754         hent = array[0];
755         for (;;) {
756             if (hent && ckWARN_d(WARN_INTERNAL)) {
757                 Perl_warner(aTHX_ WARN_INTERNAL,
758                      "Unbalanced string table refcount: (%d) for \"%s\"",
759                      HeVAL(hent) - Nullsv, HeKEY(hent));
760                 HeVAL(hent) = Nullsv;
761                 hent = HeNEXT(hent);
762             }
763             if (!hent) {
764                 if (++riter > max)
765                     break;
766                 hent = array[riter];
767             }
768         }
769     }
770     SvREFCNT_dec(PL_strtab);
771
772 #ifdef USE_ITHREADS
773     /* free the pointer table used for cloning */
774     ptr_table_free(PL_ptr_table);
775 #endif
776
777     /* free special SVs */
778
779     SvREFCNT(&PL_sv_yes) = 0;
780     sv_clear(&PL_sv_yes);
781     SvANY(&PL_sv_yes) = NULL;
782     SvFLAGS(&PL_sv_yes) = 0;
783
784     SvREFCNT(&PL_sv_no) = 0;
785     sv_clear(&PL_sv_no);
786     SvANY(&PL_sv_no) = NULL;
787     SvFLAGS(&PL_sv_no) = 0;
788
789     SvREFCNT(&PL_sv_undef) = 0;
790     SvREADONLY_off(&PL_sv_undef);
791
792     if (PL_sv_count != 0 && ckWARN_d(WARN_INTERNAL))
793         Perl_warner(aTHX_ WARN_INTERNAL,"Scalars leaked: %ld\n", (long)PL_sv_count);
794
795     Safefree(PL_origfilename);
796     Safefree(PL_reg_start_tmp);
797     if (PL_reg_curpm)
798         Safefree(PL_reg_curpm);
799     Safefree(PL_reg_poscache);
800     Safefree(HeKEY_hek(&PL_hv_fetch_ent_mh));
801     Safefree(PL_op_mask);
802     Safefree(PL_psig_ptr);
803     Safefree(PL_psig_name);
804     Safefree(PL_bitcount);
805     Safefree(PL_psig_pend);
806     nuke_stacks();
807     PL_hints = 0;               /* Reset hints. Should hints be per-interpreter ? */
808
809     DEBUG_P(debprofdump());
810 #ifdef USE_THREADS
811     MUTEX_DESTROY(&PL_strtab_mutex);
812     MUTEX_DESTROY(&PL_sv_mutex);
813     MUTEX_DESTROY(&PL_eval_mutex);
814     MUTEX_DESTROY(&PL_cred_mutex);
815     MUTEX_DESTROY(&PL_fdpid_mutex);
816     COND_DESTROY(&PL_eval_cond);
817 #ifdef EMULATE_ATOMIC_REFCOUNTS
818     MUTEX_DESTROY(&PL_svref_mutex);
819 #endif /* EMULATE_ATOMIC_REFCOUNTS */
820
821     /* As the penultimate thing, free the non-arena SV for thrsv */
822     Safefree(SvPVX(PL_thrsv));
823     Safefree(SvANY(PL_thrsv));
824     Safefree(PL_thrsv);
825     PL_thrsv = Nullsv;
826 #endif /* USE_THREADS */
827
828 #ifdef USE_REENTRANT_API
829     Safefree(PL_reentrant_buffer->tmbuff);
830     Safefree(PL_reentrant_buffer);
831 #endif
832
833     sv_free_arenas();
834
835     /* As the absolutely last thing, free the non-arena SV for mess() */
836
837     if (PL_mess_sv) {
838         /* it could have accumulated taint magic */
839         if (SvTYPE(PL_mess_sv) >= SVt_PVMG) {
840             MAGIC* mg;
841             MAGIC* moremagic;
842             for (mg = SvMAGIC(PL_mess_sv); mg; mg = moremagic) {
843                 moremagic = mg->mg_moremagic;
844                 if (mg->mg_ptr && mg->mg_type != PERL_MAGIC_regex_global
845                                                 && mg->mg_len >= 0)
846                     Safefree(mg->mg_ptr);
847                 Safefree(mg);
848             }
849         }
850         /* we know that type >= SVt_PV */
851         (void)SvOOK_off(PL_mess_sv);
852         Safefree(SvPVX(PL_mess_sv));
853         Safefree(SvANY(PL_mess_sv));
854         Safefree(PL_mess_sv);
855         PL_mess_sv = Nullsv;
856     }
857 }
858
859 /*
860 =for apidoc perl_free
861
862 Releases a Perl interpreter.  See L<perlembed>.
863
864 =cut
865 */
866
867 void
868 perl_free(pTHXx)
869 {
870 #if defined(PERL_OBJECT)
871     PerlMem_free(this);
872 #else
873 #  if defined(WIN32) || defined(NETWARE)
874 #  if defined(PERL_IMPLICIT_SYS)
875     #ifdef NETWARE
876                 void *host = nw_internal_host;
877         #else
878                 void *host = w32_internal_host;
879         #endif
880         #ifndef NETWARE
881         if (PerlProc_lasthost()) {
882         PerlIO_cleanup();
883         }
884         #endif
885     PerlMem_free(aTHXx);
886         #ifdef NETWARE
887                 nw5_delete_internal_host(host);
888         #else
889                 win32_delete_internal_host(host);
890         #endif
891 #else
892     PerlIO_cleanup();
893     PerlMem_free(aTHXx);
894 #endif
895 #  else
896     PerlMem_free(aTHXx);
897 #  endif
898 #endif
899 }
900
901 void
902 Perl_call_atexit(pTHX_ ATEXIT_t fn, void *ptr)
903 {
904     Renew(PL_exitlist, PL_exitlistlen+1, PerlExitListEntry);
905     PL_exitlist[PL_exitlistlen].fn = fn;
906     PL_exitlist[PL_exitlistlen].ptr = ptr;
907     ++PL_exitlistlen;
908 }
909
910 /*
911 =for apidoc perl_parse
912
913 Tells a Perl interpreter to parse a Perl script.  See L<perlembed>.
914
915 =cut
916 */
917
918 int
919 perl_parse(pTHXx_ XSINIT_t xsinit, int argc, char **argv, char **env)
920 {
921     I32 oldscope;
922     int ret;
923     dJMPENV;
924 #ifdef USE_THREADS
925     dTHX;
926 #endif
927
928 #ifdef SETUID_SCRIPTS_ARE_SECURE_NOW
929 #ifdef IAMSUID
930 #undef IAMSUID
931     Perl_croak(aTHX_ "suidperl is no longer needed since the kernel can now execute\n\
932 setuid perl scripts securely.\n");
933 #endif
934 #endif
935
936 #if defined(__DYNAMIC__) && (defined(NeXT) || defined(__NeXT__))
937     _dyld_lookup_and_bind
938         ("__environ", (unsigned long *) &environ_pointer, NULL);
939 #endif /* environ */
940
941     PL_origargc = argc;
942     {
943         /* we copy rather than point to argv
944          * since perl_clone will copy and perl_destruct
945          * has no way of knowing if we've made a copy or 
946          * just point to argv
947          */
948         int i = PL_origargc;
949         New(0, PL_origargv, i+1, char*);
950         PL_origargv[i] = '\0';
951         while (i-- > 0) {
952             PL_origargv[i] = savepv(argv[i]);
953         }
954     }
955
956 #ifdef  USE_ENVIRON_ARRAY
957     PL_origenviron = environ;
958 #endif
959
960     if (PL_do_undump) {
961
962         /* Come here if running an undumped a.out. */
963
964         PL_origfilename = savepv(argv[0]);
965         PL_do_undump = FALSE;
966         cxstack_ix = -1;                /* start label stack again */
967         init_ids();
968         init_postdump_symbols(argc,argv,env);
969         return 0;
970     }
971
972     if (PL_main_root) {
973         PL_curpad = AvARRAY(PL_comppad);
974         op_free(PL_main_root);
975         PL_main_root = Nullop;
976     }
977     PL_main_start = Nullop;
978     SvREFCNT_dec(PL_main_cv);
979     PL_main_cv = Nullcv;
980
981     time(&PL_basetime);
982     oldscope = PL_scopestack_ix;
983     PL_dowarn = G_WARN_OFF;
984
985 #ifdef PERL_FLEXIBLE_EXCEPTIONS
986     CALLPROTECT(aTHX_ pcur_env, &ret, MEMBER_TO_FPTR(S_vparse_body), env, xsinit);
987 #else
988     JMPENV_PUSH(ret);
989 #endif
990     switch (ret) {
991     case 0:
992 #ifndef PERL_FLEXIBLE_EXCEPTIONS
993         parse_body(env,xsinit);
994 #endif
995         if (PL_checkav)
996             call_list(oldscope, PL_checkav);
997         ret = 0;
998         break;
999     case 1:
1000         STATUS_ALL_FAILURE;
1001         /* FALL THROUGH */
1002     case 2:
1003         /* my_exit() was called */
1004         while (PL_scopestack_ix > oldscope)
1005             LEAVE;
1006         FREETMPS;
1007         PL_curstash = PL_defstash;
1008         if (PL_checkav)
1009             call_list(oldscope, PL_checkav);
1010         ret = STATUS_NATIVE_EXPORT;
1011         break;
1012     case 3:
1013         PerlIO_printf(Perl_error_log, "panic: top_env\n");
1014         ret = 1;
1015         break;
1016     }
1017     JMPENV_POP;
1018     return ret;
1019 }
1020
1021 #ifdef PERL_FLEXIBLE_EXCEPTIONS
1022 STATIC void *
1023 S_vparse_body(pTHX_ va_list args)
1024 {
1025     char **env = va_arg(args, char**);
1026     XSINIT_t xsinit = va_arg(args, XSINIT_t);
1027
1028     return parse_body(env, xsinit);
1029 }
1030 #endif
1031
1032 STATIC void *
1033 S_parse_body(pTHX_ char **env, XSINIT_t xsinit)
1034 {
1035     int argc = PL_origargc;
1036     char **argv = PL_origargv;
1037     char *scriptname = NULL;
1038     int fdscript = -1;
1039     VOL bool dosearch = FALSE;
1040     char *validarg = "";
1041     AV* comppadlist;
1042     register SV *sv;
1043     register char *s;
1044     char *cddir = Nullch;
1045
1046     sv_setpvn(PL_linestr,"",0);
1047     sv = newSVpvn("",0);                /* first used for -I flags */
1048     SAVEFREESV(sv);
1049     init_main_stash();
1050
1051     for (argc--,argv++; argc > 0; argc--,argv++) {
1052         if (argv[0][0] != '-' || !argv[0][1])
1053             break;
1054 #ifdef DOSUID
1055     if (*validarg)
1056         validarg = " PHOOEY ";
1057     else
1058         validarg = argv[0];
1059 #endif
1060         s = argv[0]+1;
1061       reswitch:
1062         switch (*s) {
1063         case 'C':
1064 #ifdef  WIN32
1065             win32_argv2utf8(argc-1, argv+1);
1066             /* FALL THROUGH */
1067 #endif
1068 #ifndef PERL_STRICT_CR
1069         case '\r':
1070 #endif
1071         case ' ':
1072         case '0':
1073         case 'F':
1074         case 'a':
1075         case 'c':
1076         case 'd':
1077         case 'D':
1078         case 'h':
1079         case 'i':
1080         case 'l':
1081         case 'M':
1082         case 'm':
1083         case 'n':
1084         case 'p':
1085         case 's':
1086         case 'u':
1087         case 'U':
1088         case 'v':
1089         case 'W':
1090         case 'X':
1091         case 'w':
1092             if ((s = moreswitches(s)))
1093                 goto reswitch;
1094             break;
1095
1096         case 'T':
1097             PL_tainting = TRUE;
1098             s++;
1099             goto reswitch;
1100
1101         case 'e':
1102 #ifdef MACOS_TRADITIONAL
1103             /* ignore -e for Dev:Pseudo argument */
1104             if (argv[1] && !strcmp(argv[1], "Dev:Pseudo"))
1105                 break;
1106 #endif
1107             if (PL_euid != PL_uid || PL_egid != PL_gid)
1108                 Perl_croak(aTHX_ "No -e allowed in setuid scripts");
1109             if (!PL_e_script) {
1110                 PL_e_script = newSVpvn("",0);
1111                 filter_add(read_e_script, NULL);
1112             }
1113             if (*++s)
1114                 sv_catpv(PL_e_script, s);
1115             else if (argv[1]) {
1116                 sv_catpv(PL_e_script, argv[1]);
1117                 argc--,argv++;
1118             }
1119             else
1120                 Perl_croak(aTHX_ "No code specified for -e");
1121             sv_catpv(PL_e_script, "\n");
1122             break;
1123
1124         case 'I':       /* -I handled both here and in moreswitches() */
1125             forbid_setid("-I");
1126             if (!*++s && (s=argv[1]) != Nullch) {
1127                 argc--,argv++;
1128             }
1129             if (s && *s) {
1130                 char *p;
1131                 STRLEN len = strlen(s);
1132                 p = savepvn(s, len);
1133                 incpush(p, TRUE, TRUE);
1134                 sv_catpvn(sv, "-I", 2);
1135                 sv_catpvn(sv, p, len);
1136                 sv_catpvn(sv, " ", 1);
1137                 Safefree(p);
1138             }
1139             else
1140                 Perl_croak(aTHX_ "No directory specified for -I");
1141             break;
1142         case 'P':
1143             forbid_setid("-P");
1144             PL_preprocess = TRUE;
1145             s++;
1146             goto reswitch;
1147         case 'S':
1148             forbid_setid("-S");
1149             dosearch = TRUE;
1150             s++;
1151             goto reswitch;
1152         case 'V':
1153             if (!PL_preambleav)
1154                 PL_preambleav = newAV();
1155             av_push(PL_preambleav, newSVpv("use Config qw(myconfig config_vars)",0));
1156             if (*++s != ':')  {
1157                 PL_Sv = newSVpv("print myconfig();",0);
1158 #ifdef VMS
1159                 sv_catpv(PL_Sv,"print \"\\nCharacteristics of this PERLSHR image: \\n\",");
1160 #else
1161                 sv_catpv(PL_Sv,"print \"\\nCharacteristics of this binary (from libperl): \\n\",");
1162 #endif
1163                 sv_catpv(PL_Sv,"\"  Compile-time options:");
1164 #  ifdef DEBUGGING
1165                 sv_catpv(PL_Sv," DEBUGGING");
1166 #  endif
1167 #  ifdef MULTIPLICITY
1168                 sv_catpv(PL_Sv," MULTIPLICITY");
1169 #  endif
1170 #  ifdef USE_THREADS
1171                 sv_catpv(PL_Sv," USE_THREADS");
1172 #  endif
1173 #  ifdef USE_ITHREADS
1174                 sv_catpv(PL_Sv," USE_ITHREADS");
1175 #  endif
1176 #  ifdef USE_64_BIT_INT
1177                 sv_catpv(PL_Sv," USE_64_BIT_INT");
1178 #  endif
1179 #  ifdef USE_64_BIT_ALL
1180                 sv_catpv(PL_Sv," USE_64_BIT_ALL");
1181 #  endif
1182 #  ifdef USE_LONG_DOUBLE
1183                 sv_catpv(PL_Sv," USE_LONG_DOUBLE");
1184 #  endif
1185 #  ifdef USE_LARGE_FILES
1186                 sv_catpv(PL_Sv," USE_LARGE_FILES");
1187 #  endif
1188 #  ifdef USE_SOCKS
1189                 sv_catpv(PL_Sv," USE_SOCKS");
1190 #  endif
1191 #  ifdef PERL_OBJECT
1192                 sv_catpv(PL_Sv," PERL_OBJECT");
1193 #  endif
1194 #  ifdef PERL_IMPLICIT_CONTEXT
1195                 sv_catpv(PL_Sv," PERL_IMPLICIT_CONTEXT");
1196 #  endif
1197 #  ifdef PERL_IMPLICIT_SYS
1198                 sv_catpv(PL_Sv," PERL_IMPLICIT_SYS");
1199 #  endif
1200                 sv_catpv(PL_Sv,"\\n\",");
1201
1202 #if defined(LOCAL_PATCH_COUNT)
1203                 if (LOCAL_PATCH_COUNT > 0) {
1204                     int i;
1205                     sv_catpv(PL_Sv,"\"  Locally applied patches:\\n\",");
1206                     for (i = 1; i <= LOCAL_PATCH_COUNT; i++) {
1207                         if (PL_localpatches[i])
1208                             Perl_sv_catpvf(aTHX_ PL_Sv,"q\"  \t%s\n\",",PL_localpatches[i]);
1209                     }
1210                 }
1211 #endif
1212                 Perl_sv_catpvf(aTHX_ PL_Sv,"\"  Built under %s\\n\"",OSNAME);
1213 #ifdef __DATE__
1214 #  ifdef __TIME__
1215                 Perl_sv_catpvf(aTHX_ PL_Sv,",\"  Compiled at %s %s\\n\"",__DATE__,__TIME__);
1216 #  else
1217                 Perl_sv_catpvf(aTHX_ PL_Sv,",\"  Compiled on %s\\n\"",__DATE__);
1218 #  endif
1219 #endif
1220                 sv_catpv(PL_Sv, "; \
1221 $\"=\"\\n    \"; \
1222 @env = map { \"$_=\\\"$ENV{$_}\\\"\" } sort grep {/^PERL/} keys %ENV; ");
1223 #ifdef __CYGWIN__
1224                 sv_catpv(PL_Sv,"\
1225 push @env, \"CYGWIN=\\\"$ENV{CYGWIN}\\\"\";");
1226 #endif
1227                 sv_catpv(PL_Sv, "\
1228 print \"  \\%ENV:\\n    @env\\n\" if @env; \
1229 print \"  \\@INC:\\n    @INC\\n\";");
1230             }
1231             else {
1232                 PL_Sv = newSVpv("config_vars(qw(",0);
1233                 sv_catpv(PL_Sv, ++s);
1234                 sv_catpv(PL_Sv, "))");
1235                 s += strlen(s);
1236             }
1237             av_push(PL_preambleav, PL_Sv);
1238             scriptname = BIT_BUCKET;    /* don't look for script or read stdin */
1239             goto reswitch;
1240         case 'x':
1241             PL_doextract = TRUE;
1242             s++;
1243             if (*s)
1244                 cddir = s;
1245             break;
1246         case 0:
1247             break;
1248         case '-':
1249             if (!*++s || isSPACE(*s)) {
1250                 argc--,argv++;
1251                 goto switch_end;
1252             }
1253             /* catch use of gnu style long options */
1254             if (strEQ(s, "version")) {
1255                 s = "v";
1256                 goto reswitch;
1257             }
1258             if (strEQ(s, "help")) {
1259                 s = "h";
1260                 goto reswitch;
1261             }
1262             s--;
1263             /* FALL THROUGH */
1264         default:
1265             Perl_croak(aTHX_ "Unrecognized switch: -%s  (-h will show valid options)",s);
1266         }
1267     }
1268   switch_end:
1269
1270     if (
1271 #ifndef SECURE_INTERNAL_GETENV
1272         !PL_tainting &&
1273 #endif
1274         (s = PerlEnv_getenv("PERL5OPT")))
1275     {
1276         char *popt = s;
1277         while (isSPACE(*s))
1278             s++;
1279         if (*s == '-' && *(s+1) == 'T')
1280             PL_tainting = TRUE;
1281         else {
1282             char *popt_copy = Nullch;
1283             while (s && *s) {
1284                 char *d;
1285                 while (isSPACE(*s))
1286                     s++;
1287                 if (*s == '-') {
1288                     s++;
1289                     if (isSPACE(*s))
1290                         continue;
1291                 }
1292                 d = s;
1293                 if (!*s)
1294                     break;
1295                 if (!strchr("DIMUdmw", *s))
1296                     Perl_croak(aTHX_ "Illegal switch in PERL5OPT: -%c", *s);
1297                 while (++s && *s) {
1298                     if (isSPACE(*s)) {
1299                         if (!popt_copy) {
1300                             popt_copy = SvPVX(sv_2mortal(newSVpv(popt,0)));
1301                             s = popt_copy + (s - popt);
1302                             d = popt_copy + (d - popt);
1303                         }
1304                         *s++ = '\0';
1305                         break;
1306                     }
1307                 }
1308                 moreswitches(d);
1309             }
1310         }
1311     }
1312
1313     if (!scriptname)
1314         scriptname = argv[0];
1315     if (PL_e_script) {
1316         argc++,argv--;
1317         scriptname = BIT_BUCKET;        /* don't look for script or read stdin */
1318     }
1319     else if (scriptname == Nullch) {
1320 #ifdef MSDOS
1321         if ( PerlLIO_isatty(PerlIO_fileno(PerlIO_stdin())) )
1322             moreswitches("h");
1323 #endif
1324         scriptname = "-";
1325     }
1326
1327     init_perllib();
1328
1329     open_script(scriptname,dosearch,sv,&fdscript);
1330
1331     validate_suid(validarg, scriptname,fdscript);
1332
1333 #ifndef PERL_MICRO
1334 #if defined(SIGCHLD) || defined(SIGCLD)
1335     {
1336 #ifndef SIGCHLD
1337 #  define SIGCHLD SIGCLD
1338 #endif
1339         Sighandler_t sigstate = rsignal_state(SIGCHLD);
1340         if (sigstate == SIG_IGN) {
1341             if (ckWARN(WARN_SIGNAL))
1342                 Perl_warner(aTHX_ WARN_SIGNAL,
1343                             "Can't ignore signal CHLD, forcing to default");
1344             (void)rsignal(SIGCHLD, (Sighandler_t)SIG_DFL);
1345         }
1346     }
1347 #endif
1348 #endif
1349
1350 #ifdef MACOS_TRADITIONAL
1351     if (PL_doextract || gMacPerl_AlwaysExtract) {
1352 #else
1353     if (PL_doextract) {
1354 #endif
1355         find_beginning();
1356         if (cddir && PerlDir_chdir(cddir) < 0)
1357             Perl_croak(aTHX_ "Can't chdir to %s",cddir);
1358
1359     }
1360
1361     PL_main_cv = PL_compcv = (CV*)NEWSV(1104,0);
1362     sv_upgrade((SV *)PL_compcv, SVt_PVCV);
1363     CvUNIQUE_on(PL_compcv);
1364
1365     PL_comppad = newAV();
1366     av_push(PL_comppad, Nullsv);
1367     PL_curpad = AvARRAY(PL_comppad);
1368     PL_comppad_name = newAV();
1369     PL_comppad_name_fill = 0;
1370     PL_min_intro_pending = 0;
1371     PL_padix = 0;
1372 #ifdef USE_THREADS
1373     av_store(PL_comppad_name, 0, newSVpvn("@_", 2));
1374     PL_curpad[0] = (SV*)newAV();
1375     SvPADMY_on(PL_curpad[0]);   /* XXX Needed? */
1376     CvOWNER(PL_compcv) = 0;
1377     New(666, CvMUTEXP(PL_compcv), 1, perl_mutex);
1378     MUTEX_INIT(CvMUTEXP(PL_compcv));
1379 #endif /* USE_THREADS */
1380
1381     comppadlist = newAV();
1382     AvREAL_off(comppadlist);
1383     av_store(comppadlist, 0, (SV*)PL_comppad_name);
1384     av_store(comppadlist, 1, (SV*)PL_comppad);
1385     CvPADLIST(PL_compcv) = comppadlist;
1386
1387     boot_core_PerlIO();
1388     boot_core_UNIVERSAL();
1389 #ifndef PERL_MICRO
1390     boot_core_xsutils();
1391 #endif
1392
1393     if (xsinit)
1394         (*xsinit)(aTHXo);       /* in case linked C routines want magical variables */
1395 #ifndef PERL_MICRO
1396 #if defined(VMS) || defined(WIN32) || defined(DJGPP) || defined(__CYGWIN__) || defined(EPOC)
1397     init_os_extras();
1398 #endif
1399 #endif
1400
1401 #ifdef USE_SOCKS
1402 #   ifdef HAS_SOCKS5_INIT
1403     socks5_init(argv[0]);
1404 #   else
1405     SOCKSinit(argv[0]);
1406 #   endif
1407 #endif
1408
1409     init_predump_symbols();
1410     /* init_postdump_symbols not currently designed to be called */
1411     /* more than once (ENV isn't cleared first, for example)     */
1412     /* But running with -u leaves %ENV & @ARGV undefined!    XXX */
1413     if (!PL_do_undump)
1414         init_postdump_symbols(argc,argv,env);
1415
1416     init_lexer();
1417
1418     /* now parse the script */
1419
1420     SETERRNO(0,SS$_NORMAL);
1421     PL_error_count = 0;
1422 #ifdef MACOS_TRADITIONAL
1423     if (gMacPerl_SyntaxError = (yyparse() || PL_error_count)) {
1424         if (PL_minus_c)
1425             Perl_croak(aTHX_ "%s had compilation errors.\n", MacPerl_MPWFileName(PL_origfilename));
1426         else {
1427             Perl_croak(aTHX_ "Execution of %s aborted due to compilation errors.\n",
1428                        MacPerl_MPWFileName(PL_origfilename));
1429         }
1430     }
1431 #else
1432     if (yyparse() || PL_error_count) {
1433         if (PL_minus_c)
1434             Perl_croak(aTHX_ "%s had compilation errors.\n", PL_origfilename);
1435         else {
1436             Perl_croak(aTHX_ "Execution of %s aborted due to compilation errors.\n",
1437                        PL_origfilename);
1438         }
1439     }
1440 #endif
1441     CopLINE_set(PL_curcop, 0);
1442     PL_curstash = PL_defstash;
1443     PL_preprocess = FALSE;
1444     if (PL_e_script) {
1445         SvREFCNT_dec(PL_e_script);
1446         PL_e_script = Nullsv;
1447     }
1448
1449     /* now that script is parsed, we can modify record separator */
1450     SvREFCNT_dec(PL_rs);
1451     PL_rs = SvREFCNT_inc(PL_nrs);
1452     sv_setsv(get_sv("/", TRUE), PL_rs);
1453     if (PL_do_undump)
1454         my_unexec();
1455
1456     if (isWARN_ONCE) {
1457         SAVECOPFILE(PL_curcop);
1458         SAVECOPLINE(PL_curcop);
1459         gv_check(PL_defstash);
1460     }
1461
1462     LEAVE;
1463     FREETMPS;
1464
1465 #ifdef MYMALLOC
1466     if ((s=PerlEnv_getenv("PERL_DEBUG_MSTATS")) && atoi(s) >= 2)
1467         dump_mstats("after compilation:");
1468 #endif
1469
1470     ENTER;
1471     PL_restartop = 0;
1472     return NULL;
1473 }
1474
1475 /*
1476 =for apidoc perl_run
1477
1478 Tells a Perl interpreter to run.  See L<perlembed>.
1479
1480 =cut
1481 */
1482
1483 int
1484 perl_run(pTHXx)
1485 {
1486     I32 oldscope;
1487     int ret = 0;
1488     dJMPENV;
1489 #ifdef USE_THREADS
1490     dTHX;
1491 #endif
1492
1493     oldscope = PL_scopestack_ix;
1494
1495 #ifdef PERL_FLEXIBLE_EXCEPTIONS
1496  redo_body:
1497     CALLPROTECT(aTHX_ pcur_env, &ret, MEMBER_TO_FPTR(S_vrun_body), oldscope);
1498 #else
1499     JMPENV_PUSH(ret);
1500 #endif
1501     switch (ret) {
1502     case 1:
1503         cxstack_ix = -1;                /* start context stack again */
1504         goto redo_body;
1505     case 0:                             /* normal completion */
1506 #ifndef PERL_FLEXIBLE_EXCEPTIONS
1507  redo_body:
1508         run_body(oldscope);
1509 #endif
1510         /* FALL THROUGH */
1511     case 2:                             /* my_exit() */
1512         while (PL_scopestack_ix > oldscope)
1513             LEAVE;
1514         FREETMPS;
1515         PL_curstash = PL_defstash;
1516 #ifdef MYMALLOC
1517         if (PerlEnv_getenv("PERL_DEBUG_MSTATS"))
1518             dump_mstats("after execution:  ");
1519 #endif
1520         ret = STATUS_NATIVE_EXPORT;
1521         break;
1522     case 3:
1523         if (PL_restartop) {
1524             POPSTACK_TO(PL_mainstack);
1525             goto redo_body;
1526         }
1527         PerlIO_printf(Perl_error_log, "panic: restartop\n");
1528         FREETMPS;
1529         ret = 1;
1530         break;
1531     }
1532
1533     JMPENV_POP;
1534     return ret;
1535 }
1536
1537 #ifdef PERL_FLEXIBLE_EXCEPTIONS
1538 STATIC void *
1539 S_vrun_body(pTHX_ va_list args)
1540 {
1541     I32 oldscope = va_arg(args, I32);
1542
1543     return run_body(oldscope);
1544 }
1545 #endif
1546
1547
1548 STATIC void *
1549 S_run_body(pTHX_ I32 oldscope)
1550 {
1551     DEBUG_r(PerlIO_printf(Perl_debug_log, "%s $` $& $' support.\n",
1552                     PL_sawampersand ? "Enabling" : "Omitting"));
1553
1554     if (!PL_restartop) {
1555         DEBUG_x(dump_all());
1556         DEBUG(PerlIO_printf(Perl_debug_log, "\nEXECUTING...\n\n"));
1557         DEBUG_S(PerlIO_printf(Perl_debug_log, "main thread is 0x%"UVxf"\n",
1558                               PTR2UV(thr)));
1559
1560         if (PL_minus_c) {
1561 #ifdef MACOS_TRADITIONAL
1562             PerlIO_printf(Perl_error_log, "%s syntax OK\n", MacPerl_MPWFileName(PL_origfilename));
1563 #else
1564             PerlIO_printf(Perl_error_log, "%s syntax OK\n", PL_origfilename);
1565 #endif
1566             my_exit(0);
1567         }
1568         if (PERLDB_SINGLE && PL_DBsingle)
1569             sv_setiv(PL_DBsingle, 1);
1570         if (PL_initav)
1571             call_list(oldscope, PL_initav);
1572     }
1573
1574     /* do it */
1575
1576     if (PL_restartop) {
1577         PL_op = PL_restartop;
1578         PL_restartop = 0;
1579         CALLRUNOPS(aTHX);
1580     }
1581     else if (PL_main_start) {
1582         CvDEPTH(PL_main_cv) = 1;
1583         PL_op = PL_main_start;
1584         CALLRUNOPS(aTHX);
1585     }
1586
1587     my_exit(0);
1588     /* NOTREACHED */
1589     return NULL;
1590 }
1591
1592 /*
1593 =for apidoc p||get_sv
1594
1595 Returns the SV of the specified Perl scalar.  If C<create> is set and the
1596 Perl variable does not exist then it will be created.  If C<create> is not
1597 set and the variable does not exist then NULL is returned.
1598
1599 =cut
1600 */
1601
1602 SV*
1603 Perl_get_sv(pTHX_ const char *name, I32 create)
1604 {
1605     GV *gv;
1606 #ifdef USE_THREADS
1607     if (name[1] == '\0' && !isALPHA(name[0])) {
1608         PADOFFSET tmp = find_threadsv(name);
1609         if (tmp != NOT_IN_PAD)
1610             return THREADSV(tmp);
1611     }
1612 #endif /* USE_THREADS */
1613     gv = gv_fetchpv(name, create, SVt_PV);
1614     if (gv)
1615         return GvSV(gv);
1616     return Nullsv;
1617 }
1618
1619 /*
1620 =for apidoc p||get_av
1621
1622 Returns the AV of the specified Perl array.  If C<create> is set and the
1623 Perl variable does not exist then it will be created.  If C<create> is not
1624 set and the variable does not exist then NULL is returned.
1625
1626 =cut
1627 */
1628
1629 AV*
1630 Perl_get_av(pTHX_ const char *name, I32 create)
1631 {
1632     GV* gv = gv_fetchpv(name, create, SVt_PVAV);
1633     if (create)
1634         return GvAVn(gv);
1635     if (gv)
1636         return GvAV(gv);
1637     return Nullav;
1638 }
1639
1640 /*
1641 =for apidoc p||get_hv
1642
1643 Returns the HV of the specified Perl hash.  If C<create> is set and the
1644 Perl variable does not exist then it will be created.  If C<create> is not
1645 set and the variable does not exist then NULL is returned.
1646
1647 =cut
1648 */
1649
1650 HV*
1651 Perl_get_hv(pTHX_ const char *name, I32 create)
1652 {
1653     GV* gv = gv_fetchpv(name, create, SVt_PVHV);
1654     if (create)
1655         return GvHVn(gv);
1656     if (gv)
1657         return GvHV(gv);
1658     return Nullhv;
1659 }
1660
1661 /*
1662 =for apidoc p||get_cv
1663
1664 Returns the CV of the specified Perl subroutine.  If C<create> is set and
1665 the Perl subroutine does not exist then it will be declared (which has the
1666 same effect as saying C<sub name;>).  If C<create> is not set and the
1667 subroutine does not exist then NULL is returned.
1668
1669 =cut
1670 */
1671
1672 CV*
1673 Perl_get_cv(pTHX_ const char *name, I32 create)
1674 {
1675     GV* gv = gv_fetchpv(name, create, SVt_PVCV);
1676     /* XXX unsafe for threads if eval_owner isn't held */
1677     /* XXX this is probably not what they think they're getting.
1678      * It has the same effect as "sub name;", i.e. just a forward
1679      * declaration! */
1680     if (create && !GvCVu(gv))
1681         return newSUB(start_subparse(FALSE, 0),
1682                       newSVOP(OP_CONST, 0, newSVpv(name,0)),
1683                       Nullop,
1684                       Nullop);
1685     if (gv)
1686         return GvCVu(gv);
1687     return Nullcv;
1688 }
1689
1690 /* Be sure to refetch the stack pointer after calling these routines. */
1691
1692 /*
1693 =for apidoc p||call_argv
1694
1695 Performs a callback to the specified Perl sub.  See L<perlcall>.
1696
1697 =cut
1698 */
1699
1700 I32
1701 Perl_call_argv(pTHX_ const char *sub_name, I32 flags, register char **argv)
1702
1703                         /* See G_* flags in cop.h */
1704                         /* null terminated arg list */
1705 {
1706     dSP;
1707
1708     PUSHMARK(SP);
1709     if (argv) {
1710         while (*argv) {
1711             XPUSHs(sv_2mortal(newSVpv(*argv,0)));
1712             argv++;
1713         }
1714         PUTBACK;
1715     }
1716     return call_pv(sub_name, flags);
1717 }
1718
1719 /*
1720 =for apidoc p||call_pv
1721
1722 Performs a callback to the specified Perl sub.  See L<perlcall>.
1723
1724 =cut
1725 */
1726
1727 I32
1728 Perl_call_pv(pTHX_ const char *sub_name, I32 flags)
1729                         /* name of the subroutine */
1730                         /* See G_* flags in cop.h */
1731 {
1732     return call_sv((SV*)get_cv(sub_name, TRUE), flags);
1733 }
1734
1735 /*
1736 =for apidoc p||call_method
1737
1738 Performs a callback to the specified Perl method.  The blessed object must
1739 be on the stack.  See L<perlcall>.
1740
1741 =cut
1742 */
1743
1744 I32
1745 Perl_call_method(pTHX_ const char *methname, I32 flags)
1746                         /* name of the subroutine */
1747                         /* See G_* flags in cop.h */
1748 {
1749     return call_sv(sv_2mortal(newSVpv(methname,0)), flags | G_METHOD);
1750 }
1751
1752 /* May be called with any of a CV, a GV, or an SV containing the name. */
1753 /*
1754 =for apidoc p||call_sv
1755
1756 Performs a callback to the Perl sub whose name is in the SV.  See
1757 L<perlcall>.
1758
1759 =cut
1760 */
1761
1762 I32
1763 Perl_call_sv(pTHX_ SV *sv, I32 flags)
1764                         /* See G_* flags in cop.h */
1765 {
1766     dSP;
1767     LOGOP myop;         /* fake syntax tree node */
1768     UNOP method_op;
1769     I32 oldmark;
1770     volatile I32 retval = 0;
1771     I32 oldscope;
1772     bool oldcatch = CATCH_GET;
1773     int ret;
1774     OP* oldop = PL_op;
1775     dJMPENV;
1776
1777     if (flags & G_DISCARD) {
1778         ENTER;
1779         SAVETMPS;
1780     }
1781
1782     Zero(&myop, 1, LOGOP);
1783     myop.op_next = Nullop;
1784     if (!(flags & G_NOARGS))
1785         myop.op_flags |= OPf_STACKED;
1786     myop.op_flags |= ((flags & G_VOID) ? OPf_WANT_VOID :
1787                       (flags & G_ARRAY) ? OPf_WANT_LIST :
1788                       OPf_WANT_SCALAR);
1789     SAVEOP();
1790     PL_op = (OP*)&myop;
1791
1792     EXTEND(PL_stack_sp, 1);
1793     *++PL_stack_sp = sv;
1794     oldmark = TOPMARK;
1795     oldscope = PL_scopestack_ix;
1796
1797     if (PERLDB_SUB && PL_curstash != PL_debstash
1798            /* Handle first BEGIN of -d. */
1799           && (PL_DBcv || (PL_DBcv = GvCV(PL_DBsub)))
1800            /* Try harder, since this may have been a sighandler, thus
1801             * curstash may be meaningless. */
1802           && (SvTYPE(sv) != SVt_PVCV || CvSTASH((CV*)sv) != PL_debstash)
1803           && !(flags & G_NODEBUG))
1804         PL_op->op_private |= OPpENTERSUB_DB;
1805
1806     if (flags & G_METHOD) {
1807         Zero(&method_op, 1, UNOP);
1808         method_op.op_next = PL_op;
1809         method_op.op_ppaddr = PL_ppaddr[OP_METHOD];
1810         myop.op_ppaddr = PL_ppaddr[OP_ENTERSUB];
1811         PL_op = (OP*)&method_op;
1812     }
1813
1814     if (!(flags & G_EVAL)) {
1815         CATCH_SET(TRUE);
1816         call_body((OP*)&myop, FALSE);
1817         retval = PL_stack_sp - (PL_stack_base + oldmark);
1818         CATCH_SET(oldcatch);
1819     }
1820     else {
1821         myop.op_other = (OP*)&myop;
1822         PL_markstack_ptr--;
1823         /* we're trying to emulate pp_entertry() here */
1824         {
1825             register PERL_CONTEXT *cx;
1826             I32 gimme = GIMME_V;
1827         
1828             ENTER;
1829             SAVETMPS;
1830         
1831             push_return(Nullop);
1832             PUSHBLOCK(cx, (CXt_EVAL|CXp_TRYBLOCK), PL_stack_sp);
1833             PUSHEVAL(cx, 0, 0);
1834             PL_eval_root = PL_op;             /* Only needed so that goto works right. */
1835         
1836             PL_in_eval = EVAL_INEVAL;
1837             if (flags & G_KEEPERR)
1838                 PL_in_eval |= EVAL_KEEPERR;
1839             else
1840                 sv_setpv(ERRSV,"");
1841         }
1842         PL_markstack_ptr++;
1843
1844 #ifdef PERL_FLEXIBLE_EXCEPTIONS
1845  redo_body:
1846         CALLPROTECT(aTHX_ pcur_env, &ret, MEMBER_TO_FPTR(S_vcall_body),
1847                     (OP*)&myop, FALSE);
1848 #else
1849         JMPENV_PUSH(ret);
1850 #endif
1851         switch (ret) {
1852         case 0:
1853 #ifndef PERL_FLEXIBLE_EXCEPTIONS
1854  redo_body:
1855             call_body((OP*)&myop, FALSE);
1856 #endif
1857             retval = PL_stack_sp - (PL_stack_base + oldmark);
1858             if (!(flags & G_KEEPERR))
1859                 sv_setpv(ERRSV,"");
1860             break;
1861         case 1:
1862             STATUS_ALL_FAILURE;
1863             /* FALL THROUGH */
1864         case 2:
1865             /* my_exit() was called */
1866             PL_curstash = PL_defstash;
1867             FREETMPS;
1868             JMPENV_POP;
1869             if (PL_statusvalue && !(PL_exit_flags & PERL_EXIT_EXPECTED))
1870                 Perl_croak(aTHX_ "Callback called exit");
1871             my_exit_jump();
1872             /* NOTREACHED */
1873         case 3:
1874             if (PL_restartop) {
1875                 PL_op = PL_restartop;
1876                 PL_restartop = 0;
1877                 goto redo_body;
1878             }
1879             PL_stack_sp = PL_stack_base + oldmark;
1880             if (flags & G_ARRAY)
1881                 retval = 0;
1882             else {
1883                 retval = 1;
1884                 *++PL_stack_sp = &PL_sv_undef;
1885             }
1886             break;
1887         }
1888
1889         if (PL_scopestack_ix > oldscope) {
1890             SV **newsp;
1891             PMOP *newpm;
1892             I32 gimme;
1893             register PERL_CONTEXT *cx;
1894             I32 optype;
1895
1896             POPBLOCK(cx,newpm);
1897             POPEVAL(cx);
1898             pop_return();
1899             PL_curpm = newpm;
1900             LEAVE;
1901         }
1902         JMPENV_POP;
1903     }
1904
1905     if (flags & G_DISCARD) {
1906         PL_stack_sp = PL_stack_base + oldmark;
1907         retval = 0;
1908         FREETMPS;
1909         LEAVE;
1910     }
1911     PL_op = oldop;
1912     return retval;
1913 }
1914
1915 #ifdef PERL_FLEXIBLE_EXCEPTIONS
1916 STATIC void *
1917 S_vcall_body(pTHX_ va_list args)
1918 {
1919     OP *myop = va_arg(args, OP*);
1920     int is_eval = va_arg(args, int);
1921
1922     call_body(myop, is_eval);
1923     return NULL;
1924 }
1925 #endif
1926
1927 STATIC void
1928 S_call_body(pTHX_ OP *myop, int is_eval)
1929 {
1930     if (PL_op == myop) {
1931         if (is_eval)
1932             PL_op = Perl_pp_entereval(aTHX);    /* this doesn't do a POPMARK */
1933         else
1934             PL_op = Perl_pp_entersub(aTHX);     /* this does */
1935     }
1936     if (PL_op)
1937         CALLRUNOPS(aTHX);
1938 }
1939
1940 /* Eval a string. The G_EVAL flag is always assumed. */
1941
1942 /*
1943 =for apidoc p||eval_sv
1944
1945 Tells Perl to C<eval> the string in the SV.
1946
1947 =cut
1948 */
1949
1950 I32
1951 Perl_eval_sv(pTHX_ SV *sv, I32 flags)
1952
1953                         /* See G_* flags in cop.h */
1954 {
1955     dSP;
1956     UNOP myop;          /* fake syntax tree node */
1957     volatile I32 oldmark = SP - PL_stack_base;
1958     volatile I32 retval = 0;
1959     I32 oldscope;
1960     int ret;
1961     OP* oldop = PL_op;
1962     dJMPENV;
1963
1964     if (flags & G_DISCARD) {
1965         ENTER;
1966         SAVETMPS;
1967     }
1968
1969     SAVEOP();
1970     PL_op = (OP*)&myop;
1971     Zero(PL_op, 1, UNOP);
1972     EXTEND(PL_stack_sp, 1);
1973     *++PL_stack_sp = sv;
1974     oldscope = PL_scopestack_ix;
1975
1976     if (!(flags & G_NOARGS))
1977         myop.op_flags = OPf_STACKED;
1978     myop.op_next = Nullop;
1979     myop.op_type = OP_ENTEREVAL;
1980     myop.op_flags |= ((flags & G_VOID) ? OPf_WANT_VOID :
1981                       (flags & G_ARRAY) ? OPf_WANT_LIST :
1982                       OPf_WANT_SCALAR);
1983     if (flags & G_KEEPERR)
1984         myop.op_flags |= OPf_SPECIAL;
1985
1986 #ifdef PERL_FLEXIBLE_EXCEPTIONS
1987  redo_body:
1988     CALLPROTECT(aTHX_ pcur_env, &ret, MEMBER_TO_FPTR(S_vcall_body),
1989                 (OP*)&myop, TRUE);
1990 #else
1991     JMPENV_PUSH(ret);
1992 #endif
1993     switch (ret) {
1994     case 0:
1995 #ifndef PERL_FLEXIBLE_EXCEPTIONS
1996  redo_body:
1997         call_body((OP*)&myop,TRUE);
1998 #endif
1999         retval = PL_stack_sp - (PL_stack_base + oldmark);
2000         if (!(flags & G_KEEPERR))
2001             sv_setpv(ERRSV,"");
2002         break;
2003     case 1:
2004         STATUS_ALL_FAILURE;
2005         /* FALL THROUGH */
2006     case 2:
2007         /* my_exit() was called */
2008         PL_curstash = PL_defstash;
2009         FREETMPS;
2010         JMPENV_POP;
2011         if (PL_statusvalue && !(PL_exit_flags & PERL_EXIT_EXPECTED))
2012             Perl_croak(aTHX_ "Callback called exit");
2013         my_exit_jump();
2014         /* NOTREACHED */
2015     case 3:
2016         if (PL_restartop) {
2017             PL_op = PL_restartop;
2018             PL_restartop = 0;
2019             goto redo_body;
2020         }
2021         PL_stack_sp = PL_stack_base + oldmark;
2022         if (flags & G_ARRAY)
2023             retval = 0;
2024         else {
2025             retval = 1;
2026             *++PL_stack_sp = &PL_sv_undef;
2027         }
2028         break;
2029     }
2030
2031     JMPENV_POP;
2032     if (flags & G_DISCARD) {
2033         PL_stack_sp = PL_stack_base + oldmark;
2034         retval = 0;
2035         FREETMPS;
2036         LEAVE;
2037     }
2038     PL_op = oldop;
2039     return retval;
2040 }
2041
2042 /*
2043 =for apidoc p||eval_pv
2044
2045 Tells Perl to C<eval> the given string and return an SV* result.
2046
2047 =cut
2048 */
2049
2050 SV*
2051 Perl_eval_pv(pTHX_ const char *p, I32 croak_on_error)
2052 {
2053     dSP;
2054     SV* sv = newSVpv(p, 0);
2055
2056     eval_sv(sv, G_SCALAR);
2057     SvREFCNT_dec(sv);
2058
2059     SPAGAIN;
2060     sv = POPs;
2061     PUTBACK;
2062
2063     if (croak_on_error && SvTRUE(ERRSV)) {
2064         STRLEN n_a;
2065         Perl_croak(aTHX_ SvPVx(ERRSV, n_a));
2066     }
2067
2068     return sv;
2069 }
2070
2071 /* Require a module. */
2072
2073 /*
2074 =for apidoc p||require_pv
2075
2076 Tells Perl to C<require> the file named by the string argument.  It is
2077 analogous to the Perl code C<eval "require '$file'">.  It's even
2078 implemented that way; consider using Perl_load_module instead.
2079
2080 =cut */
2081
2082 void
2083 Perl_require_pv(pTHX_ const char *pv)
2084 {
2085     SV* sv;
2086     dSP;
2087     PUSHSTACKi(PERLSI_REQUIRE);
2088     PUTBACK;
2089     sv = sv_newmortal();
2090     sv_setpv(sv, "require '");
2091     sv_catpv(sv, pv);
2092     sv_catpv(sv, "'");
2093     eval_sv(sv, G_DISCARD);
2094     SPAGAIN;
2095     POPSTACK;
2096 }
2097
2098 void
2099 Perl_magicname(pTHX_ char *sym, char *name, I32 namlen)
2100 {
2101     register GV *gv;
2102
2103     if ((gv = gv_fetchpv(sym,TRUE, SVt_PV)))
2104         sv_magic(GvSV(gv), (SV*)gv, PERL_MAGIC_sv, name, namlen);
2105 }
2106
2107 STATIC void
2108 S_usage(pTHX_ char *name)               /* XXX move this out into a module ? */
2109 {
2110     /* This message really ought to be max 23 lines.
2111      * Removed -h because the user already knows that option. Others? */
2112
2113     static char *usage_msg[] = {
2114 "-0[octal]       specify record separator (\\0, if no argument)",
2115 "-a              autosplit mode with -n or -p (splits $_ into @F)",
2116 "-C              enable native wide character system interfaces",
2117 "-c              check syntax only (runs BEGIN and CHECK blocks)",
2118 "-d[:debugger]   run program under debugger",
2119 "-D[number/list] set debugging flags (argument is a bit mask or alphabets)",
2120 "-e 'command'    one line of program (several -e's allowed, omit programfile)",
2121 "-F/pattern/     split() pattern for -a switch (//'s are optional)",
2122 "-i[extension]   edit <> files in place (makes backup if extension supplied)",
2123 "-Idirectory     specify @INC/#include directory (several -I's allowed)",
2124 "-l[octal]       enable line ending processing, specifies line terminator",
2125 "-[mM][-]module  execute `use/no module...' before executing program",
2126 "-n              assume 'while (<>) { ... }' loop around program",
2127 "-p              assume loop like -n but print line also, like sed",
2128 "-P              run program through C preprocessor before compilation",
2129 "-s              enable rudimentary parsing for switches after programfile",
2130 "-S              look for programfile using PATH environment variable",
2131 "-T              enable tainting checks",
2132 "-u              dump core after parsing program",
2133 "-U              allow unsafe operations",
2134 "-v              print version, subversion (includes VERY IMPORTANT perl info)",
2135 "-V[:variable]   print configuration summary (or a single Config.pm variable)",
2136 "-w              enable many useful warnings (RECOMMENDED)",
2137 "-W              enable all warnings",
2138 "-X              disable all warnings",
2139 "-x[directory]   strip off text before #!perl line and perhaps cd to directory",
2140 "\n",
2141 NULL
2142 };
2143     char **p = usage_msg;
2144
2145     PerlIO_printf(PerlIO_stdout(),
2146                   "\nUsage: %s [switches] [--] [programfile] [arguments]",
2147                   name);
2148     while (*p)
2149         PerlIO_printf(PerlIO_stdout(), "\n  %s", *p++);
2150 }
2151
2152 /* This routine handles any switches that can be given during run */
2153
2154 char *
2155 Perl_moreswitches(pTHX_ char *s)
2156 {
2157     STRLEN numlen;
2158     U32 rschar;
2159
2160     switch (*s) {
2161     case '0':
2162     {
2163         numlen = 0;                     /* disallow underscores */
2164         rschar = (U32)scan_oct(s, 4, &numlen);
2165         SvREFCNT_dec(PL_nrs);
2166         if (rschar & ~((U8)~0))
2167             PL_nrs = &PL_sv_undef;
2168         else if (!rschar && numlen >= 2)
2169             PL_nrs = newSVpvn("", 0);
2170         else {
2171             char ch = rschar;
2172             PL_nrs = newSVpvn(&ch, 1);
2173         }
2174         return s + numlen;
2175     }
2176     case 'C':
2177         PL_widesyscalls = TRUE;
2178         s++;
2179         return s;
2180     case 'F':
2181         PL_minus_F = TRUE;
2182         PL_splitstr = savepv(s + 1);
2183         s += strlen(s);
2184         return s;
2185     case 'a':
2186         PL_minus_a = TRUE;
2187         s++;
2188         return s;
2189     case 'c':
2190         PL_minus_c = TRUE;
2191         s++;
2192         return s;
2193     case 'd':
2194         forbid_setid("-d");
2195         s++;
2196         /* The following permits -d:Mod to accepts arguments following an =
2197            in the fashion that -MSome::Mod does. */
2198         if (*s == ':' || *s == '=') {
2199             char *start;
2200             SV *sv;
2201             sv = newSVpv("use Devel::", 0);
2202             start = ++s;
2203             /* We now allow -d:Module=Foo,Bar */
2204             while(isALNUM(*s) || *s==':') ++s;
2205             if (*s != '=')
2206                 sv_catpv(sv, start);
2207             else {
2208                 sv_catpvn(sv, start, s-start);
2209                 sv_catpv(sv, " split(/,/,q{");
2210                 sv_catpv(sv, ++s);
2211                 sv_catpv(sv,    "})");
2212             }
2213             s += strlen(s);
2214             my_setenv("PERL5DB", SvPV(sv, PL_na));
2215         }
2216         if (!PL_perldb) {
2217             PL_perldb = PERLDB_ALL;
2218             init_debugger();
2219         }
2220         return s;
2221     case 'D':
2222     {   
2223 #ifdef DEBUGGING
2224         forbid_setid("-D");
2225         if (isALPHA(s[1])) {
2226             /* if adding extra options, remember to update DEBUG_MASK */
2227             static char debopts[] = "psltocPmfrxuLHXDSTR";
2228             char *d;
2229
2230             for (s++; *s && (d = strchr(debopts,*s)); s++)
2231                 PL_debug |= 1 << (d - debopts);
2232         }
2233         else {
2234             PL_debug = atoi(s+1);
2235             for (s++; isDIGIT(*s); s++) ;
2236         }
2237         PL_debug |= DEBUG_TOP_FLAG;
2238 #else
2239         if (ckWARN_d(WARN_DEBUGGING))
2240             Perl_warner(aTHX_ WARN_DEBUGGING,
2241                    "Recompile perl with -DDEBUGGING to use -D switch\n");
2242         for (s++; isALNUM(*s); s++) ;
2243 #endif
2244         /*SUPPRESS 530*/
2245         return s;
2246     }   
2247     case 'h':
2248         usage(PL_origargv[0]);
2249         PerlProc_exit(0);
2250     case 'i':
2251         if (PL_inplace)
2252             Safefree(PL_inplace);
2253         PL_inplace = savepv(s+1);
2254         /*SUPPRESS 530*/
2255         for (s = PL_inplace; *s && !isSPACE(*s); s++) ;
2256         if (*s) {
2257             *s++ = '\0';
2258             if (*s == '-')      /* Additional switches on #! line. */
2259                 s++;
2260         }
2261         return s;
2262     case 'I':   /* -I handled both here and in parse_perl() */
2263         forbid_setid("-I");
2264         ++s;
2265         while (*s && isSPACE(*s))
2266             ++s;
2267         if (*s) {
2268             char *e, *p;
2269             p = s;
2270             /* ignore trailing spaces (possibly followed by other switches) */
2271             do {
2272                 for (e = p; *e && !isSPACE(*e); e++) ;
2273                 p = e;
2274                 while (isSPACE(*p))
2275                     p++;
2276             } while (*p && *p != '-');
2277             e = savepvn(s, e-s);
2278             incpush(e, TRUE, TRUE);
2279             Safefree(e);
2280             s = p;
2281             if (*s == '-')
2282                 s++;
2283         }
2284         else
2285             Perl_croak(aTHX_ "No directory specified for -I");
2286         return s;
2287     case 'l':
2288         PL_minus_l = TRUE;
2289         s++;
2290         if (PL_ors_sv) {
2291             SvREFCNT_dec(PL_ors_sv);
2292             PL_ors_sv = Nullsv;
2293         }
2294         if (isDIGIT(*s)) {
2295             PL_ors_sv = newSVpvn("\n",1);
2296             numlen = 0;                 /* disallow underscores */
2297             *SvPVX(PL_ors_sv) = (char)scan_oct(s, 3 + (*s == '0'), &numlen);
2298             s += numlen;
2299         }
2300         else {
2301             if (RsPARA(PL_nrs)) {
2302                 PL_ors_sv = newSVpvn("\n\n",2);
2303             }
2304             else {
2305                 PL_ors_sv = newSVsv(PL_nrs);
2306             }
2307         }
2308         return s;
2309     case 'M':
2310         forbid_setid("-M");     /* XXX ? */
2311         /* FALL THROUGH */
2312     case 'm':
2313         forbid_setid("-m");     /* XXX ? */
2314         if (*++s) {
2315             char *start;
2316             SV *sv;
2317             char *use = "use ";
2318             /* -M-foo == 'no foo'       */
2319             if (*s == '-') { use = "no "; ++s; }
2320             sv = newSVpv(use,0);
2321             start = s;
2322             /* We allow -M'Module qw(Foo Bar)'  */
2323             while(isALNUM(*s) || *s==':') ++s;
2324             if (*s != '=') {
2325                 sv_catpv(sv, start);
2326                 if (*(start-1) == 'm') {
2327                     if (*s != '\0')
2328                         Perl_croak(aTHX_ "Can't use '%c' after -mname", *s);
2329                     sv_catpv( sv, " ()");
2330                 }
2331             } else {
2332                 if (s == start)
2333                     Perl_croak(aTHX_ "Module name required with -%c option",
2334                                s[-1]);
2335                 sv_catpvn(sv, start, s-start);
2336                 sv_catpv(sv, " split(/,/,q{");
2337                 sv_catpv(sv, ++s);
2338                 sv_catpv(sv,    "})");
2339             }
2340             s += strlen(s);
2341             if (!PL_preambleav)
2342                 PL_preambleav = newAV();
2343             av_push(PL_preambleav, sv);
2344         }
2345         else
2346             Perl_croak(aTHX_ "No space allowed after -%c", *(s-1));
2347         return s;
2348     case 'n':
2349         PL_minus_n = TRUE;
2350         s++;
2351         return s;
2352     case 'p':
2353         PL_minus_p = TRUE;
2354         s++;
2355         return s;
2356     case 's':
2357         forbid_setid("-s");
2358         PL_doswitches = TRUE;
2359         s++;
2360         return s;
2361     case 'T':
2362         if (!PL_tainting)
2363             Perl_croak(aTHX_ "Too late for \"-T\" option");
2364         s++;
2365         return s;
2366     case 'u':
2367 #ifdef MACOS_TRADITIONAL
2368         Perl_croak(aTHX_ "Believe me, you don't want to use \"-u\" on a Macintosh");
2369 #endif
2370         PL_do_undump = TRUE;
2371         s++;
2372         return s;
2373     case 'U':
2374         PL_unsafe = TRUE;
2375         s++;
2376         return s;
2377     case 'v':
2378 #if !defined(DGUX)
2379         PerlIO_printf(PerlIO_stdout(),
2380                       Perl_form(aTHX_ "\nThis is perl, v%"VDf" built for %s",
2381                                 PL_patchlevel, ARCHNAME));
2382 #else /* DGUX */
2383 /* Adjust verbose output as in the perl that ships with the DG/UX OS from EMC */
2384         PerlIO_printf(PerlIO_stdout(),
2385                         Perl_form(aTHX_ "\nThis is perl, version %vd\n", PL_patchlevel));
2386         PerlIO_printf(PerlIO_stdout(),
2387                         Perl_form(aTHX_ "        built under %s at %s %s\n",
2388                                         OSNAME, __DATE__, __TIME__));
2389         PerlIO_printf(PerlIO_stdout(),
2390                         Perl_form(aTHX_ "        OS Specific Release: %s\n",
2391                                         OSVERS));
2392 #endif /* !DGUX */
2393
2394 #if defined(LOCAL_PATCH_COUNT)
2395         if (LOCAL_PATCH_COUNT > 0)
2396             PerlIO_printf(PerlIO_stdout(),
2397                           "\n(with %d registered patch%s, "
2398                           "see perl -V for more detail)",
2399                           (int)LOCAL_PATCH_COUNT,
2400                           (LOCAL_PATCH_COUNT!=1) ? "es" : "");
2401 #endif
2402
2403         PerlIO_printf(PerlIO_stdout(),
2404                       "\n\nCopyright 1987-2001, Larry Wall\n");
2405 #ifdef MACOS_TRADITIONAL
2406         PerlIO_printf(PerlIO_stdout(),
2407                       "\nMac OS port Copyright (c) 1991-2001, Matthias Neeracher\n");
2408 #endif
2409 #ifdef MSDOS
2410         PerlIO_printf(PerlIO_stdout(),
2411                       "\nMS-DOS port Copyright (c) 1989, 1990, Diomidis Spinellis\n");
2412 #endif
2413 #ifdef DJGPP
2414         PerlIO_printf(PerlIO_stdout(),
2415                       "djgpp v2 port (jpl5003c) by Hirofumi Watanabe, 1996\n"
2416                       "djgpp v2 port (perl5004+) by Laszlo Molnar, 1997-1999\n");
2417 #endif
2418 #ifdef OS2
2419         PerlIO_printf(PerlIO_stdout(),
2420                       "\n\nOS/2 port Copyright (c) 1990, 1991, Raymond Chen, Kai Uwe Rommel\n"
2421                       "Version 5 port Copyright (c) 1994-1999, Andreas Kaiser, Ilya Zakharevich\n");
2422 #endif
2423 #ifdef atarist
2424         PerlIO_printf(PerlIO_stdout(),
2425                       "atariST series port, ++jrb  bammi@cadence.com\n");
2426 #endif
2427 #ifdef __BEOS__
2428         PerlIO_printf(PerlIO_stdout(),
2429                       "BeOS port Copyright Tom Spindler, 1997-1999\n");
2430 #endif
2431 #ifdef MPE
2432         PerlIO_printf(PerlIO_stdout(),
2433                       "MPE/iX port Copyright by Mark Klein and Mark Bixby, 1996-2001\n");
2434 #endif
2435 #ifdef OEMVS
2436         PerlIO_printf(PerlIO_stdout(),
2437                       "MVS (OS390) port by Mortice Kern Systems, 1997-1999\n");
2438 #endif
2439 #ifdef __VOS__
2440         PerlIO_printf(PerlIO_stdout(),
2441                       "Stratus VOS port by Paul_Green@stratus.com, 1997-1999\n");
2442 #endif
2443 #ifdef __OPEN_VM
2444         PerlIO_printf(PerlIO_stdout(),
2445                       "VM/ESA port by Neale Ferguson, 1998-1999\n");
2446 #endif
2447 #ifdef POSIX_BC
2448         PerlIO_printf(PerlIO_stdout(),
2449                       "BS2000 (POSIX) port by Start Amadeus GmbH, 1998-1999\n");
2450 #endif
2451 #ifdef __MINT__
2452         PerlIO_printf(PerlIO_stdout(),
2453                       "MiNT port by Guido Flohr, 1997-1999\n");
2454 #endif
2455 #ifdef EPOC
2456         PerlIO_printf(PerlIO_stdout(),
2457                       "EPOC port by Olaf Flebbe, 1999-2000\n");
2458 #endif
2459 #ifdef UNDER_CE
2460         printf("WINCE port by Rainer Keuchel, 2001\n");
2461         printf("Built on " __DATE__ " " __TIME__ "\n\n");
2462         wce_hitreturn();
2463 #endif
2464 #ifdef BINARY_BUILD_NOTICE
2465         BINARY_BUILD_NOTICE;
2466 #endif
2467         PerlIO_printf(PerlIO_stdout(),
2468                       "\n\
2469 Perl may be copied only under the terms of either the Artistic License or the\n\
2470 GNU General Public License, which may be found in the Perl 5 source kit.\n\n\
2471 Complete documentation for Perl, including FAQ lists, should be found on\n\
2472 this system using `man perl' or `perldoc perl'.  If you have access to the\n\
2473 Internet, point your browser at http://www.perl.com/, the Perl Home Page.\n\n");
2474         PerlProc_exit(0);
2475     case 'w':
2476         if (! (PL_dowarn & G_WARN_ALL_MASK))
2477             PL_dowarn |= G_WARN_ON;
2478         s++;
2479         return s;
2480     case 'W':
2481         PL_dowarn = G_WARN_ALL_ON|G_WARN_ON;
2482         PL_compiling.cop_warnings = pWARN_ALL ;
2483         s++;
2484         return s;
2485     case 'X':
2486         PL_dowarn = G_WARN_ALL_OFF;
2487         PL_compiling.cop_warnings = pWARN_NONE ;
2488         s++;
2489         return s;
2490     case '*':
2491     case ' ':
2492         if (s[1] == '-')        /* Additional switches on #! line. */
2493             return s+2;
2494         break;
2495     case '-':
2496     case 0:
2497 #if defined(WIN32) || !defined(PERL_STRICT_CR)
2498     case '\r':
2499 #endif
2500     case '\n':
2501     case '\t':
2502         break;
2503 #ifdef ALTERNATE_SHEBANG
2504     case 'S':                   /* OS/2 needs -S on "extproc" line. */
2505         break;
2506 #endif
2507     case 'P':
2508         if (PL_preprocess)
2509             return s+1;
2510         /* FALL THROUGH */
2511     default:
2512         Perl_croak(aTHX_ "Can't emulate -%.1s on #! line",s);
2513     }
2514     return Nullch;
2515 }
2516
2517 /* compliments of Tom Christiansen */
2518
2519 /* unexec() can be found in the Gnu emacs distribution */
2520 /* Known to work with -DUNEXEC and using unexelf.c from GNU emacs-20.2 */
2521
2522 void
2523 Perl_my_unexec(pTHX)
2524 {
2525 #ifdef UNEXEC
2526     SV*    prog;
2527     SV*    file;
2528     int    status = 1;
2529     extern int etext;
2530
2531     prog = newSVpv(BIN_EXP, 0);
2532     sv_catpv(prog, "/perl");
2533     file = newSVpv(PL_origfilename, 0);
2534     sv_catpv(file, ".perldump");
2535
2536     unexec(SvPVX(file), SvPVX(prog), &etext, sbrk(0), 0);
2537     /* unexec prints msg to stderr in case of failure */
2538     PerlProc_exit(status);
2539 #else
2540 #  ifdef VMS
2541 #    include <lib$routines.h>
2542      lib$signal(SS$_DEBUG);  /* ssdef.h #included from vmsish.h */
2543 #  else
2544     ABORT();            /* for use with undump */
2545 #  endif
2546 #endif
2547 }
2548
2549 /* initialize curinterp */
2550 STATIC void
2551 S_init_interp(pTHX)
2552 {
2553
2554 #ifdef PERL_OBJECT              /* XXX kludge */
2555 #define I_REINIT \
2556   STMT_START {                          \
2557     PL_chopset          = " \n-";       \
2558     PL_copline          = NOLINE;       \
2559     PL_curcop           = &PL_compiling;\
2560     PL_curcopdb         = NULL;         \
2561     PL_dbargs           = 0;            \
2562     PL_dumpindent       = 4;            \
2563     PL_laststatval      = -1;           \
2564     PL_laststype        = OP_STAT;      \
2565     PL_maxscream        = -1;           \
2566     PL_maxsysfd         = MAXSYSFD;     \
2567     PL_statname         = Nullsv;       \
2568     PL_tmps_floor       = -1;           \
2569     PL_tmps_ix          = -1;           \
2570     PL_op_mask          = NULL;         \
2571     PL_laststatval      = -1;           \
2572     PL_laststype        = OP_STAT;      \
2573     PL_mess_sv          = Nullsv;       \
2574     PL_splitstr         = " ";          \
2575     PL_generation       = 100;          \
2576     PL_exitlist         = NULL;         \
2577     PL_exitlistlen      = 0;            \
2578     PL_regindent        = 0;            \
2579     PL_in_clean_objs    = FALSE;        \
2580     PL_in_clean_all     = FALSE;        \
2581     PL_profiledata      = NULL;         \
2582     PL_rsfp             = Nullfp;       \
2583     PL_rsfp_filters     = Nullav;       \
2584     PL_dirty            = FALSE;        \
2585   } STMT_END
2586     I_REINIT;
2587 #else
2588 #  ifdef MULTIPLICITY
2589 #    define PERLVAR(var,type)
2590 #    define PERLVARA(var,n,type)
2591 #    if defined(PERL_IMPLICIT_CONTEXT)
2592 #      if defined(USE_THREADS)
2593 #        define PERLVARI(var,type,init)         PERL_GET_INTERP->var = init;
2594 #        define PERLVARIC(var,type,init)        PERL_GET_INTERP->var = init;
2595 #      else /* !USE_THREADS */
2596 #        define PERLVARI(var,type,init)         aTHX->var = init;
2597 #        define PERLVARIC(var,type,init)        aTHX->var = init;
2598 #      endif /* USE_THREADS */
2599 #    else
2600 #      define PERLVARI(var,type,init)   PERL_GET_INTERP->var = init;
2601 #      define PERLVARIC(var,type,init)  PERL_GET_INTERP->var = init;
2602 #    endif
2603 #    include "intrpvar.h"
2604 #    ifndef USE_THREADS
2605 #      include "thrdvar.h"
2606 #    endif
2607 #    undef PERLVAR
2608 #    undef PERLVARA
2609 #    undef PERLVARI
2610 #    undef PERLVARIC
2611 #  else
2612 #    define PERLVAR(var,type)
2613 #    define PERLVARA(var,n,type)
2614 #    define PERLVARI(var,type,init)     PL_##var = init;
2615 #    define PERLVARIC(var,type,init)    PL_##var = init;
2616 #    include "intrpvar.h"
2617 #    ifndef USE_THREADS
2618 #      include "thrdvar.h"
2619 #    endif
2620 #    undef PERLVAR
2621 #    undef PERLVARA
2622 #    undef PERLVARI
2623 #    undef PERLVARIC
2624 #  endif
2625 #endif
2626
2627 }
2628
2629 STATIC void
2630 S_init_main_stash(pTHX)
2631 {
2632     GV *gv;
2633
2634     /* Note that strtab is a rather special HV.  Assumptions are made
2635        about not iterating on it, and not adding tie magic to it.
2636        It is properly deallocated in perl_destruct() */
2637     PL_strtab = newHV();
2638 #ifdef USE_THREADS
2639     MUTEX_INIT(&PL_strtab_mutex);
2640 #endif
2641     HvSHAREKEYS_off(PL_strtab);                 /* mandatory */
2642     hv_ksplit(PL_strtab, 512);
2643
2644     PL_curstash = PL_defstash = newHV();
2645     PL_curstname = newSVpvn("main",4);
2646     gv = gv_fetchpv("main::",TRUE, SVt_PVHV);
2647     SvREFCNT_dec(GvHV(gv));
2648     GvHV(gv) = (HV*)SvREFCNT_inc(PL_defstash);
2649     SvREADONLY_on(gv);
2650     HvNAME(PL_defstash) = savepv("main");
2651     PL_incgv = gv_HVadd(gv_AVadd(gv_fetchpv("INC",TRUE, SVt_PVAV)));
2652     GvMULTI_on(PL_incgv);
2653     PL_hintgv = gv_fetchpv("\010",TRUE, SVt_PV); /* ^H */
2654     GvMULTI_on(PL_hintgv);
2655     PL_defgv = gv_fetchpv("_",TRUE, SVt_PVAV);
2656     PL_errgv = gv_HVadd(gv_fetchpv("@", TRUE, SVt_PV));
2657     GvMULTI_on(PL_errgv);
2658     PL_replgv = gv_fetchpv("\022", TRUE, SVt_PV); /* ^R */
2659     GvMULTI_on(PL_replgv);
2660     (void)Perl_form(aTHX_ "%240s","");  /* Preallocate temp - for immediate signals. */
2661     sv_grow(ERRSV, 240);        /* Preallocate - for immediate signals. */
2662     sv_setpvn(ERRSV, "", 0);
2663     PL_curstash = PL_defstash;
2664     CopSTASH_set(&PL_compiling, PL_defstash);
2665     PL_debstash = GvHV(gv_fetchpv("DB::", GV_ADDMULTI, SVt_PVHV));
2666     PL_globalstash = GvHV(gv_fetchpv("CORE::GLOBAL::", GV_ADDMULTI, SVt_PVHV));
2667     PL_nullstash = GvHV(gv_fetchpv("<none>::", GV_ADDMULTI, SVt_PVHV));
2668     /* We must init $/ before switches are processed. */
2669     sv_setpvn(get_sv("/", TRUE), "\n", 1);
2670 }
2671
2672 STATIC void
2673 S_open_script(pTHX_ char *scriptname, bool dosearch, SV *sv, int *fdscript)
2674 {
2675     *fdscript = -1;
2676
2677     if (PL_e_script) {
2678         PL_origfilename = savepv("-e");
2679     }
2680     else {
2681         /* if find_script() returns, it returns a malloc()-ed value */
2682         PL_origfilename = scriptname = find_script(scriptname, dosearch, NULL, 1);
2683
2684         if (strnEQ(scriptname, "/dev/fd/", 8) && isDIGIT(scriptname[8]) ) {
2685             char *s = scriptname + 8;
2686             *fdscript = atoi(s);
2687             while (isDIGIT(*s))
2688                 s++;
2689             if (*s) {
2690                 scriptname = savepv(s + 1);
2691                 Safefree(PL_origfilename);
2692                 PL_origfilename = scriptname;
2693             }
2694         }
2695     }
2696
2697 #ifdef USE_ITHREADS
2698     Safefree(CopFILE(PL_curcop));
2699 #else
2700     SvREFCNT_dec(CopFILEGV(PL_curcop));
2701 #endif
2702     CopFILE_set(PL_curcop, PL_origfilename);
2703     if (strEQ(PL_origfilename,"-"))
2704         scriptname = "";
2705     if (*fdscript >= 0) {
2706         PL_rsfp = PerlIO_fdopen(*fdscript,PERL_SCRIPT_MODE);
2707 #if defined(HAS_FCNTL) && defined(F_SETFD)
2708         if (PL_rsfp)
2709             fcntl(PerlIO_fileno(PL_rsfp),F_SETFD,1);  /* ensure close-on-exec */
2710 #endif
2711     }
2712     else if (PL_preprocess) {
2713         char *cpp_cfg = CPPSTDIN;
2714         SV *cpp = newSVpvn("",0);
2715         SV *cmd = NEWSV(0,0);
2716
2717         if (strEQ(cpp_cfg, "cppstdin"))
2718             Perl_sv_catpvf(aTHX_ cpp, "%s/", BIN_EXP);
2719         sv_catpv(cpp, cpp_cfg);
2720
2721         sv_catpvn(sv, "-I", 2);
2722         sv_catpv(sv,PRIVLIB_EXP);
2723
2724         DEBUG_P(PerlIO_printf(Perl_debug_log,
2725                               "PL_preprocess: scriptname=\"%s\", cpp=\"%s\", sv=\"%s\", CPPMINUS=\"%s\"\n",
2726                               scriptname, SvPVX (cpp), SvPVX (sv), CPPMINUS));
2727 #if defined(MSDOS) || defined(WIN32)
2728         Perl_sv_setpvf(aTHX_ cmd, "\
2729 sed %s -e \"/^[^#]/b\" \
2730  -e \"/^#[      ]*include[      ]/b\" \
2731  -e \"/^#[      ]*define[       ]/b\" \
2732  -e \"/^#[      ]*if[   ]/b\" \
2733  -e \"/^#[      ]*ifdef[        ]/b\" \
2734  -e \"/^#[      ]*ifndef[       ]/b\" \
2735  -e \"/^#[      ]*else/b\" \
2736  -e \"/^#[      ]*elif[         ]/b\" \
2737  -e \"/^#[      ]*undef[        ]/b\" \
2738  -e \"/^#[      ]*endif/b\" \
2739  -e \"s/^#.*//\" \
2740  %s | %"SVf" -C %"SVf" %s",
2741           (PL_doextract ? "-e \"1,/^#/d\n\"" : ""),
2742 #else
2743 #  ifdef __OPEN_VM
2744         Perl_sv_setpvf(aTHX_ cmd, "\
2745 %s %s -e '/^[^#]/b' \
2746  -e '/^#[       ]*include[      ]/b' \
2747  -e '/^#[       ]*define[       ]/b' \
2748  -e '/^#[       ]*if[   ]/b' \
2749  -e '/^#[       ]*ifdef[        ]/b' \
2750  -e '/^#[       ]*ifndef[       ]/b' \
2751  -e '/^#[       ]*else/b' \
2752  -e '/^#[       ]*elif[         ]/b' \
2753  -e '/^#[       ]*undef[        ]/b' \
2754  -e '/^#[       ]*endif/b' \
2755  -e 's/^[       ]*#.*//' \
2756  %s | %"SVf" %"SVf" %s",
2757 #  else
2758         Perl_sv_setpvf(aTHX_ cmd, "\
2759 %s %s -e '/^[^#]/b' \
2760  -e '/^#[       ]*include[      ]/b' \
2761  -e '/^#[       ]*define[       ]/b' \
2762  -e '/^#[       ]*if[   ]/b' \
2763  -e '/^#[       ]*ifdef[        ]/b' \
2764  -e '/^#[       ]*ifndef[       ]/b' \
2765  -e '/^#[       ]*else/b' \
2766  -e '/^#[       ]*elif[         ]/b' \
2767  -e '/^#[       ]*undef[        ]/b' \
2768  -e '/^#[       ]*endif/b' \
2769  -e 's/^[       ]*#.*//' \
2770  %s | %"SVf" -C %"SVf" %s",
2771 #  endif
2772 #ifdef LOC_SED
2773           LOC_SED,
2774 #else
2775           "sed",
2776 #endif
2777           (PL_doextract ? "-e '1,/^#/d\n'" : ""),
2778 #endif
2779           scriptname, cpp, sv, CPPMINUS);
2780         PL_doextract = FALSE;
2781 #ifdef IAMSUID                          /* actually, this is caught earlier */
2782         if (PL_euid != PL_uid && !PL_euid) {    /* if running suidperl */
2783 #ifdef HAS_SETEUID
2784             (void)seteuid(PL_uid);              /* musn't stay setuid root */
2785 #else
2786 #ifdef HAS_SETREUID
2787             (void)setreuid((Uid_t)-1, PL_uid);
2788 #else
2789 #ifdef HAS_SETRESUID
2790             (void)setresuid((Uid_t)-1, PL_uid, (Uid_t)-1);
2791 #else
2792             PerlProc_setuid(PL_uid);
2793 #endif
2794 #endif
2795 #endif
2796             if (PerlProc_geteuid() != PL_uid)
2797                 Perl_croak(aTHX_ "Can't do seteuid!\n");
2798         }
2799 #endif /* IAMSUID */
2800         PL_rsfp = PerlProc_popen(SvPVX(cmd), "r");
2801         SvREFCNT_dec(cmd);
2802         SvREFCNT_dec(cpp);
2803     }
2804     else if (!*scriptname) {
2805         forbid_setid("program input from stdin");
2806         PL_rsfp = PerlIO_stdin();
2807     }
2808     else {
2809         PL_rsfp = PerlIO_open(scriptname,PERL_SCRIPT_MODE);
2810 #if defined(HAS_FCNTL) && defined(F_SETFD)
2811         if (PL_rsfp)
2812             fcntl(PerlIO_fileno(PL_rsfp),F_SETFD,1);  /* ensure close-on-exec */
2813 #endif
2814     }
2815     if (!PL_rsfp) {
2816 #ifdef DOSUID
2817 #ifndef IAMSUID         /* in case script is not readable before setuid */
2818         if (PL_euid &&
2819             PerlLIO_stat(CopFILE(PL_curcop),&PL_statbuf) >= 0 &&
2820             PL_statbuf.st_mode & (S_ISUID|S_ISGID))
2821         {
2822             /* try again */
2823             PerlProc_execv(Perl_form(aTHX_ "%s/sperl"PERL_FS_VER_FMT, BIN_EXP,
2824                                      (int)PERL_REVISION, (int)PERL_VERSION,
2825                                      (int)PERL_SUBVERSION), PL_origargv);
2826             Perl_croak(aTHX_ "Can't do setuid\n");
2827         }
2828 #endif
2829 #endif
2830 #ifdef IAMSUID
2831         errno = EPERM;
2832         Perl_croak(aTHX_ "Can't open perl script: %s\n",
2833                    Strerror(errno));
2834 #else
2835         Perl_croak(aTHX_ "Can't open perl script \"%s\": %s\n",
2836                    CopFILE(PL_curcop), Strerror(errno));
2837 #endif
2838     }
2839 }
2840
2841 /* Mention
2842  * I_SYSSTATVFS HAS_FSTATVFS
2843  * I_SYSMOUNT
2844  * I_STATFS     HAS_FSTATFS     HAS_GETFSSTAT
2845  * I_MNTENT     HAS_GETMNTENT   HAS_HASMNTOPT
2846  * here so that metaconfig picks them up. */
2847
2848 #ifdef IAMSUID
2849 STATIC int
2850 S_fd_on_nosuid_fs(pTHX_ int fd)
2851 {
2852     int check_okay = 0; /* able to do all the required sys/libcalls */
2853     int on_nosuid  = 0; /* the fd is on a nosuid fs */
2854 /*
2855  * Preferred order: fstatvfs(), fstatfs(), ustat()+getmnt(), getmntent().
2856  * fstatvfs() is UNIX98.
2857  * fstatfs() is 4.3 BSD.
2858  * ustat()+getmnt() is pre-4.3 BSD.
2859  * getmntent() is O(number-of-mounted-filesystems) and can hang on
2860  * an irrelevant filesystem while trying to reach the right one.
2861  */
2862
2863 #undef FD_ON_NOSUID_CHECK_OKAY  /* found the syscalls to do the check? */
2864
2865 #   if !defined(FD_ON_NOSUID_CHECK_OKAY) && \
2866         defined(HAS_FSTATVFS)
2867 #   define FD_ON_NOSUID_CHECK_OKAY
2868     struct statvfs stfs;
2869
2870     check_okay = fstatvfs(fd, &stfs) == 0;
2871     on_nosuid  = check_okay && (stfs.f_flag  & ST_NOSUID);
2872 #   endif /* fstatvfs */
2873
2874 #   if !defined(FD_ON_NOSUID_CHECK_OKAY) && \
2875         defined(PERL_MOUNT_NOSUID)      && \
2876         defined(HAS_FSTATFS)            && \
2877         defined(HAS_STRUCT_STATFS)      && \
2878         defined(HAS_STRUCT_STATFS_F_FLAGS)
2879 #   define FD_ON_NOSUID_CHECK_OKAY
2880     struct statfs  stfs;
2881
2882     check_okay = fstatfs(fd, &stfs)  == 0;
2883     on_nosuid  = check_okay && (stfs.f_flags & PERL_MOUNT_NOSUID);
2884 #   endif /* fstatfs */
2885
2886 #   if !defined(FD_ON_NOSUID_CHECK_OKAY) && \
2887         defined(PERL_MOUNT_NOSUID)      && \
2888         defined(HAS_FSTAT)              && \
2889         defined(HAS_USTAT)              && \
2890         defined(HAS_GETMNT)             && \
2891         defined(HAS_STRUCT_FS_DATA)     && \
2892         defined(NOSTAT_ONE)
2893 #   define FD_ON_NOSUID_CHECK_OKAY
2894     struct stat fdst;
2895
2896     if (fstat(fd, &fdst) == 0) {
2897         struct ustat us;
2898         if (ustat(fdst.st_dev, &us) == 0) {
2899             struct fs_data fsd;
2900             /* NOSTAT_ONE here because we're not examining fields which
2901              * vary between that case and STAT_ONE. */
2902             if (getmnt((int*)0, &fsd, (int)0, NOSTAT_ONE, us.f_fname) == 0) {
2903                 size_t cmplen = sizeof(us.f_fname);
2904                 if (sizeof(fsd.fd_req.path) < cmplen)
2905                     cmplen = sizeof(fsd.fd_req.path);
2906                 if (strnEQ(fsd.fd_req.path, us.f_fname, cmplen) &&
2907                     fdst.st_dev == fsd.fd_req.dev) {
2908                         check_okay = 1;
2909                         on_nosuid = fsd.fd_req.flags & PERL_MOUNT_NOSUID;
2910                     }
2911                 }
2912             }
2913         }
2914     }
2915 #   endif /* fstat+ustat+getmnt */
2916
2917 #   if !defined(FD_ON_NOSUID_CHECK_OKAY) && \
2918         defined(HAS_GETMNTENT)          && \
2919         defined(HAS_HASMNTOPT)          && \
2920         defined(MNTOPT_NOSUID)
2921 #   define FD_ON_NOSUID_CHECK_OKAY
2922     FILE                *mtab = fopen("/etc/mtab", "r");
2923     struct mntent       *entry;
2924     struct stat         stb, fsb;
2925
2926     if (mtab && (fstat(fd, &stb) == 0)) {
2927         while (entry = getmntent(mtab)) {
2928             if (stat(entry->mnt_dir, &fsb) == 0
2929                 && fsb.st_dev == stb.st_dev)
2930             {
2931                 /* found the filesystem */
2932                 check_okay = 1;
2933                 if (hasmntopt(entry, MNTOPT_NOSUID))
2934                     on_nosuid = 1;
2935                 break;
2936             } /* A single fs may well fail its stat(). */
2937         }
2938     }
2939     if (mtab)
2940         fclose(mtab);
2941 #   endif /* getmntent+hasmntopt */
2942
2943     if (!check_okay)
2944         Perl_croak(aTHX_ "Can't check filesystem of script \"%s\" for nosuid", PL_origfilename);
2945     return on_nosuid;
2946 }
2947 #endif /* IAMSUID */
2948
2949 STATIC void
2950 S_validate_suid(pTHX_ char *validarg, char *scriptname, int fdscript)
2951 {
2952 #ifdef IAMSUID
2953     int which;
2954 #endif
2955
2956     /* do we need to emulate setuid on scripts? */
2957
2958     /* This code is for those BSD systems that have setuid #! scripts disabled
2959      * in the kernel because of a security problem.  Merely defining DOSUID
2960      * in perl will not fix that problem, but if you have disabled setuid
2961      * scripts in the kernel, this will attempt to emulate setuid and setgid
2962      * on scripts that have those now-otherwise-useless bits set.  The setuid
2963      * root version must be called suidperl or sperlN.NNN.  If regular perl
2964      * discovers that it has opened a setuid script, it calls suidperl with
2965      * the same argv that it had.  If suidperl finds that the script it has
2966      * just opened is NOT setuid root, it sets the effective uid back to the
2967      * uid.  We don't just make perl setuid root because that loses the
2968      * effective uid we had before invoking perl, if it was different from the
2969      * uid.
2970      *
2971      * DOSUID must be defined in both perl and suidperl, and IAMSUID must
2972      * be defined in suidperl only.  suidperl must be setuid root.  The
2973      * Configure script will set this up for you if you want it.
2974      */
2975
2976 #ifdef DOSUID
2977     char *s, *s2;
2978
2979     if (PerlLIO_fstat(PerlIO_fileno(PL_rsfp),&PL_statbuf) < 0)  /* normal stat is insecure */
2980         Perl_croak(aTHX_ "Can't stat script \"%s\"",PL_origfilename);
2981     if (fdscript < 0 && PL_statbuf.st_mode & (S_ISUID|S_ISGID)) {
2982         I32 len;
2983         STRLEN n_a;
2984
2985 #ifdef IAMSUID
2986 #ifndef HAS_SETREUID
2987         /* On this access check to make sure the directories are readable,
2988          * there is actually a small window that the user could use to make
2989          * filename point to an accessible directory.  So there is a faint
2990          * chance that someone could execute a setuid script down in a
2991          * non-accessible directory.  I don't know what to do about that.
2992          * But I don't think it's too important.  The manual lies when
2993          * it says access() is useful in setuid programs.
2994          */
2995         if (PerlLIO_access(CopFILE(PL_curcop),1)) /*double check*/
2996             Perl_croak(aTHX_ "Permission denied");
2997 #else
2998         /* If we can swap euid and uid, then we can determine access rights
2999          * with a simple stat of the file, and then compare device and
3000          * inode to make sure we did stat() on the same file we opened.
3001          * Then we just have to make sure he or she can execute it.
3002          */
3003         {
3004             struct stat tmpstatbuf;
3005
3006             if (
3007 #ifdef HAS_SETREUID
3008                 setreuid(PL_euid,PL_uid) < 0
3009 #else
3010 # if HAS_SETRESUID
3011                 setresuid(PL_euid,PL_uid,(Uid_t)-1) < 0
3012 # endif
3013 #endif
3014                 || PerlProc_getuid() != PL_euid || PerlProc_geteuid() != PL_uid)
3015                 Perl_croak(aTHX_ "Can't swap uid and euid");    /* really paranoid */
3016             if (PerlLIO_stat(CopFILE(PL_curcop),&tmpstatbuf) < 0)
3017                 Perl_croak(aTHX_ "Permission denied");  /* testing full pathname here */
3018 #if defined(IAMSUID) && !defined(NO_NOSUID_CHECK)
3019             if (fd_on_nosuid_fs(PerlIO_fileno(PL_rsfp)))
3020                 Perl_croak(aTHX_ "Permission denied");
3021 #endif
3022             if (tmpstatbuf.st_dev != PL_statbuf.st_dev ||
3023                 tmpstatbuf.st_ino != PL_statbuf.st_ino) {
3024                 (void)PerlIO_close(PL_rsfp);
3025                 Perl_croak(aTHX_ "Permission denied\n");
3026             }
3027             if (
3028 #ifdef HAS_SETREUID
3029               setreuid(PL_uid,PL_euid) < 0
3030 #else
3031 # if defined(HAS_SETRESUID)
3032               setresuid(PL_uid,PL_euid,(Uid_t)-1) < 0
3033 # endif
3034 #endif
3035               || PerlProc_getuid() != PL_uid || PerlProc_geteuid() != PL_euid)
3036                 Perl_croak(aTHX_ "Can't reswap uid and euid");
3037             if (!cando(S_IXUSR,FALSE,&PL_statbuf))              /* can real uid exec? */
3038                 Perl_croak(aTHX_ "Permission denied\n");
3039         }
3040 #endif /* HAS_SETREUID */
3041 #endif /* IAMSUID */
3042
3043         if (!S_ISREG(PL_statbuf.st_mode))
3044             Perl_croak(aTHX_ "Permission denied");
3045         if (PL_statbuf.st_mode & S_IWOTH)
3046             Perl_croak(aTHX_ "Setuid/gid script is writable by world");
3047         PL_doswitches = FALSE;          /* -s is insecure in suid */
3048         CopLINE_inc(PL_curcop);
3049         if (sv_gets(PL_linestr, PL_rsfp, 0) == Nullch ||
3050           strnNE(SvPV(PL_linestr,n_a),"#!",2) ) /* required even on Sys V */
3051             Perl_croak(aTHX_ "No #! line");
3052         s = SvPV(PL_linestr,n_a)+2;
3053         if (*s == ' ') s++;
3054         while (!isSPACE(*s)) s++;
3055         for (s2 = s;  (s2 > SvPV(PL_linestr,n_a)+2 &&
3056                        (isDIGIT(s2[-1]) || strchr("._-", s2[-1])));  s2--) ;
3057         if (strnNE(s2-4,"perl",4) && strnNE(s-9,"perl",4))  /* sanity check */
3058             Perl_croak(aTHX_ "Not a perl script");
3059         while (*s == ' ' || *s == '\t') s++;
3060         /*
3061          * #! arg must be what we saw above.  They can invoke it by
3062          * mentioning suidperl explicitly, but they may not add any strange
3063          * arguments beyond what #! says if they do invoke suidperl that way.
3064          */
3065         len = strlen(validarg);
3066         if (strEQ(validarg," PHOOEY ") ||
3067             strnNE(s,validarg,len) || !isSPACE(s[len]))
3068             Perl_croak(aTHX_ "Args must match #! line");
3069
3070 #ifndef IAMSUID
3071         if (PL_euid != PL_uid && (PL_statbuf.st_mode & S_ISUID) &&
3072             PL_euid == PL_statbuf.st_uid)
3073             if (!PL_do_undump)
3074                 Perl_croak(aTHX_ "YOU HAVEN'T DISABLED SET-ID SCRIPTS IN THE KERNEL YET!\n\
3075 FIX YOUR KERNEL, PUT A C WRAPPER AROUND THIS SCRIPT, OR USE -u AND UNDUMP!\n");
3076 #endif /* IAMSUID */
3077
3078         if (PL_euid) {  /* oops, we're not the setuid root perl */
3079             (void)PerlIO_close(PL_rsfp);
3080 #ifndef IAMSUID
3081             /* try again */
3082             PerlProc_execv(Perl_form(aTHX_ "%s/sperl"PERL_FS_VER_FMT, BIN_EXP,
3083                                      (int)PERL_REVISION, (int)PERL_VERSION,
3084                                      (int)PERL_SUBVERSION), PL_origargv);
3085 #endif
3086             Perl_croak(aTHX_ "Can't do setuid\n");
3087         }
3088
3089         if (PL_statbuf.st_mode & S_ISGID && PL_statbuf.st_gid != PL_egid) {
3090 #ifdef HAS_SETEGID
3091             (void)setegid(PL_statbuf.st_gid);
3092 #else
3093 #ifdef HAS_SETREGID
3094            (void)setregid((Gid_t)-1,PL_statbuf.st_gid);
3095 #else
3096 #ifdef HAS_SETRESGID
3097            (void)setresgid((Gid_t)-1,PL_statbuf.st_gid,(Gid_t)-1);
3098 #else
3099             PerlProc_setgid(PL_statbuf.st_gid);
3100 #endif
3101 #endif
3102 #endif
3103             if (PerlProc_getegid() != PL_statbuf.st_gid)
3104                 Perl_croak(aTHX_ "Can't do setegid!\n");
3105         }
3106         if (PL_statbuf.st_mode & S_ISUID) {
3107             if (PL_statbuf.st_uid != PL_euid)
3108 #ifdef HAS_SETEUID
3109                 (void)seteuid(PL_statbuf.st_uid);       /* all that for this */
3110 #else
3111 #ifdef HAS_SETREUID
3112                 (void)setreuid((Uid_t)-1,PL_statbuf.st_uid);
3113 #else
3114 #ifdef HAS_SETRESUID
3115                 (void)setresuid((Uid_t)-1,PL_statbuf.st_uid,(Uid_t)-1);
3116 #else
3117                 PerlProc_setuid(PL_statbuf.st_uid);
3118 #endif
3119 #endif
3120 #endif
3121             if (PerlProc_geteuid() != PL_statbuf.st_uid)
3122                 Perl_croak(aTHX_ "Can't do seteuid!\n");
3123         }
3124         else if (PL_uid) {                      /* oops, mustn't run as root */
3125 #ifdef HAS_SETEUID
3126           (void)seteuid((Uid_t)PL_uid);
3127 #else
3128 #ifdef HAS_SETREUID
3129           (void)setreuid((Uid_t)-1,(Uid_t)PL_uid);
3130 #else
3131 #ifdef HAS_SETRESUID
3132           (void)setresuid((Uid_t)-1,(Uid_t)PL_uid,(Uid_t)-1);
3133 #else
3134           PerlProc_setuid((Uid_t)PL_uid);
3135 #endif
3136 #endif
3137 #endif
3138             if (PerlProc_geteuid() != PL_uid)
3139                 Perl_croak(aTHX_ "Can't do seteuid!\n");
3140         }
3141         init_ids();
3142         if (!cando(S_IXUSR,TRUE,&PL_statbuf))
3143             Perl_croak(aTHX_ "Permission denied\n");    /* they can't do this */
3144     }
3145 #ifdef IAMSUID
3146     else if (PL_preprocess)
3147         Perl_croak(aTHX_ "-P not allowed for setuid/setgid script\n");
3148     else if (fdscript >= 0)
3149         Perl_croak(aTHX_ "fd script not allowed in suidperl\n");
3150     else
3151         Perl_croak(aTHX_ "Script is not setuid/setgid in suidperl\n");
3152
3153     /* We absolutely must clear out any saved ids here, so we */
3154     /* exec the real perl, substituting fd script for scriptname. */
3155     /* (We pass script name as "subdir" of fd, which perl will grok.) */
3156     PerlIO_rewind(PL_rsfp);
3157     PerlLIO_lseek(PerlIO_fileno(PL_rsfp),(Off_t)0,0);  /* just in case rewind didn't */
3158     for (which = 1; PL_origargv[which] && PL_origargv[which] != scriptname; which++) ;
3159     if (!PL_origargv[which])
3160         Perl_croak(aTHX_ "Permission denied");
3161     PL_origargv[which] = savepv(Perl_form(aTHX_ "/dev/fd/%d/%s",
3162                                   PerlIO_fileno(PL_rsfp), PL_origargv[which]));
3163 #if defined(HAS_FCNTL) && defined(F_SETFD)
3164     fcntl(PerlIO_fileno(PL_rsfp),F_SETFD,0);    /* ensure no close-on-exec */
3165 #endif
3166     PerlProc_execv(Perl_form(aTHX_ "%s/perl"PERL_FS_VER_FMT, BIN_EXP,
3167                              (int)PERL_REVISION, (int)PERL_VERSION,
3168                              (int)PERL_SUBVERSION), PL_origargv);/* try again */
3169     Perl_croak(aTHX_ "Can't do setuid\n");
3170 #endif /* IAMSUID */
3171 #else /* !DOSUID */
3172     if (PL_euid != PL_uid || PL_egid != PL_gid) {       /* (suidperl doesn't exist, in fact) */
3173 #ifndef SETUID_SCRIPTS_ARE_SECURE_NOW
3174         PerlLIO_fstat(PerlIO_fileno(PL_rsfp),&PL_statbuf);      /* may be either wrapped or real suid */
3175         if ((PL_euid != PL_uid && PL_euid == PL_statbuf.st_uid && PL_statbuf.st_mode & S_ISUID)
3176             ||
3177             (PL_egid != PL_gid && PL_egid == PL_statbuf.st_gid && PL_statbuf.st_mode & S_ISGID)
3178            )
3179             if (!PL_do_undump)
3180                 Perl_croak(aTHX_ "YOU HAVEN'T DISABLED SET-ID SCRIPTS IN THE KERNEL YET!\n\
3181 FIX YOUR KERNEL, PUT A C WRAPPER AROUND THIS SCRIPT, OR USE -u AND UNDUMP!\n");
3182 #endif /* SETUID_SCRIPTS_ARE_SECURE_NOW */
3183         /* not set-id, must be wrapped */
3184     }
3185 #endif /* DOSUID */
3186 }
3187
3188 STATIC void
3189 S_find_beginning(pTHX)
3190 {
3191     register char *s, *s2;
3192
3193     /* skip forward in input to the real script? */
3194
3195     forbid_setid("-x");
3196 #ifdef MACOS_TRADITIONAL
3197     /* Since the Mac OS does not honor #! arguments for us, we do it ourselves */
3198
3199     while (PL_doextract || gMacPerl_AlwaysExtract) {
3200         if ((s = sv_gets(PL_linestr, PL_rsfp, 0)) == Nullch) {
3201             if (!gMacPerl_AlwaysExtract)
3202                 Perl_croak(aTHX_ "No Perl script found in input\n");
3203                 
3204             if (PL_doextract)                   /* require explicit override ? */
3205                 if (!OverrideExtract(PL_origfilename))
3206                     Perl_croak(aTHX_ "User aborted script\n");
3207                 else
3208                     PL_doextract = FALSE;
3209                 
3210             /* Pater peccavi, file does not have #! */
3211             PerlIO_rewind(PL_rsfp);
3212         
3213             break;
3214         }
3215 #else
3216     while (PL_doextract) {
3217         if ((s = sv_gets(PL_linestr, PL_rsfp, 0)) == Nullch)
3218             Perl_croak(aTHX_ "No Perl script found in input\n");
3219 #endif
3220         s2 = s;
3221         if (*s == '#' && s[1] == '!' && ((s = instr(s,"perl")) || (s = instr(s2,"PERL")))) {
3222             PerlIO_ungetc(PL_rsfp, '\n');               /* to keep line count right */
3223             PL_doextract = FALSE;
3224             while (*s && !(isSPACE (*s) || *s == '#')) s++;
3225             s2 = s;
3226             while (*s == ' ' || *s == '\t') s++;
3227             if (*s++ == '-') {
3228                 while (isDIGIT(s2[-1]) || strchr("-._", s2[-1])) s2--;
3229                 if (strnEQ(s2-4,"perl",4))
3230                     /*SUPPRESS 530*/
3231                     while ((s = moreswitches(s)))
3232                         ;
3233             }
3234 #ifdef MACOS_TRADITIONAL
3235             break;
3236 #endif
3237         }
3238     }
3239 }
3240
3241
3242 STATIC void
3243 S_init_ids(pTHX)
3244 {
3245     PL_uid = PerlProc_getuid();
3246     PL_euid = PerlProc_geteuid();
3247     PL_gid = PerlProc_getgid();
3248     PL_egid = PerlProc_getegid();
3249 #ifdef VMS
3250     PL_uid |= PL_gid << 16;
3251     PL_euid |= PL_egid << 16;
3252 #endif
3253     PL_tainting |= (PL_uid && (PL_euid != PL_uid || PL_egid != PL_gid));
3254 }
3255
3256 STATIC void
3257 S_forbid_setid(pTHX_ char *s)
3258 {
3259     if (PL_euid != PL_uid)
3260         Perl_croak(aTHX_ "No %s allowed while running setuid", s);
3261     if (PL_egid != PL_gid)
3262         Perl_croak(aTHX_ "No %s allowed while running setgid", s);
3263 }
3264
3265 void
3266 Perl_init_debugger(pTHX)
3267 {
3268     HV *ostash = PL_curstash;
3269
3270     PL_curstash = PL_debstash;
3271     PL_dbargs = GvAV(gv_AVadd((gv_fetchpv("args", GV_ADDMULTI, SVt_PVAV))));
3272     AvREAL_off(PL_dbargs);
3273     PL_DBgv = gv_fetchpv("DB", GV_ADDMULTI, SVt_PVGV);
3274     PL_DBline = gv_fetchpv("dbline", GV_ADDMULTI, SVt_PVAV);
3275     PL_DBsub = gv_HVadd(gv_fetchpv("sub", GV_ADDMULTI, SVt_PVHV));
3276     sv_upgrade(GvSV(PL_DBsub), SVt_IV); /* IVX accessed if PERLDB_SUB_NN */
3277     PL_DBsingle = GvSV((gv_fetchpv("single", GV_ADDMULTI, SVt_PV)));
3278     sv_setiv(PL_DBsingle, 0);
3279     PL_DBtrace = GvSV((gv_fetchpv("trace", GV_ADDMULTI, SVt_PV)));
3280     sv_setiv(PL_DBtrace, 0);
3281     PL_DBsignal = GvSV((gv_fetchpv("signal", GV_ADDMULTI, SVt_PV)));
3282     sv_setiv(PL_DBsignal, 0);
3283     PL_curstash = ostash;
3284 }
3285
3286 #ifndef STRESS_REALLOC
3287 #define REASONABLE(size) (size)
3288 #else
3289 #define REASONABLE(size) (1) /* unreasonable */
3290 #endif
3291
3292 void
3293 Perl_init_stacks(pTHX)
3294 {
3295     /* start with 128-item stack and 8K cxstack */
3296     PL_curstackinfo = new_stackinfo(REASONABLE(128),
3297                                  REASONABLE(8192/sizeof(PERL_CONTEXT) - 1));
3298     PL_curstackinfo->si_type = PERLSI_MAIN;
3299     PL_curstack = PL_curstackinfo->si_stack;
3300     PL_mainstack = PL_curstack;         /* remember in case we switch stacks */
3301
3302     PL_stack_base = AvARRAY(PL_curstack);
3303     PL_stack_sp = PL_stack_base;
3304     PL_stack_max = PL_stack_base + AvMAX(PL_curstack);
3305
3306     New(50,PL_tmps_stack,REASONABLE(128),SV*);
3307     PL_tmps_floor = -1;
3308     PL_tmps_ix = -1;
3309     PL_tmps_max = REASONABLE(128);
3310
3311     New(54,PL_markstack,REASONABLE(32),I32);
3312     PL_markstack_ptr = PL_markstack;
3313     PL_markstack_max = PL_markstack + REASONABLE(32);
3314
3315     SET_MARK_OFFSET;
3316
3317     New(54,PL_scopestack,REASONABLE(32),I32);
3318     PL_scopestack_ix = 0;
3319     PL_scopestack_max = REASONABLE(32);
3320
3321     New(54,PL_savestack,REASONABLE(128),ANY);
3322     PL_savestack_ix = 0;
3323     PL_savestack_max = REASONABLE(128);
3324
3325     New(54,PL_retstack,REASONABLE(16),OP*);
3326     PL_retstack_ix = 0;
3327     PL_retstack_max = REASONABLE(16);
3328 }
3329
3330 #undef REASONABLE
3331
3332 STATIC void
3333 S_nuke_stacks(pTHX)
3334 {
3335     while (PL_curstackinfo->si_next)
3336         PL_curstackinfo = PL_curstackinfo->si_next;
3337     while (PL_curstackinfo) {
3338         PERL_SI *p = PL_curstackinfo->si_prev;
3339         /* curstackinfo->si_stack got nuked by sv_free_arenas() */
3340         Safefree(PL_curstackinfo->si_cxstack);
3341         Safefree(PL_curstackinfo);
3342         PL_curstackinfo = p;
3343     }
3344     Safefree(PL_tmps_stack);
3345     Safefree(PL_markstack);
3346     Safefree(PL_scopestack);
3347     Safefree(PL_savestack);
3348     Safefree(PL_retstack);
3349 }
3350
3351 #ifndef PERL_OBJECT
3352 static PerlIO *tmpfp;  /* moved outside init_lexer() because of UNICOS bug */
3353 #endif
3354
3355 STATIC void
3356 S_init_lexer(pTHX)
3357 {
3358 #ifdef PERL_OBJECT
3359         PerlIO *tmpfp;
3360 #endif
3361     tmpfp = PL_rsfp;
3362     PL_rsfp = Nullfp;
3363     lex_start(PL_linestr);
3364     PL_rsfp = tmpfp;
3365     PL_subname = newSVpvn("main",4);
3366 }
3367
3368 STATIC void
3369 S_init_predump_symbols(pTHX)
3370 {
3371     GV *tmpgv;
3372     IO *io;
3373
3374     sv_setpvn(get_sv("\"", TRUE), " ", 1);
3375     PL_stdingv = gv_fetchpv("STDIN",TRUE, SVt_PVIO);
3376     GvMULTI_on(PL_stdingv);
3377     io = GvIOp(PL_stdingv);
3378     IoTYPE(io) = IoTYPE_RDONLY;
3379     IoIFP(io) = PerlIO_stdin();
3380     tmpgv = gv_fetchpv("stdin",TRUE, SVt_PV);
3381     GvMULTI_on(tmpgv);
3382     GvIOp(tmpgv) = (IO*)SvREFCNT_inc(io);
3383
3384     tmpgv = gv_fetchpv("STDOUT",TRUE, SVt_PVIO);
3385     GvMULTI_on(tmpgv);
3386     io = GvIOp(tmpgv);
3387     IoTYPE(io) = IoTYPE_WRONLY;
3388     IoOFP(io) = IoIFP(io) = PerlIO_stdout();
3389     setdefout(tmpgv);
3390     tmpgv = gv_fetchpv("stdout",TRUE, SVt_PV);
3391     GvMULTI_on(tmpgv);
3392     GvIOp(tmpgv) = (IO*)SvREFCNT_inc(io);
3393
3394     PL_stderrgv = gv_fetchpv("STDERR",TRUE, SVt_PVIO);
3395     GvMULTI_on(PL_stderrgv);
3396     io = GvIOp(PL_stderrgv);
3397     IoTYPE(io) = IoTYPE_WRONLY;
3398     IoOFP(io) = IoIFP(io) = PerlIO_stderr();
3399     tmpgv = gv_fetchpv("stderr",TRUE, SVt_PV);
3400     GvMULTI_on(tmpgv);
3401     GvIOp(tmpgv) = (IO*)SvREFCNT_inc(io);
3402
3403     PL_statname = NEWSV(66,0);          /* last filename we did stat on */
3404
3405     if (PL_osname)
3406         Safefree(PL_osname);
3407     PL_osname = savepv(OSNAME);
3408 }
3409
3410 STATIC void
3411 S_init_postdump_symbols(pTHX_ register int argc, register char **argv, register char **env)
3412 {
3413     char *s;
3414     SV *sv;
3415     GV* tmpgv;
3416 #ifdef NEED_ENVIRON_DUP_FOR_MODIFY
3417     char **dup_env_base = 0;
3418     int dup_env_count = 0;
3419 #endif
3420
3421     argc--,argv++;      /* skip name of script */
3422     if (PL_doswitches) {
3423         for (; argc > 0 && **argv == '-'; argc--,argv++) {
3424             if (!argv[0][1])
3425                 break;
3426             if (argv[0][1] == '-' && !argv[0][2]) {
3427                 argc--,argv++;
3428                 break;
3429             }
3430             if ((s = strchr(argv[0], '='))) {
3431                 *s++ = '\0';
3432                 sv_setpv(GvSV(gv_fetchpv(argv[0]+1,TRUE, SVt_PV)),s);
3433             }
3434             else
3435                 sv_setiv(GvSV(gv_fetchpv(argv[0]+1,TRUE, SVt_PV)),1);
3436         }
3437     }
3438     PL_toptarget = NEWSV(0,0);
3439     sv_upgrade(PL_toptarget, SVt_PVFM);
3440     sv_setpvn(PL_toptarget, "", 0);
3441     PL_bodytarget = NEWSV(0,0);
3442     sv_upgrade(PL_bodytarget, SVt_PVFM);
3443     sv_setpvn(PL_bodytarget, "", 0);
3444     PL_formtarget = PL_bodytarget;
3445
3446     TAINT;
3447     if ((tmpgv = gv_fetchpv("0",TRUE, SVt_PV))) {
3448 #ifdef MACOS_TRADITIONAL
3449         /* $0 is not majick on a Mac */
3450         sv_setpv(GvSV(tmpgv),MacPerl_MPWFileName(PL_origfilename));
3451 #else
3452         sv_setpv(GvSV(tmpgv),PL_origfilename);
3453         magicname("0", "0", 1);
3454 #endif
3455     }
3456     if ((tmpgv = gv_fetchpv("\030",TRUE, SVt_PV)))
3457 #ifdef OS2
3458         sv_setpv(GvSV(tmpgv), os2_execname(aTHX));
3459 #else
3460         sv_setpv(GvSV(tmpgv),PL_origargv[0]);
3461 #endif
3462     if ((PL_argvgv = gv_fetchpv("ARGV",TRUE, SVt_PVAV))) {
3463         GvMULTI_on(PL_argvgv);
3464         (void)gv_AVadd(PL_argvgv);
3465         av_clear(GvAVn(PL_argvgv));
3466         for (; argc > 0; argc--,argv++) {
3467             SV *sv = newSVpv(argv[0],0);
3468             av_push(GvAVn(PL_argvgv),sv);
3469             if (PL_widesyscalls)
3470                 (void)sv_utf8_decode(sv);
3471         }
3472     }
3473     if ((PL_envgv = gv_fetchpv("ENV",TRUE, SVt_PVHV))) {
3474         HV *hv;
3475         GvMULTI_on(PL_envgv);
3476         hv = GvHVn(PL_envgv);
3477         hv_magic(hv, Nullgv, PERL_MAGIC_env);
3478 #ifdef USE_ENVIRON_ARRAY
3479         /* Note that if the supplied env parameter is actually a copy
3480            of the global environ then it may now point to free'd memory
3481            if the environment has been modified since. To avoid this
3482            problem we treat env==NULL as meaning 'use the default'
3483         */
3484         if (!env)
3485             env = environ;
3486         if (env != environ)
3487             environ[0] = Nullch;
3488 #ifdef NEED_ENVIRON_DUP_FOR_MODIFY
3489         {
3490             char **env_base;
3491             for (env_base = env; *env; env++)
3492                 dup_env_count++;
3493             if ((dup_env_base = (char **)
3494                  safesysmalloc( sizeof(char *) * (dup_env_count+1) ))) {
3495                 char **dup_env;
3496                 for (env = env_base, dup_env = dup_env_base;
3497                      *env;
3498                      env++, dup_env++) {
3499                     /* With environ one needs to use safesysmalloc(). */
3500                     *dup_env = safesysmalloc(strlen(*env) + 1);
3501                     (void)strcpy(*dup_env, *env);
3502                 }
3503                 *dup_env = Nullch;
3504                 env = dup_env_base;
3505             } /* else what? */
3506         }
3507 #endif /* NEED_ENVIRON_DUP_FOR_MODIFY */
3508         if (env)
3509           for (; *env; env++) {
3510             if (!(s = strchr(*env,'=')))
3511                 continue;
3512             *s++ = '\0';
3513 #if defined(MSDOS)
3514             (void)strupr(*env);
3515 #endif
3516             sv = newSVpv(s--,0);
3517             (void)hv_store(hv, *env, s - *env, sv, 0);
3518             *s = '=';
3519           }
3520 #ifdef NEED_ENVIRON_DUP_FOR_MODIFY
3521         if (dup_env_base) {
3522             char **dup_env;
3523             for (dup_env = dup_env_base; *dup_env; dup_env++)
3524                 safesysfree(*dup_env);
3525             safesysfree(dup_env_base);
3526         }
3527 #endif /* NEED_ENVIRON_DUP_FOR_MODIFY */
3528 #endif /* USE_ENVIRON_ARRAY */
3529     }
3530     TAINT_NOT;
3531     if ((tmpgv = gv_fetchpv("$",TRUE, SVt_PV)))
3532         sv_setiv(GvSV(tmpgv), (IV)PerlProc_getpid());
3533 }
3534
3535 STATIC void
3536 S_init_perllib(pTHX)
3537 {
3538     char *s;
3539     if (!PL_tainting) {
3540 #ifndef VMS
3541         s = PerlEnv_getenv("PERL5LIB");
3542         if (s)
3543             incpush(s, TRUE, TRUE);
3544         else
3545             incpush(PerlEnv_getenv("PERLLIB"), FALSE, FALSE);
3546 #else /* VMS */
3547         /* Treat PERL5?LIB as a possible search list logical name -- the
3548          * "natural" VMS idiom for a Unix path string.  We allow each
3549          * element to be a set of |-separated directories for compatibility.
3550          */
3551         char buf[256];
3552         int idx = 0;
3553         if (my_trnlnm("PERL5LIB",buf,0))
3554             do { incpush(buf,TRUE,TRUE); } while (my_trnlnm("PERL5LIB",buf,++idx));
3555         else
3556             while (my_trnlnm("PERLLIB",buf,idx++)) incpush(buf,FALSE,FALSE);
3557 #endif /* VMS */
3558     }
3559
3560 /* Use the ~-expanded versions of APPLLIB (undocumented),
3561     ARCHLIB PRIVLIB SITEARCH SITELIB VENDORARCH and VENDORLIB
3562 */
3563 #ifdef APPLLIB_EXP
3564     incpush(APPLLIB_EXP, TRUE, TRUE);
3565 #endif
3566
3567 #ifdef ARCHLIB_EXP
3568     incpush(ARCHLIB_EXP, FALSE, FALSE);
3569 #endif
3570 #ifdef MACOS_TRADITIONAL
3571     {
3572         struct stat tmpstatbuf;
3573         SV * privdir = NEWSV(55, 0);
3574         char * macperl = PerlEnv_getenv("MACPERL");
3575         
3576         if (!macperl)
3577             macperl = "";
3578         
3579         Perl_sv_setpvf(aTHX_ privdir, "%slib:", macperl);
3580         if (PerlLIO_stat(SvPVX(privdir), &tmpstatbuf) >= 0 && S_ISDIR(tmpstatbuf.st_mode))
3581             incpush(SvPVX(privdir), TRUE, FALSE);
3582         Perl_sv_setpvf(aTHX_ privdir, "%ssite_perl:", macperl);
3583         if (PerlLIO_stat(SvPVX(privdir), &tmpstatbuf) >= 0 && S_ISDIR(tmpstatbuf.st_mode))
3584             incpush(SvPVX(privdir), TRUE, FALSE);
3585         
3586         SvREFCNT_dec(privdir);
3587     }
3588     if (!PL_tainting)
3589         incpush(":", FALSE, FALSE);
3590 #else
3591 #ifndef PRIVLIB_EXP
3592 #  define PRIVLIB_EXP "/usr/local/lib/perl5:/usr/local/lib/perl"
3593 #endif
3594 #if defined(WIN32)
3595     incpush(PRIVLIB_EXP, TRUE, FALSE);
3596 #else
3597     incpush(PRIVLIB_EXP, FALSE, FALSE);
3598 #endif
3599
3600 #ifdef SITEARCH_EXP
3601     /* sitearch is always relative to sitelib on Windows for
3602      * DLL-based path intuition to work correctly */
3603 #  if !defined(WIN32)
3604     incpush(SITEARCH_EXP, FALSE, FALSE);
3605 #  endif
3606 #endif
3607
3608 #ifdef SITELIB_EXP
3609 #  if defined(WIN32)
3610     incpush(SITELIB_EXP, TRUE, FALSE);  /* this picks up sitearch as well */
3611 #  else
3612     incpush(SITELIB_EXP, FALSE, FALSE);
3613 #  endif
3614 #endif
3615
3616 #ifdef SITELIB_STEM /* Search for version-specific dirs below here */
3617     incpush(SITELIB_STEM, FALSE, TRUE);
3618 #endif
3619
3620 #ifdef PERL_VENDORARCH_EXP
3621     /* vendorarch is always relative to vendorlib on Windows for
3622      * DLL-based path intuition to work correctly */
3623 #  if !defined(WIN32)
3624     incpush(PERL_VENDORARCH_EXP, FALSE, FALSE);
3625 #  endif
3626 #endif
3627
3628 #ifdef PERL_VENDORLIB_EXP
3629 #  if defined(WIN32)
3630     incpush(PERL_VENDORLIB_EXP, TRUE, FALSE);   /* this picks up vendorarch as well */
3631 #  else
3632     incpush(PERL_VENDORLIB_EXP, FALSE, FALSE);
3633 #  endif
3634 #endif
3635
3636 #ifdef PERL_VENDORLIB_STEM /* Search for version-specific dirs below here */
3637     incpush(PERL_VENDORLIB_STEM, FALSE, TRUE);
3638 #endif
3639
3640 #ifdef PERL_OTHERLIBDIRS
3641     incpush(PERL_OTHERLIBDIRS, TRUE, TRUE);
3642 #endif
3643
3644     if (!PL_tainting)
3645         incpush(".", FALSE, FALSE);
3646 #endif /* MACOS_TRADITIONAL */
3647 }
3648
3649 #if defined(DOSISH) || defined(EPOC)
3650 #    define PERLLIB_SEP ';'
3651 #else
3652 #  if defined(VMS)
3653 #    define PERLLIB_SEP '|'
3654 #  else
3655 #    if defined(MACOS_TRADITIONAL)
3656 #      define PERLLIB_SEP ','
3657 #    else
3658 #      define PERLLIB_SEP ':'
3659 #    endif
3660 #  endif
3661 #endif
3662 #ifndef PERLLIB_MANGLE
3663 #  define PERLLIB_MANGLE(s,n) (s)
3664 #endif
3665
3666 STATIC void
3667 S_incpush(pTHX_ char *p, int addsubdirs, int addoldvers)
3668 {
3669     SV *subdir = Nullsv;
3670
3671     if (!p || !*p)
3672         return;
3673
3674     if (addsubdirs || addoldvers) {
3675         subdir = sv_newmortal();
3676     }
3677
3678     /* Break at all separators */
3679     while (p && *p) {
3680         SV *libdir = NEWSV(55,0);
3681         char *s;
3682
3683         /* skip any consecutive separators */
3684         while ( *p == PERLLIB_SEP ) {
3685             /* Uncomment the next line for PATH semantics */
3686             /* av_push(GvAVn(PL_incgv), newSVpvn(".", 1)); */
3687             p++;
3688         }
3689
3690         if ( (s = strchr(p, PERLLIB_SEP)) != Nullch ) {
3691             sv_setpvn(libdir, PERLLIB_MANGLE(p, (STRLEN)(s - p)),
3692                       (STRLEN)(s - p));
3693             p = s + 1;
3694         }
3695         else {
3696             sv_setpv(libdir, PERLLIB_MANGLE(p, 0));
3697             p = Nullch; /* break out */
3698         }
3699 #ifdef MACOS_TRADITIONAL
3700         if (!strchr(SvPVX(libdir), ':'))
3701             sv_insert(libdir, 0, 0, ":", 1);
3702         if (SvPVX(libdir)[SvCUR(libdir)-1] != ':')
3703             sv_catpv(libdir, ":");
3704 #endif
3705
3706         /*
3707          * BEFORE pushing libdir onto @INC we may first push version- and
3708          * archname-specific sub-directories.
3709          */
3710         if (addsubdirs || addoldvers) {
3711 #ifdef PERL_INC_VERSION_LIST
3712             /* Configure terminates PERL_INC_VERSION_LIST with a NULL */
3713             const char *incverlist[] = { PERL_INC_VERSION_LIST };
3714             const char **incver;
3715 #endif
3716             struct stat tmpstatbuf;
3717 #ifdef VMS
3718             char *unix;
3719             STRLEN len;
3720
3721             if ((unix = tounixspec_ts(SvPV(libdir,len),Nullch)) != Nullch) {
3722                 len = strlen(unix);
3723                 while (unix[len-1] == '/') len--;  /* Cosmetic */
3724                 sv_usepvn(libdir,unix,len);
3725             }
3726             else
3727                 PerlIO_printf(Perl_error_log,
3728                               "Failed to unixify @INC element \"%s\"\n",
3729                               SvPV(libdir,len));
3730 #endif
3731             if (addsubdirs) {
3732 #ifdef MACOS_TRADITIONAL
3733 #define PERL_AV_SUFFIX_FMT      ""
3734 #define PERL_ARCH_FMT           "%s:"
3735 #define PERL_ARCH_FMT_PATH      PERL_FS_VER_FMT PERL_AV_SUFFIX_FMT
3736 #else
3737 #define PERL_AV_SUFFIX_FMT      "/"
3738 #define PERL_ARCH_FMT           "/%s"
3739 #define PERL_ARCH_FMT_PATH      PERL_AV_SUFFIX_FMT PERL_FS_VER_FMT
3740 #endif
3741                 /* .../version/archname if -d .../version/archname */
3742                 Perl_sv_setpvf(aTHX_ subdir, "%"SVf PERL_ARCH_FMT_PATH PERL_ARCH_FMT,
3743                                 libdir,
3744                                (int)PERL_REVISION, (int)PERL_VERSION,
3745                                (int)PERL_SUBVERSION, ARCHNAME);
3746                 if (PerlLIO_stat(SvPVX(subdir), &tmpstatbuf) >= 0 &&
3747                       S_ISDIR(tmpstatbuf.st_mode))
3748                     av_push(GvAVn(PL_incgv), newSVsv(subdir));
3749
3750                 /* .../version if -d .../version */
3751                 Perl_sv_setpvf(aTHX_ subdir, "%"SVf PERL_ARCH_FMT_PATH, libdir,
3752                                (int)PERL_REVISION, (int)PERL_VERSION,
3753                                (int)PERL_SUBVERSION);
3754                 if (PerlLIO_stat(SvPVX(subdir), &tmpstatbuf) >= 0 &&
3755                       S_ISDIR(tmpstatbuf.st_mode))
3756                     av_push(GvAVn(PL_incgv), newSVsv(subdir));
3757
3758                 /* .../archname if -d .../archname */
3759                 Perl_sv_setpvf(aTHX_ subdir, "%"SVf PERL_ARCH_FMT, libdir, ARCHNAME);
3760                 if (PerlLIO_stat(SvPVX(subdir), &tmpstatbuf) >= 0 &&
3761                       S_ISDIR(tmpstatbuf.st_mode))
3762                     av_push(GvAVn(PL_incgv), newSVsv(subdir));
3763             }
3764
3765 #ifdef PERL_INC_VERSION_LIST
3766             if (addoldvers) {
3767                 for (incver = incverlist; *incver; incver++) {
3768                     /* .../xxx if -d .../xxx */
3769                     Perl_sv_setpvf(aTHX_ subdir, "%"SVf PERL_ARCH_FMT, libdir, *incver);
3770                     if (PerlLIO_stat(SvPVX(subdir), &tmpstatbuf) >= 0 &&
3771                           S_ISDIR(tmpstatbuf.st_mode))
3772                         av_push(GvAVn(PL_incgv), newSVsv(subdir));
3773                 }
3774             }
3775 #endif
3776         }
3777
3778         /* finally push this lib directory on the end of @INC */
3779         av_push(GvAVn(PL_incgv), libdir);
3780     }
3781 }
3782
3783 #ifdef USE_THREADS
3784 STATIC struct perl_thread *
3785 S_init_main_thread(pTHX)
3786 {
3787 #if !defined(PERL_IMPLICIT_CONTEXT)
3788     struct perl_thread *thr;
3789 #endif
3790     XPV *xpv;
3791
3792     Newz(53, thr, 1, struct perl_thread);
3793     PL_curcop = &PL_compiling;
3794     thr->interp = PERL_GET_INTERP;
3795     thr->cvcache = newHV();
3796     thr->threadsv = newAV();
3797     /* thr->threadsvp is set when find_threadsv is called */
3798     thr->specific = newAV();
3799     thr->flags = THRf_R_JOINABLE;
3800     MUTEX_INIT(&thr->mutex);
3801     /* Handcraft thrsv similarly to mess_sv */
3802     New(53, PL_thrsv, 1, SV);
3803     Newz(53, xpv, 1, XPV);
3804     SvFLAGS(PL_thrsv) = SVt_PV;
3805     SvANY(PL_thrsv) = (void*)xpv;
3806     SvREFCNT(PL_thrsv) = 1 << 30;       /* practically infinite */
3807     SvPVX(PL_thrsv) = (char*)thr;
3808     SvCUR_set(PL_thrsv, sizeof(thr));
3809     SvLEN_set(PL_thrsv, sizeof(thr));
3810     *SvEND(PL_thrsv) = '\0';    /* in the trailing_nul field */
3811     thr->oursv = PL_thrsv;
3812     PL_chopset = " \n-";
3813     PL_dumpindent = 4;
3814
3815     MUTEX_LOCK(&PL_threads_mutex);
3816     PL_nthreads++;
3817     thr->tid = 0;
3818     thr->next = thr;
3819     thr->prev = thr;
3820     thr->thr_done = 0;
3821     MUTEX_UNLOCK(&PL_threads_mutex);
3822
3823 #ifdef HAVE_THREAD_INTERN
3824     Perl_init_thread_intern(thr);
3825 #endif
3826
3827 #ifdef SET_THREAD_SELF
3828     SET_THREAD_SELF(thr);
3829 #else
3830     thr->self = pthread_self();
3831 #endif /* SET_THREAD_SELF */
3832     PERL_SET_THX(thr);
3833
3834     /*
3835      * These must come after the thread self setting
3836      * because sv_setpvn does SvTAINT and the taint
3837      * fields thread selfness being set.
3838      */
3839     PL_toptarget = NEWSV(0,0);
3840     sv_upgrade(PL_toptarget, SVt_PVFM);
3841     sv_setpvn(PL_toptarget, "", 0);
3842     PL_bodytarget = NEWSV(0,0);
3843     sv_upgrade(PL_bodytarget, SVt_PVFM);
3844     sv_setpvn(PL_bodytarget, "", 0);
3845     PL_formtarget = PL_bodytarget;
3846     thr->errsv = newSVpvn("", 0);
3847     (void) find_threadsv("@");  /* Ensure $@ is initialised early */
3848
3849     PL_maxscream = -1;
3850     PL_peepp = MEMBER_TO_FPTR(Perl_peep);
3851     PL_regcompp = MEMBER_TO_FPTR(Perl_pregcomp);
3852     PL_regexecp = MEMBER_TO_FPTR(Perl_regexec_flags);
3853     PL_regint_start = MEMBER_TO_FPTR(Perl_re_intuit_start);
3854     PL_regint_string = MEMBER_TO_FPTR(Perl_re_intuit_string);
3855     PL_regfree = MEMBER_TO_FPTR(Perl_pregfree);
3856     PL_regindent = 0;
3857     PL_reginterp_cnt = 0;
3858
3859     return thr;
3860 }
3861 #endif /* USE_THREADS */
3862
3863 void
3864 Perl_call_list(pTHX_ I32 oldscope, AV *paramList)
3865 {
3866     SV *atsv;
3867     line_t oldline = CopLINE(PL_curcop);
3868     CV *cv;
3869     STRLEN len;
3870     int ret;
3871     dJMPENV;
3872
3873     while (AvFILL(paramList) >= 0) {
3874         cv = (CV*)av_shift(paramList);
3875         if (PL_savebegin && (paramList == PL_beginav)) {
3876                 /* save PL_beginav for compiler */
3877             if (! PL_beginav_save)
3878                 PL_beginav_save = newAV();
3879             av_push(PL_beginav_save, (SV*)cv);
3880         } else {
3881             SAVEFREESV(cv);
3882         }
3883 #ifdef PERL_FLEXIBLE_EXCEPTIONS
3884         CALLPROTECT(aTHX_ pcur_env, &ret, MEMBER_TO_FPTR(S_vcall_list_body), cv);
3885 #else
3886         JMPENV_PUSH(ret);
3887 #endif
3888         switch (ret) {
3889         case 0:
3890 #ifndef PERL_FLEXIBLE_EXCEPTIONS
3891             call_list_body(cv);
3892 #endif
3893             atsv = ERRSV;
3894             (void)SvPV(atsv, len);
3895             if (len) {
3896                 STRLEN n_a;
3897                 PL_curcop = &PL_compiling;
3898                 CopLINE_set(PL_curcop, oldline);
3899                 if (paramList == PL_beginav)
3900                     sv_catpv(atsv, "BEGIN failed--compilation aborted");
3901                 else
3902                     Perl_sv_catpvf(aTHX_ atsv,
3903                                    "%s failed--call queue aborted",
3904                                    paramList == PL_checkav ? "CHECK"
3905                                    : paramList == PL_initav ? "INIT"
3906                                    : "END");
3907                 while (PL_scopestack_ix > oldscope)
3908                     LEAVE;
3909                 JMPENV_POP;
3910                 Perl_croak(aTHX_ "%s", SvPVx(atsv, n_a));
3911             }
3912             break;
3913         case 1:
3914             STATUS_ALL_FAILURE;
3915             /* FALL THROUGH */
3916         case 2:
3917             /* my_exit() was called */
3918             while (PL_scopestack_ix > oldscope)
3919                 LEAVE;
3920             FREETMPS;
3921             PL_curstash = PL_defstash;
3922             PL_curcop = &PL_compiling;
3923             CopLINE_set(PL_curcop, oldline);
3924             JMPENV_POP;
3925             if (PL_statusvalue && !(PL_exit_flags & PERL_EXIT_EXPECTED)) {
3926                 if (paramList == PL_beginav)
3927                     Perl_croak(aTHX_ "BEGIN failed--compilation aborted");
3928                 else
3929                     Perl_croak(aTHX_ "%s failed--call queue aborted",
3930                                paramList == PL_checkav ? "CHECK"
3931                                : paramList == PL_initav ? "INIT"
3932                                : "END");
3933             }
3934             my_exit_jump();
3935             /* NOTREACHED */
3936         case 3:
3937             if (PL_restartop) {
3938                 PL_curcop = &PL_compiling;
3939                 CopLINE_set(PL_curcop, oldline);
3940                 JMPENV_JUMP(3);
3941             }
3942             PerlIO_printf(Perl_error_log, "panic: restartop\n");
3943             FREETMPS;
3944             break;
3945         }
3946         JMPENV_POP;
3947     }
3948 }
3949
3950 #ifdef PERL_FLEXIBLE_EXCEPTIONS
3951 STATIC void *
3952 S_vcall_list_body(pTHX_ va_list args)
3953 {
3954     CV *cv = va_arg(args, CV*);
3955     return call_list_body(cv);
3956 }
3957 #endif
3958
3959 STATIC void *
3960 S_call_list_body(pTHX_ CV *cv)
3961 {
3962     PUSHMARK(PL_stack_sp);
3963     call_sv((SV*)cv, G_EVAL|G_DISCARD);
3964     return NULL;
3965 }
3966
3967 void
3968 Perl_my_exit(pTHX_ U32 status)
3969 {
3970     DEBUG_S(PerlIO_printf(Perl_debug_log, "my_exit: thread %p, status %lu\n",
3971                           thr, (unsigned long) status));
3972     switch (status) {
3973     case 0:
3974         STATUS_ALL_SUCCESS;
3975         break;
3976     case 1:
3977         STATUS_ALL_FAILURE;
3978         break;
3979     default:
3980         STATUS_NATIVE_SET(status);
3981         break;
3982     }
3983     my_exit_jump();
3984 }
3985
3986 void
3987 Perl_my_failure_exit(pTHX)
3988 {
3989 #ifdef VMS
3990     if (vaxc$errno & 1) {
3991         if (STATUS_NATIVE & 1)          /* fortuitiously includes "-1" */
3992             STATUS_NATIVE_SET(44);
3993     }
3994     else {
3995         if (!vaxc$errno && errno)       /* unlikely */
3996             STATUS_NATIVE_SET(44);
3997         else
3998             STATUS_NATIVE_SET(vaxc$errno);
3999     }
4000 #else
4001     int exitstatus;
4002     if (errno & 255)
4003         STATUS_POSIX_SET(errno);
4004     else {
4005         exitstatus = STATUS_POSIX >> 8;
4006         if (exitstatus & 255)
4007             STATUS_POSIX_SET(exitstatus);
4008         else
4009             STATUS_POSIX_SET(255);
4010     }
4011 #endif
4012     my_exit_jump();
4013 }
4014
4015 STATIC void
4016 S_my_exit_jump(pTHX)
4017 {
4018     register PERL_CONTEXT *cx;
4019     I32 gimme;
4020     SV **newsp;
4021
4022     if (PL_e_script) {
4023         SvREFCNT_dec(PL_e_script);
4024         PL_e_script = Nullsv;
4025     }
4026
4027     POPSTACK_TO(PL_mainstack);
4028     if (cxstack_ix >= 0) {
4029         if (cxstack_ix > 0)
4030             dounwind(0);
4031         POPBLOCK(cx,PL_curpm);
4032         LEAVE;
4033     }
4034
4035     JMPENV_JUMP(2);
4036 }
4037
4038 #ifdef PERL_OBJECT
4039 #include "XSUB.h"
4040 #endif
4041
4042 static I32
4043 read_e_script(pTHXo_ int idx, SV *buf_sv, int maxlen)
4044 {
4045     char *p, *nl;
4046     p  = SvPVX(PL_e_script);
4047     nl = strchr(p, '\n');
4048     nl = (nl) ? nl+1 : SvEND(PL_e_script);
4049     if (nl-p == 0) {
4050         filter_del(read_e_script);
4051         return 0;
4052     }
4053     sv_catpvn(buf_sv, p, nl-p);
4054     sv_chop(PL_e_script, nl);
4055     return 1;
4056 }