Skip to content

gc: support user-defined OOM callback #14

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 17, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions py/gc.c
Original file line number Diff line number Diff line change
Expand Up @@ -455,6 +455,15 @@ void gc_info(gc_info_t *info) {
GC_EXIT();
}

#if MICROPY_OOM_CALLBACK
static gc_oom_callback_t gc_oom_callback = NULL;

void gc_set_oom_callback(gc_oom_callback_t func)
{
gc_oom_callback = func;
}
#endif

void *gc_alloc(size_t n_bytes, unsigned int alloc_flags) {
bool has_finaliser = alloc_flags & GC_ALLOC_FLAG_HAS_FINALISER;
size_t n_blocks = ((n_bytes + BYTES_PER_BLOCK - 1) & (~(BYTES_PER_BLOCK - 1))) / BYTES_PER_BLOCK;
Expand Down Expand Up @@ -504,6 +513,11 @@ void *gc_alloc(size_t n_bytes, unsigned int alloc_flags) {
GC_EXIT();
// nothing found!
if (collected) {
#if MICROPY_OOM_CALLBACK
if (gc_oom_callback) {
gc_oom_callback();
}
#endif
return NULL;
}
DEBUG_printf("gc_alloc(" UINT_FMT "): no free mem, triggering GC\n", n_bytes);
Expand Down
6 changes: 6 additions & 0 deletions py/gc.h
Original file line number Diff line number Diff line change
Expand Up @@ -73,4 +73,10 @@ void gc_dump_alloc_table(void);
extern size_t alloc_count;
#endif

#if MICROPY_OOM_CALLBACK
typedef void (*gc_oom_callback_t)(void);

void gc_set_oom_callback(gc_oom_callback_t func);
#endif

#endif // MICROPY_INCLUDED_PY_GC_H
1 change: 1 addition & 0 deletions py/mpprint.c
Original file line number Diff line number Diff line change
Expand Up @@ -536,6 +536,7 @@ int mp_vprintf(const mp_print_t *print, const char *fmt, va_list args) {
}
case 'p':
case 'P': // don't bother to handle upcase for 'P'
chrs += mp_print_str(print, "0x"); // used by meminfo JSON dumps
// Use unsigned long int to work on both ILP32 and LP64 systems
chrs += mp_print_int(print, va_arg(args, unsigned long int), 0, 16, 'a', flags, fill, width);
break;
Expand Down
Loading