1 /* $OpenBSD: history.c,v 1.41 2015/09/01 13:12:31 tedu Exp $ */
2 /* $OpenBSD: trap.c,v 1.23 2010/05/19 17:36:08 jasper Exp $ */
5 * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
6 * 2011, 2012, 2014, 2015, 2016
7 * mirabilos <m@mirbsd.org>
9 * Provided that these terms and disclaimer and all copyright notices
10 * are retained or reproduced in an accompanying document, permission
11 * is granted to deal in this work without restriction, including un-
12 * limited rights to use, publicly perform, distribute, sell, modify,
13 * merge, give away, or sublicence.
15 * This work is provided "AS IS" and WITHOUT WARRANTY of any kind, to
16 * the utmost extent permitted by applicable law, neither express nor
17 * implied; without malicious intent or gross negligence. In no event
18 * may a licensor, author or contributor be held liable for indirect,
19 * direct, other damage, loss, or other issues arising in any way out
20 * of dealing in the work, even if advised of the possibility of such
21 * damage or existence of a defect, except proven that it results out
22 * of said person's immediate fault when using the work as intended.
30 __RCSID("$MirOS: src/bin/mksh/histrap.c,v 1.152 2016/01/14 23:18:08 tg Exp $");
32 Trap sigtraps[ksh_NSIG + 1];
33 static struct sigaction Sigact_ign;
35 #if HAVE_PERSISTENT_HISTORY
36 static int histload(Source *, unsigned char *, size_t);
37 static int writehistline(int, int, const char *);
38 static void writehistfile(int, const char *);
41 static int hist_execute(char *, Area *);
42 static char **hist_get(const char *, bool, bool);
43 static char **hist_get_oldest(void);
45 static bool hstarted; /* set after hist_init() called */
46 static Source *hist_source;
48 #if HAVE_PERSISTENT_HISTORY
51 #define caddr_cast(x) ((void *)(x))
53 #define caddr_cast(x) ((caddr_t)(x))
56 /* several OEs do not have these constants */
58 #define MAP_FAILED caddr_cast(-1)
61 /* some OEs need the default mapping type specified */
66 /* current history file: name, fd, size */
68 static int histfd = -1;
69 static off_t histfsize;
72 static const char Tnot_in_history[] = "not in history";
73 #define Thistory (Tnot_in_history + 7)
75 static const char TFCEDIT_dollaru[] = "${FCEDIT:-/bin/ed} $_";
76 #define Tspdollaru (TFCEDIT_dollaru + 18)
78 /* HISTSIZE default: size of saved history, persistent or standard */
80 #define MKSH_DEFHISTSIZE 255
82 #define MKSH_DEFHISTSIZE 2047
84 /* maximum considered size of persistent history file */
85 #define MKSH_MAXHISTFSIZE ((off_t)1048576 * 96)
88 #define HIST_DISCARD 5
95 bool gflag = false, lflag = false, nflag = false, rflag = false,
98 const char *p, *first = NULL, *last = NULL;
99 char **hfirst, **hlast, **hp, *editor = NULL;
101 if (!Flag(FTALKING_I)) {
102 bi_errorf("history %ss not available", Tfunction);
106 while ((optc = ksh_getopt(wp, &builtin_opt,
107 "e:glnrs0,1,2,3,4,5,6,7,8,9,")) != -1)
111 p = builtin_opt.optarg;
115 size_t len = strlen(p);
117 /* almost certainly not overflowing */
118 editor = alloc(len + 4, ATEMP);
119 memcpy(editor, p, len);
120 memcpy(editor + len, Tspdollaru, 4);
141 /* POSIX version of -e - */
146 /* kludge city - accept -num as -- -num (kind of) */
147 case '0': case '1': case '2': case '3': case '4':
148 case '5': case '6': case '7': case '8': case '9':
149 p = shf_smprintf("-%c%s",
150 optc, builtin_opt.optarg);
156 bi_errorf("too many arguments");
164 wp += builtin_opt.optind;
166 /* Substitute and execute command */
168 char *pat = NULL, *rep = NULL, *line;
170 if (editor || lflag || nflag || rflag) {
171 bi_errorf("can't use -e, -l, -n, -r with -s (-e -)");
175 /* Check for pattern replacement argument */
176 if (*wp && **wp && (p = cstrchr(*wp + 1, '='))) {
177 strdupx(pat, *wp, ATEMP);
178 rep = pat + (p - *wp);
182 /* Check for search prefix */
183 if (!first && (first = *wp))
186 bi_errorf("too many arguments");
190 hp = first ? hist_get(first, false, false) :
191 hist_get_newest(false);
196 strdupx(line, *hp, ATEMP);
199 size_t len, pat_len, rep_len;
202 bool any_subst = false;
204 pat_len = strlen(pat);
205 rep_len = strlen(rep);
206 Xinit(xs, xp, 128, ATEMP);
207 for (s = *hp; (s1 = strstr(s, pat)) &&
208 (!any_subst || gflag); s = s1 + pat_len) {
211 XcheckN(xs, xp, len + rep_len);
216 memcpy(xp, rep, rep_len);
220 bi_errorf("bad substitution");
224 XcheckN(xs, xp, len);
227 line = Xclose(xs, xp);
229 return (hist_execute(line, ATEMP));
232 if (editor && (lflag || nflag)) {
233 bi_errorf("can't use -l, -n with -e");
237 if (!first && (first = *wp))
239 if (!last && (last = *wp))
242 bi_errorf("too many arguments");
246 hfirst = lflag ? hist_get("-16", true, true) :
247 hist_get_newest(false);
250 /* can't fail if hfirst didn't fail */
251 hlast = hist_get_newest(false);
254 * POSIX says not an error if first/last out of bounds
255 * when range is specified; AT&T ksh and pdksh allow out
256 * of bounds for -l as well.
258 hfirst = hist_get(first, tobool(lflag || last), lflag);
261 hlast = last ? hist_get(last, true, lflag) :
262 (lflag ? hist_get_newest(false) : hfirst);
266 if (hfirst > hlast) {
269 temp = hfirst; hfirst = hlast; hlast = temp;
278 for (hp = rflag ? hlast : hfirst;
279 hp >= hfirst && hp <= hlast; hp += rflag ? -1 : 1) {
281 shf_fprintf(shl_stdout, "%lu",
282 (unsigned long)hist_source->line -
283 (unsigned long)(histptr - hp));
284 shf_putc('\t', shl_stdout);
285 /* print multi-line commands correctly */
287 while ((t = strchr(s, '\n'))) {
289 shf_fprintf(shl_stdout, "%s\n\t", s);
293 shf_fprintf(shl_stdout, "%s\n", s);
295 shf_flush(shl_stdout);
299 /* Run editor on selected lines, then run resulting commands */
301 tf = maketemp(ATEMP, TT_HIST_EDIT, &e->temps);
302 if (!(shf = tf->shf)) {
303 bi_errorf("can't %s temporary file %s: %s",
304 "create", tf->tffn, cstrerror(errno));
307 for (hp = rflag ? hlast : hfirst;
308 hp >= hfirst && hp <= hlast; hp += rflag ? -1 : 1)
309 shf_fprintf(shf, "%s\n", *hp);
310 if (shf_close(shf) == -1) {
311 bi_errorf("can't %s temporary file %s: %s",
312 "write", tf->tffn, cstrerror(errno));
316 /* Ignore setstr errors here (arbitrary) */
317 setstr(local("_", false), tf->tffn, KSH_RETURN_ERROR);
319 /* XXX: source should not get trashed by this.. */
321 Source *sold = source;
324 ret = command(editor ? editor : TFCEDIT_dollaru, 0);
336 if (!(shf = shf_open(tf->tffn, O_RDONLY, 0, 0))) {
337 bi_errorf("can't %s temporary file %s: %s",
338 "open", tf->tffn, cstrerror(errno));
342 if (stat(tf->tffn, &statb) < 0)
344 else if ((off_t)statb.st_size > MKSH_MAXHISTFSIZE) {
345 bi_errorf("%s %s too large: %lu", Thistory,
346 "file", (unsigned long)statb.st_size);
349 n = (size_t)statb.st_size + 1;
350 Xinit(xs, xp, n, hist_source->areap);
351 while ((n = shf_read(xp, Xnleft(xs, xp), shf)) > 0) {
353 if (Xnleft(xs, xp) <= 0)
354 XcheckN(xs, xp, Xlength(xs, xp));
357 bi_errorf("can't %s temporary file %s: %s",
358 "read", tf->tffn, cstrerror(shf_errno(shf)));
365 strip_nuls(Xstring(xs, xp), Xlength(xs, xp));
366 return (hist_execute(Xstring(xs, xp), hist_source->areap));
370 /* save cmd in history, execute cmd (cmd gets afree’d) */
372 hist_execute(char *cmd, Area *areap)
374 static int last_line = -1;
378 /* Back up over last histsave */
379 if (histptr >= history && last_line != hist_source->line) {
381 afree(*histptr, APERM);
383 last_line = hist_source->line;
386 histsave(&hist_source->line, cmd, HIST_STORE, true);
387 /* now *histptr == cmd without all trailing newlines */
390 /* pdksh says POSIX doesn’t say this is done, testsuite needs it */
394 * Commands are executed here instead of pushing them onto the
395 * input 'cause POSIX says the redirection and variable assignments
397 * X=y fc -e - 42 2> /dev/null
398 * are to effect the repeated commands environment.
400 /* XXX: source should not get trashed by this.. */
402 ret = command(cmd, 0);
408 * get pointer to history given pattern
409 * pattern is a number or string
412 hist_get(const char *str, bool approx, bool allow_cur)
418 hp = histptr + (n < 0 ? n : (n - hist_source->line));
419 if ((size_t)hp < (size_t)history) {
421 hp = hist_get_oldest();
423 bi_errorf("%s: %s", str, Tnot_in_history);
426 } else if ((size_t)hp > (size_t)histptr) {
428 hp = hist_get_newest(allow_cur);
430 bi_errorf("%s: %s", str, Tnot_in_history);
433 } else if (!allow_cur && hp == histptr) {
434 bi_errorf("%s: %s", str, "invalid range");
438 bool anchored = *str == '?' ? (++str, false) : true;
440 /* the -1 is to avoid the current fc command */
441 if ((n = findhist(histptr - history - 1, 0, str, anchored)) < 0)
442 bi_errorf("%s: %s", str, Tnot_in_history);
449 /* Return a pointer to the newest command in the history */
451 hist_get_newest(bool allow_cur)
453 if (histptr < history || (!allow_cur && histptr == history)) {
454 bi_errorf("no history (yet)");
457 return (allow_cur ? histptr : histptr - 1);
460 /* Return a pointer to the oldest command in the history */
462 hist_get_oldest(void)
464 if (histptr <= history) {
465 bi_errorf("no history (yet)");
471 #if !defined(MKSH_NO_CMDLINE_EDITING) && !MKSH_S_NOVI
472 /* current position in history[] */
473 static char **current;
476 * Return the current position.
487 int last = histptr - history;
489 if (n < 0 || n >= last) {
493 current = &history[n];
500 * This will become unnecessary if hist_get is modified to allow
501 * searching from positions other than the end, and in either
505 findhist(int start, int fwd, const char *str, bool anchored)
508 int maxhist = histptr - history;
509 int incr = fwd ? 1 : -1;
510 size_t len = strlen(str);
512 if (start < 0 || start >= maxhist)
515 hp = &history[start];
516 for (; hp >= history && hp <= histptr; hp += incr)
517 if ((anchored && strncmp(*hp, str, len) == 0) ||
518 (!anchored && strstr(*hp, str)))
519 return (hp - history);
525 * set history; this means reallocating the dataspace
528 sethistsize(mksh_ari_t n)
530 if (n > 0 && n != histsize) {
531 int cursize = histptr - history;
533 /* save most recent history */
535 memmove(history, histptr - n + 1, n * sizeof(char *));
539 history = aresize2(history, n, sizeof(char *), APERM);
542 histptr = history + cursize;
546 #if HAVE_PERSISTENT_HISTORY
548 * set history file; this can mean reloading/resetting/starting
549 * history file maintenance
552 sethistfile(const char *name)
554 /* if not started then nothing to do */
555 if (hstarted == false)
558 /* if the name is the same as the name we have */
559 if (hname && name && !strcmp(hname, name))
563 * it's a new name - possibly
566 /* yes the file is open */
572 /* let's reset the history */
573 histsave(NULL, NULL, HIST_DISCARD, true);
574 histptr = history - 1;
575 hist_source->line = 0;
579 hist_init(hist_source);
584 * initialise the history vector
589 if (history == (char **)NULL) {
590 histsize = MKSH_DEFHISTSIZE;
591 history = alloc2(histsize, sizeof(char *), APERM);
592 histptr = history - 1;
598 * It turns out that there is a lot of ghastly hackery here
601 #if !defined(MKSH_SMALL) && HAVE_PERSISTENT_HISTORY
602 /* do not save command in history but possibly sync */
606 bool changed = false;
608 /* called by histsave(), may not HIST_DISCARD, caller should flush */
611 int lno = hist_source->line;
614 writehistfile(0, NULL);
617 if (lno != hist_source->line)
626 * save command in history
629 histsave(int *lnp, const char *cmd, int svmode, bool ignoredups)
631 static char *enqueued = NULL;
635 if (svmode == HIST_DISCARD) {
636 afree(enqueued, APERM);
641 if (svmode == HIST_APPEND) {
644 } else if (enqueued) {
648 histsave(lnp, c, HIST_STORE, true);
652 if (svmode == HIST_FLUSH)
655 ccp = cmd + strlen(cmd);
656 while (ccp > cmd && ccp[-1] == '\n')
658 strndupx(c, cmd, ccp - cmd, APERM);
660 if (svmode != HIST_APPEND) {
661 if (ignoredups && !strcmp(c, *histptr)
662 #if !defined(MKSH_SMALL) && HAVE_PERSISTENT_HISTORY
672 #if HAVE_PERSISTENT_HISTORY
673 if (svmode == HIST_STORE && histfd != -1)
674 writehistfile(*lnp, c);
677 if (svmode == HIST_QUEUE || svmode == HIST_APPEND) {
688 nenq = strlen(enqueued);
690 enqueued = aresize(enqueued, nenq + 1 + ncmd + 1, APERM);
691 enqueued[nenq] = '\n';
692 memcpy(enqueued + nenq + 1, c, ncmd + 1);
699 if (++hp >= history + histsize) {
700 /* remove oldest command */
701 afree(*history, APERM);
702 for (hp = history; hp < history + histsize - 1; hp++)
710 * Write history data to a file nominated by HISTFILE;
711 * if HISTFILE is unset then history still happens, but
712 * the data is not written to a file. All copies of ksh
713 * looking at the file will maintain the same history.
714 * This is ksh behaviour.
716 * This stuff uses mmap()
718 * This stuff is so totally broken it must eventually be
719 * redesigned, without mmap, better checks, support for
720 * larger files, etc. and handle partially corrupted files
724 * Open a history file
727 * HMAGIC - just to check that we are dealing with the correct object
728 * Then follows a number of stored commands
730 * <command byte><command number(4 octets, big endian)><bytes><NUL>
736 #if HAVE_PERSISTENT_HISTORY
737 static const unsigned char sprinkle[2] = { HMAGIC1, HMAGIC2 };
743 #if HAVE_PERSISTENT_HISTORY
746 enum { hist_init_first, hist_init_retry, hist_init_restore } hs;
749 histsave(NULL, NULL, HIST_DISCARD, true);
751 if (Flag(FTALKING) == 0)
757 #if HAVE_PERSISTENT_HISTORY
758 if (((hname = str_val(global("HISTFILE"))) == NULL) || !*hname) {
762 strdupx(hname, hname, APERM);
763 hs = hist_init_first;
766 /* we have a file and are interactive */
767 if ((fd = binopen3(hname, O_RDWR | O_CREAT | O_APPEND, 0600)) < 0)
776 histfsize = lseek(histfd, (off_t)0, SEEK_END);
777 if (histfsize > MKSH_MAXHISTFSIZE || hs == hist_init_restore) {
778 /* we ignore too large files but still append to them */
779 /* we also don't need to re-read after truncation */
781 } else if (histfsize > 2) {
782 /* we have some data, check its validity */
783 base = (void *)mmap(NULL, (size_t)histfsize, PROT_READ,
784 MAP_FILE | MAP_PRIVATE, histfd, (off_t)0);
785 if (base == (unsigned char *)MAP_FAILED)
787 if (base[0] != HMAGIC1 || base[1] != HMAGIC2) {
788 munmap(caddr_cast(base), (size_t)histfsize);
791 /* load _all_ data */
792 lines = histload(hist_source, base + 2, (size_t)histfsize - 2);
793 munmap(caddr_cast(base), (size_t)histfsize);
794 /* check if the file needs to be truncated */
795 if (lines > histsize && histptr >= history) {
796 /* you're fucked up with the current code, trust me */
800 /* create temporary file */
801 nhname = shf_smprintf("%s.%d", hname, (int)procpid);
802 if ((fd = binopen3(nhname, O_RDWR | O_CREAT | O_TRUNC |
803 O_EXCL, 0600)) < 0) {
804 /* just don't truncate then, meh. */
805 goto hist_trunc_dont;
807 if (fstat(histfd, &sb) >= 0 &&
808 chown(nhname, sb.st_uid, sb.st_gid)) {
809 /* abort the truncation then, meh. */
810 goto hist_trunc_abort;
812 /* we definitively want some magic in that file */
813 if (write(fd, sprinkle, 2) != 2)
814 goto hist_trunc_abort;
815 /* and of course the entries */
817 while (hp < histptr) {
818 if (!writehistline(fd,
819 s->line - (histptr - hp), *hp))
820 goto hist_trunc_abort;
823 /* now unlock, close both, rename, rinse, repeat */
827 if (rename(nhname, hname) < 0) {
833 goto hist_trunc_dont;
834 /* darn! restore histfd and pray */
836 hs = hist_init_restore;
838 afree(nhname, ATEMP);
839 if (hs == hist_init_restore)
842 } else if (histfsize != 0) {
843 /* negative or too small... */
845 /* ... or mmap failed or illegal */
847 /* nuke the bogus file then retry, at most once */
848 if (!unlink(hname) && hs != hist_init_retry) {
849 hs = hist_init_retry;
852 if (hs != hist_init_retry)
853 bi_errorf("can't %s %s: %s",
854 "unlink HISTFILE", hname, cstrerror(errno));
858 /* size 0, add magic to the history file */
859 if (write(histfd, sprinkle, 2) != 2) {
864 histfsize = lseek(histfd, (off_t)0, SEEK_END);
870 #if HAVE_PERSISTENT_HISTORY
872 * load the history structure from the stored data
875 histload(Source *s, unsigned char *base, size_t bytes)
877 int lno = 0, lines = 0;
881 /* !bytes check as some systems (older FreeBSDs) have buggy memchr */
882 if (!bytes || (cp = memchr(base, COMMAND, bytes)) == NULL)
884 /* advance base pointer past COMMAND byte */
885 bytes -= ++cp - base;
887 /* if there is no full string left, don't bother with the rest */
888 if (bytes < 5 || (cp = memchr(base + 4, '\0', bytes - 4)) == NULL)
890 /* load the stored line number */
891 lno = ((base[0] & 0xFF) << 24) | ((base[1] & 0xFF) << 16) |
892 ((base[2] & 0xFF) << 8) | (base[3] & 0xFF);
893 /* store away the found line (@base[4]) */
895 if (histptr >= history && lno - 1 != s->line) {
899 if (lno >= s->line - (histptr - history) && lno <= s->line) {
900 hp = &histptr[lno - s->line];
902 strdupx(*hp, (char *)(base + 4), APERM);
906 histsave(&lno, (char *)(base + 4), HIST_NOTE, false);
908 /* advance base pointer past NUL */
909 bytes -= ++cp - base;
911 /* repeat until no more */
916 * write a command to the end of the history file
918 * This *MAY* seem easy but it's also necessary to check
919 * that the history file has not changed in size.
920 * If it has - then some other shell has written to it and
921 * we should (re)read those commands to update our history
924 writehistfile(int lno, const char *cmd)
928 unsigned char *base, *news;
931 sizenow = lseek(histfd, (off_t)0, SEEK_END);
932 if (sizenow < histfsize) {
933 /* the file has shrunk; give up */
937 /* ignore changes when the file is too large */
938 sizenow <= MKSH_MAXHISTFSIZE
940 /* the size has changed, we need to do read updates */
943 /* both sizenow and histfsize are <= MKSH_MAXHISTFSIZE */
944 bytes = (size_t)(sizenow - histfsize);
945 base = (void *)mmap(NULL, (size_t)sizenow, PROT_READ,
946 MAP_FILE | MAP_PRIVATE, histfd, (off_t)0);
947 if (base == (unsigned char *)MAP_FAILED)
949 news = base + (size_t)histfsize;
950 if (*news == COMMAND) {
952 histload(hist_source, news, bytes);
954 lno = hist_source->line;
957 munmap(caddr_cast(base), (size_t)sizenow);
961 if (cmd && !writehistline(histfd, lno, cmd)) {
966 histfsize = lseek(histfd, (off_t)0, SEEK_END);
971 writehistline(int fd, int lno, const char *cmd)
974 unsigned char hdr[5];
977 hdr[1] = (lno >> 24) & 0xFF;
978 hdr[2] = (lno >> 16) & 0xFF;
979 hdr[3] = (lno >> 8) & 0xFF;
982 return (write(fd, hdr, 5) == 5 && write(fd, cmd, n) == n);
997 #if !HAVE_SYS_SIGNAME
998 static const struct mksh_sigpair {
999 const char * const name;
1001 } mksh_sigpairs[] = {
1002 #include "signames.inc"
1007 #if HAVE_SYS_SIGLIST
1008 #if !HAVE_SYS_SIGLIST_DECL
1009 extern const char * const sys_siglist[];
1021 /* Populate sigtraps based on sys_signame and sys_siglist. */
1022 for (i = 1; i < ksh_NSIG; i++) {
1023 sigtraps[i].signal = i;
1024 #if HAVE_SYS_SIGNAME
1025 cs = sys_signame[i];
1027 const struct mksh_sigpair *pair = mksh_sigpairs;
1028 while ((pair->nr != i) && (pair->name != NULL))
1034 sigtraps[i].name = shf_smprintf("%d", i);
1038 /* this is not optimal, what about SIGSIG1? */
1039 if (ksh_eq(cs[0], 'S', 's') &&
1040 ksh_eq(cs[1], 'I', 'i') &&
1041 ksh_eq(cs[2], 'G', 'g') &&
1043 /* skip leading "SIG" */
1046 strdupx(s, cs, APERM);
1047 sigtraps[i].name = s;
1048 while ((*s = ksh_toupper(*s)))
1051 #if HAVE_SYS_SIGLIST
1052 sigtraps[i].mess = sys_siglist[i];
1053 #elif HAVE_STRSIGNAL
1054 sigtraps[i].mess = strsignal(i);
1056 sigtraps[i].mess = NULL;
1058 if ((sigtraps[i].mess == NULL) ||
1059 (sigtraps[i].mess[0] == '\0'))
1060 sigtraps[i].mess = shf_smprintf("%s %d",
1063 sigtraps[ksh_SIGEXIT].signal = ksh_SIGEXIT;
1064 sigtraps[ksh_SIGEXIT].name = "EXIT";
1065 sigtraps[ksh_SIGEXIT].mess = "Exit trap";
1066 sigtraps[ksh_SIGERR].signal = ksh_SIGERR;
1067 sigtraps[ksh_SIGERR].name = "ERR";
1068 sigtraps[ksh_SIGERR].mess = "Error handler";
1070 (void)sigemptyset(&Sigact_ign.sa_mask);
1071 Sigact_ign.sa_flags = 0; /* interruptible */
1072 Sigact_ign.sa_handler = SIG_IGN;
1074 sigtraps[SIGINT].flags |= TF_DFL_INTR | TF_TTY_INTR;
1075 sigtraps[SIGQUIT].flags |= TF_DFL_INTR | TF_TTY_INTR;
1076 /* SIGTERM is not fatal for interactive */
1077 sigtraps[SIGTERM].flags |= TF_DFL_INTR;
1078 sigtraps[SIGHUP].flags |= TF_FATAL;
1079 sigtraps[SIGCHLD].flags |= TF_SHELL_USES;
1081 /* these are always caught so we can clean up any temporary files. */
1082 setsig(&sigtraps[SIGINT], trapsig, SS_RESTORE_ORIG);
1083 setsig(&sigtraps[SIGQUIT], trapsig, SS_RESTORE_ORIG);
1084 setsig(&sigtraps[SIGTERM], trapsig, SS_RESTORE_ORIG);
1085 setsig(&sigtraps[SIGHUP], trapsig, SS_RESTORE_ORIG);
1088 static void alarm_catcher(int sig);
1093 sigtraps[SIGALRM].flags |= TF_SHELL_USES;
1094 setsig(&sigtraps[SIGALRM], alarm_catcher,
1095 SS_RESTORE_ORIG|SS_FORCE|SS_SHTRAP);
1100 alarm_catcher(int sig MKSH_A_UNUSED)
1102 /* this runs inside interrupt context, with errno saved */
1104 if (ksh_tmout_state == TMOUT_READING) {
1105 int left = alarm(0);
1108 ksh_tmout_state = TMOUT_LEAVING;
1116 gettrap(const char *cs, bool igncase, bool allsigs)
1122 /* signal number (1..ksh_NSIG) or 0? */
1124 if (ksh_isdigit(*cs))
1125 return ((getn(cs, &i) && 0 <= i && i < ksh_NSIG) ?
1126 (&sigtraps[i]) : NULL);
1128 /* do a lookup by name then */
1130 /* this breaks SIGSIG1, but we do that above anyway */
1131 if (ksh_eq(cs[0], 'S', 's') &&
1132 ksh_eq(cs[1], 'I', 'i') &&
1133 ksh_eq(cs[2], 'G', 'g') &&
1135 /* skip leading "SIG" */
1141 strdupx(as, cs, ATEMP);
1143 while ((*s = ksh_toupper(*s)))
1148 /* this is idiotic, we really want a hashtable here */
1153 if (!strcmp(p->name, cs))
1161 if (p->signal == ksh_SIGEXIT || p->signal == ksh_SIGERR) {
1171 * trap signal handler
1176 Trap *p = &sigtraps[i];
1180 if (p->flags & TF_DFL_INTR)
1182 if ((p->flags & TF_FATAL) && !p->trap) {
1192 * called when we want to allow the user to ^C out of something - won't
1193 * work if user has trapped SIGINT.
1199 runtraps(TF_DFL_INTR|TF_FATAL);
1203 * called after EINTR to check if a signal with normally causes process
1204 * termination has been received.
1207 fatal_trap_check(void)
1210 int i = ksh_NSIG + 1;
1212 /* todo: should check if signal is fatal, not the TF_DFL_INTR flag */
1214 if (p->set && (p->flags & (TF_DFL_INTR|TF_FATAL)))
1215 /* return value is used as an exit code */
1216 return (ksh_sigmask(p->signal));
1223 * Returns the signal number of any pending traps: ie, a signal which has
1224 * occurred for which a trap has been set or for which the TF_DFL_INTR flag
1231 int i = ksh_NSIG + 1;
1234 if (p->set && ((p->trap && p->trap[0]) ||
1235 ((p->flags & (TF_DFL_INTR|TF_FATAL)) && !p->trap)))
1243 * run any pending traps. If intr is set, only run traps that
1244 * can interrupt commands.
1250 int i = ksh_NSIG + 1;
1252 if (ksh_tmout_state == TMOUT_LEAVING) {
1253 ksh_tmout_state = TMOUT_EXECUTING;
1254 warningf(false, "timed out waiting for input");
1258 * XXX: this means the alarm will have no effect if a trap
1259 * is caught after the alarm() was started...not good.
1261 ksh_tmout_state = TMOUT_EXECUTING;
1264 if (flag & TF_DFL_INTR)
1266 if (flag & TF_FATAL)
1270 if (p->set && (!flag ||
1271 ((p->flags & flag) && p->trap == NULL)))
1276 runtrap(NULL, true);
1280 runtrap(Trap *p, bool is_last)
1282 int old_changed = 0, i;
1286 /* just clean up, see runtraps() above */
1291 if (trapstr == NULL) {
1293 if (p->flags & (TF_FATAL | TF_DFL_INTR)) {
1294 exstat = (int)(128U + (unsigned)i);
1295 if ((unsigned)exstat > 255U)
1299 if (p->flags & TF_FATAL)
1301 /* e.g. SIGINT, SIGQUIT, SIGTERM, etc. */
1302 if (p->flags & TF_DFL_INTR)
1306 if (trapstr[0] == '\0')
1309 if (i == ksh_SIGEXIT || i == ksh_SIGERR) {
1310 /* avoid recursion on these */
1311 old_changed = p->flags & TF_CHANGED;
1312 p->flags &= ~TF_CHANGED;
1315 if (trap_exstat == -1)
1316 trap_exstat = exstat & 0xFF;
1318 * Note: trapstr is fully parsed before anything is executed, thus
1319 * no problem with afree(p->trap) in settrap() while still in use.
1321 command(trapstr, current_lineno);
1322 if (i == ksh_SIGEXIT || i == ksh_SIGERR) {
1323 if (p->flags & TF_CHANGED)
1324 /* don't clear TF_CHANGED */
1325 afree(trapstr, APERM);
1328 p->flags |= old_changed;
1332 /* we're the last trap of a sequence executed */
1333 if (is_last && trap_exstat != -1) {
1334 exstat = trap_exstat;
1339 /* clear pending traps and reset user's trap handlers; used after fork(2) */
1344 int i = ksh_NSIG + 1;
1352 if ((p->flags & TF_USER_SET) && (p->trap && p->trap[0]))
1358 /* restore signals just before an exec(2) */
1363 int i = ksh_NSIG + 1;
1366 if (p->flags & (TF_EXEC_IGN|TF_EXEC_DFL))
1367 setsig(p, (p->flags & TF_EXEC_IGN) ? SIG_IGN : SIG_DFL,
1368 SS_RESTORE_CURR|SS_FORCE);
1374 settrap(Trap *p, const char *s)
1378 afree(p->trap, APERM);
1379 /* handles s == NULL */
1380 strdupx(p->trap, s, APERM);
1381 p->flags |= TF_CHANGED;
1382 f = !s ? SIG_DFL : s[0] ? trapsig : SIG_IGN;
1384 p->flags |= TF_USER_SET;
1385 if ((p->flags & (TF_DFL_INTR|TF_FATAL)) && f == SIG_DFL)
1387 else if (p->flags & TF_SHELL_USES) {
1388 if (!(p->flags & TF_ORIG_IGN) || Flag(FTALKING)) {
1389 /* do what user wants at exec time */
1390 p->flags &= ~(TF_EXEC_IGN|TF_EXEC_DFL);
1392 p->flags |= TF_EXEC_IGN;
1394 p->flags |= TF_EXEC_DFL;
1398 * assumes handler already set to what shell wants it
1399 * (normally trapsig, but could be j_sigchld() or SIG_IGN)
1404 /* todo: should we let user know signal is ignored? how? */
1405 setsig(p, f, SS_RESTORE_CURR|SS_USER);
1409 * Called by c_print() when writing to a co-process to ensure SIGPIPE won't
1410 * kill shell (unless user catches it and exits)
1415 int restore_dfl = 0;
1416 Trap *p = &sigtraps[SIGPIPE];
1418 if (!(p->flags & (TF_ORIG_IGN|TF_ORIG_DFL))) {
1419 setsig(p, SIG_IGN, SS_RESTORE_CURR);
1420 if (p->flags & TF_ORIG_DFL)
1422 } else if (p->cursig == SIG_DFL) {
1423 setsig(p, SIG_IGN, SS_RESTORE_CURR);
1424 /* restore to SIG_DFL */
1427 return (restore_dfl);
1430 /* Called by c_print() to undo whatever block_pipe() did */
1432 restore_pipe(int restore_dfl)
1435 setsig(&sigtraps[SIGPIPE], SIG_DFL, SS_RESTORE_CURR);
1439 * Set action for a signal. Action may not be set if original
1440 * action was SIG_IGN, depending on the value of flags and FTALKING.
1443 setsig(Trap *p, sig_t f, int flags)
1445 struct sigaction sigact;
1447 if (p->signal == ksh_SIGEXIT || p->signal == ksh_SIGERR)
1450 memset(&sigact, 0, sizeof(sigact));
1453 * First time setting this signal? If so, get and note the current
1456 if (!(p->flags & (TF_ORIG_IGN|TF_ORIG_DFL))) {
1457 sigaction(p->signal, &Sigact_ign, &sigact);
1458 p->flags |= sigact.sa_handler == SIG_IGN ?
1459 TF_ORIG_IGN : TF_ORIG_DFL;
1460 p->cursig = SIG_IGN;
1464 * Generally, an ignored signal stays ignored, except if
1465 * - the user of an interactive shell wants to change it
1466 * - the shell wants for force a change
1468 if ((p->flags & TF_ORIG_IGN) && !(flags & SS_FORCE) &&
1469 (!(flags & SS_USER) || !Flag(FTALKING)))
1472 setexecsig(p, flags & SS_RESTORE_MASK);
1475 * This is here 'cause there should be a way of clearing
1476 * shtraps, but don't know if this is a sane way of doing
1477 * it. At the moment, all users of shtrap are lifetime
1478 * users (SIGALRM, SIGCHLD, SIGWINCH).
1480 if (!(flags & SS_USER))
1481 p->shtrap = (sig_t)NULL;
1482 if (flags & SS_SHTRAP) {
1487 if (p->cursig != f) {
1489 (void)sigemptyset(&sigact.sa_mask);
1491 sigact.sa_flags = 0;
1492 sigact.sa_handler = f;
1493 sigaction(p->signal, &sigact, NULL);
1499 /* control what signal is set to before an exec() */
1501 setexecsig(Trap *p, int restore)
1504 if (!(p->flags & (TF_ORIG_IGN|TF_ORIG_DFL)))
1505 internal_errorf("setexecsig: unset signal %d(%s)",
1506 p->signal, p->name);
1508 /* restore original value for exec'd kids */
1509 p->flags &= ~(TF_EXEC_IGN|TF_EXEC_DFL);
1510 switch (restore & SS_RESTORE_MASK) {
1511 case SS_RESTORE_CURR:
1512 /* leave things as they currently are */
1514 case SS_RESTORE_ORIG:
1515 p->flags |= p->flags & TF_ORIG_IGN ? TF_EXEC_IGN : TF_EXEC_DFL;
1517 case SS_RESTORE_DFL:
1518 p->flags |= TF_EXEC_DFL;
1520 case SS_RESTORE_IGN:
1521 p->flags |= TF_EXEC_IGN;
1526 #if HAVE_PERSISTENT_HISTORY || defined(DF)
1528 * File descriptor locking and unlocking functions.
1529 * Could use some error handling, but hey, this is only
1530 * advisory locking anyway, will often not work over NFS,
1531 * and you are SOL if this fails...
1537 #if defined(__OpenBSD__)
1538 /* flock is not interrupted by signals */
1539 (void)flock(fd, LOCK_EX);
1545 rv = flock(fd, LOCK_EX);
1546 } while (rv == 1 && errno == EINTR);
1547 #elif HAVE_LOCK_FCNTL
1551 memset(&lks, 0, sizeof(lks));
1552 lks.l_type = F_WRLCK;
1554 rv = fcntl(fd, F_SETLKW, &lks);
1555 } while (rv == 1 && errno == EINTR);
1559 /* designed to not define mksh_unlkfd if none triggered */
1564 (void)flock(fd, LOCK_UN);
1566 #elif HAVE_LOCK_FCNTL
1572 memset(&lks, 0, sizeof(lks));
1573 lks.l_type = F_UNLCK;
1574 (void)fcntl(fd, F_SETLKW, &lks);