[PATCH 2/2] Using NJS_MALLOC() in functions that create new objects.

Alejandro Colomar alx.manpages at gmail.com
Mon Jan 30 13:35:55 UTC 2023

NGINX Unit introduced a memory leak recently due to forgetting to call
the destructor.  This could probably have been warned at compile time,
or maybe at link time, by the compiler, if we had used the GNU
attribute.  Let's use it to prevent misuse of the APIs.  It also helps
self-document through source code how they should be used properly.

The bug in Unit was found by Liam Crilly.

Cc: Liam Crilly <liam at nginx.com>
Cc: Zhidao Hong <z.hong at f5.com>
Signed-off-by: Alejandro Colomar <alx at nginx.com>
 src/njs.h | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)

diff --git a/src/njs.h b/src/njs.h
index 95c4125..86b5a8a 100644
--- a/src/njs.h
+++ b/src/njs.h
@@ -306,15 +306,17 @@ typedef struct {
 NJS_EXPORT void njs_vm_opt_init(njs_vm_opt_t *options);
-NJS_EXPORT njs_vm_t *njs_vm_create(njs_vm_opt_t *options);
 NJS_EXPORT void njs_vm_destroy(njs_vm_t *vm);
+NJS_EXPORT NJS_MALLOC(njs_vm_destroy) njs_vm_t *njs_vm_create(
+    njs_vm_opt_t *options);
 NJS_EXPORT njs_int_t njs_vm_compile(njs_vm_t *vm, u_char **start, u_char *end);
 NJS_EXPORT njs_mod_t *njs_vm_add_module(njs_vm_t *vm, njs_str_t *name,
     njs_value_t *value);
 NJS_EXPORT njs_mod_t *njs_vm_compile_module(njs_vm_t *vm, njs_str_t *name,
     u_char **start, u_char *end);
-NJS_EXPORT njs_vm_t *njs_vm_clone(njs_vm_t *vm, njs_external_ptr_t external);
+NJS_EXPORT NJS_MALLOC(njs_vm_destroy) njs_vm_t *njs_vm_clone(njs_vm_t *vm,
+    njs_external_ptr_t external);
 NJS_EXPORT njs_vm_event_t njs_vm_add_event(njs_vm_t *vm,
     njs_function_t *function, njs_uint_t once, njs_host_event_t host_ev,

More information about the nginx-devel mailing list