perl 3.0 patch #44 patch #42, continued
[p5sagit/p5-mst-13.2.git] / perl.c
1 char rcsid[] = "$Header: perl.c,v 4.0 91/03/20 01:37:44 lwall Locked $\nPatch level: ###\n";
2 /*
3  *    Copyright (c) 1989, Larry Wall
4  *
5  *    You may distribute under the terms of the GNU General Public License
6  *    as specified in the README file that comes with the perl 3.0 kit.
7  *
8  * $Log:        perl.c,v $
9  * Revision 4.0  91/03/20  01:37:44  lwall
10  * 4.0 baseline.
11  * 
12  */
13
14 #include "EXTERN.h"
15 #include "perl.h"
16 #include "perly.h"
17 #ifdef MSDOS
18 #include "patchlev.h"
19 #else
20 #include "patchlevel.h"
21 #endif
22
23 #ifdef IAMSUID
24 #ifndef DOSUID
25 #define DOSUID
26 #endif
27 #endif
28
29 #ifdef SETUID_SCRIPTS_ARE_SECURE_NOW
30 #ifdef DOSUID
31 #undef DOSUID
32 #endif
33 #endif
34
35 static char* moreswitches();
36 static char* cddir;
37 #ifndef __STDC__
38 extern char **environ;
39 #endif /* ! __STDC__ */
40 static bool minus_c;
41 static char patchlevel[6];
42 static char *nrs = "\n";
43 static int nrschar = '\n';      /* final char of rs, or 0777 if none */
44 static int nrslen = 1;
45
46 main(argc,argv,env)
47 register int argc;
48 register char **argv;
49 register char **env;
50 {
51     register STR *str;
52     register char *s;
53     char *index(), *strcpy(), *getenv();
54     bool dosearch = FALSE;
55 #ifdef DOSUID
56     char *validarg = "";
57 #endif
58
59 #ifdef SETUID_SCRIPTS_ARE_SECURE_NOW
60 #ifdef IAMSUID
61 #undef IAMSUID
62     fatal("suidperl is no longer needed since the kernel can now execute\n\
63 setuid perl scripts securely.\n");
64 #endif
65 #endif
66
67     origargv = argv;
68     origargc = argc;
69     origenviron = environ;
70     uid = (int)getuid();
71     euid = (int)geteuid();
72     gid = (int)getgid();
73     egid = (int)getegid();
74     sprintf(patchlevel,"%3.3s%2.2d", index(rcsid,'4'), PATCHLEVEL);
75 #ifdef MSDOS
76     /*
77      * There is no way we can refer to them from Perl so close them to save
78      * space.  The other alternative would be to provide STDAUX and STDPRN
79      * filehandles.
80      */
81     (void)fclose(stdaux);
82     (void)fclose(stdprn);
83 #endif
84     if (do_undump) {
85         origfilename = savestr(argv[0]);
86         do_undump = 0;
87         loop_ptr = -1;          /* start label stack again */
88         goto just_doit;
89     }
90     (void)sprintf(index(rcsid,'#'), "%d\n", PATCHLEVEL);
91     linestr = Str_new(65,80);
92     str_nset(linestr,"",0);
93     str = str_make("",0);               /* first used for -I flags */
94     curstash = defstash = hnew(0);
95     curstname = str_make("main",4);
96     stab_xhash(stabent("_main",TRUE)) = defstash;
97     defstash->tbl_name = "main";
98     incstab = hadd(aadd(stabent("INC",TRUE)));
99     incstab->str_pok |= SP_MULTI;
100     for (argc--,argv++; argc > 0; argc--,argv++) {
101         if (argv[0][0] != '-' || !argv[0][1])
102             break;
103 #ifdef DOSUID
104     if (*validarg)
105         validarg = " PHOOEY ";
106     else
107         validarg = argv[0];
108 #endif
109         s = argv[0]+1;
110       reswitch:
111         switch (*s) {
112         case '0':
113         case 'a':
114         case 'c':
115         case 'd':
116         case 'D':
117         case 'i':
118         case 'l':
119         case 'n':
120         case 'p':
121         case 'u':
122         case 'U':
123         case 'v':
124         case 'w':
125             if (s = moreswitches(s))
126                 goto reswitch;
127             break;
128
129         case 'e':
130 #ifdef TAINT
131             if (euid != uid || egid != gid)
132                 fatal("No -e allowed in setuid scripts");
133 #endif
134             if (!e_fp) {
135                 e_tmpname = savestr(TMPPATH);
136                 (void)mktemp(e_tmpname);
137                 e_fp = fopen(e_tmpname,"w");
138                 if (!e_fp)
139                     fatal("Cannot open temporary file");
140             }
141             if (argv[1]) {
142                 fputs(argv[1],e_fp);
143                 argc--,argv++;
144             }
145             (void)putc('\n', e_fp);
146             break;
147         case 'I':
148 #ifdef TAINT
149             if (euid != uid || egid != gid)
150                 fatal("No -I allowed in setuid scripts");
151 #endif
152             str_cat(str,"-");
153             str_cat(str,s);
154             str_cat(str," ");
155             if (*++s) {
156                 (void)apush(stab_array(incstab),str_make(s,0));
157             }
158             else if (argv[1]) {
159                 (void)apush(stab_array(incstab),str_make(argv[1],0));
160                 str_cat(str,argv[1]);
161                 argc--,argv++;
162                 str_cat(str," ");
163             }
164             break;
165         case 'P':
166 #ifdef TAINT
167             if (euid != uid || egid != gid)
168                 fatal("No -P allowed in setuid scripts");
169 #endif
170             preprocess = TRUE;
171             s++;
172             goto reswitch;
173         case 's':
174 #ifdef TAINT
175             if (euid != uid || egid != gid)
176                 fatal("No -s allowed in setuid scripts");
177 #endif
178             doswitches = TRUE;
179             s++;
180             goto reswitch;
181         case 'S':
182             dosearch = TRUE;
183             s++;
184             goto reswitch;
185         case 'x':
186             doextract = TRUE;
187             s++;
188             if (*s)
189                 cddir = savestr(s);
190             break;
191         case '-':
192             argc--,argv++;
193             goto switch_end;
194         case 0:
195             break;
196         default:
197             fatal("Unrecognized switch: -%s",s);
198         }
199     }
200   switch_end:
201     if (e_fp) {
202         (void)fclose(e_fp);
203         argc++,argv--;
204         argv[0] = e_tmpname;
205     }
206
207 #ifdef MSDOS
208 #define PERLLIB_SEP ';'
209 #else
210 #define PERLLIB_SEP ':'
211 #endif
212 #ifndef TAINT           /* Can't allow arbitrary PERLLIB in setuid script */
213     {
214         char * s2 = getenv("PERLLIB");
215
216         if ( s2 ) {
217             /* Break at all separators */
218             while ( *s2 ) {
219                 /* First, skip any consecutive separators */
220                 while ( *s2 == PERLLIB_SEP ) {
221                     /* Uncomment the next line for PATH semantics */
222                     /* (void)apush(stab_array(incstab),str_make(".",1)); */
223                     s2++;
224                 }
225                 if ( (s = index(s2,PERLLIB_SEP)) != Nullch ) {
226                     (void)apush(stab_array(incstab),str_make(s2,(int)(s-s2)));
227                     s2 = s+1;
228                 } else {
229                     (void)apush(stab_array(incstab),str_make(s2,0));
230                     break;
231                 }
232             }
233         }
234     }
235 #endif /* TAINT */
236
237 #ifndef PRIVLIB
238 #define PRIVLIB "/usr/local/lib/perl"
239 #endif
240     (void)apush(stab_array(incstab),str_make(PRIVLIB,0));
241     (void)apush(stab_array(incstab),str_make(".",1));
242
243     str_set(&str_no,No);
244     str_set(&str_yes,Yes);
245
246     /* open script */
247
248     if (argv[0] == Nullch)
249 #ifdef MSDOS
250     {
251         if ( isatty(fileno(stdin)) )
252           moreswitches("v");
253         argv[0] = "-";
254     }
255 #else
256         argv[0] = "-";
257 #endif
258     if (dosearch && !index(argv[0], '/') && (s = getenv("PATH"))) {
259         char *xfound = Nullch, *xfailed = Nullch;
260         int len;
261
262         bufend = s + strlen(s);
263         while (*s) {
264 #ifndef MSDOS
265             s = cpytill(tokenbuf,s,bufend,':',&len);
266 #else
267             for (len = 0; *s && *s != ';'; tokenbuf[len++] = *s++);
268             tokenbuf[len] = '\0';
269 #endif
270             if (*s)
271                 s++;
272 #ifndef MSDOS
273             if (len && tokenbuf[len-1] != '/')
274 #else
275             if (len && tokenbuf[len-1] != '\\')
276 #endif
277                 (void)strcat(tokenbuf+len,"/");
278             (void)strcat(tokenbuf+len,argv[0]);
279 #ifdef DEBUGGING
280             if (debug & 1)
281                 fprintf(stderr,"Looking for %s\n",tokenbuf);
282 #endif
283             if (stat(tokenbuf,&statbuf) < 0)            /* not there? */
284                 continue;
285             if (S_ISREG(statbuf.st_mode)
286              && cando(S_IRUSR,TRUE,&statbuf) && cando(S_IXUSR,TRUE,&statbuf)) {
287                 xfound = tokenbuf;              /* bingo! */
288                 break;
289             }
290             if (!xfailed)
291                 xfailed = savestr(tokenbuf);
292         }
293         if (!xfound)
294             fatal("Can't execute %s", xfailed ? xfailed : argv[0] );
295         if (xfailed)
296             Safefree(xfailed);
297         argv[0] = savestr(xfound);
298     }
299
300     fdpid = anew(Nullstab);     /* for remembering popen pids by fd */
301     pidstatus = hnew(COEFFSIZE);/* for remembering status of dead pids */
302
303     origfilename = savestr(argv[0]);
304     curcmd->c_filestab = fstab(origfilename);
305     if (strEQ(origfilename,"-"))
306         argv[0] = "";
307     if (preprocess) {
308         str_cat(str,"-I");
309         str_cat(str,PRIVLIB);
310         (void)sprintf(buf, "\
311 %ssed %s -e '/^[^#]/b' \
312  -e '/^#[       ]*include[      ]/b' \
313  -e '/^#[       ]*define[       ]/b' \
314  -e '/^#[       ]*if[   ]/b' \
315  -e '/^#[       ]*ifdef[        ]/b' \
316  -e '/^#[       ]*ifndef[       ]/b' \
317  -e '/^#[       ]*else/b' \
318  -e '/^#[       ]*endif/b' \
319  -e 's/^#.*//' \
320  %s | %s -C %s %s",
321 #ifdef MSDOS
322           "",
323 #else
324           "/bin/",
325 #endif
326           (doextract ? "-e '1,/^#/d\n'" : ""),
327           argv[0], CPPSTDIN, str_get(str), CPPMINUS);
328 #ifdef DEBUGGING
329         if (debug & 64) {
330             fputs(buf,stderr);
331             fputs("\n",stderr);
332         }
333 #endif
334         doextract = FALSE;
335 #ifdef IAMSUID                          /* actually, this is caught earlier */
336         if (euid != uid && !euid)       /* if running suidperl */
337 #ifdef HAS_SETEUID
338             (void)seteuid(uid);         /* musn't stay setuid root */
339 #else
340 #ifdef HAS_SETREUID
341             (void)setreuid(-1, uid);
342 #else
343             setuid(uid);
344 #endif
345 #endif
346 #endif /* IAMSUID */
347         rsfp = mypopen(buf,"r");
348     }
349     else if (!*argv[0])
350         rsfp = stdin;
351     else
352         rsfp = fopen(argv[0],"r");
353     if (rsfp == Nullfp) {
354 #ifdef DOSUID
355 #ifndef IAMSUID         /* in case script is not readable before setuid */
356         if (euid && stat(stab_val(curcmd->c_filestab)->str_ptr,&statbuf) >= 0 &&
357           statbuf.st_mode & (S_ISUID|S_ISGID)) {
358             (void)sprintf(buf, "%s/sperl%s", BIN, patchlevel);
359             execv(buf, origargv);       /* try again */
360             fatal("Can't do setuid\n");
361         }
362 #endif
363 #endif
364         fatal("Can't open perl script \"%s\": %s\n",
365           stab_val(curcmd->c_filestab)->str_ptr, strerror(errno));
366     }
367     str_free(str);              /* free -I directories */
368     str = Nullstr;
369
370     /* do we need to emulate setuid on scripts? */
371
372     /* This code is for those BSD systems that have setuid #! scripts disabled
373      * in the kernel because of a security problem.  Merely defining DOSUID
374      * in perl will not fix that problem, but if you have disabled setuid
375      * scripts in the kernel, this will attempt to emulate setuid and setgid
376      * on scripts that have those now-otherwise-useless bits set.  The setuid
377      * root version must be called suidperl or sperlN.NNN.  If regular perl
378      * discovers that it has opened a setuid script, it calls suidperl with
379      * the same argv that it had.  If suidperl finds that the script it has
380      * just opened is NOT setuid root, it sets the effective uid back to the
381      * uid.  We don't just make perl setuid root because that loses the
382      * effective uid we had before invoking perl, if it was different from the
383      * uid.
384      *
385      * DOSUID must be defined in both perl and suidperl, and IAMSUID must
386      * be defined in suidperl only.  suidperl must be setuid root.  The
387      * Configure script will set this up for you if you want it.
388      *
389      * There is also the possibility of have a script which is running
390      * set-id due to a C wrapper.  We want to do the TAINT checks
391      * on these set-id scripts, but don't want to have the overhead of
392      * them in normal perl, and can't use suidperl because it will lose
393      * the effective uid info, so we have an additional non-setuid root
394      * version called taintperl or tperlN.NNN that just does the TAINT checks.
395      */
396
397 #ifdef DOSUID
398     if (fstat(fileno(rsfp),&statbuf) < 0)       /* normal stat is insecure */
399         fatal("Can't stat script \"%s\"",origfilename);
400     if (statbuf.st_mode & (S_ISUID|S_ISGID)) {
401         int len;
402
403 #ifdef IAMSUID
404 #ifndef HAS_SETREUID
405         /* On this access check to make sure the directories are readable,
406          * there is actually a small window that the user could use to make
407          * filename point to an accessible directory.  So there is a faint
408          * chance that someone could execute a setuid script down in a
409          * non-accessible directory.  I don't know what to do about that.
410          * But I don't think it's too important.  The manual lies when
411          * it says access() is useful in setuid programs.
412          */
413         if (access(stab_val(curcmd->c_filestab)->str_ptr,1))    /*double check*/
414             fatal("Permission denied");
415 #else
416         /* If we can swap euid and uid, then we can determine access rights
417          * with a simple stat of the file, and then compare device and
418          * inode to make sure we did stat() on the same file we opened.
419          * Then we just have to make sure he or she can execute it.
420          */
421         {
422             struct stat tmpstatbuf;
423
424             if (setreuid(euid,uid) < 0 || getuid() != euid || geteuid() != uid)
425                 fatal("Can't swap uid and euid");       /* really paranoid */
426             if (stat(stab_val(curcmd->c_filestab)->str_ptr,&tmpstatbuf) < 0)
427                 fatal("Permission denied");     /* testing full pathname here */
428             if (tmpstatbuf.st_dev != statbuf.st_dev ||
429                 tmpstatbuf.st_ino != statbuf.st_ino) {
430                 (void)fclose(rsfp);
431                 if (rsfp = mypopen("/bin/mail root","w")) {     /* heh, heh */
432                     fprintf(rsfp,
433 "User %d tried to run dev %d ino %d in place of dev %d ino %d!\n\
434 (Filename of set-id script was %s, uid %d gid %d.)\n\nSincerely,\nperl\n",
435                         uid,tmpstatbuf.st_dev, tmpstatbuf.st_ino,
436                         statbuf.st_dev, statbuf.st_ino,
437                         stab_val(curcmd->c_filestab)->str_ptr,
438                         statbuf.st_uid, statbuf.st_gid);
439                     (void)mypclose(rsfp);
440                 }
441                 fatal("Permission denied\n");
442             }
443             if (setreuid(uid,euid) < 0 || getuid() != uid || geteuid() != euid)
444                 fatal("Can't reswap uid and euid");
445             if (!cando(S_IXUSR,FALSE,&statbuf))         /* can real uid exec? */
446                 fatal("Permission denied\n");
447         }
448 #endif /* HAS_SETREUID */
449 #endif /* IAMSUID */
450
451         if (!S_ISREG(statbuf.st_mode))
452             fatal("Permission denied");
453         if (statbuf.st_mode & S_IWOTH)
454             fatal("Setuid/gid script is writable by world");
455         doswitches = FALSE;             /* -s is insecure in suid */
456         curcmd->c_line++;
457         if (fgets(tokenbuf,sizeof tokenbuf, rsfp) == Nullch ||
458           strnNE(tokenbuf,"#!",2) )     /* required even on Sys V */
459             fatal("No #! line");
460         s = tokenbuf+2;
461         if (*s == ' ') s++;
462         while (!isspace(*s)) s++;
463         if (strnNE(s-4,"perl",4) && strnNE(s-9,"perl",4))  /* sanity check */
464             fatal("Not a perl script");
465         while (*s == ' ' || *s == '\t') s++;
466         /*
467          * #! arg must be what we saw above.  They can invoke it by
468          * mentioning suidperl explicitly, but they may not add any strange
469          * arguments beyond what #! says if they do invoke suidperl that way.
470          */
471         len = strlen(validarg);
472         if (strEQ(validarg," PHOOEY ") ||
473             strnNE(s,validarg,len) || !isspace(s[len]))
474             fatal("Args must match #! line");
475
476 #ifndef IAMSUID
477         if (euid != uid && (statbuf.st_mode & S_ISUID) &&
478             euid == statbuf.st_uid)
479             if (!do_undump)
480                 fatal("YOU HAVEN'T DISABLED SET-ID SCRIPTS IN THE KERNEL YET!\n\
481 FIX YOUR KERNEL, PUT A C WRAPPER AROUND THIS SCRIPT, OR USE -u AND UNDUMP!\n");
482 #endif /* IAMSUID */
483
484         if (euid) {     /* oops, we're not the setuid root perl */
485             (void)fclose(rsfp);
486 #ifndef IAMSUID
487             (void)sprintf(buf, "%s/sperl%s", BIN, patchlevel);
488             execv(buf, origargv);       /* try again */
489 #endif
490             fatal("Can't do setuid\n");
491         }
492
493         if (statbuf.st_mode & S_ISGID && statbuf.st_gid != egid)
494 #ifdef HAS_SETEGID
495             (void)setegid(statbuf.st_gid);
496 #else
497 #ifdef HAS_SETREGID
498             (void)setregid((GIDTYPE)-1,statbuf.st_gid);
499 #else
500             setgid(statbuf.st_gid);
501 #endif
502 #endif
503         if (statbuf.st_mode & S_ISUID) {
504             if (statbuf.st_uid != euid)
505 #ifdef HAS_SETEUID
506                 (void)seteuid(statbuf.st_uid);  /* all that for this */
507 #else
508 #ifdef HAS_SETREUID
509                 (void)setreuid((UIDTYPE)-1,statbuf.st_uid);
510 #else
511                 setuid(statbuf.st_uid);
512 #endif
513 #endif
514         }
515         else if (uid)                   /* oops, mustn't run as root */
516 #ifdef HAS_SETEUID
517             (void)seteuid((UIDTYPE)uid);
518 #else
519 #ifdef HAS_SETREUID
520             (void)setreuid((UIDTYPE)-1,(UIDTYPE)uid);
521 #else
522             setuid((UIDTYPE)uid);
523 #endif
524 #endif
525         uid = (int)getuid();
526         euid = (int)geteuid();
527         gid = (int)getgid();
528         egid = (int)getegid();
529         if (!cando(S_IXUSR,TRUE,&statbuf))
530             fatal("Permission denied\n");       /* they can't do this */
531     }
532 #ifdef IAMSUID
533     else if (preprocess)
534         fatal("-P not allowed for setuid/setgid script\n");
535     else
536         fatal("Script is not setuid/setgid in suidperl\n");
537 #else
538 #ifndef TAINT           /* we aren't taintperl or suidperl */
539     /* script has a wrapper--can't run suidperl or we lose euid */
540     else if (euid != uid || egid != gid) {
541         (void)fclose(rsfp);
542         (void)sprintf(buf, "%s/tperl%s", BIN, patchlevel);
543         execv(buf, origargv);   /* try again */
544         fatal("Can't run setuid script with taint checks");
545     }
546 #endif /* TAINT */
547 #endif /* IAMSUID */
548 #else /* !DOSUID */
549 #ifndef TAINT           /* we aren't taintperl or suidperl */
550     if (euid != uid || egid != gid) {   /* (suidperl doesn't exist, in fact) */
551 #ifndef SETUID_SCRIPTS_ARE_SECURE_NOW
552         fstat(fileno(rsfp),&statbuf);   /* may be either wrapped or real suid */
553         if ((euid != uid && euid == statbuf.st_uid && statbuf.st_mode & S_ISUID)
554             ||
555             (egid != gid && egid == statbuf.st_gid && statbuf.st_mode & S_ISGID)
556            )
557             if (!do_undump)
558                 fatal("YOU HAVEN'T DISABLED SET-ID SCRIPTS IN THE KERNEL YET!\n\
559 FIX YOUR KERNEL, PUT A C WRAPPER AROUND THIS SCRIPT, OR USE -u AND UNDUMP!\n");
560 #endif /* SETUID_SCRIPTS_ARE_SECURE_NOW */
561         /* not set-id, must be wrapped */
562         (void)fclose(rsfp);
563         (void)sprintf(buf, "%s/tperl%s", BIN, patchlevel);
564         execv(buf, origargv);   /* try again */
565         fatal("Can't run setuid script with taint checks");
566     }
567 #endif /* TAINT */
568 #endif /* DOSUID */
569
570 #if !defined(IAMSUID) && !defined(TAINT)
571
572     /* skip forward in input to the real script? */
573
574     while (doextract) {
575         if ((s = str_gets(linestr, rsfp, 0)) == Nullch)
576             fatal("No Perl script found in input\n");
577         if (*s == '#' && s[1] == '!' && instr(s,"perl")) {
578             ungetc('\n',rsfp);          /* to keep line count right */
579             doextract = FALSE;
580             if (s = instr(s,"perl -")) {
581                 s += 6;
582                 while (s = moreswitches(s)) ;
583             }
584             if (cddir && chdir(cddir) < 0)
585                 fatal("Can't chdir to %s",cddir);
586         }
587     }
588 #endif /* !defined(IAMSUID) && !defined(TAINT) */
589
590     defstab = stabent("_",TRUE);
591
592     if (perldb) {
593         debstash = hnew(0);
594         stab_xhash(stabent("_DB",TRUE)) = debstash;
595         curstash = debstash;
596         dbargs = stab_xarray(aadd((tmpstab = stabent("args",TRUE))));
597         tmpstab->str_pok |= SP_MULTI;
598         dbargs->ary_flags = 0;
599         subname = str_make("main",4);
600         DBstab = stabent("DB",TRUE);
601         DBstab->str_pok |= SP_MULTI;
602         DBline = stabent("dbline",TRUE);
603         DBline->str_pok |= SP_MULTI;
604         DBsub = hadd(tmpstab = stabent("sub",TRUE));
605         tmpstab->str_pok |= SP_MULTI;
606         DBsingle = stab_val((tmpstab = stabent("single",TRUE)));
607         tmpstab->str_pok |= SP_MULTI;
608         DBtrace = stab_val((tmpstab = stabent("trace",TRUE)));
609         tmpstab->str_pok |= SP_MULTI;
610         DBsignal = stab_val((tmpstab = stabent("signal",TRUE)));
611         tmpstab->str_pok |= SP_MULTI;
612         curstash = defstash;
613     }
614
615     /* init tokener */
616
617     bufend = bufptr = str_get(linestr);
618
619     savestack = anew(Nullstab);         /* for saving non-local values */
620     stack = anew(Nullstab);             /* for saving non-local values */
621     stack->ary_flags = 0;               /* not a real array */
622     afill(stack,63); afill(stack,-1);   /* preextend stack */
623     afill(savestack,63); afill(savestack,-1);
624
625     /* now parse the script */
626
627     error_count = 0;
628     if (yyparse() || error_count) {
629         if (minus_c)
630             fatal("%s had compilation errors.\n", origfilename);
631         else {
632             fatal("Execution of %s aborted due to compilation errors.\n",
633                 origfilename);
634         }
635     }
636
637     New(50,loop_stack,128,struct loop);
638 #ifdef DEBUGGING
639     if (debug) {
640         New(51,debname,128,char);
641         New(52,debdelim,128,char);
642     }
643 #endif
644     curstash = defstash;
645
646     preprocess = FALSE;
647     if (e_fp) {
648         e_fp = Nullfp;
649         (void)UNLINK(e_tmpname);
650     }
651
652     /* initialize everything that won't change if we undump */
653
654     if (sigstab = stabent("SIG",allstabs)) {
655         sigstab->str_pok |= SP_MULTI;
656         (void)hadd(sigstab);
657     }
658
659     magicalize("!#?^~=-%.+&*()<>,\\/[|`':\004\t\024\027");
660     userinit();         /* in case linked C routines want magical variables */
661
662     amperstab = stabent("&",allstabs);
663     leftstab = stabent("`",allstabs);
664     rightstab = stabent("'",allstabs);
665     sawampersand = (amperstab || leftstab || rightstab);
666     if (tmpstab = stabent(":",allstabs))
667         str_set(STAB_STR(tmpstab),chopset);
668     if (tmpstab = stabent("\024",allstabs))
669         time(&basetime);
670
671     /* these aren't necessarily magical */
672     if (tmpstab = stabent(";",allstabs))
673         str_set(STAB_STR(tmpstab),"\034");
674     if (tmpstab = stabent("]",allstabs)) {
675         str = STAB_STR(tmpstab);
676         str_set(str,rcsid);
677         str->str_u.str_nval = atof(patchlevel);
678         str->str_nok = 1;
679     }
680     str_nset(stab_val(stabent("\"", TRUE)), " ", 1);
681
682     stdinstab = stabent("STDIN",TRUE);
683     stdinstab->str_pok |= SP_MULTI;
684     stab_io(stdinstab) = stio_new();
685     stab_io(stdinstab)->ifp = stdin;
686     tmpstab = stabent("stdin",TRUE);
687     stab_io(tmpstab) = stab_io(stdinstab);
688     tmpstab->str_pok |= SP_MULTI;
689
690     tmpstab = stabent("STDOUT",TRUE);
691     tmpstab->str_pok |= SP_MULTI;
692     stab_io(tmpstab) = stio_new();
693     stab_io(tmpstab)->ofp = stab_io(tmpstab)->ifp = stdout;
694     defoutstab = tmpstab;
695     tmpstab = stabent("stdout",TRUE);
696     stab_io(tmpstab) = stab_io(defoutstab);
697     tmpstab->str_pok |= SP_MULTI;
698
699     curoutstab = stabent("STDERR",TRUE);
700     curoutstab->str_pok |= SP_MULTI;
701     stab_io(curoutstab) = stio_new();
702     stab_io(curoutstab)->ofp = stab_io(curoutstab)->ifp = stderr;
703     tmpstab = stabent("stderr",TRUE);
704     stab_io(tmpstab) = stab_io(curoutstab);
705     tmpstab->str_pok |= SP_MULTI;
706     curoutstab = defoutstab;            /* switch back to STDOUT */
707
708     statname = Str_new(66,0);           /* last filename we did stat on */
709
710     /* now that script is parsed, we can modify record separator */
711
712     rs = nrs;
713     rslen = nrslen;
714     rschar = nrschar;
715     str_nset(stab_val(stabent("/", TRUE)), rs, rslen);
716
717     if (do_undump)
718         my_unexec();
719
720   just_doit:            /* come here if running an undumped a.out */
721     argc--,argv++;      /* skip name of script */
722     if (doswitches) {
723         for (; argc > 0 && **argv == '-'; argc--,argv++) {
724             if (argv[0][1] == '-') {
725                 argc--,argv++;
726                 break;
727             }
728             if (s = index(argv[0], '=')) {
729                 *s++ = '\0';
730                 str_set(stab_val(stabent(argv[0]+1,TRUE)),s);
731             }
732             else
733                 str_numset(stab_val(stabent(argv[0]+1,TRUE)),(double)1.0);
734         }
735     }
736 #ifdef TAINT
737     tainted = 1;
738 #endif
739     if (tmpstab = stabent("0",allstabs)) {
740         str_set(stab_val(tmpstab),origfilename);
741         magicname("0", Nullch, 0);
742     }
743     if (tmpstab = stabent("\020",allstabs))
744         str_set(stab_val(tmpstab),origargv[0]);
745     if (argvstab = stabent("ARGV",allstabs)) {
746         argvstab->str_pok |= SP_MULTI;
747         (void)aadd(argvstab);
748         aclear(stab_array(argvstab));
749         for (; argc > 0; argc--,argv++) {
750             (void)apush(stab_array(argvstab),str_make(argv[0],0));
751         }
752     }
753 #ifdef TAINT
754     (void) stabent("ENV",TRUE);         /* must test PATH and IFS */
755 #endif
756     if (envstab = stabent("ENV",allstabs)) {
757         envstab->str_pok |= SP_MULTI;
758         (void)hadd(envstab);
759         hclear(stab_hash(envstab), FALSE);
760         if (env != environ)
761             environ[0] = Nullch;
762         for (; *env; env++) {
763             if (!(s = index(*env,'=')))
764                 continue;
765             *s++ = '\0';
766             str = str_make(s--,0);
767             str_magic(str, envstab, 'E', *env, s - *env);
768             (void)hstore(stab_hash(envstab), *env, s - *env, str, 0);
769             *s = '=';
770         }
771     }
772 #ifdef TAINT
773     tainted = 0;
774 #endif
775     if (tmpstab = stabent("$",allstabs))
776         str_numset(STAB_STR(tmpstab),(double)getpid());
777
778     if (dowarn) {
779         stab_check('A','Z');
780         stab_check('a','z');
781     }
782
783     if (setjmp(top_env))        /* sets goto_targ on longjump */
784         loop_ptr = -1;          /* start label stack again */
785
786 #ifdef DEBUGGING
787     if (debug & 1024)
788         dump_all();
789     if (debug)
790         fprintf(stderr,"\nEXECUTING...\n\n");
791 #endif
792
793     if (minus_c) {
794         fprintf(stderr,"%s syntax OK\n", origfilename);
795         exit(0);
796     }
797
798     /* do it */
799
800     (void) cmd_exec(main_root,G_SCALAR,-1);
801
802     if (goto_targ)
803         fatal("Can't find label \"%s\"--aborting",goto_targ);
804     exit(0);
805     /* NOTREACHED */
806 }
807
808 void
809 magicalize(list)
810 register char *list;
811 {
812     char sym[2];
813
814     sym[1] = '\0';
815     while (*sym = *list++)
816         magicname(sym, Nullch, 0);
817 }
818
819 void
820 magicname(sym,name,namlen)
821 char *sym;
822 char *name;
823 int namlen;
824 {
825     register STAB *stab;
826
827     if (stab = stabent(sym,allstabs)) {
828         stab_flags(stab) = SF_VMAGIC;
829         str_magic(stab_val(stab), stab, 0, name, namlen);
830     }
831 }
832
833 /* this routine is in perl.c by virtue of being sort of an alternate main() */
834
835 int
836 do_eval(str,optype,stash,gimme,arglast)
837 STR *str;
838 int optype;
839 HASH *stash;
840 int gimme;
841 int *arglast;
842 {
843     STR **st = stack->ary_array;
844     int retval;
845     CMD *myroot = Nullcmd;
846     ARRAY *ar;
847     int i;
848     CMD * VOLATILE oldcurcmd = curcmd;
849     VOLATILE int oldtmps_base = tmps_base;
850     VOLATILE int oldsave = savestack->ary_fill;
851     VOLATILE int oldperldb = perldb;
852     SPAT * VOLATILE oldspat = curspat;
853     SPAT * VOLATILE oldlspat = lastspat;
854     static char *last_eval = Nullch;
855     static CMD *last_root = Nullcmd;
856     VOLATILE int sp = arglast[0];
857     char *specfilename;
858     char *tmpfilename;
859     int parsing = 1;
860
861     tmps_base = tmps_max;
862     if (curstash != stash) {
863         (void)savehptr(&curstash);
864         curstash = stash;
865     }
866     str_set(stab_val(stabent("@",TRUE)),"");
867     if (curcmd->c_line == 0)            /* don't debug debugger... */
868         perldb = FALSE;
869     curcmd = &compiling;
870     if (optype == O_EVAL) {             /* normal eval */
871         curcmd->c_filestab = fstab("(eval)");
872         curcmd->c_line = 1;
873         str_sset(linestr,str);
874         str_cat(linestr,";");           /* be kind to them */
875     }
876     else {
877         if (last_root && !in_eval) {
878             Safefree(last_eval);
879             last_eval = Nullch;
880             cmd_free(last_root);
881             last_root = Nullcmd;
882         }
883         specfilename = str_get(str);
884         str_set(linestr,"");
885         if (optype == O_REQUIRE && &str_undef !=
886           hfetch(stab_hash(incstab), specfilename, strlen(specfilename), 0)) {
887             curcmd = oldcurcmd;
888             tmps_base = oldtmps_base;
889             st[++sp] = &str_yes;
890             perldb = oldperldb;
891             return sp;
892         }
893         tmpfilename = savestr(specfilename);
894         if (index("/.", *tmpfilename))
895             rsfp = fopen(tmpfilename,"r");
896         else {
897             ar = stab_array(incstab);
898             for (i = 0; i <= ar->ary_fill; i++) {
899                 (void)sprintf(buf, "%s/%s",
900                   str_get(afetch(ar,i,TRUE)), specfilename);
901                 rsfp = fopen(buf,"r");
902                 if (rsfp) {
903                     char *s = buf;
904
905                     if (*s == '.' && s[1] == '/')
906                         s += 2;
907                     Safefree(tmpfilename);
908                     tmpfilename = savestr(s);
909                     break;
910                 }
911             }
912         }
913         curcmd->c_filestab = fstab(tmpfilename);
914         Safefree(tmpfilename);
915         tmpfilename = Nullch;
916         if (!rsfp) {
917             curcmd = oldcurcmd;
918             tmps_base = oldtmps_base;
919             if (optype == O_REQUIRE) {
920                 sprintf(tokenbuf,"Can't locate %s in @INC", specfilename);
921                 if (instr(tokenbuf,".h "))
922                     strcat(tokenbuf," (change .h to .ph maybe?)");
923                 if (instr(tokenbuf,".ph "))
924                     strcat(tokenbuf," (did you run h2ph?)");
925                 fatal("%s",tokenbuf);
926             }
927             if (gimme != G_ARRAY)
928                 st[++sp] = &str_undef;
929             perldb = oldperldb;
930             return sp;
931         }
932         curcmd->c_line = 0;
933     }
934     in_eval++;
935     oldoldbufptr = oldbufptr = bufptr = str_get(linestr);
936     bufend = bufptr + linestr->str_cur;
937     if (++loop_ptr >= loop_max) {
938         loop_max += 128;
939         Renew(loop_stack, loop_max, struct loop);
940     }
941     loop_stack[loop_ptr].loop_label = "_EVAL_";
942     loop_stack[loop_ptr].loop_sp = sp;
943 #ifdef DEBUGGING
944     if (debug & 4) {
945         deb("(Pushing label #%d _EVAL_)\n", loop_ptr);
946     }
947 #endif
948     eval_root = Nullcmd;
949     if (setjmp(loop_stack[loop_ptr].loop_env)) {
950         retval = 1;
951     }
952     else {
953         error_count = 0;
954         if (rsfp) {
955             retval = yyparse();
956             retval |= error_count;
957         }
958         else if (last_root && *bufptr == *last_eval && strEQ(bufptr,last_eval)){
959             retval = 0;
960             eval_root = last_root;      /* no point in reparsing */
961         }
962         else if (in_eval == 1) {
963             if (last_root) {
964                 Safefree(last_eval);
965                 last_eval = Nullch;
966                 cmd_free(last_root);
967             }
968             last_root = Nullcmd;
969             last_eval = savestr(bufptr);
970             retval = yyparse();
971             retval |= error_count;
972             if (!retval)
973                 last_root = eval_root;
974             if (!last_root) {
975                 Safefree(last_eval);
976                 last_eval = Nullch;
977             }
978         }
979         else
980             retval = yyparse();
981     }
982     myroot = eval_root;         /* in case cmd_exec does another eval! */
983
984     if (retval) {
985         st = stack->ary_array;
986         sp = arglast[0];
987         if (gimme != G_ARRAY)
988             st[++sp] = &str_undef;
989         if (parsing) {
990 #ifndef MANGLEDPARSE
991 #ifdef DEBUGGING
992             if (debug & 128)
993                 fprintf(stderr,"Freeing eval_root %lx\n",(long)eval_root);
994 #endif
995             cmd_free(eval_root);
996 #endif
997             if (eval_root == last_root)
998                 last_root = Nullcmd;
999             eval_root = myroot = Nullcmd;
1000         }
1001         if (rsfp) {
1002             fclose(rsfp);
1003             rsfp = 0;
1004         }
1005     }
1006     else {
1007         parsing = 0;
1008         sp = cmd_exec(eval_root,gimme,sp);
1009         st = stack->ary_array;
1010         for (i = arglast[0] + 1; i <= sp; i++)
1011             st[i] = str_mortal(st[i]);
1012                                 /* if we don't save result, free zaps it */
1013         if (in_eval != 1 && myroot != last_root)
1014             cmd_free(myroot);
1015     }
1016
1017     perldb = oldperldb;
1018     in_eval--;
1019 #ifdef DEBUGGING
1020     if (debug & 4) {
1021         char *tmps = loop_stack[loop_ptr].loop_label;
1022         deb("(Popping label #%d %s)\n",loop_ptr,
1023             tmps ? tmps : "" );
1024     }
1025 #endif
1026     loop_ptr--;
1027     tmps_base = oldtmps_base;
1028     curspat = oldspat;
1029     lastspat = oldlspat;
1030     if (savestack->ary_fill > oldsave)  /* let them use local() */
1031         restorelist(oldsave);
1032
1033     if (optype != O_EVAL) {
1034         if (retval) {
1035             if (optype == O_REQUIRE)
1036                 fatal("%s", str_get(stab_val(stabent("@",TRUE))));
1037         }
1038         else {
1039             curcmd = oldcurcmd;
1040             if (gimme == G_SCALAR ? str_true(st[sp]) : sp > arglast[0]) {
1041                 (void)hstore(stab_hash(incstab), specfilename,
1042                   strlen(specfilename), str_smake(stab_val(curcmd->c_filestab)),
1043                       0 );
1044             }
1045             else if (optype == O_REQUIRE)
1046                 fatal("%s did not return a true value", specfilename);
1047         }
1048     }
1049     curcmd = oldcurcmd;
1050     return sp;
1051 }
1052
1053 /* This routine handles any switches that can be given during run */
1054
1055 static char *
1056 moreswitches(s)
1057 char *s;
1058 {
1059     int numlen;
1060
1061   reswitch:
1062     switch (*s) {
1063     case '0':
1064         nrschar = scanoct(s, 4, &numlen);
1065         nrs = nsavestr("\n",1);
1066         *nrs = nrschar;
1067         if (nrschar > 0377) {
1068             nrslen = 0;
1069             nrs = "";
1070         }
1071         else if (!nrschar && numlen >= 2) {
1072             nrslen = 2;
1073             nrs = "\n\n";
1074             nrschar = '\n';
1075         }
1076         return s + numlen;
1077     case 'a':
1078         minus_a = TRUE;
1079         s++;
1080         return s;
1081     case 'c':
1082         minus_c = TRUE;
1083         s++;
1084         return s;
1085     case 'd':
1086 #ifdef TAINT
1087         if (euid != uid || egid != gid)
1088             fatal("No -d allowed in setuid scripts");
1089 #endif
1090         perldb = TRUE;
1091         s++;
1092         return s;
1093     case 'D':
1094 #ifdef DEBUGGING
1095 #ifdef TAINT
1096         if (euid != uid || egid != gid)
1097             fatal("No -D allowed in setuid scripts");
1098 #endif
1099         debug = atoi(s+1) | 32768;
1100 #else
1101         warn("Recompile perl with -DDEBUGGING to use -D switch\n");
1102 #endif
1103         for (s++; isdigit(*s); s++) ;
1104         return s;
1105     case 'i':
1106         inplace = savestr(s+1);
1107         for (s = inplace; *s && !isspace(*s); s++) ;
1108         *s = '\0';
1109         break;
1110     case 'I':
1111 #ifdef TAINT
1112         if (euid != uid || egid != gid)
1113             fatal("No -I allowed in setuid scripts");
1114 #endif
1115         if (*++s) {
1116             (void)apush(stab_array(incstab),str_make(s,0));
1117         }
1118         else
1119             fatal("No space allowed after -I");
1120         break;
1121     case 'l':
1122         minus_l = TRUE;
1123         s++;
1124         if (isdigit(*s)) {
1125             ors = savestr("\n");
1126             orslen = 1;
1127             *ors = scanoct(s, 3 + (*s == '0'), &numlen);
1128             s += numlen;
1129         }
1130         else {
1131             ors = nsavestr(nrs,nrslen);
1132             orslen = nrslen;
1133         }
1134         return s;
1135     case 'n':
1136         minus_n = TRUE;
1137         s++;
1138         return s;
1139     case 'p':
1140         minus_p = TRUE;
1141         s++;
1142         return s;
1143     case 'u':
1144         do_undump = TRUE;
1145         s++;
1146         return s;
1147     case 'U':
1148         unsafe = TRUE;
1149         s++;
1150         return s;
1151     case 'v':
1152         fputs("\nThis is perl, version 4.0\n\n",stdout);
1153         fputs(rcsid,stdout);
1154         fputs("\nCopyright (c) 1989, 1990, 1991, Larry Wall\n",stdout);
1155 #ifdef MSDOS
1156         fputs("MS-DOS port Copyright (c) 1989, 1990, Diomidis Spinellis\n",
1157         stdout);
1158 #ifdef OS2
1159         fputs("OS/2 port Copyright (c) 1990, Raymond Chen, Kai Uwe Rommel\n",
1160         stdout);
1161 #endif
1162 #endif
1163         fputs("\n\
1164 Perl may be copied only under the terms of the GNU General Public License,\n\
1165 a copy of which can be found with the Perl 4.0 distribution kit.\n",stdout);
1166 #ifdef MSDOS
1167         usage(origargv[0]);
1168 #endif
1169         exit(0);
1170     case 'w':
1171         dowarn = TRUE;
1172         s++;
1173         return s;
1174     case ' ':
1175     case '\n':
1176     case '\t':
1177         break;
1178     default:
1179         fatal("Switch meaningless after -x: -%s",s);
1180     }
1181     return Nullch;
1182 }
1183
1184 /* compliments of Tom Christiansen */
1185
1186 /* unexec() can be found in the Gnu emacs distribution */
1187
1188 my_unexec()
1189 {
1190 #ifdef UNEXEC
1191     int    status;
1192     extern int etext;
1193     static char dumpname[BUFSIZ];
1194     static char perlpath[256];
1195
1196     sprintf (dumpname, "%s.perldump", origfilename);
1197     sprintf (perlpath, "%s/perl", BIN);
1198
1199     status = unexec(dumpname, perlpath, &etext, sbrk(0), 0);
1200     if (status)
1201         fprintf(stderr, "unexec of %s into %s failed!\n", perlpath, dumpname);
1202     exit(status);
1203 #else
1204 #   ifndef SIGABRT
1205 #       define SIGABRT SIGILL
1206 #   endif
1207 #   ifndef SIGILL
1208 #       define SIGILL 6         /* blech */
1209 #   endif
1210     kill(getpid(),SIGABRT);     /* for use with undump */
1211 #endif
1212 }
1213