#1 Today 08:07:55

zed
Member
Registered: 2015-02-26
Posts: 122

Usage of SetDllDirectoryW within the framework

In my application, I encountered an issue with mORMot 2: dynamically loading libcurl via LibCurlInitialize([giAll], 'libcurl-4.dll') results in a call to SetDllDirectoryW(nil). This breaks subsequent LoadLibrary calls for loading third-party DLLs. The problem arises because my application calls SetDllDirectoryW at startup to set a global DLL directory.

After analyzing the DLL loading algorithm in mORMot 2, I would like to propose a few improvements:

1. When loading libcurl, use the TryFromExecutableFolder option instead of forcibly appending the absolute path Executable.ProgramFilePath + dllname (which, by the way, is done without checking whether dllname is relative or absolute).

// mormot.lib.curl
procedure LibCurlInitialize
...
  curl := TLibCurl.Create;
  {$ifdef OSWINDOWS}
  curl.TryFromExecutableFolder := True;                     // << fix
  {$endif OSWINDOWS}
  curl.TryLoadResolve([    
    //{$ifdef OSWINDOWS}
    // first try the libcurl.dll in the local executable folder
    //Executable.ProgramFilePath + dllname,           // << fix
    //{$endif OSWINDOWS}
    // search standard library in path
    dllname
    ...

2. Inside TryLoadLibrary, invoke LibrarySetDirectory only if the path differs from Executable.ProgramFilePath.

// mormot.core.os
function TSynLibrary.TryLoadLibrary
...
  if (nwd <> '') and (nwd <> Executable.ProgramFilePath) then                       // << fix
  begin
    GlobalLock; // SetDllDirectoryW() is for the whole process not thread
    if not LibrarySetDirectory(nwd) then // as documented on microsoft.com
    begin
      GlobalUnLock;
      nwd := '';
    end;
  end else 
    nwd := '';                            // << fix

3. Add a global variable LibraryUseSetDllDirectory to mormot.core.os to allow completely disabling SetDllDirectoryW within the framework.

// mormot.core.os
var
  LibraryUseSetDllDirectory: boolean; // = False by default

Last edited by zed (Today 08:12:53)

Offline

Board footer

Powered by FluxBB