1 /* $NetBSD: proc.c,v 1.43 2025/03/20 15:02:00 buhrow Exp $ */
2 
3 /*-
4  * Copyright (c) 1980, 1991, 1993
5  *        The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #include <sys/cdefs.h>
33 #ifndef lint
34 #if 0
35 static char sccsid[] = "@(#)proc.c      8.1 (Berkeley) 5/31/93";
36 #else
37 __RCSID("$NetBSD: proc.c,v 1.43 2025/03/20 15:02:00 buhrow Exp $");
38 #endif
39 #endif /* not lint */
40 
41 #include <sys/types.h>
42 #include <sys/wait.h>
43 
44 #include <errno.h>
45 #include <stdarg.h>
46 #include <stdlib.h>
47 #include <string.h>
48 #include <unistd.h>
49 
50 #include "csh.h"
51 #include "dir.h"
52 #include "extern.h"
53 #include "proc.h"
54 
55 #define BIGINDEX 9 /* largest desirable job index */
56 
57 extern int insource;
58 
59 struct process proclist;
60 int pnoprocesses;
61 
62 struct process *pholdjob;
63 
64 struct process *pcurrjob;
65 struct process *pcurrent;
66 struct process *pprevious;
67 
68 int pmaxindex;
69 
70 static void pflushall(void);
71 static void pflush(struct process *);
72 static void pclrcurr(struct process *);
73 static void padd(struct command *);
74 static int pprint(struct process *, int);
75 static void ptprint(struct process *);
76 static void pads(Char *);
77 static void pkill(Char **v, int);
78 static struct process *pgetcurr(struct process *);
79 static void okpcntl(void);
80 
81 /*
82  * pchild - called at interrupt level by the SIGCHLD signal
83  *        indicating that at least one child has terminated or stopped
84  *        thus at least one wait system call will definitely return a
85  *        childs status.  Top level routines (like pwait) must be sure
86  *        to mask interrupts when playing with the proclist data structures!
87  */
88 /* ARGSUSED */
89 void
pchild(int notused)90 pchild(int notused)
91 {
92     struct rusage ru;
93     struct process *fp, *pp;
94     int jobflags, pid, w;
95 
96 loop:
97     errno = 0;                          /* reset, just in case */
98     pid = wait3(&w,
99        (setintr && (intty || insource) ? WNOHANG | WUNTRACED : WNOHANG), &ru);
100 
101     if (pid <= 0) {
102           if (errno == EINTR) {
103               errno = 0;
104               goto loop;
105           }
106           pnoprocesses = pid == -1;
107           return;
108     }
109     for (pp = proclist.p_next; pp != NULL; pp = pp->p_next)
110           if (pid == pp->p_pid)
111               goto found;
112     goto loop;
113 found:
114     if (pid == atoi(short2str(value(STRchild))))
115           unsetv(STRchild);
116     pp->p_flags &= ~(PRUNNING | PSTOPPED | PREPORTED);
117     if (WIFSTOPPED(w)) {
118           pp->p_flags |= PSTOPPED;
119           pp->p_reason = WSTOPSIG(w);
120     }
121     else {
122           if (pp->p_flags & (PTIME | PPTIME) || adrof(STRtime))
123               (void)clock_gettime(CLOCK_MONOTONIC, &pp->p_etime);
124 
125           pp->p_rusage = ru;
126           if (WIFSIGNALED(w)) {
127               if (WTERMSIG(w) == SIGINT)
128                     pp->p_flags |= PINTERRUPTED;
129               else
130                     pp->p_flags |= PSIGNALED;
131               if (WCOREDUMP(w))
132                     pp->p_flags |= PDUMPED;
133               pp->p_reason = WTERMSIG(w);
134           }
135           else {
136               pp->p_reason = WEXITSTATUS(w);
137               if (pp->p_reason != 0)
138                     pp->p_flags |= PAEXITED;
139               else
140                     pp->p_flags |= PNEXITED;
141           }
142     }
143     jobflags = 0;
144     fp = pp;
145     do {
146           if ((fp->p_flags & (PPTIME | PRUNNING | PSTOPPED)) == 0 &&
147               !child && adrof(STRtime) &&
148               fp->p_rusage.ru_utime.tv_sec + fp->p_rusage.ru_stime.tv_sec
149               >= atoi(short2str(value(STRtime))))
150               fp->p_flags |= PTIME;
151           jobflags |= fp->p_flags;
152     } while ((fp = fp->p_friends) != pp);
153     pp->p_flags &= ~PFOREGND;
154     if (pp == pp->p_friends && (pp->p_flags & PPTIME)) {
155           pp->p_flags &= ~PPTIME;
156           pp->p_flags |= PTIME;
157     }
158     if ((jobflags & (PRUNNING | PREPORTED)) == 0) {
159           fp = pp;
160           do {
161               if (fp->p_flags & PSTOPPED)
162                     fp->p_flags |= PREPORTED;
163           } while ((fp = fp->p_friends) != pp);
164           while (fp->p_pid != fp->p_jobid)
165               fp = fp->p_friends;
166           if (jobflags & PSTOPPED) {
167               if (pcurrent && pcurrent != fp)
168                     pprevious = pcurrent;
169               pcurrent = fp;
170           }
171           else
172               pclrcurr(fp);
173           if (jobflags & PFOREGND) {
174               if (jobflags & (PSIGNALED | PSTOPPED | PPTIME) ||
175 #ifdef IIASA
176                     jobflags & PAEXITED ||
177 #endif
178                     !eq(dcwd->di_name, fp->p_cwd->di_name)) {
179                     ;                   /* print in pjwait */
180               }
181               /* PWP: print a newline after ^C */
182               else if (jobflags & PINTERRUPTED) {
183                     (void)vis_fputc('\r' | QUOTE, cshout);
184                     (void)fputc('\n', cshout);
185               }
186           }
187           else {
188               if (jobflags & PNOTIFY || adrof(STRnotify)) {
189                     (void)vis_fputc('\r' | QUOTE, cshout);
190                     (void)fputc('\n', cshout);
191                     (void)pprint(pp, NUMBER | NAME | REASON);
192                     if ((jobflags & PSTOPPED) == 0)
193                         pflush(pp);
194               }
195               else {
196                     fp->p_flags |= PNEEDNOTE;
197                     neednote++;
198               }
199           }
200     }
201     goto loop;
202 }
203 
204 void
pnote(void)205 pnote(void)
206 {
207     struct process *pp;
208     sigset_t osigset, nsigset;
209     int flags;
210 
211     neednote = 0;
212     sigemptyset(&nsigset);
213     (void)sigaddset(&nsigset, SIGCHLD);
214     for (pp = proclist.p_next; pp != NULL; pp = pp->p_next) {
215           if (pp->p_flags & PNEEDNOTE) {
216               (void)sigprocmask(SIG_BLOCK, &nsigset, &osigset);
217               pp->p_flags &= ~PNEEDNOTE;
218               flags = pprint(pp, NUMBER | NAME | REASON);
219               if ((flags & (PRUNNING | PSTOPPED)) == 0)
220                     pflush(pp);
221               (void)sigprocmask(SIG_SETMASK, &osigset, NULL);
222           }
223     }
224 }
225 
226 /*
227  * pwait - wait for current job to terminate, maintaining integrity
228  *        of current and previous job indicators.
229  */
230 void
pwait(void)231 pwait(void)
232 {
233     struct process *fp, *pp;
234     sigset_t osigset, nsigset;
235 
236     /*
237      * Here's where dead procs get flushed.
238      */
239     sigemptyset(&nsigset);
240     (void)sigaddset(&nsigset, SIGCHLD);
241     (void)sigprocmask(SIG_BLOCK, &nsigset, &osigset);
242     for (pp = (fp = &proclist)->p_next; pp != NULL; pp = (fp = pp)->p_next)
243           if (pp->p_pid == 0) {
244               fp->p_next = pp->p_next;
245               free(pp->p_command);
246               if (pp->p_cwd && --pp->p_cwd->di_count == 0)
247                     if (pp->p_cwd->di_next == 0)
248                         dfree(pp->p_cwd);
249               free(pp);
250               pp = fp;
251           }
252     (void)sigprocmask(SIG_SETMASK, &osigset, NULL);
253     pjwait(pcurrjob);
254 }
255 
256 
257 /*
258  * pjwait - wait for a job to finish or become stopped
259  *        It is assumed to be in the foreground state (PFOREGND)
260  */
261 void
pjwait(struct process * pp)262 pjwait(struct process *pp)
263 {
264     struct process *fp;
265     sigset_t osigset, nsigset;
266     int jobflags, reason;
267 
268     while (pp->p_pid != pp->p_jobid)
269           pp = pp->p_friends;
270     fp = pp;
271 
272     do {
273           if ((fp->p_flags & (PFOREGND | PRUNNING)) == PRUNNING)
274               (void)fprintf(csherr, "BUG: waiting for background job!\n");
275     } while ((fp = fp->p_friends) != pp);
276     /*
277      * Now keep pausing as long as we are not interrupted (SIGINT), and the
278      * target process, or any of its friends, are running
279      */
280     fp = pp;
281     sigemptyset(&nsigset);
282     (void)sigaddset(&nsigset, SIGCHLD);
283     (void)sigprocmask(SIG_BLOCK, &nsigset, &osigset);
284     for (;;) {
285           sigemptyset(&nsigset);
286           (void)sigaddset(&nsigset, SIGCHLD);
287           (void)sigprocmask(SIG_BLOCK, &nsigset, NULL);
288           jobflags = 0;
289           do
290               jobflags |= fp->p_flags;
291           while ((fp = (fp->p_friends)) != pp);
292           if ((jobflags & PRUNNING) == 0)
293               break;
294 #ifdef JOBDEBUG
295           (void)fprintf(csherr, "starting to sigsuspend for  SIGCHLD on %d\n",
296                            fp->p_pid);
297 #endif                                  /* JOBDEBUG */
298           nsigset = osigset;
299           (void)sigdelset(&nsigset, SIGCHLD);
300           (void)sigsuspend(&nsigset);
301     }
302     (void)sigprocmask(SIG_SETMASK, &osigset, NULL);
303     if (tpgrp > 0)            /* get tty back */
304           (void)tcsetpgrp(FSHTTY, tpgrp);
305     if ((jobflags & (PSIGNALED | PSTOPPED | PTIME)) ||
306           !eq(dcwd->di_name, fp->p_cwd->di_name)) {
307           if (jobflags & PSTOPPED) {
308               (void) fputc('\n', cshout);
309               if (adrof(STRlistjobs)) {
310                     Char *jobcommand[3];
311 
312                     jobcommand[0] = STRjobs;
313                     if (eq(value(STRlistjobs), STRlong))
314                         jobcommand[1] = STRml;
315                     else
316                         jobcommand[1] = NULL;
317                     jobcommand[2] = NULL;
318 
319                     dojobs(jobcommand, NULL);
320                     (void)pprint(pp, SHELLDIR);
321               }
322               else
323                     (void)pprint(pp, AREASON | SHELLDIR);
324           }
325           else
326               (void)pprint(pp, AREASON | SHELLDIR);
327     }
328     if ((jobflags & (PINTERRUPTED | PSTOPPED)) && setintr &&
329           (!gointr || !eq(gointr, STRminus))) {
330           if ((jobflags & PSTOPPED) == 0)
331               pflush(pp);
332           pintr1(0);
333     }
334     reason = 0;
335     fp = pp;
336     do {
337           if (fp->p_reason)
338               reason = fp->p_flags & (PSIGNALED | PINTERRUPTED) ?
339                     fp->p_reason | META : fp->p_reason;
340     } while ((fp = fp->p_friends) != pp);
341     if ((reason != 0) && (adrof(STRprintexitvalue))) {
342           (void)fprintf(cshout, "Exit %d\n", reason);
343     }
344     set(STRstatus, putn(reason));
345     if (reason && exiterr)
346           exitstat();
347     pflush(pp);
348 }
349 
350 /*
351  * dowait - wait for all processes to finish
352  */
353 void
354 /*ARGSUSED*/
dowait(Char ** v,struct command * t)355 dowait(Char **v, struct command *t)
356 {
357     struct process *pp;
358     sigset_t osigset, nsigset;
359 
360     pjobs++;
361     sigemptyset(&nsigset);
362     (void)sigaddset(&nsigset, SIGCHLD);
363     (void)sigprocmask(SIG_BLOCK, &nsigset, &osigset);
364 loop:
365     for (pp = proclist.p_next; pp; pp = pp->p_next)
366           if (pp->p_pid &&    /* pp->p_pid == pp->p_jobid && */
367               pp->p_flags & PRUNNING) {
368               sigemptyset(&nsigset);
369               (void)sigsuspend(&nsigset);
370               goto loop;
371           }
372     (void)sigprocmask(SIG_SETMASK, &osigset, NULL);
373     pjobs = 0;
374 }
375 
376 /*
377  * pflushall - flush all jobs from list (e.g. at fork())
378  */
379 static void
pflushall(void)380 pflushall(void)
381 {
382     struct process *pp;
383 
384     for (pp = proclist.p_next; pp != NULL; pp = pp->p_next)
385           if (pp->p_pid)
386               pflush(pp);
387 }
388 
389 /*
390  * pflush - flag all process structures in the same job as the
391  *        the argument process for deletion.  The actual free of the
392  *        space is not done here since pflush is called at interrupt level.
393  */
394 static void
pflush(struct process * pp)395 pflush(struct process *pp)
396 {
397     struct process *np;
398     int idx;
399 
400     if (pp->p_pid == 0) {
401           (void)fprintf(csherr, "BUG: process flushed twice");
402           return;
403     }
404     while (pp->p_pid != pp->p_jobid)
405           pp = pp->p_friends;
406     pclrcurr(pp);
407     if (pp == pcurrjob)
408           pcurrjob = 0;
409     idx = pp->p_index;
410     np = pp;
411     do {
412           np->p_index = np->p_pid = 0;
413           np->p_flags &= ~PNEEDNOTE;
414     } while ((np = np->p_friends) != pp);
415     if (idx == pmaxindex) {
416           for (np = proclist.p_next, idx = 0; np; np = np->p_next)
417               if (np->p_index > idx)
418                     idx = np->p_index;
419           pmaxindex = idx;
420     }
421 }
422 
423 /*
424  * pclrcurr - make sure the given job is not the current or previous job;
425  *        pp MUST be the job leader
426  */
427 static void
pclrcurr(struct process * pp)428 pclrcurr(struct process *pp)
429 {
430     if (pp == pcurrent) {
431           if (pprevious != NULL) {
432               pcurrent = pprevious;
433               pprevious = pgetcurr(pp);
434           }
435           else {
436               pcurrent = pgetcurr(pp);
437               pprevious = pgetcurr(pp);
438           }
439     } else if (pp == pprevious)
440           pprevious = pgetcurr(pp);
441 }
442 
443 /* +4 here is 1 for '\0', 1 ea for << >& >> */
444 static Char command[PMAXLEN + 4];
445 static size_t cmdlen;
446 static Char *cmdp;
447 
448 /*
449  * palloc - allocate a process structure and fill it up.
450  *        an important assumption is made that the process is running.
451  */
452 void
palloc(int pid,struct command * t)453 palloc(int pid, struct command *t)
454 {
455     struct process *pp;
456     int i;
457 
458     pp = xcalloc(1, sizeof(*pp));
459     pp->p_pid = pid;
460     pp->p_flags = t->t_dflg & F_AMPERSAND ? PRUNNING : PRUNNING | PFOREGND;
461     if (t->t_dflg & F_TIME)
462           pp->p_flags |= PPTIME;
463     cmdp = command;
464     cmdlen = 0;
465     padd(t);
466     *cmdp++ = 0;
467     if (t->t_dflg & F_PIPEOUT) {
468           pp->p_flags |= PPOU;
469           if (t->t_dflg & F_STDERR)
470               pp->p_flags |= PERR;
471     }
472     pp->p_command = Strsave(command);
473     if (pcurrjob) {
474           struct process *fp;
475 
476           /* careful here with interrupt level */
477           pp->p_cwd = 0;
478           pp->p_index = pcurrjob->p_index;
479           pp->p_friends = pcurrjob;
480           pp->p_jobid = pcurrjob->p_pid;
481           for (fp = pcurrjob; fp->p_friends != pcurrjob; fp = fp->p_friends)
482               continue;
483           fp->p_friends = pp;
484     }
485     else {
486           pcurrjob = pp;
487           pp->p_jobid = pid;
488           pp->p_friends = pp;
489           pp->p_cwd = dcwd;
490           dcwd->di_count++;
491           if (pmaxindex < BIGINDEX)
492               pp->p_index = ++pmaxindex;
493           else {
494               struct process *np;
495 
496               for (i = 1;; i++) {
497                     for (np = proclist.p_next; np; np = np->p_next)
498                         if (np->p_index == i)
499                               goto tryagain;
500                     pp->p_index = i;
501                     if (i > pmaxindex)
502                         pmaxindex = i;
503                     break;
504           tryagain:;
505               }
506           }
507           if (pcurrent == NULL)
508               pcurrent = pp;
509           else if (pprevious == NULL)
510               pprevious = pp;
511     }
512     pp->p_next = proclist.p_next;
513     proclist.p_next = pp;
514     (void)clock_gettime(CLOCK_MONOTONIC, &pp->p_btime);
515 }
516 
517 static void
padd(struct command * t)518 padd(struct command *t)
519 {
520     Char **argp;
521 
522     if (t == 0)
523           return;
524     switch (t->t_dtyp) {
525     case NODE_PAREN:
526           pads(STRLparensp);
527           padd(t->t_dspr);
528           pads(STRspRparen);
529           break;
530     case NODE_COMMAND:
531           for (argp = t->t_dcom; *argp; argp++) {
532               pads(*argp);
533               if (argp[1])
534                     pads(STRspace);
535           }
536           break;
537     case NODE_OR:
538     case NODE_AND:
539     case NODE_PIPE:
540     case NODE_LIST:
541           padd(t->t_dcar);
542           switch (t->t_dtyp) {
543           case NODE_OR:
544               pads(STRspor2sp);
545               break;
546           case NODE_AND:
547               pads(STRspand2sp);
548               break;
549           case NODE_PIPE:
550               pads(STRsporsp);
551               break;
552           case NODE_LIST:
553               pads(STRsemisp);
554               break;
555           }
556           padd(t->t_dcdr);
557           return;
558     }
559     if ((t->t_dflg & F_PIPEIN) == 0 && t->t_dlef) {
560           pads((t->t_dflg & F_READ) ? STRspLarrow2sp : STRspLarrowsp);
561           pads(t->t_dlef);
562     }
563     if ((t->t_dflg & F_PIPEOUT) == 0 && t->t_drit) {
564           pads((t->t_dflg & F_APPEND) ? STRspRarrow2 : STRspRarrow);
565           if (t->t_dflg & F_STDERR)
566               pads(STRand);
567           pads(STRspace);
568           pads(t->t_drit);
569     }
570 }
571 
572 static void
pads(Char * cp)573 pads(Char *cp)
574 {
575     size_t i;
576 
577     /*
578      * Avoid the Quoted Space alias hack! Reported by:
579      * sam@john-bigboote.ICS.UCI.EDU (Sam Horrocks)
580      */
581     if (cp[0] == STRQNULL[0])
582           cp++;
583 
584     i = Strlen(cp);
585 
586     if (cmdlen >= PMAXLEN)
587           return;
588     if (cmdlen + i >= PMAXLEN) {
589           (void)Strcpy(cmdp, STRsp3dots);
590           cmdlen = PMAXLEN;
591           cmdp += 4;
592           return;
593     }
594     (void)Strcpy(cmdp, cp);
595     cmdp += i;
596     cmdlen += i;
597 }
598 
599 /*
600  * psavejob - temporarily save the current job on a one level stack
601  *        so another job can be created.  Used for { } in exp6
602  *        and `` in globbing.
603  */
604 void
psavejob(void)605 psavejob(void)
606 {
607     pholdjob = pcurrjob;
608     pcurrjob = NULL;
609 }
610 
611 /*
612  * prestjob - opposite of psavejob.  This may be missed if we are interrupted
613  *        somewhere, but pendjob cleans up anyway.
614  */
615 void
prestjob(void)616 prestjob(void)
617 {
618     pcurrjob = pholdjob;
619     pholdjob = NULL;
620 }
621 
622 /*
623  * pendjob - indicate that a job (set of commands) has been completed
624  *        or is about to begin.
625  */
626 void
pendjob(void)627 pendjob(void)
628 {
629     struct process *pp, *tp;
630 
631     if (pcurrjob && (pcurrjob->p_flags & (PFOREGND | PSTOPPED)) == 0) {
632           pp = pcurrjob;
633           while (pp->p_pid != pp->p_jobid)
634               pp = pp->p_friends;
635           (void)fprintf(cshout, "[%d]", pp->p_index);
636           tp = pp;
637           do {
638               (void)fprintf(cshout, " %ld", (long)pp->p_pid);
639               pp = pp->p_friends;
640           } while (pp != tp);
641           (void)fputc('\n', cshout);
642     }
643     pholdjob = pcurrjob = 0;
644 }
645 
646 /*
647  * pprint - print a job
648  */
649 static int
pprint(struct process * pp,int flag)650 pprint(struct process *pp, int flag)
651 {
652     static struct rusage zru;
653     struct process *tp;
654     const char *format;
655     int jobflags, pstatus, reason, status;
656     int hadnl;
657 
658     hadnl = 1; /* did we just have a newline */
659     (void)fpurge(cshout);
660 
661     while (pp->p_pid != pp->p_jobid)
662           pp = pp->p_friends;
663     if (pp == pp->p_friends && (pp->p_flags & PPTIME)) {
664           pp->p_flags &= ~PPTIME;
665           pp->p_flags |= PTIME;
666     }
667     tp = pp;
668     status = reason = -1;
669     jobflags = 0;
670     do {
671           jobflags |= pp->p_flags;
672           pstatus = pp->p_flags & PALLSTATES;
673           if (tp != pp && !hadnl && !(flag & FANCY) &&
674               ((pstatus == status && pp->p_reason == reason) ||
675                !(flag & REASON))) {
676               (void)fputc(' ', cshout);
677               hadnl = 0;
678           }
679           else {
680               if (tp != pp && !hadnl) {
681                     (void)fputc('\n', cshout);
682                     hadnl = 1;
683               }
684               if (flag & NUMBER) {
685                     if (pp == tp)
686                         (void)fprintf(cshout, "[%d]%s %c ", pp->p_index,
687                                   pp->p_index < 10 ? " " : "",
688                                   pp == pcurrent ? '+' :
689                                   (pp == pprevious ? '-' : ' '));
690                     else
691                         (void)fprintf(cshout, "       ");
692                     hadnl = 0;
693               }
694               if (flag & FANCY) {
695                     (void)fprintf(cshout, "%5ld ", (long)pp->p_pid);
696                     hadnl = 0;
697               }
698               if (flag & (REASON | AREASON)) {
699                     if (flag & NAME)
700                         format = "%-23s";
701                     else
702                         format = "%s";
703                     if (pstatus == status) {
704                         if (pp->p_reason == reason) {
705                               (void)fprintf(cshout, format, "");
706                               hadnl = 0;
707                               goto prcomd;
708                         }
709                         else
710                               reason = pp->p_reason;
711                     } else {
712                         status = pstatus;
713                         reason = pp->p_reason;
714                     }
715                     switch (status) {
716                     case PRUNNING:
717                         (void)fprintf(cshout, format, "Running ");
718                         hadnl = 0;
719                         break;
720                     case PINTERRUPTED:
721                     case PSTOPPED:
722                     case PSIGNALED:
723                     /*
724                      * tell what happened to the background job
725                      * From: Michael Schroeder
726                      * <mlschroe@immd4.informatik.uni-erlangen.de>
727                      */
728                     if ((flag & REASON)
729                         || ((flag & AREASON)
730                             && reason != SIGINT
731                             && (reason != SIGPIPE
732                                 || (pp->p_flags & PPOU) == 0))) {
733                               (void)fprintf(cshout, format,
734                                                sys_siglist[(unsigned char)
735                                                                pp->p_reason]);
736                               hadnl = 0;
737                         }
738                         break;
739                     case PNEXITED:
740                     case PAEXITED:
741                         if (flag & REASON) {
742                               if (pp->p_reason)
743                                   (void)fprintf(cshout, "Exit %-18d", pp->p_reason);
744                               else
745                                   (void)fprintf(cshout, format, "Done");
746                               hadnl = 0;
747                         }
748                         break;
749                     default:
750                         (void)fprintf(csherr, "BUG: status=%-9o", status);
751                     }
752               }
753           }
754 prcomd:
755           if (flag & NAME) {
756               (void)fprintf(cshout, "%s", vis_str(pp->p_command));
757               if (pp->p_flags & PPOU)
758                     (void)fprintf(cshout, " |");
759               if (pp->p_flags & PERR)
760                     (void)fputc('&', cshout);
761               hadnl = 0;
762           }
763           if (flag & (REASON | AREASON) && pp->p_flags & PDUMPED) {
764               (void)fprintf(cshout, " (core dumped)");
765               hadnl = 0;
766           }
767           if (tp == pp->p_friends) {
768               if (flag & AMPERSAND) {
769                     (void)fprintf(cshout, " &");
770                     hadnl = 0;
771               }
772               if (flag & JOBDIR &&
773                     !eq(tp->p_cwd->di_name, dcwd->di_name)) {
774                     (void)fprintf(cshout, " (wd: ");
775                     dtildepr(value(STRhome), tp->p_cwd->di_name);
776                     (void)fputc(')', cshout);
777                     hadnl = 0;
778               }
779           }
780           if (pp->p_flags & PPTIME && !(status & (PSTOPPED | PRUNNING))) {
781               if (!hadnl)
782                     (void)fprintf(cshout, "\n\t");
783               prusage(cshout, &zru, &pp->p_rusage, &pp->p_etime,
784                         &pp->p_btime);
785               hadnl = 1;
786           }
787           if (tp == pp->p_friends) {
788               if (!hadnl) {
789                     (void)fputc('\n', cshout);
790                     hadnl = 1;
791               }
792               if (flag & SHELLDIR && !eq(tp->p_cwd->di_name, dcwd->di_name)) {
793                     (void)fprintf(cshout, "(wd now: ");
794                     dtildepr(value(STRhome), dcwd->di_name);
795                     (void)fprintf(cshout, ")\n");
796                     hadnl = 1;
797               }
798           }
799     } while ((pp = pp->p_friends) != tp);
800     if (jobflags & PTIME && (jobflags & (PSTOPPED | PRUNNING)) == 0) {
801           if (jobflags & NUMBER)
802               (void)fprintf(cshout, "       ");
803           ptprint(tp);
804           hadnl = 1;
805     }
806     (void)fflush(cshout);
807     return (jobflags);
808 }
809 
810 static void
ptprint(struct process * tp)811 ptprint(struct process *tp)
812 {
813     static struct rusage zru;
814     static struct timespec ztime;
815     struct rusage ru;
816     struct timespec tetime, diff;
817     struct process *pp;
818 
819     pp = tp;
820     ru = zru;
821     tetime = ztime;
822     do {
823           ruadd(&ru, &pp->p_rusage);
824           timespecsub(&pp->p_etime, &pp->p_btime, &diff);
825           if (timespeccmp(&diff, &tetime, >))
826               tetime = diff;
827     } while ((pp = pp->p_friends) != tp);
828     prusage(cshout, &zru, &ru, &tetime, &ztime);
829 }
830 
831 /*
832  * dojobs - print all jobs
833  */
834 void
835 /*ARGSUSED*/
dojobs(Char ** v,struct command * t)836 dojobs(Char **v, struct command *t)
837 {
838     struct process *pp;
839     int flag, i;
840 
841     flag = NUMBER | NAME | REASON;
842     if (chkstop)
843           chkstop = 2;
844     if (*++v) {
845               if (eq(*v, STRml) && !v[1]) {
846                     flag |= FANCY | JOBDIR;
847               } else if (eq(*v, STRmZ)) {
848                     if (v[1] && v[1][0]) {
849                         setproctitle("%s", short2str(v[1]));
850                     } else {
851                         setproctitle(NULL);
852                     }
853                     return;
854               } else {
855                     stderror(ERR_JOBS);
856               }
857     }
858     for (i = 1; i <= pmaxindex; i++)
859           for (pp = proclist.p_next; pp; pp = pp->p_next)
860               if (pp->p_index == i && pp->p_pid == pp->p_jobid) {
861                     pp->p_flags &= ~PNEEDNOTE;
862                     if (!(pprint(pp, flag) & (PRUNNING | PSTOPPED)))
863                         pflush(pp);
864                     break;
865               }
866 }
867 
868 /*
869  * dofg - builtin - put the job into the foreground
870  */
871 void
872 /*ARGSUSED*/
dofg(Char ** v,struct command * t)873 dofg(Char **v, struct command *t)
874 {
875     struct process *pp;
876 
877     okpcntl();
878     ++v;
879     do {
880           pp = pfind(*v);
881           pstart(pp, 1);
882           pjwait(pp);
883     } while (*v && *++v);
884 }
885 
886 /*
887  * %... - builtin - put the job into the foreground
888  */
889 void
890 /*ARGSUSED*/
dofg1(Char ** v,struct command * t)891 dofg1(Char **v, struct command *t)
892 {
893     struct process *pp;
894 
895     okpcntl();
896     pp = pfind(v[0]);
897     pstart(pp, 1);
898     pjwait(pp);
899 }
900 
901 /*
902  * dobg - builtin - put the job into the background
903  */
904 void
905 /*ARGSUSED*/
dobg(Char ** v,struct command * t)906 dobg(Char **v, struct command *t)
907 {
908     struct process *pp;
909 
910     okpcntl();
911     ++v;
912     do {
913           pp = pfind(*v);
914           pstart(pp, 0);
915     } while (*v && *++v);
916 }
917 
918 /*
919  * %... & - builtin - put the job into the background
920  */
921 void
922 /*ARGSUSED*/
dobg1(Char ** v,struct command * t)923 dobg1(Char **v, struct command *t)
924 {
925     struct process *pp;
926 
927     pp = pfind(v[0]);
928     pstart(pp, 0);
929 }
930 
931 /*
932  * dostop - builtin - stop the job
933  */
934 void
935 /*ARGSUSED*/
dostop(Char ** v,struct command * t)936 dostop(Char **v, struct command *t)
937 {
938     pkill(++v, SIGSTOP);
939 }
940 
941 /*
942  * dokill - builtin - superset of kill (1)
943  */
944 void
945 /*ARGSUSED*/
dokill(Char ** v,struct command * t)946 dokill(Char **v, struct command *t)
947 {
948     Char *signame;
949     char *name;
950     long signum;
951     char *ep;
952 
953     signum = SIGTERM;
954     v++;
955     if (v[0] && v[0][0] == '-') {
956           if (v[0][1] == 'l') {
957               if (v[1]) {
958                     if (!Isdigit(v[1][0]))
959                         stderror(ERR_NAME | ERR_BADSIG);
960 
961                     signum = strtol(short2str(v[1]), &ep, 10);
962                     if (signum < 0 || signum >= NSIG)
963                         stderror(ERR_NAME | ERR_BADSIG);
964                     else if (signum == 0)
965                         (void)fputc('0', cshout); /* 0's symbolic name is '0' */
966                     else
967                         (void)fprintf(cshout, "%s ", sys_signame[signum]);
968               } else {
969                     for (signum = 1; signum < NSIG; signum++) {
970                         (void)fprintf(cshout, "%s ", sys_signame[signum]);
971                         if (signum == NSIG / 2)
972                               (void)fputc('\n', cshout);
973                     }
974               }
975               (void)fputc('\n', cshout);
976               return;
977           }
978           if (Isdigit(v[0][1])) {
979               signum = strtol(short2str(v[0] + 1), &ep, 10);
980               if (signum < 0 || signum >= NSIG || *ep)
981                     stderror(ERR_NAME | ERR_BADSIG);
982           }
983           else {
984               if (v[0][1] == 's' && v[0][2] == '\0')
985                     signame = *(++v);
986               else
987                     signame = &v[0][1];
988 
989               if (signame == NULL || v[1] == NULL)
990                     stderror(ERR_NAME | ERR_TOOFEW);
991 
992               name = short2str(signame);
993               for (signum = 1; signum < NSIG; signum++)
994                     if (!strcasecmp(sys_signame[signum], name) ||
995                         (!strncasecmp("SIG", name, 3) &&    /* skip "SIG" prefix */
996                          !strcasecmp(sys_signame[signum], name + 3)))
997                         break;
998 
999               if (signum == NSIG) {
1000                     if (signame[0] == '0')
1001                         signum = 0;
1002                     else {
1003                         setname(vis_str(signame));
1004                         stderror(ERR_NAME | ERR_UNKSIG);
1005                     }
1006               }
1007           }
1008           v++;
1009     }
1010     pkill(v, (int)signum);
1011 }
1012 
1013 static void
pkill(Char ** v,int signum)1014 pkill(Char **v, int signum)
1015 {
1016     struct process *pp, *np;
1017     Char *cp;
1018     sigset_t nsigset;
1019     int err1, jobflags, pid;
1020     char *ep;
1021 
1022     jobflags = 0;
1023     err1 = 0;
1024     sigemptyset(&nsigset);
1025     (void)sigaddset(&nsigset, SIGCHLD);
1026     if (setintr)
1027           (void)sigaddset(&nsigset, SIGINT);
1028     (void)sigprocmask(SIG_BLOCK, &nsigset, NULL);
1029     gflag = 0, tglob(v);
1030     if (gflag) {
1031           v = globall(v);
1032           if (v == 0)
1033               stderror(ERR_NAME | ERR_NOMATCH);
1034     }
1035     else {
1036           v = gargv = saveblk(v);
1037           trim(v);
1038     }
1039 
1040     while (v && (cp = *v)) {
1041           if (*cp == '%') {
1042               np = pp = pfind(cp);
1043               do
1044                     jobflags |= np->p_flags;
1045               while ((np = np->p_friends) != pp);
1046               switch (signum) {
1047               case SIGSTOP:
1048               case SIGTSTP:
1049               case SIGTTIN:
1050               case SIGTTOU:
1051                     if ((jobflags & PRUNNING) == 0) {
1052                         (void)fprintf(csherr, "%s: Already suspended\n",
1053                                            vis_str(cp));
1054                         err1++;
1055                         goto cont;
1056                     }
1057                     break;
1058                     /*
1059                      * suspend a process, kill -CONT %, then type jobs; the shell
1060                      * says it is suspended, but it is running; thanks jaap..
1061                      */
1062               case SIGCONT:
1063                     pstart(pp, 0);
1064                     goto cont;
1065               }
1066               if (kill(-pp->p_jobid, signum) < 0) {
1067                     (void)fprintf(csherr, "%s: %s\n", vis_str(cp),
1068                                      strerror(errno));
1069                     err1++;
1070               }
1071               if (signum == SIGTERM || signum == SIGHUP)
1072                     (void)kill(-pp->p_jobid, SIGCONT);
1073           }
1074           else if (!(Isdigit(*cp) || *cp == '-'))
1075               stderror(ERR_NAME | ERR_JOBARGS);
1076           else {
1077               pid = (pid_t)strtoul(short2str(cp), &ep, 0);
1078               if (*ep) {
1079                     (void)fprintf(csherr, "%s: Badly formed number\n",
1080                         short2str(cp));
1081                     err1++;
1082                     goto cont;
1083               } else if (kill(pid, signum) < 0) {
1084                     (void)fprintf(csherr, "%d: %s\n", pid, strerror(errno));
1085                     err1++;
1086                     goto cont;
1087               }
1088               if (signum == SIGTERM || signum == SIGHUP)
1089                     (void)kill((pid_t) pid, SIGCONT);
1090           }
1091 cont:
1092           v++;
1093     }
1094     if (gargv)
1095           blkfree(gargv), gargv = 0;
1096     (void)sigprocmask(SIG_UNBLOCK, &nsigset, NULL);
1097     if (err1)
1098           stderror(ERR_SILENT);
1099 }
1100 
1101 /*
1102  * pstart - start the job in foreground/background
1103  */
1104 void
pstart(struct process * pp,int foregnd)1105 pstart(struct process *pp, int foregnd)
1106 {
1107     struct process *np;
1108     sigset_t osigset, nsigset;
1109     long jobflags;
1110 
1111     jobflags = 0;
1112     sigemptyset(&nsigset);
1113     (void)sigaddset(&nsigset, SIGCHLD);
1114     (void)sigprocmask(SIG_BLOCK, &nsigset, &osigset);
1115     np = pp;
1116     do {
1117           jobflags |= np->p_flags;
1118           if (np->p_flags & (PRUNNING | PSTOPPED)) {
1119               np->p_flags |= PRUNNING;
1120               np->p_flags &= ~PSTOPPED;
1121               if (foregnd)
1122                     np->p_flags |= PFOREGND;
1123               else
1124                     np->p_flags &= ~PFOREGND;
1125           }
1126     } while ((np = np->p_friends) != pp);
1127     if (!foregnd)
1128           pclrcurr(pp);
1129     (void)pprint(pp, foregnd ? NAME | JOBDIR : NUMBER | NAME | AMPERSAND);
1130     if (foregnd)
1131           (void)tcsetpgrp(FSHTTY, pp->p_jobid);
1132     if (jobflags & PSTOPPED)
1133           (void)kill(-pp->p_jobid, SIGCONT);
1134     (void)sigprocmask(SIG_SETMASK, &osigset, NULL);
1135 }
1136 
1137 void
panystop(int neednl)1138 panystop(int neednl)
1139 {
1140     struct process *pp;
1141 
1142     chkstop = 2;
1143     for (pp = proclist.p_next; pp; pp = pp->p_next)
1144           if (pp->p_flags & PSTOPPED)
1145               stderror(ERR_STOPPED, neednl ? "\n" : "");
1146 }
1147 
1148 struct process *
pfind(Char * cp)1149 pfind(Char *cp)
1150 {
1151     struct process *pp, *np;
1152 
1153     if (cp == 0 || cp[1] == 0 || eq(cp, STRcent2) || eq(cp, STRcentplus)) {
1154           if (pcurrent == NULL)
1155               stderror(ERR_NAME | ERR_JOBCUR);
1156           return (pcurrent);
1157     }
1158     if (eq(cp, STRcentminus) || eq(cp, STRcenthash)) {
1159           if (pprevious == NULL)
1160               stderror(ERR_NAME | ERR_JOBPREV);
1161           return (pprevious);
1162     }
1163     if (Isdigit(cp[1])) {
1164           int     idx = atoi(short2str(cp + 1));
1165 
1166           for (pp = proclist.p_next; pp; pp = pp->p_next)
1167               if (pp->p_index == idx && pp->p_pid == pp->p_jobid)
1168                     return (pp);
1169           stderror(ERR_NAME | ERR_NOSUCHJOB);
1170     }
1171     np = NULL;
1172     for (pp = proclist.p_next; pp; pp = pp->p_next)
1173           if (pp->p_pid == pp->p_jobid) {
1174               if (cp[1] == '?') {
1175                     Char *dp;
1176 
1177                     for (dp = pp->p_command; *dp; dp++) {
1178                         if (*dp != cp[2])
1179                               continue;
1180                         if (prefix(cp + 2, dp))
1181                               goto match;
1182                     }
1183               }
1184               else if (prefix(cp + 1, pp->p_command)) {
1185           match:
1186                     if (np)
1187                         stderror(ERR_NAME | ERR_AMBIG);
1188                     np = pp;
1189               }
1190           }
1191     if (np)
1192           return (np);
1193     stderror(ERR_NAME | (cp[1] == '?' ? ERR_JOBPAT : ERR_NOSUCHJOB));
1194     /* NOTREACHED */
1195 }
1196 
1197 /*
1198  * pgetcurr - find most recent job that is not pp, preferably stopped
1199  */
1200 static struct process *
pgetcurr(struct process * pp)1201 pgetcurr(struct process *pp)
1202 {
1203     struct process *np, *xp;
1204 
1205     xp = NULL;
1206     for (np = proclist.p_next; np; np = np->p_next)
1207           if (np != pcurrent && np != pp && np->p_pid &&
1208               np->p_pid == np->p_jobid) {
1209               if (np->p_flags & PSTOPPED)
1210                     return (np);
1211               if (xp == NULL)
1212                     xp = np;
1213           }
1214     return (xp);
1215 }
1216 
1217 /*
1218  * donotify - flag the job so as to report termination asynchronously
1219  */
1220 void
1221 /*ARGSUSED*/
donotify(Char ** v,struct command * t)1222 donotify(Char **v, struct command *t)
1223 {
1224     struct process *pp;
1225 
1226     pp = pfind(*++v);
1227     pp->p_flags |= PNOTIFY;
1228 }
1229 
1230 /*
1231  * Do the fork and whatever should be done in the child side that
1232  * should not be done if we are not forking at all (like for simple builtin's)
1233  * Also do everything that needs any signals fiddled with in the parent side
1234  *
1235  * Wanttty tells whether process and/or tty pgrps are to be manipulated:
1236  *        -1:       leave tty alone; inherit pgrp from parent
1237  *         0:       already have tty; manipulate process pgrps only
1238  *         1:       want to claim tty; manipulate process and tty pgrps
1239  * It is usually just the value of tpgrp.
1240  */
1241 
1242 int
pfork(struct command * t,int wanttty)1243 pfork(struct command *t /* command we are forking for */, int wanttty)
1244 {
1245     int pgrp, pid;
1246     sigset_t osigset, nsigset;
1247     int ignint;
1248 
1249     ignint = 0;
1250     /*
1251      * A child will be uninterruptible only under very special conditions.
1252      * Remember that the semantics of '&' is implemented by disconnecting the
1253      * process from the tty so signals do not need to ignored just for '&'.
1254      * Thus signals are set to default action for children unless: we have had
1255      * an "onintr -" (then specifically ignored) we are not playing with
1256      * signals (inherit action)
1257      */
1258     if (setintr)
1259           ignint = (tpgrp == -1 && (t->t_dflg & F_NOINTERRUPT))
1260               || (gointr && eq(gointr, STRminus));
1261     /*
1262      * Check for maximum nesting of 16 processes to avoid Forking loops
1263      */
1264     if (child == 16)
1265           stderror(ERR_NESTING, 16);
1266     /*
1267      * Hold SIGCHLD until we have the process installed in our table.
1268      */
1269     sigemptyset(&nsigset);
1270     (void)sigaddset(&nsigset, SIGCHLD);
1271     (void)sigprocmask(SIG_BLOCK, &nsigset, &osigset);
1272     while ((pid = fork()) < 0)
1273           if (setintr == 0)
1274               (void)sleep(FORKSLEEP);
1275           else {
1276               (void)sigprocmask(SIG_SETMASK, &osigset, NULL);
1277               stderror(ERR_NOPROC);
1278           }
1279     if (pid == 0) {
1280           settimes();
1281           pgrp = pcurrjob ? pcurrjob->p_jobid : getpid();
1282           pflushall();
1283           pcurrjob = NULL;
1284           child++;
1285           if (setintr) {
1286               setintr = 0;    /* until I think otherwise */
1287               /*
1288                * Children just get blown away on SIGINT, SIGQUIT unless "onintr
1289                * -" seen.
1290                */
1291               (void)signal(SIGINT, ignint ? SIG_IGN : SIG_DFL);
1292               (void)signal(SIGQUIT, ignint ? SIG_IGN : SIG_DFL);
1293               if (wanttty >= 0) {
1294                     /* make stoppable */
1295                     (void)signal(SIGTSTP, SIG_DFL);
1296                     (void)signal(SIGTTIN, SIG_DFL);
1297                     (void)signal(SIGTTOU, SIG_DFL);
1298               }
1299               (void)signal(SIGTERM, parterm);
1300           }
1301           else if (tpgrp == -1 && (t->t_dflg & F_NOINTERRUPT)) {
1302               (void)signal(SIGINT, SIG_IGN);
1303               (void)signal(SIGQUIT, SIG_IGN);
1304           }
1305           pgetty(wanttty, pgrp);
1306           /*
1307            * Nohup and nice apply only to NODE_COMMAND's but it would be nice
1308            * (?!?) if you could say "nohup (foo;bar)" Then the parser would have
1309            * to know about nice/nohup/time
1310            */
1311           if (t->t_dflg & F_NOHUP)
1312               (void)signal(SIGHUP, SIG_IGN);
1313           if (t->t_dflg & F_NICE)
1314               (void)setpriority(PRIO_PROCESS, 0, t->t_nice);
1315     }
1316     else {
1317           if (wanttty >= 0)
1318               (void)setpgid(pid, pcurrjob ? pcurrjob->p_jobid : pid);
1319           palloc(pid, t);
1320           (void)sigprocmask(SIG_SETMASK, &osigset, NULL);
1321     }
1322 
1323     return (pid);
1324 }
1325 
1326 static void
okpcntl(void)1327 okpcntl(void)
1328 {
1329     if (tpgrp == -1)
1330           stderror(ERR_JOBCONTROL);
1331     if (tpgrp == 0)
1332           stderror(ERR_JOBCTRLSUB);
1333     /* NOTREACHED */
1334 }
1335 
1336 /*
1337  * if we don't have vfork(), things can still go in the wrong order
1338  * resulting in the famous 'Stopped (tty output)'. But some systems
1339  * don't permit the setpgid() call, (these are more recent secure
1340  * systems such as ibm's aix). Then we'd rather print an error message
1341  * than hang the shell!
1342  * I am open to suggestions how to fix that.
1343  */
1344 void
pgetty(int wanttty,int pgrp)1345 pgetty(int wanttty, int pgrp)
1346 {
1347     sigset_t osigset, nsigset;
1348 
1349     /*
1350      * christos: I am blocking the tty signals till I've set things
1351      * correctly....
1352      */
1353     if (wanttty > 0) {
1354           sigemptyset(&nsigset);
1355           (void)sigaddset(&nsigset, SIGTSTP);
1356           (void)sigaddset(&nsigset, SIGTTIN);
1357           (void)sigaddset(&nsigset, SIGTTOU);
1358           (void)sigprocmask(SIG_BLOCK, &nsigset, &osigset);
1359     }
1360     /*
1361      * From: Michael Schroeder <mlschroe@immd4.informatik.uni-erlangen.de>
1362      * Don't check for tpgrp >= 0 so even non-interactive shells give
1363      * background jobs process groups Same for the comparison in the other part
1364      * of the #ifdef
1365      */
1366     if (wanttty >= 0)
1367           if (setpgid(0, pgrp) == -1) {
1368               (void)fprintf(csherr, "csh: setpgid error.\n");
1369               xexit(0);
1370           }
1371 
1372     if (wanttty > 0) {
1373           (void)tcsetpgrp(FSHTTY, pgrp);
1374           (void)sigprocmask(SIG_SETMASK, &osigset, NULL);
1375     }
1376 
1377     if (tpgrp > 0)
1378           tpgrp = 0;                    /* gave tty away */
1379 }
1380