Use _init_called bool variable in elf object, initialize to false, set to true
at end of run_init_funcs(), in run_fini_funcs() only call fini functions if
_init_called has been set to true. Avoids page fault case by only calling fini
functions for modules who's init functions were called for. Instead throws
corresponding exception and error message is shown.

Signed-off-by: AubreyTurner <aubreyt1...@gmail.com>
---
 core/elf.cc        | 6 ++++--
 include/osv/elf.hh | 1 +
 2 files changed, 5 insertions(+), 2 deletions(-)

diff --git a/core/elf.cc b/core/elf.cc
index 80bfd841..418aa10f 100644
--- a/core/elf.cc
+++ b/core/elf.cc
@@ -123,6 +123,7 @@ object::object(program& prog, std::string pathname)
     , _dynamic_table(nullptr)
     , _module_index(_prog.register_dtv(this))
     , _is_executable(false)
+    , _init_called(false)
     , _visibility_thread(nullptr)
     , _visibility_level(VisibilityLevel::Public)
 {
@@ -1178,12 +1179,13 @@ void object::run_init_funcs(int argc, char** argv)
         }
         elf_debug("Finished executing %d DT_INIT_ARRAYSZ functions\n", nr);
     }
+    _init_called = true;
 }
 
 // Run the object's static destructors or similar finalization
 void object::run_fini_funcs()
 {
-    if (dynamic_exists(DT_FINI_ARRAY)) {
+    if (dynamic_exists(DT_FINI_ARRAY) && _init_called) {
         auto funcs = dynamic_ptr<void (*)()>(DT_FINI_ARRAY);
         auto nr = dynamic_val(DT_FINI_ARRAYSZ) / sizeof(*funcs);
         elf_debug("Executing %d DT_FINI_ARRAYSZ functions\n", nr);
@@ -1193,7 +1195,7 @@ void object::run_fini_funcs()
         }
         elf_debug("Finished executing %d DT_FINI_ARRAYSZ functions\n", nr);
     }
-    if (dynamic_exists(DT_FINI)) {
+    if (dynamic_exists(DT_FINI) && _init_called) {
         auto func = dynamic_ptr<void>(DT_FINI);
         if (func) {
             elf_debug("Executing DT_FINI function\n");
diff --git a/include/osv/elf.hh b/include/osv/elf.hh
index ae6ff786..afc9c9a5 100644
--- a/include/osv/elf.hh
+++ b/include/osv/elf.hh
@@ -435,6 +435,7 @@ protected:
     std::unique_ptr<char[]> _section_names_cache;
     bool _is_executable;
     bool is_core();
+    bool _init_called;
 
     std::unordered_map<std::string,void*> _cached_symbols;
 
-- 
2.30.2

-- 
You received this message because you are subscribed to the Google Groups "OSv 
Development" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to osv-dev+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/osv-dev/20211209071458.35108-1-aubreyt1231%40gmail.com.

Reply via email to