1 /* $Header: /p/tcsh/cvsroot/tcsh/sh.lex.c,v 3.87 2011/01/24 17:48:15 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.87 2011/01/24 17:48:15 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);
69 static ssize_t wide_read (int, Char *, size_t, int);
72 * Peekc is a peek character for getC, peekread for readc.
73 * There is a subtlety here in many places... history routines
74 * will read ahead and then insert stuff into the input stream.
75 * If they push back a character then they must push it behind
76 * the text substituted by the history substitution. On the other
77 * hand in several places we need 2 peek characters. To make this
78 * all work, the history routines read with getC, and make use both
79 * of ungetC and unreadc. The key observation is that the state
80 * of getC at the call of a history reference is such that calls
81 * to getC from the history routines will always yield calls of
82 * readc, unless this peeking is involved. That is to say that during
83 * getexcl the variables lap, exclp, and exclnxt are all zero.
85 * Getdol invokes history substitution, hence the extra peek, peekd,
86 * which it can ungetD to be before history substitutions.
88 static Char peekc = 0, peekd = 0;
89 static Char peekread = 0;
91 /* (Tail of) current word from ! subst */
92 static Char *exclp = NULL;
94 /* The rest of the ! subst words */
95 static struct wordent *exclnxt = NULL;
97 /* Count of remaining words in ! subst */
100 /* "Globp" for alias resubstitution */
101 int aret = TCSH_F_SEEK;
104 * Labuf implements a general buffer for lookahead during lexical operations.
105 * Text which is to be placed in the input stream can be stuck here.
106 * We stick parsed ahead $ constructs during initial input,
107 * process id's from `$$', and modified variable values (from qualifiers
108 * during expansion in sh.dol.c) here.
110 struct Strbuf labuf; /* = Strbuf_INIT; */
113 * Lex returns to its caller not only a wordlist (as a "var" parameter)
114 * but also whether a history substitution occurred. This is used in
115 * the main (process) routine to determine whether to echo, and also
116 * when called by the alias routine to determine whether to keep the
119 static int hadhist = 0;
122 * Avoid alias expansion recursion via \!#
126 struct Strbuf histline; /* = Strbuf_INIT; last line input */
128 int histvalid = 0; /* is histline valid */
132 #define getC(f) (((getCtmp = peekc) != '\0') ? (peekc = 0, (eChar)getCtmp) : getC1(f))
133 #define ungetC(c) peekc = (Char) c
134 #define ungetD(c) peekd = (Char) c
136 /* Use Htime to store timestamps picked up from history file for enthist()
137 * if reading saved history (sg)
139 time_t Htime = (time_t)0;
140 static time_t a2time_t (Char *);
143 * special parsing rules apply for source -h
145 extern int enterhist;
148 lex(struct wordent *hp)
152 int parsehtime = enterhist;
158 hp->next = hp->prev = hp;
163 while (c == ' ' || c == '\t');
164 if (c == (eChar)HISTSUB && intty)
165 /* ^lef^rit from tty is short !:s^lef^rit */
169 cleanup_push(hp, lex_cleanup);
172 * The following loop is written so that the links needed by freelex will
173 * be ready and rarin to go even if it is interrupted.
178 new = xmalloc(sizeof(*new));
185 wdp->word = word(parsehtime);
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 freelex(struct wordent *vp)
265 while (vp->next != vp) {
275 lex_cleanup(void *xvp)
287 struct Strbuf wbuf = Strbuf_INIT;
292 cleanup_push(&wbuf, Strbuf_cleanup);
294 while ((c = getC(DOALL)) == ' ' || c == '\t')
296 if (cmap(c, _META | _ESC))
302 Strbuf_append1(&wbuf, c);
305 Strbuf_append1(&wbuf, c1);
311 if (intty || (enterhist && !parsehtime))
318 if (h < 11 && parsehtime)
323 Htime = a2time_t(hbuf);
333 Strbuf_append1(&wbuf, c);
343 if (c != (eChar)HIST)
344 Strbuf_append1(&wbuf, '\\');
357 else if (c == '\\') {
360 * PWP: this is dumb, but how all of the other shells work. If \ quotes
361 * a character OUTSIDE of a set of ''s, why shouldn't it quote EVERY
362 * following character INSIDE a set of ''s.
364 * Actually, all I really want to be able to say is 'foo\'bar' --> foo'bar
366 if (c == (eChar)HIST)
370 ((c == '\'') || (c == '"') ||
371 (c == '\\') || (c == '$'))) {
377 * if (c1 == '`') c = ' '; else
385 else if (c == '\n') {
386 seterror(ERR_UNMATCHED, c1);
391 else if (cmap(c, _META | _QF | _QB | _ESC)) {
399 if (c != (eChar)HIST)
400 Strbuf_append1(&wbuf, '\\');
403 else if (cmap(c, _QF | _QB)) { /* '"` */
405 dolflg = c == '"' ? DOALL : DOEXCL;
407 else if (c != '#' || (!intty && !enterhist)) {
412 Strbuf_append1(&wbuf, c);
416 cleanup_ignore(&wbuf);
417 cleanup_until(&wbuf);
418 return Strbuf_finish(&wbuf);
427 if ((c = peekc) != 0) {
431 if (lap < labuf.len) {
433 if (cmap(c, _META | _QF | _QB))
437 if ((c = peekd) != 0) {
442 if ((c = *exclp++) != 0)
444 if (exclnxt && --exclc >= 0) {
445 exclnxt = exclnxt->next;
446 setexclp(exclnxt->word);
451 /* this will throw away the dummy history entries */
456 exclnxt = exclnxt->next;
460 setexclp(exclnxt->word);
465 /* Catch EOF in the middle of a line. (An EOF at the beginning of
466 * a line would have been processed by the readc(0) in lex().) */
470 if (c == '$' && (flag & DODOL)) {
474 if (c == (eChar)HIST && (flag & DOEXCL)) {
486 struct Strbuf name = Strbuf_INIT;
491 c = sc = getC(DOEXCL);
492 if (any("\t \n", c)) {
497 cleanup_push(&name, Strbuf_cleanup);
498 Strbuf_append1(&name, '$');
500 Strbuf_append1(&name, c), c = getC(DOEXCL);
501 if (c == '#' || c == '?' || c == '%')
502 special++, Strbuf_append1(&name, c), c = getC(DOEXCL);
503 Strbuf_append1(&name, c);
510 seterror(ERR_SPDOLLT);
517 seterror(ERR_NEWLINE);
522 seterror(ERR_SPSTAR);
528 /* let $?0 pass for now */
534 while ((c = getC(DOEXCL)) != 0) {
537 Strbuf_append1(&name, c);
540 else if (letter(c)) {
541 while ((c = getC(DOEXCL)) != 0) {
542 /* Bugfix for ${v123x} from Chris Torek, DAS DEC-90. */
543 if (!letter(c) && !Isdigit(c))
545 Strbuf_append1(&name, c);
550 seterror(ERR_VARILL);
560 Strbuf_append1(&name, c);
563 * Michael Greim: Allow $ expansion to take place in selector
564 * expressions. (limits the number of characters returned)
566 c = getC(DOEXCL | DODOL);
570 seterror(ERR_NLINDEX);
573 Strbuf_append1(&name, c);
579 * if the :g modifier is followed by a newline, then error right away!
583 int gmodflag = 0, amodflag = 0;
586 Strbuf_append1(&name, c), c = getC(DOEXCL);
587 if (c == 'g' || c == 'a') {
592 Strbuf_append1(&name, c); c = getC(DOEXCL);
594 if ((c == 'g' && !gmodflag) || (c == 'a' && !amodflag)) {
599 Strbuf_append1(&name, c); c = getC(DOEXCL);
601 Strbuf_append1(&name, c);
602 /* scan s// [eichin:19910926.0512EST] */
605 eChar delim = getC(0);
607 Strbuf_append1(&name, delim);
608 if (!delim || letter(delim)
609 || Isdigit(delim) || any(" \t\n", delim)) {
610 seterror(ERR_BADSUBST);
613 while ((c = getC(0)) != CHAR_ERR) {
614 Strbuf_append1(&name, c);
615 if(c == delim) delimcnt--;
619 seterror(ERR_BADSUBST);
624 if (!any("htrqxesul", c)) {
625 if ((amodflag || gmodflag) && c == '\n')
626 stderror(ERR_VARSYN); /* strike */
627 seterror(ERR_BADMOD, c);
631 while ((c = getC(DOEXCL)) == ':');
640 seterror(ERR_MISSING, '}');
643 Strbuf_append1(&name, c);
646 cleanup_ignore(&name);
647 cleanup_until(&name);
648 addla(Strbuf_finish(&name));
651 /* xfree()'s its argument */
655 static struct Strbuf buf; /* = Strbuf_INIT; */
658 Strbuf_appendn(&buf, labuf.s + lap, labuf.len - lap);
660 Strbuf_append(&labuf, cp);
661 Strbuf_terminate(&labuf);
662 Strbuf_appendn(&labuf, buf.s, buf.len);
667 /* left-hand side of last :s or search string of last ?event? */
668 static struct Strbuf lhsb; /* = Strbuf_INIT; */
669 static struct Strbuf slhs; /* = Strbuf_INIT; left-hand side of last :s */
670 static struct Strbuf rhsb; /* = Strbuf_INIT; right-hand side of last :s */
676 struct wordent *hp, *ip;
677 int left, right, dol;
696 for (ip = hp->next->next; ip != alhistt; ip = ip->next)
699 for (ip = hp->next->next; ip != hp->prev; ip = ip->next)
701 left = 0, right = dol;
702 if (sc == HISTSUB && HISTSUB != '\0') {
703 ungetC('s'), unreadc(HISTSUB), c = ':';
707 if (!any(":^$*-%", c))
713 if (letter(c) || c == '&') {
715 left = 0, right = dol;
721 if (!getsel(&left, &right, dol))
727 if (!getsel(&left, &right, dol))
732 exclc = right - left + 1;
735 if ((sc == HISTSUB && HISTSUB != '\0') || c == ':') {
745 seterror(ERR_BADBANG);
750 static struct wordent *
751 getsub(struct wordent *en)
762 while (c == 'g' || c == 'a') {
763 global |= (c == 'g') ? FLAG_G : FLAG_A;
787 seterror(ERR_NOSUBST);
791 Strbuf_append(&lhsb, slhs.s);
792 Strbuf_terminate(&lhsb);
804 if (letter(delim) || Isdigit(delim) || any(" \t\n", delim)) {
807 seterror(ERR_BADSUBST);
810 Strbuf_terminate(&lhsb);
822 if (c != delim && c != '\\')
823 Strbuf_append1(&lhsb, '\\');
825 Strbuf_append1(&lhsb, c);
828 Strbuf_terminate(&lhsb);
829 else if (lhsb.s[0] == 0) {
833 lhsb.len = Strlen(lhsb.s); /* lhsb.s wasn't changed */
845 if (c != delim /* && c != '~' */ )
846 Strbuf_append1(&rhsb, '\\');
848 Strbuf_append1(&rhsb, c);
850 Strbuf_terminate(&rhsb);
856 seterror(ERR_BADBANGMOD, (int)c);
860 if (lhsb.s != NULL && lhsb.len != 0)
861 Strbuf_append(&slhs, lhsb.s);
862 Strbuf_terminate(&slhs);
864 en = dosub(sc, en, global);
866 while ((c = getC(0)) == ':');
873 * From Beto Appleton (beto@aixwiz.austin.ibm.com)
875 * when using history substitution, and the variable
876 * 'history' is set to a value higher than 1000,
877 * the shell might either freeze (hang) or core-dump.
878 * We raise the limit to 50000000
881 #define HIST_PURGE -50000000
882 static struct wordent *
883 dosub(Char sc, struct wordent *en, int global)
886 int didsub = 0, didone = 0;
887 struct wordent *hp = &lexi;
894 struct wordent *new = xcalloc(1, sizeof *wdp);
903 Char *tword, *otword;
905 if ((global & FLAG_G) || didsub == 0) {
909 tword = subword(en->word, sc, &didone, &pos);
912 if (global & FLAG_A) {
913 while (didone && tword != STRNULL) {
915 tword = subword(otword, sc, &didone, &pos);
916 if (Strcmp(tword, otword) == 0) {
926 tword = Strsave(en->word);
931 seterror(ERR_MODFAIL);
934 * ANSI mode HP/UX compiler chokes on
935 * return &enthist(HIST_PURGE, &lexi, 0)->Hlex;
937 hst = enthist(HIST_PURGE, &lexi, 0, 0, -1);
941 /* Return a newly allocated result of one modification of CP using the
942 operation TYPE. Set ADID to 1 if a modification was performed.
943 If TYPE == 's', perform substitutions only from *START_POS on and set
944 *START_POS to the position of next substitution attempt. */
946 subword(Char *cp, Char type, int *adid, size_t *start_pos)
961 wp = domod(cp, type);
964 return (Strsave(cp));
970 for (mp = cp + *start_pos; *mp; mp++) {
971 if (matchs(mp, lhsb.s)) {
972 struct Strbuf wbuf = Strbuf_INIT;
974 Strbuf_appendn(&wbuf, cp, mp - cp);
975 for (np = rhsb.s; *np; np++)
984 Strbuf_append1(&wbuf, *np);
988 Strbuf_append(&wbuf, lhsb.s);
991 *start_pos = wbuf.len;
992 Strbuf_append(&wbuf, mp + lhsb.len);
994 return Strbuf_finish(&wbuf);
998 return (Strsave(cp));
1003 domod(Char *cp, Char type)
1013 for (xp = wp; (c = *xp) != 0; xp++)
1014 if ((c != ' ' && c != '\t') || type == 'q')
1019 wp = NLSChangeCase(cp, 1);
1020 return wp ? wp : Strsave(cp);
1023 wp = NLSChangeCase(cp, 0);
1024 return wp ? wp : Strsave(cp);
1028 if (!any(short2str(cp), '/'))
1029 return (type == 't' ? Strsave(cp) : 0);
1030 wp = Strrchr(cp, '/');
1032 xp = Strnsave(cp, wp - cp);
1034 xp = Strsave(wp + 1);
1040 for (wp--; wp >= cp && *wp != '/'; wp--)
1043 xp = Strsave(wp + 1);
1045 xp = Strnsave(cp, wp - cp);
1048 return (Strsave(type == 'e' ? STRNULL : cp));
1056 matchs(const Char *str, const Char *pat)
1058 while (*str && *pat && *str == *pat)
1064 getsel(int *al, int *ar, int dol)
1068 int first = *al < 0;
1073 if (quesarg == -1) {
1074 seterror(ERR_BADBANGARG);
1116 while (Isdigit(c)) {
1117 i = i * 10 + c - '0';
1139 if (*al > *ar || *ar > dol) {
1140 seterror(ERR_BADBANGARG);
1147 static struct wordent *
1156 c = (sc == HISTSUB && HISTSUB != '\0') ? (eChar)HIST : getC(0);
1157 if (c == (eChar)HIST) {
1171 if (lastev == eventno && alhistp)
1176 case '#': /* !# is command being typed in (mrh) */
1178 seterror(ERR_HISTLOOP);
1191 if (any("(=~", c)) {
1196 Strbuf_terminate(&lhsb);
1199 while (!cmap(c, _ESC | _META | _QF | _QB) && !any("^*-%${}:#", c)) {
1200 if (event != -1 && Isdigit(c))
1201 event = event * 10 + c - '0';
1204 Strbuf_append1(&lhsb, c);
1208 if (lhsb.len == 0) {
1209 lhsb.len = Strlen(lhsb.s); /* lhsb.s wasn't changed */
1213 Strbuf_terminate(&lhsb);
1216 * History had only digits
1219 event = eventno + (alhistp == 0) - event;
1223 Strbuf_append1(&lhsb, '\0'); /* Allocate space */
1224 Strbuf_terminate(&lhsb);
1225 memmove(lhsb.s + 1, lhsb.s, (lhsb.len - 1) * sizeof (*lhsb.s));
1228 hp = findev(lhsb.s, 0);
1234 Strbuf_terminate(&lhsb);
1244 Strbuf_append1(&lhsb, c);
1246 if (lhsb.len == 0) {
1247 lhsb.len = Strlen(lhsb.s); /* lhsb.s wasn't changed */
1248 if (lhsb.len == 0) {
1249 seterror(ERR_NOSEARCH);
1254 Strbuf_terminate(&lhsb);
1255 hp = findev(lhsb.s, 1);
1261 for (hp = Histlist.Hnext; hp; hp = hp->Hnext)
1262 if (hp->Hnum == event) {
1267 np = putn((tcsh_number_t)event);
1268 seterror(ERR_NOEVENT, short2str(np));
1273 static struct Hist *
1274 findev(Char *cp, int anyarg)
1278 for (hp = Histlist.Hnext; hp; hp = hp->Hnext) {
1281 struct wordent *lp = hp->Hlex.next;
1285 * The entries added by alias substitution don't have a newline but do
1286 * have a negative event number. Savehist() trims off these entries,
1287 * but it happens before alias expansion, too early to delete those
1288 * from the previous command.
1292 if (lp->word[0] == '\n')
1300 while (*p++ == *q++);
1304 for (dp = lp->word; *dp; dp++) {
1312 while (*p++ == *q++);
1316 } while (lp->word[0] != '\n');
1318 seterror(ERR_NOEVENT, short2str(cp));
1326 if (cp && cp[0] == '\n')
1334 peekread = (Char) c;
1341 static int sincereal; /* Number of real EOFs we've seen */
1346 if ((c = peekread) != 0) {
1356 xprintf("alvecp %c\n", *alvecp & 0xff);
1359 if ((c = *alvecp++) != 0)
1361 if (alvec && *alvec) {
1373 if ((alvecp = *alvec) != 0) {
1377 /* Infinite source! */
1383 if ((c = *evalp++) != 0)
1385 if (evalvec && *evalvec) {
1393 if (evalvec == INVPPTR) {
1397 if ((evalp = *evalvec) != 0) {
1405 if (arginp == INVPTR || onelflg == 1) {
1411 if ((c = *arginp++) == 0) {
1419 #endif /* BSDJOBS */
1421 if (c == CHAR_ERR) {
1422 #ifndef WINNT_NATIVE
1428 # endif /* TERMIO */
1432 #endif /* !WINNT_NATIVE */
1435 /* was isatty but raw with ignoreeof yields problems */
1436 #ifndef WINNT_NATIVE
1439 if (ioctl(SHIN, TCGETA, (ioctl_t) & tty) == 0 &&
1440 (tty.c_lflag & ICANON))
1442 if (ioctl(SHIN, TIOCGETP, (ioctl_t) & tty) == 0 &&
1443 (tty.sg_flags & RAW) == 0)
1444 # endif /* TERMIO */
1446 if (tcgetattr(SHIN, &tty) == 0 &&
1447 (tty.c_lflag & ICANON))
1449 #else /* WINNT_NATIVE */
1451 #endif /* !WINNT_NATIVE */
1455 #endif /* BSDJOBS */
1457 if (numeof != 0 && ++sincereal >= numeof) /* Too many EOFs? Bye! */
1461 (ctpgrp = tcgetpgrp(FSHTTY)) != -1 &&
1463 (void) tcsetpgrp(FSHTTY, tpgrp);
1466 # endif /* _SEQUENT */
1467 (void) killpg(ctpgrp, SIGHUP);
1470 * With the walking process group fix, this message
1471 * is now obsolete. As the foreground process group
1472 * changes, the shell needs to adjust. Well too bad.
1474 xprintf(CGETS(16, 1, "Reset tty pgrp from %d to %d\n"),
1475 (int)ctpgrp, (int)tpgrp);
1476 # endif /* notdef */
1479 #endif /* BSDJOBS */
1480 /* What follows is complicated EOF handling -- sterling@netcom.com */
1481 /* First, we check to see if we have ignoreeof set */
1482 if (adrof(STRignoreeof)) {
1483 /* If so, we check for any stopped jobs only on the first EOF */
1484 if ((sincereal == 1) && (chkstop == 0)) {
1488 /* If we don't have ignoreeof set, always check for stopped jobs */
1493 /* At this point, if there were stopped jobs, we would have already
1494 * called reset(). If we got this far, assume we can print an
1495 * exit/logout message if we ignoreeof, or just exit.
1497 if (adrof(STRignoreeof)) {
1498 /* If so, tell the user to use exit or logout */
1500 xprintf("%s", CGETS(16, 2,
1501 "\nUse \"logout\" to logout.\n"));
1503 xprintf(CGETS(16, 3,
1504 "\nUse \"exit\" to leave %s.\n"),
1509 /* If we don't have ignoreeof set, just fall through */
1518 if (c == '\n' && onelflg)
1521 Strbuf_append1(&histline, c);
1530 while (buf >= fblocks) {
1531 nfbuf = xcalloc(fblocks + 2, sizeof(Char **));
1533 (void) blkcpy(nfbuf, fbuf);
1537 fbuf[fblocks] = xcalloc(BUFSIZE, sizeof(Char));
1543 wide_read(int fildes, Char *buf, size_t nchars, int use_fclens)
1545 char cbuf[BUFSIZE + 1];
1552 assert (nchars <= sizeof(cbuf) / sizeof(*cbuf));
1558 size_t len = nchars > partial ? nchars - partial : 1;
1560 if (partial + len >= sizeof(cbuf) / sizeof(*cbuf))
1563 r = xread(fildes, cbuf + partial, len);
1565 if (partial == 0 && r <= 0)
1569 while (i < partial && nchars != 0) {
1572 tlen = normal_mbtowc(buf + res, cbuf + i, partial - i);
1575 if ((partial - i) < MB_LEN_MAX && r > 0)
1576 /* Maybe a partial character and there is still a chance
1579 buf[res] = (unsigned char)cbuf[i] | INVALID_BYTE;
1592 memmove(cbuf, cbuf + i, partial - i);
1594 } while (partial != 0 && nchars > 0);
1595 /* Throwing away possible partial multibyte characters on error if the
1596 stream is not seekable */
1598 lseek(fildes, -(off_t)partial, L_INCR);
1600 return res != 0 ? res : r;
1608 int numleft = 0, roomleft;
1611 if (fseekp < fbobp || fseekp > feobp) {
1612 fbobp = feobp = fseekp;
1613 (void) lseek(SHIN, fseekp, L_SET);
1615 if (fseekp == feobp) {
1621 for (i = 0; i < (size_t)(feobp - fbobp); i++)
1623 fseekp = feobp = bytes;
1626 c = wide_read(SHIN, fbuf[0], BUFSIZE, 1);
1629 stderror(ERR_SYSTEM, progname, strerror(errno));
1635 #if !defined(WINNT_NATIVE) && !defined(__CYGWIN__)
1636 ch = fbuf[0][fseekp - fbobp];
1640 ch = fbuf[0][fseekp - fbobp];
1642 } while(ch == '\r');
1643 #endif /* !WINNT_NATIVE && !__CYGWIN__ */
1647 while (fseekp >= feobp) {
1649 #if defined(FILEC) && defined(TIOCSTI)
1651 #endif /* FILEC && TIOCSTI */
1652 ) && intty) { /* then use twenex routine */
1653 fseekp = feobp; /* where else? */
1654 #if defined(FILEC) && defined(TIOCSTI)
1656 c = numleft = tenex(InputBuf, BUFSIZE);
1658 #endif /* FILEC && TIOCSTI */
1659 c = numleft = Inputl(); /* PWP: get a line */
1660 while (numleft > 0) {
1661 off = (int) feobp % BUFSIZE;
1662 buf = (int) feobp / BUFSIZE;
1664 roomleft = BUFSIZE - off;
1665 if (roomleft > numleft)
1667 (void) memcpy(fbuf[buf] + off, InputBuf + c - numleft,
1668 roomleft * sizeof(Char));
1669 numleft -= roomleft;
1673 off = (int) feobp % BUFSIZE;
1674 buf = (int) feobp / BUFSIZE;
1676 roomleft = BUFSIZE - off;
1677 c = wide_read(SHIN, fbuf[buf] + off, roomleft, 0);
1681 if (c == 0 || (c < 0 && fixio(SHIN, errno) == -1))
1686 (void) check_window_size(0); /* for window systems */
1687 #endif /* SIG_WINDOW */
1688 #if !defined(WINNT_NATIVE) && !defined(__CYGWIN__)
1689 ch = fbuf[(int) fseekp / BUFSIZE][(int) fseekp % BUFSIZE];
1693 ch = fbuf[(int) fseekp / BUFSIZE][(int) fseekp % BUFSIZE];
1695 } while(ch == '\r');
1696 #endif /* !WINNT_NATIVE && !__CYGWIN__ */
1709 sb = (int) (fseekp - 1) / BUFSIZE;
1711 for (i = 0; i < sb; i++)
1713 (void) blkcpy(fbuf, &fbuf[sb]);
1714 fseekp -= BUFSIZE * sb;
1715 feobp -= BUFSIZE * sb;
1721 bseek(struct Ain *l)
1723 switch (aret = l->type) {
1725 evalvec = l->a_seek;
1728 xprintf(CGETS(16, 4, "seek to eval %x %x\n"), evalvec, evalp);
1735 xprintf(CGETS(16, 5, "seek to alias %x %x\n"), alvec, alvecp);
1740 xprintf(CGETS(16, 6, "seek to file %x\n"), fseekp);
1745 if (fseekp >= fbobp && feobp >= fbobp) {
1750 for (i = 0; i < (size_t)(feobp - fbobp); i++) {
1762 fbobp = feobp = fseekp + 1; /* To force lseek() */
1767 xprintf(CGETS(16, 7, "Bad seek type %d\n"), aret);
1772 /* any similarity to bell telephone is purely accidental */
1774 btell(struct Ain *l)
1776 switch (l->type = aret) {
1778 l->a_seek = evalvec;
1781 xprintf(CGETS(16, 8, "tell eval %x %x\n"), evalvec, evalp);
1788 xprintf(CGETS(16, 9, "tell alias %x %x\n"), alvec, alvecp);
1793 if (cantell && fseekp >= fbobp && fseekp <= feobp) {
1797 for (i = 0; i < (size_t)(fseekp - fbobp); i++)
1798 l->f_seek += fclens[i];
1805 xprintf(CGETS(16, 10, "tell file %x\n"), fseekp);
1809 xprintf(CGETS(16, 7, "Bad seek type %d\n"), aret);
1817 (void) lseek(SHIN, (off_t) 0, L_XTND);
1833 if (arginp || onelflg || intty)
1835 if ((x = lseek(SHIN, (off_t) 0, L_INCR)) == -1)
1837 fbuf = xcalloc(2, sizeof(Char **));
1839 fbuf[0] = xcalloc(BUFSIZE, sizeof(Char));
1840 fseekp = fbobp = feobp = x;