Skip to content

Commit

Permalink
Fix block memory leak
Browse files Browse the repository at this point in the history
-fsanitize=address report when CTRL+a x exiting:
=================================================================
==297977==ERROR: LeakSanitizer: detected memory leaks

Direct leak of 23400 byte(s) in 117 object(s) allocated from:
    #0 0x761b706fd340 in calloc ../../../../src/libsanitizer/asan/asan_malloc_linux.cpp:77
    #1 0x633ad9c5e310 in block_translate src/emulate.c:649
    #2 0x633ad9c5e310 in block_find_or_translate src/emulate.c:865
    #3 0x633ad9c5e310 in rv_step src/emulate.c:1029
    #4 0x633ad9c5e310 in rv_run src/riscv.c:498
    #5 0x633ad9c5e310 in main src/main.c:279

Direct leak of 3136 byte(s) in 125 object(s) allocated from:
    #0 0x761b706fd9c7 in malloc ../../../../src/libsanitizer/asan/asan_malloc_linux.cpp:69
    #1 0x633ad9c5fea4 in match_pattern src/emulate.c:767
    #2 0x633ad9c5fea4 in block_find_or_translate src/emulate.c:872
    #3 0x633ad9c5fea4 in rv_step src/emulate.c:1029
    #4 0x633ad9c5fea4 in rv_run src/riscv.c:498
    #5 0x633ad9c5fea4 in main src/main.c:279

Register a clean up callback, async_block_clear() to free all the
allocated memory fix this when emulator exits.
  • Loading branch information
ChinYikMing committed Dec 10, 2024
1 parent b4329fb commit 2657bdc
Showing 1 changed file with 21 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/riscv.c
Original file line number Diff line number Diff line change
Expand Up @@ -300,13 +300,34 @@ static void capture_keyboard_input()
}
#endif

/*
*
* atexit() registers void (*)(void) callbacks, so no parameters can be passed.
* Memory must be freed at runtime. block_map_clear() requires a RISC-V instance
* and runs in interpreter mode. Instead of modifying its signature, access the
* global RISC-V instance in main.c with external linkage.
*
*/
extern riscv_t *rv;
static void async_block_clear()
{
#if !RV32_HAS(JIT)
if (rv && rv->block_map.size)
block_map_clear(rv);
#else /* TODO: JIT mode */
return;
#endif /* !RV32_HAS(JIT) */
}

riscv_t *rv_create(riscv_user_t rv_attr)
{
assert(rv_attr);

riscv_t *rv = calloc(1, sizeof(riscv_t));
assert(rv);

atexit(async_block_clear);

/* copy over the attr */
rv->data = rv_attr;

Expand Down

0 comments on commit 2657bdc

Please sign in to comment.