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, 2017
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.166 2017/08/07 23:25:09 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 /* HISTSIZE default: size of saved history, persistent or standard */
74 #define MKSH_DEFHISTSIZE 255
76 #define MKSH_DEFHISTSIZE 2047
78 /* maximum considered size of persistent history file */
79 #define MKSH_MAXHISTFSIZE ((off_t)1048576 * 96)
82 #define HIST_DISCARD 5
89 bool gflag = false, lflag = false, nflag = false, rflag = false,
92 const char *p, *first = NULL, *last = NULL;
93 char **hfirst, **hlast, **hp, *editor = NULL;
95 if (!Flag(FTALKING_I)) {
96 bi_errorf("history %ss not available", Tfunction);
100 while ((optc = ksh_getopt(wp, &builtin_opt,
101 "e:glnrs0,1,2,3,4,5,6,7,8,9,")) != -1)
105 p = builtin_opt.optarg;
109 size_t len = strlen(p);
111 /* almost certainly not overflowing */
112 editor = alloc(len + 4, ATEMP);
113 memcpy(editor, p, len);
114 memcpy(editor + len, Tspdollaru, 4);
135 /* POSIX version of -e - */
140 /* kludge city - accept -num as -- -num (kind of) */
141 case '0': case '1': case '2': case '3': case '4':
142 case '5': case '6': case '7': case '8': case '9':
143 p = shf_smprintf("-%c%s",
144 optc, builtin_opt.optarg);
150 bi_errorf(Ttoo_many_args);
158 wp += builtin_opt.optind;
160 /* Substitute and execute command */
162 char *pat = NULL, *rep = NULL, *line;
164 if (editor || lflag || nflag || rflag) {
165 bi_errorf("can't use -e, -l, -n, -r with -s (-e -)");
169 /* Check for pattern replacement argument */
170 if (*wp && **wp && (p = cstrchr(*wp + 1, '='))) {
171 strdupx(pat, *wp, ATEMP);
172 rep = pat + (p - *wp);
176 /* Check for search prefix */
177 if (!first && (first = *wp))
180 bi_errorf(Ttoo_many_args);
184 hp = first ? hist_get(first, false, false) :
185 hist_get_newest(false);
190 strdupx(line, *hp, ATEMP);
193 size_t len, pat_len, rep_len;
196 bool any_subst = false;
198 pat_len = strlen(pat);
199 rep_len = strlen(rep);
200 Xinit(xs, xp, 128, ATEMP);
201 for (s = *hp; (s1 = strstr(s, pat)) &&
202 (!any_subst || gflag); s = s1 + pat_len) {
205 XcheckN(xs, xp, len + rep_len);
210 memcpy(xp, rep, rep_len);
214 bi_errorf(Tbadsubst);
218 XcheckN(xs, xp, len);
221 line = Xclose(xs, xp);
223 return (hist_execute(line, ATEMP));
226 if (editor && (lflag || nflag)) {
227 bi_errorf("can't use -l, -n with -e");
231 if (!first && (first = *wp))
233 if (!last && (last = *wp))
236 bi_errorf(Ttoo_many_args);
240 hfirst = lflag ? hist_get("-16", true, true) :
241 hist_get_newest(false);
244 /* can't fail if hfirst didn't fail */
245 hlast = hist_get_newest(false);
248 * POSIX says not an error if first/last out of bounds
249 * when range is specified; AT&T ksh and pdksh allow out
250 * of bounds for -l as well.
252 hfirst = hist_get(first, tobool(lflag || last), lflag);
255 hlast = last ? hist_get(last, true, lflag) :
256 (lflag ? hist_get_newest(false) : hfirst);
260 if (hfirst > hlast) {
263 temp = hfirst; hfirst = hlast; hlast = temp;
272 for (hp = rflag ? hlast : hfirst;
273 hp >= hfirst && hp <= hlast; hp += rflag ? -1 : 1) {
275 shf_fprintf(shl_stdout, Tf_lu,
276 (unsigned long)hist_source->line -
277 (unsigned long)(histptr - hp));
278 shf_putc('\t', shl_stdout);
279 /* print multi-line commands correctly */
281 while ((t = strchr(s, '\n'))) {
283 shf_fprintf(shl_stdout, "%s\n\t", s);
287 shf_fprintf(shl_stdout, Tf_sN, s);
289 shf_flush(shl_stdout);
293 /* Run editor on selected lines, then run resulting commands */
295 tf = maketemp(ATEMP, TT_HIST_EDIT, &e->temps);
296 if (!(shf = tf->shf)) {
297 bi_errorf(Tf_temp, Tcreate, tf->tffn, cstrerror(errno));
300 for (hp = rflag ? hlast : hfirst;
301 hp >= hfirst && hp <= hlast; hp += rflag ? -1 : 1)
302 shf_fprintf(shf, Tf_sN, *hp);
303 if (shf_close(shf) == -1) {
304 bi_errorf(Tf_temp, Twrite, tf->tffn, cstrerror(errno));
308 /* Ignore setstr errors here (arbitrary) */
309 setstr(local("_", false), tf->tffn, KSH_RETURN_ERROR);
311 if ((optc = command(editor ? editor : TFCEDIT_dollaru, 0)))
320 if (!(shf = shf_open(tf->tffn, O_RDONLY, 0, 0))) {
321 bi_errorf(Tf_temp, Topen, tf->tffn, cstrerror(errno));
325 if (stat(tf->tffn, &statb) < 0)
327 else if ((off_t)statb.st_size > MKSH_MAXHISTFSIZE) {
328 bi_errorf(Tf_toolarge, Thistory,
329 Tfile, (unsigned long)statb.st_size);
332 n = (size_t)statb.st_size + 1;
333 Xinit(xs, xp, n, hist_source->areap);
334 while ((n = shf_read(xp, Xnleft(xs, xp), shf)) > 0) {
336 if (Xnleft(xs, xp) <= 0)
337 XcheckN(xs, xp, Xlength(xs, xp));
340 bi_errorf(Tf_temp, Tread, tf->tffn,
341 cstrerror(shf_errno(shf)));
348 strip_nuls(Xstring(xs, xp), Xlength(xs, xp));
349 return (hist_execute(Xstring(xs, xp), hist_source->areap));
353 /* save cmd in history, execute cmd (cmd gets afree’d) */
355 hist_execute(char *cmd, Area *areap)
357 static int last_line = -1;
359 /* Back up over last histsave */
360 if (histptr >= history && last_line != hist_source->line) {
362 afree(*histptr, APERM);
364 last_line = hist_source->line;
367 histsave(&hist_source->line, cmd, HIST_STORE, true);
368 /* now *histptr == cmd without all trailing newlines */
371 /* pdksh says POSIX doesn’t say this is done, testsuite needs it */
375 * Commands are executed here instead of pushing them onto the
376 * input 'cause POSIX says the redirection and variable assignments
378 * X=y fc -e - 42 2> /dev/null
379 * are to effect the repeated commands environment.
381 return (command(cmd, 0));
385 * get pointer to history given pattern
386 * pattern is a number or string
389 hist_get(const char *str, bool approx, bool allow_cur)
395 hp = histptr + (n < 0 ? n : (n - hist_source->line));
396 if ((size_t)hp < (size_t)history) {
398 hp = hist_get_oldest();
400 bi_errorf(Tf_sD_s, str, Tnot_in_history);
403 } else if ((size_t)hp > (size_t)histptr) {
405 hp = hist_get_newest(allow_cur);
407 bi_errorf(Tf_sD_s, str, Tnot_in_history);
410 } else if (!allow_cur && hp == histptr) {
411 bi_errorf(Tf_sD_s, str, "invalid range");
415 bool anchored = *str == '?' ? (++str, false) : true;
417 /* the -1 is to avoid the current fc command */
418 if ((n = findhist(histptr - history - 1, 0, str, anchored)) < 0)
419 bi_errorf(Tf_sD_s, str, Tnot_in_history);
426 /* Return a pointer to the newest command in the history */
428 hist_get_newest(bool allow_cur)
430 if (histptr < history || (!allow_cur && histptr == history)) {
431 bi_errorf("no history (yet)");
434 return (allow_cur ? histptr : histptr - 1);
437 /* Return a pointer to the oldest command in the history */
439 hist_get_oldest(void)
441 if (histptr <= history) {
442 bi_errorf("no history (yet)");
448 #if !defined(MKSH_NO_CMDLINE_EDITING) && !MKSH_S_NOVI
449 /* current position in history[] */
450 static char **current;
453 * Return the current position.
464 int last = histptr - history;
466 if (n < 0 || n >= last) {
470 current = &history[n];
477 * This will become unnecessary if hist_get is modified to allow
478 * searching from positions other than the end, and in either
482 findhist(int start, int fwd, const char *str, bool anchored)
485 int maxhist = histptr - history;
486 int incr = fwd ? 1 : -1;
487 size_t len = strlen(str);
489 if (start < 0 || start >= maxhist)
492 hp = &history[start];
493 for (; hp >= history && hp <= histptr; hp += incr)
494 if ((anchored && strncmp(*hp, str, len) == 0) ||
495 (!anchored && strstr(*hp, str)))
496 return (hp - history);
502 * set history; this means reallocating the dataspace
505 sethistsize(mksh_ari_t n)
507 if (n > 0 && n != histsize) {
508 int cursize = histptr - history;
510 /* save most recent history */
512 memmove(history, histptr - n + 1, n * sizeof(char *));
516 history = aresize2(history, n, sizeof(char *), APERM);
519 histptr = history + cursize;
523 #if HAVE_PERSISTENT_HISTORY
525 * set history file; this can mean reloading/resetting/starting
526 * history file maintenance
529 sethistfile(const char *name)
531 /* if not started then nothing to do */
532 if (hstarted == false)
535 /* if the name is the same as the name we have */
536 if (hname && name && !strcmp(hname, name))
540 * it's a new name - possibly
543 /* yes the file is open */
549 /* let's reset the history */
550 histsave(NULL, NULL, HIST_DISCARD, true);
551 histptr = history - 1;
552 hist_source->line = 0;
556 hist_init(hist_source);
561 * initialise the history vector
566 if (history == (char **)NULL) {
567 histsize = MKSH_DEFHISTSIZE;
568 history = alloc2(histsize, sizeof(char *), APERM);
569 histptr = history - 1;
575 * It turns out that there is a lot of ghastly hackery here
578 #if !defined(MKSH_SMALL) && HAVE_PERSISTENT_HISTORY
579 /* do not save command in history but possibly sync */
583 bool changed = false;
585 /* called by histsave(), may not HIST_DISCARD, caller should flush */
588 int lno = hist_source->line;
591 writehistfile(0, NULL);
594 if (lno != hist_source->line)
603 * save command in history
606 histsave(int *lnp, const char *cmd, int svmode, bool ignoredups)
608 static char *enqueued = NULL;
612 if (svmode == HIST_DISCARD) {
613 afree(enqueued, APERM);
618 if (svmode == HIST_APPEND) {
621 } else if (enqueued) {
625 histsave(lnp, c, HIST_STORE, true);
629 if (svmode == HIST_FLUSH)
633 while (ccp > cmd && ccp[-1] == '\n')
635 strndupx(c, cmd, ccp - cmd, APERM);
637 if (svmode != HIST_APPEND) {
639 histptr >= history &&
641 #if !defined(MKSH_SMALL) && HAVE_PERSISTENT_HISTORY
651 #if HAVE_PERSISTENT_HISTORY
652 if (svmode == HIST_STORE && histfd != -1)
653 writehistfile(*lnp, c);
656 if (svmode == HIST_QUEUE || svmode == HIST_APPEND) {
667 nenq = strlen(enqueued);
669 enqueued = aresize(enqueued, nenq + 1 + ncmd + 1, APERM);
670 enqueued[nenq] = '\n';
671 memcpy(enqueued + nenq + 1, c, ncmd + 1);
678 if (++hp >= history + histsize) {
679 /* remove oldest command */
680 afree(*history, APERM);
681 for (hp = history; hp < history + histsize - 1; hp++)
689 * Write history data to a file nominated by HISTFILE;
690 * if HISTFILE is unset then history still happens, but
691 * the data is not written to a file. All copies of ksh
692 * looking at the file will maintain the same history.
693 * This is ksh behaviour.
695 * This stuff uses mmap()
697 * This stuff is so totally broken it must eventually be
698 * redesigned, without mmap, better checks, support for
699 * larger files, etc. and handle partially corrupted files
703 * Open a history file
706 * HMAGIC - just to check that we are dealing with the correct object
707 * Then follows a number of stored commands
709 * <command byte><command number(4 octets, big endian)><bytes><NUL>
715 #if HAVE_PERSISTENT_HISTORY
716 static const unsigned char sprinkle[2] = { HMAGIC1, HMAGIC2 };
719 hist_persist_back(int srcfd)
725 #define MKSH_HS_BUFSIZ 4096
727 if ((tot = lseek(srcfd, (off_t)0, SEEK_END)) < 0 ||
728 lseek(srcfd, (off_t)0, SEEK_SET) < 0 ||
729 lseek(histfd, (off_t)0, SEEK_SET) < 0)
732 if ((buf = malloc_osfunc(MKSH_HS_BUFSIZ)) == NULL)
737 if ((n = blocking_read(srcfd, (cp = buf),
738 MKSH_HS_BUFSIZ)) == -1) {
739 if (errno == EINTR) {
749 if ((w = write(histfd, cp, n)) != -1) {
754 if (errno == EINTR) {
762 if (ftruncate(histfd, tot)) {
771 hist_persist_init(void)
775 enum { hist_init_first, hist_init_retry, hist_use_it } hs;
777 if (((hname = str_val(global("HISTFILE"))) == NULL) || !*hname) {
781 strdupx(hname, hname, APERM);
782 hs = hist_init_first;
785 /* we have a file and are interactive */
786 if ((fd = binopen3(hname, O_RDWR | O_CREAT | O_APPEND, 0600)) < 0)
788 if ((histfd = savefd(fd)) < 0)
795 histfsize = lseek(histfd, (off_t)0, SEEK_END);
796 if (histfsize > MKSH_MAXHISTFSIZE) {
797 /* we ignore too large files but still append to them */
799 } else if (histfsize > 2) {
800 /* we have some data, check its validity */
801 base = (void *)mmap(NULL, (size_t)histfsize, PROT_READ,
802 MAP_FILE | MAP_PRIVATE, histfd, (off_t)0);
803 if (base == (unsigned char *)MAP_FAILED)
805 if (base[0] != HMAGIC1 || base[1] != HMAGIC2) {
806 munmap(caddr_cast(base), (size_t)histfsize);
809 /* load _all_ data */
810 lines = histload(hist_source, base + 2, (size_t)histfsize - 2);
811 munmap(caddr_cast(base), (size_t)histfsize);
812 /* check if the file needs to be truncated */
813 if (lines > histsize && histptr >= history) {
814 /* you're fucked up with the current code, trust me */
818 /* create temporary file */
819 nhname = shf_smprintf("%s.%d", hname, (int)procpid);
820 if ((fd = binopen3(nhname, O_RDWR | O_CREAT | O_TRUNC |
821 O_EXCL, 0600)) < 0) {
822 /* just don't truncate then, meh. */
824 goto hist_trunc_dont;
826 if (fstat(histfd, &sb) >= 0 &&
827 chown(nhname, sb.st_uid, sb.st_gid)) {
828 /* abort the truncation then, meh. */
829 goto hist_trunc_abort;
831 /* we definitively want some magic in that file */
832 if (write(fd, sprinkle, 2) != 2)
833 goto hist_trunc_abort;
834 /* and of course the entries */
836 while (hp < histptr) {
837 if (!writehistline(fd,
838 hist_source->line - (histptr - hp), *hp))
839 goto hist_trunc_abort;
842 /* now transfer back */
843 if (!hist_persist_back(fd)) {
848 /* remove temporary file */
852 /* use whatever is in the file now */
854 afree(nhname, ATEMP);
855 if (hs == hist_use_it)
856 goto hist_trunc_done;
859 } else if (histfsize != 0) {
860 /* negative or too small... */
862 /* ... or mmap failed or illegal */
864 /* nuke the bogus file then retry, at most once */
865 if (!unlink(hname) && hs != hist_init_retry) {
866 hs = hist_init_retry;
869 if (hs != hist_init_retry)
870 bi_errorf(Tf_cant_ss_s,
871 "unlink HISTFILE", hname, cstrerror(errno));
875 /* size 0, add magic to the history file */
876 if (write(histfd, sprinkle, 2) != 2) {
882 histfsize = lseek(histfd, (off_t)0, SEEK_END);
891 histsave(NULL, NULL, HIST_DISCARD, true);
893 if (Flag(FTALKING) == 0)
899 #if HAVE_PERSISTENT_HISTORY
904 #if HAVE_PERSISTENT_HISTORY
906 * load the history structure from the stored data
909 histload(Source *s, unsigned char *base, size_t bytes)
911 int lno = 0, lines = 0;
915 /* !bytes check as some systems (older FreeBSDs) have buggy memchr */
916 if (!bytes || (cp = memchr(base, COMMAND, bytes)) == NULL)
918 /* advance base pointer past COMMAND byte */
919 bytes -= ++cp - base;
921 /* if there is no full string left, don't bother with the rest */
922 if (bytes < 5 || (cp = memchr(base + 4, '\0', bytes - 4)) == NULL)
924 /* load the stored line number */
925 lno = ((base[0] & 0xFF) << 24) | ((base[1] & 0xFF) << 16) |
926 ((base[2] & 0xFF) << 8) | (base[3] & 0xFF);
927 /* store away the found line (@base[4]) */
929 if (histptr >= history && lno - 1 != s->line) {
933 if (lno >= s->line - (histptr - history) && lno <= s->line) {
934 hp = &histptr[lno - s->line];
936 strdupx(*hp, (char *)(base + 4), APERM);
940 histsave(&lno, (char *)(base + 4), HIST_NOTE, false);
942 /* advance base pointer past NUL */
943 bytes -= ++cp - base;
945 /* repeat until no more */
950 * write a command to the end of the history file
952 * This *MAY* seem easy but it's also necessary to check
953 * that the history file has not changed in size.
954 * If it has - then some other shell has written to it and
955 * we should (re)read those commands to update our history
958 writehistfile(int lno, const char *cmd)
962 unsigned char *base, *news;
965 sizenow = lseek(histfd, (off_t)0, SEEK_END);
966 if (sizenow < histfsize) {
967 /* the file has shrunk; trust it just appending the new data */
968 /* well, for now, anyway… since mksh strdups all into memory */
969 /* we can use a nicer approach some time later… */
972 /* ignore changes when the file is too large */
973 sizenow <= MKSH_MAXHISTFSIZE
975 /* the size has changed, we need to do read updates */
978 /* both sizenow and histfsize are <= MKSH_MAXHISTFSIZE */
979 bytes = (size_t)(sizenow - histfsize);
980 base = (void *)mmap(NULL, (size_t)sizenow, PROT_READ,
981 MAP_FILE | MAP_PRIVATE, histfd, (off_t)0);
982 if (base == (unsigned char *)MAP_FAILED)
984 news = base + (size_t)histfsize;
985 if (*news == COMMAND) {
987 histload(hist_source, news, bytes);
989 lno = hist_source->line;
992 munmap(caddr_cast(base), (size_t)sizenow);
996 if (cmd && !writehistline(histfd, lno, cmd)) {
1001 histfsize = lseek(histfd, (off_t)0, SEEK_END);
1002 mksh_unlkfd(histfd);
1006 writehistline(int fd, int lno, const char *cmd)
1009 unsigned char hdr[5];
1012 hdr[1] = (lno >> 24) & 0xFF;
1013 hdr[2] = (lno >> 16) & 0xFF;
1014 hdr[3] = (lno >> 8) & 0xFF;
1015 hdr[4] = lno & 0xFF;
1016 n = strlen(cmd) + 1;
1017 return (write(fd, hdr, 5) == 5 && write(fd, cmd, n) == n);
1024 mksh_unlkfd(histfd);
1025 (void)close(histfd);
1032 #if !HAVE_SYS_SIGNAME
1033 static const struct mksh_sigpair {
1034 const char * const name;
1036 } mksh_sigpairs[] = {
1037 #include "signames.inc"
1042 #if HAVE_SYS_SIGLIST
1043 #if !HAVE_SYS_SIGLIST_DECL
1044 extern const char * const sys_siglist[];
1053 #if !HAVE_SYS_SIGNAME
1054 const struct mksh_sigpair *pair;
1059 /* populate sigtraps based on sys_signame and sys_siglist */
1060 for (i = 1; i < ksh_NSIG; i++) {
1061 sigtraps[i].signal = i;
1062 #if HAVE_SYS_SIGNAME
1063 cs = sys_signame[i];
1065 pair = mksh_sigpairs;
1066 while ((pair->nr != i) && (pair->name != NULL))
1072 sigtraps[i].name = null;
1076 /* this is not optimal, what about SIGSIG1? */
1077 if (ksh_eq(cs[0], 'S', 's') &&
1078 ksh_eq(cs[1], 'I', 'i') &&
1079 ksh_eq(cs[2], 'G', 'g') &&
1081 /* skip leading "SIG" */
1084 strdupx(s, cs, APERM);
1085 sigtraps[i].name = s;
1086 while ((*s = ksh_toupper(*s)))
1088 /* check for reserved names */
1089 if (!strcmp(sigtraps[i].name, "EXIT") ||
1090 !strcmp(sigtraps[i].name, "ERR")) {
1092 internal_warningf(Tinvname, sigtraps[i].name,
1095 sigtraps[i].name = null;
1098 if (sigtraps[i].name == null)
1099 sigtraps[i].name = shf_smprintf(Tf_d, i);
1100 #if HAVE_SYS_SIGLIST
1101 sigtraps[i].mess = sys_siglist[i];
1102 #elif HAVE_STRSIGNAL
1103 sigtraps[i].mess = strsignal(i);
1105 sigtraps[i].mess = NULL;
1107 if ((sigtraps[i].mess == NULL) ||
1108 (sigtraps[i].mess[0] == '\0'))
1109 sigtraps[i].mess = shf_smprintf(Tf_sd,
1112 sigtraps[ksh_SIGEXIT].signal = ksh_SIGEXIT;
1113 sigtraps[ksh_SIGEXIT].name = "EXIT";
1114 sigtraps[ksh_SIGEXIT].mess = "Exit trap";
1115 sigtraps[ksh_SIGERR].signal = ksh_SIGERR;
1116 sigtraps[ksh_SIGERR].name = "ERR";
1117 sigtraps[ksh_SIGERR].mess = "Error handler";
1119 (void)sigemptyset(&Sigact_ign.sa_mask);
1120 Sigact_ign.sa_flags = 0; /* interruptible */
1121 Sigact_ign.sa_handler = SIG_IGN;
1123 sigtraps[SIGINT].flags |= TF_DFL_INTR | TF_TTY_INTR;
1124 sigtraps[SIGQUIT].flags |= TF_DFL_INTR | TF_TTY_INTR;
1125 /* SIGTERM is not fatal for interactive */
1126 sigtraps[SIGTERM].flags |= TF_DFL_INTR;
1127 sigtraps[SIGHUP].flags |= TF_FATAL;
1128 sigtraps[SIGCHLD].flags |= TF_SHELL_USES;
1130 /* these are always caught so we can clean up any temporary files. */
1131 setsig(&sigtraps[SIGINT], trapsig, SS_RESTORE_ORIG);
1132 setsig(&sigtraps[SIGQUIT], trapsig, SS_RESTORE_ORIG);
1133 setsig(&sigtraps[SIGTERM], trapsig, SS_RESTORE_ORIG);
1134 setsig(&sigtraps[SIGHUP], trapsig, SS_RESTORE_ORIG);
1137 static void alarm_catcher(int sig);
1142 sigtraps[SIGALRM].flags |= TF_SHELL_USES;
1143 setsig(&sigtraps[SIGALRM], alarm_catcher,
1144 SS_RESTORE_ORIG|SS_FORCE|SS_SHTRAP);
1149 alarm_catcher(int sig MKSH_A_UNUSED)
1151 /* this runs inside interrupt context, with errno saved */
1153 if (ksh_tmout_state == TMOUT_READING) {
1154 int left = alarm(0);
1157 ksh_tmout_state = TMOUT_LEAVING;
1165 gettrap(const char *cs, bool igncase, bool allsigs)
1171 /* signal number (1..ksh_NSIG) or 0? */
1173 if (ctype(*cs, C_DIGIT))
1174 return ((getn(cs, &i) && 0 <= i && i < ksh_NSIG) ?
1175 (&sigtraps[i]) : NULL);
1177 /* do a lookup by name then */
1179 /* this breaks SIGSIG1, but we do that above anyway */
1180 if (ksh_eq(cs[0], 'S', 's') &&
1181 ksh_eq(cs[1], 'I', 'i') &&
1182 ksh_eq(cs[2], 'G', 'g') &&
1184 /* skip leading "SIG" */
1190 strdupx(as, cs, ATEMP);
1192 while ((*s = ksh_toupper(*s)))
1197 /* this is idiotic, we really want a hashtable here */
1202 if (!strcmp(p->name, cs))
1210 if (p->signal == ksh_SIGEXIT || p->signal == ksh_SIGERR) {
1220 * trap signal handler
1225 Trap *p = &sigtraps[i];
1229 if (p->flags & TF_DFL_INTR)
1231 if ((p->flags & TF_FATAL) && !p->trap) {
1241 * called when we want to allow the user to ^C out of something - won't
1242 * work if user has trapped SIGINT.
1248 runtraps(TF_DFL_INTR|TF_FATAL);
1252 * called after EINTR to check if a signal with normally causes process
1253 * termination has been received.
1256 fatal_trap_check(void)
1259 int i = ksh_NSIG + 1;
1261 /* todo: should check if signal is fatal, not the TF_DFL_INTR flag */
1263 if (p->set && (p->flags & (TF_DFL_INTR|TF_FATAL)))
1264 /* return value is used as an exit code */
1265 return (ksh_sigmask(p->signal));
1272 * Returns the signal number of any pending traps: ie, a signal which has
1273 * occurred for which a trap has been set or for which the TF_DFL_INTR flag
1280 int i = ksh_NSIG + 1;
1283 if (p->set && ((p->trap && p->trap[0]) ||
1284 ((p->flags & (TF_DFL_INTR|TF_FATAL)) && !p->trap)))
1292 * run any pending traps. If intr is set, only run traps that
1293 * can interrupt commands.
1299 int i = ksh_NSIG + 1;
1301 if (ksh_tmout_state == TMOUT_LEAVING) {
1302 ksh_tmout_state = TMOUT_EXECUTING;
1303 warningf(false, "timed out waiting for input");
1307 * XXX: this means the alarm will have no effect if a trap
1308 * is caught after the alarm() was started...not good.
1310 ksh_tmout_state = TMOUT_EXECUTING;
1313 if (flag & TF_DFL_INTR)
1315 if (flag & TF_FATAL)
1319 if (p->set && (!flag ||
1320 ((p->flags & flag) && p->trap == NULL)))
1325 runtrap(NULL, true);
1329 runtrap(Trap *p, bool is_last)
1331 int old_changed = 0, i;
1335 /* just clean up, see runtraps() above */
1340 if (trapstr == NULL) {
1342 if (p->flags & (TF_FATAL | TF_DFL_INTR)) {
1343 exstat = (int)(128U + (unsigned)i);
1344 if ((unsigned)exstat > 255U)
1348 if (p->flags & TF_FATAL)
1350 /* e.g. SIGINT, SIGQUIT, SIGTERM, etc. */
1351 if (p->flags & TF_DFL_INTR)
1355 if (trapstr[0] == '\0')
1358 if (i == ksh_SIGEXIT || i == ksh_SIGERR) {
1359 /* avoid recursion on these */
1360 old_changed = p->flags & TF_CHANGED;
1361 p->flags &= ~TF_CHANGED;
1364 if (trap_exstat == -1)
1365 trap_exstat = exstat & 0xFF;
1367 * Note: trapstr is fully parsed before anything is executed, thus
1368 * no problem with afree(p->trap) in settrap() while still in use.
1370 command(trapstr, current_lineno);
1371 if (i == ksh_SIGEXIT || i == ksh_SIGERR) {
1372 if (p->flags & TF_CHANGED)
1373 /* don't clear TF_CHANGED */
1374 afree(trapstr, APERM);
1377 p->flags |= old_changed;
1381 /* we're the last trap of a sequence executed */
1382 if (is_last && trap_exstat != -1) {
1383 exstat = trap_exstat;
1388 /* clear pending traps and reset user's trap handlers; used after fork(2) */
1393 int i = ksh_NSIG + 1;
1401 if ((p->flags & TF_USER_SET) && (p->trap && p->trap[0]))
1407 /* restore signals just before an exec(2) */
1412 int i = ksh_NSIG + 1;
1415 if (p->flags & (TF_EXEC_IGN|TF_EXEC_DFL))
1416 setsig(p, (p->flags & TF_EXEC_IGN) ? SIG_IGN : SIG_DFL,
1417 SS_RESTORE_CURR|SS_FORCE);
1423 settrap(Trap *p, const char *s)
1427 afree(p->trap, APERM);
1428 /* handles s == NULL */
1429 strdupx(p->trap, s, APERM);
1430 p->flags |= TF_CHANGED;
1431 f = !s ? SIG_DFL : s[0] ? trapsig : SIG_IGN;
1433 p->flags |= TF_USER_SET;
1434 if ((p->flags & (TF_DFL_INTR|TF_FATAL)) && f == SIG_DFL)
1436 else if (p->flags & TF_SHELL_USES) {
1437 if (!(p->flags & TF_ORIG_IGN) || Flag(FTALKING)) {
1438 /* do what user wants at exec time */
1439 p->flags &= ~(TF_EXEC_IGN|TF_EXEC_DFL);
1441 p->flags |= TF_EXEC_IGN;
1443 p->flags |= TF_EXEC_DFL;
1447 * assumes handler already set to what shell wants it
1448 * (normally trapsig, but could be j_sigchld() or SIG_IGN)
1453 /* todo: should we let user know signal is ignored? how? */
1454 setsig(p, f, SS_RESTORE_CURR|SS_USER);
1458 * called by c_print() when writing to a co-process to ensure
1459 * SIGPIPE won't kill shell (unless user catches it and exits)
1464 bool restore_dfl = false;
1465 Trap *p = &sigtraps[SIGPIPE];
1467 if (!(p->flags & (TF_ORIG_IGN|TF_ORIG_DFL))) {
1468 setsig(p, SIG_IGN, SS_RESTORE_CURR);
1469 if (p->flags & TF_ORIG_DFL)
1471 } else if (p->cursig == SIG_DFL) {
1472 setsig(p, SIG_IGN, SS_RESTORE_CURR);
1473 /* restore to SIG_DFL */
1476 return (restore_dfl);
1479 /* called by c_print() to undo whatever block_pipe() did */
1483 setsig(&sigtraps[SIGPIPE], SIG_DFL, SS_RESTORE_CURR);
1487 * Set action for a signal. Action may not be set if original
1488 * action was SIG_IGN, depending on the value of flags and FTALKING.
1491 setsig(Trap *p, sig_t f, int flags)
1493 struct sigaction sigact;
1495 if (p->signal == ksh_SIGEXIT || p->signal == ksh_SIGERR)
1498 memset(&sigact, 0, sizeof(sigact));
1501 * First time setting this signal? If so, get and note the current
1504 if (!(p->flags & (TF_ORIG_IGN|TF_ORIG_DFL))) {
1505 sigaction(p->signal, &Sigact_ign, &sigact);
1506 p->flags |= sigact.sa_handler == SIG_IGN ?
1507 TF_ORIG_IGN : TF_ORIG_DFL;
1508 p->cursig = SIG_IGN;
1512 * Generally, an ignored signal stays ignored, except if
1513 * - the user of an interactive shell wants to change it
1514 * - the shell wants for force a change
1516 if ((p->flags & TF_ORIG_IGN) && !(flags & SS_FORCE) &&
1517 (!(flags & SS_USER) || !Flag(FTALKING)))
1520 setexecsig(p, flags & SS_RESTORE_MASK);
1523 * This is here 'cause there should be a way of clearing
1524 * shtraps, but don't know if this is a sane way of doing
1525 * it. At the moment, all users of shtrap are lifetime
1526 * users (SIGALRM, SIGCHLD, SIGWINCH).
1528 if (!(flags & SS_USER))
1529 p->shtrap = (sig_t)NULL;
1530 if (flags & SS_SHTRAP) {
1535 if (p->cursig != f) {
1537 (void)sigemptyset(&sigact.sa_mask);
1539 sigact.sa_flags = 0;
1540 sigact.sa_handler = f;
1541 sigaction(p->signal, &sigact, NULL);
1547 /* control what signal is set to before an exec() */
1549 setexecsig(Trap *p, int restore)
1552 if (!(p->flags & (TF_ORIG_IGN|TF_ORIG_DFL)))
1553 internal_errorf("setexecsig: unset signal %d(%s)",
1554 p->signal, p->name);
1556 /* restore original value for exec'd kids */
1557 p->flags &= ~(TF_EXEC_IGN|TF_EXEC_DFL);
1558 switch (restore & SS_RESTORE_MASK) {
1559 case SS_RESTORE_CURR:
1560 /* leave things as they currently are */
1562 case SS_RESTORE_ORIG:
1563 p->flags |= p->flags & TF_ORIG_IGN ? TF_EXEC_IGN : TF_EXEC_DFL;
1565 case SS_RESTORE_DFL:
1566 p->flags |= TF_EXEC_DFL;
1568 case SS_RESTORE_IGN:
1569 p->flags |= TF_EXEC_IGN;
1574 #if HAVE_PERSISTENT_HISTORY || defined(DF)
1576 * File descriptor locking and unlocking functions.
1577 * Could use some error handling, but hey, this is only
1578 * advisory locking anyway, will often not work over NFS,
1579 * and you are SOL if this fails...
1585 #if defined(__OpenBSD__)
1586 /* flock is not interrupted by signals */
1587 (void)flock(fd, LOCK_EX);
1593 rv = flock(fd, LOCK_EX);
1594 } while (rv == 1 && errno == EINTR);
1595 #elif HAVE_LOCK_FCNTL
1599 memset(&lks, 0, sizeof(lks));
1600 lks.l_type = F_WRLCK;
1602 rv = fcntl(fd, F_SETLKW, &lks);
1603 } while (rv == 1 && errno == EINTR);
1607 /* designed to not define mksh_unlkfd if none triggered */
1612 (void)flock(fd, LOCK_UN);
1614 #elif HAVE_LOCK_FCNTL
1620 memset(&lks, 0, sizeof(lks));
1621 lks.l_type = F_UNLCK;
1622 (void)fcntl(fd, F_SETLKW, &lks);