1 /* $OpenBSD: lex.c,v 1.49 2013/12/17 16:37:06 deraadt Exp $ */
4 * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
5 * 2011, 2012, 2013, 2014, 2015
6 * Thorsten Glaser <tg@mirbsd.org>
8 * Provided that these terms and disclaimer and all copyright notices
9 * are retained or reproduced in an accompanying document, permission
10 * is granted to deal in this work without restriction, including un-
11 * limited rights to use, publicly perform, distribute, sell, modify,
12 * merge, give away, or sublicence.
14 * This work is provided "AS IS" and WITHOUT WARRANTY of any kind, to
15 * the utmost extent permitted by applicable law, neither express nor
16 * implied; without malicious intent or gross negligence. In no event
17 * may a licensor, author or contributor be held liable for indirect,
18 * direct, other damage, loss, or other issues arising in any way out
19 * of dealing in the work, even if advised of the possibility of such
20 * damage or existence of a defect, except proven that it results out
21 * of said person's immediate fault when using the work as intended.
26 __RCSID("$MirOS: src/bin/mksh/lex.c,v 1.193.2.5 2015/04/19 19:18:19 tg Exp $");
29 * states while lexing word
31 #define SBASE 0 /* outside any lexical constructs */
32 #define SWORD 1 /* implicit quoting for substitute() */
33 #define SLETPAREN 2 /* inside (( )), implicit quoting */
34 #define SSQUOTE 3 /* inside '' */
35 #define SDQUOTE 4 /* inside "" */
36 #define SEQUOTE 5 /* inside $'' */
37 #define SBRACE 6 /* inside ${} */
38 #define SQBRACE 7 /* inside "${}" */
39 #define SBQUOTE 8 /* inside `` */
40 #define SASPAREN 9 /* inside $(( )) */
41 #define SHEREDELIM 10 /* parsing <<,<<-,<<< delimiter */
42 #define SHEREDQUOTE 11 /* parsing " in <<,<<-,<<< delimiter */
43 #define SPATTERN 12 /* parsing *(...|...) pattern (*+?@!) */
44 #define SADELIM 13 /* like SBASE, looking for delimiter */
45 #define STBRACEKORN 14 /* parsing ${...[#%]...} !FSH */
46 #define STBRACEBOURNE 15 /* parsing ${...[#%]...} FSH */
47 #define SINVALID 255 /* invalid state */
49 struct sretrace_info {
50 struct sretrace_info *next;
56 * Structure to keep track of the lexing state and the various pieces of info
57 * needed for each particular state.
59 typedef struct lex_state {
61 /* point to the next state block */
62 struct lex_state *base;
63 /* marks start of state output in output string */
65 /* SBQUOTE: true if in double quotes: "`...`" */
66 /* SEQUOTE: got NUL, ignore rest of string */
68 /* SADELIM information */
70 /* character to search for */
71 unsigned char delimiter;
72 /* max. number of delimiters */
76 /* count open parentheses */
78 /* type of this state */
81 #define ls_base u.base
82 #define ls_start u.start
83 #define ls_bool u.abool
84 #define ls_adelim u.adelim
91 static void readhere(struct ioword *);
92 static void ungetsc(int);
93 static void ungetsc_i(int);
94 static int getsc_uu(void);
95 static void getsc_line(Source *);
96 static int getsc_bn(void);
97 static int s_get(void);
98 static void s_put(int);
99 static char *get_brace_var(XString *, char *);
100 static bool arraysub(char **);
101 static void gethere(bool);
102 static Lex_state *push_state_i(State_info *, Lex_state *);
103 static Lex_state *pop_state_i(State_info *, Lex_state *);
105 static int backslash_skip;
106 static int ignore_backslash_newline;
108 /* optimised getsc_bn() */
109 #define o_getsc() (*source->str != '\0' && *source->str != '\\' && \
110 !backslash_skip ? *source->str++ : getsc_bn())
111 /* optimised getsc_uu() */
112 #define o_getsc_u() ((*source->str != '\0') ? *source->str++ : getsc_uu())
115 #define o_getsc_r(carg) { \
117 struct sretrace_info *rp = retrace_info; \
120 Xcheck(rp->xs, rp->xp); \
128 #if defined(MKSH_SMALL) && !defined(MKSH_SMALL_BUT_FAST)
129 static int getsc(void);
134 o_getsc_r(o_getsc());
137 static int getsc_r(int);
145 #define getsc() getsc_r(o_getsc())
148 #define STATE_BSIZE 8
150 #define PUSH_STATE(s) do { \
151 if (++statep == state_info.end) \
152 statep = push_state_i(&state_info, statep); \
153 state = statep->type = (s); \
154 } while (/* CONSTCOND */ 0)
156 #define POP_STATE() do { \
157 if (--statep == state_info.base) \
158 statep = pop_state_i(&state_info, statep); \
159 state = statep->type; \
160 } while (/* CONSTCOND */ 0)
162 #define PUSH_SRETRACE(s) do { \
163 struct sretrace_info *ri; \
166 statep->ls_start = Xsavepos(ws, wp); \
167 ri = alloc(sizeof(struct sretrace_info), ATEMP); \
168 Xinit(ri->xs, ri->xp, 64, ATEMP); \
169 ri->next = retrace_info; \
171 } while (/* CONSTCOND */ 0)
173 #define POP_SRETRACE() do { \
174 wp = Xrestpos(ws, wp, statep->ls_start); \
175 *retrace_info->xp = '\0'; \
176 sp = Xstring(retrace_info->xs, retrace_info->xp); \
177 dp = (void *)retrace_info; \
178 retrace_info = retrace_info->next; \
181 } while (/* CONSTCOND */ 0)
186 * tokens are not regular expressions, they are LL(1).
187 * for example, "${var:-${PWD}}", and "$(size $(whence ksh))".
188 * hence the state stack. Note "$(...)" are now parsed recursively.
194 Lex_state states[STATE_BSIZE], *statep, *s2, *base;
195 State_info state_info;
198 XString ws; /* expandable output word */
199 char *wp; /* output word pointer */
203 states[0].type = SINVALID;
204 states[0].ls_base = NULL;
206 state_info.base = states;
207 state_info.end = &state_info.base[STATE_BSIZE];
209 Xinit(ws, wp, 64, ATEMP);
212 ignore_backslash_newline = 0;
216 else if (cf & LETEXPR) {
217 /* enclose arguments in (double) quotes */
223 state = (cf & HEREDELIM) ? SHEREDELIM : SBASE;
224 while ((c = getsc()) == ' ' || c == '\t')
227 ignore_backslash_newline++;
228 while ((c = getsc()) != '\0' && c != '\n')
230 ignore_backslash_newline--;
234 if (source->flags & SF_ALIAS) {
235 /* trailing ' ' in alias definition */
236 source->flags &= ~SF_ALIAS;
240 /* Initial state: one of SWORD SLETPAREN SHEREDELIM SBASE */
241 statep->type = state;
243 /* check for here string */
244 if (state == SHEREDELIM) {
248 while ((c = getsc()) == ' ' || c == '\t')
257 /* collect non-special or quoted characters to form word */
258 while (!((c = getsc()) == 0 ||
259 ((state == SBASE || state == SHEREDELIM) && ctype(c, C_LEX1)))) {
260 if (state == SBASE &&
261 subshell_nesting_type == /*{*/ '}' &&
263 /* possibly end ${ :;} */
273 else if (statep->nparen == 0 && (c == /*{*/ '}' ||
274 c == (int)statep->ls_adelim.delimiter)) {
277 if (c == /*{*/ '}' || --statep->ls_adelim.num == 0)
285 if (c == '[' && (cf & (VARASN|ARRAYVAR))) {
288 if (is_wdvarname(Xstring(ws, wp), false)) {
291 if (arraysub(&tmp)) {
294 for (p = tmp; *p; ) {
317 Sbase1: /* includes *(...|...) pattern (*+?@!) */
318 if (c == '*' || c == '@' || c == '+' || c == '?' ||
321 if (c2 == '(' /*)*/ ) {
324 PUSH_STATE(SPATTERN);
330 Sbase2: /* doesn't include *(...|...) pattern (*+?@!) */
335 /* trailing \ is lost */
341 open_ssquote_unless_heredoc:
345 ignore_backslash_newline++;
355 * processing of dollar sign belongs into
356 * Subst, except for those which can open
357 * a string: $'…' and $"…"
393 /* trailing \ is lost */
405 if (c == '(') /*)*/ {
407 if (c == '(') /*)*/ {
409 PUSH_SRETRACE(SASPAREN);
411 *retrace_info->xp++ = '(';
424 } else if (c == '{') /*}*/ {
425 if ((c = getsc()) == '|') {
432 } else if (ctype(c, C_IFSWS)) {
435 * "command" substitution
443 wp = get_brace_var(&ws, wp);
445 /* allow :# and :% (ksh88 compat) */
457 statep->ls_adelim.delimiter = ':';
458 statep->ls_adelim.num = 1;
461 } else if (ksh_isdigit(c) ||
462 c == '('/*)*/ || c == ' ' ||
465 /* substring subst. */
473 statep->ls_adelim.delimiter = ':';
474 statep->ls_adelim.num = 2;
478 } else if (c == '/') {
481 if ((c = getsc()) == '/') {
488 statep->ls_adelim.delimiter = '/';
489 statep->ls_adelim.num = 1;
494 * If this is a trim operation,
495 * treat (,|,) specially in STBRACE.
497 if (ctype(c, C_SUBOP2)) {
500 PUSH_STATE(STBRACEBOURNE);
502 PUSH_STATE(STBRACEKORN);
505 if (state == SDQUOTE ||
511 } else if (ksh_isalphx(c)) {
518 } while (ksh_isalnux(c));
523 } else if (ctype(c, C_VAR1 | C_DIGIT)) {
542 * Need to know if we are inside double quotes
543 * since sh/AT&T-ksh translate the \" to " in
545 * This is not done in POSIX mode (section
546 * 3.2.3, Double Quotes: "The backquote shall
547 * retain its special meaning introducing the
548 * other form of command substitution (see
549 * 3.6.3). The portion of the quoted string
550 * from the initial backquote and the
551 * characters up to the next backquote that
552 * is not preceded by a backslash (having
553 * escape characters removed) defines that
554 * command whose output replaces `...` when
555 * the word is expanded."
556 * Section 3.6.3, Command Substitution:
557 * "Within the backquoted style of command
558 * substitution, backslash shall retain its
559 * literal meaning, except when followed by
562 statep->ls_bool = false;
564 base = state_info.base;
565 while (/* CONSTCOND */ 1) {
566 for (; s2 != base; s2--) {
567 if (s2->type == SDQUOTE) {
568 statep->ls_bool = true;
574 if (!(s2 = s2->ls_base))
576 base = s2-- - STATE_BSIZE;
597 ignore_backslash_newline--;
598 } else if (c == '\\') {
599 if ((c2 = unbksl(true, s_get, s_put)) == -1)
602 statep->ls_bool = true;
603 if (!statep->ls_bool) {
606 if ((unsigned int)c2 < 0x100) {
610 cz = utf_wctomb(ts, c2 - 0x100);
612 for (cz = 0; ts[cz]; ++cz) {
618 } else if (!statep->ls_bool) {
627 if ((cf & HEREDOC) || state == SQBRACE)
630 ignore_backslash_newline--;
651 if (statep->nparen == 1) {
655 if ((c2 = getsc()) == /*(*/ ')') {
658 memcpy(wp, sp + 1, cz);
668 * mismatched parenthesis -
669 * assume we were really
670 * parsing a $(...) expression
683 /* reuse existing state machine */
689 * perform POSIX "quote removal" if the back-
690 * slash is "special", i.e. same cases as the
691 * {case '\\':} in Subst: plus closing brace;
692 * in mksh code "quote removal" on '\c' means
693 * write QCHAR+c, otherwise CHAR+\+CHAR+c are
694 * emitted (in heredocquote:)
696 if ((c = getsc()) == '"' || c == '\\' ||
697 c == '$' || c == '`' || c == /*{*/'}')
705 goto open_ssquote_unless_heredoc;
712 goto subst_dollar_ex;
715 else if (c != /*{*/ '}')
722 /* Same as SBASE, except (,|,) treated specially */
730 PUSH_STATE(SPATTERN);
731 } else /* FALLTHROUGH */
733 if (c == /*{*/ '}') {
745 } else if (c == '\\') {
746 switch (c = getsc()) {
748 /* trailing \ is lost */
755 if (statep->ls_bool) {
773 /* LETEXPR: (( ... )) */
775 if (c == /*(*/ ')') {
776 if (statep->nparen > 0)
778 else if ((c2 = getsc()) == /*(*/ ')') {
787 * mismatched parenthesis -
788 * assume we were really
789 * parsing a (...) expression
792 sp = Xstring(ws, wp);
793 dp = wdstrip(sp, WDS_KEEPQ);
794 s = pushs(SREREAD, source->areap);
795 s->start = s->str = s->u.freeme = dp;
802 * parentheses inside quotes and
803 * backslashes are lost, but AT&T ksh
804 * doesn't count them either
809 /* <<, <<-, <<< delimiter */
812 * here delimiters need a special case since
813 * $ and `...` are not to be treated specially
818 /* trailing \ is lost */
824 goto open_ssquote_unless_heredoc;
826 if ((c2 = getsc()) == '\'') {
829 ignore_backslash_newline++;
831 statep->ls_bool = false;
833 } else if (c2 == '"') {
836 PUSH_SRETRACE(SHEREDQUOTE);
847 /* " in <<, <<-, <<< delimiter */
853 /* remove the trailing double quote */
855 /* store the quoted string */
857 XcheckN(ws, wp, (dp - sp) * 2);
859 while ((c = *dp++)) {
861 switch ((c = *dp++)) {
878 state = statep->type = SHEREDELIM;
881 /* in *(...|...) pattern (*+?@!) */
883 if (c == /*(*/ ')') {
886 } else if (c == '|') {
888 } else if (c == '(') {
892 PUSH_STATE(SPATTERN);
900 if (statep != &states[1])
901 /* XXX figure out what is missing */
902 yyerror("no closing quote\n");
904 /* This done to avoid tests for SHEREDELIM wherever SBASE tested */
905 if (state == SHEREDELIM)
908 dp = Xstring(ws, wp);
909 if (state == SBASE && (
910 #ifndef MKSH_LEGACY_MODE
911 (c == '&' && !Flag(FSH) && !Flag(FPOSIX)) ||
913 c == '<' || c == '>')) {
914 struct ioword *iop = alloc(sizeof(struct ioword), ATEMP);
916 if (Xlength(ws, wp) == 0)
917 iop->unit = c == '<' ? 0 : 1;
918 else for (iop->unit = 0, c2 = 0; c2 < Xlength(ws, wp); c2 += 2) {
921 if (!ksh_isdigit(dp[c2 + 1]))
923 iop->unit = (iop->unit * 10) + dp[c2 + 1] - '0';
924 if (iop->unit >= FDBASE)
929 if ((c2 = getsc()) != '>') {
934 iop->ioflag = IOBASH;
939 /* <<, >>, <> are ok, >< is not */
940 if (c == c2 || (c == '<' && c2 == '>')) {
941 iop->ioflag |= c == c2 ?
942 (c == '>' ? IOCAT : IOHERE) : IORDWR;
943 if (iop->ioflag == IOHERE) {
944 if ((c2 = getsc()) == '-') {
945 iop->ioflag |= IOSKIP;
947 } else if (c2 == '<')
948 iop->ioflag |= IOHERESTR;
951 iop->ioflag |= IONDELIM;
953 } else if (c2 == '&')
954 iop->ioflag |= IODUP | (c == '<' ? IORDUP : 0);
956 iop->ioflag |= c == '>' ? IOWRITE : IOREAD;
957 if (c == '>' && c2 == '|')
958 iop->ioflag |= IOCLOB;
974 if (wp == dp && state == SBASE) {
977 /* no word, process LEX1 character */
978 if ((c == '|') || (c == '&') || (c == ';') || (c == '('/*)*/)) {
979 if ((c2 = getsc()) == c)
980 c = (c == ';') ? BREAK :
982 (c == '&') ? LOGAND :
983 /* c == '(' ) */ MDPAREN;
984 else if (c == '|' && c2 == '&')
986 else if (c == ';' && c2 == '|')
988 else if (c == ';' && c2 == '&')
994 if ((c2 = getsc()) == '&')
1000 } else if (c == '\n') {
1004 } else if (c == '\0')
1005 /* need here strings at EOF */
1010 /* terminate word */
1012 yylval.cp = Xclose(ws, wp);
1013 if (state == SWORD || state == SLETPAREN
1017 /* unget terminator */
1021 * note: the alias-vs-function code below depends on several
1022 * interna: starting from here, source->str is not modified;
1023 * the way getsc() and ungetsc() operate; etc.
1026 /* copy word to unprefixed string ident */
1029 if ((cf & HEREDELIM) && (sp[1] == '<')) {
1031 switch ((c = *sp++)) {
1037 goto herestringloop;
1044 while ((dp - ident) < IDENT && (c = *sp++) == CHAR)
1047 /* word is not unquoted */
1049 /* make sure the ident array stays NUL padded */
1050 memset(dp, 0, (ident + IDENT) - dp + 1);
1052 if (!(cf & (KEYWORD | ALIAS)))
1055 if (*ident != '\0') {
1057 uint32_t h = hash(ident);
1059 if ((cf & KEYWORD) && (p = ktsearch(&keywords, ident, h)) &&
1060 (!(cf & ESACONLY) || p->val.i == ESAC ||
1061 p->val.i == /*{*/ '}')) {
1062 afree(yylval.cp, ATEMP);
1065 if ((cf & ALIAS) && (p = ktsearch(&aliases, ident, h)) &&
1066 (p->flag & ISSET)) {
1068 * this still points to the same character as the
1069 * ungetsc'd terminator from above
1071 const char *cp = source->str;
1073 /* prefer POSIX but not Korn functions over aliases */
1074 while (*cp == ' ' || *cp == '\t')
1076 * this is like getsc() without skipping
1077 * over Source boundaries (including not
1078 * parsing ungetsc'd characters that got
1079 * pushed into an SREREAD) which is what
1080 * we want here anyway: find out whether
1081 * the alias name is followed by a POSIX
1082 * function definition
1085 /* prefer functions over aliases */
1086 if (cp[0] != '(' || cp[1] != ')') {
1089 while (s && (s->flags & SF_HASALIAS))
1094 /* push alias expansion */
1095 s = pushs(SALIAS, source->areap);
1096 s->start = s->str = p->val.s;
1098 s->flags |= SF_HASALIAS;
1100 if (source->type == SEOF) {
1101 /* prevent infinite recursion at EOS */
1103 source->flags |= SF_HASALIAS;
1106 afree(yylval.cp, ATEMP);
1110 } else if (cf & ALIAS) {
1111 /* retain typeset et al. even when quoted */
1112 if (assign_command((dp = wdstrip(yylval.cp, 0))))
1113 strlcpy(ident, dp, sizeof(ident));
1125 for (p = heres; p < herep; p++)
1126 if (iseof && !((*p)->ioflag & IOHERESTR))
1127 /* only here strings at EOF */
1135 * read "<<word" text into temp file
1139 readhere(struct ioword *iop)
1142 const char *eof, *eofp;
1147 if (iop->ioflag & IOHERESTR) {
1148 /* process the here string */
1149 iop->heredoc = xp = evalstr(iop->delim, DOBLANK);
1150 xpos = strlen(xp) - 1;
1151 memmove(xp, xp + 1, xpos);
1156 eof = iop->ioflag & IONDELIM ? "<<" : evalstr(iop->delim, 0);
1158 if (!(iop->ioflag & IOEVAL))
1159 ignore_backslash_newline++;
1161 Xinit(xs, xp, 256, ATEMP);
1164 /* beginning of line */
1166 xpos = Xsavepos(xs, xp);
1167 if (iop->ioflag & IOSKIP) {
1168 /* skip over leading tabs */
1169 while ((c = getsc()) == '\t')
1171 goto heredoc_parse_char;
1176 /* compare with here document marker */
1178 /* end of here document marker, what to do? */
1181 if (!subshell_nesting_type)
1183 * not allowed outside $(...) or (...)
1187 /* allow $(...) or (...) to close here */
1192 * Allow EOF here to commands without trailing
1193 * newlines (mksh -c '...') will work as well.
1196 /* Newline terminates here document marker */
1197 goto heredoc_found_terminator;
1199 } else if (c == *eofp++)
1200 /* store; then read and compare next character */
1201 goto heredoc_store_and_loop;
1202 /* nope, mismatch; read until end of line */
1205 /* oops, reached EOF */
1206 yyerror("%s '%s' unclosed\n", "here document", eof);
1207 /* store character */
1210 /* read next character */
1213 /* we read a newline as last character */
1214 heredoc_store_and_loop:
1215 /* store character */
1219 goto heredoc_read_line;
1220 goto heredoc_read_char;
1222 heredoc_found_terminator:
1223 /* jump back to saved beginning of line */
1224 xp = Xrestpos(xs, xp, xpos);
1225 /* terminate, close and store */
1227 iop->heredoc = Xclose(xs, xp);
1229 if (!(iop->ioflag & IOEVAL))
1230 ignore_backslash_newline--;
1234 yyerror(const char *fmt, ...)
1238 /* pop aliases and re-reads */
1239 while (source->type == SALIAS || source->type == SREREAD)
1240 source = source->next;
1241 /* zap pending input */
1246 shf_vfprintf(shl_out, fmt, va);
1252 * input for yylex with alias expansion
1256 pushs(int type, Area *areap)
1260 s = alloc(sizeof(Source), areap);
1261 memset(s, 0, sizeof(Source));
1265 if (type == SFILE || type == SSTDIN)
1266 XinitN(s->xs, 256, s->areap);
1276 while ((c = *s->str++) == 0) {
1277 /* return 0 for EOF by default */
1293 case SSTRINGCMDLINE:
1297 s->start = s->str = *s->u.strv++;
1302 if (*s->u.strv == NULL) {
1303 s->start = s->str = "\n";
1306 s->start = s->str = " ";
1312 if (s->flags & SF_ALIASEND) {
1313 /* pass on an unused SF_ALIAS flag */
1315 source->flags |= s->flags & SF_ALIAS;
1317 } else if (*s->u.tblp->val.s &&
1318 (c = strnul(s->u.tblp->val.s)[-1], ksh_isspace(c))) {
1319 /* pop source stack */
1320 source = s = s->next;
1322 * Note that this alias ended with a
1323 * space, enabling alias expansion on
1324 * the following word.
1326 s->flags |= SF_ALIAS;
1329 * At this point, we need to keep the current
1330 * alias in the source list so recursive
1331 * aliases can be detected and we also need to
1332 * return the next character. Do this by
1333 * temporarily popping the alias to get the
1334 * next character and then put it back in the
1335 * source list with the SF_ALIASEND flag set.
1337 /* pop source stack */
1339 source->flags |= s->flags & SF_ALIAS;
1342 s->flags |= SF_ALIASEND;
1343 s->ugbuf[0] = c; s->ugbuf[1] = '\0';
1344 s->start = s->str = s->ugbuf;
1349 /* avoid reading EOF twice */
1357 if (s->start != s->ugbuf)
1359 afree(s->u.freeme, ATEMP);
1360 source = s = s->next;
1363 if (s->str == NULL) {
1365 s->start = s->str = null;
1368 if (s->flags & SF_ECHO) {
1369 shf_puts(s->str, shl_out);
1377 getsc_line(Source *s)
1379 char *xp = Xstring(s->xs, xp), *cp;
1380 bool interactive = Flag(FTALKING) && s->type == SSTDIN;
1381 bool have_tty = tobool(interactive && (s->flags & SF_TTY));
1383 /* Done here to ensure nothing odd happens when a timeout occurs */
1384 XcheckN(s->xs, xp, LINE);
1386 s->start = s->str = xp;
1388 if (have_tty && ksh_tmout) {
1389 ksh_tmout_state = TMOUT_READING;
1394 #ifndef MKSH_NO_CMDLINE_EDITING
1399 Flag(FEMACS) || Flag(FGMACS))) {
1416 while (/* CONSTCOND */ 1) {
1417 char *p = shf_getse(xp, Xnleft(s->xs, xp), s->u.shf);
1419 if (!p && shf_error(s->u.shf) &&
1420 shf_errno(s->u.shf) == EINTR) {
1421 shf_clearerr(s->u.shf);
1426 if (!p || (xp = p, xp[-1] == '\n'))
1428 /* double buffer size */
1429 /* move past NUL so doubling works... */
1431 XcheckN(s->xs, xp, Xlength(s->xs, xp));
1432 /* ...and move back again */
1436 * flush any unwanted input so other programs/builtins
1437 * can read it. Not very optimal, but less error prone
1438 * than flushing else where, dealing with redirections,
1440 * TODO: reduce size of shf buffer (~128?) if SSTDIN
1442 if (s->type == SSTDIN)
1443 shf_flush(s->u.shf);
1446 * XXX: temporary kludge to restore source after a
1447 * trap may have been executed.
1450 if (have_tty && ksh_tmout) {
1451 ksh_tmout_state = TMOUT_EXECUTING;
1454 cp = Xstring(s->xs, xp);
1456 s->start = s->str = cp;
1457 strip_nuls(Xstring(s->xs, xp), Xlength(s->xs, xp));
1458 /* Note: if input is all nulls, this is not eof */
1459 if (Xlength(s->xs, xp) == 0) {
1461 if (s->type == SFILE)
1462 shf_fdclose(s->u.shf);
1464 } else if (interactive && *s->str &&
1465 (cur_prompt != PS1 || !ctype(*s->str, C_IFS | C_IFSWS))) {
1466 histsave(&s->line, s->str, true, true);
1467 #if !defined(MKSH_SMALL) && HAVE_PERSISTENT_HISTORY
1468 } else if (interactive && cur_prompt == PS1) {
1469 cp = Xstring(s->xs, xp);
1470 while (*cp && ctype(*cp, C_IFSWS))
1477 set_prompt(PS2, NULL);
1481 set_prompt(int to, Source *s)
1483 cur_prompt = (uint8_t)to;
1489 * Substitute ! and !! here, before substitutions are done
1490 * so ! in expanded variables are not expanded.
1491 * NOTE: this is not what AT&T ksh does (it does it after
1492 * substitutions, POSIX doesn't say which is to be done.
1496 char * volatile ps1;
1499 ps1 = str_val(global("PS1"));
1500 shf = shf_sopen(NULL, strlen(ps1) * 2,
1501 SHF_WR | SHF_DYNAMIC, NULL);
1503 if (*ps1 != '!' || *++ps1 == '!')
1504 shf_putchar(*ps1++, shf);
1506 shf_fprintf(shf, "%lu", s ?
1507 (unsigned long)s->line + 1 : 0UL);
1508 ps1 = shf_sclose(shf);
1509 saved_atemp = ATEMP;
1511 if (kshsetjmp(e->jbuf)) {
1512 prompt = safe_prompt;
1514 * Don't print an error - assume it has already
1515 * been printed. Reason is we may have forked
1516 * to run a command and the child may be
1517 * unwinding its stack through this code as it
1521 char *cp = substitute(ps1, 0);
1522 strdupx(prompt, cp, saved_atemp);
1527 /* command continuation */
1529 prompt = str_val(global("PS2"));
1535 pprompt(const char *cp, int ntruncate)
1538 bool doprint = (ntruncate != -1);
1539 bool indelimit = false;
1540 int columns = 0, lines = 0;
1543 * Undocumented AT&T ksh feature:
1544 * If the second char in the prompt string is \r then the first
1545 * char is taken to be a non-printing delimiter and any chars
1546 * between two instances of the delimiter are not considered to
1547 * be part of the prompt length
1549 if (*cp && cp[1] == '\r') {
1554 if (indelimit && *cp != delimiter)
1556 else if (*cp == '\n' || *cp == '\r') {
1557 lines += columns / x_cols + ((*cp == '\n') ? 1 : 0);
1559 } else if (*cp == '\t') {
1560 columns = (columns | 7) + 1;
1561 } else if (*cp == '\b') {
1564 } else if (*cp == delimiter)
1565 indelimit = !indelimit;
1566 else if (UTFMODE && ((unsigned char)*cp > 0x7F)) {
1568 columns += utf_widthadj(cp, &cp2);
1569 if (doprint && (indelimit ||
1570 (ntruncate < (x_cols * lines + columns))))
1571 shf_write(cp, cp2 - cp, shl_out);
1572 cp = cp2 - /* loop increment */ 1;
1576 if (doprint && (*cp != delimiter) &&
1577 (indelimit || (ntruncate < (x_cols * lines + columns))))
1578 shf_putc(*cp, shl_out);
1582 return (x_cols * lines + columns);
1586 * Read the variable part of a ${...} expression (i.e. up to but not
1587 * including the :[-+?=#%] or close-brace).
1590 get_brace_var(XString *wsp, char *wp)
1594 PS_INITIAL, PS_SAW_HASH, PS_IDENT,
1596 } state = PS_INITIAL;
1598 while (/* CONSTCOND */ 1) {
1600 /* State machine to figure out where the variable part ends. */
1603 if (c == '#' || c == '!' || c == '%') {
1604 state = PS_SAW_HASH;
1611 else if (ksh_isdigit(c))
1613 else if (c == '#') {
1614 if (state == PS_SAW_HASH) {
1619 if (c2 != /*{*/ '}') {
1625 } else if (ctype(c, C_VAR1))
1631 if (!ksh_isalnux(c)) {
1635 if (!arraysub(&tmp))
1636 yyerror("missing ]\n");
1638 for (p = tmp; *p; ) {
1650 if (!ksh_isdigit(c))
1660 /* end of variable part */
1667 * Save an array subscript - returns true if matching bracket found, false
1668 * if eof or newline was found.
1669 * (Returned string double null terminated)
1672 arraysub(char **strp)
1676 /* we are just past the initial [ */
1677 unsigned int depth = 1;
1679 Xinit(ws, wp, 32, ATEMP);
1689 } while (depth > 0 && c && c != '\n');
1692 *strp = Xclose(ws, wp);
1694 return (tobool(depth == 0));
1697 /* Unget a char: handles case when we are already at the start of the buffer */
1701 struct sretrace_info *rp = retrace_info;
1705 /* Don't unget EOF... */
1706 if (source->str == null && c == '\0')
1709 if (Xlength(rp->xs, rp->xp))
1718 if (source->str > source->start)
1723 s = pushs(SREREAD, source->areap);
1724 s->ugbuf[0] = c; s->ugbuf[1] = '\0';
1725 s->start = s->str = s->ugbuf;
1732 /* Called to get a char that isn't a \newline sequence. */
1738 if (ignore_backslash_newline)
1739 return (o_getsc_u());
1741 if (backslash_skip == 1) {
1743 return (o_getsc_u());
1748 while (/* CONSTCOND */ 1) {
1751 if ((c2 = o_getsc_u()) == '\n')
1752 /* ignore the \newline; get the next char... */
1766 if ((unsigned char)(c = o_getsc_u()) != 0xEF) {
1770 if ((unsigned char)(c = o_getsc_u()) != 0xBB) {
1775 if ((unsigned char)(c = o_getsc_u()) != 0xBF) {
1785 push_state_i(State_info *si, Lex_state *old_end)
1787 Lex_state *news = alloc2(STATE_BSIZE, sizeof(Lex_state), ATEMP);
1789 news[0].ls_base = old_end;
1790 si->base = &news[0];
1791 si->end = &news[STATE_BSIZE];
1796 pop_state_i(State_info *si, Lex_state *old_end)
1798 Lex_state *old_base = si->base;
1800 si->base = old_end->ls_base - STATE_BSIZE;
1801 si->end = old_end->ls_base;
1803 afree(old_base, ATEMP);
1805 return (si->base + STATE_BSIZE - 1);