Skip to content

Commit 84b2fde

Browse files
authored
Improve resource deallocation (#343)
Upon failure, resources allocated by elf_open() must be appropriately released. This commit simplifies the error-handling process and corrects an oversight by including a missing close(fd). Co-authored-by: Chun-Hung Tseng <[email protected]>
1 parent eb453e9 commit 84b2fde

File tree

1 file changed

+19
-16
lines changed

1 file changed

+19
-16
lines changed

src/elf.c

Lines changed: 19 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -300,8 +300,7 @@ bool elf_open(elf_t *e, const char *input)
300300
#if HAVE_MMAP
301301
int fd = open(path, O_RDONLY);
302302
if (fd < 0) {
303-
free(path);
304-
return false;
303+
goto free_path;
305304
}
306305

307306
/* get file size */
@@ -314,27 +313,22 @@ bool elf_open(elf_t *e, const char *input)
314313
*/
315314
e->raw_data = mmap(0, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
316315
if (e->raw_data == MAP_FAILED) {
317-
release(e);
318-
free(path);
319-
return false;
316+
goto free_fd;
320317
}
321318
close(fd);
322319

323320
#else /* fallback to standard I/O text stream */
324321
FILE *f = fopen(path, "rb");
325322
if (!f) {
326-
free(path);
327-
return false;
323+
goto free_path;
328324
}
329325

330326
/* get file size */
331327
fseek(f, 0, SEEK_END);
332328
e->raw_size = ftell(f);
333329
fseek(f, 0, SEEK_SET);
334330
if (e->raw_size == 0) {
335-
fclose(f);
336-
free(path);
337-
return false;
331+
goto free_fd;
338332
}
339333

340334
/* allocate memory */
@@ -346,9 +340,7 @@ bool elf_open(elf_t *e, const char *input)
346340
const size_t r = fread(e->raw_data, 1, e->raw_size, f);
347341
fclose(f);
348342
if (r != e->raw_size) {
349-
release(e);
350-
free(path);
351-
return false;
343+
goto free_path;
352344
}
353345
#endif /* HAVE_MMAP */
354346

@@ -357,13 +349,24 @@ bool elf_open(elf_t *e, const char *input)
357349

358350
/* check it is a valid ELF file */
359351
if (!is_valid(e)) {
360-
release(e);
361-
free(path);
362-
return false;
352+
goto free_path;
363353
}
364354

365355
free(path);
366356
return true;
357+
358+
free_fd:
359+
#if HAVE_MMAP
360+
close(fd);
361+
#else
362+
close(f);
363+
#endif
364+
365+
free_path:
366+
free(path);
367+
368+
release(e);
369+
return false;
367370
}
368371

369372
struct Elf32_Ehdr *get_elf_header(elf_t *e)

0 commit comments

Comments
 (0)