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 void find_beginning _((void));
74 static void forbid_setid _((char *));
75 static void incpush _((char *, int));
76 static void init_ids _((void));
77 static void init_debugger _((void));
78 static void init_lexer _((void));
79 static void init_main_stash _((void));
81 static struct perl_thread * init_main_thread _((void));
82 #endif /* USE_THREADS */
83 static void init_perllib _((void));
84 static void init_postdump_symbols _((int, char **, char **));
85 static void init_predump_symbols _((void));
86 static void my_exit_jump _((void)) __attribute__((noreturn));
87 static void nuke_stacks _((void));
88 static void open_script _((char *, bool, SV *, int *fd));
89 static void usage _((char *));
90 static void validate_suid _((char *, char*, int));
91 static I32 read_e_script _((int idx, SV *buf_sv, int maxlen));
95 CPerlObj* perl_alloc(IPerlMem* ipM, IPerlEnv* ipE, IPerlStdIO* ipStd,
96 IPerlLIO* ipLIO, IPerlDir* ipD, IPerlSock* ipS, IPerlProc* ipP)
98 CPerlObj* pPerl = new(ipM) CPerlObj(ipM, ipE, ipStd, ipLIO, ipD, ipS, ipP);
108 PerlInterpreter *sv_interp;
111 New(53, sv_interp, 1, PerlInterpreter);
114 #endif /* PERL_OBJECT */
118 CPerlObj::perl_construct(void)
120 perl_construct(register PerlInterpreter *sv_interp)
126 struct perl_thread *thr;
127 #endif /* FAKE_THREADS */
128 #endif /* USE_THREADS */
131 if (!(curinterp = sv_interp))
136 Zero(sv_interp, 1, PerlInterpreter);
139 /* Init the real globals (and main thread)? */
144 #ifdef ALLOC_THREAD_KEY
147 if (pthread_key_create(&thr_key, 0))
148 croak("panic: pthread_key_create");
150 MUTEX_INIT(&sv_mutex);
152 * Safe to use basic SV functions from now on (though
153 * not things like mortals or tainting yet).
155 MUTEX_INIT(&eval_mutex);
156 COND_INIT(&eval_cond);
157 MUTEX_INIT(&threads_mutex);
158 COND_INIT(&nthreads_cond);
159 #ifdef EMULATE_ATOMIC_REFCOUNTS
160 MUTEX_INIT(&svref_mutex);
161 #endif /* EMULATE_ATOMIC_REFCOUNTS */
163 thr = init_main_thread();
164 #endif /* USE_THREADS */
166 linestr = NEWSV(65,80);
167 sv_upgrade(linestr,SVt_PVIV);
169 if (!SvREADONLY(&sv_undef)) {
170 SvREADONLY_on(&sv_undef);
174 SvREADONLY_on(&sv_no);
176 sv_setpv(&sv_yes,Yes);
178 SvREADONLY_on(&sv_yes);
181 nrs = newSVpv("\n", 1);
182 rs = SvREFCNT_inc(nrs);
186 /* sighandlerp = sighandler; */
188 sighandlerp = sighandler;
194 * There is no way we can refer to them from Perl so close them to save
195 * space. The other alternative would be to provide STDAUX and STDPRN
198 (void)fclose(stdaux);
199 (void)fclose(stdprn);
206 perl_destruct_level = 1;
208 if(perl_destruct_level > 0)
213 lex_state = LEX_NOTPARSING;
215 start_env.je_prev = NULL;
216 start_env.je_ret = -1;
217 start_env.je_mustcatch = TRUE;
218 top_env = &start_env;
221 SET_NUMERIC_STANDARD();
222 #if defined(SUBVERSION) && SUBVERSION > 0
223 sprintf(patchlevel, "%7.5f", (double) 5
224 + ((double) PATCHLEVEL / (double) 1000)
225 + ((double) SUBVERSION / (double) 100000));
227 sprintf(patchlevel, "%5.3f", (double) 5 +
228 ((double) PATCHLEVEL / (double) 1000));
231 #if defined(LOCAL_PATCH_COUNT)
232 localpatches = local_patches; /* For possible -v */
235 PerlIO_init(); /* Hook to IO system */
237 fdpid = newAV(); /* for remembering popen pids by fd */
238 modglobal = newHV(); /* pointers to per-interpreter module globals */
241 New(51,debname,128,char);
242 New(52,debdelim,128,char);
250 CPerlObj::perl_destruct(void)
252 perl_destruct(register PerlInterpreter *sv_interp)
256 int destruct_level; /* 0=none, 1=full, 2=full with checks */
261 #endif /* USE_THREADS */
264 if (!(curinterp = sv_interp))
270 /* Pass 1 on any remaining threads: detach joinables, join zombies */
272 MUTEX_LOCK(&threads_mutex);
273 DEBUG_L(PerlIO_printf(PerlIO_stderr(),
274 "perl_destruct: waiting for %d threads...\n",
276 for (t = thr->next; t != thr; t = t->next) {
277 MUTEX_LOCK(&t->mutex);
278 switch (ThrSTATE(t)) {
281 DEBUG_L(PerlIO_printf(PerlIO_stderr(),
282 "perl_destruct: joining zombie %p\n", t));
283 ThrSETSTATE(t, THRf_DEAD);
284 MUTEX_UNLOCK(&t->mutex);
287 * The SvREFCNT_dec below may take a long time (e.g. av
288 * may contain an object scalar whose destructor gets
289 * called) so we have to unlock threads_mutex and start
292 MUTEX_UNLOCK(&threads_mutex);
294 SvREFCNT_dec((SV*)av);
295 DEBUG_L(PerlIO_printf(PerlIO_stderr(),
296 "perl_destruct: joined zombie %p OK\n", t));
298 case THRf_R_JOINABLE:
299 DEBUG_L(PerlIO_printf(PerlIO_stderr(),
300 "perl_destruct: detaching thread %p\n", t));
301 ThrSETSTATE(t, THRf_R_DETACHED);
303 * We unlock threads_mutex and t->mutex in the opposite order
304 * from which we locked them just so that DETACH won't
305 * deadlock if it panics. It's only a breach of good style
306 * not a bug since they are unlocks not locks.
308 MUTEX_UNLOCK(&threads_mutex);
310 MUTEX_UNLOCK(&t->mutex);
313 DEBUG_L(PerlIO_printf(PerlIO_stderr(),
314 "perl_destruct: ignoring %p (state %u)\n",
316 MUTEX_UNLOCK(&t->mutex);
317 /* fall through and out */
320 /* We leave the above "Pass 1" loop with threads_mutex still locked */
322 /* Pass 2 on remaining threads: wait for the thread count to drop to one */
325 DEBUG_L(PerlIO_printf(PerlIO_stderr(),
326 "perl_destruct: final wait for %d threads\n",
328 COND_WAIT(&nthreads_cond, &threads_mutex);
330 /* At this point, we're the last thread */
331 MUTEX_UNLOCK(&threads_mutex);
332 DEBUG_L(PerlIO_printf(PerlIO_stderr(), "perl_destruct: armageddon has arrived\n"));
333 MUTEX_DESTROY(&threads_mutex);
334 COND_DESTROY(&nthreads_cond);
335 #endif /* !defined(FAKE_THREADS) */
336 #endif /* USE_THREADS */
338 destruct_level = perl_destruct_level;
342 if (s = PerlEnv_getenv("PERL_DESTRUCT_LEVEL")) {
344 if (destruct_level < i)
353 /* We must account for everything. */
355 /* Destroy the main CV and syntax tree */
357 curpad = AvARRAY(comppad);
363 SvREFCNT_dec(main_cv);
368 * Try to destruct global references. We do this first so that the
369 * destructors and destructees still exist. Some sv's might remain.
370 * Non-referenced objects are on their own.
377 /* unhook hooks which will soon be, or use, destroyed data */
378 SvREFCNT_dec(warnhook);
380 SvREFCNT_dec(diehook);
382 SvREFCNT_dec(parsehook);
385 /* call exit list functions */
386 while (exitlistlen-- > 0)
387 exitlist[exitlistlen].fn(exitlist[exitlistlen].ptr);
391 if (destruct_level == 0){
393 DEBUG_P(debprofdump());
395 /* The exit() function will do everything that needs doing. */
399 /* loosen bonds of global variables */
402 (void)PerlIO_close(rsfp);
406 /* Filters for program text */
407 SvREFCNT_dec(rsfp_filters);
408 rsfp_filters = Nullav;
420 sawampersand = FALSE; /* must save all match strings */
421 sawstudy = FALSE; /* do fbm_instr on all strings */
429 SvREFCNT_dec(e_script);
433 /* magical thingies */
435 Safefree(ofs); /* $, */
438 Safefree(ors); /* $\ */
441 SvREFCNT_dec(nrs); /* $\ helper */
444 multiline = 0; /* $* */
446 SvREFCNT_dec(statname);
450 /* defgv, aka *_ should be taken care of elsewhere */
452 /* clean up after study() */
453 SvREFCNT_dec(lastscream);
455 Safefree(screamfirst);
457 Safefree(screamnext);
460 /* startup and shutdown function lists */
461 SvREFCNT_dec(beginav);
463 SvREFCNT_dec(initav);
468 /* shortcuts just get cleared */
478 /* reset so print() ends up where we expect */
481 /* Prepare to destruct main symbol table. */
488 if (destruct_level >= 2) {
489 if (scopestack_ix != 0)
490 warn("Unbalanced scopes: %ld more ENTERs than LEAVEs\n",
491 (long)scopestack_ix);
492 if (savestack_ix != 0)
493 warn("Unbalanced saves: %ld more saves than restores\n",
495 if (tmps_floor != -1)
496 warn("Unbalanced tmps: %ld more allocs than frees\n",
497 (long)tmps_floor + 1);
498 if (cxstack_ix != -1)
499 warn("Unbalanced context: %ld more PUSHes than POPs\n",
500 (long)cxstack_ix + 1);
503 /* Now absolutely destruct everything, somehow or other, loops or no. */
505 SvFLAGS(strtab) |= SVTYPEMASK; /* don't clean out strtab now */
506 while (sv_count != 0 && sv_count != last_sv_count) {
507 last_sv_count = sv_count;
510 SvFLAGS(strtab) &= ~SVTYPEMASK;
511 SvFLAGS(strtab) |= SVt_PVHV;
513 /* Destruct the global string table. */
515 /* Yell and reset the HeVAL() slots that are still holding refcounts,
516 * so that sv_free() won't fail on them.
525 array = HvARRAY(strtab);
529 warn("Unbalanced string table refcount: (%d) for \"%s\"",
530 HeVAL(hent) - Nullsv, HeKEY(hent));
531 HeVAL(hent) = Nullsv;
541 SvREFCNT_dec(strtab);
544 warn("Scalars leaked: %ld\n", (long)sv_count);
548 /* No SVs have survived, need to clean out */
552 Safefree(origfilename);
554 hints = 0; /* Reset hints. Should hints be per-interpreter ? */
556 DEBUG_P(debprofdump());
558 MUTEX_DESTROY(&sv_mutex);
559 MUTEX_DESTROY(&eval_mutex);
560 COND_DESTROY(&eval_cond);
562 /* As the penultimate thing, free the non-arena SV for thrsv */
563 Safefree(SvPVX(thrsv));
564 Safefree(SvANY(thrsv));
567 #endif /* USE_THREADS */
569 /* As the absolutely last thing, free the non-arena SV for mess() */
572 /* we know that type >= SVt_PV */
574 Safefree(SvPVX(mess_sv));
575 Safefree(SvANY(mess_sv));
583 CPerlObj::perl_free(void)
585 perl_free(PerlInterpreter *sv_interp)
591 if (!(curinterp = sv_interp))
598 perl_atexit(void (*fn) (void *), void *ptr)
600 Renew(exitlist, exitlistlen+1, PerlExitListEntry);
601 exitlist[exitlistlen].fn = fn;
602 exitlist[exitlistlen].ptr = ptr;
608 CPerlObj::perl_parse(void (*xsinit) (CPerlObj*), int argc, char **argv, char **env)
610 perl_parse(PerlInterpreter *sv_interp, void (*xsinit) (void), int argc, char **argv, char **env)
616 char *scriptname = NULL;
617 VOL bool dosearch = FALSE;
625 #ifdef SETUID_SCRIPTS_ARE_SECURE_NOW
628 croak("suidperl is no longer needed since the kernel can now execute\n\
629 setuid perl scripts securely.\n");
634 if (!(curinterp = sv_interp))
638 #if defined(NeXT) && defined(__DYNAMIC__)
639 _dyld_lookup_and_bind
640 ("__environ", (unsigned long *) &environ_pointer, NULL);
645 #ifndef VMS /* VMS doesn't have environ array */
646 origenviron = environ;
651 /* Come here if running an undumped a.out. */
653 origfilename = savepv(argv[0]);
655 cxstack_ix = -1; /* start label stack again */
657 init_postdump_symbols(argc,argv,env);
662 curpad = AvARRAY(comppad);
667 SvREFCNT_dec(main_cv);
671 oldscope = scopestack_ix;
679 /* my_exit() was called */
680 while (scopestack_ix > oldscope)
685 call_list(oldscope, endav);
687 return STATUS_NATIVE_EXPORT;
690 PerlIO_printf(PerlIO_stderr(), "panic: top_env\n");
694 sv_setpvn(linestr,"",0);
695 sv = newSVpv("",0); /* first used for -I flags */
699 for (argc--,argv++; argc > 0; argc--,argv++) {
700 if (argv[0][0] != '-' || !argv[0][1])
704 validarg = " PHOOEY ";
730 if (s = moreswitches(s))
740 if (euid != uid || egid != gid)
741 croak("No -e allowed in setuid scripts");
743 e_script = newSVpv("",0);
744 filter_add(read_e_script, NULL);
747 sv_catpv(e_script, s);
749 sv_catpv(e_script, argv[1]);
753 croak("No code specified for -e");
754 sv_catpv(e_script, "\n");
757 case 'I': /* -I handled both here and in moreswitches() */
759 if (!*++s && (s=argv[1]) != Nullch) {
762 while (s && isSPACE(*s))
766 for (e = s; *e && !isSPACE(*e); e++) ;
773 } /* XXX else croak? */
787 preambleav = newAV();
788 av_push(preambleav, newSVpv("use Config qw(myconfig config_vars)",0));
790 Sv = newSVpv("print myconfig();",0);
792 sv_catpv(Sv,"print \"\\nCharacteristics of this PERLSHR image: \\n\",");
794 sv_catpv(Sv,"print \"\\nCharacteristics of this binary (from libperl): \\n\",");
796 #if defined(DEBUGGING) || defined(NO_EMBED) || defined(MULTIPLICITY)
797 sv_catpv(Sv,"\" Compile-time options:");
799 sv_catpv(Sv," DEBUGGING");
802 sv_catpv(Sv," NO_EMBED");
805 sv_catpv(Sv," MULTIPLICITY");
807 sv_catpv(Sv,"\\n\",");
809 #if defined(LOCAL_PATCH_COUNT)
810 if (LOCAL_PATCH_COUNT > 0) {
812 sv_catpv(Sv,"\" Locally applied patches:\\n\",");
813 for (i = 1; i <= LOCAL_PATCH_COUNT; i++) {
815 sv_catpvf(Sv,"\" \\t%s\\n\",",localpatches[i]);
819 sv_catpvf(Sv,"\" Built under %s\\n\"",OSNAME);
822 sv_catpvf(Sv,",\" Compiled at %s %s\\n\"",__DATE__,__TIME__);
824 sv_catpvf(Sv,",\" Compiled on %s\\n\"",__DATE__);
829 @env = map { \"$_=\\\"$ENV{$_}\\\"\" } sort grep {/^PERL/} keys %ENV; \
830 print \" \\%ENV:\\n @env\\n\" if @env; \
831 print \" \\@INC:\\n @INC\\n\";");
834 Sv = newSVpv("config_vars(qw(",0);
839 av_push(preambleav, Sv);
840 scriptname = BIT_BUCKET; /* don't look for script or read stdin */
851 if (!*++s || isSPACE(*s)) {
855 /* catch use of gnu style long options */
856 if (strEQ(s, "version")) {
860 if (strEQ(s, "help")) {
867 croak("Unrecognized switch: -%s (-h will show valid options)",s);
872 if (!tainting && (s = PerlEnv_getenv("PERL5OPT"))) {
883 if (!strchr("DIMUdmw", *s))
884 croak("Illegal switch in PERL5OPT: -%c", *s);
890 scriptname = argv[0];
893 scriptname = BIT_BUCKET; /* don't look for script or read stdin */
895 else if (scriptname == Nullch) {
897 if ( PerlLIO_isatty(PerlIO_fileno(PerlIO_stdin())) )
905 open_script(scriptname,dosearch,sv,&fdscript);
907 validate_suid(validarg, scriptname,fdscript);
912 main_cv = compcv = (CV*)NEWSV(1104,0);
913 sv_upgrade((SV *)compcv, SVt_PVCV);
917 av_push(comppad, Nullsv);
918 curpad = AvARRAY(comppad);
919 comppad_name = newAV();
920 comppad_name_fill = 0;
921 min_intro_pending = 0;
924 av_store(comppad_name, 0, newSVpv("@_", 2));
925 curpad[0] = (SV*)newAV();
926 SvPADMY_on(curpad[0]); /* XXX Needed? */
928 New(666, CvMUTEXP(compcv), 1, perl_mutex);
929 MUTEX_INIT(CvMUTEXP(compcv));
930 #endif /* USE_THREADS */
932 comppadlist = newAV();
933 AvREAL_off(comppadlist);
934 av_store(comppadlist, 0, (SV*)comppad_name);
935 av_store(comppadlist, 1, (SV*)comppad);
936 CvPADLIST(compcv) = comppadlist;
938 boot_core_UNIVERSAL();
941 (*xsinit)(THIS); /* in case linked C routines want magical variables */
942 #if defined(VMS) || defined(WIN32) || defined(DJGPP)
946 init_predump_symbols();
947 /* init_postdump_symbols not currently designed to be called */
948 /* more than once (ENV isn't cleared first, for example) */
949 /* But running with -u leaves %ENV & @ARGV undefined! XXX */
951 init_postdump_symbols(argc,argv,env);
955 /* now parse the script */
957 SETERRNO(0,SS$_NORMAL);
959 if (yyparse() || error_count) {
961 croak("%s had compilation errors.\n", origfilename);
963 croak("Execution of %s aborted due to compilation errors.\n",
967 curcop->cop_line = 0;
971 SvREFCNT_dec(e_script);
975 /* now that script is parsed, we can modify record separator */
977 rs = SvREFCNT_inc(nrs);
978 sv_setsv(perl_get_sv("/", TRUE), rs);
989 if ((s=PerlEnv_getenv("PERL_DEBUG_MSTATS")) && atoi(s) >= 2)
990 dump_mstats("after compilation:");
1001 CPerlObj::perl_run(void)
1003 perl_run(PerlInterpreter *sv_interp)
1012 if (!(curinterp = sv_interp))
1016 oldscope = scopestack_ix;
1021 cxstack_ix = -1; /* start context stack again */
1024 /* my_exit() was called */
1025 while (scopestack_ix > oldscope)
1028 curstash = defstash;
1030 call_list(oldscope, endav);
1032 if (PerlEnv_getenv("PERL_DEBUG_MSTATS"))
1033 dump_mstats("after execution: ");
1036 return STATUS_NATIVE_EXPORT;
1039 PerlIO_printf(PerlIO_stderr(), "panic: restartop\n");
1044 POPSTACK_TO(mainstack);
1048 DEBUG_r(PerlIO_printf(Perl_debug_log, "%s $` $& $' support.\n",
1049 sawampersand ? "Enabling" : "Omitting"));
1052 DEBUG_x(dump_all());
1053 DEBUG(PerlIO_printf(Perl_debug_log, "\nEXECUTING...\n\n"));
1055 DEBUG_L(PerlIO_printf(Perl_debug_log, "main thread is 0x%lx\n",
1056 (unsigned long) thr));
1057 #endif /* USE_THREADS */
1060 PerlIO_printf(PerlIO_stderr(), "%s syntax OK\n", origfilename);
1063 if (PERLDB_SINGLE && DBsingle)
1064 sv_setiv(DBsingle, 1);
1066 call_list(oldscope, initav);
1076 else if (main_start) {
1077 CvDEPTH(main_cv) = 1;
1088 perl_get_sv(char *name, I32 create)
1092 if (name[1] == '\0' && !isALPHA(name[0])) {
1093 PADOFFSET tmp = find_threadsv(name);
1094 if (tmp != NOT_IN_PAD) {
1096 return THREADSV(tmp);
1099 #endif /* USE_THREADS */
1100 gv = gv_fetchpv(name, create, SVt_PV);
1107 perl_get_av(char *name, I32 create)
1109 GV* gv = gv_fetchpv(name, create, SVt_PVAV);
1118 perl_get_hv(char *name, I32 create)
1120 GV* gv = gv_fetchpv(name, create, SVt_PVHV);
1129 perl_get_cv(char *name, I32 create)
1131 GV* gv = gv_fetchpv(name, create, SVt_PVCV);
1132 if (create && !GvCVu(gv))
1133 return newSUB(start_subparse(FALSE, 0),
1134 newSVOP(OP_CONST, 0, newSVpv(name,0)),
1142 /* Be sure to refetch the stack pointer after calling these routines. */
1145 perl_call_argv(char *sub_name, I32 flags, register char **argv)
1147 /* See G_* flags in cop.h */
1148 /* null terminated arg list */
1155 XPUSHs(sv_2mortal(newSVpv(*argv,0)));
1160 return perl_call_pv(sub_name, flags);
1164 perl_call_pv(char *sub_name, I32 flags)
1165 /* name of the subroutine */
1166 /* See G_* flags in cop.h */
1168 return perl_call_sv((SV*)perl_get_cv(sub_name, TRUE), flags);
1172 perl_call_method(char *methname, I32 flags)
1173 /* name of the subroutine */
1174 /* See G_* flags in cop.h */
1180 XPUSHs(sv_2mortal(newSVpv(methname,0)));
1185 return perl_call_sv(*stack_sp--, flags);
1188 /* May be called with any of a CV, a GV, or an SV containing the name. */
1190 perl_call_sv(SV *sv, I32 flags)
1192 /* See G_* flags in cop.h */
1195 LOGOP myop; /* fake syntax tree node */
1199 bool oldcatch = CATCH_GET;
1204 if (flags & G_DISCARD) {
1209 Zero(&myop, 1, LOGOP);
1210 myop.op_next = Nullop;
1211 if (!(flags & G_NOARGS))
1212 myop.op_flags |= OPf_STACKED;
1213 myop.op_flags |= ((flags & G_VOID) ? OPf_WANT_VOID :
1214 (flags & G_ARRAY) ? OPf_WANT_LIST :
1219 EXTEND(stack_sp, 1);
1222 oldscope = scopestack_ix;
1224 if (PERLDB_SUB && curstash != debstash
1225 /* Handle first BEGIN of -d. */
1226 && (DBcv || (DBcv = GvCV(DBsub)))
1227 /* Try harder, since this may have been a sighandler, thus
1228 * curstash may be meaningless. */
1229 && (SvTYPE(sv) != SVt_PVCV || CvSTASH((CV*)sv) != debstash)
1230 && !(flags & G_NODEBUG))
1231 op->op_private |= OPpENTERSUB_DB;
1233 if (flags & G_EVAL) {
1234 cLOGOP->op_other = op;
1236 /* we're trying to emulate pp_entertry() here */
1238 register PERL_CONTEXT *cx;
1239 I32 gimme = GIMME_V;
1244 push_return(op->op_next);
1245 PUSHBLOCK(cx, CXt_EVAL, stack_sp);
1247 eval_root = op; /* Only needed so that goto works right. */
1250 if (flags & G_KEEPERR)
1265 /* my_exit() was called */
1266 curstash = defstash;
1270 croak("Callback called exit");
1279 stack_sp = stack_base + oldmark;
1280 if (flags & G_ARRAY)
1284 *++stack_sp = &sv_undef;
1292 if (op == (OP*)&myop)
1293 op = pp_entersub(ARGS);
1296 retval = stack_sp - (stack_base + oldmark);
1297 if ((flags & G_EVAL) && !(flags & G_KEEPERR))
1301 if (flags & G_EVAL) {
1302 if (scopestack_ix > oldscope) {
1306 register PERL_CONTEXT *cx;
1318 CATCH_SET(oldcatch);
1320 if (flags & G_DISCARD) {
1321 stack_sp = stack_base + oldmark;
1330 /* Eval a string. The G_EVAL flag is always assumed. */
1333 perl_eval_sv(SV *sv, I32 flags)
1335 /* See G_* flags in cop.h */
1338 UNOP myop; /* fake syntax tree node */
1339 I32 oldmark = SP - stack_base;
1346 if (flags & G_DISCARD) {
1354 EXTEND(stack_sp, 1);
1356 oldscope = scopestack_ix;
1358 if (!(flags & G_NOARGS))
1359 myop.op_flags = OPf_STACKED;
1360 myop.op_next = Nullop;
1361 myop.op_type = OP_ENTEREVAL;
1362 myop.op_flags |= ((flags & G_VOID) ? OPf_WANT_VOID :
1363 (flags & G_ARRAY) ? OPf_WANT_LIST :
1365 if (flags & G_KEEPERR)
1366 myop.op_flags |= OPf_SPECIAL;
1376 /* my_exit() was called */
1377 curstash = defstash;
1381 croak("Callback called exit");
1390 stack_sp = stack_base + oldmark;
1391 if (flags & G_ARRAY)
1395 *++stack_sp = &sv_undef;
1400 if (op == (OP*)&myop)
1401 op = pp_entereval(ARGS);
1404 retval = stack_sp - (stack_base + oldmark);
1405 if (!(flags & G_KEEPERR))
1410 if (flags & G_DISCARD) {
1411 stack_sp = stack_base + oldmark;
1421 perl_eval_pv(char *p, I32 croak_on_error)
1424 SV* sv = newSVpv(p, 0);
1427 perl_eval_sv(sv, G_SCALAR);
1434 if (croak_on_error && SvTRUE(ERRSV))
1435 croak(SvPVx(ERRSV, na));
1440 /* Require a module. */
1443 perl_require_pv(char *pv)
1445 SV* sv = sv_newmortal();
1446 sv_setpv(sv, "require '");
1449 perl_eval_sv(sv, G_DISCARD);
1453 magicname(char *sym, char *name, I32 namlen)
1457 if (gv = gv_fetchpv(sym,TRUE, SVt_PV))
1458 sv_magic(GvSV(gv), (SV*)gv, 0, name, namlen);
1462 usage(char *name) /* XXX move this out into a module ? */
1465 /* This message really ought to be max 23 lines.
1466 * Removed -h because the user already knows that opton. Others? */
1468 static char *usage_msg[] = {
1469 "-0[octal] specify record separator (\\0, if no argument)",
1470 "-a autosplit mode with -n or -p (splits $_ into @F)",
1471 "-c check syntax only (runs BEGIN and END blocks)",
1472 "-d[:debugger] run scripts under debugger",
1473 "-D[number/list] set debugging flags (argument is a bit mask or flags)",
1474 "-e 'command' one line of script. Several -e's allowed. Omit [programfile].",
1475 "-F/pattern/ split() pattern for autosplit (-a). The //'s are optional.",
1476 "-i[extension] edit <> files in place (make backup if extension supplied)",
1477 "-Idirectory specify @INC/#include directory (may be used more than once)",
1478 "-l[octal] enable line ending processing, specifies line terminator",
1479 "-[mM][-]module.. executes `use/no module...' before executing your script.",
1480 "-n assume 'while (<>) { ... }' loop around your script",
1481 "-p assume loop like -n but print line also like sed",
1482 "-P run script through C preprocessor before compilation",
1483 "-s enable some switch parsing for switches after script name",
1484 "-S look for the script using PATH environment variable",
1485 "-T turn on tainting checks",
1486 "-u dump core after parsing script",
1487 "-U allow unsafe operations",
1488 "-v print version number, patchlevel plus VERY IMPORTANT perl info",
1489 "-V[:variable] print perl configuration information",
1490 "-w TURN WARNINGS ON FOR COMPILATION OF YOUR SCRIPT. Recommended.",
1491 "-x[directory] strip off text before #!perl line and perhaps cd to directory",
1495 char **p = usage_msg;
1497 printf("\nUsage: %s [switches] [--] [programfile] [arguments]", name);
1499 printf("\n %s", *p++);
1502 /* This routine handles any switches that can be given during run */
1505 moreswitches(char *s)
1514 rschar = scan_oct(s, 4, &numlen);
1516 if (rschar & ~((U8)~0))
1518 else if (!rschar && numlen >= 2)
1519 nrs = newSVpv("", 0);
1522 nrs = newSVpv(&ch, 1);
1528 splitstr = savepv(s + 1);
1542 if (*s == ':' || *s == '=') {
1543 my_setenv("PERL5DB", form("use Devel::%s;", ++s));
1547 perldb = PERLDB_ALL;
1554 if (isALPHA(s[1])) {
1555 static char debopts[] = "psltocPmfrxuLHXD";
1558 for (s++; *s && (d = strchr(debopts,*s)); s++)
1559 debug |= 1 << (d - debopts);
1563 for (s++; isDIGIT(*s); s++) ;
1565 debug |= 0x80000000;
1567 warn("Recompile perl with -DDEBUGGING to use -D switch\n");
1568 for (s++; isALNUM(*s); s++) ;
1578 inplace = savepv(s+1);
1580 for (s = inplace; *s && !isSPACE(*s); s++) ;
1583 if (*s == '-') /* Additional switches on #! line. */
1587 case 'I': /* -I handled both here and in parse_perl() */
1590 while (*s && isSPACE(*s))
1594 for (e = s; *e && !isSPACE(*e); e++) ;
1595 p = savepvn(s, e-s);
1601 croak("No space allowed after -I");
1611 *ors = scan_oct(s, 3 + (*s == '0'), &numlen);
1621 ors = SvPV(nrs, orslen);
1622 ors = savepvn(ors, orslen);
1626 forbid_setid("-M"); /* XXX ? */
1629 forbid_setid("-m"); /* XXX ? */
1634 /* -M-foo == 'no foo' */
1635 if (*s == '-') { use = "no "; ++s; }
1636 sv = newSVpv(use,0);
1638 /* We allow -M'Module qw(Foo Bar)' */
1639 while(isALNUM(*s) || *s==':') ++s;
1641 sv_catpv(sv, start);
1642 if (*(start-1) == 'm') {
1644 croak("Can't use '%c' after -mname", *s);
1645 sv_catpv( sv, " ()");
1648 sv_catpvn(sv, start, s-start);
1649 sv_catpv(sv, " split(/,/,q{");
1654 if (preambleav == NULL)
1655 preambleav = newAV();
1656 av_push(preambleav, sv);
1659 croak("No space allowed after -%c", *(s-1));
1676 croak("Too late for \"-T\" option");
1688 #if defined(SUBVERSION) && SUBVERSION > 0
1689 printf("\nThis is perl, version 5.%03d_%02d built for %s",
1690 PATCHLEVEL, SUBVERSION, ARCHNAME);
1692 printf("\nThis is perl, version %s built for %s",
1693 patchlevel, ARCHNAME);
1695 #if defined(LOCAL_PATCH_COUNT)
1696 if (LOCAL_PATCH_COUNT > 0)
1697 printf("\n(with %d registered patch%s, see perl -V for more detail)",
1698 LOCAL_PATCH_COUNT, (LOCAL_PATCH_COUNT!=1) ? "es" : "");
1701 printf("\n\nCopyright 1987-1998, Larry Wall\n");
1703 printf("\nMS-DOS port Copyright (c) 1989, 1990, Diomidis Spinellis\n");
1706 printf("djgpp v2 port (jpl5003c) by Hirofumi Watanabe, 1996\n");
1707 printf("djgpp v2 port (perl5004+) by Laszlo Molnar, 1997-1998\n");
1710 printf("\n\nOS/2 port Copyright (c) 1990, 1991, Raymond Chen, Kai Uwe Rommel\n"
1711 "Version 5 port Copyright (c) 1994-1998, Andreas Kaiser, Ilya Zakharevich\n");
1714 printf("atariST series port, ++jrb bammi@cadence.com\n");
1717 Perl may be copied only under the terms of either the Artistic License or the\n\
1718 GNU General Public License, which may be found in the Perl 5.0 source kit.\n\n\
1719 Complete documentation for Perl, including FAQ lists, should be found on\n\
1720 this system using `man perl' or `perldoc perl'. If you have access to the\n\
1721 Internet, point your browser at http://www.perl.com/, the Perl Home Page.\n\n");
1729 if (s[1] == '-') /* Additional switches on #! line. */
1740 #ifdef ALTERNATE_SHEBANG
1741 case 'S': /* OS/2 needs -S on "extproc" line. */
1749 croak("Can't emulate -%.1s on #! line",s);
1754 /* compliments of Tom Christiansen */
1756 /* unexec() can be found in the Gnu emacs distribution */
1757 /* Known to work with -DUNEXEC and using unexelf.c from GNU emacs-20.2 */
1768 prog = newSVpv(BIN_EXP, 0);
1769 sv_catpv(prog, "/perl");
1770 file = newSVpv(origfilename, 0);
1771 sv_catpv(file, ".perldump");
1773 unexec(SvPVX(file), SvPVX(prog), &etext, sbrk(0), 0);
1774 /* unexec prints msg to stderr in case of failure */
1775 PerlProc_exit(status);
1778 # include <lib$routines.h>
1779 lib$signal(SS$_DEBUG); /* ssdef.h #included from vmsish.h */
1781 ABORT(); /* for use with undump */
1787 init_main_stash(void)
1792 /* Note that strtab is a rather special HV. Assumptions are made
1793 about not iterating on it, and not adding tie magic to it.
1794 It is properly deallocated in perl_destruct() */
1796 HvSHAREKEYS_off(strtab); /* mandatory */
1797 Newz(506,((XPVHV*)SvANY(strtab))->xhv_array,
1798 sizeof(HE*) * (((XPVHV*)SvANY(strtab))->xhv_max + 1), char);
1800 curstash = defstash = newHV();
1801 curstname = newSVpv("main",4);
1802 gv = gv_fetchpv("main::",TRUE, SVt_PVHV);
1803 SvREFCNT_dec(GvHV(gv));
1804 GvHV(gv) = (HV*)SvREFCNT_inc(defstash);
1806 HvNAME(defstash) = savepv("main");
1807 incgv = gv_HVadd(gv_AVadd(gv_fetchpv("INC",TRUE, SVt_PVAV)));
1809 defgv = gv_fetchpv("_",TRUE, SVt_PVAV);
1810 errgv = gv_HVadd(gv_fetchpv("@", TRUE, SVt_PV));
1812 (void)form("%240s",""); /* Preallocate temp - for immediate signals. */
1813 sv_grow(ERRSV, 240); /* Preallocate - for immediate signals. */
1814 sv_setpvn(ERRSV, "", 0);
1815 curstash = defstash;
1816 compiling.cop_stash = defstash;
1817 debstash = GvHV(gv_fetchpv("DB::", GV_ADDMULTI, SVt_PVHV));
1818 globalstash = GvHV(gv_fetchpv("CORE::GLOBAL::", GV_ADDMULTI, SVt_PVHV));
1819 /* We must init $/ before switches are processed. */
1820 sv_setpvn(GvSV(gv_fetchpv("/", TRUE, SVt_PV)), "\n", 1);
1824 open_script(char *scriptname, bool dosearch, SV *sv, int *fdscript)
1829 scriptname = find_script(scriptname, dosearch, NULL, 0);
1831 if (strnEQ(scriptname, "/dev/fd/", 8) && isDIGIT(scriptname[8]) ) {
1832 char *s = scriptname + 8;
1833 *fdscript = atoi(s);
1841 origfilename = savepv(e_script ? "-e" : scriptname);
1842 curcop->cop_filegv = gv_fetchfile(origfilename);
1843 if (strEQ(origfilename,"-"))
1845 if (*fdscript >= 0) {
1846 rsfp = PerlIO_fdopen(*fdscript,PERL_SCRIPT_MODE);
1847 #if defined(HAS_FCNTL) && defined(F_SETFD)
1849 fcntl(PerlIO_fileno(rsfp),F_SETFD,1); /* ensure close-on-exec */
1852 else if (preprocess) {
1853 char *cpp_cfg = CPPSTDIN;
1854 SV *cpp = NEWSV(0,0);
1855 SV *cmd = NEWSV(0,0);
1857 if (strEQ(cpp_cfg, "cppstdin"))
1858 sv_catpvf(cpp, "%s/", BIN_EXP);
1859 sv_catpv(cpp, cpp_cfg);
1862 sv_catpv(sv,PRIVLIB_EXP);
1866 sed %s -e \"/^[^#]/b\" \
1867 -e \"/^#[ ]*include[ ]/b\" \
1868 -e \"/^#[ ]*define[ ]/b\" \
1869 -e \"/^#[ ]*if[ ]/b\" \
1870 -e \"/^#[ ]*ifdef[ ]/b\" \
1871 -e \"/^#[ ]*ifndef[ ]/b\" \
1872 -e \"/^#[ ]*else/b\" \
1873 -e \"/^#[ ]*elif[ ]/b\" \
1874 -e \"/^#[ ]*undef[ ]/b\" \
1875 -e \"/^#[ ]*endif/b\" \
1878 (doextract ? "-e \"1,/^#/d\n\"" : ""),
1881 %s %s -e '/^[^#]/b' \
1882 -e '/^#[ ]*include[ ]/b' \
1883 -e '/^#[ ]*define[ ]/b' \
1884 -e '/^#[ ]*if[ ]/b' \
1885 -e '/^#[ ]*ifdef[ ]/b' \
1886 -e '/^#[ ]*ifndef[ ]/b' \
1887 -e '/^#[ ]*else/b' \
1888 -e '/^#[ ]*elif[ ]/b' \
1889 -e '/^#[ ]*undef[ ]/b' \
1890 -e '/^#[ ]*endif/b' \
1898 (doextract ? "-e '1,/^#/d\n'" : ""),
1900 scriptname, cpp, sv, CPPMINUS);
1902 #ifdef IAMSUID /* actually, this is caught earlier */
1903 if (euid != uid && !euid) { /* if running suidperl */
1905 (void)seteuid(uid); /* musn't stay setuid root */
1908 (void)setreuid((Uid_t)-1, uid);
1910 #ifdef HAS_SETRESUID
1911 (void)setresuid((Uid_t)-1, uid, (Uid_t)-1);
1913 PerlProc_setuid(uid);
1917 if (PerlProc_geteuid() != uid)
1918 croak("Can't do seteuid!\n");
1920 #endif /* IAMSUID */
1921 rsfp = PerlProc_popen(SvPVX(cmd), "r");
1925 else if (!*scriptname) {
1926 forbid_setid("program input from stdin");
1927 rsfp = PerlIO_stdin();
1930 rsfp = PerlIO_open(scriptname,PERL_SCRIPT_MODE);
1931 #if defined(HAS_FCNTL) && defined(F_SETFD)
1933 fcntl(PerlIO_fileno(rsfp),F_SETFD,1); /* ensure close-on-exec */
1938 #ifndef IAMSUID /* in case script is not readable before setuid */
1939 if (euid && PerlLIO_stat(SvPVX(GvSV(curcop->cop_filegv)),&statbuf) >= 0 &&
1940 statbuf.st_mode & (S_ISUID|S_ISGID)) {
1942 PerlProc_execv(form("%s/sperl%s", BIN_EXP, patchlevel), origargv);
1943 croak("Can't do setuid\n");
1947 croak("Can't open perl script \"%s\": %s\n",
1948 SvPVX(GvSV(curcop->cop_filegv)), Strerror(errno));
1953 validate_suid(char *validarg, char *scriptname, int fdscript)
1957 /* do we need to emulate setuid on scripts? */
1959 /* This code is for those BSD systems that have setuid #! scripts disabled
1960 * in the kernel because of a security problem. Merely defining DOSUID
1961 * in perl will not fix that problem, but if you have disabled setuid
1962 * scripts in the kernel, this will attempt to emulate setuid and setgid
1963 * on scripts that have those now-otherwise-useless bits set. The setuid
1964 * root version must be called suidperl or sperlN.NNN. If regular perl
1965 * discovers that it has opened a setuid script, it calls suidperl with
1966 * the same argv that it had. If suidperl finds that the script it has
1967 * just opened is NOT setuid root, it sets the effective uid back to the
1968 * uid. We don't just make perl setuid root because that loses the
1969 * effective uid we had before invoking perl, if it was different from the
1972 * DOSUID must be defined in both perl and suidperl, and IAMSUID must
1973 * be defined in suidperl only. suidperl must be setuid root. The
1974 * Configure script will set this up for you if you want it.
1981 if (PerlLIO_fstat(PerlIO_fileno(rsfp),&statbuf) < 0) /* normal stat is insecure */
1982 croak("Can't stat script \"%s\"",origfilename);
1983 if (fdscript < 0 && statbuf.st_mode & (S_ISUID|S_ISGID)) {
1987 #ifndef HAS_SETREUID
1988 /* On this access check to make sure the directories are readable,
1989 * there is actually a small window that the user could use to make
1990 * filename point to an accessible directory. So there is a faint
1991 * chance that someone could execute a setuid script down in a
1992 * non-accessible directory. I don't know what to do about that.
1993 * But I don't think it's too important. The manual lies when
1994 * it says access() is useful in setuid programs.
1996 if (PerlLIO_access(SvPVX(GvSV(curcop->cop_filegv)),1)) /*double check*/
1997 croak("Permission denied");
1999 /* If we can swap euid and uid, then we can determine access rights
2000 * with a simple stat of the file, and then compare device and
2001 * inode to make sure we did stat() on the same file we opened.
2002 * Then we just have to make sure he or she can execute it.
2005 struct stat tmpstatbuf;
2009 setreuid(euid,uid) < 0
2012 setresuid(euid,uid,(Uid_t)-1) < 0
2015 || PerlProc_getuid() != euid || PerlProc_geteuid() != uid)
2016 croak("Can't swap uid and euid"); /* really paranoid */
2017 if (PerlLIO_stat(SvPVX(GvSV(curcop->cop_filegv)),&tmpstatbuf) < 0)
2018 croak("Permission denied"); /* testing full pathname here */
2019 if (tmpstatbuf.st_dev != statbuf.st_dev ||
2020 tmpstatbuf.st_ino != statbuf.st_ino) {
2021 (void)PerlIO_close(rsfp);
2022 if (rsfp = PerlProc_popen("/bin/mail root","w")) { /* heh, heh */
2024 "User %ld tried to run dev %ld ino %ld in place of dev %ld ino %ld!\n\
2025 (Filename of set-id script was %s, uid %ld gid %ld.)\n\nSincerely,\nperl\n",
2026 (long)uid,(long)tmpstatbuf.st_dev, (long)tmpstatbuf.st_ino,
2027 (long)statbuf.st_dev, (long)statbuf.st_ino,
2028 SvPVX(GvSV(curcop->cop_filegv)),
2029 (long)statbuf.st_uid, (long)statbuf.st_gid);
2030 (void)PerlProc_pclose(rsfp);
2032 croak("Permission denied\n");
2036 setreuid(uid,euid) < 0
2038 # if defined(HAS_SETRESUID)
2039 setresuid(uid,euid,(Uid_t)-1) < 0
2042 || PerlProc_getuid() != uid || PerlProc_geteuid() != euid)
2043 croak("Can't reswap uid and euid");
2044 if (!cando(S_IXUSR,FALSE,&statbuf)) /* can real uid exec? */
2045 croak("Permission denied\n");
2047 #endif /* HAS_SETREUID */
2048 #endif /* IAMSUID */
2050 if (!S_ISREG(statbuf.st_mode))
2051 croak("Permission denied");
2052 if (statbuf.st_mode & S_IWOTH)
2053 croak("Setuid/gid script is writable by world");
2054 doswitches = FALSE; /* -s is insecure in suid */
2056 if (sv_gets(linestr, rsfp, 0) == Nullch ||
2057 strnNE(SvPV(linestr,na),"#!",2) ) /* required even on Sys V */
2058 croak("No #! line");
2059 s = SvPV(linestr,na)+2;
2061 while (!isSPACE(*s)) s++;
2062 for (s2 = s; (s2 > SvPV(linestr,na)+2 &&
2063 (isDIGIT(s2[-1]) || strchr("._-", s2[-1]))); s2--) ;
2064 if (strnNE(s2-4,"perl",4) && strnNE(s-9,"perl",4)) /* sanity check */
2065 croak("Not a perl script");
2066 while (*s == ' ' || *s == '\t') s++;
2068 * #! arg must be what we saw above. They can invoke it by
2069 * mentioning suidperl explicitly, but they may not add any strange
2070 * arguments beyond what #! says if they do invoke suidperl that way.
2072 len = strlen(validarg);
2073 if (strEQ(validarg," PHOOEY ") ||
2074 strnNE(s,validarg,len) || !isSPACE(s[len]))
2075 croak("Args must match #! line");
2078 if (euid != uid && (statbuf.st_mode & S_ISUID) &&
2079 euid == statbuf.st_uid)
2081 croak("YOU HAVEN'T DISABLED SET-ID SCRIPTS IN THE KERNEL YET!\n\
2082 FIX YOUR KERNEL, PUT A C WRAPPER AROUND THIS SCRIPT, OR USE -u AND UNDUMP!\n");
2083 #endif /* IAMSUID */
2085 if (euid) { /* oops, we're not the setuid root perl */
2086 (void)PerlIO_close(rsfp);
2089 PerlProc_execv(form("%s/sperl%s", BIN_EXP, patchlevel), origargv);
2091 croak("Can't do setuid\n");
2094 if (statbuf.st_mode & S_ISGID && statbuf.st_gid != egid) {
2096 (void)setegid(statbuf.st_gid);
2099 (void)setregid((Gid_t)-1,statbuf.st_gid);
2101 #ifdef HAS_SETRESGID
2102 (void)setresgid((Gid_t)-1,statbuf.st_gid,(Gid_t)-1);
2104 PerlProc_setgid(statbuf.st_gid);
2108 if (PerlProc_getegid() != statbuf.st_gid)
2109 croak("Can't do setegid!\n");
2111 if (statbuf.st_mode & S_ISUID) {
2112 if (statbuf.st_uid != euid)
2114 (void)seteuid(statbuf.st_uid); /* all that for this */
2117 (void)setreuid((Uid_t)-1,statbuf.st_uid);
2119 #ifdef HAS_SETRESUID
2120 (void)setresuid((Uid_t)-1,statbuf.st_uid,(Uid_t)-1);
2122 PerlProc_setuid(statbuf.st_uid);
2126 if (PerlProc_geteuid() != statbuf.st_uid)
2127 croak("Can't do seteuid!\n");
2129 else if (uid) { /* oops, mustn't run as root */
2131 (void)seteuid((Uid_t)uid);
2134 (void)setreuid((Uid_t)-1,(Uid_t)uid);
2136 #ifdef HAS_SETRESUID
2137 (void)setresuid((Uid_t)-1,(Uid_t)uid,(Uid_t)-1);
2139 PerlProc_setuid((Uid_t)uid);
2143 if (PerlProc_geteuid() != uid)
2144 croak("Can't do seteuid!\n");
2147 if (!cando(S_IXUSR,TRUE,&statbuf))
2148 croak("Permission denied\n"); /* they can't do this */
2151 else if (preprocess)
2152 croak("-P not allowed for setuid/setgid script\n");
2153 else if (fdscript >= 0)
2154 croak("fd script not allowed in suidperl\n");
2156 croak("Script is not setuid/setgid in suidperl\n");
2158 /* We absolutely must clear out any saved ids here, so we */
2159 /* exec the real perl, substituting fd script for scriptname. */
2160 /* (We pass script name as "subdir" of fd, which perl will grok.) */
2161 PerlIO_rewind(rsfp);
2162 PerlLIO_lseek(PerlIO_fileno(rsfp),(Off_t)0,0); /* just in case rewind didn't */
2163 for (which = 1; origargv[which] && origargv[which] != scriptname; which++) ;
2164 if (!origargv[which])
2165 croak("Permission denied");
2166 origargv[which] = savepv(form("/dev/fd/%d/%s",
2167 PerlIO_fileno(rsfp), origargv[which]));
2168 #if defined(HAS_FCNTL) && defined(F_SETFD)
2169 fcntl(PerlIO_fileno(rsfp),F_SETFD,0); /* ensure no close-on-exec */
2171 PerlProc_execv(form("%s/perl%s", BIN_EXP, patchlevel), origargv); /* try again */
2172 croak("Can't do setuid\n");
2173 #endif /* IAMSUID */
2175 if (euid != uid || egid != gid) { /* (suidperl doesn't exist, in fact) */
2176 #ifndef SETUID_SCRIPTS_ARE_SECURE_NOW
2178 PerlLIO_fstat(PerlIO_fileno(rsfp),&statbuf); /* may be either wrapped or real suid */
2179 if ((euid != uid && euid == statbuf.st_uid && statbuf.st_mode & S_ISUID)
2181 (egid != gid && egid == statbuf.st_gid && statbuf.st_mode & S_ISGID)
2184 croak("YOU HAVEN'T DISABLED SET-ID SCRIPTS IN THE KERNEL YET!\n\
2185 FIX YOUR KERNEL, PUT A C WRAPPER AROUND THIS SCRIPT, OR USE -u AND UNDUMP!\n");
2186 #endif /* SETUID_SCRIPTS_ARE_SECURE_NOW */
2187 /* not set-id, must be wrapped */
2193 find_beginning(void)
2195 register char *s, *s2;
2197 /* skip forward in input to the real script? */
2201 if ((s = sv_gets(linestr, rsfp, 0)) == Nullch)
2202 croak("No Perl script found in input\n");
2203 if (*s == '#' && s[1] == '!' && (s = instr(s,"perl"))) {
2204 PerlIO_ungetc(rsfp, '\n'); /* to keep line count right */
2206 while (*s && !(isSPACE (*s) || *s == '#')) s++;
2208 while (*s == ' ' || *s == '\t') s++;
2210 while (isDIGIT(s2[-1]) || strchr("-._", s2[-1])) s2--;
2211 if (strnEQ(s2-4,"perl",4))
2213 while (s = moreswitches(s)) ;
2215 if (cddir && PerlDir_chdir(cddir) < 0)
2216 croak("Can't chdir to %s",cddir);
2223 read_e_script(int idx, SV *buf_sv, int maxlen)
2226 FILTER_READ(idx+1, buf_sv, maxlen);
2227 p = SvPVX(e_script);
2228 nl = strchr(p, '\n');
2229 nl = (nl) ? nl+1 : SvEND(e_script);
2232 sv_catpvn(buf_sv, p, nl-p);
2233 sv_chop(e_script, nl);
2241 uid = (int)PerlProc_getuid();
2242 euid = (int)PerlProc_geteuid();
2243 gid = (int)PerlProc_getgid();
2244 egid = (int)PerlProc_getegid();
2249 tainting |= (uid && (euid != uid || egid != gid));
2253 forbid_setid(char *s)
2256 croak("No %s allowed while running setuid", s);
2258 croak("No %s allowed while running setgid", s);
2265 curstash = debstash;
2266 dbargs = GvAV(gv_AVadd((gv_fetchpv("args", GV_ADDMULTI, SVt_PVAV))));
2268 DBgv = gv_fetchpv("DB", GV_ADDMULTI, SVt_PVGV);
2269 DBline = gv_fetchpv("dbline", GV_ADDMULTI, SVt_PVAV);
2270 DBsub = gv_HVadd(gv_fetchpv("sub", GV_ADDMULTI, SVt_PVHV));
2271 DBsingle = GvSV((gv_fetchpv("single", GV_ADDMULTI, SVt_PV)));
2272 sv_setiv(DBsingle, 0);
2273 DBtrace = GvSV((gv_fetchpv("trace", GV_ADDMULTI, SVt_PV)));
2274 sv_setiv(DBtrace, 0);
2275 DBsignal = GvSV((gv_fetchpv("signal", GV_ADDMULTI, SVt_PV)));
2276 sv_setiv(DBsignal, 0);
2277 curstash = defstash;
2280 #ifndef STRESS_REALLOC
2281 #define REASONABLE(size) (size)
2283 #define REASONABLE(size) (1) /* unreasonable */
2287 init_stacks(ARGSproto)
2289 /* start with 128-item stack and 8K cxstack */
2290 curstackinfo = new_stackinfo(REASONABLE(128),
2291 REASONABLE(8192/sizeof(PERL_CONTEXT) - 1));
2292 curstackinfo->si_type = SI_MAIN;
2293 curstack = curstackinfo->si_stack;
2294 mainstack = curstack; /* remember in case we switch stacks */
2296 stack_base = AvARRAY(curstack);
2297 stack_sp = stack_base;
2298 stack_max = stack_base + AvMAX(curstack);
2300 New(50,tmps_stack,REASONABLE(128),SV*);
2303 tmps_max = REASONABLE(128);
2306 * The following stacks almost certainly should be per-interpreter,
2307 * but for now they're not. XXX
2311 markstack_ptr = markstack;
2313 New(54,markstack,REASONABLE(32),I32);
2314 markstack_ptr = markstack;
2315 markstack_max = markstack + REASONABLE(32);
2323 New(54,scopestack,REASONABLE(32),I32);
2325 scopestack_max = REASONABLE(32);
2331 New(54,savestack,REASONABLE(128),ANY);
2333 savestack_max = REASONABLE(128);
2339 New(54,retstack,REASONABLE(16),OP*);
2341 retstack_max = REASONABLE(16);
2351 while (curstackinfo->si_next)
2352 curstackinfo = curstackinfo->si_next;
2353 while (curstackinfo) {
2354 PERL_SI *p = curstackinfo->si_prev;
2355 /* curstackinfo->si_stack got nuked by sv_free_arenas() */
2356 Safefree(curstackinfo->si_cxstack);
2357 Safefree(curstackinfo);
2360 Safefree(tmps_stack);
2368 static PerlIO *tmpfp; /* moved outside init_lexer() because of UNICOS bug */
2381 subname = newSVpv("main",4);
2385 init_predump_symbols(void)
2391 sv_setpvn(perl_get_sv("\"", TRUE), " ", 1);
2392 stdingv = gv_fetchpv("STDIN",TRUE, SVt_PVIO);
2393 GvMULTI_on(stdingv);
2394 IoIFP(GvIOp(stdingv)) = PerlIO_stdin();
2395 tmpgv = gv_fetchpv("stdin",TRUE, SVt_PV);
2397 GvIOp(tmpgv) = (IO*)SvREFCNT_inc(GvIOp(stdingv));
2399 tmpgv = gv_fetchpv("STDOUT",TRUE, SVt_PVIO);
2401 IoOFP(GvIOp(tmpgv)) = IoIFP(GvIOp(tmpgv)) = PerlIO_stdout();
2403 tmpgv = gv_fetchpv("stdout",TRUE, SVt_PV);
2405 GvIOp(tmpgv) = (IO*)SvREFCNT_inc(GvIOp(defoutgv));
2407 othergv = gv_fetchpv("STDERR",TRUE, SVt_PVIO);
2408 GvMULTI_on(othergv);
2409 IoOFP(GvIOp(othergv)) = IoIFP(GvIOp(othergv)) = PerlIO_stderr();
2410 tmpgv = gv_fetchpv("stderr",TRUE, SVt_PV);
2412 GvIOp(tmpgv) = (IO*)SvREFCNT_inc(GvIOp(othergv));
2414 statname = NEWSV(66,0); /* last filename we did stat on */
2417 osname = savepv(OSNAME);
2421 init_postdump_symbols(register int argc, register char **argv, register char **env)
2428 argc--,argv++; /* skip name of script */
2430 for (; argc > 0 && **argv == '-'; argc--,argv++) {
2433 if (argv[0][1] == '-') {
2437 if (s = strchr(argv[0], '=')) {
2439 sv_setpv(GvSV(gv_fetchpv(argv[0]+1,TRUE, SVt_PV)),s);
2442 sv_setiv(GvSV(gv_fetchpv(argv[0]+1,TRUE, SVt_PV)),1);
2445 toptarget = NEWSV(0,0);
2446 sv_upgrade(toptarget, SVt_PVFM);
2447 sv_setpvn(toptarget, "", 0);
2448 bodytarget = NEWSV(0,0);
2449 sv_upgrade(bodytarget, SVt_PVFM);
2450 sv_setpvn(bodytarget, "", 0);
2451 formtarget = bodytarget;
2454 if (tmpgv = gv_fetchpv("0",TRUE, SVt_PV)) {
2455 sv_setpv(GvSV(tmpgv),origfilename);
2456 magicname("0", "0", 1);
2458 if (tmpgv = gv_fetchpv("\030",TRUE, SVt_PV))
2459 sv_setpv(GvSV(tmpgv),origargv[0]);
2460 if (argvgv = gv_fetchpv("ARGV",TRUE, SVt_PVAV)) {
2462 (void)gv_AVadd(argvgv);
2463 av_clear(GvAVn(argvgv));
2464 for (; argc > 0; argc--,argv++) {
2465 av_push(GvAVn(argvgv),newSVpv(argv[0],0));
2468 if (envgv = gv_fetchpv("ENV",TRUE, SVt_PVHV)) {
2472 hv_magic(hv, envgv, 'E');
2473 #ifndef VMS /* VMS doesn't have environ array */
2474 /* Note that if the supplied env parameter is actually a copy
2475 of the global environ then it may now point to free'd memory
2476 if the environment has been modified since. To avoid this
2477 problem we treat env==NULL as meaning 'use the default'
2482 environ[0] = Nullch;
2483 for (; *env; env++) {
2484 if (!(s = strchr(*env,'=')))
2487 #if defined(WIN32) || defined(MSDOS)
2490 sv = newSVpv(s--,0);
2491 (void)hv_store(hv, *env, s - *env, sv, 0);
2493 #if defined(__BORLANDC__) && defined(USE_WIN32_RTL_ENV)
2494 /* Sins of the RTL. See note in my_setenv(). */
2495 (void)PerlEnv_putenv(savepv(*env));
2499 #ifdef DYNAMIC_ENV_FETCH
2500 HvNAME(hv) = savepv(ENV_HV_NAME);
2504 if (tmpgv = gv_fetchpv("$",TRUE, SVt_PV))
2505 sv_setiv(GvSV(tmpgv), (IV)getpid());
2514 s = PerlEnv_getenv("PERL5LIB");
2518 incpush(PerlEnv_getenv("PERLLIB"), FALSE);
2520 /* Treat PERL5?LIB as a possible search list logical name -- the
2521 * "natural" VMS idiom for a Unix path string. We allow each
2522 * element to be a set of |-separated directories for compatibility.
2526 if (my_trnlnm("PERL5LIB",buf,0))
2527 do { incpush(buf,TRUE); } while (my_trnlnm("PERL5LIB",buf,++idx));
2529 while (my_trnlnm("PERLLIB",buf,idx++)) incpush(buf,FALSE);
2533 /* Use the ~-expanded versions of APPLLIB (undocumented),
2534 ARCHLIB PRIVLIB SITEARCH and SITELIB
2537 incpush(APPLLIB_EXP, TRUE);
2541 incpush(ARCHLIB_EXP, FALSE);
2544 #define PRIVLIB_EXP "/usr/local/lib/perl5:/usr/local/lib/perl"
2547 incpush(PRIVLIB_EXP, TRUE);
2549 incpush(PRIVLIB_EXP, FALSE);
2553 incpush(SITEARCH_EXP, FALSE);
2557 incpush(SITELIB_EXP, TRUE);
2559 incpush(SITELIB_EXP, FALSE);
2563 incpush(".", FALSE);
2567 # define PERLLIB_SEP ';'
2570 # define PERLLIB_SEP '|'
2572 # define PERLLIB_SEP ':'
2575 #ifndef PERLLIB_MANGLE
2576 # define PERLLIB_MANGLE(s,n) (s)
2580 incpush(char *p, int addsubdirs)
2582 SV *subdir = Nullsv;
2588 subdir = NEWSV(55,0);
2589 if (!archpat_auto) {
2590 STRLEN len = (sizeof(ARCHNAME) + strlen(patchlevel)
2591 + sizeof("//auto"));
2592 New(55, archpat_auto, len, char);
2593 sprintf(archpat_auto, "/%s/%s/auto", ARCHNAME, patchlevel);
2595 for (len = sizeof(ARCHNAME) + 2;
2596 archpat_auto[len] != '\0' && archpat_auto[len] != '/'; len++)
2597 if (archpat_auto[len] == '.') archpat_auto[len] = '_';
2602 /* Break at all separators */
2604 SV *libdir = NEWSV(55,0);
2607 /* skip any consecutive separators */
2608 while ( *p == PERLLIB_SEP ) {
2609 /* Uncomment the next line for PATH semantics */
2610 /* av_push(GvAVn(incgv), newSVpv(".", 1)); */
2614 if ( (s = strchr(p, PERLLIB_SEP)) != Nullch ) {
2615 sv_setpvn(libdir, PERLLIB_MANGLE(p, (STRLEN)(s - p)),
2620 sv_setpv(libdir, PERLLIB_MANGLE(p, 0));
2621 p = Nullch; /* break out */
2625 * BEFORE pushing libdir onto @INC we may first push version- and
2626 * archname-specific sub-directories.
2629 struct stat tmpstatbuf;
2634 if ((unix = tounixspec_ts(SvPV(libdir,na),Nullch)) != Nullch) {
2636 while (unix[len-1] == '/') len--; /* Cosmetic */
2637 sv_usepvn(libdir,unix,len);
2640 PerlIO_printf(PerlIO_stderr(),
2641 "Failed to unixify @INC element \"%s\"\n",
2644 /* .../archname/version if -d .../archname/version/auto */
2645 sv_setsv(subdir, libdir);
2646 sv_catpv(subdir, archpat_auto);
2647 if (PerlLIO_stat(SvPVX(subdir), &tmpstatbuf) >= 0 &&
2648 S_ISDIR(tmpstatbuf.st_mode))
2649 av_push(GvAVn(incgv),
2650 newSVpv(SvPVX(subdir), SvCUR(subdir) - sizeof "auto"));
2652 /* .../archname if -d .../archname/auto */
2653 sv_insert(subdir, SvCUR(libdir) + sizeof(ARCHNAME),
2654 strlen(patchlevel) + 1, "", 0);
2655 if (PerlLIO_stat(SvPVX(subdir), &tmpstatbuf) >= 0 &&
2656 S_ISDIR(tmpstatbuf.st_mode))
2657 av_push(GvAVn(incgv),
2658 newSVpv(SvPVX(subdir), SvCUR(subdir) - sizeof "auto"));
2661 /* finally push this lib directory on the end of @INC */
2662 av_push(GvAVn(incgv), libdir);
2665 SvREFCNT_dec(subdir);
2669 STATIC struct perl_thread *
2672 struct perl_thread *thr;
2675 Newz(53, thr, 1, struct perl_thread);
2676 curcop = &compiling;
2677 thr->cvcache = newHV();
2678 thr->threadsv = newAV();
2679 /* thr->threadsvp is set when find_threadsv is called */
2680 thr->specific = newAV();
2681 thr->errhv = newHV();
2682 thr->flags = THRf_R_JOINABLE;
2683 MUTEX_INIT(&thr->mutex);
2684 /* Handcraft thrsv similarly to mess_sv */
2685 New(53, thrsv, 1, SV);
2686 Newz(53, xpv, 1, XPV);
2687 SvFLAGS(thrsv) = SVt_PV;
2688 SvANY(thrsv) = (void*)xpv;
2689 SvREFCNT(thrsv) = 1 << 30; /* practically infinite */
2690 SvPVX(thrsv) = (char*)thr;
2691 SvCUR_set(thrsv, sizeof(thr));
2692 SvLEN_set(thrsv, sizeof(thr));
2693 *SvEND(thrsv) = '\0'; /* in the trailing_nul field */
2697 MUTEX_LOCK(&threads_mutex);
2702 MUTEX_UNLOCK(&threads_mutex);
2704 #ifdef HAVE_THREAD_INTERN
2705 init_thread_intern(thr);
2708 #ifdef SET_THREAD_SELF
2709 SET_THREAD_SELF(thr);
2711 thr->self = pthread_self();
2712 #endif /* SET_THREAD_SELF */
2716 * These must come after the SET_THR because sv_setpvn does
2717 * SvTAINT and the taint fields require dTHR.
2719 toptarget = NEWSV(0,0);
2720 sv_upgrade(toptarget, SVt_PVFM);
2721 sv_setpvn(toptarget, "", 0);
2722 bodytarget = NEWSV(0,0);
2723 sv_upgrade(bodytarget, SVt_PVFM);
2724 sv_setpvn(bodytarget, "", 0);
2725 formtarget = bodytarget;
2726 thr->errsv = newSVpv("", 0);
2727 (void) find_threadsv("@"); /* Ensure $@ is initialised early */
2730 #endif /* USE_THREADS */
2733 call_list(I32 oldscope, AV *paramList)
2736 line_t oldline = curcop->cop_line;
2741 while (AvFILL(paramList) >= 0) {
2742 CV *cv = (CV*)av_shift(paramList);
2751 perl_call_sv((SV*)cv, G_EVAL|G_DISCARD);
2752 (void)SvPV(atsv, len);
2755 curcop = &compiling;
2756 curcop->cop_line = oldline;
2757 if (paramList == beginav)
2758 sv_catpv(atsv, "BEGIN failed--compilation aborted");
2760 sv_catpv(atsv, "END failed--cleanup aborted");
2761 while (scopestack_ix > oldscope)
2763 croak("%s", SvPVX(atsv));
2771 /* my_exit() was called */
2772 while (scopestack_ix > oldscope)
2775 curstash = defstash;
2777 call_list(oldscope, endav);
2779 curcop = &compiling;
2780 curcop->cop_line = oldline;
2782 if (paramList == beginav)
2783 croak("BEGIN failed--compilation aborted");
2785 croak("END failed--cleanup aborted");
2791 PerlIO_printf(PerlIO_stderr(), "panic: restartop\n");
2796 curcop = &compiling;
2797 curcop->cop_line = oldline;
2810 DEBUG_L(PerlIO_printf(Perl_debug_log, "my_exit: thread %p, status %lu\n",
2811 thr, (unsigned long) status));
2812 #endif /* USE_THREADS */
2821 STATUS_NATIVE_SET(status);
2828 my_failure_exit(void)
2831 if (vaxc$errno & 1) {
2832 if (STATUS_NATIVE & 1) /* fortuitiously includes "-1" */
2833 STATUS_NATIVE_SET(44);
2836 if (!vaxc$errno && errno) /* unlikely */
2837 STATUS_NATIVE_SET(44);
2839 STATUS_NATIVE_SET(vaxc$errno);
2844 STATUS_POSIX_SET(errno);
2846 exitstatus = STATUS_POSIX >> 8;
2847 if (exitstatus & 255)
2848 STATUS_POSIX_SET(exitstatus);
2850 STATUS_POSIX_SET(255);
2860 register PERL_CONTEXT *cx;
2865 SvREFCNT_dec(e_script);
2869 POPSTACK_TO(mainstack);
2870 if (cxstack_ix >= 0) {