3 * Copyright (c) 1987-1997 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> */
27 dEXTCONST char rcsid[] = "perl.c\nPatch level: ###\n";
35 #ifdef SETUID_SCRIPTS_ARE_SECURE_NOW
45 curcop = &compiling; \
52 laststype = OP_STAT; \
54 maxsysfd = MAXSYSFD; \
61 laststype = OP_STAT; \
65 static void find_beginning _((void));
66 static void forbid_setid _((char *));
67 static void incpush _((char *, int));
68 static void init_ids _((void));
69 static void init_debugger _((void));
70 static void init_lexer _((void));
71 static void init_main_stash _((void));
72 static void init_perllib _((void));
73 static void init_postdump_symbols _((int, char **, char **));
74 static void init_predump_symbols _((void));
75 static void my_exit_jump _((void)) __attribute__((noreturn));
76 static void nuke_stacks _((void));
77 static void open_script _((char *, bool, SV *));
78 static void usage _((char *));
79 static void validate_suid _((char *, char*));
81 static int fdscript = -1;
83 #if defined(DEBUGGING) && defined(USE_THREADS) && defined(__linux__)
84 #include <asm/sigcontext.h>
86 catch_sigsegv(int signo, struct sigcontext_struct sc)
88 signal(SIGSEGV, SIG_DFL);
89 fprintf(stderr, "Segmentation fault dereferencing 0x%lx\n"
90 "return_address = 0x%lx, eip = 0x%lx\n",
91 sc.cr2, __builtin_return_address(0), sc.eip);
92 fprintf(stderr, "thread = 0x%lx\n", (unsigned long)THR);
99 PerlInterpreter *sv_interp;
102 New(53, sv_interp, 1, PerlInterpreter);
107 perl_construct( sv_interp )
108 register PerlInterpreter *sv_interp;
110 #if defined(USE_THREADS) && !defined(FAKE_THREADS)
114 if (!(curinterp = sv_interp))
118 Zero(sv_interp, 1, PerlInterpreter);
121 /* Init the real globals (and main thread)? */
125 Newz(53, thr, 1, struct thread);
126 MUTEX_INIT(&malloc_mutex);
127 MUTEX_INIT(&sv_mutex);
128 MUTEX_INIT(&eval_mutex);
129 COND_INIT(&eval_cond);
130 MUTEX_INIT(&threads_mutex);
131 COND_INIT(&nthreads_cond);
135 thr->flags = THRf_NORMAL;
140 thr->next_run = thr->prev_run = thr;
146 DuplicateHandle(GetCurrentProcess(),
152 DUPLICATE_SAME_ACCESS);
153 /* XXX TlsAlloc() should probably be done in the DLL entry
156 if ((thr_key = TlsAlloc()) == TLS_OUT_OF_INDEXES)
157 croak("panic: pthread_key_create");
158 if (TlsSetValue(thr_key, (LPVOID) thr) != TRUE)
159 croak("panic: pthread_setspecific");
161 self = pthread_self();
162 if (pthread_key_create(&thr_key, 0))
163 croak("panic: pthread_key_create");
164 if (pthread_setspecific(thr_key, (void *) thr))
165 croak("panic: pthread_setspecific");
167 #endif /* FAKE_THREADS */
168 #endif /* USE_THREADS */
170 linestr = NEWSV(65,80);
171 sv_upgrade(linestr,SVt_PVIV);
173 if (!SvREADONLY(&sv_undef)) {
174 SvREADONLY_on(&sv_undef);
178 SvREADONLY_on(&sv_no);
180 sv_setpv(&sv_yes,Yes);
182 SvREADONLY_on(&sv_yes);
185 nrs = newSVpv("\n", 1);
186 rs = SvREFCNT_inc(nrs);
188 sighandlerp = sighandler;
193 * There is no way we can refer to them from Perl so close them to save
194 * space. The other alternative would be to provide STDAUX and STDPRN
197 (void)fclose(stdaux);
198 (void)fclose(stdprn);
204 perl_destruct_level = 1;
206 if(perl_destruct_level > 0)
212 start_env.je_prev = NULL;
213 start_env.je_ret = -1;
214 start_env.je_mustcatch = TRUE;
215 top_env = &start_env;
218 SET_NUMERIC_STANDARD();
219 #if defined(SUBVERSION) && SUBVERSION > 0
220 sprintf(patchlevel, "%7.5f", (double) 5
221 + ((double) PATCHLEVEL / (double) 1000)
222 + ((double) SUBVERSION / (double) 100000));
224 sprintf(patchlevel, "%5.3f", (double) 5 +
225 ((double) PATCHLEVEL / (double) 1000));
228 #if defined(LOCAL_PATCH_COUNT)
229 localpatches = local_patches; /* For possible -v */
232 PerlIO_init(); /* Hook to IO system */
234 fdpid = newAV(); /* for remembering popen pids by fd */
238 New(51,debname,128,char);
239 New(52,debdelim,128,char);
246 perl_destruct(sv_interp)
247 register PerlInterpreter *sv_interp;
250 int destruct_level; /* 0=none, 1=full, 2=full with checks */
255 if (!(curinterp = sv_interp))
260 /* Detach any remaining joinable threads apart from ourself */
261 MUTEX_LOCK(&threads_mutex);
262 DEBUG_L(PerlIO_printf(PerlIO_stderr(),
263 "perl_destruct: detaching remaining %d threads\n",
265 for (t = thr->next; t != thr; t = t->next) {
266 if (ThrSTATE(t) == THRf_NORMAL) {
268 ThrSETSTATE(t, THRf_DETACHED);
269 DEBUG_L(PerlIO_printf(PerlIO_stderr(), "...detached %p\n", t));
272 /* Now wait for the thread count nthreads to drop to one */
275 DEBUG_L(PerlIO_printf(PerlIO_stderr(),
276 "perl_destruct: waiting for %d threads\n",
278 COND_WAIT(&nthreads_cond, &threads_mutex);
280 /* At this point, we're the last thread */
281 MUTEX_UNLOCK(&threads_mutex);
282 DEBUG_L(PerlIO_printf(PerlIO_stderr(), "perl_destruct: armageddon has arrived\n"));
283 MUTEX_DESTROY(&threads_mutex);
284 COND_DESTROY(&nthreads_cond);
285 #endif /* !defined(FAKE_THREADS) */
286 #endif /* USE_THREADS */
288 destruct_level = perl_destruct_level;
292 if (s = getenv("PERL_DESTRUCT_LEVEL")) {
294 if (destruct_level < i)
303 /* We must account for everything. */
305 /* Destroy the main CV and syntax tree */
307 curpad = AvARRAY(comppad);
312 SvREFCNT_dec(main_cv);
317 * Try to destruct global references. We do this first so that the
318 * destructors and destructees still exist. Some sv's might remain.
319 * Non-referenced objects are on their own.
326 /* unhook hooks which will soon be, or use, destroyed data */
327 SvREFCNT_dec(warnhook);
329 SvREFCNT_dec(diehook);
331 SvREFCNT_dec(parsehook);
334 if (destruct_level == 0){
336 DEBUG_P(debprofdump());
338 /* The exit() function will do everything that needs doing. */
342 /* loosen bonds of global variables */
345 (void)PerlIO_close(rsfp);
349 /* Filters for program text */
350 SvREFCNT_dec(rsfp_filters);
351 rsfp_filters = Nullav;
363 sawampersand = FALSE; /* must save all match strings */
364 sawstudy = FALSE; /* do fbm_instr on all strings */
379 /* magical thingies */
381 Safefree(ofs); /* $, */
384 Safefree(ors); /* $\ */
387 SvREFCNT_dec(nrs); /* $\ helper */
390 multiline = 0; /* $* */
392 SvREFCNT_dec(statname);
396 /* defgv, aka *_ should be taken care of elsewhere */
398 #if 0 /* just about all regexp stuff, seems to be ok */
400 /* shortcuts to regexp stuff */
405 SAVEFREEOP(oldlastpm); /* for saving regexp context during debugger */
407 regprecomp = NULL; /* uncompiled string. */
408 regparse = NULL; /* Input-scan pointer. */
409 regxend = NULL; /* End of input for compile */
410 regnpar = 0; /* () count. */
411 regcode = NULL; /* Code-emit pointer; ®dummy = don't. */
412 regsize = 0; /* Code size. */
413 regnaughty = 0; /* How bad is this pattern? */
414 regsawback = 0; /* Did we see \1, ...? */
416 reginput = NULL; /* String-input pointer. */
417 regbol = NULL; /* Beginning of input, for ^ check. */
418 regeol = NULL; /* End of input, for $ check. */
419 regstartp = (char **)NULL; /* Pointer to startp array. */
420 regendp = (char **)NULL; /* Ditto for endp. */
421 reglastparen = 0; /* Similarly for lastparen. */
422 regtill = NULL; /* How far we are required to go. */
423 regflags = 0; /* are we folding, multilining? */
424 regprev = (char)NULL; /* char before regbol, \n if none */
428 /* clean up after study() */
429 SvREFCNT_dec(lastscream);
431 Safefree(screamfirst);
433 Safefree(screamnext);
436 /* startup and shutdown function lists */
437 SvREFCNT_dec(beginav);
439 SvREFCNT_dec(initav);
444 /* temp stack during pp_sort() */
445 SvREFCNT_dec(sortstack);
448 /* shortcuts just get cleared */
458 /* reset so print() ends up where we expect */
461 /* Prepare to destruct main symbol table. */
468 if (destruct_level >= 2) {
469 if (scopestack_ix != 0)
470 warn("Unbalanced scopes: %ld more ENTERs than LEAVEs\n",
471 (long)scopestack_ix);
472 if (savestack_ix != 0)
473 warn("Unbalanced saves: %ld more saves than restores\n",
475 if (tmps_floor != -1)
476 warn("Unbalanced tmps: %ld more allocs than frees\n",
477 (long)tmps_floor + 1);
478 if (cxstack_ix != -1)
479 warn("Unbalanced context: %ld more PUSHes than POPs\n",
480 (long)cxstack_ix + 1);
483 /* Now absolutely destruct everything, somehow or other, loops or no. */
485 SvFLAGS(strtab) |= SVTYPEMASK; /* don't clean out strtab now */
486 while (sv_count != 0 && sv_count != last_sv_count) {
487 last_sv_count = sv_count;
490 SvFLAGS(strtab) &= ~SVTYPEMASK;
491 SvFLAGS(strtab) |= SVt_PVHV;
493 /* Destruct the global string table. */
495 /* Yell and reset the HeVAL() slots that are still holding refcounts,
496 * so that sv_free() won't fail on them.
505 array = HvARRAY(strtab);
509 warn("Unbalanced string table refcount: (%d) for \"%s\"",
510 HeVAL(hent) - Nullsv, HeKEY(hent));
511 HeVAL(hent) = Nullsv;
521 SvREFCNT_dec(strtab);
524 warn("Scalars leaked: %ld\n", (long)sv_count);
528 /* No SVs have survived, need to clean out */
532 Safefree(origfilename);
534 hints = 0; /* Reset hints. Should hints be per-interpreter ? */
536 DEBUG_P(debprofdump());
538 MUTEX_DESTROY(&sv_mutex);
539 MUTEX_DESTROY(&malloc_mutex);
540 MUTEX_DESTROY(&eval_mutex);
541 COND_DESTROY(&eval_cond);
542 #endif /* USE_THREADS */
544 /* As the absolutely last thing, free the non-arena SV for mess() */
547 /* we know that type >= SVt_PV */
549 Safefree(SvPVX(mess_sv));
550 Safefree(SvANY(mess_sv));
558 PerlInterpreter *sv_interp;
560 if (!(curinterp = sv_interp))
566 perl_parse(sv_interp, xsinit, argc, argv, env)
567 PerlInterpreter *sv_interp;
568 void (*xsinit)_((void));
576 char *scriptname = NULL;
577 VOL bool dosearch = FALSE;
584 #ifdef SETUID_SCRIPTS_ARE_SECURE_NOW
587 croak("suidperl is no longer needed since the kernel can now execute\n\
588 setuid perl scripts securely.\n");
592 if (!(curinterp = sv_interp))
595 #if defined(NeXT) && defined(__DYNAMIC__)
596 _dyld_lookup_and_bind
597 ("__environ", (unsigned long *) &environ_pointer, NULL);
602 #ifndef VMS /* VMS doesn't have environ array */
603 origenviron = environ;
609 /* Come here if running an undumped a.out. */
611 origfilename = savepv(argv[0]);
613 cxstack_ix = -1; /* start label stack again */
615 init_postdump_symbols(argc,argv,env);
620 curpad = AvARRAY(comppad);
625 SvREFCNT_dec(main_cv);
629 oldscope = scopestack_ix;
637 /* my_exit() was called */
638 while (scopestack_ix > oldscope)
643 call_list(oldscope, endav);
645 return STATUS_NATIVE_EXPORT;
648 PerlIO_printf(PerlIO_stderr(), "panic: top_env\n");
652 sv_setpvn(linestr,"",0);
653 sv = newSVpv("",0); /* first used for -I flags */
657 for (argc--,argv++; argc > 0; argc--,argv++) {
658 if (argv[0][0] != '-' || !argv[0][1])
662 validarg = " PHOOEY ";
687 if (s = moreswitches(s))
697 if (euid != uid || egid != gid)
698 croak("No -e allowed in setuid scripts");
700 e_tmpname = savepv(TMPPATH);
701 (void)mktemp(e_tmpname);
703 croak("Can't mktemp()");
704 e_fp = PerlIO_open(e_tmpname,"w");
706 croak("Cannot open temporary file");
711 PerlIO_puts(e_fp,argv[1]);
715 croak("No code specified for -e");
716 (void)PerlIO_putc(e_fp,'\n');
727 incpush(argv[1], TRUE);
728 sv_catpv(sv,argv[1]);
745 preambleav = newAV();
746 av_push(preambleav, newSVpv("use Config qw(myconfig config_vars)",0));
748 Sv = newSVpv("print myconfig();",0);
750 sv_catpv(Sv,"print \"\\nCharacteristics of this PERLSHR image: \\n\",");
752 sv_catpv(Sv,"print \"\\nCharacteristics of this binary (from libperl): \\n\",");
754 #if defined(DEBUGGING) || defined(NO_EMBED) || defined(MULTIPLICITY)
755 sv_catpv(Sv,"\" Compile-time options:");
757 sv_catpv(Sv," DEBUGGING");
760 sv_catpv(Sv," NO_EMBED");
763 sv_catpv(Sv," MULTIPLICITY");
765 sv_catpv(Sv,"\\n\",");
767 #if defined(LOCAL_PATCH_COUNT)
768 if (LOCAL_PATCH_COUNT > 0) {
770 sv_catpv(Sv,"\" Locally applied patches:\\n\",");
771 for (i = 1; i <= LOCAL_PATCH_COUNT; i++) {
773 sv_catpvf(Sv,"\" \\t%s\\n\",",localpatches[i]);
777 sv_catpvf(Sv,"\" Built under %s\\n\"",OSNAME);
780 sv_catpvf(Sv,",\" Compiled at %s %s\\n\"",__DATE__,__TIME__);
782 sv_catpvf(Sv,",\" Compiled on %s\\n\"",__DATE__);
787 @env = map { \"$_=\\\"$ENV{$_}\\\"\" } sort grep {/^PERL/} keys %ENV; \
788 print \" \\%ENV:\\n @env\\n\" if @env; \
789 print \" \\@INC:\\n @INC\\n\";");
792 Sv = newSVpv("config_vars(qw(",0);
797 av_push(preambleav, Sv);
798 scriptname = BIT_BUCKET; /* don't look for script or read stdin */
807 if (*++s) { /* catch use of gnu style long options */
808 if (strEQ(s, "version")) {
812 if (strEQ(s, "help")) {
816 croak("Unrecognized switch: --%s (-h will show valid options)",s);
823 croak("Unrecognized switch: -%s (-h will show valid options)",s);
828 if (!tainting && (s = getenv("PERL5OPT"))) {
839 if (!strchr("DIMUdmw", *s))
840 croak("Illegal switch in PERL5OPT: -%c", *s);
846 scriptname = argv[0];
848 if (PerlIO_flush(e_fp) || PerlIO_error(e_fp) || PerlIO_close(e_fp)) {
850 warn("Did you forget to compile with -DMULTIPLICITY?");
852 croak("Can't write to temp file for -e: %s", Strerror(errno));
856 scriptname = e_tmpname;
858 else if (scriptname == Nullch) {
860 if ( isatty(PerlIO_fileno(PerlIO_stdin())) )
868 open_script(scriptname,dosearch,sv);
870 validate_suid(validarg, scriptname);
875 main_cv = compcv = (CV*)NEWSV(1104,0);
876 sv_upgrade((SV *)compcv, SVt_PVCV);
880 av_push(comppad, Nullsv);
881 curpad = AvARRAY(comppad);
882 comppad_name = newAV();
883 comppad_name_fill = 0;
884 min_intro_pending = 0;
887 av_store(comppad_name, 0, newSVpv("@_", 2));
888 curpad[0] = (SV*)newAV();
889 SvPADMY_on(curpad[0]); /* XXX Needed? */
891 New(666, CvMUTEXP(compcv), 1, perl_mutex);
892 MUTEX_INIT(CvMUTEXP(compcv));
893 #endif /* USE_THREADS */
895 comppadlist = newAV();
896 AvREAL_off(comppadlist);
897 av_store(comppadlist, 0, (SV*)comppad_name);
898 av_store(comppadlist, 1, (SV*)comppad);
899 CvPADLIST(compcv) = comppadlist;
901 boot_core_UNIVERSAL();
903 (*xsinit)(); /* in case linked C routines want magical variables */
904 #if defined(VMS) || defined(WIN32)
908 #if defined(DEBUGGING) && defined(USE_THREADS) && defined(__linux__)
909 DEBUG_L(signal(SIGSEGV, (void(*)(int))catch_sigsegv););
912 init_predump_symbols();
914 init_postdump_symbols(argc,argv,env);
918 /* now parse the script */
921 if (yyparse() || error_count) {
923 croak("%s had compilation errors.\n", origfilename);
925 croak("Execution of %s aborted due to compilation errors.\n",
929 curcop->cop_line = 0;
933 (void)UNLINK(e_tmpname);
938 /* now that script is parsed, we can modify record separator */
940 rs = SvREFCNT_inc(nrs);
941 sv_setsv(GvSV(gv_fetchpv("/", TRUE, SVt_PV)), rs);
953 if ((s=getenv("PERL_DEBUG_MSTATS")) && atoi(s) >= 2)
954 dump_mstats("after compilation:");
965 PerlInterpreter *sv_interp;
972 if (!(curinterp = sv_interp))
975 oldscope = scopestack_ix;
980 cxstack_ix = -1; /* start context stack again */
983 /* my_exit() was called */
984 while (scopestack_ix > oldscope)
989 call_list(oldscope, endav);
991 if (getenv("PERL_DEBUG_MSTATS"))
992 dump_mstats("after execution: ");
995 return STATUS_NATIVE_EXPORT;
998 PerlIO_printf(PerlIO_stderr(), "panic: restartop\n");
1003 if (curstack != mainstack) {
1005 SWITCHSTACK(curstack, mainstack);
1010 DEBUG_r(PerlIO_printf(PerlIO_stderr(), "%s $` $& $' support.\n",
1011 sawampersand ? "Enabling" : "Omitting"));
1014 DEBUG_x(dump_all());
1015 DEBUG(PerlIO_printf(Perl_debug_log, "\nEXECUTING...\n\n"));
1017 DEBUG_L(PerlIO_printf(Perl_debug_log, "main thread is 0x%lx\n",
1018 (unsigned long) thr));
1019 #endif /* USE_THREADS */
1022 PerlIO_printf(PerlIO_stderr(), "%s syntax OK\n", origfilename);
1025 if (PERLDB_SINGLE && DBsingle)
1026 sv_setiv(DBsingle, 1);
1028 call_list(oldscope, initav);
1038 else if (main_start) {
1039 CvDEPTH(main_cv) = 1;
1050 perl_get_sv(name, create)
1054 GV* gv = gv_fetchpv(name, create, SVt_PV);
1061 perl_get_av(name, create)
1065 GV* gv = gv_fetchpv(name, create, SVt_PVAV);
1074 perl_get_hv(name, create)
1078 GV* gv = gv_fetchpv(name, create, SVt_PVHV);
1087 perl_get_cv(name, create)
1091 GV* gv = gv_fetchpv(name, create, SVt_PVCV);
1092 if (create && !GvCVu(gv))
1093 return newSUB(start_subparse(FALSE, 0),
1094 newSVOP(OP_CONST, 0, newSVpv(name,0)),
1102 /* Be sure to refetch the stack pointer after calling these routines. */
1105 perl_call_argv(subname, flags, argv)
1107 I32 flags; /* See G_* flags in cop.h */
1108 register char **argv; /* null terminated arg list */
1116 XPUSHs(sv_2mortal(newSVpv(*argv,0)));
1121 return perl_call_pv(subname, flags);
1125 perl_call_pv(subname, flags)
1126 char *subname; /* name of the subroutine */
1127 I32 flags; /* See G_* flags in cop.h */
1129 return perl_call_sv((SV*)perl_get_cv(subname, TRUE), flags);
1133 perl_call_method(methname, flags)
1134 char *methname; /* name of the subroutine */
1135 I32 flags; /* See G_* flags in cop.h */
1142 XPUSHs(sv_2mortal(newSVpv(methname,0)));
1145 return perl_call_sv(*stack_sp--, flags);
1148 /* May be called with any of a CV, a GV, or an SV containing the name. */
1150 perl_call_sv(sv, flags)
1152 I32 flags; /* See G_* flags in cop.h */
1155 LOGOP myop; /* fake syntax tree node */
1161 bool oldcatch = CATCH_GET;
1166 if (flags & G_DISCARD) {
1171 Zero(&myop, 1, LOGOP);
1172 myop.op_next = Nullop;
1173 if (!(flags & G_NOARGS))
1174 myop.op_flags |= OPf_STACKED;
1175 myop.op_flags |= ((flags & G_VOID) ? OPf_WANT_VOID :
1176 (flags & G_ARRAY) ? OPf_WANT_LIST :
1181 EXTEND(stack_sp, 1);
1184 oldscope = scopestack_ix;
1186 if (PERLDB_SUB && curstash != debstash
1187 /* Handle first BEGIN of -d. */
1188 && (DBcv || (DBcv = GvCV(DBsub)))
1189 /* Try harder, since this may have been a sighandler, thus
1190 * curstash may be meaningless. */
1191 && (SvTYPE(sv) != SVt_PVCV || CvSTASH((CV*)sv) != debstash))
1192 op->op_private |= OPpENTERSUB_DB;
1194 if (flags & G_EVAL) {
1195 cLOGOP->op_other = op;
1197 /* we're trying to emulate pp_entertry() here */
1199 register CONTEXT *cx;
1200 I32 gimme = GIMME_V;
1205 push_return(op->op_next);
1206 PUSHBLOCK(cx, CXt_EVAL, stack_sp);
1208 eval_root = op; /* Only needed so that goto works right. */
1211 if (flags & G_KEEPERR)
1214 sv_setpv(GvSV(errgv),"");
1226 /* my_exit() was called */
1227 curstash = defstash;
1231 croak("Callback called exit");
1240 stack_sp = stack_base + oldmark;
1241 if (flags & G_ARRAY)
1245 *++stack_sp = &sv_undef;
1253 if (op == (OP*)&myop)
1254 op = pp_entersub(ARGS);
1257 retval = stack_sp - (stack_base + oldmark);
1258 if ((flags & G_EVAL) && !(flags & G_KEEPERR))
1259 sv_setpv(GvSV(errgv),"");
1262 if (flags & G_EVAL) {
1263 if (scopestack_ix > oldscope) {
1267 register CONTEXT *cx;
1279 CATCH_SET(oldcatch);
1281 if (flags & G_DISCARD) {
1282 stack_sp = stack_base + oldmark;
1291 /* Eval a string. The G_EVAL flag is always assumed. */
1294 perl_eval_sv(sv, flags)
1296 I32 flags; /* See G_* flags in cop.h */
1299 UNOP myop; /* fake syntax tree node */
1301 I32 oldmark = sp - stack_base;
1308 if (flags & G_DISCARD) {
1316 EXTEND(stack_sp, 1);
1318 oldscope = scopestack_ix;
1320 if (!(flags & G_NOARGS))
1321 myop.op_flags = OPf_STACKED;
1322 myop.op_next = Nullop;
1323 myop.op_type = OP_ENTEREVAL;
1324 myop.op_flags |= ((flags & G_VOID) ? OPf_WANT_VOID :
1325 (flags & G_ARRAY) ? OPf_WANT_LIST :
1327 if (flags & G_KEEPERR)
1328 myop.op_flags |= OPf_SPECIAL;
1338 /* my_exit() was called */
1339 curstash = defstash;
1343 croak("Callback called exit");
1352 stack_sp = stack_base + oldmark;
1353 if (flags & G_ARRAY)
1357 *++stack_sp = &sv_undef;
1362 if (op == (OP*)&myop)
1363 op = pp_entereval(ARGS);
1366 retval = stack_sp - (stack_base + oldmark);
1367 if (!(flags & G_KEEPERR))
1368 sv_setpv(GvSV(errgv),"");
1372 if (flags & G_DISCARD) {
1373 stack_sp = stack_base + oldmark;
1383 perl_eval_pv(p, croak_on_error)
1389 SV* sv = newSVpv(p, 0);
1392 perl_eval_sv(sv, G_SCALAR);
1399 if (croak_on_error && SvTRUE(GvSV(errgv)))
1400 croak(SvPVx(GvSV(errgv), na));
1405 /* Require a module. */
1411 SV* sv = sv_newmortal();
1412 sv_setpv(sv, "require '");
1415 perl_eval_sv(sv, G_DISCARD);
1419 magicname(sym,name,namlen)
1426 if (gv = gv_fetchpv(sym,TRUE, SVt_PV))
1427 sv_magic(GvSV(gv), (SV*)gv, 0, name, namlen);
1431 usage(name) /* XXX move this out into a module ? */
1434 /* This message really ought to be max 23 lines.
1435 * Removed -h because the user already knows that opton. Others? */
1436 printf("\nUsage: %s [switches] [--] [programfile] [arguments]", name);
1437 printf("\n -0[octal] specify record separator (\\0, if no argument)");
1438 printf("\n -a autosplit mode with -n or -p (splits $_ into @F)");
1439 printf("\n -c check syntax only (runs BEGIN and END blocks)");
1440 printf("\n -d[:debugger] run scripts under debugger");
1441 printf("\n -D[number/list] set debugging flags (argument is a bit mask or flags)");
1442 printf("\n -e 'command' one line of script. Several -e's allowed. Omit [programfile].");
1443 printf("\n -F/pattern/ split() pattern for autosplit (-a). The //'s are optional.");
1444 printf("\n -i[extension] edit <> files in place (make backup if extension supplied)");
1445 printf("\n -Idirectory specify @INC/#include directory (may be used more than once)");
1446 printf("\n -l[octal] enable line ending processing, specifies line terminator");
1447 printf("\n -[mM][-]module.. executes `use/no module...' before executing your script.");
1448 printf("\n -n assume 'while (<>) { ... }' loop around your script");
1449 printf("\n -p assume loop like -n but print line also like sed");
1450 printf("\n -P run script through C preprocessor before compilation");
1451 printf("\n -s enable some switch parsing for switches after script name");
1452 printf("\n -S look for the script using PATH environment variable");
1453 printf("\n -T turn on tainting checks");
1454 printf("\n -u dump core after parsing script");
1455 printf("\n -U allow unsafe operations");
1456 printf("\n -v print version number and patchlevel of perl");
1457 printf("\n -V[:variable] print perl configuration information");
1458 printf("\n -w TURN WARNINGS ON FOR COMPILATION OF YOUR SCRIPT. Recommended.");
1459 printf("\n -x[directory] strip off text before #!perl line and perhaps cd to directory\n");
1462 /* This routine handles any switches that can be given during run */
1473 rschar = scan_oct(s, 4, &numlen);
1475 if (rschar & ~((U8)~0))
1477 else if (!rschar && numlen >= 2)
1478 nrs = newSVpv("", 0);
1481 nrs = newSVpv(&ch, 1);
1486 splitstr = savepv(s + 1);
1500 if (*s == ':' || *s == '=') {
1501 my_setenv("PERL5DB", form("use Devel::%s;", ++s));
1505 perldb = PERLDB_ALL;
1512 if (isALPHA(s[1])) {
1513 static char debopts[] = "psltocPmfrxuLHXD";
1516 for (s++; *s && (d = strchr(debopts,*s)); s++)
1517 debug |= 1 << (d - debopts);
1521 for (s++; isDIGIT(*s); s++) ;
1523 debug |= 0x80000000;
1525 warn("Recompile perl with -DDEBUGGING to use -D switch\n");
1526 for (s++; isALNUM(*s); s++) ;
1536 inplace = savepv(s+1);
1538 for (s = inplace; *s && !isSPACE(*s); s++) ;
1545 for (e = s; *e && !isSPACE(*e); e++) ;
1546 p = savepvn(s, e-s);
1553 croak("No space allowed after -I");
1563 *ors = scan_oct(s, 3 + (*s == '0'), &numlen);
1572 ors = SvPV(nrs, orslen);
1573 ors = savepvn(ors, orslen);
1577 forbid_setid("-M"); /* XXX ? */
1580 forbid_setid("-m"); /* XXX ? */
1585 /* -M-foo == 'no foo' */
1586 if (*s == '-') { use = "no "; ++s; }
1587 sv = newSVpv(use,0);
1589 /* We allow -M'Module qw(Foo Bar)' */
1590 while(isALNUM(*s) || *s==':') ++s;
1592 sv_catpv(sv, start);
1593 if (*(start-1) == 'm') {
1595 croak("Can't use '%c' after -mname", *s);
1596 sv_catpv( sv, " ()");
1599 sv_catpvn(sv, start, s-start);
1600 sv_catpv(sv, " split(/,/,q{");
1605 if (preambleav == NULL)
1606 preambleav = newAV();
1607 av_push(preambleav, sv);
1610 croak("No space allowed after -%c", *(s-1));
1627 croak("Too late for \"-T\" option");
1639 #if defined(SUBVERSION) && SUBVERSION > 0
1640 printf("\nThis is perl, version 5.%03d_%02d", PATCHLEVEL, SUBVERSION);
1642 printf("\nThis is perl, version %s",patchlevel);
1645 printf("\n\nCopyright 1987-1997, Larry Wall\n");
1647 printf("\n\nMS-DOS port Copyright (c) 1989, 1990, Diomidis Spinellis\n");
1650 printf("djgpp v2 port (jpl5003c) by Hirofumi Watanabe, 1996\n");
1653 printf("\n\nOS/2 port Copyright (c) 1990, 1991, Raymond Chen, Kai Uwe Rommel\n"
1654 "Version 5 port Copyright (c) 1994-1997, Andreas Kaiser, Ilya Zakharevich\n");
1657 printf("atariST series port, ++jrb bammi@cadence.com\n");
1660 Perl may be copied only under the terms of either the Artistic License or the\n\
1661 GNU General Public License, which may be found in the Perl 5.0 source kit.\n\n");
1669 if (s[1] == '-') /* Additional switches on #! line. */
1677 #ifdef ALTERNATE_SHEBANG
1678 case 'S': /* OS/2 needs -S on "extproc" line. */
1686 croak("Can't emulate -%.1s on #! line",s);
1691 /* compliments of Tom Christiansen */
1693 /* unexec() can be found in the Gnu emacs distribution */
1704 prog = newSVpv(BIN_EXP);
1705 sv_catpv(prog, "/perl");
1706 file = newSVpv(origfilename);
1707 sv_catpv(file, ".perldump");
1709 status = unexec(SvPVX(file), SvPVX(prog), &etext, sbrk(0), 0);
1711 PerlIO_printf(PerlIO_stderr(), "unexec of %s into %s failed!\n",
1712 SvPVX(prog), SvPVX(file));
1716 # include <lib$routines.h>
1717 lib$signal(SS$_DEBUG); /* ssdef.h #included from vmsish.h */
1719 ABORT(); /* for use with undump */
1730 /* Note that strtab is a rather special HV. Assumptions are made
1731 about not iterating on it, and not adding tie magic to it.
1732 It is properly deallocated in perl_destruct() */
1734 HvSHAREKEYS_off(strtab); /* mandatory */
1735 Newz(506,((XPVHV*)SvANY(strtab))->xhv_array,
1736 sizeof(HE*) * (((XPVHV*)SvANY(strtab))->xhv_max + 1), char);
1738 curstash = defstash = newHV();
1739 curstname = newSVpv("main",4);
1740 gv = gv_fetchpv("main::",TRUE, SVt_PVHV);
1741 SvREFCNT_dec(GvHV(gv));
1742 GvHV(gv) = (HV*)SvREFCNT_inc(defstash);
1744 HvNAME(defstash) = savepv("main");
1745 incgv = gv_HVadd(gv_AVadd(gv_fetchpv("INC",TRUE, SVt_PVAV)));
1747 defgv = gv_fetchpv("_",TRUE, SVt_PVAV);
1748 errgv = gv_HVadd(gv_fetchpv("@", TRUE, SVt_PV));
1750 (void)form("%240s",""); /* Preallocate temp - for immediate signals. */
1751 sv_grow(GvSV(errgv), 240); /* Preallocate - for immediate signals. */
1752 sv_setpvn(GvSV(errgv), "", 0);
1753 curstash = defstash;
1754 compiling.cop_stash = defstash;
1755 debstash = GvHV(gv_fetchpv("DB::", GV_ADDMULTI, SVt_PVHV));
1756 /* We must init $/ before switches are processed. */
1757 sv_setpvn(GvSV(gv_fetchpv("/", TRUE, SVt_PV)), "\n", 1);
1760 #ifdef CAN_PROTOTYPE
1762 open_script(char *scriptname, bool dosearch, SV *sv)
1765 open_script(scriptname,dosearch,sv)
1772 char *xfound = Nullch;
1773 char *xfailed = Nullch;
1777 #if defined(DOSISH) && !defined(OS2) && !defined(atarist)
1778 # define SEARCH_EXTS ".bat", ".cmd", NULL
1779 # define MAX_EXT_LEN 4
1782 # define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
1783 # define MAX_EXT_LEN 4
1786 # define SEARCH_EXTS ".pl", ".com", NULL
1787 # define MAX_EXT_LEN 4
1789 /* additional extensions to try in each dir if scriptname not found */
1791 char *ext[] = { SEARCH_EXTS };
1792 int extidx = 0, i = 0;
1793 char *curext = Nullch;
1795 # define MAX_EXT_LEN 0
1799 * If dosearch is true and if scriptname does not contain path
1800 * delimiters, search the PATH for scriptname.
1802 * If SEARCH_EXTS is also defined, will look for each
1803 * scriptname{SEARCH_EXTS} whenever scriptname is not found
1804 * while searching the PATH.
1806 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
1807 * proceeds as follows:
1809 * + look for ./scriptname{,.foo,.bar}
1810 * + search the PATH for scriptname{,.foo,.bar}
1813 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
1814 * this will not look in '.' if it's not in the PATH)
1819 int hasdir, idx = 0, deftypes = 1;
1822 hasdir = (strpbrk(scriptname,":[</") != Nullch) ;
1823 /* The first time through, just add SEARCH_EXTS to whatever we
1824 * already have, so we can check for default file types. */
1826 (!hasdir && my_trnlnm("DCL$PATH",tokenbuf,idx++)) )
1832 if ((strlen(tokenbuf) + strlen(scriptname)
1833 + MAX_EXT_LEN) >= sizeof tokenbuf)
1834 continue; /* don't search dir with too-long name */
1835 strcat(tokenbuf, scriptname);
1839 if (strEQ(scriptname, "-"))
1841 if (dosearch) { /* Look in '.' first. */
1842 char *cur = scriptname;
1844 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
1846 if (strEQ(ext[i++],curext)) {
1847 extidx = -1; /* already has an ext */
1852 DEBUG_p(PerlIO_printf(Perl_debug_log,
1853 "Looking for %s\n",cur));
1854 if (Stat(cur,&statbuf) >= 0) {
1862 if (cur == scriptname) {
1863 len = strlen(scriptname);
1864 if (len+MAX_EXT_LEN+1 >= sizeof(tokenbuf))
1866 cur = strcpy(tokenbuf, scriptname);
1868 } while (extidx >= 0 && ext[extidx] /* try an extension? */
1869 && strcpy(tokenbuf+len, ext[extidx++]));
1874 if (dosearch && !strchr(scriptname, '/')
1876 && !strchr(scriptname, '\\')
1878 && (s = getenv("PATH"))) {
1881 bufend = s + strlen(s);
1882 while (s < bufend) {
1883 #if defined(atarist) || defined(DOSISH)
1888 && *s != ';'; len++, s++) {
1889 if (len < sizeof tokenbuf)
1892 if (len < sizeof tokenbuf)
1893 tokenbuf[len] = '\0';
1894 #else /* ! (atarist || DOSISH) */
1895 s = delimcpy(tokenbuf, tokenbuf + sizeof tokenbuf, s, bufend,
1898 #endif /* ! (atarist || DOSISH) */
1901 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tokenbuf)
1902 continue; /* don't search dir with too-long name */
1904 #if defined(atarist) || defined(DOSISH)
1905 && tokenbuf[len - 1] != '/'
1906 && tokenbuf[len - 1] != '\\'
1909 tokenbuf[len++] = '/';
1910 if (len == 2 && tokenbuf[0] == '.')
1912 (void)strcpy(tokenbuf + len, scriptname);
1916 len = strlen(tokenbuf);
1917 if (extidx > 0) /* reset after previous loop */
1921 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tokenbuf));
1922 retval = Stat(tokenbuf,&statbuf);
1924 } while ( retval < 0 /* not there */
1925 && extidx>=0 && ext[extidx] /* try an extension? */
1926 && strcpy(tokenbuf+len, ext[extidx++])
1931 if (S_ISREG(statbuf.st_mode)
1932 && cando(S_IRUSR,TRUE,&statbuf)
1934 && cando(S_IXUSR,TRUE,&statbuf)
1938 xfound = tokenbuf; /* bingo! */
1942 xfailed = savepv(tokenbuf);
1945 if (!xfound && !seen_dot && !xfailed && (Stat(scriptname,&statbuf) < 0))
1947 seen_dot = 1; /* Disable message. */
1949 croak("Can't %s %s%s%s",
1950 (xfailed ? "execute" : "find"),
1951 (xfailed ? xfailed : scriptname),
1952 (xfailed ? "" : " on PATH"),
1953 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
1956 scriptname = xfound;
1959 if (strnEQ(scriptname, "/dev/fd/", 8) && isDIGIT(scriptname[8]) ) {
1960 char *s = scriptname + 8;
1969 origfilename = savepv(e_tmpname ? "-e" : scriptname);
1970 curcop->cop_filegv = gv_fetchfile(origfilename);
1971 if (strEQ(origfilename,"-"))
1973 if (fdscript >= 0) {
1974 rsfp = PerlIO_fdopen(fdscript,"r");
1975 #if defined(HAS_FCNTL) && defined(F_SETFD)
1977 fcntl(PerlIO_fileno(rsfp),F_SETFD,1); /* ensure close-on-exec */
1980 else if (preprocess) {
1981 char *cpp_cfg = CPPSTDIN;
1982 SV *cpp = NEWSV(0,0);
1983 SV *cmd = NEWSV(0,0);
1985 if (strEQ(cpp_cfg, "cppstdin"))
1986 sv_catpvf(cpp, "%s/", BIN_EXP);
1987 sv_catpv(cpp, cpp_cfg);
1990 sv_catpv(sv,PRIVLIB_EXP);
1994 sed %s -e \"/^[^#]/b\" \
1995 -e \"/^#[ ]*include[ ]/b\" \
1996 -e \"/^#[ ]*define[ ]/b\" \
1997 -e \"/^#[ ]*if[ ]/b\" \
1998 -e \"/^#[ ]*ifdef[ ]/b\" \
1999 -e \"/^#[ ]*ifndef[ ]/b\" \
2000 -e \"/^#[ ]*else/b\" \
2001 -e \"/^#[ ]*elif[ ]/b\" \
2002 -e \"/^#[ ]*undef[ ]/b\" \
2003 -e \"/^#[ ]*endif/b\" \
2006 (doextract ? "-e \"1,/^#/d\n\"" : ""),
2009 %s %s -e '/^[^#]/b' \
2010 -e '/^#[ ]*include[ ]/b' \
2011 -e '/^#[ ]*define[ ]/b' \
2012 -e '/^#[ ]*if[ ]/b' \
2013 -e '/^#[ ]*ifdef[ ]/b' \
2014 -e '/^#[ ]*ifndef[ ]/b' \
2015 -e '/^#[ ]*else/b' \
2016 -e '/^#[ ]*elif[ ]/b' \
2017 -e '/^#[ ]*undef[ ]/b' \
2018 -e '/^#[ ]*endif/b' \
2026 (doextract ? "-e '1,/^#/d\n'" : ""),
2028 scriptname, cpp, sv, CPPMINUS);
2030 #ifdef IAMSUID /* actually, this is caught earlier */
2031 if (euid != uid && !euid) { /* if running suidperl */
2033 (void)seteuid(uid); /* musn't stay setuid root */
2036 (void)setreuid((Uid_t)-1, uid);
2038 #ifdef HAS_SETRESUID
2039 (void)setresuid((Uid_t)-1, uid, (Uid_t)-1);
2045 if (geteuid() != uid)
2046 croak("Can't do seteuid!\n");
2048 #endif /* IAMSUID */
2049 rsfp = my_popen(SvPVX(cmd), "r");
2053 else if (!*scriptname) {
2054 forbid_setid("program input from stdin");
2055 rsfp = PerlIO_stdin();
2058 rsfp = PerlIO_open(scriptname,"r");
2059 #if defined(HAS_FCNTL) && defined(F_SETFD)
2061 fcntl(PerlIO_fileno(rsfp),F_SETFD,1); /* ensure close-on-exec */
2069 #ifndef IAMSUID /* in case script is not readable before setuid */
2070 if (euid && Stat(SvPVX(GvSV(curcop->cop_filegv)),&statbuf) >= 0 &&
2071 statbuf.st_mode & (S_ISUID|S_ISGID)) {
2073 execv(form("%s/sperl%s", BIN_EXP, patchlevel), origargv);
2074 croak("Can't do setuid\n");
2078 croak("Can't open perl script \"%s\": %s\n",
2079 SvPVX(GvSV(curcop->cop_filegv)), Strerror(errno));
2084 validate_suid(validarg, scriptname)
2090 /* do we need to emulate setuid on scripts? */
2092 /* This code is for those BSD systems that have setuid #! scripts disabled
2093 * in the kernel because of a security problem. Merely defining DOSUID
2094 * in perl will not fix that problem, but if you have disabled setuid
2095 * scripts in the kernel, this will attempt to emulate setuid and setgid
2096 * on scripts that have those now-otherwise-useless bits set. The setuid
2097 * root version must be called suidperl or sperlN.NNN. If regular perl
2098 * discovers that it has opened a setuid script, it calls suidperl with
2099 * the same argv that it had. If suidperl finds that the script it has
2100 * just opened is NOT setuid root, it sets the effective uid back to the
2101 * uid. We don't just make perl setuid root because that loses the
2102 * effective uid we had before invoking perl, if it was different from the
2105 * DOSUID must be defined in both perl and suidperl, and IAMSUID must
2106 * be defined in suidperl only. suidperl must be setuid root. The
2107 * Configure script will set this up for you if you want it.
2113 if (Fstat(PerlIO_fileno(rsfp),&statbuf) < 0) /* normal stat is insecure */
2114 croak("Can't stat script \"%s\"",origfilename);
2115 if (fdscript < 0 && statbuf.st_mode & (S_ISUID|S_ISGID)) {
2119 #ifndef HAS_SETREUID
2120 /* On this access check to make sure the directories are readable,
2121 * there is actually a small window that the user could use to make
2122 * filename point to an accessible directory. So there is a faint
2123 * chance that someone could execute a setuid script down in a
2124 * non-accessible directory. I don't know what to do about that.
2125 * But I don't think it's too important. The manual lies when
2126 * it says access() is useful in setuid programs.
2128 if (access(SvPVX(GvSV(curcop->cop_filegv)),1)) /*double check*/
2129 croak("Permission denied");
2131 /* If we can swap euid and uid, then we can determine access rights
2132 * with a simple stat of the file, and then compare device and
2133 * inode to make sure we did stat() on the same file we opened.
2134 * Then we just have to make sure he or she can execute it.
2137 struct stat tmpstatbuf;
2141 setreuid(euid,uid) < 0
2144 setresuid(euid,uid,(Uid_t)-1) < 0
2147 || getuid() != euid || geteuid() != uid)
2148 croak("Can't swap uid and euid"); /* really paranoid */
2149 if (Stat(SvPVX(GvSV(curcop->cop_filegv)),&tmpstatbuf) < 0)
2150 croak("Permission denied"); /* testing full pathname here */
2151 if (tmpstatbuf.st_dev != statbuf.st_dev ||
2152 tmpstatbuf.st_ino != statbuf.st_ino) {
2153 (void)PerlIO_close(rsfp);
2154 if (rsfp = my_popen("/bin/mail root","w")) { /* heh, heh */
2156 "User %ld tried to run dev %ld ino %ld in place of dev %ld ino %ld!\n\
2157 (Filename of set-id script was %s, uid %ld gid %ld.)\n\nSincerely,\nperl\n",
2158 (long)uid,(long)tmpstatbuf.st_dev, (long)tmpstatbuf.st_ino,
2159 (long)statbuf.st_dev, (long)statbuf.st_ino,
2160 SvPVX(GvSV(curcop->cop_filegv)),
2161 (long)statbuf.st_uid, (long)statbuf.st_gid);
2162 (void)my_pclose(rsfp);
2164 croak("Permission denied\n");
2168 setreuid(uid,euid) < 0
2170 # if defined(HAS_SETRESUID)
2171 setresuid(uid,euid,(Uid_t)-1) < 0
2174 || getuid() != uid || geteuid() != euid)
2175 croak("Can't reswap uid and euid");
2176 if (!cando(S_IXUSR,FALSE,&statbuf)) /* can real uid exec? */
2177 croak("Permission denied\n");
2179 #endif /* HAS_SETREUID */
2180 #endif /* IAMSUID */
2182 if (!S_ISREG(statbuf.st_mode))
2183 croak("Permission denied");
2184 if (statbuf.st_mode & S_IWOTH)
2185 croak("Setuid/gid script is writable by world");
2186 doswitches = FALSE; /* -s is insecure in suid */
2188 if (sv_gets(linestr, rsfp, 0) == Nullch ||
2189 strnNE(SvPV(linestr,na),"#!",2) ) /* required even on Sys V */
2190 croak("No #! line");
2191 s = SvPV(linestr,na)+2;
2193 while (!isSPACE(*s)) s++;
2194 for (s2 = s; (s2 > SvPV(linestr,na)+2 &&
2195 (isDIGIT(s2[-1]) || strchr("._-", s2[-1]))); s2--) ;
2196 if (strnNE(s2-4,"perl",4) && strnNE(s-9,"perl",4)) /* sanity check */
2197 croak("Not a perl script");
2198 while (*s == ' ' || *s == '\t') s++;
2200 * #! arg must be what we saw above. They can invoke it by
2201 * mentioning suidperl explicitly, but they may not add any strange
2202 * arguments beyond what #! says if they do invoke suidperl that way.
2204 len = strlen(validarg);
2205 if (strEQ(validarg," PHOOEY ") ||
2206 strnNE(s,validarg,len) || !isSPACE(s[len]))
2207 croak("Args must match #! line");
2210 if (euid != uid && (statbuf.st_mode & S_ISUID) &&
2211 euid == statbuf.st_uid)
2213 croak("YOU HAVEN'T DISABLED SET-ID SCRIPTS IN THE KERNEL YET!\n\
2214 FIX YOUR KERNEL, PUT A C WRAPPER AROUND THIS SCRIPT, OR USE -u AND UNDUMP!\n");
2215 #endif /* IAMSUID */
2217 if (euid) { /* oops, we're not the setuid root perl */
2218 (void)PerlIO_close(rsfp);
2221 execv(form("%s/sperl%s", BIN_EXP, patchlevel), origargv);
2223 croak("Can't do setuid\n");
2226 if (statbuf.st_mode & S_ISGID && statbuf.st_gid != egid) {
2228 (void)setegid(statbuf.st_gid);
2231 (void)setregid((Gid_t)-1,statbuf.st_gid);
2233 #ifdef HAS_SETRESGID
2234 (void)setresgid((Gid_t)-1,statbuf.st_gid,(Gid_t)-1);
2236 setgid(statbuf.st_gid);
2240 if (getegid() != statbuf.st_gid)
2241 croak("Can't do setegid!\n");
2243 if (statbuf.st_mode & S_ISUID) {
2244 if (statbuf.st_uid != euid)
2246 (void)seteuid(statbuf.st_uid); /* all that for this */
2249 (void)setreuid((Uid_t)-1,statbuf.st_uid);
2251 #ifdef HAS_SETRESUID
2252 (void)setresuid((Uid_t)-1,statbuf.st_uid,(Uid_t)-1);
2254 setuid(statbuf.st_uid);
2258 if (geteuid() != statbuf.st_uid)
2259 croak("Can't do seteuid!\n");
2261 else if (uid) { /* oops, mustn't run as root */
2263 (void)seteuid((Uid_t)uid);
2266 (void)setreuid((Uid_t)-1,(Uid_t)uid);
2268 #ifdef HAS_SETRESUID
2269 (void)setresuid((Uid_t)-1,(Uid_t)uid,(Uid_t)-1);
2275 if (geteuid() != uid)
2276 croak("Can't do seteuid!\n");
2279 if (!cando(S_IXUSR,TRUE,&statbuf))
2280 croak("Permission denied\n"); /* they can't do this */
2283 else if (preprocess)
2284 croak("-P not allowed for setuid/setgid script\n");
2285 else if (fdscript >= 0)
2286 croak("fd script not allowed in suidperl\n");
2288 croak("Script is not setuid/setgid in suidperl\n");
2290 /* We absolutely must clear out any saved ids here, so we */
2291 /* exec the real perl, substituting fd script for scriptname. */
2292 /* (We pass script name as "subdir" of fd, which perl will grok.) */
2293 PerlIO_rewind(rsfp);
2294 lseek(PerlIO_fileno(rsfp),(Off_t)0,0); /* just in case rewind didn't */
2295 for (which = 1; origargv[which] && origargv[which] != scriptname; which++) ;
2296 if (!origargv[which])
2297 croak("Permission denied");
2298 origargv[which] = savepv(form("/dev/fd/%d/%s",
2299 PerlIO_fileno(rsfp), origargv[which]));
2300 #if defined(HAS_FCNTL) && defined(F_SETFD)
2301 fcntl(PerlIO_fileno(rsfp),F_SETFD,0); /* ensure no close-on-exec */
2303 execv(form("%s/perl%s", BIN_EXP, patchlevel), origargv); /* try again */
2304 croak("Can't do setuid\n");
2305 #endif /* IAMSUID */
2307 if (euid != uid || egid != gid) { /* (suidperl doesn't exist, in fact) */
2308 #ifndef SETUID_SCRIPTS_ARE_SECURE_NOW
2310 Fstat(PerlIO_fileno(rsfp),&statbuf); /* may be either wrapped or real suid */
2311 if ((euid != uid && euid == statbuf.st_uid && statbuf.st_mode & S_ISUID)
2313 (egid != gid && egid == statbuf.st_gid && statbuf.st_mode & S_ISGID)
2316 croak("YOU HAVEN'T DISABLED SET-ID SCRIPTS IN THE KERNEL YET!\n\
2317 FIX YOUR KERNEL, PUT A C WRAPPER AROUND THIS SCRIPT, OR USE -u AND UNDUMP!\n");
2318 #endif /* SETUID_SCRIPTS_ARE_SECURE_NOW */
2319 /* not set-id, must be wrapped */
2327 register char *s, *s2;
2329 /* skip forward in input to the real script? */
2333 if ((s = sv_gets(linestr, rsfp, 0)) == Nullch)
2334 croak("No Perl script found in input\n");
2335 if (*s == '#' && s[1] == '!' && (s = instr(s,"perl"))) {
2336 PerlIO_ungetc(rsfp, '\n'); /* to keep line count right */
2338 while (*s && !(isSPACE (*s) || *s == '#')) s++;
2340 while (*s == ' ' || *s == '\t') s++;
2342 while (isDIGIT(s2[-1]) || strchr("-._", s2[-1])) s2--;
2343 if (strnEQ(s2-4,"perl",4))
2345 while (s = moreswitches(s)) ;
2347 if (cddir && chdir(cddir) < 0)
2348 croak("Can't chdir to %s",cddir);
2356 uid = (int)getuid();
2357 euid = (int)geteuid();
2358 gid = (int)getgid();
2359 egid = (int)getegid();
2364 tainting |= (uid && (euid != uid || egid != gid));
2372 croak("No %s allowed while running setuid", s);
2374 croak("No %s allowed while running setgid", s);
2381 curstash = debstash;
2382 dbargs = GvAV(gv_AVadd((gv_fetchpv("args", GV_ADDMULTI, SVt_PVAV))));
2384 DBgv = gv_fetchpv("DB", GV_ADDMULTI, SVt_PVGV);
2385 DBline = gv_fetchpv("dbline", GV_ADDMULTI, SVt_PVAV);
2386 DBsub = gv_HVadd(gv_fetchpv("sub", GV_ADDMULTI, SVt_PVHV));
2387 DBsingle = GvSV((gv_fetchpv("single", GV_ADDMULTI, SVt_PV)));
2388 sv_setiv(DBsingle, 0);
2389 DBtrace = GvSV((gv_fetchpv("trace", GV_ADDMULTI, SVt_PV)));
2390 sv_setiv(DBtrace, 0);
2391 DBsignal = GvSV((gv_fetchpv("signal", GV_ADDMULTI, SVt_PV)));
2392 sv_setiv(DBsignal, 0);
2393 curstash = defstash;
2401 mainstack = curstack; /* remember in case we switch stacks */
2402 AvREAL_off(curstack); /* not a real array */
2403 av_extend(curstack,127);
2405 stack_base = AvARRAY(curstack);
2406 stack_sp = stack_base;
2407 stack_max = stack_base + 127;
2409 cxstack_max = 8192 / sizeof(CONTEXT) - 2; /* Use most of 8K. */
2410 New(50,cxstack,cxstack_max + 1,CONTEXT);
2413 New(50,tmps_stack,128,SV*);
2419 * The following stacks almost certainly should be per-interpreter,
2420 * but for now they're not. XXX
2424 markstack_ptr = markstack;
2426 New(54,markstack,64,I32);
2427 markstack_ptr = markstack;
2428 markstack_max = markstack + 64;
2434 New(54,scopestack,32,I32);
2436 scopestack_max = 32;
2442 New(54,savestack,128,ANY);
2444 savestack_max = 128;
2450 New(54,retstack,16,OP*);
2461 Safefree(tmps_stack);
2468 static PerlIO *tmpfp; /* moved outside init_lexer() because of UNICOS bug */
2477 subname = newSVpv("main",4);
2481 init_predump_symbols()
2487 sv_setpvn(GvSV(gv_fetchpv("\"", TRUE, SVt_PV)), " ", 1);
2489 stdingv = gv_fetchpv("STDIN",TRUE, SVt_PVIO);
2490 GvMULTI_on(stdingv);
2491 IoIFP(GvIOp(stdingv)) = PerlIO_stdin();
2492 tmpgv = gv_fetchpv("stdin",TRUE, SVt_PV);
2494 GvIOp(tmpgv) = (IO*)SvREFCNT_inc(GvIOp(stdingv));
2496 tmpgv = gv_fetchpv("STDOUT",TRUE, SVt_PVIO);
2498 IoOFP(GvIOp(tmpgv)) = IoIFP(GvIOp(tmpgv)) = PerlIO_stdout();
2500 tmpgv = gv_fetchpv("stdout",TRUE, SVt_PV);
2502 GvIOp(tmpgv) = (IO*)SvREFCNT_inc(GvIOp(defoutgv));
2504 othergv = gv_fetchpv("STDERR",TRUE, SVt_PVIO);
2505 GvMULTI_on(othergv);
2506 IoOFP(GvIOp(othergv)) = IoIFP(GvIOp(othergv)) = PerlIO_stderr();
2507 tmpgv = gv_fetchpv("stderr",TRUE, SVt_PV);
2509 GvIOp(tmpgv) = (IO*)SvREFCNT_inc(GvIOp(othergv));
2511 statname = NEWSV(66,0); /* last filename we did stat on */
2514 osname = savepv(OSNAME);
2518 init_postdump_symbols(argc,argv,env)
2520 register char **argv;
2521 register char **env;
2527 argc--,argv++; /* skip name of script */
2529 for (; argc > 0 && **argv == '-'; argc--,argv++) {
2532 if (argv[0][1] == '-') {
2536 if (s = strchr(argv[0], '=')) {
2538 sv_setpv(GvSV(gv_fetchpv(argv[0]+1,TRUE, SVt_PV)),s);
2541 sv_setiv(GvSV(gv_fetchpv(argv[0]+1,TRUE, SVt_PV)),1);
2544 toptarget = NEWSV(0,0);
2545 sv_upgrade(toptarget, SVt_PVFM);
2546 sv_setpvn(toptarget, "", 0);
2547 bodytarget = NEWSV(0,0);
2548 sv_upgrade(bodytarget, SVt_PVFM);
2549 sv_setpvn(bodytarget, "", 0);
2550 formtarget = bodytarget;
2553 if (tmpgv = gv_fetchpv("0",TRUE, SVt_PV)) {
2554 sv_setpv(GvSV(tmpgv),origfilename);
2555 magicname("0", "0", 1);
2557 if (tmpgv = gv_fetchpv("\030",TRUE, SVt_PV))
2558 sv_setpv(GvSV(tmpgv),origargv[0]);
2559 if (argvgv = gv_fetchpv("ARGV",TRUE, SVt_PVAV)) {
2561 (void)gv_AVadd(argvgv);
2562 av_clear(GvAVn(argvgv));
2563 for (; argc > 0; argc--,argv++) {
2564 av_push(GvAVn(argvgv),newSVpv(argv[0],0));
2567 if (envgv = gv_fetchpv("ENV",TRUE, SVt_PVHV)) {
2571 hv_magic(hv, envgv, 'E');
2572 #ifndef VMS /* VMS doesn't have environ array */
2573 /* Note that if the supplied env parameter is actually a copy
2574 of the global environ then it may now point to free'd memory
2575 if the environment has been modified since. To avoid this
2576 problem we treat env==NULL as meaning 'use the default'
2581 environ[0] = Nullch;
2582 for (; *env; env++) {
2583 if (!(s = strchr(*env,'=')))
2589 sv = newSVpv(s--,0);
2590 (void)hv_store(hv, *env, s - *env, sv, 0);
2592 #if defined(__BORLANDC__) && defined(USE_WIN32_RTL_ENV)
2593 /* Sins of the RTL. See note in my_setenv(). */
2594 (void)putenv(savepv(*env));
2598 #ifdef DYNAMIC_ENV_FETCH
2599 HvNAME(hv) = savepv(ENV_HV_NAME);
2603 if (tmpgv = gv_fetchpv("$",TRUE, SVt_PV))
2604 sv_setiv(GvSV(tmpgv), (IV)getpid());
2613 s = getenv("PERL5LIB");
2617 incpush(getenv("PERLLIB"), FALSE);
2619 /* Treat PERL5?LIB as a possible search list logical name -- the
2620 * "natural" VMS idiom for a Unix path string. We allow each
2621 * element to be a set of |-separated directories for compatibility.
2625 if (my_trnlnm("PERL5LIB",buf,0))
2626 do { incpush(buf,TRUE); } while (my_trnlnm("PERL5LIB",buf,++idx));
2628 while (my_trnlnm("PERLLIB",buf,idx++)) incpush(buf,FALSE);
2632 /* Use the ~-expanded versions of APPLLIB (undocumented),
2633 ARCHLIB PRIVLIB SITEARCH SITELIB and OLDARCHLIB
2636 incpush(APPLLIB_EXP, FALSE);
2640 incpush(ARCHLIB_EXP, FALSE);
2643 #define PRIVLIB_EXP "/usr/local/lib/perl5:/usr/local/lib/perl"
2645 incpush(PRIVLIB_EXP, FALSE);
2648 incpush(SITEARCH_EXP, FALSE);
2651 incpush(SITELIB_EXP, FALSE);
2653 #ifdef OLDARCHLIB_EXP /* 5.00[01] compatibility */
2654 incpush(OLDARCHLIB_EXP, FALSE);
2658 incpush(".", FALSE);
2662 # define PERLLIB_SEP ';'
2665 # define PERLLIB_SEP '|'
2667 # define PERLLIB_SEP ':'
2670 #ifndef PERLLIB_MANGLE
2671 # define PERLLIB_MANGLE(s,n) (s)
2675 incpush(p, addsubdirs)
2679 SV *subdir = Nullsv;
2680 static char *archpat_auto;
2687 if (!archpat_auto) {
2688 STRLEN len = (sizeof(ARCHNAME) + strlen(patchlevel)
2689 + sizeof("//auto"));
2690 New(55, archpat_auto, len, char);
2691 sprintf(archpat_auto, "/%s/%s/auto", ARCHNAME, patchlevel);
2693 for (len = sizeof(ARCHNAME) + 2;
2694 archpat_auto[len] != '\0' && archpat_auto[len] != '/'; len++)
2695 if (archpat_auto[len] == '.') archpat_auto[len] = '_';
2700 /* Break at all separators */
2702 SV *libdir = newSV(0);
2705 /* skip any consecutive separators */
2706 while ( *p == PERLLIB_SEP ) {
2707 /* Uncomment the next line for PATH semantics */
2708 /* av_push(GvAVn(incgv), newSVpv(".", 1)); */
2712 if ( (s = strchr(p, PERLLIB_SEP)) != Nullch ) {
2713 sv_setpvn(libdir, PERLLIB_MANGLE(p, (STRLEN)(s - p)),
2718 sv_setpv(libdir, PERLLIB_MANGLE(p, 0));
2719 p = Nullch; /* break out */
2723 * BEFORE pushing libdir onto @INC we may first push version- and
2724 * archname-specific sub-directories.
2727 struct stat tmpstatbuf;
2732 if ((unix = tounixspec_ts(SvPV(libdir,na),Nullch)) != Nullch) {
2734 while (unix[len-1] == '/') len--; /* Cosmetic */
2735 sv_usepvn(libdir,unix,len);
2738 PerlIO_printf(PerlIO_stderr(),
2739 "Failed to unixify @INC element \"%s\"\n",
2742 /* .../archname/version if -d .../archname/version/auto */
2743 sv_setsv(subdir, libdir);
2744 sv_catpv(subdir, archpat_auto);
2745 if (Stat(SvPVX(subdir), &tmpstatbuf) >= 0 &&
2746 S_ISDIR(tmpstatbuf.st_mode))
2747 av_push(GvAVn(incgv),
2748 newSVpv(SvPVX(subdir), SvCUR(subdir) - sizeof "auto"));
2750 /* .../archname if -d .../archname/auto */
2751 sv_insert(subdir, SvCUR(libdir) + sizeof(ARCHNAME),
2752 strlen(patchlevel) + 1, "", 0);
2753 if (Stat(SvPVX(subdir), &tmpstatbuf) >= 0 &&
2754 S_ISDIR(tmpstatbuf.st_mode))
2755 av_push(GvAVn(incgv),
2756 newSVpv(SvPVX(subdir), SvCUR(subdir) - sizeof "auto"));
2759 /* finally push this lib directory on the end of @INC */
2760 av_push(GvAVn(incgv), libdir);
2763 SvREFCNT_dec(subdir);
2767 call_list(oldscope, list)
2772 line_t oldline = curcop->cop_line;
2777 while (AvFILL(list) >= 0) {
2778 CV *cv = (CV*)av_shift(list);
2785 SV* atsv = GvSV(errgv);
2787 perl_call_sv((SV*)cv, G_EVAL|G_DISCARD);
2788 (void)SvPV(atsv, len);
2791 curcop = &compiling;
2792 curcop->cop_line = oldline;
2793 if (list == beginav)
2794 sv_catpv(atsv, "BEGIN failed--compilation aborted");
2796 sv_catpv(atsv, "END failed--cleanup aborted");
2797 while (scopestack_ix > oldscope)
2799 croak("%s", SvPVX(atsv));
2807 /* my_exit() was called */
2808 while (scopestack_ix > oldscope)
2811 curstash = defstash;
2813 call_list(oldscope, endav);
2815 curcop = &compiling;
2816 curcop->cop_line = oldline;
2818 if (list == beginav)
2819 croak("BEGIN failed--compilation aborted");
2821 croak("END failed--cleanup aborted");
2827 PerlIO_printf(PerlIO_stderr(), "panic: restartop\n");
2832 curcop = &compiling;
2833 curcop->cop_line = oldline;
2847 DEBUG_L(PerlIO_printf(Perl_debug_log, "my_exit: thread 0x%lx, status %lu\n",
2848 (unsigned long) thr, (unsigned long) status));
2849 #endif /* USE_THREADS */
2858 STATUS_NATIVE_SET(status);
2868 if (vaxc$errno & 1) {
2869 if (STATUS_NATIVE & 1) /* fortuitiously includes "-1" */
2870 STATUS_NATIVE_SET(44);
2873 if (!vaxc$errno && errno) /* unlikely */
2874 STATUS_NATIVE_SET(44);
2876 STATUS_NATIVE_SET(vaxc$errno);
2880 STATUS_POSIX_SET(errno);
2881 else if (STATUS_POSIX == 0)
2882 STATUS_POSIX_SET(255);
2891 register CONTEXT *cx;
2900 (void)UNLINK(e_tmpname);
2901 Safefree(e_tmpname);
2905 if (cxstack_ix >= 0) {