Skip to content

Commit b56e02a

Browse files
committed
Make bar generation bound-safe
This replaces strncat-based appends in gen_hist_bar with bounded memcpy while tracking remaining capacity and always NUL-terminating.
1 parent f29a741 commit b56e02a

File tree

1 file changed

+33
-6
lines changed

1 file changed

+33
-6
lines changed

tools/rv_histogram.c

Lines changed: 33 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -132,13 +132,40 @@ static char *gen_hist_bar(char *hist_bar,
132132
hist_bar[v] = 0;
133133
#else
134134
const char *a[] = {" ", "▏", "▎", "▍", "▌", "▋", "▊", "▉", "█"};
135-
size_t v = insn_freq * (max_col - used_col) * 8 / max_insn_freq;
136-
hist_bar[0] = '\0';
137-
while (v > 8) {
138-
strncat(hist_bar, a[8], hist_bar_len--);
139-
v -= 8;
135+
size_t units = insn_freq * (max_col - used_col) * 8 / max_insn_freq;
136+
size_t full = units / 8; /* count of full blocks */
137+
size_t rem = units % 8; /* remainder block index */
138+
139+
char *p = hist_bar;
140+
size_t remaining = hist_bar_len;
141+
142+
if (remaining == 0)
143+
return hist_bar;
144+
145+
/* Append full blocks safely */
146+
for (size_t i = 0; i < full; i++) {
147+
const char *blk = a[8];
148+
size_t glyph_len = strlen(blk); /* UTF-8, typically 3 bytes */
149+
if (glyph_len + 1 > remaining)
150+
break; /* not enough space for this glyph + NUL */
151+
memcpy(p, blk, glyph_len);
152+
p += glyph_len;
153+
remaining -= glyph_len;
140154
}
141-
strncat(hist_bar, a[v], hist_bar_len--);
155+
156+
/* Append remainder block if any */
157+
if (rem > 0) {
158+
const char *blk = a[rem];
159+
size_t glyph_len = strlen(blk);
160+
if (glyph_len + 1 <= remaining) {
161+
memcpy(p, blk, glyph_len);
162+
p += glyph_len;
163+
remaining -= glyph_len;
164+
}
165+
}
166+
167+
/* NUL-terminate */
168+
*p = '\0';
142169
#endif
143170

144171
return hist_bar;

0 commit comments

Comments
 (0)