2 * sh.lex.c: Lexical analysis into tokens
5 * Copyright (c) 1980, 1991 The Regents of the University of California.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of the University nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 /* #define DEBUG_INP */
37 /* #define DEBUG_SEEK */
46 * These lexical routines read input and form lists of words.
47 * There is some involved processing here, because of the complications
48 * of input buffering, and especially because of history substitution.
50 static Char *word (int);
51 static eChar getC1 (int);
52 static void getdol (void);
53 static void getexcl (Char);
54 static struct Hist *findev (Char *, int);
55 static void setexclp (Char *);
56 static eChar bgetc (void);
57 static void balloc (int);
58 static void bfree (void);
59 static struct wordent *gethent (Char);
60 static int matchs (const Char *, const Char *);
61 static int getsel (int *, int *, int);
62 static struct wordent *getsub (struct wordent *);
63 static Char *subword (Char *, Char, int *, size_t *);
64 static struct wordent *dosub (Char, struct wordent *, int);
67 * Peekc is a peek character for getC, peekread for readc.
68 * There is a subtlety here in many places... history routines
69 * will read ahead and then insert stuff into the input stream.
70 * If they push back a character then they must push it behind
71 * the text substituted by the history substitution. On the other
72 * hand in several places we need 2 peek characters. To make this
73 * all work, the history routines read with getC, and make use both
74 * of ungetC and unreadc. The key observation is that the state
75 * of getC at the call of a history reference is such that calls
76 * to getC from the history routines will always yield calls of
77 * readc, unless this peeking is involved. That is to say that during
78 * getexcl the variables lap, exclp, and exclnxt are all zero.
80 * Getdol invokes history substitution, hence the extra peek, peekd,
81 * which it can ungetD to be before history substitutions.
83 static Char peekc = 0, peekd = 0;
84 static Char peekread = 0;
86 /* (Tail of) current word from ! subst */
87 static Char *exclp = NULL;
89 /* The rest of the ! subst words */
90 static struct wordent *exclnxt = NULL;
92 /* Count of remaining words in ! subst */
95 /* "Globp" for alias resubstitution */
96 int aret = TCSH_F_SEEK;
99 * Labuf implements a general buffer for lookahead during lexical operations.
100 * Text which is to be placed in the input stream can be stuck here.
101 * We stick parsed ahead $ constructs during initial input,
102 * process id's from `$$', and modified variable values (from qualifiers
103 * during expansion in sh.dol.c) here.
105 struct Strbuf labuf; /* = Strbuf_INIT; */
108 * Lex returns to its caller not only a wordlist (as a "var" parameter)
109 * but also whether a history substitution occurred. This is used in
110 * the main (process) routine to determine whether to echo, and also
111 * when called by the alias routine to determine whether to keep the
114 static int hadhist = 0;
117 * Avoid alias expansion recursion via \!#
121 struct Strbuf histline; /* = Strbuf_INIT; last line input */
123 int histvalid = 0; /* is histline valid */
127 #define getC(f) (((getCtmp = peekc) != '\0') ? (peekc = 0, (eChar)getCtmp) : getC1(f))
128 #define ungetC(c) peekc = (Char) c
129 #define ungetD(c) peekd = (Char) c
131 /* Use Htime to store timestamps picked up from history file for enthist()
132 * if reading saved history (sg)
134 time_t Htime = (time_t)0;
135 static time_t a2time_t (Char *);
138 * special parsing rules apply for source -h
140 extern int enterhist;
141 extern int postcmd_active;
144 lex(struct wordent *hp)
148 int parsehtime = enterhist;
156 hp->next = hp->prev = hp;
161 while (c == ' ' || c == '\t');
162 if (c == (eChar)HISTSUB && intty)
163 /* ^lef^rit from tty is short !:s^lef^rit */
167 cleanup_push(hp, lex_cleanup);
170 * The following loop is written so that the links needed by freelex will
171 * be ready and rarin to go even if it is interrupted.
176 new = xmalloc(sizeof(*new));
183 wdp->word = word(parsehtime);
185 if (enterhist && toolong++ > 10 * 1024)
186 stderror(ERR_LTOOLONG);
187 } while (wdp->word[0] != '\n');
190 Strbuf_terminate(&histline);
191 if (histline.len != 0 && histline.s[histline.len - 1] == '\n')
192 histline.s[histline.len - 1] = '\0';
199 a2time_t(Char *wordx)
201 /* Attempt to distinguish timestamps from other possible entries.
202 * Format: "+NNNNNNNNNN" (10 digits, left padded with ascii '0') */
208 if (!wordx || *(s = wordx) != '+')
211 for (++s, ret = 0, ct = 0; *s; ++s, ++ct) {
212 if (!isdigit((unsigned char)*s))
214 ret = ret * 10 + (time_t)((unsigned char)*s - '0');
224 prlex(struct wordent *sp0)
226 struct wordent *sp = sp0->next;
229 xprintf("%S", sp->word);
233 if (sp->word[0] != '\n')
239 copylex(struct wordent *hp, struct wordent *fp)
248 new = xmalloc(sizeof(*new));
255 wdp->word = Strsave(fp->word);
257 } while (wdp->word[0] != '\n');
261 initlex(struct wordent *vp)
269 freelex(struct wordent *vp)
273 while (vp->next != vp) {
283 lex_cleanup(void *xvp)
295 struct Strbuf wbuf = Strbuf_INIT;
301 cleanup_push(&wbuf, Strbuf_cleanup);
303 if (enterhist && toolong++ > 256 * 1024)
304 seterror(ERR_WTOOLONG);
305 while ((c = getC(DOALL)) == ' ' || c == '\t')
307 if (cmap(c, _META | _ESC))
313 Strbuf_append1(&wbuf, c);
316 Strbuf_append1(&wbuf, c1);
322 if (intty || (enterhist && !parsehtime))
329 if (h < 11 && parsehtime)
334 Htime = a2time_t(hbuf);
344 Strbuf_append1(&wbuf, c);
354 if (c != (eChar)HIST)
355 Strbuf_append1(&wbuf, '\\');
363 if (enterhist && toolong++ > 256 * 1024)
364 seterror(ERR_WTOOLONG);
370 else if (c == '\\') {
373 * PWP: this is dumb, but how all of the other shells work. If \ quotes
374 * a character OUTSIDE of a set of ''s, why shouldn't it quote EVERY
375 * following character INSIDE a set of ''s.
377 * Actually, all I really want to be able to say is 'foo\'bar' --> foo'bar
379 if (c == (eChar)HIST)
383 ((c == '\'') || (c == '"') ||
384 (c == '\\') || (c == '$'))) {
390 * if (c1 == '`') c = ' '; else
398 else if (c == '\n') {
399 seterror(ERR_UNMATCHED, c1);
404 else if (cmap(c, _META | _QF | _QB | _ESC)) {
412 if (c != (eChar)HIST)
413 Strbuf_append1(&wbuf, '\\');
416 else if (cmap(c, _QF | _QB)) { /* '"` */
418 dolflg = c == '"' ? DOALL : DOEXCL;
420 else if (c != '#' || (!intty && !enterhist)) {
425 Strbuf_append1(&wbuf, c);
429 cleanup_ignore(&wbuf);
430 cleanup_until(&wbuf);
431 return Strbuf_finish(&wbuf);
440 if ((c = peekc) != 0) {
444 if (lap < labuf.len) {
446 if (cmap(c, _META | _QF | _QB))
450 if ((c = peekd) != 0) {
455 if ((c = *exclp++) != 0)
457 if (exclnxt && --exclc >= 0) {
458 exclnxt = exclnxt->next;
459 setexclp(exclnxt->word);
464 /* this will throw away the dummy history entries */
469 exclnxt = exclnxt->next;
473 setexclp(exclnxt->word);
478 /* Catch EOF in the middle of a line. (An EOF at the beginning of
479 * a line would have been processed by the readc(0) in lex().) */
483 if (c == '$' && (flag & DODOL)) {
487 if (c == (eChar)HIST && (flag & DOEXCL)) {
499 struct Strbuf name = Strbuf_INIT;
504 c = sc = getC(DOEXCL);
505 if (any("\t \n", c)) {
510 cleanup_push(&name, Strbuf_cleanup);
511 Strbuf_append1(&name, '$');
513 Strbuf_append1(&name, c), c = getC(DOEXCL);
514 if (c == '#' || c == '?' || c == '%')
515 special++, Strbuf_append1(&name, c), c = getC(DOEXCL);
516 Strbuf_append1(&name, c);
523 seterror(ERR_SPDOLLT);
530 seterror(ERR_NEWLINE);
535 seterror(ERR_SPSTAR);
541 /* let $?0 pass for now */
547 while ((c = getC(DOEXCL)) != 0) {
550 Strbuf_append1(&name, c);
553 else if (letter(c)) {
554 while ((c = getC(DOEXCL)) != 0) {
555 /* Bugfix for ${v123x} from Chris Torek, DAS DEC-90. */
556 if (!letter(c) && !Isdigit(c))
558 Strbuf_append1(&name, c);
563 seterror(ERR_VARILL);
573 Strbuf_append1(&name, c);
576 * Michael Greim: Allow $ expansion to take place in selector
577 * expressions. (limits the number of characters returned)
579 c = getC(DOEXCL | DODOL);
583 seterror(ERR_NLINDEX);
586 Strbuf_append1(&name, c);
592 * if the :g modifier is followed by a newline, then error right away!
596 int gmodflag = 0, amodflag = 0;
599 Strbuf_append1(&name, c), c = getC(DOEXCL);
600 if (c == 'g' || c == 'a') {
605 Strbuf_append1(&name, c); c = getC(DOEXCL);
607 if ((c == 'g' && !gmodflag) || (c == 'a' && !amodflag)) {
612 Strbuf_append1(&name, c); c = getC(DOEXCL);
614 Strbuf_append1(&name, c);
615 /* scan s// [eichin:19910926.0512EST] */
618 eChar delim = getC(0);
620 Strbuf_append1(&name, delim);
621 if (!delim || letter(delim)
622 || Isdigit(delim) || any(" \t\n", delim)) {
623 seterror(ERR_BADSUBST);
626 while ((c = getC(0)) != CHAR_ERR) {
627 Strbuf_append1(&name, c);
628 if(c == delim) delimcnt--;
632 seterror(ERR_BADSUBST);
637 if (!any("htrqxesul", c)) {
638 if ((amodflag || gmodflag) && c == '\n')
639 stderror(ERR_VARSYN); /* strike */
640 seterror(ERR_BADMOD, c);
644 while ((c = getC(DOEXCL)) == ':');
653 seterror(ERR_MISSING, '}');
656 Strbuf_append1(&name, c);
659 cleanup_ignore(&name);
660 cleanup_until(&name);
661 addla(Strbuf_finish(&name));
664 /* xfree()'s its argument */
668 static struct Strbuf buf; /* = Strbuf_INIT; */
671 Strbuf_appendn(&buf, labuf.s + lap, labuf.len - lap);
673 Strbuf_append(&labuf, cp);
674 Strbuf_terminate(&labuf);
675 Strbuf_appendn(&labuf, buf.s, buf.len);
680 /* left-hand side of last :s or search string of last ?event? */
681 static struct Strbuf lhsb; /* = Strbuf_INIT; */
682 static struct Strbuf slhs; /* = Strbuf_INIT; left-hand side of last :s */
683 static struct Strbuf rhsb; /* = Strbuf_INIT; right-hand side of last :s */
689 struct wordent *hp, *ip;
690 int left, right, dol;
709 for (ip = hp->next->next; ip != alhistt; ip = ip->next)
712 for (ip = hp->next->next; ip != hp->prev; ip = ip->next)
714 left = 0, right = dol;
715 if (sc == HISTSUB && HISTSUB != '\0') {
716 ungetC('s'), unreadc(HISTSUB), c = ':';
720 if (!any(":^$*-%", c))
726 if (letter(c) || c == '&') {
728 left = 0, right = dol;
734 if (!getsel(&left, &right, dol))
740 if (!getsel(&left, &right, dol))
745 exclc = right - left + 1;
748 if ((sc == HISTSUB && HISTSUB != '\0') || c == ':') {
758 seterror(ERR_BADBANG);
763 static struct wordent *
764 getsub(struct wordent *en)
775 while (c == 'g' || c == 'a') {
776 global |= (c == 'g') ? FLAG_G : FLAG_A;
800 seterror(ERR_NOSUBST);
804 Strbuf_append(&lhsb, slhs.s);
805 Strbuf_terminate(&lhsb);
817 if (letter(delim) || Isdigit(delim) || any(" \t\n", delim)) {
820 seterror(ERR_BADSUBST);
823 Strbuf_terminate(&lhsb);
835 if (c != delim && c != '\\')
836 Strbuf_append1(&lhsb, '\\');
838 Strbuf_append1(&lhsb, c);
841 Strbuf_terminate(&lhsb);
842 else if (lhsb.s[0] == 0) {
846 lhsb.len = Strlen(lhsb.s); /* lhsb.s wasn't changed */
858 if (c != delim /* && c != '~' */ )
859 Strbuf_append1(&rhsb, '\\');
861 Strbuf_append1(&rhsb, c);
863 Strbuf_terminate(&rhsb);
869 seterror(ERR_BADBANGMOD, (int)c);
873 if (lhsb.s != NULL && lhsb.len != 0)
874 Strbuf_append(&slhs, lhsb.s);
875 Strbuf_terminate(&slhs);
877 en = dosub(sc, en, global);
879 while ((c = getC(0)) == ':');
886 * From Beto Appleton (beto@aixwiz.austin.ibm.com)
888 * when using history substitution, and the variable
889 * 'history' is set to a value higher than 1000,
890 * the shell might either freeze (hang) or core-dump.
891 * We raise the limit to 50000000
894 #define HIST_PURGE -50000000
895 static struct wordent *
896 dosub(Char sc, struct wordent *en, int global)
899 int didsub = 0, didone = 0;
900 struct wordent *hp = &lexi;
907 struct wordent *new = xcalloc(1, sizeof *wdp);
916 Char *tword, *otword;
918 if ((global & FLAG_G) || didsub == 0) {
922 tword = subword(en->word, sc, &didone, &pos);
925 if (global & FLAG_A) {
926 while (didone && tword != STRNULL) {
928 tword = subword(otword, sc, &didone, &pos);
929 if (Strcmp(tword, otword) == 0) {
939 tword = Strsave(en->word);
944 seterror(ERR_MODFAIL);
947 * ANSI mode HP/UX compiler chokes on
948 * return &enthist(HIST_PURGE, &lexi, 0)->Hlex;
950 hst = enthist(HIST_PURGE, &lexi, 0, 0, -1);
954 /* Return a newly allocated result of one modification of CP using the
955 operation TYPE. Set ADID to 1 if a modification was performed.
956 If TYPE == 's', perform substitutions only from *START_POS on and set
957 *START_POS to the position of next substitution attempt. */
959 subword(Char *cp, Char type, int *adid, size_t *start_pos)
974 wp = domod(cp, type);
977 return (Strsave(cp));
983 for (mp = cp + *start_pos; *mp; mp++) {
984 if (matchs(mp, lhsb.s)) {
985 struct Strbuf wbuf = Strbuf_INIT;
987 Strbuf_appendn(&wbuf, cp, mp - cp);
988 for (np = rhsb.s; *np; np++)
997 Strbuf_append1(&wbuf, *np);
1001 Strbuf_append(&wbuf, lhsb.s);
1004 *start_pos = wbuf.len;
1005 Strbuf_append(&wbuf, mp + lhsb.len);
1007 return Strbuf_finish(&wbuf);
1011 return (Strsave(cp));
1016 domod(Char *cp, Char type)
1026 return Strsave(STRQNULL);
1028 for (xp = wp; (c = *xp) != 0; xp++)
1029 if ((c != ' ' && c != '\t') || type == 'q')
1034 wp = NLSChangeCase(cp, 1);
1035 return wp ? wp : Strsave(cp);
1038 wp = NLSChangeCase(cp, 0);
1039 return wp ? wp : Strsave(cp);
1043 if (!any(short2str(cp), '/'))
1044 return (type == 't' ? Strsave(cp) : 0);
1045 wp = Strrchr(cp, '/');
1047 xp = Strnsave(cp, wp - cp);
1049 xp = Strsave(wp + 1);
1055 for (wp--; wp >= cp && *wp != '/'; wp--)
1058 xp = Strsave(wp + 1);
1060 xp = Strnsave(cp, wp - cp);
1063 return (Strsave(type == 'e' ? STRNULL : cp));
1071 matchs(const Char *str, const Char *pat)
1073 while (*str && *pat && *str == *pat)
1079 getsel(int *al, int *ar, int dol)
1083 int first = *al < 0;
1088 if (quesarg == -1) {
1089 seterror(ERR_BADBANGARG);
1131 while (Isdigit(c)) {
1132 i = i * 10 + c - '0';
1154 if (*al > *ar || *ar > dol) {
1155 seterror(ERR_BADBANGARG);
1162 static struct wordent *
1171 c = (sc == HISTSUB && HISTSUB != '\0') ? (eChar)HIST : getC(0);
1172 if (c == (eChar)HIST) {
1186 if (lastev == eventno && alhistp)
1191 case '#': /* !# is command being typed in (mrh) */
1193 seterror(ERR_HISTLOOP);
1206 if (any("(=~", c)) {
1211 Strbuf_terminate(&lhsb);
1214 while (!cmap(c, _ESC | _META | _QF | _QB) && !any("^*-%${}:#", c)) {
1215 if (event != -1 && Isdigit(c))
1216 event = event * 10 + c - '0';
1219 Strbuf_append1(&lhsb, c);
1223 if (lhsb.len == 0) {
1224 lhsb.len = Strlen(lhsb.s); /* lhsb.s wasn't changed */
1228 Strbuf_terminate(&lhsb);
1231 * History had only digits
1234 event = eventno + (alhistp == 0) - event;
1238 Strbuf_append1(&lhsb, '\0'); /* Allocate space */
1239 Strbuf_terminate(&lhsb);
1240 memmove(lhsb.s + 1, lhsb.s, (lhsb.len - 1) * sizeof (*lhsb.s));
1243 hp = findev(lhsb.s, 0);
1249 Strbuf_terminate(&lhsb);
1259 Strbuf_append1(&lhsb, c);
1261 if (lhsb.len == 0) {
1262 lhsb.len = Strlen(lhsb.s); /* lhsb.s wasn't changed */
1263 if (lhsb.len == 0) {
1264 seterror(ERR_NOSEARCH);
1269 Strbuf_terminate(&lhsb);
1270 hp = findev(lhsb.s, 1);
1276 for (hp = Histlist.Hnext; hp; hp = hp->Hnext)
1277 if (hp->Hnum == event) {
1282 np = putn((tcsh_number_t)event);
1283 seterror(ERR_NOEVENT, short2str(np));
1288 static struct Hist *
1289 findev(Char *cp, int anyarg)
1293 for (hp = Histlist.Hnext; hp; hp = hp->Hnext) {
1296 struct wordent *lp = hp->Hlex.next;
1300 * The entries added by alias substitution don't have a newline but do
1301 * have a negative event number. Savehist() trims off these entries,
1302 * but it happens before alias expansion, too early to delete those
1303 * from the previous command.
1307 if (lp->word[0] == '\n')
1315 while (*p++ == *q++);
1319 for (dp = lp->word; *dp; dp++) {
1327 while (*p++ == *q++);
1331 } while (lp->word[0] != '\n');
1333 seterror(ERR_NOEVENT, short2str(cp));
1341 if (cp && cp[0] == '\n')
1349 peekread = (Char) c;
1356 static int sincereal; /* Number of real EOFs we've seen */
1361 if ((c = peekread) != 0) {
1371 xprintf("alvecp %c\n", *alvecp & 0xff);
1374 if ((c = *alvecp++) != 0)
1376 if (alvec && *alvec) {
1388 if ((alvecp = *alvec) != 0) {
1392 /* Infinite source! */
1398 if ((c = *evalp++) != 0)
1400 if (evalvec && *evalvec) {
1408 if (evalvec == INVPPTR) {
1412 if ((evalp = *evalvec) != 0) {
1420 if (arginp == INVPTR || onelflg == 1) {
1426 if ((c = *arginp++) == 0) {
1434 #endif /* BSDJOBS */
1436 if (c == CHAR_ERR) {
1437 #ifndef WINNT_NATIVE
1443 # endif /* TERMIO */
1447 #endif /* !WINNT_NATIVE */
1450 /* was isatty but raw with ignoreeof yields problems */
1451 #ifndef WINNT_NATIVE
1454 if (ioctl(SHIN, TCGETA, (ioctl_t) & tty) == 0 &&
1455 (tty.c_lflag & ICANON))
1457 if (ioctl(SHIN, TIOCGETP, (ioctl_t) & tty) == 0 &&
1458 (tty.sg_flags & RAW) == 0)
1459 # endif /* TERMIO */
1461 if (tcgetattr(SHIN, &tty) == 0 &&
1462 (tty.c_lflag & ICANON))
1464 #else /* WINNT_NATIVE */
1466 #endif /* !WINNT_NATIVE */
1470 #endif /* BSDJOBS */
1472 if (numeof != 0 && ++sincereal >= numeof) /* Too many EOFs? Bye! */
1476 (ctpgrp = tcgetpgrp(FSHTTY)) != -1 &&
1478 (void) tcsetpgrp(FSHTTY, tpgrp);
1481 # endif /* _SEQUENT */
1482 (void) killpg(ctpgrp, SIGHUP);
1485 * With the walking process group fix, this message
1486 * is now obsolete. As the foreground process group
1487 * changes, the shell needs to adjust. Well too bad.
1489 xprintf(CGETS(16, 1, "Reset tty pgrp from %d to %d\n"),
1490 (int)ctpgrp, (int)tpgrp);
1491 # endif /* notdef */
1494 #endif /* BSDJOBS */
1495 /* What follows is complicated EOF handling -- sterling@netcom.com */
1496 /* First, we check to see if we have ignoreeof set */
1497 if (adrof(STRignoreeof)) {
1498 /* If so, we check for any stopped jobs only on the first EOF */
1499 if ((sincereal == 1) && (chkstop == 0)) {
1503 /* If we don't have ignoreeof set, always check for stopped jobs */
1508 /* At this point, if there were stopped jobs, we would have already
1509 * called reset(). If we got this far, assume we can print an
1510 * exit/logout message if we ignoreeof, or just exit.
1512 if (adrof(STRignoreeof)) {
1513 /* If so, tell the user to use exit or logout */
1515 xprintf("%s", CGETS(16, 2,
1516 "\nUse \"logout\" to logout.\n"));
1518 xprintf(CGETS(16, 3,
1519 "\nUse \"exit\" to leave %s.\n"),
1524 /* If we don't have ignoreeof set, just fall through */
1533 if (c == '\n' && onelflg)
1536 Strbuf_append1(&histline, c);
1545 while (buf >= fblocks) {
1546 nfbuf = xcalloc(fblocks + 2, sizeof(Char **));
1548 (void) blkcpy(nfbuf, fbuf);
1552 fbuf[fblocks] = xcalloc(BUFSIZE, sizeof(Char));
1558 wide_read(int fildes, Char *buf, size_t nchars, int use_fclens)
1560 char cbuf[BUFSIZE + 1];
1567 assert (nchars <= sizeof(cbuf) / sizeof(*cbuf));
1573 size_t len = nchars > partial ? nchars - partial : 1;
1575 if (partial + len >= sizeof(cbuf) / sizeof(*cbuf))
1578 r = xread(fildes, cbuf + partial, len);
1580 if (partial == 0 && r <= 0)
1584 while (i < partial && nchars != 0) {
1587 tlen = normal_mbtowc(buf + res, cbuf + i, partial - i);
1590 if ((partial - i) < MB_LEN_MAX && r > 0)
1591 /* Maybe a partial character and there is still a chance
1594 buf[res] = (unsigned char)cbuf[i] | INVALID_BYTE;
1607 memmove(cbuf, cbuf + i, partial - i);
1609 } while (partial != 0 && nchars > 0);
1610 /* Throwing away possible partial multibyte characters on error if the
1611 stream is not seekable */
1613 lseek(fildes, -(off_t)partial, L_INCR);
1615 return res != 0 ? res : r;
1623 int numleft = 0, roomleft;
1626 if (fseekp < fbobp || fseekp > feobp) {
1627 fbobp = feobp = fseekp;
1628 (void) lseek(SHIN, fseekp, L_SET);
1630 if (fseekp == feobp) {
1636 for (i = 0; i < (size_t)(feobp - fbobp); i++)
1638 fseekp = feobp = bytes;
1641 c = wide_read(SHIN, fbuf[0], BUFSIZE, 1);
1644 stderror(ERR_SYSTEM, progname, strerror(errno));
1650 #if !defined(WINNT_NATIVE) && !defined(__CYGWIN__)
1651 ch = fbuf[0][fseekp - fbobp];
1655 ch = fbuf[0][fseekp - fbobp];
1657 } while(ch == '\r');
1658 #endif /* !WINNT_NATIVE && !__CYGWIN__ */
1662 while (fseekp >= feobp) {
1664 #if defined(FILEC) && defined(TIOCSTI)
1666 #endif /* FILEC && TIOCSTI */
1667 ) && intty) { /* then use twenex routine */
1668 fseekp = feobp; /* where else? */
1669 #if defined(FILEC) && defined(TIOCSTI)
1671 c = numleft = tenex(InputBuf, BUFSIZE);
1673 #endif /* FILEC && TIOCSTI */
1674 c = numleft = Inputl(); /* PWP: get a line */
1675 while (numleft > 0) {
1676 off = (int) feobp % BUFSIZE;
1677 buf = (int) feobp / BUFSIZE;
1679 roomleft = BUFSIZE - off;
1680 if (roomleft > numleft)
1682 (void) memcpy(fbuf[buf] + off, InputBuf + c - numleft,
1683 roomleft * sizeof(Char));
1684 numleft -= roomleft;
1688 off = (int) feobp % BUFSIZE;
1689 buf = (int) feobp / BUFSIZE;
1691 roomleft = BUFSIZE - off;
1692 c = wide_read(SHIN, fbuf[buf] + off, roomleft, 0);
1696 if (c == 0 || (c < 0 && fixio(SHIN, errno) == -1))
1701 (void) check_window_size(0); /* for window systems */
1702 #endif /* SIG_WINDOW */
1703 #if !defined(WINNT_NATIVE) && !defined(__CYGWIN__)
1704 ch = fbuf[(int) fseekp / BUFSIZE][(int) fseekp % BUFSIZE];
1708 ch = fbuf[(int) fseekp / BUFSIZE][(int) fseekp % BUFSIZE];
1710 } while(ch == '\r');
1711 #endif /* !WINNT_NATIVE && !__CYGWIN__ */
1724 sb = (int) (fseekp - 1) / BUFSIZE;
1726 for (i = 0; i < sb; i++)
1728 (void) blkcpy(fbuf, &fbuf[sb]);
1729 fseekp -= BUFSIZE * sb;
1730 feobp -= BUFSIZE * sb;
1736 bseek(struct Ain *l)
1738 switch (aret = l->type) {
1740 evalvec = l->a_seek;
1743 xprintf(CGETS(16, 4, "seek to eval %x %x\n"), evalvec, evalp);
1750 xprintf(CGETS(16, 5, "seek to alias %x %x\n"), alvec, alvecp);
1755 xprintf(CGETS(16, 6, "seek to file %x\n"), fseekp);
1760 if (fseekp >= fbobp && feobp >= fbobp) {
1765 for (i = 0; i < (size_t)(feobp - fbobp); i++) {
1777 fbobp = feobp = fseekp + 1; /* To force lseek() */
1782 xprintf(CGETS(16, 7, "Bad seek type %d\n"), aret);
1787 /* any similarity to bell telephone is purely accidental */
1789 btell(struct Ain *l)
1791 switch (l->type = aret) {
1793 l->a_seek = evalvec;
1796 xprintf(CGETS(16, 8, "tell eval %x %x\n"), evalvec, evalp);
1803 xprintf(CGETS(16, 9, "tell alias %x %x\n"), alvec, alvecp);
1808 if (cantell && fseekp >= fbobp && fseekp <= feobp) {
1812 for (i = 0; i < (size_t)(fseekp - fbobp); i++)
1813 l->f_seek += fclens[i];
1820 xprintf(CGETS(16, 10, "tell file %x\n"), fseekp);
1824 xprintf(CGETS(16, 7, "Bad seek type %d\n"), aret);
1832 (void) lseek(SHIN, (off_t) 0, L_XTND);
1848 if (arginp || onelflg || intty)
1850 if ((x = lseek(SHIN, (off_t) 0, L_INCR)) == -1)
1852 fbuf = xcalloc(2, sizeof(Char **));
1854 fbuf[0] = xcalloc(BUFSIZE, sizeof(Char));
1855 fseekp = fbobp = feobp = x;