3 * Copyright (c) 1987-1998 Larry Wall
5 * You may distribute under the terms of either the GNU General Public
6 * License or the Artistic License, as specified in the README file.
11 * "A ship then new they built for him/of mithril and of elven glass" --Bilbo
16 #include "patchlevel.h"
18 /* XXX If this causes problems, set i_unistd=undef in the hint file. */
23 #if !defined(STANDARD_C) && !defined(HAS_GETENV_PROTOTYPE)
24 char *getenv _((char *)); /* Usually in <stdlib.h> */
34 dEXTCONST char rcsid[] = "perl.c\nPatch level: ###\n";
42 #ifdef SETUID_SCRIPTS_ARE_SECURE_NOW
52 curcop = &compiling; \
59 laststype = OP_STAT; \
61 maxsysfd = MAXSYSFD; \
68 laststype = OP_STAT; \
73 static I32 read_e_script _((CPerlObj* pPerl, int idx, SV *buf_sv, int maxlen));
75 static void find_beginning _((void));
76 static void forbid_setid _((char *));
77 static void incpush _((char *, int));
78 static void init_ids _((void));
79 static void init_debugger _((void));
80 static void init_lexer _((void));
81 static void init_main_stash _((void));
83 static struct perl_thread * init_main_thread _((void));
84 #endif /* USE_THREADS */
85 static void init_perllib _((void));
86 static void init_postdump_symbols _((int, char **, char **));
87 static void init_predump_symbols _((void));
88 static void my_exit_jump _((void)) __attribute__((noreturn));
89 static void nuke_stacks _((void));
90 static void open_script _((char *, bool, SV *, int *fd));
91 static void usage _((char *));
92 static void validate_suid _((char *, char*, int));
93 static I32 read_e_script _((int idx, SV *buf_sv, int maxlen));
97 CPerlObj* perl_alloc(IPerlMem* ipM, IPerlEnv* ipE, IPerlStdIO* ipStd,
98 IPerlLIO* ipLIO, IPerlDir* ipD, IPerlSock* ipS, IPerlProc* ipP)
100 CPerlObj* pPerl = new(ipM) CPerlObj(ipM, ipE, ipStd, ipLIO, ipD, ipS, ipP);
110 PerlInterpreter *sv_interp;
113 New(53, sv_interp, 1, PerlInterpreter);
116 #endif /* PERL_OBJECT */
120 CPerlObj::perl_construct(void)
122 perl_construct(register PerlInterpreter *sv_interp)
128 struct perl_thread *thr;
129 #endif /* FAKE_THREADS */
130 #endif /* USE_THREADS */
133 if (!(curinterp = sv_interp))
138 Zero(sv_interp, 1, PerlInterpreter);
141 /* Init the real globals (and main thread)? */
146 #ifdef ALLOC_THREAD_KEY
149 if (pthread_key_create(&thr_key, 0))
150 croak("panic: pthread_key_create");
152 MUTEX_INIT(&sv_mutex);
154 * Safe to use basic SV functions from now on (though
155 * not things like mortals or tainting yet).
157 MUTEX_INIT(&eval_mutex);
158 COND_INIT(&eval_cond);
159 MUTEX_INIT(&threads_mutex);
160 COND_INIT(&nthreads_cond);
161 #ifdef EMULATE_ATOMIC_REFCOUNTS
162 MUTEX_INIT(&svref_mutex);
163 #endif /* EMULATE_ATOMIC_REFCOUNTS */
165 thr = init_main_thread();
166 #endif /* USE_THREADS */
168 linestr = NEWSV(65,80);
169 sv_upgrade(linestr,SVt_PVIV);
171 if (!SvREADONLY(&sv_undef)) {
172 SvREADONLY_on(&sv_undef);
176 SvREADONLY_on(&sv_no);
178 sv_setpv(&sv_yes,Yes);
180 SvREADONLY_on(&sv_yes);
183 nrs = newSVpv("\n", 1);
184 rs = SvREFCNT_inc(nrs);
188 /* sighandlerp = sighandler; */
190 sighandlerp = sighandler;
196 * There is no way we can refer to them from Perl so close them to save
197 * space. The other alternative would be to provide STDAUX and STDPRN
200 (void)fclose(stdaux);
201 (void)fclose(stdprn);
208 perl_destruct_level = 1;
210 if(perl_destruct_level > 0)
215 lex_state = LEX_NOTPARSING;
217 start_env.je_prev = NULL;
218 start_env.je_ret = -1;
219 start_env.je_mustcatch = TRUE;
220 top_env = &start_env;
223 SET_NUMERIC_STANDARD();
224 #if defined(SUBVERSION) && SUBVERSION > 0
225 sprintf(patchlevel, "%7.5f", (double) 5
226 + ((double) PATCHLEVEL / (double) 1000)
227 + ((double) SUBVERSION / (double) 100000));
229 sprintf(patchlevel, "%5.3f", (double) 5 +
230 ((double) PATCHLEVEL / (double) 1000));
233 #if defined(LOCAL_PATCH_COUNT)
234 localpatches = local_patches; /* For possible -v */
237 PerlIO_init(); /* Hook to IO system */
239 fdpid = newAV(); /* for remembering popen pids by fd */
240 modglobal = newHV(); /* pointers to per-interpreter module globals */
243 New(51,debname,128,char);
244 New(52,debdelim,128,char);
252 CPerlObj::perl_destruct(void)
254 perl_destruct(register PerlInterpreter *sv_interp)
258 int destruct_level; /* 0=none, 1=full, 2=full with checks */
263 #endif /* USE_THREADS */
266 if (!(curinterp = sv_interp))
272 /* Pass 1 on any remaining threads: detach joinables, join zombies */
274 MUTEX_LOCK(&threads_mutex);
275 DEBUG_L(PerlIO_printf(PerlIO_stderr(),
276 "perl_destruct: waiting for %d threads...\n",
278 for (t = thr->next; t != thr; t = t->next) {
279 MUTEX_LOCK(&t->mutex);
280 switch (ThrSTATE(t)) {
283 DEBUG_L(PerlIO_printf(PerlIO_stderr(),
284 "perl_destruct: joining zombie %p\n", t));
285 ThrSETSTATE(t, THRf_DEAD);
286 MUTEX_UNLOCK(&t->mutex);
289 * The SvREFCNT_dec below may take a long time (e.g. av
290 * may contain an object scalar whose destructor gets
291 * called) so we have to unlock threads_mutex and start
294 MUTEX_UNLOCK(&threads_mutex);
296 SvREFCNT_dec((SV*)av);
297 DEBUG_L(PerlIO_printf(PerlIO_stderr(),
298 "perl_destruct: joined zombie %p OK\n", t));
300 case THRf_R_JOINABLE:
301 DEBUG_L(PerlIO_printf(PerlIO_stderr(),
302 "perl_destruct: detaching thread %p\n", t));
303 ThrSETSTATE(t, THRf_R_DETACHED);
305 * We unlock threads_mutex and t->mutex in the opposite order
306 * from which we locked them just so that DETACH won't
307 * deadlock if it panics. It's only a breach of good style
308 * not a bug since they are unlocks not locks.
310 MUTEX_UNLOCK(&threads_mutex);
312 MUTEX_UNLOCK(&t->mutex);
315 DEBUG_L(PerlIO_printf(PerlIO_stderr(),
316 "perl_destruct: ignoring %p (state %u)\n",
318 MUTEX_UNLOCK(&t->mutex);
319 /* fall through and out */
322 /* We leave the above "Pass 1" loop with threads_mutex still locked */
324 /* Pass 2 on remaining threads: wait for the thread count to drop to one */
327 DEBUG_L(PerlIO_printf(PerlIO_stderr(),
328 "perl_destruct: final wait for %d threads\n",
330 COND_WAIT(&nthreads_cond, &threads_mutex);
332 /* At this point, we're the last thread */
333 MUTEX_UNLOCK(&threads_mutex);
334 DEBUG_L(PerlIO_printf(PerlIO_stderr(), "perl_destruct: armageddon has arrived\n"));
335 MUTEX_DESTROY(&threads_mutex);
336 COND_DESTROY(&nthreads_cond);
337 #endif /* !defined(FAKE_THREADS) */
338 #endif /* USE_THREADS */
340 destruct_level = perl_destruct_level;
344 if (s = PerlEnv_getenv("PERL_DESTRUCT_LEVEL")) {
346 if (destruct_level < i)
355 /* We must account for everything. */
357 /* Destroy the main CV and syntax tree */
359 curpad = AvARRAY(comppad);
365 SvREFCNT_dec(main_cv);
370 * Try to destruct global references. We do this first so that the
371 * destructors and destructees still exist. Some sv's might remain.
372 * Non-referenced objects are on their own.
379 /* unhook hooks which will soon be, or use, destroyed data */
380 SvREFCNT_dec(warnhook);
382 SvREFCNT_dec(diehook);
384 SvREFCNT_dec(parsehook);
387 /* call exit list functions */
388 while (exitlistlen-- > 0)
389 exitlist[exitlistlen].fn(PERL_OBJECT_THIS_ exitlist[exitlistlen].ptr);
393 if (destruct_level == 0){
395 DEBUG_P(debprofdump());
397 /* The exit() function will do everything that needs doing. */
401 /* loosen bonds of global variables */
404 (void)PerlIO_close(rsfp);
408 /* Filters for program text */
409 SvREFCNT_dec(rsfp_filters);
410 rsfp_filters = Nullav;
422 sawampersand = FALSE; /* must save all match strings */
423 sawstudy = FALSE; /* do fbm_instr on all strings */
431 SvREFCNT_dec(e_script);
435 /* magical thingies */
437 Safefree(ofs); /* $, */
440 Safefree(ors); /* $\ */
443 SvREFCNT_dec(nrs); /* $\ helper */
446 multiline = 0; /* $* */
448 SvREFCNT_dec(statname);
452 /* defgv, aka *_ should be taken care of elsewhere */
454 /* clean up after study() */
455 SvREFCNT_dec(lastscream);
457 Safefree(screamfirst);
459 Safefree(screamnext);
462 /* startup and shutdown function lists */
463 SvREFCNT_dec(beginav);
465 SvREFCNT_dec(initav);
470 /* shortcuts just get cleared */
481 /* reset so print() ends up where we expect */
484 /* Prepare to destruct main symbol table. */
491 if (destruct_level >= 2) {
492 if (scopestack_ix != 0)
493 warn("Unbalanced scopes: %ld more ENTERs than LEAVEs\n",
494 (long)scopestack_ix);
495 if (savestack_ix != 0)
496 warn("Unbalanced saves: %ld more saves than restores\n",
498 if (tmps_floor != -1)
499 warn("Unbalanced tmps: %ld more allocs than frees\n",
500 (long)tmps_floor + 1);
501 if (cxstack_ix != -1)
502 warn("Unbalanced context: %ld more PUSHes than POPs\n",
503 (long)cxstack_ix + 1);
506 /* Now absolutely destruct everything, somehow or other, loops or no. */
508 SvFLAGS(strtab) |= SVTYPEMASK; /* don't clean out strtab now */
509 while (sv_count != 0 && sv_count != last_sv_count) {
510 last_sv_count = sv_count;
513 SvFLAGS(strtab) &= ~SVTYPEMASK;
514 SvFLAGS(strtab) |= SVt_PVHV;
516 /* Destruct the global string table. */
518 /* Yell and reset the HeVAL() slots that are still holding refcounts,
519 * so that sv_free() won't fail on them.
528 array = HvARRAY(strtab);
532 warn("Unbalanced string table refcount: (%d) for \"%s\"",
533 HeVAL(hent) - Nullsv, HeKEY(hent));
534 HeVAL(hent) = Nullsv;
544 SvREFCNT_dec(strtab);
547 warn("Scalars leaked: %ld\n", (long)sv_count);
551 /* No SVs have survived, need to clean out */
555 Safefree(origfilename);
557 hints = 0; /* Reset hints. Should hints be per-interpreter ? */
559 DEBUG_P(debprofdump());
561 MUTEX_DESTROY(&sv_mutex);
562 MUTEX_DESTROY(&eval_mutex);
563 COND_DESTROY(&eval_cond);
565 /* As the penultimate thing, free the non-arena SV for thrsv */
566 Safefree(SvPVX(thrsv));
567 Safefree(SvANY(thrsv));
570 #endif /* USE_THREADS */
572 /* As the absolutely last thing, free the non-arena SV for mess() */
575 /* we know that type >= SVt_PV */
577 Safefree(SvPVX(mess_sv));
578 Safefree(SvANY(mess_sv));
586 CPerlObj::perl_free(void)
588 perl_free(PerlInterpreter *sv_interp)
594 if (!(curinterp = sv_interp))
602 CPerlObj::perl_atexit(void (*fn) (CPerlObj*,void *), void *ptr)
604 perl_atexit(void (*fn) (void *), void *ptr)
607 Renew(exitlist, exitlistlen+1, PerlExitListEntry);
608 exitlist[exitlistlen].fn = fn;
609 exitlist[exitlistlen].ptr = ptr;
615 CPerlObj::perl_parse(void (*xsinit) (CPerlObj*), int argc, char **argv, char **env)
617 perl_parse(PerlInterpreter *sv_interp, void (*xsinit) (void), int argc, char **argv, char **env)
623 char *scriptname = NULL;
624 VOL bool dosearch = FALSE;
632 #ifdef SETUID_SCRIPTS_ARE_SECURE_NOW
635 croak("suidperl is no longer needed since the kernel can now execute\n\
636 setuid perl scripts securely.\n");
641 if (!(curinterp = sv_interp))
645 #if defined(NeXT) && defined(__DYNAMIC__)
646 _dyld_lookup_and_bind
647 ("__environ", (unsigned long *) &environ_pointer, NULL);
652 #ifndef VMS /* VMS doesn't have environ array */
653 origenviron = environ;
658 /* Come here if running an undumped a.out. */
660 origfilename = savepv(argv[0]);
662 cxstack_ix = -1; /* start label stack again */
664 init_postdump_symbols(argc,argv,env);
669 curpad = AvARRAY(comppad);
674 SvREFCNT_dec(main_cv);
678 oldscope = scopestack_ix;
686 /* my_exit() was called */
687 while (scopestack_ix > oldscope)
692 call_list(oldscope, endav);
694 return STATUS_NATIVE_EXPORT;
697 PerlIO_printf(PerlIO_stderr(), "panic: top_env\n");
701 sv_setpvn(linestr,"",0);
702 sv = newSVpv("",0); /* first used for -I flags */
706 for (argc--,argv++; argc > 0; argc--,argv++) {
707 if (argv[0][0] != '-' || !argv[0][1])
711 validarg = " PHOOEY ";
737 if (s = moreswitches(s))
747 if (euid != uid || egid != gid)
748 croak("No -e allowed in setuid scripts");
750 e_script = newSVpv("",0);
751 filter_add(read_e_script, NULL);
754 sv_catpv(e_script, s);
756 sv_catpv(e_script, argv[1]);
760 croak("No code specified for -e");
761 sv_catpv(e_script, "\n");
764 case 'I': /* -I handled both here and in moreswitches() */
766 if (!*++s && (s=argv[1]) != Nullch) {
769 while (s && isSPACE(*s))
773 for (e = s; *e && !isSPACE(*e); e++) ;
780 } /* XXX else croak? */
794 preambleav = newAV();
795 av_push(preambleav, newSVpv("use Config qw(myconfig config_vars)",0));
797 Sv = newSVpv("print myconfig();",0);
799 sv_catpv(Sv,"print \"\\nCharacteristics of this PERLSHR image: \\n\",");
801 sv_catpv(Sv,"print \"\\nCharacteristics of this binary (from libperl): \\n\",");
803 #if defined(DEBUGGING) || defined(NO_EMBED) || defined(MULTIPLICITY)
804 sv_catpv(Sv,"\" Compile-time options:");
806 sv_catpv(Sv," DEBUGGING");
809 sv_catpv(Sv," NO_EMBED");
812 sv_catpv(Sv," MULTIPLICITY");
814 sv_catpv(Sv,"\\n\",");
816 #if defined(LOCAL_PATCH_COUNT)
817 if (LOCAL_PATCH_COUNT > 0) {
819 sv_catpv(Sv,"\" Locally applied patches:\\n\",");
820 for (i = 1; i <= LOCAL_PATCH_COUNT; i++) {
822 sv_catpvf(Sv,"\" \\t%s\\n\",",localpatches[i]);
826 sv_catpvf(Sv,"\" Built under %s\\n\"",OSNAME);
829 sv_catpvf(Sv,",\" Compiled at %s %s\\n\"",__DATE__,__TIME__);
831 sv_catpvf(Sv,",\" Compiled on %s\\n\"",__DATE__);
836 @env = map { \"$_=\\\"$ENV{$_}\\\"\" } sort grep {/^PERL/} keys %ENV; \
837 print \" \\%ENV:\\n @env\\n\" if @env; \
838 print \" \\@INC:\\n @INC\\n\";");
841 Sv = newSVpv("config_vars(qw(",0);
846 av_push(preambleav, Sv);
847 scriptname = BIT_BUCKET; /* don't look for script or read stdin */
858 if (!*++s || isSPACE(*s)) {
862 /* catch use of gnu style long options */
863 if (strEQ(s, "version")) {
867 if (strEQ(s, "help")) {
874 croak("Unrecognized switch: -%s (-h will show valid options)",s);
879 if (!tainting && (s = PerlEnv_getenv("PERL5OPT"))) {
890 if (!strchr("DIMUdmw", *s))
891 croak("Illegal switch in PERL5OPT: -%c", *s);
897 scriptname = argv[0];
900 scriptname = BIT_BUCKET; /* don't look for script or read stdin */
902 else if (scriptname == Nullch) {
904 if ( PerlLIO_isatty(PerlIO_fileno(PerlIO_stdin())) )
912 open_script(scriptname,dosearch,sv,&fdscript);
914 validate_suid(validarg, scriptname,fdscript);
919 main_cv = compcv = (CV*)NEWSV(1104,0);
920 sv_upgrade((SV *)compcv, SVt_PVCV);
924 av_push(comppad, Nullsv);
925 curpad = AvARRAY(comppad);
926 comppad_name = newAV();
927 comppad_name_fill = 0;
928 min_intro_pending = 0;
931 av_store(comppad_name, 0, newSVpv("@_", 2));
932 curpad[0] = (SV*)newAV();
933 SvPADMY_on(curpad[0]); /* XXX Needed? */
935 New(666, CvMUTEXP(compcv), 1, perl_mutex);
936 MUTEX_INIT(CvMUTEXP(compcv));
937 #endif /* USE_THREADS */
939 comppadlist = newAV();
940 AvREAL_off(comppadlist);
941 av_store(comppadlist, 0, (SV*)comppad_name);
942 av_store(comppadlist, 1, (SV*)comppad);
943 CvPADLIST(compcv) = comppadlist;
945 boot_core_UNIVERSAL();
948 (*xsinit)(PERL_OBJECT_THIS); /* in case linked C routines want magical variables */
949 #if defined(VMS) || defined(WIN32) || defined(DJGPP)
953 init_predump_symbols();
954 /* init_postdump_symbols not currently designed to be called */
955 /* more than once (ENV isn't cleared first, for example) */
956 /* But running with -u leaves %ENV & @ARGV undefined! XXX */
958 init_postdump_symbols(argc,argv,env);
962 /* now parse the script */
964 SETERRNO(0,SS$_NORMAL);
966 if (yyparse() || error_count) {
968 croak("%s had compilation errors.\n", origfilename);
970 croak("Execution of %s aborted due to compilation errors.\n",
974 curcop->cop_line = 0;
978 SvREFCNT_dec(e_script);
982 /* now that script is parsed, we can modify record separator */
984 rs = SvREFCNT_inc(nrs);
985 sv_setsv(perl_get_sv("/", TRUE), rs);
996 if ((s=PerlEnv_getenv("PERL_DEBUG_MSTATS")) && atoi(s) >= 2)
997 dump_mstats("after compilation:");
1008 CPerlObj::perl_run(void)
1010 perl_run(PerlInterpreter *sv_interp)
1019 if (!(curinterp = sv_interp))
1023 oldscope = scopestack_ix;
1028 cxstack_ix = -1; /* start context stack again */
1031 /* my_exit() was called */
1032 while (scopestack_ix > oldscope)
1035 curstash = defstash;
1037 call_list(oldscope, endav);
1039 if (PerlEnv_getenv("PERL_DEBUG_MSTATS"))
1040 dump_mstats("after execution: ");
1043 return STATUS_NATIVE_EXPORT;
1046 PerlIO_printf(PerlIO_stderr(), "panic: restartop\n");
1051 POPSTACK_TO(mainstack);
1055 DEBUG_r(PerlIO_printf(Perl_debug_log, "%s $` $& $' support.\n",
1056 sawampersand ? "Enabling" : "Omitting"));
1059 DEBUG_x(dump_all());
1060 DEBUG(PerlIO_printf(Perl_debug_log, "\nEXECUTING...\n\n"));
1062 DEBUG_L(PerlIO_printf(Perl_debug_log, "main thread is 0x%lx\n",
1063 (unsigned long) thr));
1064 #endif /* USE_THREADS */
1067 PerlIO_printf(PerlIO_stderr(), "%s syntax OK\n", origfilename);
1070 if (PERLDB_SINGLE && DBsingle)
1071 sv_setiv(DBsingle, 1);
1073 call_list(oldscope, initav);
1083 else if (main_start) {
1084 CvDEPTH(main_cv) = 1;
1095 perl_get_sv(char *name, I32 create)
1099 if (name[1] == '\0' && !isALPHA(name[0])) {
1100 PADOFFSET tmp = find_threadsv(name);
1101 if (tmp != NOT_IN_PAD) {
1103 return THREADSV(tmp);
1106 #endif /* USE_THREADS */
1107 gv = gv_fetchpv(name, create, SVt_PV);
1114 perl_get_av(char *name, I32 create)
1116 GV* gv = gv_fetchpv(name, create, SVt_PVAV);
1125 perl_get_hv(char *name, I32 create)
1127 GV* gv = gv_fetchpv(name, create, SVt_PVHV);
1136 perl_get_cv(char *name, I32 create)
1138 GV* gv = gv_fetchpv(name, create, SVt_PVCV);
1139 if (create && !GvCVu(gv))
1140 return newSUB(start_subparse(FALSE, 0),
1141 newSVOP(OP_CONST, 0, newSVpv(name,0)),
1149 /* Be sure to refetch the stack pointer after calling these routines. */
1152 perl_call_argv(char *sub_name, I32 flags, register char **argv)
1154 /* See G_* flags in cop.h */
1155 /* null terminated arg list */
1162 XPUSHs(sv_2mortal(newSVpv(*argv,0)));
1167 return perl_call_pv(sub_name, flags);
1171 perl_call_pv(char *sub_name, I32 flags)
1172 /* name of the subroutine */
1173 /* See G_* flags in cop.h */
1175 return perl_call_sv((SV*)perl_get_cv(sub_name, TRUE), flags);
1179 perl_call_method(char *methname, I32 flags)
1180 /* name of the subroutine */
1181 /* See G_* flags in cop.h */
1187 XPUSHs(sv_2mortal(newSVpv(methname,0)));
1192 return perl_call_sv(*stack_sp--, flags);
1195 /* May be called with any of a CV, a GV, or an SV containing the name. */
1197 perl_call_sv(SV *sv, I32 flags)
1199 /* See G_* flags in cop.h */
1202 LOGOP myop; /* fake syntax tree node */
1206 bool oldcatch = CATCH_GET;
1211 if (flags & G_DISCARD) {
1216 Zero(&myop, 1, LOGOP);
1217 myop.op_next = Nullop;
1218 if (!(flags & G_NOARGS))
1219 myop.op_flags |= OPf_STACKED;
1220 myop.op_flags |= ((flags & G_VOID) ? OPf_WANT_VOID :
1221 (flags & G_ARRAY) ? OPf_WANT_LIST :
1226 EXTEND(stack_sp, 1);
1229 oldscope = scopestack_ix;
1231 if (PERLDB_SUB && curstash != debstash
1232 /* Handle first BEGIN of -d. */
1233 && (DBcv || (DBcv = GvCV(DBsub)))
1234 /* Try harder, since this may have been a sighandler, thus
1235 * curstash may be meaningless. */
1236 && (SvTYPE(sv) != SVt_PVCV || CvSTASH((CV*)sv) != debstash)
1237 && !(flags & G_NODEBUG))
1238 op->op_private |= OPpENTERSUB_DB;
1240 if (flags & G_EVAL) {
1241 cLOGOP->op_other = op;
1243 /* we're trying to emulate pp_entertry() here */
1245 register PERL_CONTEXT *cx;
1246 I32 gimme = GIMME_V;
1251 push_return(op->op_next);
1252 PUSHBLOCK(cx, CXt_EVAL, stack_sp);
1254 eval_root = op; /* Only needed so that goto works right. */
1257 if (flags & G_KEEPERR)
1272 /* my_exit() was called */
1273 curstash = defstash;
1277 croak("Callback called exit");
1286 stack_sp = stack_base + oldmark;
1287 if (flags & G_ARRAY)
1291 *++stack_sp = &sv_undef;
1299 if (op == (OP*)&myop)
1300 op = pp_entersub(ARGS);
1303 retval = stack_sp - (stack_base + oldmark);
1304 if ((flags & G_EVAL) && !(flags & G_KEEPERR))
1308 if (flags & G_EVAL) {
1309 if (scopestack_ix > oldscope) {
1313 register PERL_CONTEXT *cx;
1325 CATCH_SET(oldcatch);
1327 if (flags & G_DISCARD) {
1328 stack_sp = stack_base + oldmark;
1337 /* Eval a string. The G_EVAL flag is always assumed. */
1340 perl_eval_sv(SV *sv, I32 flags)
1342 /* See G_* flags in cop.h */
1345 UNOP myop; /* fake syntax tree node */
1346 I32 oldmark = SP - stack_base;
1353 if (flags & G_DISCARD) {
1361 EXTEND(stack_sp, 1);
1363 oldscope = scopestack_ix;
1365 if (!(flags & G_NOARGS))
1366 myop.op_flags = OPf_STACKED;
1367 myop.op_next = Nullop;
1368 myop.op_type = OP_ENTEREVAL;
1369 myop.op_flags |= ((flags & G_VOID) ? OPf_WANT_VOID :
1370 (flags & G_ARRAY) ? OPf_WANT_LIST :
1372 if (flags & G_KEEPERR)
1373 myop.op_flags |= OPf_SPECIAL;
1383 /* my_exit() was called */
1384 curstash = defstash;
1388 croak("Callback called exit");
1397 stack_sp = stack_base + oldmark;
1398 if (flags & G_ARRAY)
1402 *++stack_sp = &sv_undef;
1407 if (op == (OP*)&myop)
1408 op = pp_entereval(ARGS);
1411 retval = stack_sp - (stack_base + oldmark);
1412 if (!(flags & G_KEEPERR))
1417 if (flags & G_DISCARD) {
1418 stack_sp = stack_base + oldmark;
1428 perl_eval_pv(char *p, I32 croak_on_error)
1431 SV* sv = newSVpv(p, 0);
1434 perl_eval_sv(sv, G_SCALAR);
1441 if (croak_on_error && SvTRUE(ERRSV))
1442 croak(SvPVx(ERRSV, na));
1447 /* Require a module. */
1450 perl_require_pv(char *pv)
1452 SV* sv = sv_newmortal();
1453 sv_setpv(sv, "require '");
1456 perl_eval_sv(sv, G_DISCARD);
1460 magicname(char *sym, char *name, I32 namlen)
1464 if (gv = gv_fetchpv(sym,TRUE, SVt_PV))
1465 sv_magic(GvSV(gv), (SV*)gv, 0, name, namlen);
1469 usage(char *name) /* XXX move this out into a module ? */
1472 /* This message really ought to be max 23 lines.
1473 * Removed -h because the user already knows that opton. Others? */
1475 static char *usage_msg[] = {
1476 "-0[octal] specify record separator (\\0, if no argument)",
1477 "-a autosplit mode with -n or -p (splits $_ into @F)",
1478 "-c check syntax only (runs BEGIN and END blocks)",
1479 "-d[:debugger] run scripts under debugger",
1480 "-D[number/list] set debugging flags (argument is a bit mask or flags)",
1481 "-e 'command' one line of script. Several -e's allowed. Omit [programfile].",
1482 "-F/pattern/ split() pattern for autosplit (-a). The //'s are optional.",
1483 "-i[extension] edit <> files in place (make backup if extension supplied)",
1484 "-Idirectory specify @INC/#include directory (may be used more than once)",
1485 "-l[octal] enable line ending processing, specifies line terminator",
1486 "-[mM][-]module.. executes `use/no module...' before executing your script.",
1487 "-n assume 'while (<>) { ... }' loop around your script",
1488 "-p assume loop like -n but print line also like sed",
1489 "-P run script through C preprocessor before compilation",
1490 "-s enable some switch parsing for switches after script name",
1491 "-S look for the script using PATH environment variable",
1492 "-T turn on tainting checks",
1493 "-u dump core after parsing script",
1494 "-U allow unsafe operations",
1495 "-v print version number, patchlevel plus VERY IMPORTANT perl info",
1496 "-V[:variable] print perl configuration information",
1497 "-w TURN WARNINGS ON FOR COMPILATION OF YOUR SCRIPT. Recommended.",
1498 "-x[directory] strip off text before #!perl line and perhaps cd to directory",
1502 char **p = usage_msg;
1504 printf("\nUsage: %s [switches] [--] [programfile] [arguments]", name);
1506 printf("\n %s", *p++);
1509 /* This routine handles any switches that can be given during run */
1512 moreswitches(char *s)
1521 rschar = scan_oct(s, 4, &numlen);
1523 if (rschar & ~((U8)~0))
1525 else if (!rschar && numlen >= 2)
1526 nrs = newSVpv("", 0);
1529 nrs = newSVpv(&ch, 1);
1535 splitstr = savepv(s + 1);
1549 if (*s == ':' || *s == '=') {
1550 my_setenv("PERL5DB", form("use Devel::%s;", ++s));
1554 perldb = PERLDB_ALL;
1561 if (isALPHA(s[1])) {
1562 static char debopts[] = "psltocPmfrxuLHXD";
1565 for (s++; *s && (d = strchr(debopts,*s)); s++)
1566 debug |= 1 << (d - debopts);
1570 for (s++; isDIGIT(*s); s++) ;
1572 debug |= 0x80000000;
1574 warn("Recompile perl with -DDEBUGGING to use -D switch\n");
1575 for (s++; isALNUM(*s); s++) ;
1585 inplace = savepv(s+1);
1587 for (s = inplace; *s && !isSPACE(*s); s++) ;
1590 if (*s == '-') /* Additional switches on #! line. */
1594 case 'I': /* -I handled both here and in parse_perl() */
1597 while (*s && isSPACE(*s))
1601 for (e = s; *e && !isSPACE(*e); e++) ;
1602 p = savepvn(s, e-s);
1608 croak("No space allowed after -I");
1618 *ors = scan_oct(s, 3 + (*s == '0'), &numlen);
1628 ors = SvPV(nrs, orslen);
1629 ors = savepvn(ors, orslen);
1633 forbid_setid("-M"); /* XXX ? */
1636 forbid_setid("-m"); /* XXX ? */
1641 /* -M-foo == 'no foo' */
1642 if (*s == '-') { use = "no "; ++s; }
1643 sv = newSVpv(use,0);
1645 /* We allow -M'Module qw(Foo Bar)' */
1646 while(isALNUM(*s) || *s==':') ++s;
1648 sv_catpv(sv, start);
1649 if (*(start-1) == 'm') {
1651 croak("Can't use '%c' after -mname", *s);
1652 sv_catpv( sv, " ()");
1655 sv_catpvn(sv, start, s-start);
1656 sv_catpv(sv, " split(/,/,q{");
1661 if (preambleav == NULL)
1662 preambleav = newAV();
1663 av_push(preambleav, sv);
1666 croak("No space allowed after -%c", *(s-1));
1683 croak("Too late for \"-T\" option");
1695 #if defined(SUBVERSION) && SUBVERSION > 0
1696 printf("\nThis is perl, version 5.%03d_%02d built for %s",
1697 PATCHLEVEL, SUBVERSION, ARCHNAME);
1699 printf("\nThis is perl, version %s built for %s",
1700 patchlevel, ARCHNAME);
1702 #if defined(LOCAL_PATCH_COUNT)
1703 if (LOCAL_PATCH_COUNT > 0)
1704 printf("\n(with %d registered patch%s, see perl -V for more detail)",
1705 LOCAL_PATCH_COUNT, (LOCAL_PATCH_COUNT!=1) ? "es" : "");
1708 printf("\n\nCopyright 1987-1998, Larry Wall\n");
1710 printf("\nMS-DOS port Copyright (c) 1989, 1990, Diomidis Spinellis\n");
1713 printf("djgpp v2 port (jpl5003c) by Hirofumi Watanabe, 1996\n");
1714 printf("djgpp v2 port (perl5004+) by Laszlo Molnar, 1997-1998\n");
1717 printf("\n\nOS/2 port Copyright (c) 1990, 1991, Raymond Chen, Kai Uwe Rommel\n"
1718 "Version 5 port Copyright (c) 1994-1998, Andreas Kaiser, Ilya Zakharevich\n");
1721 printf("atariST series port, ++jrb bammi@cadence.com\n");
1724 Perl may be copied only under the terms of either the Artistic License or the\n\
1725 GNU General Public License, which may be found in the Perl 5.0 source kit.\n\n\
1726 Complete documentation for Perl, including FAQ lists, should be found on\n\
1727 this system using `man perl' or `perldoc perl'. If you have access to the\n\
1728 Internet, point your browser at http://www.perl.com/, the Perl Home Page.\n\n");
1736 if (s[1] == '-') /* Additional switches on #! line. */
1747 #ifdef ALTERNATE_SHEBANG
1748 case 'S': /* OS/2 needs -S on "extproc" line. */
1756 croak("Can't emulate -%.1s on #! line",s);
1761 /* compliments of Tom Christiansen */
1763 /* unexec() can be found in the Gnu emacs distribution */
1764 /* Known to work with -DUNEXEC and using unexelf.c from GNU emacs-20.2 */
1775 prog = newSVpv(BIN_EXP, 0);
1776 sv_catpv(prog, "/perl");
1777 file = newSVpv(origfilename, 0);
1778 sv_catpv(file, ".perldump");
1780 unexec(SvPVX(file), SvPVX(prog), &etext, sbrk(0), 0);
1781 /* unexec prints msg to stderr in case of failure */
1782 PerlProc_exit(status);
1785 # include <lib$routines.h>
1786 lib$signal(SS$_DEBUG); /* ssdef.h #included from vmsish.h */
1788 ABORT(); /* for use with undump */
1794 init_main_stash(void)
1799 /* Note that strtab is a rather special HV. Assumptions are made
1800 about not iterating on it, and not adding tie magic to it.
1801 It is properly deallocated in perl_destruct() */
1803 HvSHAREKEYS_off(strtab); /* mandatory */
1804 Newz(506,((XPVHV*)SvANY(strtab))->xhv_array,
1805 sizeof(HE*) * (((XPVHV*)SvANY(strtab))->xhv_max + 1), char);
1807 curstash = defstash = newHV();
1808 curstname = newSVpv("main",4);
1809 gv = gv_fetchpv("main::",TRUE, SVt_PVHV);
1810 SvREFCNT_dec(GvHV(gv));
1811 GvHV(gv) = (HV*)SvREFCNT_inc(defstash);
1813 HvNAME(defstash) = savepv("main");
1814 incgv = gv_HVadd(gv_AVadd(gv_fetchpv("INC",TRUE, SVt_PVAV)));
1816 defgv = gv_fetchpv("_",TRUE, SVt_PVAV);
1817 errgv = gv_HVadd(gv_fetchpv("@", TRUE, SVt_PV));
1819 replgv = gv_HVadd(gv_fetchpv("\022", TRUE, SVt_PV)); /* ^R */
1821 (void)form("%240s",""); /* Preallocate temp - for immediate signals. */
1822 sv_grow(ERRSV, 240); /* Preallocate - for immediate signals. */
1823 sv_setpvn(ERRSV, "", 0);
1824 curstash = defstash;
1825 compiling.cop_stash = defstash;
1826 debstash = GvHV(gv_fetchpv("DB::", GV_ADDMULTI, SVt_PVHV));
1827 globalstash = GvHV(gv_fetchpv("CORE::GLOBAL::", GV_ADDMULTI, SVt_PVHV));
1828 /* We must init $/ before switches are processed. */
1829 sv_setpvn(GvSV(gv_fetchpv("/", TRUE, SVt_PV)), "\n", 1);
1833 open_script(char *scriptname, bool dosearch, SV *sv, int *fdscript)
1838 scriptname = find_script(scriptname, dosearch, NULL, 0);
1840 if (strnEQ(scriptname, "/dev/fd/", 8) && isDIGIT(scriptname[8]) ) {
1841 char *s = scriptname + 8;
1842 *fdscript = atoi(s);
1850 origfilename = savepv(e_script ? "-e" : scriptname);
1851 curcop->cop_filegv = gv_fetchfile(origfilename);
1852 if (strEQ(origfilename,"-"))
1854 if (*fdscript >= 0) {
1855 rsfp = PerlIO_fdopen(*fdscript,PERL_SCRIPT_MODE);
1856 #if defined(HAS_FCNTL) && defined(F_SETFD)
1858 fcntl(PerlIO_fileno(rsfp),F_SETFD,1); /* ensure close-on-exec */
1861 else if (preprocess) {
1862 char *cpp_cfg = CPPSTDIN;
1863 SV *cpp = NEWSV(0,0);
1864 SV *cmd = NEWSV(0,0);
1866 if (strEQ(cpp_cfg, "cppstdin"))
1867 sv_catpvf(cpp, "%s/", BIN_EXP);
1868 sv_catpv(cpp, cpp_cfg);
1871 sv_catpv(sv,PRIVLIB_EXP);
1875 sed %s -e \"/^[^#]/b\" \
1876 -e \"/^#[ ]*include[ ]/b\" \
1877 -e \"/^#[ ]*define[ ]/b\" \
1878 -e \"/^#[ ]*if[ ]/b\" \
1879 -e \"/^#[ ]*ifdef[ ]/b\" \
1880 -e \"/^#[ ]*ifndef[ ]/b\" \
1881 -e \"/^#[ ]*else/b\" \
1882 -e \"/^#[ ]*elif[ ]/b\" \
1883 -e \"/^#[ ]*undef[ ]/b\" \
1884 -e \"/^#[ ]*endif/b\" \
1887 (doextract ? "-e \"1,/^#/d\n\"" : ""),
1890 %s %s -e '/^[^#]/b' \
1891 -e '/^#[ ]*include[ ]/b' \
1892 -e '/^#[ ]*define[ ]/b' \
1893 -e '/^#[ ]*if[ ]/b' \
1894 -e '/^#[ ]*ifdef[ ]/b' \
1895 -e '/^#[ ]*ifndef[ ]/b' \
1896 -e '/^#[ ]*else/b' \
1897 -e '/^#[ ]*elif[ ]/b' \
1898 -e '/^#[ ]*undef[ ]/b' \
1899 -e '/^#[ ]*endif/b' \
1907 (doextract ? "-e '1,/^#/d\n'" : ""),
1909 scriptname, cpp, sv, CPPMINUS);
1911 #ifdef IAMSUID /* actually, this is caught earlier */
1912 if (euid != uid && !euid) { /* if running suidperl */
1914 (void)seteuid(uid); /* musn't stay setuid root */
1917 (void)setreuid((Uid_t)-1, uid);
1919 #ifdef HAS_SETRESUID
1920 (void)setresuid((Uid_t)-1, uid, (Uid_t)-1);
1922 PerlProc_setuid(uid);
1926 if (PerlProc_geteuid() != uid)
1927 croak("Can't do seteuid!\n");
1929 #endif /* IAMSUID */
1930 rsfp = PerlProc_popen(SvPVX(cmd), "r");
1934 else if (!*scriptname) {
1935 forbid_setid("program input from stdin");
1936 rsfp = PerlIO_stdin();
1939 rsfp = PerlIO_open(scriptname,PERL_SCRIPT_MODE);
1940 #if defined(HAS_FCNTL) && defined(F_SETFD)
1942 fcntl(PerlIO_fileno(rsfp),F_SETFD,1); /* ensure close-on-exec */
1947 #ifndef IAMSUID /* in case script is not readable before setuid */
1948 if (euid && PerlLIO_stat(SvPVX(GvSV(curcop->cop_filegv)),&statbuf) >= 0 &&
1949 statbuf.st_mode & (S_ISUID|S_ISGID)) {
1951 PerlProc_execv(form("%s/sperl%s", BIN_EXP, patchlevel), origargv);
1952 croak("Can't do setuid\n");
1956 croak("Can't open perl script \"%s\": %s\n",
1957 SvPVX(GvSV(curcop->cop_filegv)), Strerror(errno));
1962 validate_suid(char *validarg, char *scriptname, int fdscript)
1966 /* do we need to emulate setuid on scripts? */
1968 /* This code is for those BSD systems that have setuid #! scripts disabled
1969 * in the kernel because of a security problem. Merely defining DOSUID
1970 * in perl will not fix that problem, but if you have disabled setuid
1971 * scripts in the kernel, this will attempt to emulate setuid and setgid
1972 * on scripts that have those now-otherwise-useless bits set. The setuid
1973 * root version must be called suidperl or sperlN.NNN. If regular perl
1974 * discovers that it has opened a setuid script, it calls suidperl with
1975 * the same argv that it had. If suidperl finds that the script it has
1976 * just opened is NOT setuid root, it sets the effective uid back to the
1977 * uid. We don't just make perl setuid root because that loses the
1978 * effective uid we had before invoking perl, if it was different from the
1981 * DOSUID must be defined in both perl and suidperl, and IAMSUID must
1982 * be defined in suidperl only. suidperl must be setuid root. The
1983 * Configure script will set this up for you if you want it.
1990 if (PerlLIO_fstat(PerlIO_fileno(rsfp),&statbuf) < 0) /* normal stat is insecure */
1991 croak("Can't stat script \"%s\"",origfilename);
1992 if (fdscript < 0 && statbuf.st_mode & (S_ISUID|S_ISGID)) {
1996 #ifndef HAS_SETREUID
1997 /* On this access check to make sure the directories are readable,
1998 * there is actually a small window that the user could use to make
1999 * filename point to an accessible directory. So there is a faint
2000 * chance that someone could execute a setuid script down in a
2001 * non-accessible directory. I don't know what to do about that.
2002 * But I don't think it's too important. The manual lies when
2003 * it says access() is useful in setuid programs.
2005 if (PerlLIO_access(SvPVX(GvSV(curcop->cop_filegv)),1)) /*double check*/
2006 croak("Permission denied");
2008 /* If we can swap euid and uid, then we can determine access rights
2009 * with a simple stat of the file, and then compare device and
2010 * inode to make sure we did stat() on the same file we opened.
2011 * Then we just have to make sure he or she can execute it.
2014 struct stat tmpstatbuf;
2018 setreuid(euid,uid) < 0
2021 setresuid(euid,uid,(Uid_t)-1) < 0
2024 || PerlProc_getuid() != euid || PerlProc_geteuid() != uid)
2025 croak("Can't swap uid and euid"); /* really paranoid */
2026 if (PerlLIO_stat(SvPVX(GvSV(curcop->cop_filegv)),&tmpstatbuf) < 0)
2027 croak("Permission denied"); /* testing full pathname here */
2028 if (tmpstatbuf.st_dev != statbuf.st_dev ||
2029 tmpstatbuf.st_ino != statbuf.st_ino) {
2030 (void)PerlIO_close(rsfp);
2031 if (rsfp = PerlProc_popen("/bin/mail root","w")) { /* heh, heh */
2033 "User %ld tried to run dev %ld ino %ld in place of dev %ld ino %ld!\n\
2034 (Filename of set-id script was %s, uid %ld gid %ld.)\n\nSincerely,\nperl\n",
2035 (long)uid,(long)tmpstatbuf.st_dev, (long)tmpstatbuf.st_ino,
2036 (long)statbuf.st_dev, (long)statbuf.st_ino,
2037 SvPVX(GvSV(curcop->cop_filegv)),
2038 (long)statbuf.st_uid, (long)statbuf.st_gid);
2039 (void)PerlProc_pclose(rsfp);
2041 croak("Permission denied\n");
2045 setreuid(uid,euid) < 0
2047 # if defined(HAS_SETRESUID)
2048 setresuid(uid,euid,(Uid_t)-1) < 0
2051 || PerlProc_getuid() != uid || PerlProc_geteuid() != euid)
2052 croak("Can't reswap uid and euid");
2053 if (!cando(S_IXUSR,FALSE,&statbuf)) /* can real uid exec? */
2054 croak("Permission denied\n");
2056 #endif /* HAS_SETREUID */
2057 #endif /* IAMSUID */
2059 if (!S_ISREG(statbuf.st_mode))
2060 croak("Permission denied");
2061 if (statbuf.st_mode & S_IWOTH)
2062 croak("Setuid/gid script is writable by world");
2063 doswitches = FALSE; /* -s is insecure in suid */
2065 if (sv_gets(linestr, rsfp, 0) == Nullch ||
2066 strnNE(SvPV(linestr,na),"#!",2) ) /* required even on Sys V */
2067 croak("No #! line");
2068 s = SvPV(linestr,na)+2;
2070 while (!isSPACE(*s)) s++;
2071 for (s2 = s; (s2 > SvPV(linestr,na)+2 &&
2072 (isDIGIT(s2[-1]) || strchr("._-", s2[-1]))); s2--) ;
2073 if (strnNE(s2-4,"perl",4) && strnNE(s-9,"perl",4)) /* sanity check */
2074 croak("Not a perl script");
2075 while (*s == ' ' || *s == '\t') s++;
2077 * #! arg must be what we saw above. They can invoke it by
2078 * mentioning suidperl explicitly, but they may not add any strange
2079 * arguments beyond what #! says if they do invoke suidperl that way.
2081 len = strlen(validarg);
2082 if (strEQ(validarg," PHOOEY ") ||
2083 strnNE(s,validarg,len) || !isSPACE(s[len]))
2084 croak("Args must match #! line");
2087 if (euid != uid && (statbuf.st_mode & S_ISUID) &&
2088 euid == statbuf.st_uid)
2090 croak("YOU HAVEN'T DISABLED SET-ID SCRIPTS IN THE KERNEL YET!\n\
2091 FIX YOUR KERNEL, PUT A C WRAPPER AROUND THIS SCRIPT, OR USE -u AND UNDUMP!\n");
2092 #endif /* IAMSUID */
2094 if (euid) { /* oops, we're not the setuid root perl */
2095 (void)PerlIO_close(rsfp);
2098 PerlProc_execv(form("%s/sperl%s", BIN_EXP, patchlevel), origargv);
2100 croak("Can't do setuid\n");
2103 if (statbuf.st_mode & S_ISGID && statbuf.st_gid != egid) {
2105 (void)setegid(statbuf.st_gid);
2108 (void)setregid((Gid_t)-1,statbuf.st_gid);
2110 #ifdef HAS_SETRESGID
2111 (void)setresgid((Gid_t)-1,statbuf.st_gid,(Gid_t)-1);
2113 PerlProc_setgid(statbuf.st_gid);
2117 if (PerlProc_getegid() != statbuf.st_gid)
2118 croak("Can't do setegid!\n");
2120 if (statbuf.st_mode & S_ISUID) {
2121 if (statbuf.st_uid != euid)
2123 (void)seteuid(statbuf.st_uid); /* all that for this */
2126 (void)setreuid((Uid_t)-1,statbuf.st_uid);
2128 #ifdef HAS_SETRESUID
2129 (void)setresuid((Uid_t)-1,statbuf.st_uid,(Uid_t)-1);
2131 PerlProc_setuid(statbuf.st_uid);
2135 if (PerlProc_geteuid() != statbuf.st_uid)
2136 croak("Can't do seteuid!\n");
2138 else if (uid) { /* oops, mustn't run as root */
2140 (void)seteuid((Uid_t)uid);
2143 (void)setreuid((Uid_t)-1,(Uid_t)uid);
2145 #ifdef HAS_SETRESUID
2146 (void)setresuid((Uid_t)-1,(Uid_t)uid,(Uid_t)-1);
2148 PerlProc_setuid((Uid_t)uid);
2152 if (PerlProc_geteuid() != uid)
2153 croak("Can't do seteuid!\n");
2156 if (!cando(S_IXUSR,TRUE,&statbuf))
2157 croak("Permission denied\n"); /* they can't do this */
2160 else if (preprocess)
2161 croak("-P not allowed for setuid/setgid script\n");
2162 else if (fdscript >= 0)
2163 croak("fd script not allowed in suidperl\n");
2165 croak("Script is not setuid/setgid in suidperl\n");
2167 /* We absolutely must clear out any saved ids here, so we */
2168 /* exec the real perl, substituting fd script for scriptname. */
2169 /* (We pass script name as "subdir" of fd, which perl will grok.) */
2170 PerlIO_rewind(rsfp);
2171 PerlLIO_lseek(PerlIO_fileno(rsfp),(Off_t)0,0); /* just in case rewind didn't */
2172 for (which = 1; origargv[which] && origargv[which] != scriptname; which++) ;
2173 if (!origargv[which])
2174 croak("Permission denied");
2175 origargv[which] = savepv(form("/dev/fd/%d/%s",
2176 PerlIO_fileno(rsfp), origargv[which]));
2177 #if defined(HAS_FCNTL) && defined(F_SETFD)
2178 fcntl(PerlIO_fileno(rsfp),F_SETFD,0); /* ensure no close-on-exec */
2180 PerlProc_execv(form("%s/perl%s", BIN_EXP, patchlevel), origargv); /* try again */
2181 croak("Can't do setuid\n");
2182 #endif /* IAMSUID */
2184 if (euid != uid || egid != gid) { /* (suidperl doesn't exist, in fact) */
2185 #ifndef SETUID_SCRIPTS_ARE_SECURE_NOW
2187 PerlLIO_fstat(PerlIO_fileno(rsfp),&statbuf); /* may be either wrapped or real suid */
2188 if ((euid != uid && euid == statbuf.st_uid && statbuf.st_mode & S_ISUID)
2190 (egid != gid && egid == statbuf.st_gid && statbuf.st_mode & S_ISGID)
2193 croak("YOU HAVEN'T DISABLED SET-ID SCRIPTS IN THE KERNEL YET!\n\
2194 FIX YOUR KERNEL, PUT A C WRAPPER AROUND THIS SCRIPT, OR USE -u AND UNDUMP!\n");
2195 #endif /* SETUID_SCRIPTS_ARE_SECURE_NOW */
2196 /* not set-id, must be wrapped */
2202 find_beginning(void)
2204 register char *s, *s2;
2206 /* skip forward in input to the real script? */
2210 if ((s = sv_gets(linestr, rsfp, 0)) == Nullch)
2211 croak("No Perl script found in input\n");
2212 if (*s == '#' && s[1] == '!' && (s = instr(s,"perl"))) {
2213 PerlIO_ungetc(rsfp, '\n'); /* to keep line count right */
2215 while (*s && !(isSPACE (*s) || *s == '#')) s++;
2217 while (*s == ' ' || *s == '\t') s++;
2219 while (isDIGIT(s2[-1]) || strchr("-._", s2[-1])) s2--;
2220 if (strnEQ(s2-4,"perl",4))
2222 while (s = moreswitches(s)) ;
2224 if (cddir && PerlDir_chdir(cddir) < 0)
2225 croak("Can't chdir to %s",cddir);
2234 uid = (int)PerlProc_getuid();
2235 euid = (int)PerlProc_geteuid();
2236 gid = (int)PerlProc_getgid();
2237 egid = (int)PerlProc_getegid();
2242 tainting |= (uid && (euid != uid || egid != gid));
2246 forbid_setid(char *s)
2249 croak("No %s allowed while running setuid", s);
2251 croak("No %s allowed while running setgid", s);
2258 curstash = debstash;
2259 dbargs = GvAV(gv_AVadd((gv_fetchpv("args", GV_ADDMULTI, SVt_PVAV))));
2261 DBgv = gv_fetchpv("DB", GV_ADDMULTI, SVt_PVGV);
2262 DBline = gv_fetchpv("dbline", GV_ADDMULTI, SVt_PVAV);
2263 DBsub = gv_HVadd(gv_fetchpv("sub", GV_ADDMULTI, SVt_PVHV));
2264 DBsingle = GvSV((gv_fetchpv("single", GV_ADDMULTI, SVt_PV)));
2265 sv_setiv(DBsingle, 0);
2266 DBtrace = GvSV((gv_fetchpv("trace", GV_ADDMULTI, SVt_PV)));
2267 sv_setiv(DBtrace, 0);
2268 DBsignal = GvSV((gv_fetchpv("signal", GV_ADDMULTI, SVt_PV)));
2269 sv_setiv(DBsignal, 0);
2270 curstash = defstash;
2273 #ifndef STRESS_REALLOC
2274 #define REASONABLE(size) (size)
2276 #define REASONABLE(size) (1) /* unreasonable */
2280 init_stacks(ARGSproto)
2282 /* start with 128-item stack and 8K cxstack */
2283 curstackinfo = new_stackinfo(REASONABLE(128),
2284 REASONABLE(8192/sizeof(PERL_CONTEXT) - 1));
2285 curstackinfo->si_type = SI_MAIN;
2286 curstack = curstackinfo->si_stack;
2287 mainstack = curstack; /* remember in case we switch stacks */
2289 stack_base = AvARRAY(curstack);
2290 stack_sp = stack_base;
2291 stack_max = stack_base + AvMAX(curstack);
2293 New(50,tmps_stack,REASONABLE(128),SV*);
2296 tmps_max = REASONABLE(128);
2299 * The following stacks almost certainly should be per-interpreter,
2300 * but for now they're not. XXX
2304 markstack_ptr = markstack;
2306 New(54,markstack,REASONABLE(32),I32);
2307 markstack_ptr = markstack;
2308 markstack_max = markstack + REASONABLE(32);
2316 New(54,scopestack,REASONABLE(32),I32);
2318 scopestack_max = REASONABLE(32);
2324 New(54,savestack,REASONABLE(128),ANY);
2326 savestack_max = REASONABLE(128);
2332 New(54,retstack,REASONABLE(16),OP*);
2334 retstack_max = REASONABLE(16);
2344 while (curstackinfo->si_next)
2345 curstackinfo = curstackinfo->si_next;
2346 while (curstackinfo) {
2347 PERL_SI *p = curstackinfo->si_prev;
2348 /* curstackinfo->si_stack got nuked by sv_free_arenas() */
2349 Safefree(curstackinfo->si_cxstack);
2350 Safefree(curstackinfo);
2353 Safefree(tmps_stack);
2361 static PerlIO *tmpfp; /* moved outside init_lexer() because of UNICOS bug */
2374 subname = newSVpv("main",4);
2378 init_predump_symbols(void)
2384 sv_setpvn(perl_get_sv("\"", TRUE), " ", 1);
2385 stdingv = gv_fetchpv("STDIN",TRUE, SVt_PVIO);
2386 GvMULTI_on(stdingv);
2387 IoIFP(GvIOp(stdingv)) = PerlIO_stdin();
2388 tmpgv = gv_fetchpv("stdin",TRUE, SVt_PV);
2390 GvIOp(tmpgv) = (IO*)SvREFCNT_inc(GvIOp(stdingv));
2392 tmpgv = gv_fetchpv("STDOUT",TRUE, SVt_PVIO);
2394 IoOFP(GvIOp(tmpgv)) = IoIFP(GvIOp(tmpgv)) = PerlIO_stdout();
2396 tmpgv = gv_fetchpv("stdout",TRUE, SVt_PV);
2398 GvIOp(tmpgv) = (IO*)SvREFCNT_inc(GvIOp(defoutgv));
2400 othergv = gv_fetchpv("STDERR",TRUE, SVt_PVIO);
2401 GvMULTI_on(othergv);
2402 IoOFP(GvIOp(othergv)) = IoIFP(GvIOp(othergv)) = PerlIO_stderr();
2403 tmpgv = gv_fetchpv("stderr",TRUE, SVt_PV);
2405 GvIOp(tmpgv) = (IO*)SvREFCNT_inc(GvIOp(othergv));
2407 statname = NEWSV(66,0); /* last filename we did stat on */
2410 osname = savepv(OSNAME);
2414 init_postdump_symbols(register int argc, register char **argv, register char **env)
2421 argc--,argv++; /* skip name of script */
2423 for (; argc > 0 && **argv == '-'; argc--,argv++) {
2426 if (argv[0][1] == '-') {
2430 if (s = strchr(argv[0], '=')) {
2432 sv_setpv(GvSV(gv_fetchpv(argv[0]+1,TRUE, SVt_PV)),s);
2435 sv_setiv(GvSV(gv_fetchpv(argv[0]+1,TRUE, SVt_PV)),1);
2438 toptarget = NEWSV(0,0);
2439 sv_upgrade(toptarget, SVt_PVFM);
2440 sv_setpvn(toptarget, "", 0);
2441 bodytarget = NEWSV(0,0);
2442 sv_upgrade(bodytarget, SVt_PVFM);
2443 sv_setpvn(bodytarget, "", 0);
2444 formtarget = bodytarget;
2447 if (tmpgv = gv_fetchpv("0",TRUE, SVt_PV)) {
2448 sv_setpv(GvSV(tmpgv),origfilename);
2449 magicname("0", "0", 1);
2451 if (tmpgv = gv_fetchpv("\030",TRUE, SVt_PV))
2452 sv_setpv(GvSV(tmpgv),origargv[0]);
2453 if (argvgv = gv_fetchpv("ARGV",TRUE, SVt_PVAV)) {
2455 (void)gv_AVadd(argvgv);
2456 av_clear(GvAVn(argvgv));
2457 for (; argc > 0; argc--,argv++) {
2458 av_push(GvAVn(argvgv),newSVpv(argv[0],0));
2461 if (envgv = gv_fetchpv("ENV",TRUE, SVt_PVHV)) {
2465 hv_magic(hv, envgv, 'E');
2466 #ifndef VMS /* VMS doesn't have environ array */
2467 /* Note that if the supplied env parameter is actually a copy
2468 of the global environ then it may now point to free'd memory
2469 if the environment has been modified since. To avoid this
2470 problem we treat env==NULL as meaning 'use the default'
2475 environ[0] = Nullch;
2476 for (; *env; env++) {
2477 if (!(s = strchr(*env,'=')))
2483 sv = newSVpv(s--,0);
2484 (void)hv_store(hv, *env, s - *env, sv, 0);
2486 #if defined(__BORLANDC__) && defined(USE_WIN32_RTL_ENV)
2487 /* Sins of the RTL. See note in my_setenv(). */
2488 (void)PerlEnv_putenv(savepv(*env));
2492 #ifdef DYNAMIC_ENV_FETCH
2493 HvNAME(hv) = savepv(ENV_HV_NAME);
2497 if (tmpgv = gv_fetchpv("$",TRUE, SVt_PV))
2498 sv_setiv(GvSV(tmpgv), (IV)getpid());
2507 s = PerlEnv_getenv("PERL5LIB");
2511 incpush(PerlEnv_getenv("PERLLIB"), FALSE);
2513 /* Treat PERL5?LIB as a possible search list logical name -- the
2514 * "natural" VMS idiom for a Unix path string. We allow each
2515 * element to be a set of |-separated directories for compatibility.
2519 if (my_trnlnm("PERL5LIB",buf,0))
2520 do { incpush(buf,TRUE); } while (my_trnlnm("PERL5LIB",buf,++idx));
2522 while (my_trnlnm("PERLLIB",buf,idx++)) incpush(buf,FALSE);
2526 /* Use the ~-expanded versions of APPLLIB (undocumented),
2527 ARCHLIB PRIVLIB SITEARCH and SITELIB
2530 incpush(APPLLIB_EXP, TRUE);
2534 incpush(ARCHLIB_EXP, FALSE);
2537 #define PRIVLIB_EXP "/usr/local/lib/perl5:/usr/local/lib/perl"
2540 incpush(PRIVLIB_EXP, TRUE);
2542 incpush(PRIVLIB_EXP, FALSE);
2546 incpush(SITEARCH_EXP, FALSE);
2550 incpush(SITELIB_EXP, TRUE);
2552 incpush(SITELIB_EXP, FALSE);
2556 incpush(".", FALSE);
2560 # define PERLLIB_SEP ';'
2563 # define PERLLIB_SEP '|'
2565 # define PERLLIB_SEP ':'
2568 #ifndef PERLLIB_MANGLE
2569 # define PERLLIB_MANGLE(s,n) (s)
2573 incpush(char *p, int addsubdirs)
2575 SV *subdir = Nullsv;
2581 subdir = NEWSV(55,0);
2582 if (!archpat_auto) {
2583 STRLEN len = (sizeof(ARCHNAME) + strlen(patchlevel)
2584 + sizeof("//auto"));
2585 New(55, archpat_auto, len, char);
2586 sprintf(archpat_auto, "/%s/%s/auto", ARCHNAME, patchlevel);
2588 for (len = sizeof(ARCHNAME) + 2;
2589 archpat_auto[len] != '\0' && archpat_auto[len] != '/'; len++)
2590 if (archpat_auto[len] == '.') archpat_auto[len] = '_';
2595 /* Break at all separators */
2597 SV *libdir = NEWSV(55,0);
2600 /* skip any consecutive separators */
2601 while ( *p == PERLLIB_SEP ) {
2602 /* Uncomment the next line for PATH semantics */
2603 /* av_push(GvAVn(incgv), newSVpv(".", 1)); */
2607 if ( (s = strchr(p, PERLLIB_SEP)) != Nullch ) {
2608 sv_setpvn(libdir, PERLLIB_MANGLE(p, (STRLEN)(s - p)),
2613 sv_setpv(libdir, PERLLIB_MANGLE(p, 0));
2614 p = Nullch; /* break out */
2618 * BEFORE pushing libdir onto @INC we may first push version- and
2619 * archname-specific sub-directories.
2622 struct stat tmpstatbuf;
2627 if ((unix = tounixspec_ts(SvPV(libdir,na),Nullch)) != Nullch) {
2629 while (unix[len-1] == '/') len--; /* Cosmetic */
2630 sv_usepvn(libdir,unix,len);
2633 PerlIO_printf(PerlIO_stderr(),
2634 "Failed to unixify @INC element \"%s\"\n",
2637 /* .../archname/version if -d .../archname/version/auto */
2638 sv_setsv(subdir, libdir);
2639 sv_catpv(subdir, archpat_auto);
2640 if (PerlLIO_stat(SvPVX(subdir), &tmpstatbuf) >= 0 &&
2641 S_ISDIR(tmpstatbuf.st_mode))
2642 av_push(GvAVn(incgv),
2643 newSVpv(SvPVX(subdir), SvCUR(subdir) - sizeof "auto"));
2645 /* .../archname if -d .../archname/auto */
2646 sv_insert(subdir, SvCUR(libdir) + sizeof(ARCHNAME),
2647 strlen(patchlevel) + 1, "", 0);
2648 if (PerlLIO_stat(SvPVX(subdir), &tmpstatbuf) >= 0 &&
2649 S_ISDIR(tmpstatbuf.st_mode))
2650 av_push(GvAVn(incgv),
2651 newSVpv(SvPVX(subdir), SvCUR(subdir) - sizeof "auto"));
2654 /* finally push this lib directory on the end of @INC */
2655 av_push(GvAVn(incgv), libdir);
2658 SvREFCNT_dec(subdir);
2662 STATIC struct perl_thread *
2665 struct perl_thread *thr;
2668 Newz(53, thr, 1, struct perl_thread);
2669 curcop = &compiling;
2670 thr->cvcache = newHV();
2671 thr->threadsv = newAV();
2672 /* thr->threadsvp is set when find_threadsv is called */
2673 thr->specific = newAV();
2674 thr->errhv = newHV();
2675 thr->flags = THRf_R_JOINABLE;
2676 MUTEX_INIT(&thr->mutex);
2677 /* Handcraft thrsv similarly to mess_sv */
2678 New(53, thrsv, 1, SV);
2679 Newz(53, xpv, 1, XPV);
2680 SvFLAGS(thrsv) = SVt_PV;
2681 SvANY(thrsv) = (void*)xpv;
2682 SvREFCNT(thrsv) = 1 << 30; /* practically infinite */
2683 SvPVX(thrsv) = (char*)thr;
2684 SvCUR_set(thrsv, sizeof(thr));
2685 SvLEN_set(thrsv, sizeof(thr));
2686 *SvEND(thrsv) = '\0'; /* in the trailing_nul field */
2690 MUTEX_LOCK(&threads_mutex);
2695 MUTEX_UNLOCK(&threads_mutex);
2697 #ifdef HAVE_THREAD_INTERN
2698 init_thread_intern(thr);
2701 #ifdef SET_THREAD_SELF
2702 SET_THREAD_SELF(thr);
2704 thr->self = pthread_self();
2705 #endif /* SET_THREAD_SELF */
2709 * These must come after the SET_THR because sv_setpvn does
2710 * SvTAINT and the taint fields require dTHR.
2712 toptarget = NEWSV(0,0);
2713 sv_upgrade(toptarget, SVt_PVFM);
2714 sv_setpvn(toptarget, "", 0);
2715 bodytarget = NEWSV(0,0);
2716 sv_upgrade(bodytarget, SVt_PVFM);
2717 sv_setpvn(bodytarget, "", 0);
2718 formtarget = bodytarget;
2719 thr->errsv = newSVpv("", 0);
2720 (void) find_threadsv("@"); /* Ensure $@ is initialised early */
2723 #endif /* USE_THREADS */
2726 call_list(I32 oldscope, AV *paramList)
2729 line_t oldline = curcop->cop_line;
2734 while (AvFILL(paramList) >= 0) {
2735 CV *cv = (CV*)av_shift(paramList);
2744 perl_call_sv((SV*)cv, G_EVAL|G_DISCARD);
2745 (void)SvPV(atsv, len);
2748 curcop = &compiling;
2749 curcop->cop_line = oldline;
2750 if (paramList == beginav)
2751 sv_catpv(atsv, "BEGIN failed--compilation aborted");
2753 sv_catpv(atsv, "END failed--cleanup aborted");
2754 while (scopestack_ix > oldscope)
2756 croak("%s", SvPVX(atsv));
2764 /* my_exit() was called */
2765 while (scopestack_ix > oldscope)
2768 curstash = defstash;
2770 call_list(oldscope, endav);
2772 curcop = &compiling;
2773 curcop->cop_line = oldline;
2775 if (paramList == beginav)
2776 croak("BEGIN failed--compilation aborted");
2778 croak("END failed--cleanup aborted");
2784 PerlIO_printf(PerlIO_stderr(), "panic: restartop\n");
2789 curcop = &compiling;
2790 curcop->cop_line = oldline;
2803 DEBUG_L(PerlIO_printf(Perl_debug_log, "my_exit: thread %p, status %lu\n",
2804 thr, (unsigned long) status));
2805 #endif /* USE_THREADS */
2814 STATUS_NATIVE_SET(status);
2821 my_failure_exit(void)
2824 if (vaxc$errno & 1) {
2825 if (STATUS_NATIVE & 1) /* fortuitiously includes "-1" */
2826 STATUS_NATIVE_SET(44);
2829 if (!vaxc$errno && errno) /* unlikely */
2830 STATUS_NATIVE_SET(44);
2832 STATUS_NATIVE_SET(vaxc$errno);
2837 STATUS_POSIX_SET(errno);
2839 exitstatus = STATUS_POSIX >> 8;
2840 if (exitstatus & 255)
2841 STATUS_POSIX_SET(exitstatus);
2843 STATUS_POSIX_SET(255);
2853 register PERL_CONTEXT *cx;
2858 SvREFCNT_dec(e_script);
2862 POPSTACK_TO(mainstack);
2863 if (cxstack_ix >= 0) {
2878 read_e_script(CPerlObj *pPerl, int idx, SV *buf_sv, int maxlen)
2880 read_e_script(int idx, SV *buf_sv, int maxlen)
2884 p = SvPVX(e_script);
2885 nl = strchr(p, '\n');
2886 nl = (nl) ? nl+1 : SvEND(e_script);
2889 sv_catpvn(buf_sv, p, nl-p);
2890 sv_chop(e_script, nl);