LCOV - code coverage report
Current view: top level - source/ps - DllLoader.cpp (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 40 64 62.5 %
Date: 2026-12-03 01:19:39 Functions: 8 10 80.0 %

          Line data    Source code
       1             : /* Copyright (C) 2026 Wildfire Games.
       2             :  * This file is part of 0 A.D.
       3             :  *
       4             :  * 0 A.D. is free software: you can redistribute it and/or modify
       5             :  * it under the terms of the GNU General Public License as published by
       6             :  * the Free Software Foundation, either version 2 of the License, or
       7             :  * (at your option) any later version.
       8             :  *
       9             :  * 0 A.D. is distributed in the hope that it will be useful,
      10             :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      11             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      12             :  * GNU General Public License for more details.
      13             :  *
      14             :  * You should have received a copy of the GNU General Public License
      15             :  * along with 0 A.D.  If not, see <http://www.gnu.org/licenses/>.
      16             :  */
      17             : 
      18             : #include "precompiled.h"
      19             : 
      20             : #include "DllLoader.h"
      21             : 
      22             : #include "lib/code_annotation.h"
      23             : #include "lib/debug.h"
      24             : #include "lib/posix/posix_dlfcn.h"
      25             : #include "lib/sysdep/os.h"
      26             : #include "ps/Profiler2.h"
      27             : 
      28             : #include <cstddef>
      29             : #include <sstream>
      30             : #include <string>
      31             : 
      32             : #if OS_MACOSX
      33             : # include "lib/sysdep/os/osx/osx_bundle.h"
      34             : #endif
      35             : 
      36             : static void* const HANDLE_UNAVAILABLE = (void*)-1;
      37             : 
      38             : // directory to search for libraries (optionally set by --libdir at build-time,
      39             : // optionally overridden by -libdir at run-time in the test executable);
      40             : // if we don't have an explicit libdir then the linker will look in DT_RUNPATH
      41             : // (which we set to $ORIGIN) to find it in the executable's directory
      42             : #ifdef INSTALLED_LIBDIR
      43             : static CStr g_Libdir = STRINGIZE(INSTALLED_LIBDIR);
      44             : #else
      45             : static CStr g_Libdir = "";
      46             : #endif
      47             : 
      48             : // note: on Linux, lib is prepended to the SO file name
      49             : #if OS_UNIX
      50             : static CStr g_DllPrefix = "lib";
      51             : #else
      52             : static CStr g_DllPrefix = "";
      53             : #endif
      54             : 
      55             : // we usually want to use the same debug/release build type as the
      56             : // main executable (the library should also be efficient in release builds and
      57             : // allow easy symbol access in debug builds). however, that version of the
      58             : // library might be missing, so we check for both.
      59             : // this works because the interface is binary-compatible.
      60             : #ifndef NDEBUG
      61             : static CStr suffixes[] = { "_dbg", "" };    // (order matters)
      62             : #else
      63             : static CStr suffixes[] = { "", "_dbg" };
      64             : #endif
      65             : 
      66             : // NB: our Windows dlopen() function changes the extension to .dll
      67             : static CStr extensions[] = {
      68             :     ".so",
      69             : #if OS_MACOSX
      70             :     ".dylib"  // supported by OS X dlopen
      71             : #endif
      72             : };
      73             : 
      74             : // (This class is currently only used by 'Collada' and 'AtlasUI' which follow
      75             : // the naming/location convention above - it'll need to be changed if we want
      76             : // to support other DLLs.)
      77             : 
      78           7 : CStr DllLoader::GenerateFilename(const CStr& name, const CStr& suffix, const CStr& extension)
      79             : {
      80           7 :     CStr n;
      81             : 
      82           7 :     if (!g_Libdir.empty())
      83           0 :         n = g_Libdir + "/";
      84             : 
      85             : #if OS_MACOSX
      86             :     if (osx_IsAppBundleValid())
      87             :     {
      88             :         // We are in a bundle, in which case the lib directory is ../Frameworks
      89             :         // relative to the binary, so we use a helper function to get the system path
      90             :         // (alternately we could use @executable_path as below, but this seems better)
      91             :         CStr frameworksPath = osx_GetBundleFrameworksPath();
      92             :         if (!frameworksPath.empty())
      93             :             n = frameworksPath + "/";
      94             :     }
      95             :     else
      96             :     {
      97             :         // On OS X, dlopen will search the current working directory for the library to
      98             :         // to load if given only a filename. But the CWD is not guaranteed to be
      99             :         // binaries/system (where our dylibs are placed) and it's not when e.g. the user
     100             :         // launches the game from Finder.
     101             :         // To work around this, we use the @executable_path variable, which should always
     102             :         // resolve to binaries/system, if we're not a bundle.
     103             :         // (see Apple's dyld(1) and dlopen(3) man pages for more info)
     104             :         n = "@executable_path/";
     105             :     }
     106             : #endif
     107             : 
     108          28 :     n += g_DllPrefix + name + suffix + extension;
     109           7 :     return n;
     110           0 : }
     111             : 
     112             : 
     113             : 
     114             : // @param name base name of the library (excluding prefix/suffix/extension)
     115             : // @param errors receives descriptions of any and all errors encountered
     116             : // @return valid handle or 0
     117           7 : static void* LoadAnyVariant(const CStr& name, std::stringstream& errors)
     118             : {
     119           7 :     for (size_t idxSuffix = 0; idxSuffix < ARRAY_SIZE(suffixes); idxSuffix++)
     120             :     {
     121           7 :         for (size_t idxExtension = 0; idxExtension < ARRAY_SIZE(extensions); idxExtension++)
     122             :         {
     123           7 :             CStr filename = DllLoader::GenerateFilename(name, suffixes[idxSuffix], extensions[idxExtension]);
     124             : 
     125             :             // we don't really care when relocations take place, but one of
     126             :             // {RTLD_NOW, RTLD_LAZY} must be specified. go with the former because
     127             :             // it is safer and matches the Windows load behavior.
     128           7 :             const int flags = RTLD_LOCAL|RTLD_NOW;
     129           7 :             void* handle = dlopen(filename.c_str(), flags);
     130           7 :             if (handle)
     131           7 :                 return handle;
     132             :             else
     133           0 :                 errors << "dlopen(" << filename << ") failed: " << dlerror() << "; ";
     134           7 :         }
     135             :     }
     136             : 
     137             :     return 0;   // none worked
     138             : }
     139             : 
     140             : 
     141          13 : DllLoader::DllLoader(const char* name, CLogger::ELogMethod loadErrorLogMethod)
     142          13 :     : m_Name(name), m_Handle(0), m_LoadErrorLogMethod(loadErrorLogMethod)
     143             : {
     144          13 : }
     145             : 
     146          13 : DllLoader::~DllLoader()
     147             : {
     148          13 :     if (IsLoaded())
     149           6 :         dlclose(m_Handle);
     150          13 : }
     151             : 
     152          61 : bool DllLoader::IsLoaded() const
     153             : {
     154          13 :     return (m_Handle != 0 && m_Handle != HANDLE_UNAVAILABLE);
     155             : }
     156             : 
     157           7 : bool DllLoader::LoadDLL()
     158             : {
     159             :     // first time: try to open the shared object
     160             :     // postcondition: m_Handle valid or == HANDLE_UNAVAILABLE.
     161           7 :     if (m_Handle == 0)
     162             :     {
     163           7 :         PROFILE2("LoadDLL");
     164             : 
     165           7 :         std::stringstream errors;
     166           7 :         m_Handle = LoadAnyVariant(m_Name, errors);
     167           7 :         if (!m_Handle)  // (only report errors if nothing worked)
     168             :         {
     169           0 :             LogLoadError(errors.str().c_str());
     170           0 :             m_Handle = HANDLE_UNAVAILABLE;
     171             :         }
     172           7 :     }
     173             : 
     174           7 :     return (m_Handle != HANDLE_UNAVAILABLE);
     175             : }
     176             : 
     177           1 : void DllLoader::Unload()
     178             : {
     179           1 :     if (!IsLoaded())
     180             :         return;
     181             : 
     182           1 :     dlclose(m_Handle);
     183           1 :     m_Handle = 0;
     184             : }
     185             : 
     186          28 : void DllLoader::LoadSymbolInternal(const char* name, void** fptr) const
     187             : {
     188          28 :     if (!IsLoaded())
     189             :     {
     190           0 :         debug_warn(L"Loading symbol from invalid DLL");
     191           0 :         *fptr = NULL;
     192           0 :         throw PSERROR_DllLoader_DllNotLoaded();
     193             :     }
     194             : 
     195          28 :     *fptr = dlsym(m_Handle, name);
     196          28 :     if (*fptr == NULL)
     197           0 :         throw PSERROR_DllLoader_SymbolNotFound();
     198          28 : }
     199             : 
     200           0 : void DllLoader::LogLoadError(const char* errors)
     201             : {
     202           0 :     switch (m_LoadErrorLogMethod)
     203             :     {
     204           0 :     case CLogger::Normal:
     205           0 :         LOGMESSAGE("DllLoader: {}", errors);
     206           0 :         break;
     207           0 :     case CLogger::Warning:
     208           0 :         LOGWARNING("DllLoader: {}", errors);
     209           0 :         break;
     210           0 :     case CLogger::Error:
     211           0 :         LOGERROR("DllLoader: {}", errors);
     212           0 :         break;
     213             :     }
     214           0 : }
     215             : 
     216           0 : void DllLoader::OverrideLibdir(const char* libdir)
     217             : {
     218           0 :     g_Libdir = libdir;
     219           0 : }

Generated by: LCOV version 1.16