Fix logic error in macro file reader

The old logic always finished adding lines if an empty line
was encountered, because the check that should guard against
accessing outside of the read buffer was done at the wrong
level.

Also simplify the code by letting 'q' point to the new line and
not before the newline, which also fixes potential undefined
behaviour.

Also get rid of the unused 'nread' variable.
This commit is contained in:
Michael Schroeder 2021-03-26 12:08:38 +01:00 committed by Panu Matilainen
parent e838c489db
commit 75275a87cf
1 changed files with 10 additions and 10 deletions

View File

@ -209,24 +209,24 @@ findEntry(rpmMacroContext mc, const char *name, size_t namelen, size_t *pos)
static int static int
rdcl(char * buf, size_t size, FILE *f) rdcl(char * buf, size_t size, FILE *f)
{ {
char *q = buf - 1; /* initialize just before buffer. */
size_t nb = 0; size_t nb = 0;
size_t nread = 0;
int pc = 0, bc = 0, xc = 0; int pc = 0, bc = 0, xc = 0;
int nlines = 0; int nlines = 0;
char *p = buf; char *p = buf;
char *q = buf;
if (f != NULL) if (f != NULL)
do { do {
*(++q) = '\0'; /* terminate and move forward. */ *q = '\0'; /* terminate */
if (fgets(q, size, f) == NULL) /* read next line. */ if (fgets(q, size, f) == NULL) /* read next line. */
break; break;
nlines++; nlines++;
nb = strlen(q); nb = strlen(q);
nread += nb; /* trim trailing \r and \n */ for (q += nb; nb > 0 && iseol(q[-1]); q--)
for (q += nb - 1; nb > 0 && iseol(*q); q--)
nb--; nb--;
for (; p <= q; p++) { if (*q == 0)
break; /* no newline found, EOF */
for (; p < q; p++) {
switch (*p) { switch (*p) {
case '\\': case '\\':
switch (*(p+1)) { switch (*(p+1)) {
@ -250,14 +250,14 @@ rdcl(char * buf, size_t size, FILE *f)
case ']': if (xc > 0) xc--; break; case ']': if (xc > 0) xc--; break;
} }
} }
if (nb == 0 || (*q != '\\' && !bc && !pc && !xc) || *(q+1) == '\0') { if ((nb == 0 || q[-1] != '\\') && !bc && !pc && !xc) {
*(++q) = '\0'; /* trim trailing \r, \n */ *q = '\0'; /* trim trailing \r, \n */
break; break;
} }
q++; nb++; /* copy newline too */ q++; nb++; /* copy newline too */
size -= nb; size -= nb;
if (*q == '\r') /* XXX avoid \r madness */ if (q[-1] == '\r') /* XXX avoid \r madness */
*q = '\n'; q[-1] = '\n';
} while (size > 0); } while (size > 0);
return nlines; return nlines;
} }