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