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