- .load, .loadby (Load Extension DLL)
- Parameters
- Environment
- Additional Information
- Remarks
- Load dll windows api
- LoadLibraryW function (libloaderapi.h)
- Syntax
- Parameters
- Return value
- Remarks
- Security Remarks
- Examples
- LoadLibraryExA function (libloaderapi.h)
- Syntax
- Parameters
- Return value
- Remarks
- Loading a DLL as a Data File or Image Resource
- Searching for DLLs and Dependencies
- Security Remarks
- Examples
.load, .loadby (Load Extension DLL)
The .load and .loadby commands load a new extension DLL into the debugger.
Parameters
DLLName
Specifies the debugger extension DLL to load. If you use the .load command, DLLName should include the full path. If you use the .loadby command, DLLName should include only the file name.
ModuleName
Specifies the module name of a module that is located in the same directory as the extension DLL that DLLName specifies.
Environment
Modes
User mode, kernel mode
Targets
Live, crash dump
Platforms
Additional Information
For more information about how to load, unload, and control extensions, see Loading Debugger Extension DLLs.
Remarks
When you use the .load command, you must specify the full path.
When you use the .loadby command, you do not specify the path. Instead, the debugger finds the module that the ModuleName parameter specifies, determines the path of that module, and then uses that path when the debugger loads the extension DLL. If the debugger cannot find the module or if it cannot find the extension DLL, you receive an error message that specifies the problem. There does not have to be any relationship between the specified module and the extension DLL. Using the .loadby command is therefore simply a way to avoid typing a long path.
After the .load or .loadby command has been completed, you can access the commands that are stored in the loaded extension.
To load an extension DLL, you can do one of the following:
Use the .load or .loadby command.
Execute an extension by issuing the full !DLLName.ExtensionCommand syntax. If the debugger has not yet loaded DLLName.dll, it loads the DLL at this point if it is located in the current DLL search path.
Use the .chain command to display information about what has been loaded and the current DLL search path.
Load dll windows api
Явный вызов функций DLL несколько утомителен, зато дает Вашей программе настоящий полный контроль за работой DLL. Вы можете спокойно определить есть ли DLL и вообще есть ли в ней соответствующая функция. Давайте посмотрим как это делается. Сначала нам надо получить указатель на DLL — это делает функция LoadLibrary():
Она может завершиться как успешно, так и нет. Если успешно, то вернет указатель на DLL. Что она сделает ? Она поищет DLL. Еcли найдет, то загрузит ее в память и вернет Вам указатель. Так как DLL загружается в память Вы не можете просто так ее бросить, Вам надо ее выгрузить, а для этого есть функция FreeLibrary(), которая как раз сообщит Windows, что данная программа DLL больше не использует. Вообще за загрузку и выгрузку DLL отвечает Windows, так как DLL может использоваться несколькими программами. Вы просто говорите, что программа начинает использовать DLL (LoadLibrary) и заканчивает (FreeLibrary), а OC сама разбирается надо грузить ее в память или наоборот убирать, так как никто не использует ее. Вот пример:
Как только мы получили указатель на DLL мы можем получить адрес функции по имени функции. Естественно нам имя нужно знать. Сначала надо объявить прототип функции typedef BOOL (WINAPI MESS)(UINT);. Обратите внимание, что я явно указал тип вызова WINAPI, что означает _stdcall так как С++ использует _cdecl, который не совместим с WIN32 API. Объявив прототип я могу создать указатель на функцию, а потом воспользовавшись GetProcAddress() получить функцию и уже ее вызывать.
Внимание . Тщательно следите на типом вызова функций. Win32 пользуется методом вызова функций PASCAL — _stdcall, а VC методом вызова C, а в Windows стандарт вызова функций PASCAL. Разница этих методов в помещении параметров в стек. Будет время напишу подробнее. Просто помните об этом. Свои DLL Вы можете вызывать без WINAPI, а вот чужие надо знать, если стандартный API, то WINAPI, иначе надо выяснять. Как ?? Просто получаете ошибку вызова, если ошибетесь 🙂
LoadLibraryW function (libloaderapi.h)
Loads the specified module into the address space of the calling process. The specified module may cause other modules to be loaded.
For additional load options, use the LoadLibraryEx function.
Syntax
Parameters
The name of the module. This can be either a library module (a .dll file) or an executable module (an .exe file). The name specified is the file name of the module and is not related to the name stored in the library module itself, as specified by the LIBRARY keyword in the module-definition (.def) file.
If the string specifies a full path, the function searches only that path for the module.
If the string specifies a relative path or a module name without a path, the function uses a standard search strategy to find the module; for more information, see the Remarks.
If the function cannot find the module, the function fails. When specifying a path, be sure to use backslashes (\), not forward slashes (/). For more information about paths, see Naming a File or Directory.
If the string specifies a module name without a path and the file name extension is omitted, the function appends the default library extension .dll to the module name. To prevent the function from appending .dll to the module name, include a trailing point character (.) in the module name string.
Return value
If the function succeeds, the return value is a handle to the module.
If the function fails, the return value is NULL. To get extended error information, call GetLastError.
Remarks
To enable or disable error messages displayed by the loader during DLL loads, use the SetErrorMode function.
LoadLibrary can be used to load a library module into the address space of the process and return a handle that can be used in GetProcAddress to get the address of a DLL function. LoadLibrary can also be used to load other executable modules. For example, the function can specify an .exe file to get a handle that can be used in FindResource or LoadResource. However, do not use LoadLibrary to run an .exe file. Instead, use the CreateProcess function.
If the specified module is a DLL that is not already loaded for the calling process, the system calls the DLL’s DllMain function with the DLL_PROCESS_ATTACH value. If DllMain returns TRUE, LoadLibrary returns a handle to the module. If DllMain returns FALSE, the system unloads the DLL from the process address space and LoadLibrary returns NULL. It is not safe to call LoadLibrary from DllMain. For more information, see the Remarks section in DllMain.
Module handles are not global or inheritable. A call to LoadLibrary by one process does not produce a handle that another process can use — for example, in calling GetProcAddress. The other process must make its own call to LoadLibrary for the module before calling GetProcAddress.
If lpFileName does not include a path and there is more than one loaded module with the same base name and extension, the function returns a handle to the module that was loaded first.
If no file name extension is specified in the lpFileName parameter, the default library extension .dll is appended. However, the file name string can include a trailing point character (.) to indicate that the module name has no extension. When no path is specified, the function searches for loaded modules whose base name matches the base name of the module to be loaded. If the name matches, the load succeeds. Otherwise, the function searches for the file.
The first directory searched is the directory containing the image file used to create the calling process (for more information, see the CreateProcess function). Doing this allows private dynamic-link library (DLL) files associated with a process to be found without adding the process’s installed directory to the PATH environment variable. If a relative path is specified, the entire relative path is appended to every token in the DLL search path list. To load a module from a relative path without searching any other path, use GetFullPathName to get a nonrelative path and call LoadLibrary with the nonrelative path. For more information on the DLL search order, see Dynamic-Link Library Search Order.
The search path can be altered using the SetDllDirectory function. This solution is recommended instead of using SetCurrentDirectory or hard-coding the full path to the DLL.
If a path is specified and there is a redirection file for the application, the function searches for the module in the application’s directory. If the module exists in the application’s directory, LoadLibrary ignores the specified path and loads the module from the application’s directory. If the module does not exist in the application’s directory, LoadLibrary loads the module from the specified directory. For more information, see Dynamic Link Library Redirection.
If you call LoadLibrary with the name of an assembly without a path specification and the assembly is listed in the system compatible manifest, the call is automatically redirected to the side-by-side assembly.
The system maintains a per-process reference count on all loaded modules. Calling LoadLibrary increments the reference count. Calling the FreeLibrary or FreeLibraryAndExitThread function decrements the reference count. The system unloads a module when its reference count reaches zero or when the process terminates (regardless of the reference count).
Windows ServerВ 2003 and WindowsВ XP:В В The Visual C++ compiler supports a syntax that enables you to declare thread-local variables: _declspec(thread). If you use this syntax in a DLL, you will not be able to load the DLL explicitly using LoadLibrary on versions of Windows prior to WindowsВ Vista. If your DLL will be loaded explicitly, you must use the thread local storage functions instead of _declspec(thread). For an example, see Using Thread Local Storage in a Dynamic Link Library.
Security Remarks
Do not make assumptions about the operating system version based on a LoadLibrary call that searches for a DLL. If the application is running in an environment where the DLL is legitimately not present but a malicious version of the DLL is in the search path, the malicious version of the DLL may be loaded. Instead, use the recommended techniques described in Getting the System Version.
Examples
The libloaderapi.h header defines LoadLibrary as an alias which automatically selects the ANSI or Unicode version of this function based on the definition of the UNICODE preprocessor constant. Mixing usage of the encoding-neutral alias with code that not encoding-neutral can lead to mismatches that result in compilation or runtime errors. For more information, see Conventions for Function Prototypes.
LoadLibraryExA function (libloaderapi.h)
Loads the specified module into the address space of the calling process. The specified module may cause other modules to be loaded.
Syntax
Parameters
A string that specifies the file name of the module to load. This name is not related to the name stored in a library module itself, as specified by the LIBRARY keyword in the module-definition (.def) file.
The module can be a library module (a .dll file) or an executable module (an .exe file). If the specified module is an executable module, static imports are not loaded; instead, the module is loaded as if DONT_RESOLVE_DLL_REFERENCES was specified. See the dwFlags parameter for more information.
If the string specifies a module name without a path and the file name extension is omitted, the function appends the default library extension .dll to the module name. To prevent the function from appending .dll to the module name, include a trailing point character (.) in the module name string.
If the string specifies a fully qualified path, the function searches only that path for the module. When specifying a path, be sure to use backslashes (\), not forward slashes (/). For more information about paths, see Naming Files, Paths, and Namespaces.
If the string specifies a module name without a path and more than one loaded module has the same base name and extension, the function returns a handle to the module that was loaded first.
If the string specifies a module name without a path and a module of the same name is not already loaded, or if the string specifies a module name with a relative path, the function searches for the specified module. The function also searches for modules if loading the specified module causes the system to load other associated modules (that is, if the module has dependencies). The directories that are searched and the order in which they are searched depend on the specified path and the dwFlags parameter. For more information, see Remarks.
If the function cannot find the module or one of its dependencies, the function fails.
This parameter is reserved for future use. It must be NULL.
The action to be taken when loading the module. If no flags are specified, the behavior of this function is identical to that of the LoadLibrary function. This parameter can be one of the following values.
Value | Meaning |
---|---|
DONT_RESOLVE_DLL_REFERENCES 0x00000001 | If this value is used, and the executable module is a DLL, the system does not call DllMain for process and thread initialization and termination. Also, the system does not load additional executable modules that are referenced by the specified module. |
LOAD_IGNORE_CODE_AUTHZ_LEVEL 0x00000010 | If this value is used, the system does not check AppLocker rules or apply Software Restriction Policies for the DLL. This action applies only to the DLL being loaded and not to its dependencies. This value is recommended for use in setup programs that must run extracted DLLs during installation. Windows ServerВ 2008В R2 and WindowsВ 7:В В On systems with KB2532445 installed, the caller must be running as «LocalSystem» or «TrustedInstaller»; otherwise the system ignores this flag. For more information, see «You can circumvent AppLocker rules by using an Office macro on a computer that is running Windows 7 or Windows Server 2008 R2» in the Help and Support Knowledge Base at https://support.microsoft.com/kb/2532445. Windows ServerВ 2008, WindowsВ Vista, Windows ServerВ 2003 and WindowsВ XP:В В AppLocker was introduced in WindowsВ 7 and Windows ServerВ 2008В R2. |
LOAD_LIBRARY_AS_DATAFILE 0x00000002 | If this value is used, the system maps the file into the calling process’s virtual address space as if it were a data file. Nothing is done to execute or prepare to execute the mapped file. Therefore, you cannot call functions like GetModuleFileName, GetModuleHandle or GetProcAddress with this DLL. Using this value causes writes to read-only memory to raise an access violation. Use this flag when you want to load a DLL only to extract messages or resources from it. This value can be used with LOAD_LIBRARY_AS_IMAGE_RESOURCE. For more information, see Remarks. |
LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE 0x00000040 | Similar to LOAD_LIBRARY_AS_DATAFILE, except that the DLL file is opened with exclusive write access for the calling process. Other processes cannot open the DLL file for write access while it is in use. However, the DLL can still be opened by other processes. This value can be used with LOAD_LIBRARY_AS_IMAGE_RESOURCE. For more information, see Remarks. Windows ServerВ 2003 and WindowsВ XP:В В This value is not supported until WindowsВ Vista. |
LOAD_LIBRARY_AS_IMAGE_RESOURCE 0x00000020 | If this value is used, the system maps the file into the process’s virtual address space as an image file. However, the loader does not load the static imports or perform the other usual initialization steps. Use this flag when you want to load a DLL only to extract messages or resources from it. Unless the application depends on the file having the in-memory layout of an image, this value should be used with either LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE or LOAD_LIBRARY_AS_DATAFILE. For more information, see the Remarks section. Windows ServerВ 2003 and WindowsВ XP:В В This value is not supported until WindowsВ Vista. |
LOAD_LIBRARY_SEARCH_APPLICATION_DIR 0x00000200 | If this value is used, the application’s installation directory is searched for the DLL and its dependencies. Directories in the standard search path are not searched. This value cannot be combined with LOAD_WITH_ALTERED_SEARCH_PATH. WindowsВ 7, Windows ServerВ 2008В R2, WindowsВ Vista and Windows ServerВ 2008:В В This value requires KB2533623 to be installed. Windows ServerВ 2003 and WindowsВ XP:В В This value is not supported. |
LOAD_LIBRARY_SEARCH_DEFAULT_DIRS 0x00001000 | This value is a combination of LOAD_LIBRARY_SEARCH_APPLICATION_DIR, LOAD_LIBRARY_SEARCH_SYSTEM32, and LOAD_LIBRARY_SEARCH_USER_DIRS. Directories in the standard search path are not searched. This value cannot be combined with LOAD_WITH_ALTERED_SEARCH_PATH. This value represents the recommended maximum number of directories an application should include in its DLL search path. WindowsВ 7, Windows ServerВ 2008В R2, WindowsВ Vista and Windows ServerВ 2008:В В This value requires KB2533623 to be installed. Windows ServerВ 2003 and WindowsВ XP:В В This value is not supported. |
LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR 0x00000100 | If this value is used, the directory that contains the DLL is temporarily added to the beginning of the list of directories that are searched for the DLL’s dependencies. Directories in the standard search path are not searched. The lpFileName parameter must specify a fully qualified path. This value cannot be combined with LOAD_WITH_ALTERED_SEARCH_PATH. For example, if Lib2.dll is a dependency of C:\Dir1\Lib1.dll, loading Lib1.dll with this value causes the system to search for Lib2.dll only in C:\Dir1. To search for Lib2.dll in C:\Dir1 and all of the directories in the DLL search path, combine this value with LOAD_LIBRARY_SEARCH_DEFAULT_DIRS. WindowsВ 7, Windows ServerВ 2008В R2, WindowsВ Vista and Windows ServerВ 2008:В В This value requires KB2533623 to be installed. Windows ServerВ 2003 and WindowsВ XP:В В This value is not supported. |
LOAD_LIBRARY_SEARCH_SYSTEM32 0x00000800 | If this value is used, %windows%\system32 is searched for the DLL and its dependencies. Directories in the standard search path are not searched. This value cannot be combined with LOAD_WITH_ALTERED_SEARCH_PATH. WindowsВ 7, Windows ServerВ 2008В R2, WindowsВ Vista and Windows ServerВ 2008:В В This value requires KB2533623 to be installed. Windows ServerВ 2003 and WindowsВ XP:В В This value is not supported. |
LOAD_LIBRARY_SEARCH_USER_DIRS 0x00000400 | If this value is used, directories added using the AddDllDirectory or the SetDllDirectory function are searched for the DLL and its dependencies. If more than one directory has been added, the order in which the directories are searched is unspecified. Directories in the standard search path are not searched. This value cannot be combined with LOAD_WITH_ALTERED_SEARCH_PATH. WindowsВ 7, Windows ServerВ 2008В R2, WindowsВ Vista and Windows ServerВ 2008:В В This value requires KB2533623 to be installed. Windows ServerВ 2003 and WindowsВ XP:В В This value is not supported. |
LOAD_WITH_ALTERED_SEARCH_PATH 0x00000008 | If this value is used and lpFileName specifies an absolute path, the system uses the alternate file search strategy discussed in the Remarks section to find associated executable modules that the specified module causes to be loaded. If this value is used and lpFileName specifies a relative path, the behavior is undefined. If this value is not used, or if lpFileName does not specify a path, the system uses the standard search strategy discussed in the Remarks section to find associated executable modules that the specified module causes to be loaded. This value cannot be combined with any LOAD_LIBRARY_SEARCH flag. |
LOAD_LIBRARY_REQUIRE_SIGNED_TARGET 0x00000080 | Specifies that the digital signature of the binary image must be checked at load time. |
LOAD_LIBRARY_SAFE_CURRENT_DIRS 0x00002000 | If this value is used, loading a DLL for execution from the current directory is only allowed if it is under a directory in the Safe load list. |
Return value
If the function succeeds, the return value is a handle to the loaded module.
If the function fails, the return value is NULL. To get extended error information, call GetLastError.
Remarks
The LoadLibraryEx function is very similar to the LoadLibrary function. The differences consist of a set of optional behaviors that LoadLibraryEx provides:
- LoadLibraryEx can load a DLL module without calling the DllMain function of the DLL.
- LoadLibraryEx can load a module in a way that is optimized for the case where the module will never be executed, loading the module as if it were a data file.
- LoadLibraryEx can find modules and their associated modules by using either of two search strategies or it can search a process-specific set of directories.
You select these optional behaviors by setting the dwFlags parameter; if dwFlags is zero, LoadLibraryEx behaves identically to LoadLibrary.
The calling process can use the handle returned by LoadLibraryEx to identify the module in calls to the GetProcAddress, FindResource, and LoadResource functions.
To enable or disable error messages displayed by the loader during DLL loads, use the SetErrorMode function.
It is not safe to call LoadLibraryEx from DllMain. For more information, see the Remarks section in DllMain.
Visual C++:В В The Visual C++ compiler supports a syntax that enables you to declare thread-local variables: _declspec(thread). If you use this syntax in a DLL, you will not be able to load the DLL explicitly using LoadLibraryEx on versions of Windows prior to WindowsВ Vista. If your DLL will be loaded explicitly, you must use the thread local storage functions instead of _declspec(thread). For an example, see Using Thread Local Storage in a Dynamic Link Library.
Loading a DLL as a Data File or Image Resource
If LoadLibraryEx is called twice for the same file with LOAD_LIBRARY_AS_DATAFILE, LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE, or LOAD_LIBRARY_AS_IMAGE_RESOURCE, two separate mappings are created for the file.
When the LOAD_LIBRARY_AS_IMAGE_RESOURCE value is used, the module is loaded as an image using portable executable (PE) section alignment expansion. Relative virtual addresses (RVA) do not have to be mapped to disk addresses, so resources can be more quickly retrieved from the module. Specifying LOAD_LIBRARY_AS_IMAGE_RESOURCE prevents other processes from modifying the module while it is loaded.
Unless an application depends on specific image mapping characteristics, the LOAD_LIBRARY_AS_IMAGE_RESOURCE value should be used with either LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE or LOAD_LIBRARY_AS_DATAFILE. This allows the loader to choose whether to load the module as an image resource or a data file, selecting whichever option enables the system to share pages more effectively. Resource functions such as FindResource can use either mapping.
To determine how a module was loaded, use one of the following macros to test the handle returned by LoadLibraryEx.
The following table describes these macros.
В
Use the FreeLibrary function to free a loaded module, whether or not loading the module caused its reference count to be incremented. If the module was loaded as a data or image file, the mapping is destroyed but the reference count is not decremented. Otherwise, the DLL reference count is decremented. Therefore, it is safe to call FreeLibrary with any handle returned by LoadLibraryEx.
Searching for DLLs and Dependencies
The LoadLibraryEx function uses the standard search path in the following cases:
If lpFileName specifies a relative path, the entire relative path is appended to every token in the DLL search path. To load a module from a relative path without searching any other path, use GetFullPathName to get a nonrelative path and call LoadLibraryEx with the nonrelative path. If the module is being loaded as a datafile and the relative path starts with «.» or «..», the relative path is treated as an absolute path.
If lpFileName specifies an absolute path and dwFlags is set to LOAD_WITH_ALTERED_SEARCH_PATH, LoadLibraryEx uses the altered search path. The behavior is undefined when LOAD_WITH_ALTERED_SEARCH_PATHflag is set, and lpFileName specifiies a relative path.
The SetDllDirectory function can be used to modify the search path. This solution is better than using SetCurrentDirectory or hard-coding the full path to the DLL. However, be aware that using SetDllDirectory effectively disables safe DLL search mode while the specified directory is in the search path and it is not thread safe. If possible, it is best to use AddDllDirectory to modify a default process search path. For more information, see Dynamic-Link Library Search Order.
An application can specify the directories to search for a single LoadLibraryEx call by using the LOAD_LIBRARY_SEARCH_* flags. If more than one LOAD_LIBRARY_SEARCH flag is specified, the directories are searched in the following order:
WindowsВ 7, Windows ServerВ 2008В R2, WindowsВ Vista and Windows ServerВ 2008:В В The LOAD_LIBRARY_SEARCH_ flags are available on systems that have KB2533623 installed. 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.
If the application has used the SetDefaultDllDirectories function to establish a DLL search path for the process and none of the LOAD_LIBRARY_SEARCH_* flags are used, the LoadLibraryEx function uses the process DLL search path instead of the standard search path.
If a path is specified and there is a redirection file associated with the application, the LoadLibraryEx function searches for the module in the application directory. If the module exists in the application directory, LoadLibraryEx ignores the path specification and loads the module from the application directory. If the module does not exist in the application directory, the function loads the module from the specified directory. For more information, see Dynamic Link Library Redirection.
If you call LoadLibraryEx with the name of an assembly without a path specification and the assembly is listed in the system compatible manifest, the call is automatically redirected to the side-by-side assembly.
Security Remarks
Do not use the SearchPath function to retrieve a path to a DLL for a subsequent LoadLibraryEx call. The SearchPath function uses a different search order than LoadLibraryEx and it does not use safe process search mode unless this is explicitly enabled by calling SetSearchPathMode with BASE_SEARCH_PATH_ENABLE_SAFE_SEARCHMODE. Therefore, SearchPath is likely to first search the user’s current working directory for the specified DLL. If an attacker has copied a malicious version of a DLL into the current working directory, the path retrieved by SearchPath will point to the malicious DLL, which LoadLibraryEx will then load.
Do not make assumptions about the operating system version based on a LoadLibraryEx call that searches for a DLL. If the application is running in an environment where the DLL is legitimately not present but a malicious version of the DLL is in the search path, the malicious version of the DLL may be loaded. Instead, use the recommended techniques described in Getting the System Version.
For a general discussion of DLL security issues, see Dynamic-Link Library Security.
Examples
The following code example demonstrates a call to LoadLibraryExA.
The libloaderapi.h header defines LoadLibraryEx as an alias which automatically selects the ANSI or Unicode version of this function based on the definition of the UNICODE preprocessor constant. Mixing usage of the encoding-neutral alias with code that not encoding-neutral can lead to mismatches that result in compilation or runtime errors. For more information, see Conventions for Function Prototypes.