diff --git a/src/tools/imgtool/imgtool.cpp b/src/tools/imgtool/imgtool.cpp index 5c7f3996e21..8141d2cb656 100644 --- a/src/tools/imgtool/imgtool.cpp +++ b/src/tools/imgtool/imgtool.cpp @@ -1024,7 +1024,9 @@ imgtoolerr_t imgtool::image::internal_open(const imgtool_module *module, const c goto done; } - // we've succeeded - set the output image + // we've succeeded - set the output image, and record that + // we are "okay to close" + image->m_okay_to_close = true; outimg = std::move(image); done: @@ -1072,6 +1074,7 @@ imgtool::image::image(const imgtool_module &module, object_pool *pool, void *ext : m_module(module) , m_pool(pool) , m_extra_bytes(extra_bytes) + , m_okay_to_close(false) { } @@ -1082,7 +1085,7 @@ imgtool::image::image(const imgtool_module &module, object_pool *pool, void *ext imgtool::image::~image() { - if (module().close) + if (m_okay_to_close && module().close) module().close(this); pool_free_lib(m_pool); } diff --git a/src/tools/imgtool/imgtool.h b/src/tools/imgtool/imgtool.h index ab4d28ab44b..e9da350a050 100644 --- a/src/tools/imgtool/imgtool.h +++ b/src/tools/imgtool/imgtool.h @@ -123,6 +123,11 @@ namespace imgtool object_pool *m_pool; void *m_extra_bytes; + // because of an idiosycracy of how imgtool::image::internal_open() works, we are only "okay to close" + // by invoking the module's close function once internal_open() succeeds. the long term solution is + // better C++ adoption (e.g. - std::unique_ptr<>, std:move() etc) + bool m_okay_to_close; + static imgtoolerr_t internal_open(const imgtool_module *module, const char *fname, int read_or_write, util::option_resolution *createopts, imgtool::image::ptr &outimg); };