Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

I'm not entirely happy with Xi Wang's solution to this mess.

The cast to (unsigned) feels like we're just exploiting
a compiler limitation.
The original idea here was to detect overflow and therefore
avoid hard-coding assumptions about the platform arithmetic.
But allowing compilers to assume that overflow can never happen
means that portable C code can never really detect overflow
without hackish workarounds.

The only practical solution seems to be an arbitrary limit
on the size of a string that we can format.
  • Loading branch information...
commit ce39cb40953a110eafe6c80b292e545ffa2e7963 1 parent ff1e307
Tim Kientzle kientzle authored

Showing 1 changed file with 6 additions and 11 deletions. Show diff stats Hide diff stats

  1. +6 11 tar/util.c
17 tar/util.c
@@ -120,16 +120,12 @@ safe_fprintf(FILE *f, const char *fmt, ...)
120 120 fmtbuff_length = length+1;
121 121 else if (fmtbuff_length < 8192)
122 122 fmtbuff_length *= 2;
  123 + else if (fmtbuff_length < 1000000)
  124 + fmtbuff_length += fmtbuff_length / 4;
123 125 else {
124   - int old_length = fmtbuff_length;
125   - /* Convert to unsigned to avoid signed overflow,
126   - * otherwise the check may be optimized away. */
127   - fmtbuff_length += (unsigned)fmtbuff_length / 4;
128   - if (old_length > fmtbuff_length) {
129   - length = old_length;
130   - fmtbuff_heap[length-1] = '\0';
131   - break;
132   - }
  126 + length = old_length;
  127 + fmtbuff_heap[length-1] = '\0';
  128 + break;
133 129 }
134 130 free(fmtbuff_heap);
135 131 fmtbuff_heap = malloc(fmtbuff_length);
@@ -153,8 +149,7 @@ safe_fprintf(FILE *f, const char *fmt, ...)
153 149 if (mbtowc(NULL, NULL, 1) == -1) { /* Reset the shift state. */
154 150 /* NOTE: This case may not happen, but it needs to be compiled
155 151 * safely without warnings by both gcc on linux and clang. */
156   - if (fmtbuff_heap != NULL)
157   - free(fmtbuff_heap);
  152 + free(fmtbuff_heap);
158 153 return;
159 154 }
160 155

0 comments on commit ce39cb4

Please sign in to comment.
Something went wrong with that request. Please try again.