Skip to content
Myr

Work around fgets()'s lack of length reporting

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Stop losing \0s from the end of files because we don't know how much fgets() read into our buffer. If we prefill the buffer with anything other than zeroes, we can actually tell the difference between the terminator and unused space in the buffer. This is possibly more expensive, but at least it should be correct. Fixes #1504

authored by Muh Muhten · committed by Nico Williams · parent 048acee · Browse files · 1 file+9 added−7 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+9 added−7 removed

  • other:+9 added−7 removed

1 file+9 added−7 removed

modified:src/util.c+9 added-7 removed
307 unmodified lines
308 state->buf[0] = 0;309 state->buf_valid_len = 0;310 if (state->current_input) {311 char *res;312 memset(state->buf, 0, sizeof(state->buf));312 memset(state->buf, 0xff, sizeof(state->buf));313314 while (!(res = fgets(state->buf, sizeof(state->buf), state->current_input)) &&315 ferror(state->current_input) && errno == EINTR)316 clearerr(state->current_input);
16 unmodified lines
333 } else if (p == NULL && feof(state->current_input)) {334 size_t i;335336 /*337 * XXX We can't know how many bytes we've read!337 * XXX We don't know how many bytes we've read!338 *339 * We can't use getline() because there need not be any newlines340 * in the input. The only entirely correct choices are: use341 * fgetc() or fread(). Using fread() will complicate buffer342 * management here.343 *344 * For now we guess how much fgets() read.344 * For now we check how much fgets() read by scanning backwards for the345 * terminating '\0'. This only works because we previously memset our346 * buffer with something nonzero.347 */346 for (p = state->buf, i = 0; i < sizeof(state->buf); i++) {347 if (state->buf[i] != '\0')348 p = &state->buf[i];348 for (p = state->buf, i = sizeof(state->buf) - 1; i > 0; i--) {349 if (state->buf[i] == '\0')350 break;351 }350 state->buf_valid_len = p - state->buf + 1;352 state->buf_valid_len = i;353 } else if (p == NULL) {354 state->buf_valid_len = sizeof(state->buf) - 1;355 } else {356 state->buf_valid_len = (p - state->buf) + 1;
111 unmodified lines