Skip to content
  • chengx's avatar
    Use LoadLibraryExW if applicable in LoadNativeLibrary on Windows · 5946c923
    chengx authored
    In the current LoadNativeLibrary implementation, LoadLibraryW Windows
    API is used to load a DLL. To be able to find dependencies in the same
    folder, SetCurrentDirectory() is needed to search for the DLL directory,
    and sets it back after the DLL is loaded. This is required because on
    Windows, it'll search for dependencies in a search list, which includes
    the system "current directory", but not the DLL directory.
    
    However, SetCurrentDirectory() can be potentially problematic. It is not
    recommended in a multithreaded application, and could pose a security
    risk as "If an attacker gains control of one of the directories on the
    DLL search path, it can place a malicious copy of the DLL in that
    directory. This is sometimes called a DLL preloading attack or a binary
    planting attack."
    
    The right thing to do is to use LoadLibraryExW, where we can specify
    additional flags like LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR to enable
    searching in the DLL directory. With this, we can eliminate the need of
    doing SetCurrentDirectory().
    
    Using these additional flags requires KB2533623 to be installed and the
    method is "To determine whether the flags are available, use
    GetProcAddress to get the address of the AddDllDirectory,
    RemoveDllDirectory, or SetDefaultDllDirectories function. If
    GetProcAddress succeeds, the LOAD_LIBRARY_SEARCH_* flags can be used
    with LoadLibraryEx."
    
    Therefore, we can dynamically call LoadLibraryExW if the API and the
    flags are available. If not or its call fails, we should use the
    LoadLibraryW API.
    
    This CL also adds UMA histogram to record the calling status of both
    LoadLibraryExW and LoadLibraryW APIs. Besides, this CL removes the
    LoadNativeLibraryDynamically method as it is not used anywhere.
    
    Running Chromium built with this CL locally shows that LoadLibraryExW
    call were successful for kernel32.dll and widevinecdm.dll (which caused
    crbug.com/700208), but failed when loading MDMRegistration.dll.
    LoadLibraryW succeeds in loading MDMRegistration.dll though.
    
    BUG=700503,700208
    
    Review-Url: https://codereview.chromium.org/2744043003
    Cr-Commit-Position: refs/heads/master@{#457359}
    5946c923