1 /* $Header: /p/tcsh/cvsroot/tcsh/sh.lex.c,v 3.91 2016/08/01 16:21:09 christos Exp $ */
3 * sh.lex.c: Lexical analysis into tokens
6 * Copyright (c) 1980, 1991 The Regents of the University of California.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 RCSID("$tcsh: sh.lex.c,v 3.91 2016/08/01 16:21:09 christos Exp $")
40 /* #define DEBUG_INP */
41 /* #define DEBUG_SEEK */
50 * These lexical routines read input and form lists of words.
51 * There is some involved processing here, because of the complications
52 * of input buffering, and especially because of history substitution.
54 static Char *word (int);
55 static eChar getC1 (int);
56 static void getdol (void);
57 static void getexcl (Char);
58 static struct Hist *findev (Char *, int);
59 static void setexclp (Char *);
60 static eChar bgetc (void);
61 static void balloc (int);
62 static void bfree (void);
63 static struct wordent *gethent (Char);
64 static int matchs (const Char *, const Char *);
65 static int getsel (int *, int *, int);
66 static struct wordent *getsub (struct wordent *);
67 static Char *subword (Char *, Char, int *, size_t *);
68 static struct wordent *dosub (Char, struct wordent *, int);
71 * Peekc is a peek character for getC, peekread for readc.
72 * There is a subtlety here in many places... history routines
73 * will read ahead and then insert stuff into the input stream.
74 * If they push back a character then they must push it behind
75 * the text substituted by the history substitution. On the other
76 * hand in several places we need 2 peek characters. To make this
77 * all work, the history routines read with getC, and make use both
78 * of ungetC and unreadc. The key observation is that the state
79 * of getC at the call of a history reference is such that calls
80 * to getC from the history routines will always yield calls of
81 * readc, unless this peeking is involved. That is to say that during
82 * getexcl the variables lap, exclp, and exclnxt are all zero.
84 * Getdol invokes history substitution, hence the extra peek, peekd,
85 * which it can ungetD to be before history substitutions.
87 static Char peekc = 0, peekd = 0;
88 static Char peekread = 0;
90 /* (Tail of) current word from ! subst */
91 static Char *exclp = NULL;
93 /* The rest of the ! subst words */
94 static struct wordent *exclnxt = NULL;
96 /* Count of remaining words in ! subst */
99 /* "Globp" for alias resubstitution */
100 int aret = TCSH_F_SEEK;
103 * Labuf implements a general buffer for lookahead during lexical operations.
104 * Text which is to be placed in the input stream can be stuck here.
105 * We stick parsed ahead $ constructs during initial input,
106 * process id's from `$$', and modified variable values (from qualifiers
107 * during expansion in sh.dol.c) here.
109 struct Strbuf labuf; /* = Strbuf_INIT; */
112 * Lex returns to its caller not only a wordlist (as a "var" parameter)
113 * but also whether a history substitution occurred. This is used in
114 * the main (process) routine to determine whether to echo, and also
115 * when called by the alias routine to determine whether to keep the
118 static int hadhist = 0;
121 * Avoid alias expansion recursion via \!#
125 struct Strbuf histline; /* = Strbuf_INIT; last line input */
127 int histvalid = 0; /* is histline valid */
131 #define getC(f) (((getCtmp = peekc) != '\0') ? (peekc = 0, (eChar)getCtmp) : getC1(f))
132 #define ungetC(c) peekc = (Char) c
133 #define ungetD(c) peekd = (Char) c
135 /* Use Htime to store timestamps picked up from history file for enthist()
136 * if reading saved history (sg)
138 time_t Htime = (time_t)0;
139 static time_t a2time_t (Char *);
142 * special parsing rules apply for source -h
144 extern int enterhist;
147 lex(struct wordent *hp)
151 int parsehtime = enterhist;
157 hp->next = hp->prev = hp;
162 while (c == ' ' || c == '\t');
163 if (c == (eChar)HISTSUB && intty)
164 /* ^lef^rit from tty is short !:s^lef^rit */
168 cleanup_push(hp, lex_cleanup);
171 * The following loop is written so that the links needed by freelex will
172 * be ready and rarin to go even if it is interrupted.
177 new = xmalloc(sizeof(*new));
184 wdp->word = word(parsehtime);
186 } while (wdp->word[0] != '\n');
189 Strbuf_terminate(&histline);
190 if (histline.len != 0 && histline.s[histline.len - 1] == '\n')
191 histline.s[histline.len - 1] = '\0';
198 a2time_t(Char *wordx)
200 /* Attempt to distinguish timestamps from other possible entries.
201 * Format: "+NNNNNNNNNN" (10 digits, left padded with ascii '0') */
207 if (!wordx || *(s = wordx) != '+')
210 for (++s, ret = 0, ct = 0; *s; ++s, ++ct) {
211 if (!isdigit((unsigned char)*s))
213 ret = ret * 10 + (time_t)((unsigned char)*s - '0');
223 prlex(struct wordent *sp0)
225 struct wordent *sp = sp0->next;
228 xprintf("%S", sp->word);
232 if (sp->word[0] != '\n')
238 copylex(struct wordent *hp, struct wordent *fp)
247 new = xmalloc(sizeof(*new));
254 wdp->word = Strsave(fp->word);
256 } while (wdp->word[0] != '\n');
260 initlex(struct wordent *vp)
268 freelex(struct wordent *vp)
272 while (vp->next != vp) {
282 lex_cleanup(void *xvp)
294 struct Strbuf wbuf = Strbuf_INIT;
299 cleanup_push(&wbuf, Strbuf_cleanup);
301 while ((c = getC(DOALL)) == ' ' || c == '\t')
303 if (cmap(c, _META | _ESC))
309 Strbuf_append1(&wbuf, c);
312 Strbuf_append1(&wbuf, c1);
318 if (intty || (enterhist && !parsehtime))
325 if (h < 11 && parsehtime)
330 Htime = a2time_t(hbuf);
340 Strbuf_append1(&wbuf, c);
350 if (c != (eChar)HIST)
351 Strbuf_append1(&wbuf, '\\');
364 else if (c == '\\') {
367 * PWP: this is dumb, but how all of the other shells work. If \ quotes
368 * a character OUTSIDE of a set of ''s, why shouldn't it quote EVERY
369 * following character INSIDE a set of ''s.
371 * Actually, all I really want to be able to say is 'foo\'bar' --> foo'bar
373 if (c == (eChar)HIST)
377 ((c == '\'') || (c == '"') ||
378 (c == '\\') || (c == '$'))) {
384 * if (c1 == '`') c = ' '; else
392 else if (c == '\n') {
393 seterror(ERR_UNMATCHED, c1);
398 else if (cmap(c, _META | _QF | _QB | _ESC)) {
406 if (c != (eChar)HIST)
407 Strbuf_append1(&wbuf, '\\');
410 else if (cmap(c, _QF | _QB)) { /* '"` */
412 dolflg = c == '"' ? DOALL : DOEXCL;
414 else if (c != '#' || (!intty && !enterhist)) {
419 Strbuf_append1(&wbuf, c);
423 cleanup_ignore(&wbuf);
424 cleanup_until(&wbuf);
425 return Strbuf_finish(&wbuf);
434 if ((c = peekc) != 0) {
438 if (lap < labuf.len) {
440 if (cmap(c, _META | _QF | _QB))
444 if ((c = peekd) != 0) {
449 if ((c = *exclp++) != 0)
451 if (exclnxt && --exclc >= 0) {
452 exclnxt = exclnxt->next;
453 setexclp(exclnxt->word);
458 /* this will throw away the dummy history entries */
463 exclnxt = exclnxt->next;
467 setexclp(exclnxt->word);
472 /* Catch EOF in the middle of a line. (An EOF at the beginning of
473 * a line would have been processed by the readc(0) in lex().) */
477 if (c == '$' && (flag & DODOL)) {
481 if (c == (eChar)HIST && (flag & DOEXCL)) {
493 struct Strbuf name = Strbuf_INIT;
498 c = sc = getC(DOEXCL);
499 if (any("\t \n", c)) {
504 cleanup_push(&name, Strbuf_cleanup);
505 Strbuf_append1(&name, '$');
507 Strbuf_append1(&name, c), c = getC(DOEXCL);
508 if (c == '#' || c == '?' || c == '%')
509 special++, Strbuf_append1(&name, c), c = getC(DOEXCL);
510 Strbuf_append1(&name, c);
517 seterror(ERR_SPDOLLT);
524 seterror(ERR_NEWLINE);
529 seterror(ERR_SPSTAR);
535 /* let $?0 pass for now */
541 while ((c = getC(DOEXCL)) != 0) {
544 Strbuf_append1(&name, c);
547 else if (letter(c)) {
548 while ((c = getC(DOEXCL)) != 0) {
549 /* Bugfix for ${v123x} from Chris Torek, DAS DEC-90. */
550 if (!letter(c) && !Isdigit(c))
552 Strbuf_append1(&name, c);
557 seterror(ERR_VARILL);
567 Strbuf_append1(&name, c);
570 * Michael Greim: Allow $ expansion to take place in selector
571 * expressions. (limits the number of characters returned)
573 c = getC(DOEXCL | DODOL);
577 seterror(ERR_NLINDEX);
580 Strbuf_append1(&name, c);
586 * if the :g modifier is followed by a newline, then error right away!
590 int gmodflag = 0, amodflag = 0;
593 Strbuf_append1(&name, c), c = getC(DOEXCL);
594 if (c == 'g' || c == 'a') {
599 Strbuf_append1(&name, c); c = getC(DOEXCL);
601 if ((c == 'g' && !gmodflag) || (c == 'a' && !amodflag)) {
606 Strbuf_append1(&name, c); c = getC(DOEXCL);
608 Strbuf_append1(&name, c);
609 /* scan s// [eichin:19910926.0512EST] */
612 eChar delim = getC(0);
614 Strbuf_append1(&name, delim);
615 if (!delim || letter(delim)
616 || Isdigit(delim) || any(" \t\n", delim)) {
617 seterror(ERR_BADSUBST);
620 while ((c = getC(0)) != CHAR_ERR) {
621 Strbuf_append1(&name, c);
622 if(c == delim) delimcnt--;
626 seterror(ERR_BADSUBST);
631 if (!any("htrqxesul", c)) {
632 if ((amodflag || gmodflag) && c == '\n')
633 stderror(ERR_VARSYN); /* strike */
634 seterror(ERR_BADMOD, c);
638 while ((c = getC(DOEXCL)) == ':');
647 seterror(ERR_MISSING, '}');
650 Strbuf_append1(&name, c);
653 cleanup_ignore(&name);
654 cleanup_until(&name);
655 addla(Strbuf_finish(&name));
658 /* xfree()'s its argument */
662 static struct Strbuf buf; /* = Strbuf_INIT; */
665 Strbuf_appendn(&buf, labuf.s + lap, labuf.len - lap);
667 Strbuf_append(&labuf, cp);
668 Strbuf_terminate(&labuf);
669 Strbuf_appendn(&labuf, buf.s, buf.len);
674 /* left-hand side of last :s or search string of last ?event? */
675 static struct Strbuf lhsb; /* = Strbuf_INIT; */
676 static struct Strbuf slhs; /* = Strbuf_INIT; left-hand side of last :s */
677 static struct Strbuf rhsb; /* = Strbuf_INIT; right-hand side of last :s */
683 struct wordent *hp, *ip;
684 int left, right, dol;
703 for (ip = hp->next->next; ip != alhistt; ip = ip->next)
706 for (ip = hp->next->next; ip != hp->prev; ip = ip->next)
708 left = 0, right = dol;
709 if (sc == HISTSUB && HISTSUB != '\0') {
710 ungetC('s'), unreadc(HISTSUB), c = ':';
714 if (!any(":^$*-%", c))
720 if (letter(c) || c == '&') {
722 left = 0, right = dol;
728 if (!getsel(&left, &right, dol))
734 if (!getsel(&left, &right, dol))
739 exclc = right - left + 1;
742 if ((sc == HISTSUB && HISTSUB != '\0') || c == ':') {
752 seterror(ERR_BADBANG);
757 static struct wordent *
758 getsub(struct wordent *en)
769 while (c == 'g' || c == 'a') {
770 global |= (c == 'g') ? FLAG_G : FLAG_A;
794 seterror(ERR_NOSUBST);
798 Strbuf_append(&lhsb, slhs.s);
799 Strbuf_terminate(&lhsb);
811 if (letter(delim) || Isdigit(delim) || any(" \t\n", delim)) {
814 seterror(ERR_BADSUBST);
817 Strbuf_terminate(&lhsb);
829 if (c != delim && c != '\\')
830 Strbuf_append1(&lhsb, '\\');
832 Strbuf_append1(&lhsb, c);
835 Strbuf_terminate(&lhsb);
836 else if (lhsb.s[0] == 0) {
840 lhsb.len = Strlen(lhsb.s); /* lhsb.s wasn't changed */
852 if (c != delim /* && c != '~' */ )
853 Strbuf_append1(&rhsb, '\\');
855 Strbuf_append1(&rhsb, c);
857 Strbuf_terminate(&rhsb);
863 seterror(ERR_BADBANGMOD, (int)c);
867 if (lhsb.s != NULL && lhsb.len != 0)
868 Strbuf_append(&slhs, lhsb.s);
869 Strbuf_terminate(&slhs);
871 en = dosub(sc, en, global);
873 while ((c = getC(0)) == ':');
880 * From Beto Appleton (beto@aixwiz.austin.ibm.com)
882 * when using history substitution, and the variable
883 * 'history' is set to a value higher than 1000,
884 * the shell might either freeze (hang) or core-dump.
885 * We raise the limit to 50000000
888 #define HIST_PURGE -50000000
889 static struct wordent *
890 dosub(Char sc, struct wordent *en, int global)
893 int didsub = 0, didone = 0;
894 struct wordent *hp = &lexi;
901 struct wordent *new = xcalloc(1, sizeof *wdp);
910 Char *tword, *otword;
912 if ((global & FLAG_G) || didsub == 0) {
916 tword = subword(en->word, sc, &didone, &pos);
919 if (global & FLAG_A) {
920 while (didone && tword != STRNULL) {
922 tword = subword(otword, sc, &didone, &pos);
923 if (Strcmp(tword, otword) == 0) {
933 tword = Strsave(en->word);
938 seterror(ERR_MODFAIL);
941 * ANSI mode HP/UX compiler chokes on
942 * return &enthist(HIST_PURGE, &lexi, 0)->Hlex;
944 hst = enthist(HIST_PURGE, &lexi, 0, 0, -1);
948 /* Return a newly allocated result of one modification of CP using the
949 operation TYPE. Set ADID to 1 if a modification was performed.
950 If TYPE == 's', perform substitutions only from *START_POS on and set
951 *START_POS to the position of next substitution attempt. */
953 subword(Char *cp, Char type, int *adid, size_t *start_pos)
968 wp = domod(cp, type);
971 return (Strsave(cp));
977 for (mp = cp + *start_pos; *mp; mp++) {
978 if (matchs(mp, lhsb.s)) {
979 struct Strbuf wbuf = Strbuf_INIT;
981 Strbuf_appendn(&wbuf, cp, mp - cp);
982 for (np = rhsb.s; *np; np++)
991 Strbuf_append1(&wbuf, *np);
995 Strbuf_append(&wbuf, lhsb.s);
998 *start_pos = wbuf.len;
999 Strbuf_append(&wbuf, mp + lhsb.len);
1001 return Strbuf_finish(&wbuf);
1005 return (Strsave(cp));
1010 domod(Char *cp, Char type)
1020 for (xp = wp; (c = *xp) != 0; xp++)
1021 if ((c != ' ' && c != '\t') || type == 'q')
1026 wp = NLSChangeCase(cp, 1);
1027 return wp ? wp : Strsave(cp);
1030 wp = NLSChangeCase(cp, 0);
1031 return wp ? wp : Strsave(cp);
1035 if (!any(short2str(cp), '/'))
1036 return (type == 't' ? Strsave(cp) : 0);
1037 wp = Strrchr(cp, '/');
1039 xp = Strnsave(cp, wp - cp);
1041 xp = Strsave(wp + 1);
1047 for (wp--; wp >= cp && *wp != '/'; wp--)
1050 xp = Strsave(wp + 1);
1052 xp = Strnsave(cp, wp - cp);
1055 return (Strsave(type == 'e' ? STRNULL : cp));
1063 matchs(const Char *str, const Char *pat)
1065 while (*str && *pat && *str == *pat)
1071 getsel(int *al, int *ar, int dol)
1075 int first = *al < 0;
1080 if (quesarg == -1) {
1081 seterror(ERR_BADBANGARG);
1123 while (Isdigit(c)) {
1124 i = i * 10 + c - '0';
1146 if (*al > *ar || *ar > dol) {
1147 seterror(ERR_BADBANGARG);
1154 static struct wordent *
1163 c = (sc == HISTSUB && HISTSUB != '\0') ? (eChar)HIST : getC(0);
1164 if (c == (eChar)HIST) {
1178 if (lastev == eventno && alhistp)
1183 case '#': /* !# is command being typed in (mrh) */
1185 seterror(ERR_HISTLOOP);
1198 if (any("(=~", c)) {
1203 Strbuf_terminate(&lhsb);
1206 while (!cmap(c, _ESC | _META | _QF | _QB) && !any("^*-%${}:#", c)) {
1207 if (event != -1 && Isdigit(c))
1208 event = event * 10 + c - '0';
1211 Strbuf_append1(&lhsb, c);
1215 if (lhsb.len == 0) {
1216 lhsb.len = Strlen(lhsb.s); /* lhsb.s wasn't changed */
1220 Strbuf_terminate(&lhsb);
1223 * History had only digits
1226 event = eventno + (alhistp == 0) - event;
1230 Strbuf_append1(&lhsb, '\0'); /* Allocate space */
1231 Strbuf_terminate(&lhsb);
1232 memmove(lhsb.s + 1, lhsb.s, (lhsb.len - 1) * sizeof (*lhsb.s));
1235 hp = findev(lhsb.s, 0);
1241 Strbuf_terminate(&lhsb);
1251 Strbuf_append1(&lhsb, c);
1253 if (lhsb.len == 0) {
1254 lhsb.len = Strlen(lhsb.s); /* lhsb.s wasn't changed */
1255 if (lhsb.len == 0) {
1256 seterror(ERR_NOSEARCH);
1261 Strbuf_terminate(&lhsb);
1262 hp = findev(lhsb.s, 1);
1268 for (hp = Histlist.Hnext; hp; hp = hp->Hnext)
1269 if (hp->Hnum == event) {
1274 np = putn((tcsh_number_t)event);
1275 seterror(ERR_NOEVENT, short2str(np));
1280 static struct Hist *
1281 findev(Char *cp, int anyarg)
1285 for (hp = Histlist.Hnext; hp; hp = hp->Hnext) {
1288 struct wordent *lp = hp->Hlex.next;
1292 * The entries added by alias substitution don't have a newline but do
1293 * have a negative event number. Savehist() trims off these entries,
1294 * but it happens before alias expansion, too early to delete those
1295 * from the previous command.
1299 if (lp->word[0] == '\n')
1307 while (*p++ == *q++);
1311 for (dp = lp->word; *dp; dp++) {
1319 while (*p++ == *q++);
1323 } while (lp->word[0] != '\n');
1325 seterror(ERR_NOEVENT, short2str(cp));
1333 if (cp && cp[0] == '\n')
1341 peekread = (Char) c;
1348 static int sincereal; /* Number of real EOFs we've seen */
1353 if ((c = peekread) != 0) {
1363 xprintf("alvecp %c\n", *alvecp & 0xff);
1366 if ((c = *alvecp++) != 0)
1368 if (alvec && *alvec) {
1380 if ((alvecp = *alvec) != 0) {
1384 /* Infinite source! */
1390 if ((c = *evalp++) != 0)
1392 if (evalvec && *evalvec) {
1400 if (evalvec == INVPPTR) {
1404 if ((evalp = *evalvec) != 0) {
1412 if (arginp == INVPTR || onelflg == 1) {
1418 if ((c = *arginp++) == 0) {
1426 #endif /* BSDJOBS */
1428 if (c == CHAR_ERR) {
1429 #ifndef WINNT_NATIVE
1435 # endif /* TERMIO */
1439 #endif /* !WINNT_NATIVE */
1442 /* was isatty but raw with ignoreeof yields problems */
1443 #ifndef WINNT_NATIVE
1446 if (ioctl(SHIN, TCGETA, (ioctl_t) & tty) == 0 &&
1447 (tty.c_lflag & ICANON))
1449 if (ioctl(SHIN, TIOCGETP, (ioctl_t) & tty) == 0 &&
1450 (tty.sg_flags & RAW) == 0)
1451 # endif /* TERMIO */
1453 if (tcgetattr(SHIN, &tty) == 0 &&
1454 (tty.c_lflag & ICANON))
1456 #else /* WINNT_NATIVE */
1458 #endif /* !WINNT_NATIVE */
1462 #endif /* BSDJOBS */
1464 if (numeof != 0 && ++sincereal >= numeof) /* Too many EOFs? Bye! */
1468 (ctpgrp = tcgetpgrp(FSHTTY)) != -1 &&
1470 (void) tcsetpgrp(FSHTTY, tpgrp);
1473 # endif /* _SEQUENT */
1474 (void) killpg(ctpgrp, SIGHUP);
1477 * With the walking process group fix, this message
1478 * is now obsolete. As the foreground process group
1479 * changes, the shell needs to adjust. Well too bad.
1481 xprintf(CGETS(16, 1, "Reset tty pgrp from %d to %d\n"),
1482 (int)ctpgrp, (int)tpgrp);
1483 # endif /* notdef */
1486 #endif /* BSDJOBS */
1487 /* What follows is complicated EOF handling -- sterling@netcom.com */
1488 /* First, we check to see if we have ignoreeof set */
1489 if (adrof(STRignoreeof)) {
1490 /* If so, we check for any stopped jobs only on the first EOF */
1491 if ((sincereal == 1) && (chkstop == 0)) {
1495 /* If we don't have ignoreeof set, always check for stopped jobs */
1500 /* At this point, if there were stopped jobs, we would have already
1501 * called reset(). If we got this far, assume we can print an
1502 * exit/logout message if we ignoreeof, or just exit.
1504 if (adrof(STRignoreeof)) {
1505 /* If so, tell the user to use exit or logout */
1507 xprintf("%s", CGETS(16, 2,
1508 "\nUse \"logout\" to logout.\n"));
1510 xprintf(CGETS(16, 3,
1511 "\nUse \"exit\" to leave %s.\n"),
1516 /* If we don't have ignoreeof set, just fall through */
1525 if (c == '\n' && onelflg)
1528 Strbuf_append1(&histline, c);
1537 while (buf >= fblocks) {
1538 nfbuf = xcalloc(fblocks + 2, sizeof(Char **));
1540 (void) blkcpy(nfbuf, fbuf);
1544 fbuf[fblocks] = xcalloc(BUFSIZE, sizeof(Char));
1550 wide_read(int fildes, Char *buf, size_t nchars, int use_fclens)
1552 char cbuf[BUFSIZE + 1];
1559 assert (nchars <= sizeof(cbuf) / sizeof(*cbuf));
1565 size_t len = nchars > partial ? nchars - partial : 1;
1567 if (partial + len >= sizeof(cbuf) / sizeof(*cbuf))
1570 r = xread(fildes, cbuf + partial, len);
1572 if (partial == 0 && r <= 0)
1576 while (i < partial && nchars != 0) {
1579 tlen = normal_mbtowc(buf + res, cbuf + i, partial - i);
1582 if ((partial - i) < MB_LEN_MAX && r > 0)
1583 /* Maybe a partial character and there is still a chance
1586 buf[res] = (unsigned char)cbuf[i] | INVALID_BYTE;
1599 memmove(cbuf, cbuf + i, partial - i);
1601 } while (partial != 0 && nchars > 0);
1602 /* Throwing away possible partial multibyte characters on error if the
1603 stream is not seekable */
1605 lseek(fildes, -(off_t)partial, L_INCR);
1607 return res != 0 ? res : r;
1615 int numleft = 0, roomleft;
1618 if (fseekp < fbobp || fseekp > feobp) {
1619 fbobp = feobp = fseekp;
1620 (void) lseek(SHIN, fseekp, L_SET);
1622 if (fseekp == feobp) {
1628 for (i = 0; i < (size_t)(feobp - fbobp); i++)
1630 fseekp = feobp = bytes;
1633 c = wide_read(SHIN, fbuf[0], BUFSIZE, 1);
1636 stderror(ERR_SYSTEM, progname, strerror(errno));
1642 #if !defined(WINNT_NATIVE) && !defined(__CYGWIN__)
1643 ch = fbuf[0][fseekp - fbobp];
1647 ch = fbuf[0][fseekp - fbobp];
1649 } while(ch == '\r');
1650 #endif /* !WINNT_NATIVE && !__CYGWIN__ */
1654 while (fseekp >= feobp) {
1656 #if defined(FILEC) && defined(TIOCSTI)
1658 #endif /* FILEC && TIOCSTI */
1659 ) && intty) { /* then use twenex routine */
1660 fseekp = feobp; /* where else? */
1661 #if defined(FILEC) && defined(TIOCSTI)
1663 c = numleft = tenex(InputBuf, BUFSIZE);
1665 #endif /* FILEC && TIOCSTI */
1666 c = numleft = Inputl(); /* PWP: get a line */
1667 while (numleft > 0) {
1668 off = (int) feobp % BUFSIZE;
1669 buf = (int) feobp / BUFSIZE;
1671 roomleft = BUFSIZE - off;
1672 if (roomleft > numleft)
1674 (void) memcpy(fbuf[buf] + off, InputBuf + c - numleft,
1675 roomleft * sizeof(Char));
1676 numleft -= roomleft;
1680 off = (int) feobp % BUFSIZE;
1681 buf = (int) feobp / BUFSIZE;
1683 roomleft = BUFSIZE - off;
1684 c = wide_read(SHIN, fbuf[buf] + off, roomleft, 0);
1688 if (c == 0 || (c < 0 && fixio(SHIN, errno) == -1))
1693 (void) check_window_size(0); /* for window systems */
1694 #endif /* SIG_WINDOW */
1695 #if !defined(WINNT_NATIVE) && !defined(__CYGWIN__)
1696 ch = fbuf[(int) fseekp / BUFSIZE][(int) fseekp % BUFSIZE];
1700 ch = fbuf[(int) fseekp / BUFSIZE][(int) fseekp % BUFSIZE];
1702 } while(ch == '\r');
1703 #endif /* !WINNT_NATIVE && !__CYGWIN__ */
1716 sb = (int) (fseekp - 1) / BUFSIZE;
1718 for (i = 0; i < sb; i++)
1720 (void) blkcpy(fbuf, &fbuf[sb]);
1721 fseekp -= BUFSIZE * sb;
1722 feobp -= BUFSIZE * sb;
1728 bseek(struct Ain *l)
1730 switch (aret = l->type) {
1732 evalvec = l->a_seek;
1735 xprintf(CGETS(16, 4, "seek to eval %x %x\n"), evalvec, evalp);
1742 xprintf(CGETS(16, 5, "seek to alias %x %x\n"), alvec, alvecp);
1747 xprintf(CGETS(16, 6, "seek to file %x\n"), fseekp);
1752 if (fseekp >= fbobp && feobp >= fbobp) {
1757 for (i = 0; i < (size_t)(feobp - fbobp); i++) {
1769 fbobp = feobp = fseekp + 1; /* To force lseek() */
1774 xprintf(CGETS(16, 7, "Bad seek type %d\n"), aret);
1779 /* any similarity to bell telephone is purely accidental */
1781 btell(struct Ain *l)
1783 switch (l->type = aret) {
1785 l->a_seek = evalvec;
1788 xprintf(CGETS(16, 8, "tell eval %x %x\n"), evalvec, evalp);
1795 xprintf(CGETS(16, 9, "tell alias %x %x\n"), alvec, alvecp);
1800 if (cantell && fseekp >= fbobp && fseekp <= feobp) {
1804 for (i = 0; i < (size_t)(fseekp - fbobp); i++)
1805 l->f_seek += fclens[i];
1812 xprintf(CGETS(16, 10, "tell file %x\n"), fseekp);
1816 xprintf(CGETS(16, 7, "Bad seek type %d\n"), aret);
1824 (void) lseek(SHIN, (off_t) 0, L_XTND);
1840 if (arginp || onelflg || intty)
1842 if ((x = lseek(SHIN, (off_t) 0, L_INCR)) == -1)
1844 fbuf = xcalloc(2, sizeof(Char **));
1846 fbuf[0] = xcalloc(BUFSIZE, sizeof(Char));
1847 fseekp = fbobp = feobp = x;