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