Skip to content

Commit 7aaf8a6

Browse files
authored
Merge pull request #554 from drzymalanet/master
Fix two UAF errors in read_ihex_chunks()
2 parents ec34106 + e473c83 commit 7aaf8a6

File tree

1 file changed

+13
-5
lines changed

1 file changed

+13
-5
lines changed

simavr/sim/sim_hex.c

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,7 @@ read_ihex_chunks(
8484
fw_chunk_t ** chunks_p )
8585
{
8686
fw_chunk_t *chunk = *chunks_p;
87+
fw_chunk_t *backlink_p = chunk;
8788
int len, allocation = 0;
8889
uint8_t chk = 0;
8990
uint8_t bline[272];
@@ -150,7 +151,7 @@ read_ihex_chunks(
150151
}
151152
if (!chunk || (chunk->size && addr != chunk->addr + chunk->size)) {
152153
/* New chunk. */
153-
154+
backlink_p = chunk;
154155
allocation = ALLOCATION - sizeof *chunk + 1;
155156
chunk = (fw_chunk_t *)malloc(ALLOCATION);
156157
*chunks_p = chunk;
@@ -170,6 +171,12 @@ read_ihex_chunks(
170171

171172
allocation += INCREMENT;
172173
chunk = realloc(chunk, allocation + (sizeof *chunk - 1));
174+
175+
/* Update the pointer in the previous list element */
176+
if ( backlink_p ) backlink_p->next = chunk;
177+
178+
/* Refresh the pointer to the future chunk */
179+
chunks_p = &chunk->next;
173180
}
174181
memcpy(chunk->data + chunk->size, bline + 4, bline[0]);
175182
chunk->size += bline[0];
@@ -178,7 +185,6 @@ read_ihex_chunks(
178185
fclose(f);
179186
}
180187

181-
182188
uint8_t *
183189
read_ihex_file(
184190
const char * fname, uint32_t * dsize, uint32_t * start)
@@ -255,10 +261,10 @@ sim_setup_firmware(const char * filename, uint32_t loadBase,
255261
}
256262

257263
#ifdef IHEX_TEST
258-
// gcc -std=gnu99 -Isimavr/sim simavr/sim/sim_hex.c -o sim_hex -DIHEX_TEST -Dtest_main=main
264+
// gcc -std=gnu99 -Isimavr/sim simavr/sim/sim_hex.c -o sim_hex -DIHEX_TEST -Dtest_main=main -fsanitize=address -fno-omit-frame-pointer -O1 -g
259265
int test_main(int argc, char * argv[])
260266
{
261-
fw_chunk_t *chunks;
267+
fw_chunk_t *chunks, *next_chunk;
262268
int fi;
263269

264270
for (fi = 1; fi < argc; fi++) {
@@ -274,7 +280,9 @@ int test_main(int argc, char * argv[])
274280
snprintf(n, sizeof n, "%s[%d] = %08x",
275281
argv[fi], ci, chunks->addr);
276282
hdump(n, chunks->data, chunks->size);
277-
chunks = chunks->next;
283+
next_chunk = chunks->next;
284+
free(chunks);
285+
chunks = next_chunk;
278286
}
279287
}
280288
return 0;

0 commit comments

Comments
 (0)