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);
188 } while (wdp->word[0] != '\n');
191 Strbuf_terminate(&histline);
192 if (histline.len != 0 && histline.s[histline.len - 1] == '\n')
193 histline.s[histline.len - 1] = '\0';
200 a2time_t(Char *wordx)
202 /* Attempt to distinguish timestamps from other possible entries.
203 * Format: "+NNNNNNNNNN" (10 digits, left padded with ascii '0') */
209 if (!wordx || *(s = wordx) != '+')
212 for (++s, ret = 0, ct = 0; *s; ++s, ++ct) {
213 if (!isdigit((unsigned char)*s))
215 ret = ret * 10 + (time_t)((unsigned char)*s - '0');
225 prlex(struct wordent *sp0)
227 struct wordent *sp = sp0->next;
230 xprintf("%S", sp->word);
234 if (sp->word[0] != '\n')
240 copylex(struct wordent *hp, struct wordent *fp)
249 new = xmalloc(sizeof(*new));
256 wdp->word = Strsave(fp->word);
258 } while (wdp->word[0] != '\n');
262 initlex(struct wordent *vp)
270 freelex(struct wordent *vp)
274 while (vp->next != vp) {
284 lex_cleanup(void *xvp)
296 struct Strbuf wbuf = Strbuf_INIT;
302 cleanup_push(&wbuf, Strbuf_cleanup);
304 if (enterhist && toolong++ > 256 * 1024) {
305 stderror(ERR_WTOOLONG);
307 while ((c = getC(DOALL)) == ' ' || c == '\t')
309 if (cmap(c, _META | _ESC))
315 Strbuf_append1(&wbuf, c);
318 Strbuf_append1(&wbuf, c1);
324 if (intty || (enterhist && !parsehtime))
331 if (h < 11 && parsehtime)
336 Htime = a2time_t(hbuf);
346 Strbuf_append1(&wbuf, c);
356 if (c != (eChar)HIST)
357 Strbuf_append1(&wbuf, '\\');
365 if (enterhist && toolong++ > 256 * 1024) {
366 stderror(ERR_WTOOLONG);
373 else if (c == '\\') {
376 * PWP: this is dumb, but how all of the other shells work. If \ quotes
377 * a character OUTSIDE of a set of ''s, why shouldn't it quote EVERY
378 * following character INSIDE a set of ''s.
380 * Actually, all I really want to be able to say is 'foo\'bar' --> foo'bar
382 if (c == (eChar)HIST)
386 ((c == '\'') || (c == '"') ||
387 (c == '\\') || (c == '$'))) {
393 * if (c1 == '`') c = ' '; else
401 else if (c == '\n') {
402 seterror(ERR_UNMATCHED, c1);
407 else if (cmap(c, _META | _QF | _QB | _ESC)) {
415 if (c != (eChar)HIST)
416 Strbuf_append1(&wbuf, '\\');
419 else if (cmap(c, _QF | _QB)) { /* '"` */
421 dolflg = c == '"' ? DOALL : DOEXCL;
423 else if (c != '#' || (!intty && !enterhist)) {
428 Strbuf_append1(&wbuf, c);
432 cleanup_ignore(&wbuf);
433 cleanup_until(&wbuf);
434 return Strbuf_finish(&wbuf);
443 if ((c = peekc) != 0) {
447 if (lap < labuf.len) {
449 if (cmap(c, _META | _QF | _QB))
453 if ((c = peekd) != 0) {
458 if ((c = *exclp++) != 0)
460 if (exclnxt && --exclc >= 0) {
461 exclnxt = exclnxt->next;
462 setexclp(exclnxt->word);
467 /* this will throw away the dummy history entries */
472 exclnxt = exclnxt->next;
476 setexclp(exclnxt->word);
481 /* Catch EOF in the middle of a line. (An EOF at the beginning of
482 * a line would have been processed by the readc(0) in lex().) */
486 if (c == '$' && (flag & DODOL)) {
490 if (c == (eChar)HIST && (flag & DOEXCL)) {
502 struct Strbuf name = Strbuf_INIT;
507 c = sc = getC(DOEXCL);
508 if (any("\t \n", c)) {
513 cleanup_push(&name, Strbuf_cleanup);
514 Strbuf_append1(&name, '$');
516 Strbuf_append1(&name, c), c = getC(DOEXCL);
517 if (c == '#' || c == '?' || c == '%')
518 special++, Strbuf_append1(&name, c), c = getC(DOEXCL);
519 Strbuf_append1(&name, c);
526 seterror(ERR_SPDOLLT);
533 seterror(ERR_NEWLINE);
538 seterror(ERR_SPSTAR);
544 /* let $?0 pass for now */
550 while ((c = getC(DOEXCL)) != 0) {
553 Strbuf_append1(&name, c);
556 else if (letter(c)) {
557 while ((c = getC(DOEXCL)) != 0) {
558 /* Bugfix for ${v123x} from Chris Torek, DAS DEC-90. */
559 if (!letter(c) && !Isdigit(c))
561 Strbuf_append1(&name, c);
566 seterror(ERR_VARILL);
576 Strbuf_append1(&name, c);
579 * Michael Greim: Allow $ expansion to take place in selector
580 * expressions. (limits the number of characters returned)
582 c = getC(DOEXCL | DODOL);
586 seterror(ERR_NLINDEX);
589 Strbuf_append1(&name, c);
595 * if the :g modifier is followed by a newline, then error right away!
599 int gmodflag = 0, amodflag = 0;
602 Strbuf_append1(&name, c), c = getC(DOEXCL), gmodflag = 0, amodflag = 0;
603 if (c == 'g' || c == 'a') {
608 Strbuf_append1(&name, c); c = getC(DOEXCL);
610 if ((c == 'g' && !gmodflag) || (c == 'a' && !amodflag)) {
615 Strbuf_append1(&name, c); c = getC(DOEXCL);
617 Strbuf_append1(&name, c);
618 /* scan s// [eichin:19910926.0512EST] */
621 eChar delim = getC(0);
623 Strbuf_append1(&name, delim);
624 if (!delim || letter(delim)
625 || Isdigit(delim) || any(" \t\n", delim)) {
626 seterror(ERR_BADSUBST);
629 while ((c = getC(0)) != CHAR_ERR) {
630 Strbuf_append1(&name, c);
631 if (c == delim) delimcnt--;
632 if (!delimcnt) break;
635 seterror(ERR_BADSUBST);
640 if (!any(TCSH_MODIFIERS, c)) {
641 if ((amodflag || gmodflag) && c == '\n')
642 stderror(ERR_VARSYN); /* strike */
643 seterror(ERR_BADMOD, c);
647 while ((c = getC(DOEXCL)) == ':');
656 seterror(ERR_MISSING, '}');
659 Strbuf_append1(&name, c);
662 cleanup_ignore(&name);
663 cleanup_until(&name);
664 addla(Strbuf_finish(&name));
667 /* xfree()'s its argument */
671 static struct Strbuf buf; /* = Strbuf_INIT; */
674 Strbuf_appendn(&buf, labuf.s + lap, labuf.len - lap);
676 Strbuf_append(&labuf, cp);
677 Strbuf_terminate(&labuf);
678 Strbuf_appendn(&labuf, buf.s, buf.len);
683 /* left-hand side of last :s or search string of last ?event? */
684 static struct Strbuf lhsb; /* = Strbuf_INIT; */
685 static struct Strbuf slhs; /* = Strbuf_INIT; left-hand side of last :s */
686 static struct Strbuf rhsb; /* = Strbuf_INIT; right-hand side of last :s */
692 struct wordent *hp, *ip;
693 int left, right, dol;
712 for (ip = hp->next->next; ip != alhistt; ip = ip->next)
715 for (ip = hp->next->next; ip != hp->prev; ip = ip->next)
717 left = 0, right = dol;
718 if (sc == HISTSUB && HISTSUB != '\0') {
719 ungetC('s'), unreadc(HISTSUB), c = ':';
723 if (!any(":^$*-%", c))
729 if (letter(c) || c == '&') {
731 left = 0, right = dol;
737 if (!getsel(&left, &right, dol))
743 if (!getsel(&left, &right, dol))
748 exclc = right - left + 1;
751 if ((sc == HISTSUB && HISTSUB != '\0') || c == ':') {
761 seterror(ERR_BADBANG);
766 static struct wordent *
767 getsub(struct wordent *en)
778 while (c == 'g' || c == 'a') {
779 global |= (c == 'g') ? FLAG_G : FLAG_A;
803 seterror(ERR_NOSUBST);
807 Strbuf_append(&lhsb, slhs.s);
808 Strbuf_terminate(&lhsb);
820 if (letter(delim) || Isdigit(delim) || any(" \t\n", delim)) {
823 seterror(ERR_BADSUBST);
826 Strbuf_terminate(&lhsb);
838 if (c != delim && c != '\\')
839 Strbuf_append1(&lhsb, '\\');
841 Strbuf_append1(&lhsb, c);
844 Strbuf_terminate(&lhsb);
845 else if (lhsb.s[0] == 0) {
849 lhsb.len = Strlen(lhsb.s); /* lhsb.s wasn't changed */
861 if (c != delim /* && c != '~' */ )
862 Strbuf_append1(&rhsb, '\\');
864 Strbuf_append1(&rhsb, c);
866 Strbuf_terminate(&rhsb);
872 seterror(ERR_BADBANGMOD, (int)c);
876 if (lhsb.s != NULL && lhsb.len != 0)
877 Strbuf_append(&slhs, lhsb.s);
878 Strbuf_terminate(&slhs);
880 en = dosub(sc, en, global);
882 while ((c = getC(0)) == ':');
889 * From Beto Appleton (beto@aixwiz.austin.ibm.com)
891 * when using history substitution, and the variable
892 * 'history' is set to a value higher than 1000,
893 * the shell might either freeze (hang) or core-dump.
894 * We raise the limit to 50000000
897 #define HIST_PURGE -50000000
898 static struct wordent *
899 dosub(Char sc, struct wordent *en, int global)
902 int didsub = 0, didone = 0;
903 struct wordent *hp = &lexi;
910 struct wordent *new = xcalloc(1, sizeof *wdp);
919 Char *tword, *otword;
921 if ((global & FLAG_G) || didsub == 0) {
925 tword = subword(en->word, sc, &didone, &pos);
928 if (global & FLAG_A) {
929 while (didone && tword != STRNULL) {
931 tword = subword(otword, sc, &didone, &pos);
932 if (Strcmp(tword, otword) == 0) {
942 tword = Strsave(en->word);
947 seterror(ERR_MODFAIL);
950 * ANSI mode HP/UX compiler chokes on
951 * return &enthist(HIST_PURGE, &lexi, 0)->Hlex;
953 hst = enthist(HIST_PURGE, &lexi, 0, 0, -1);
957 /* Return a newly allocated result of one modification of CP using the
958 operation TYPE. Set ADID to 1 if a modification was performed.
959 If TYPE == 's', perform substitutions only from *START_POS on and set
960 *START_POS to the position of next substitution attempt. */
962 subword(Char *cp, Char type, int *adid, size_t *start_pos)
977 wp = domod(cp, type);
980 return (Strsave(cp));
986 for (mp = cp + *start_pos; *mp; mp++) {
987 if (matchs(mp, lhsb.s)) {
988 struct Strbuf wbuf = Strbuf_INIT;
990 Strbuf_appendn(&wbuf, cp, mp - cp);
991 for (np = rhsb.s; *np; np++)
1000 Strbuf_append1(&wbuf, *np);
1004 Strbuf_append(&wbuf, lhsb.s);
1007 *start_pos = wbuf.len;
1008 Strbuf_append(&wbuf, mp + lhsb.len);
1010 return Strbuf_finish(&wbuf);
1014 return (Strsave(cp));
1019 domod(Char *cp, Char type)
1027 return Strsave(STRQNULL);
1032 for (xp = wp; (c = *xp) != 0; xp++)
1033 if ((c != ' ' && c != '\t') || type == 'q' || type == 'Q')
1038 wp = NLSChangeCase(cp, 1);
1039 return wp ? wp : Strsave(cp);
1042 wp = NLSChangeCase(cp, 0);
1043 return wp ? wp : Strsave(cp);
1047 wp = Strrchr(cp, '/');
1051 xp = Strsave(wp + 1);
1053 xp = Strnsave(cp, wp - cp);
1059 for (wp--; wp >= cp && *wp != '/'; wp--)
1062 xp = Strsave(wp + 1);
1064 xp = Strnsave(cp, wp - cp);
1067 return (Strsave(type == 'e' ? STRNULL : cp));
1076 matchs(const Char *str, const Char *pat)
1078 while (*str && *pat && *str == *pat)
1084 getsel(int *al, int *ar, int dol)
1088 int first = *al < 0;
1093 if (quesarg == -1) {
1094 seterror(ERR_BADBANGARG);
1136 while (Isdigit(c)) {
1137 i = i * 10 + c - '0';
1159 if (*al > *ar || *ar > dol) {
1160 seterror(ERR_BADBANGARG);
1167 static struct wordent *
1176 c = (sc == HISTSUB && HISTSUB != '\0') ? (eChar)HIST : getC(0);
1177 if (c == (eChar)HIST) {
1191 if (lastev == eventno && alhistp)
1196 case '#': /* !# is command being typed in (mrh) */
1198 seterror(ERR_HISTLOOP);
1211 if (any("(=~", c)) {
1216 Strbuf_terminate(&lhsb);
1219 while (!cmap(c, _ESC | _META | _QF | _QB) && !any("^*-%${}:#", c)) {
1220 if (event != -1 && Isdigit(c))
1221 event = event * 10 + c - '0';
1224 Strbuf_append1(&lhsb, c);
1228 if (lhsb.len == 0) {
1229 lhsb.len = Strlen(lhsb.s); /* lhsb.s wasn't changed */
1233 Strbuf_terminate(&lhsb);
1236 * History had only digits
1239 event = eventno + (alhistp == 0) - event;
1243 Strbuf_append1(&lhsb, '\0'); /* Allocate space */
1244 Strbuf_terminate(&lhsb);
1245 memmove(lhsb.s + 1, lhsb.s, (lhsb.len - 1) * sizeof (*lhsb.s));
1248 hp = findev(lhsb.s, 0);
1254 Strbuf_terminate(&lhsb);
1264 Strbuf_append1(&lhsb, c);
1266 if (lhsb.len == 0) {
1267 lhsb.len = Strlen(lhsb.s); /* lhsb.s wasn't changed */
1268 if (lhsb.len == 0) {
1269 seterror(ERR_NOSEARCH);
1274 Strbuf_terminate(&lhsb);
1275 hp = findev(lhsb.s, 1);
1281 for (hp = Histlist.Hnext; hp; hp = hp->Hnext)
1282 if (hp->Hnum == event) {
1287 np = putn((tcsh_number_t)event);
1288 seterror(ERR_NOEVENT, short2str(np));
1293 static struct Hist *
1294 findev(Char *cp, int anyarg)
1298 for (hp = Histlist.Hnext; hp; hp = hp->Hnext) {
1301 struct wordent *lp = hp->Hlex.next;
1305 * The entries added by alias substitution don't have a newline but do
1306 * have a negative event number. Savehist() trims off these entries,
1307 * but it happens before alias expansion, too early to delete those
1308 * from the previous command.
1312 if (lp->word[0] == '\n')
1320 while (*p++ == *q++);
1324 for (dp = lp->word; *dp; dp++) {
1332 while (*p++ == *q++);
1336 } while (lp->word[0] != '\n');
1338 seterror(ERR_NOEVENT, short2str(cp));
1346 if (cp && cp[0] == '\n')
1354 peekread = (Char) c;
1361 static int sincereal; /* Number of real EOFs we've seen */
1366 if ((c = peekread) != 0) {
1376 xprintf("alvecp %c\n", *alvecp & 0xff);
1379 if ((c = *alvecp++) != 0)
1381 if (alvec && *alvec) {
1393 if ((alvecp = *alvec) != 0) {
1397 /* Infinite source! */
1403 if ((c = *evalp++) != 0)
1405 if (evalvec && *evalvec) {
1413 if (evalvec == INVPPTR) {
1417 if ((evalp = *evalvec) != 0) {
1425 if (arginp == INVPTR || onelflg == 1) {
1431 if ((c = *arginp++) == 0) {
1439 #endif /* BSDJOBS */
1441 if (c == CHAR_ERR) {
1442 #ifndef WINNT_NATIVE
1448 # endif /* TERMIO */
1452 #endif /* !WINNT_NATIVE */
1455 /* was isatty but raw with ignoreeof yields problems */
1456 #ifndef WINNT_NATIVE
1459 if (ioctl(SHIN, TCGETA, (ioctl_t) & tty) == 0 &&
1460 (tty.c_lflag & ICANON))
1462 if (ioctl(SHIN, TIOCGETP, (ioctl_t) & tty) == 0 &&
1463 (tty.sg_flags & RAW) == 0)
1464 # endif /* TERMIO */
1466 if (tcgetattr(SHIN, &tty) == 0 &&
1467 (tty.c_lflag & ICANON))
1469 #else /* WINNT_NATIVE */
1471 #endif /* !WINNT_NATIVE */
1475 #endif /* BSDJOBS */
1477 if (numeof != 0 && ++sincereal >= numeof) /* Too many EOFs? Bye! */
1481 (ctpgrp = tcgetpgrp(FSHTTY)) != -1 &&
1483 (void) tcsetpgrp(FSHTTY, tpgrp);
1486 # endif /* _SEQUENT */
1487 (void) killpg(ctpgrp, SIGHUP);
1490 * With the walking process group fix, this message
1491 * is now obsolete. As the foreground process group
1492 * changes, the shell needs to adjust. Well too bad.
1494 xprintf(CGETS(16, 1, "Reset tty pgrp from %d to %d\n"),
1495 (int)ctpgrp, (int)tpgrp);
1496 # endif /* notdef */
1499 #endif /* BSDJOBS */
1500 /* What follows is complicated EOF handling -- sterling@netcom.com */
1501 /* First, we check to see if we have ignoreeof set */
1502 if (adrof(STRignoreeof)) {
1503 /* If so, we check for any stopped jobs only on the first EOF */
1504 if ((sincereal == 1) && (chkstop == 0)) {
1508 /* If we don't have ignoreeof set, always check for stopped jobs */
1513 /* At this point, if there were stopped jobs, we would have already
1514 * called reset(). If we got this far, assume we can print an
1515 * exit/logout message if we ignoreeof, or just exit.
1517 if (adrof(STRignoreeof)) {
1518 /* If so, tell the user to use exit or logout */
1520 xprintf("%s", CGETS(16, 2,
1521 "\nUse \"logout\" to logout.\n"));
1523 xprintf(CGETS(16, 3,
1524 "\nUse \"exit\" to leave %s.\n"),
1529 /* If we don't have ignoreeof set, just fall through */
1538 if (c == '\n' && onelflg)
1541 Strbuf_append1(&histline, c);
1550 while (buf >= fblocks) {
1551 nfbuf = xcalloc(fblocks + 2, sizeof(Char **));
1553 (void) blkcpy(nfbuf, fbuf);
1557 fbuf[fblocks] = xcalloc(BUFSIZE, sizeof(Char));
1563 wide_read(int fildes, Char *buf, size_t nchars, int use_fclens)
1565 char cbuf[BUFSIZE + 1];
1572 assert (nchars <= sizeof(cbuf) / sizeof(*cbuf));
1578 size_t len = nchars > partial ? nchars - partial : 1;
1580 if (partial + len >= sizeof(cbuf) / sizeof(*cbuf))
1583 r = xread(fildes, cbuf + partial, len);
1585 if (partial == 0 && r <= 0)
1589 while (i < partial && nchars != 0) {
1592 tlen = normal_mbtowc(buf + res, cbuf + i, partial - i);
1595 if ((partial - i) < MB_LEN_MAX && r > 0)
1596 /* Maybe a partial character and there is still a chance
1599 buf[res] = (unsigned char)cbuf[i] | INVALID_BYTE;
1612 memmove(cbuf, cbuf + i, partial - i);
1614 } while (partial != 0 && nchars > 0);
1615 /* Throwing away possible partial multibyte characters on error if the
1616 stream is not seekable */
1618 lseek(fildes, -(off_t)partial, L_INCR);
1620 return res != 0 ? res : r;
1628 int numleft = 0, roomleft;
1631 if (fseekp < fbobp || fseekp > feobp) {
1632 fbobp = feobp = fseekp;
1633 (void) lseek(SHIN, fseekp, L_SET);
1635 if (fseekp == feobp) {
1641 for (i = 0; i < (size_t)(feobp - fbobp); i++)
1643 fseekp = feobp = bytes;
1646 c = wide_read(SHIN, fbuf[0], BUFSIZE, 1);
1649 stderror(ERR_SYSTEM, progname, strerror(errno));
1655 #if !defined(WINNT_NATIVE) && !defined(__CYGWIN__)
1656 ch = fbuf[0][fseekp - fbobp];
1660 ch = fbuf[0][fseekp - fbobp];
1662 } while (ch == '\r');
1663 #endif /* !WINNT_NATIVE && !__CYGWIN__ */
1667 while (fseekp >= feobp) {
1669 #if defined(FILEC) && defined(TIOCSTI)
1671 #endif /* FILEC && TIOCSTI */
1672 ) && intty) { /* then use twenex routine */
1673 fseekp = feobp; /* where else? */
1674 #if defined(FILEC) && defined(TIOCSTI)
1676 c = numleft = tenex(InputBuf, BUFSIZE);
1678 #endif /* FILEC && TIOCSTI */
1679 c = numleft = Inputl(); /* PWP: get a line */
1680 while (numleft > 0) {
1681 off = (int) feobp % BUFSIZE;
1682 buf = (int) feobp / BUFSIZE;
1684 roomleft = BUFSIZE - off;
1685 if (roomleft > numleft)
1687 (void) memcpy(fbuf[buf] + off, InputBuf + c - numleft,
1688 roomleft * sizeof(Char));
1689 numleft -= roomleft;
1693 off = (int) feobp % BUFSIZE;
1694 buf = (int) feobp / BUFSIZE;
1696 roomleft = BUFSIZE - off;
1697 c = wide_read(SHIN, fbuf[buf] + off, roomleft, 0);
1701 if (c == 0 || (c < 0 && fixio(SHIN, errno) == -1))
1706 (void) check_window_size(0); /* for window systems */
1707 #endif /* SIG_WINDOW */
1708 #if !defined(WINNT_NATIVE) && !defined(__CYGWIN__)
1709 ch = fbuf[(int) fseekp / BUFSIZE][(int) fseekp % BUFSIZE];
1713 ch = fbuf[(int) fseekp / BUFSIZE][(int) fseekp % BUFSIZE];
1715 } while (ch == '\r');
1716 #endif /* !WINNT_NATIVE && !__CYGWIN__ */
1729 sb = (int) (fseekp - 1) / BUFSIZE;
1731 for (i = 0; i < sb; i++)
1733 (void) blkcpy(fbuf, &fbuf[sb]);
1734 fseekp -= BUFSIZE * sb;
1735 feobp -= BUFSIZE * sb;
1741 bseek(struct Ain *l)
1743 switch (aret = l->type) {
1745 evalvec = l->a_seek;
1748 xprintf(CGETS(16, 4, "seek to eval %x %x\n"), evalvec, evalp);
1755 xprintf(CGETS(16, 5, "seek to alias %x %x\n"), alvec, alvecp);
1760 xprintf(CGETS(16, 6, "seek to file %x\n"), fseekp);
1765 if (fseekp >= fbobp && feobp >= fbobp) {
1770 for (i = 0; i < (size_t)(feobp - fbobp); i++) {
1782 fbobp = feobp = fseekp + 1; /* To force lseek() */
1787 xprintf(CGETS(16, 7, "Bad seek type %d\n"), aret);
1792 /* any similarity to bell telephone is purely accidental */
1794 btell(struct Ain *l)
1796 switch (l->type = aret) {
1798 l->a_seek = evalvec;
1801 xprintf(CGETS(16, 8, "tell eval %x %x\n"), evalvec, evalp);
1808 xprintf(CGETS(16, 9, "tell alias %x %x\n"), alvec, alvecp);
1813 if (cantell && fseekp >= fbobp && fseekp <= feobp) {
1817 for (i = 0; i < (size_t)(fseekp - fbobp); i++)
1818 l->f_seek += fclens[i];
1825 xprintf(CGETS(16, 10, "tell file %x\n"), fseekp);
1829 xprintf(CGETS(16, 7, "Bad seek type %d\n"), aret);
1837 (void) lseek(SHIN, (off_t) 0, L_XTND);
1853 if (arginp || onelflg || intty)
1855 if ((x = lseek(SHIN, (off_t) 0, L_INCR)) == -1)
1857 fbuf = xcalloc(2, sizeof(Char **));
1859 fbuf[0] = xcalloc(BUFSIZE, sizeof(Char));
1860 fseekp = fbobp = feobp = x;