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 */
480 /* reset so print() ends up where we expect */
483 /* Prepare to destruct main symbol table. */
490 if (destruct_level >= 2) {
491 if (scopestack_ix != 0)
492 warn("Unbalanced scopes: %ld more ENTERs than LEAVEs\n",
493 (long)scopestack_ix);
494 if (savestack_ix != 0)
495 warn("Unbalanced saves: %ld more saves than restores\n",
497 if (tmps_floor != -1)
498 warn("Unbalanced tmps: %ld more allocs than frees\n",
499 (long)tmps_floor + 1);
500 if (cxstack_ix != -1)
501 warn("Unbalanced context: %ld more PUSHes than POPs\n",
502 (long)cxstack_ix + 1);
505 /* Now absolutely destruct everything, somehow or other, loops or no. */
507 SvFLAGS(strtab) |= SVTYPEMASK; /* don't clean out strtab now */
508 while (sv_count != 0 && sv_count != last_sv_count) {
509 last_sv_count = sv_count;
512 SvFLAGS(strtab) &= ~SVTYPEMASK;
513 SvFLAGS(strtab) |= SVt_PVHV;
515 /* Destruct the global string table. */
517 /* Yell and reset the HeVAL() slots that are still holding refcounts,
518 * so that sv_free() won't fail on them.
527 array = HvARRAY(strtab);
531 warn("Unbalanced string table refcount: (%d) for \"%s\"",
532 HeVAL(hent) - Nullsv, HeKEY(hent));
533 HeVAL(hent) = Nullsv;
543 SvREFCNT_dec(strtab);
546 warn("Scalars leaked: %ld\n", (long)sv_count);
550 /* No SVs have survived, need to clean out */
554 Safefree(origfilename);
556 hints = 0; /* Reset hints. Should hints be per-interpreter ? */
558 DEBUG_P(debprofdump());
560 MUTEX_DESTROY(&sv_mutex);
561 MUTEX_DESTROY(&eval_mutex);
562 COND_DESTROY(&eval_cond);
564 /* As the penultimate thing, free the non-arena SV for thrsv */
565 Safefree(SvPVX(thrsv));
566 Safefree(SvANY(thrsv));
569 #endif /* USE_THREADS */
571 /* As the absolutely last thing, free the non-arena SV for mess() */
574 /* we know that type >= SVt_PV */
576 Safefree(SvPVX(mess_sv));
577 Safefree(SvANY(mess_sv));
585 CPerlObj::perl_free(void)
587 perl_free(PerlInterpreter *sv_interp)
593 if (!(curinterp = sv_interp))
601 CPerlObj::perl_atexit(void (*fn) (CPerlObj*,void *), void *ptr)
603 perl_atexit(void (*fn) (void *), void *ptr)
607 Renew(exitlist, exitlistlen+1, PerlExitListEntry);
609 New(999, exitlist, 1, PerlExitListEntry);
610 exitlist[exitlistlen].fn = fn;
611 exitlist[exitlistlen].ptr = ptr;
617 CPerlObj::perl_parse(void (*xsinit) (CPerlObj*), int argc, char **argv, char **env)
619 perl_parse(PerlInterpreter *sv_interp, void (*xsinit) (void), int argc, char **argv, char **env)
625 char *scriptname = NULL;
626 VOL bool dosearch = FALSE;
634 #ifdef SETUID_SCRIPTS_ARE_SECURE_NOW
637 croak("suidperl is no longer needed since the kernel can now execute\n\
638 setuid perl scripts securely.\n");
643 if (!(curinterp = sv_interp))
647 #if defined(NeXT) && defined(__DYNAMIC__)
648 _dyld_lookup_and_bind
649 ("__environ", (unsigned long *) &environ_pointer, NULL);
654 #ifndef VMS /* VMS doesn't have environ array */
655 origenviron = environ;
660 /* Come here if running an undumped a.out. */
662 origfilename = savepv(argv[0]);
664 cxstack_ix = -1; /* start label stack again */
666 init_postdump_symbols(argc,argv,env);
671 curpad = AvARRAY(comppad);
676 SvREFCNT_dec(main_cv);
680 oldscope = scopestack_ix;
688 /* my_exit() was called */
689 while (scopestack_ix > oldscope)
694 call_list(oldscope, endav);
696 return STATUS_NATIVE_EXPORT;
699 PerlIO_printf(PerlIO_stderr(), "panic: top_env\n");
703 sv_setpvn(linestr,"",0);
704 sv = newSVpv("",0); /* first used for -I flags */
708 for (argc--,argv++; argc > 0; argc--,argv++) {
709 if (argv[0][0] != '-' || !argv[0][1])
713 validarg = " PHOOEY ";
739 if (s = moreswitches(s))
749 if (euid != uid || egid != gid)
750 croak("No -e allowed in setuid scripts");
752 e_script = newSVpv("",0);
753 filter_add(read_e_script, NULL);
756 sv_catpv(e_script, s);
758 sv_catpv(e_script, argv[1]);
762 croak("No code specified for -e");
763 sv_catpv(e_script, "\n");
766 case 'I': /* -I handled both here and in moreswitches() */
768 if (!*++s && (s=argv[1]) != Nullch) {
771 while (s && isSPACE(*s))
775 for (e = s; *e && !isSPACE(*e); e++) ;
782 } /* XXX else croak? */
796 preambleav = newAV();
797 av_push(preambleav, newSVpv("use Config qw(myconfig config_vars)",0));
799 Sv = newSVpv("print myconfig();",0);
801 sv_catpv(Sv,"print \"\\nCharacteristics of this PERLSHR image: \\n\",");
803 sv_catpv(Sv,"print \"\\nCharacteristics of this binary (from libperl): \\n\",");
805 #if defined(DEBUGGING) || defined(NO_EMBED) || defined(MULTIPLICITY)
806 sv_catpv(Sv,"\" Compile-time options:");
808 sv_catpv(Sv," DEBUGGING");
811 sv_catpv(Sv," NO_EMBED");
814 sv_catpv(Sv," MULTIPLICITY");
816 sv_catpv(Sv,"\\n\",");
818 #if defined(LOCAL_PATCH_COUNT)
819 if (LOCAL_PATCH_COUNT > 0) {
821 sv_catpv(Sv,"\" Locally applied patches:\\n\",");
822 for (i = 1; i <= LOCAL_PATCH_COUNT; i++) {
824 sv_catpvf(Sv,"\" \\t%s\\n\",",localpatches[i]);
828 sv_catpvf(Sv,"\" Built under %s\\n\"",OSNAME);
831 sv_catpvf(Sv,",\" Compiled at %s %s\\n\"",__DATE__,__TIME__);
833 sv_catpvf(Sv,",\" Compiled on %s\\n\"",__DATE__);
838 @env = map { \"$_=\\\"$ENV{$_}\\\"\" } sort grep {/^PERL/} keys %ENV; \
839 print \" \\%ENV:\\n @env\\n\" if @env; \
840 print \" \\@INC:\\n @INC\\n\";");
843 Sv = newSVpv("config_vars(qw(",0);
848 av_push(preambleav, Sv);
849 scriptname = BIT_BUCKET; /* don't look for script or read stdin */
860 if (!*++s || isSPACE(*s)) {
864 /* catch use of gnu style long options */
865 if (strEQ(s, "version")) {
869 if (strEQ(s, "help")) {
876 croak("Unrecognized switch: -%s (-h will show valid options)",s);
881 if (!tainting && (s = PerlEnv_getenv("PERL5OPT"))) {
892 if (!strchr("DIMUdmw", *s))
893 croak("Illegal switch in PERL5OPT: -%c", *s);
899 scriptname = argv[0];
902 scriptname = BIT_BUCKET; /* don't look for script or read stdin */
904 else if (scriptname == Nullch) {
906 if ( PerlLIO_isatty(PerlIO_fileno(PerlIO_stdin())) )
914 open_script(scriptname,dosearch,sv,&fdscript);
916 validate_suid(validarg, scriptname,fdscript);
921 main_cv = compcv = (CV*)NEWSV(1104,0);
922 sv_upgrade((SV *)compcv, SVt_PVCV);
926 av_push(comppad, Nullsv);
927 curpad = AvARRAY(comppad);
928 comppad_name = newAV();
929 comppad_name_fill = 0;
930 min_intro_pending = 0;
933 av_store(comppad_name, 0, newSVpv("@_", 2));
934 curpad[0] = (SV*)newAV();
935 SvPADMY_on(curpad[0]); /* XXX Needed? */
937 New(666, CvMUTEXP(compcv), 1, perl_mutex);
938 MUTEX_INIT(CvMUTEXP(compcv));
939 #endif /* USE_THREADS */
941 comppadlist = newAV();
942 AvREAL_off(comppadlist);
943 av_store(comppadlist, 0, (SV*)comppad_name);
944 av_store(comppadlist, 1, (SV*)comppad);
945 CvPADLIST(compcv) = comppadlist;
947 boot_core_UNIVERSAL();
950 (*xsinit)(PERL_OBJECT_THIS); /* in case linked C routines want magical variables */
951 #if defined(VMS) || defined(WIN32) || defined(DJGPP)
955 init_predump_symbols();
956 /* init_postdump_symbols not currently designed to be called */
957 /* more than once (ENV isn't cleared first, for example) */
958 /* But running with -u leaves %ENV & @ARGV undefined! XXX */
960 init_postdump_symbols(argc,argv,env);
964 /* now parse the script */
966 SETERRNO(0,SS$_NORMAL);
968 if (yyparse() || error_count) {
970 croak("%s had compilation errors.\n", origfilename);
972 croak("Execution of %s aborted due to compilation errors.\n",
976 curcop->cop_line = 0;
980 SvREFCNT_dec(e_script);
984 /* now that script is parsed, we can modify record separator */
986 rs = SvREFCNT_inc(nrs);
987 sv_setsv(perl_get_sv("/", TRUE), rs);
998 if ((s=PerlEnv_getenv("PERL_DEBUG_MSTATS")) && atoi(s) >= 2)
999 dump_mstats("after compilation:");
1010 CPerlObj::perl_run(void)
1012 perl_run(PerlInterpreter *sv_interp)
1021 if (!(curinterp = sv_interp))
1025 oldscope = scopestack_ix;
1030 cxstack_ix = -1; /* start context stack again */
1033 /* my_exit() was called */
1034 while (scopestack_ix > oldscope)
1037 curstash = defstash;
1039 call_list(oldscope, endav);
1041 if (PerlEnv_getenv("PERL_DEBUG_MSTATS"))
1042 dump_mstats("after execution: ");
1045 return STATUS_NATIVE_EXPORT;
1048 PerlIO_printf(PerlIO_stderr(), "panic: restartop\n");
1053 POPSTACK_TO(mainstack);
1057 DEBUG_r(PerlIO_printf(Perl_debug_log, "%s $` $& $' support.\n",
1058 sawampersand ? "Enabling" : "Omitting"));
1061 DEBUG_x(dump_all());
1062 DEBUG(PerlIO_printf(Perl_debug_log, "\nEXECUTING...\n\n"));
1064 DEBUG_L(PerlIO_printf(Perl_debug_log, "main thread is 0x%lx\n",
1065 (unsigned long) thr));
1066 #endif /* USE_THREADS */
1069 PerlIO_printf(PerlIO_stderr(), "%s syntax OK\n", origfilename);
1072 if (PERLDB_SINGLE && DBsingle)
1073 sv_setiv(DBsingle, 1);
1075 call_list(oldscope, initav);
1085 else if (main_start) {
1086 CvDEPTH(main_cv) = 1;
1097 perl_get_sv(char *name, I32 create)
1101 if (name[1] == '\0' && !isALPHA(name[0])) {
1102 PADOFFSET tmp = find_threadsv(name);
1103 if (tmp != NOT_IN_PAD) {
1105 return THREADSV(tmp);
1108 #endif /* USE_THREADS */
1109 gv = gv_fetchpv(name, create, SVt_PV);
1116 perl_get_av(char *name, I32 create)
1118 GV* gv = gv_fetchpv(name, create, SVt_PVAV);
1127 perl_get_hv(char *name, I32 create)
1129 GV* gv = gv_fetchpv(name, create, SVt_PVHV);
1138 perl_get_cv(char *name, I32 create)
1140 GV* gv = gv_fetchpv(name, create, SVt_PVCV);
1141 if (create && !GvCVu(gv))
1142 return newSUB(start_subparse(FALSE, 0),
1143 newSVOP(OP_CONST, 0, newSVpv(name,0)),
1151 /* Be sure to refetch the stack pointer after calling these routines. */
1154 perl_call_argv(char *sub_name, I32 flags, register char **argv)
1156 /* See G_* flags in cop.h */
1157 /* null terminated arg list */
1164 XPUSHs(sv_2mortal(newSVpv(*argv,0)));
1169 return perl_call_pv(sub_name, flags);
1173 perl_call_pv(char *sub_name, I32 flags)
1174 /* name of the subroutine */
1175 /* See G_* flags in cop.h */
1177 return perl_call_sv((SV*)perl_get_cv(sub_name, TRUE), flags);
1181 perl_call_method(char *methname, I32 flags)
1182 /* name of the subroutine */
1183 /* See G_* flags in cop.h */
1189 XPUSHs(sv_2mortal(newSVpv(methname,0)));
1194 return perl_call_sv(*stack_sp--, flags);
1197 /* May be called with any of a CV, a GV, or an SV containing the name. */
1199 perl_call_sv(SV *sv, I32 flags)
1201 /* See G_* flags in cop.h */
1204 LOGOP myop; /* fake syntax tree node */
1208 bool oldcatch = CATCH_GET;
1213 if (flags & G_DISCARD) {
1218 Zero(&myop, 1, LOGOP);
1219 myop.op_next = Nullop;
1220 if (!(flags & G_NOARGS))
1221 myop.op_flags |= OPf_STACKED;
1222 myop.op_flags |= ((flags & G_VOID) ? OPf_WANT_VOID :
1223 (flags & G_ARRAY) ? OPf_WANT_LIST :
1228 EXTEND(stack_sp, 1);
1231 oldscope = scopestack_ix;
1233 if (PERLDB_SUB && curstash != debstash
1234 /* Handle first BEGIN of -d. */
1235 && (DBcv || (DBcv = GvCV(DBsub)))
1236 /* Try harder, since this may have been a sighandler, thus
1237 * curstash may be meaningless. */
1238 && (SvTYPE(sv) != SVt_PVCV || CvSTASH((CV*)sv) != debstash)
1239 && !(flags & G_NODEBUG))
1240 op->op_private |= OPpENTERSUB_DB;
1242 if (flags & G_EVAL) {
1243 cLOGOP->op_other = op;
1245 /* we're trying to emulate pp_entertry() here */
1247 register PERL_CONTEXT *cx;
1248 I32 gimme = GIMME_V;
1253 push_return(op->op_next);
1254 PUSHBLOCK(cx, CXt_EVAL, stack_sp);
1256 eval_root = op; /* Only needed so that goto works right. */
1259 if (flags & G_KEEPERR)
1274 /* my_exit() was called */
1275 curstash = defstash;
1279 croak("Callback called exit");
1288 stack_sp = stack_base + oldmark;
1289 if (flags & G_ARRAY)
1293 *++stack_sp = &sv_undef;
1301 if (op == (OP*)&myop)
1302 op = pp_entersub(ARGS);
1305 retval = stack_sp - (stack_base + oldmark);
1306 if ((flags & G_EVAL) && !(flags & G_KEEPERR))
1310 if (flags & G_EVAL) {
1311 if (scopestack_ix > oldscope) {
1315 register PERL_CONTEXT *cx;
1327 CATCH_SET(oldcatch);
1329 if (flags & G_DISCARD) {
1330 stack_sp = stack_base + oldmark;
1339 /* Eval a string. The G_EVAL flag is always assumed. */
1342 perl_eval_sv(SV *sv, I32 flags)
1344 /* See G_* flags in cop.h */
1347 UNOP myop; /* fake syntax tree node */
1348 I32 oldmark = SP - stack_base;
1355 if (flags & G_DISCARD) {
1363 EXTEND(stack_sp, 1);
1365 oldscope = scopestack_ix;
1367 if (!(flags & G_NOARGS))
1368 myop.op_flags = OPf_STACKED;
1369 myop.op_next = Nullop;
1370 myop.op_type = OP_ENTEREVAL;
1371 myop.op_flags |= ((flags & G_VOID) ? OPf_WANT_VOID :
1372 (flags & G_ARRAY) ? OPf_WANT_LIST :
1374 if (flags & G_KEEPERR)
1375 myop.op_flags |= OPf_SPECIAL;
1385 /* my_exit() was called */
1386 curstash = defstash;
1390 croak("Callback called exit");
1399 stack_sp = stack_base + oldmark;
1400 if (flags & G_ARRAY)
1404 *++stack_sp = &sv_undef;
1409 if (op == (OP*)&myop)
1410 op = pp_entereval(ARGS);
1413 retval = stack_sp - (stack_base + oldmark);
1414 if (!(flags & G_KEEPERR))
1419 if (flags & G_DISCARD) {
1420 stack_sp = stack_base + oldmark;
1430 perl_eval_pv(char *p, I32 croak_on_error)
1433 SV* sv = newSVpv(p, 0);
1436 perl_eval_sv(sv, G_SCALAR);
1443 if (croak_on_error && SvTRUE(ERRSV))
1444 croak(SvPVx(ERRSV, na));
1449 /* Require a module. */
1452 perl_require_pv(char *pv)
1454 SV* sv = sv_newmortal();
1455 sv_setpv(sv, "require '");
1458 perl_eval_sv(sv, G_DISCARD);
1462 magicname(char *sym, char *name, I32 namlen)
1466 if (gv = gv_fetchpv(sym,TRUE, SVt_PV))
1467 sv_magic(GvSV(gv), (SV*)gv, 0, name, namlen);
1471 usage(char *name) /* XXX move this out into a module ? */
1474 /* This message really ought to be max 23 lines.
1475 * Removed -h because the user already knows that opton. Others? */
1477 static char *usage_msg[] = {
1478 "-0[octal] specify record separator (\\0, if no argument)",
1479 "-a autosplit mode with -n or -p (splits $_ into @F)",
1480 "-c check syntax only (runs BEGIN and END blocks)",
1481 "-d[:debugger] run scripts under debugger",
1482 "-D[number/list] set debugging flags (argument is a bit mask or flags)",
1483 "-e 'command' one line of script. Several -e's allowed. Omit [programfile].",
1484 "-F/pattern/ split() pattern for autosplit (-a). The //'s are optional.",
1485 "-i[extension] edit <> files in place (make backup if extension supplied)",
1486 "-Idirectory specify @INC/#include directory (may be used more than once)",
1487 "-l[octal] enable line ending processing, specifies line terminator",
1488 "-[mM][-]module.. executes `use/no module...' before executing your script.",
1489 "-n assume 'while (<>) { ... }' loop around your script",
1490 "-p assume loop like -n but print line also like sed",
1491 "-P run script through C preprocessor before compilation",
1492 "-s enable some switch parsing for switches after script name",
1493 "-S look for the script using PATH environment variable",
1494 "-T turn on tainting checks",
1495 "-u dump core after parsing script",
1496 "-U allow unsafe operations",
1497 "-v print version number, patchlevel plus VERY IMPORTANT perl info",
1498 "-V[:variable] print perl configuration information",
1499 "-w TURN WARNINGS ON FOR COMPILATION OF YOUR SCRIPT. Recommended.",
1500 "-x[directory] strip off text before #!perl line and perhaps cd to directory",
1504 char **p = usage_msg;
1506 printf("\nUsage: %s [switches] [--] [programfile] [arguments]", name);
1508 printf("\n %s", *p++);
1511 /* This routine handles any switches that can be given during run */
1514 moreswitches(char *s)
1523 rschar = scan_oct(s, 4, &numlen);
1525 if (rschar & ~((U8)~0))
1527 else if (!rschar && numlen >= 2)
1528 nrs = newSVpv("", 0);
1531 nrs = newSVpv(&ch, 1);
1537 splitstr = savepv(s + 1);
1551 if (*s == ':' || *s == '=') {
1552 my_setenv("PERL5DB", form("use Devel::%s;", ++s));
1556 perldb = PERLDB_ALL;
1563 if (isALPHA(s[1])) {
1564 static char debopts[] = "psltocPmfrxuLHXD";
1567 for (s++; *s && (d = strchr(debopts,*s)); s++)
1568 debug |= 1 << (d - debopts);
1572 for (s++; isDIGIT(*s); s++) ;
1574 debug |= 0x80000000;
1576 warn("Recompile perl with -DDEBUGGING to use -D switch\n");
1577 for (s++; isALNUM(*s); s++) ;
1587 inplace = savepv(s+1);
1589 for (s = inplace; *s && !isSPACE(*s); s++) ;
1592 if (*s == '-') /* Additional switches on #! line. */
1596 case 'I': /* -I handled both here and in parse_perl() */
1599 while (*s && isSPACE(*s))
1603 for (e = s; *e && !isSPACE(*e); e++) ;
1604 p = savepvn(s, e-s);
1610 croak("No space allowed after -I");
1620 *ors = scan_oct(s, 3 + (*s == '0'), &numlen);
1630 ors = SvPV(nrs, orslen);
1631 ors = savepvn(ors, orslen);
1635 forbid_setid("-M"); /* XXX ? */
1638 forbid_setid("-m"); /* XXX ? */
1643 /* -M-foo == 'no foo' */
1644 if (*s == '-') { use = "no "; ++s; }
1645 sv = newSVpv(use,0);
1647 /* We allow -M'Module qw(Foo Bar)' */
1648 while(isALNUM(*s) || *s==':') ++s;
1650 sv_catpv(sv, start);
1651 if (*(start-1) == 'm') {
1653 croak("Can't use '%c' after -mname", *s);
1654 sv_catpv( sv, " ()");
1657 sv_catpvn(sv, start, s-start);
1658 sv_catpv(sv, " split(/,/,q{");
1663 if (preambleav == NULL)
1664 preambleav = newAV();
1665 av_push(preambleav, sv);
1668 croak("No space allowed after -%c", *(s-1));
1685 croak("Too late for \"-T\" option");
1697 #if defined(SUBVERSION) && SUBVERSION > 0
1698 printf("\nThis is perl, version 5.%03d_%02d built for %s",
1699 PATCHLEVEL, SUBVERSION, ARCHNAME);
1701 printf("\nThis is perl, version %s built for %s",
1702 patchlevel, ARCHNAME);
1704 #if defined(LOCAL_PATCH_COUNT)
1705 if (LOCAL_PATCH_COUNT > 0)
1706 printf("\n(with %d registered patch%s, see perl -V for more detail)",
1707 LOCAL_PATCH_COUNT, (LOCAL_PATCH_COUNT!=1) ? "es" : "");
1710 printf("\n\nCopyright 1987-1998, Larry Wall\n");
1712 printf("\nMS-DOS port Copyright (c) 1989, 1990, Diomidis Spinellis\n");
1715 printf("djgpp v2 port (jpl5003c) by Hirofumi Watanabe, 1996\n");
1716 printf("djgpp v2 port (perl5004+) by Laszlo Molnar, 1997-1998\n");
1719 printf("\n\nOS/2 port Copyright (c) 1990, 1991, Raymond Chen, Kai Uwe Rommel\n"
1720 "Version 5 port Copyright (c) 1994-1998, Andreas Kaiser, Ilya Zakharevich\n");
1723 printf("atariST series port, ++jrb bammi@cadence.com\n");
1726 Perl may be copied only under the terms of either the Artistic License or the\n\
1727 GNU General Public License, which may be found in the Perl 5.0 source kit.\n\n\
1728 Complete documentation for Perl, including FAQ lists, should be found on\n\
1729 this system using `man perl' or `perldoc perl'. If you have access to the\n\
1730 Internet, point your browser at http://www.perl.com/, the Perl Home Page.\n\n");
1738 if (s[1] == '-') /* Additional switches on #! line. */
1749 #ifdef ALTERNATE_SHEBANG
1750 case 'S': /* OS/2 needs -S on "extproc" line. */
1758 croak("Can't emulate -%.1s on #! line",s);
1763 /* compliments of Tom Christiansen */
1765 /* unexec() can be found in the Gnu emacs distribution */
1766 /* Known to work with -DUNEXEC and using unexelf.c from GNU emacs-20.2 */
1777 prog = newSVpv(BIN_EXP, 0);
1778 sv_catpv(prog, "/perl");
1779 file = newSVpv(origfilename, 0);
1780 sv_catpv(file, ".perldump");
1782 unexec(SvPVX(file), SvPVX(prog), &etext, sbrk(0), 0);
1783 /* unexec prints msg to stderr in case of failure */
1784 PerlProc_exit(status);
1787 # include <lib$routines.h>
1788 lib$signal(SS$_DEBUG); /* ssdef.h #included from vmsish.h */
1790 ABORT(); /* for use with undump */
1796 init_main_stash(void)
1801 /* Note that strtab is a rather special HV. Assumptions are made
1802 about not iterating on it, and not adding tie magic to it.
1803 It is properly deallocated in perl_destruct() */
1805 HvSHAREKEYS_off(strtab); /* mandatory */
1806 Newz(506,((XPVHV*)SvANY(strtab))->xhv_array,
1807 sizeof(HE*) * (((XPVHV*)SvANY(strtab))->xhv_max + 1), char);
1809 curstash = defstash = newHV();
1810 curstname = newSVpv("main",4);
1811 gv = gv_fetchpv("main::",TRUE, SVt_PVHV);
1812 SvREFCNT_dec(GvHV(gv));
1813 GvHV(gv) = (HV*)SvREFCNT_inc(defstash);
1815 HvNAME(defstash) = savepv("main");
1816 incgv = gv_HVadd(gv_AVadd(gv_fetchpv("INC",TRUE, SVt_PVAV)));
1818 defgv = gv_fetchpv("_",TRUE, SVt_PVAV);
1819 errgv = gv_HVadd(gv_fetchpv("@", TRUE, SVt_PV));
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);