From 64f64b5c5066131f31c5d48f77c76a9fc78ca699 Mon Sep 17 00:00:00 2001 From: Davide Bettio Date: Sun, 29 Dec 2024 13:03:21 +0100 Subject: [PATCH 1/2] `globalcontext_make_atom` may return an invalid term globalcontext_make_atom may allocate memory, and that operation might fail. In that situation now the function returns an invalid term that must be checked (so an out of memory error can be raised). Signed-off-by: Davide Bettio --- CHANGELOG.md | 4 ++++ src/libAtomVM/globalcontext.h | 6 +++++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9e436e129..1faa4fcab 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Added `net:gethostname/0` on platforms with gethostname(3). - Added `socket:getopt/2` +### Changed +- `globalcontext_make_atom` might return an invalid term when memory allocation fails. Therefore +return value must be checked (e.g. using `term_is_invalid_term()`) + ### Fixed - ESP32: improved sntp sync speed from a cold boot. diff --git a/src/libAtomVM/globalcontext.h b/src/libAtomVM/globalcontext.h index 2fa136370..c780f0d33 100644 --- a/src/libAtomVM/globalcontext.h +++ b/src/libAtomVM/globalcontext.h @@ -412,11 +412,15 @@ static inline bool globalcontext_is_term_equal_to_atom_string(GlobalContext *glo * global context. * @param glb pointer to the global context * @param string an AtomString - * @return an atom term formed from the supplied atom string. + * @return an atom term formed from the supplied atom string, or an invalid term when out of memory */ static inline term globalcontext_make_atom(GlobalContext *glb, AtomString string) { int global_atom_index = globalcontext_insert_atom(glb, string); + if (UNLIKELY(global_atom_index < 0)) { + return term_invalid_term(); + } + return term_from_atom_index(global_atom_index); } From 852709ee4f9b40108fbc93ce50fe85758bc7aeb9 Mon Sep 17 00:00:00 2001 From: Davide Bettio Date: Sun, 29 Dec 2024 13:07:55 +0100 Subject: [PATCH 2/2] NIFs: add macro for requiring an atom Add macro that raises an error when there is an out of memory while making an atom, otherwise a term with given name is declared and available. Signed-off-by: Davide Bettio --- src/libAtomVM/nifs.h | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/libAtomVM/nifs.h b/src/libAtomVM/nifs.h index d3161d0ea..1373703cf 100644 --- a/src/libAtomVM/nifs.h +++ b/src/libAtomVM/nifs.h @@ -46,6 +46,12 @@ extern "C" { ctx->x[1] = (error_type_atom); \ return term_invalid_term(); +#define REQUIRE_ATOM(name, lenstr, str, glb) \ + term name = globalcontext_make_atom(glb, lenstr str); \ + if (UNLIKELY(term_is_invalid_term(name))) { \ + RAISE_ERROR(OUT_OF_MEMORY_ATOM); \ + } + const struct Nif *nifs_get(AtomString module, AtomString function, int arity); #ifdef __cplusplus