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