Для чего используются библиотеки windows dll

This article is about the OS/2 and Windows implementation. For dynamic linking of libraries in general, see Dynamic linker.

This article is about the OS/2 and Windows implementation. For dynamic linking of libraries in general, see Dynamic linker.

Dynamic link library

Filename extension

.dll

Internet media type

application/vnd.microsoft.portable-executable

Uniform Type Identifier (UTI) com.microsoft.windows-dynamic-link-library
Magic number MZ
Developed by Microsoft
Container for Shared library

Dynamic-link library (DLL) is Microsoft’s implementation of the shared library concept in the Microsoft Windows and OS/2 operating systems. These libraries usually have the file extension DLL, OCX (for libraries containing ActiveX controls), or DRV (for legacy system drivers).
The file formats for DLLs are the same as for Windows EXE files – that is, Portable Executable (PE) for 32-bit and 64-bit Windows, and New Executable (NE) for 16-bit Windows. As with EXEs, DLLs can contain code, data, and resources, in any combination.

Data files with the same file format as a DLL, but with different file extensions and possibly containing only resource sections, can be called resource DLLs. Examples of such DLLs include icon libraries, sometimes having the extension ICL, and font files, having the extensions FON and FOT.[1]

Background[edit]

The first versions of Microsoft Windows ran programs together in a single address space. Every program was meant to co-operate by yielding the CPU to other programs so that the graphical user interface (GUI) could multitask and be maximally responsive. All operating-system level operations were provided by the underlying operating system: MS-DOS. All higher-level services were provided by Windows Libraries «Dynamic Link Library». The Drawing API, Graphics Device Interface (GDI), was implemented in a DLL called GDI.EXE, the user interface in USER.EXE. These extra layers on top of DOS had to be shared across all running Windows programs, not just to enable Windows to work in a machine with less than a megabyte of RAM, but to enable the programs to co-operate with each other. The code in GDI needed to translate drawing commands to operations on specific devices. On the display, it had to manipulate pixels in the frame buffer. When drawing to a printer, the API calls had to be transformed into requests to a printer. Although it could have been possible to provide hard-coded support for a limited set of devices (like the Color Graphics Adapter display, the HP LaserJet Printer Command Language), Microsoft chose a different approach. GDI would work by loading different pieces of code, called «device drivers», to work with different output devices.

The same architectural concept that allowed GDI to load different device drivers also allowed the Windows shell to load different Windows programs, and for these programs to invoke API calls from the shared USER and GDI libraries. That concept was «dynamic linking».

In a conventional non-shared static library, sections of code are simply added to the calling program when its executable is built at the «linking» phase; if two programs call the same routine, the routine is included in both the programs during the linking stage of the two. With dynamic linking, shared code is placed into a single, separate file. The programs that call this file are connected to it at run time, with the operating system (or, in the case of early versions of Windows, the OS-extension), performing the binding.

For those early versions of Windows (1.0 to 3.11), the DLLs were the foundation for the entire GUI. As such, display drivers were merely DLLs with a .DRV extension that provided custom implementations of the same drawing API through a unified device driver interface (DDI), and the Drawing (GDI) and GUI (USER) APIs were merely the function calls exported by the GDI and USER, system DLLs with .EXE extension.

This notion of building up the operating system from a collection of dynamically loaded libraries is a core concept of Windows that persists as of 2015.
DLLs provide the standard benefits of shared libraries, such as modularity. Modularity allows changes to be made to code and data in a single self-contained DLL shared by several applications without any change to the applications themselves.

Another benefit of modularity is the use of generic interfaces for plug-ins. A single interface may be developed which allows old as well as new modules to be integrated seamlessly at run-time into pre-existing applications, without any modification to the application itself. This concept of dynamic extensibility is taken to the extreme with the Component Object Model, the underpinnings of ActiveX.

In Windows 1.x, 2.x and 3.x, all Windows applications shared the same address space as well as the same memory. A DLL was only loaded once into this address space; from then on, all programs using the library accessed it. The library’s data was shared across all the programs. This could be used as an indirect form of inter-process communication, or it could accidentally corrupt the different programs. With the introduction of 32-bit libraries in Windows 95, every process ran in its own address space. While the DLL code may be shared, the data is private except where shared data is explicitly requested by the library. That said, large swathes of Windows 95, Windows 98 and Windows Me were built from 16-bit libraries, which limited the performance of the Pentium Pro microprocessor when launched, and ultimately limited the stability and scalability of the DOS-based versions of Windows.

Although DLLs are the core of the Windows architecture, they have several drawbacks, collectively called «DLL hell».[2]
As of 2015 Microsoft promotes .NET Framework as one solution to the problems of DLL hell, although they now promote virtualization-based solutions such as Microsoft Virtual PC and Microsoft Application Virtualization, because they offer superior isolation between applications. An alternative mitigating solution to DLL hell has been to implement side-by-side assembly.

Features[edit]

Since DLLs are essentially the same as EXEs, the choice of which to produce as part of the linking process is for clarity, since it is possible to export functions and data from either.

It is not possible to directly execute a DLL, since it requires an EXE for the operating system to load it through an entry point, hence the existence of utilities like RUNDLL.EXE or RUNDLL32.EXE which provide the entry point and minimal framework for DLLs that contain enough functionality to execute without much support.

DLLs provide a mechanism for shared code and data, allowing a developer of shared code/data to upgrade functionality without requiring applications to be re-linked or re-compiled. From the application development point of view, Windows and OS/2 can be thought of as a collection of DLLs that are upgraded, allowing applications for one version of the OS to work in a later one, provided that the OS vendor has ensured that the interfaces and functionality are compatible.

DLLs execute in the memory space of the calling process and with the same access permissions, which means there is little overhead in their use, but also that there is no protection for the calling program if the DLL has any sort of bug.

Memory management[edit]

In Windows API, DLL files are organized into sections. Each section has its own set of attributes, such as being writable or read-only, executable (for code) or non-executable (for data), and so on.

The code in a DLL is usually shared among all the processes that use the DLL; that is, they occupy a single place in physical memory, and do not take up space in the page file. Windows does not use position-independent code for its DLLs; instead, the code undergoes relocation as it is loaded, fixing addresses for all its entry points at locations which are free in the memory space of the first process to load the DLL. In older versions of Windows, in which all running processes occupied a single common address space, a single copy of the DLL’s code would always be sufficient for all the processes. However, in newer versions of Windows which use separate address spaces for each program, it is only possible to use the same relocated copy of the DLL in multiple programs if each program has the same virtual addresses free to accommodate the DLL’s code. If some programs (or their combination of already-loaded DLLs) do not have those addresses free, then an additional physical copy of the DLL’s code will need to be created, using a different set of relocated entry points. If the physical memory occupied by a code section is to be reclaimed, its contents are discarded, and later reloaded directly from the DLL file as necessary.

In contrast to code sections, the data sections of a DLL are usually private; that is, each process using the DLL has its own copy of all the DLL’s data. Optionally, data sections can be made shared, allowing inter-process communication via this shared memory area. However, because user restrictions do not apply to the use of shared DLL memory, this creates a security hole; namely, one process can corrupt the shared data, which will likely cause all other sharing processes to behave undesirably. For example, a process running under a guest account can in this way corrupt another process running under a privileged account. This is an important reason to avoid the use of shared sections in DLLs.

If a DLL is compressed by certain executable packers (e.g. UPX), all of its code sections are marked as read and write, and will be unshared. Read-and-write code sections, much like private data sections, are private to each process. Thus DLLs with shared data sections should not be compressed if they are intended to be used simultaneously by multiple programs, since each program instance would have to carry its own copy of the DLL, resulting in increased memory consumption.

Import libraries[edit]

Like static libraries, import libraries for DLLs are noted by the .lib file extension. For example, kernel32.dll, the primary dynamic library for Windows’s base functions such as file creation and memory management, is linked via kernel32.lib. The usual way to tell an import library from a proper static library is by size: the import library is much smaller as it only contains symbols referring to the actual DLL, to be processed at link-time. Both nevertheless are Unix ar format files.

Linking to dynamic libraries is usually handled by linking to an import library when building or linking to create an executable file. The created executable then contains an import address table (IAT) by which all DLL function calls are referenced (each referenced DLL function contains its own entry in the IAT). At run-time, the IAT is filled with appropriate addresses that point directly to a function in the separately loaded DLL.[3]

In Cygwin/MSYS and MinGW, import libraries are conventionally given the suffix .dll.a, combining both the Windows DLL suffix and the Unix ar suffix. The file format is similar, but the symbols used to mark the imports are different (_head_foo_dll vs __IMPORT_DESCRIPTOR_foo).[4] Although its GNU Binutils toolchain can generate import libraries and link to them, it is faster to link to the DLL directly.[5] An experimental tool in MinGW called genlib can be used to generate import libs with MSVC-style symbols.

Symbol resolution and binding[edit]

Each function exported by a DLL is identified by a numeric ordinal and optionally a name. Likewise, functions can be imported from a DLL either by ordinal or by name. The ordinal represents the position of the function’s address pointer in the DLL Export Address table. It is common for internal functions to be exported by ordinal only. For most Windows API functions only the names are preserved across different Windows releases; the ordinals are subject to change. Thus, one cannot reliably import Windows API functions by their ordinals.

Importing functions by ordinal provides only slightly better performance than importing them by name: export tables of DLLs are ordered by name, so a binary search can be used to find a function. The index of the found name is then used to look up the ordinal in the Export Ordinal table. In 16-bit Windows, the name table was not sorted, so the name lookup overhead was much more noticeable.

It is also possible to bind an executable to a specific version of a DLL, that is, to resolve the addresses of imported functions at compile-time. For bound imports, the linker saves the timestamp and checksum of the DLL to which the import is bound. At run-time, Windows checks to see if the same version of library is being used, and if so, Windows bypasses processing the imports. Otherwise, if the library is different from the one which was bound to, Windows processes the imports in a normal way.

Bound executables load somewhat faster if they are run in the same environment that they were compiled for, and exactly the same time if they are run in a different environment, so there is no drawback for binding the imports. For example, all the standard Windows applications are bound to the system DLLs of their respective Windows release. A good opportunity to bind an application’s imports to its target environment is during the application’s installation. This keeps the libraries «bound» until the next OS update. It does, however, change the checksum of the executable, so it is not something that can be done with signed programs, or programs that are managed by a configuration management tool that uses checksums (such as MD5 checksums) to manage file versions. As more recent Windows versions have moved away from having fixed addresses for every loaded library (for security reasons), the opportunity and value of binding an executable is decreasing.

Explicit run-time linking[edit]

DLL files may be explicitly loaded at run-time, a process referred to simply as run-time dynamic linking by Microsoft, by using the LoadLibrary (or LoadLibraryEx) API function. The GetProcAddress API function is used to look up exported symbols by name, and FreeLibrary – to unload the DLL. These functions are analogous to dlopen, dlsym, and dlclose in the POSIX standard API.

The procedure for explicit run-time linking is the same in any language that supports pointers to functions, since it depends on the Windows API rather than language constructs.

Delayed loading[edit]

Normally, an application that is linked against a DLL’s import library will fail to start if the DLL cannot be found, because Windows will not run the application unless it can find all of the DLLs that the application may need. However an application may be linked against an import library to allow delayed loading of the dynamic library.[6]
In this case, the operating system will not try to find or load the DLL when the application starts; instead, a stub is included in the application by the linker which will try to find and load the DLL through LoadLibrary and GetProcAddress when one of its functions is called. If the DLL cannot be found or loaded, or the called function does not exist, the application will generate an exception, which may be caught and handled appropriately. If the application does not handle the exception, it will be caught by the operating system, which will terminate the program with an error message.

The delayed loading mechanism also provides notification hooks, allowing the application to perform additional processing or error handling when the DLL is loaded and/or any DLL function is called.

Compiler and language considerations[edit]

Delphi[edit]

In a source file, the keyword library is used instead of program. At the end of the file, the functions to be exported are listed in exports clause.

Delphi does not need LIB files to import functions from DLLs; to link to a DLL, the external keyword is used in the function declaration to signal the DLL name, followed by name to name the symbol (if different) or index to identify the index.

Microsoft Visual Basic[edit]

In Visual Basic (VB), only run-time linking is supported; but in addition to using LoadLibrary and GetProcAddress API functions, declarations of imported functions are allowed.

When importing DLL functions through declarations, VB will generate a run-time error if the DLL file cannot be found. The developer can catch the error and handle it appropriately.

When creating DLLs in VB, the IDE will only allow creation of ActiveX DLLs, however methods have been created[7] to allow the user to explicitly tell the linker to include a .DEF file which defines the ordinal position and name of each exported function. This allows the user to create a standard Windows DLL using Visual Basic (Version 6 or lower) which can be referenced through a «Declare» statement.

C and C++[edit]

Microsoft Visual C++ (MSVC) provides several extensions to standard C++ which allow functions to be specified as imported or exported directly in the C++ code; these have been adopted by other Windows C and C++ compilers, including Windows versions of GCC. These extensions use the attribute __declspec before a function declaration. Note that when C functions are accessed from C++, they must also be declared as extern "C" in C++ code, to inform the compiler that the C linkage should be used.[8]

Besides specifying imported or exported functions using __declspec attributes, they may be listed in IMPORT or EXPORTS section of the DEF file used by the project. The DEF file is processed by the linker, rather than the compiler, and thus it is not specific to C++.

DLL compilation will produce both DLL and LIB files. The LIB file (import library) is used to link against a DLL at compile-time; it is not necessary for run-time linking. Unless the DLL is a Component Object Model (COM) server, the DLL file must be placed in one of the directories listed in the PATH environment variable, in the default system directory, or in the same directory as the program using it. COM server DLLs are registered using regsvr32.exe, which places the DLL’s location and its globally unique ID (GUID) in the registry. Programs can then use the DLL by looking up its GUID in the registry to find its location or create an instance of the COM object indirectly using its class identifier and interface identifier.

Programming examples[edit]

Using DLL imports[edit]

The following examples show how to use language-specific bindings to import symbols for linking against a DLL at compile-time.

Delphi

{$APPTYPE CONSOLE}

program Example;

// import function that adds two numbers
function AddNumbers(a, b : Double): Double; StdCall; external 'Example.dll';

// main program
var
   R: Double;

begin
  R := AddNumbers(1, 2);
  Writeln('The result was: ', R);
end.

C

Example.lib file must be included (assuming that Example.dll is generated) in the project (Add Existing Item option for Project!) before static linking. The file Example.lib is automatically generated by the compiler when compiling the DLL. Not executing the above statement would cause linking error as the linker would not know where to find the definition of AddNumbers. The DLL Example.dll may also have to be copied to the location where the .exe file would be generated by the following code.

#include <windows.h>
#include <stdio.h>

// Import function that adds two numbers
extern "C" __declspec(dllimport) double AddNumbers(double a, double b);

int main(int argc, char *argv[])
{
    double result = AddNumbers(1, 2);
    printf("The result was: %fn", result);
    return 0;
}

Using explicit run-time linking[edit]

The following examples show how to use the run-time loading and linking facilities using language-specific Windows API bindings.

Note that all of the four samples are vulnerable to DLL preloading attacks, since example.dll can be resolved to a place unintended by the author (the current working directory goes before system library locations), and thus to a malicious version of the library. See the reference for Microsoft’s guidance on safe library loading: one should use SetDllDirectoryW in kernel32 to remove the current-directory lookup before any libraries are loaded.[9]

Microsoft Visual Basic[edit]

Option Explicit
Declare Function AddNumbers Lib "Example.dll" _
(ByVal a As Double, ByVal b As Double) As Double

Sub Main()
	Dim Result As Double
	Result = AddNumbers(1, 2)
	Debug.Print "The result was: " & Result
End Sub

Delphi[edit]

program Example;
  {$APPTYPE CONSOLE}
  uses Windows;
  var
  AddNumbers:function (a, b: integer): Double; StdCall;
  LibHandle:HMODULE;
begin
  LibHandle := LoadLibrary('example.dll');
  if LibHandle <> 0 then
    AddNumbers := GetProcAddress(LibHandle, 'AddNumbers');
  if Assigned(AddNumbers) then
    Writeln( '1 + 2 = ', AddNumbers( 1, 2 ) );
  Readln;
end.

C[edit]

#include <windows.h>
#include <stdio.h>

// DLL function signature
typedef double (*importFunction)(double, double);

int main(int argc, char **argv)
{
	importFunction addNumbers;
	double result;
	HINSTANCE hinstLib;

	// Load DLL file
	hinstLib = LoadLibrary(TEXT("Example.dll"));
	if (hinstLib == NULL) {
		printf("ERROR: unable to load DLLn");
		return 1;
	}

	// Get function pointer
	addNumbers = (importFunction) GetProcAddress(hinstLib, "AddNumbers");
	if (addNumbers == NULL) {
		printf("ERROR: unable to find DLL functionn");
		FreeLibrary(hinstLib);
		return 1;
	}

	// Call function.
	result = addNumbers(1, 3);

	// Unload DLL file
	FreeLibrary(hinstLib);

	// Display result
	printf("The result was: %fn", result);

	return 0;
}

Python[edit]

The Python ctypes binding will use POSIX API on POSIX systems.

import ctypes

my_dll = ctypes.cdll.LoadLibrary("Example.dll")

# The following "restype" method specification is needed to make
# Python understand what type is returned by the function.
my_dll.AddNumbers.restype = ctypes.c_double

p = my_dll.AddNumbers(ctypes.c_double(1.0), ctypes.c_double(2.0))

print("The result was:", p)

Component Object Model[edit]

The Component Object Model (COM) defines a binary standard to host the implementation of objects in DLL and EXE files. It provides mechanisms to locate and version those files as well as a language-independent and machine-readable description of the interface. Hosting COM objects in a DLL is more lightweight and allows them to share resources with the client process. This allows COM objects to implement powerful back-ends to simple GUI front ends such as Visual Basic and ASP. They can also be programmed from scripting languages.[10]

DLL hijacking[edit]

Due to a vulnerability commonly known as DLL hijacking, DLL spoofing, DLL preloading or binary planting, many programs will load and execute a malicious DLL contained in the same folder as a data file opened by these programs.[11][12][13][14] The vulnerability was discovered by Georgi Guninski in 2000.[15]
In August 2010 it gained worldwide publicity after ACROS Security rediscovered it again and many hundreds of programs were found vulnerable.[16]
Programs that are run from unsafe locations, i.e. user-writable folders like the Downloads or the Temp directory, are almost always susceptible to this vulnerability.[17][18][19][20][21][22][23]

See also[edit]

  • Dependency Walker, a utility which displays exported and imported functions of DLL and EXE files
  • Dynamic library
  • Library (computing)
  • Linker (computing)
  • Loader (computing)
  • Moricons.dll
  • Object file
  • Shared library
  • Static library
  • DLL Hell

References[edit]

  1. ^
    Microsoft Corporation. «Creating a Resource-Only DLL». Microsoft Developer Network Library.
  2. ^ «The End of DLL Hell». Microsoft Corporation. Archived from the original on 2008-05-06. Retrieved 2009-07-11.
  3. ^ «Understanding the Import Address Table».
  4. ^ «Building and Using DLLs». The import library is a regular UNIX-like .a library, but it only contains the tiny bit of information needed to tell the OS how the program interacts with («imports») the dll. This information is linked into .exe.
  5. ^ «ld and WIN32». ld documentation.
  6. ^
    «Linker Support for Delay-Loaded DLLs». Microsoft Corporation. Retrieved 2009-07-11.
  7. ^ Petrusha, Ron (2005-04-26). «Creating a Windows DLL with Visual Basic». O’Reilly Media. Retrieved 2009-07-11.
  8. ^ MSDN, Using extern to Specify Linkage
  9. ^ «Secure loading of libraries to prevent DLL preloading attacks». Microsoft Support. Retrieved 28 October 2019.
  10. ^ Satran, Michael. «Component Object Model (COM)». msdn.microsoft.com.
  11. ^ DLL Spoofing in Windows
  12. ^ «DLL Preloading Attacks». msdn.com. Retrieved 25 March 2018.
  13. ^ «More information about the DLL Preloading remote attack vector». technet.com. Retrieved 25 March 2018.
  14. ^ «An update on the DLL-preloading remote attack vector». technet.com. Retrieved 25 March 2018.
  15. ^ «Double clicking on MS Office documents from Windows Explorer may execute arbitrary programs in some cases». www.guninski.com. Retrieved 25 March 2018.
  16. ^ «Binary Planting — The Official Web Site of a Forgotten Vulnerability . ACROS Security». www.binaryplanting.com. Retrieved 25 March 2018.
  17. ^ Carpet Bombing and Directory Poisoning
  18. ^ «Dev to Mozilla: Please dump ancient Windows install processes». theregister.co.uk. Retrieved 25 March 2018.
  19. ^ «Gpg4win — Security Advisory Gpg4win 2015-11-25». www.gpg4win.org. Retrieved 25 March 2018.
  20. ^ «McAfee KB — McAfee Security Bulletin: Security patch for several McAfee installers and uninstallers (CVE-2015-8991, CVE-2015-8992, and CVE-2015-8993) (TS102462)». service.mcafee.com. Retrieved 25 March 2018.
  21. ^ «fsc-2015-4 — F-Secure Labs». www.f-secure.com. Archived from the original on 31 July 2017. Retrieved 25 March 2018.
  22. ^ «ScanNow DLL Search Order Hijacking Vulnerability and Deprecation». rapid7.com. 21 December 2015. Retrieved 25 March 2018.
  23. ^ Team, VeraCrypt. «oss-sec: CVE-2016-1281: TrueCrypt and VeraCrypt Windows installers allow arbitrary code execution with elevation of privilege». seclists.org. Retrieved 25 March 2018.
  • Hart, Johnson. Windows System Programming Third Edition. Addison-Wesley, 2005. ISBN 0-321-25619-0.
  • Rector, Brent et al. Win32 Programming. Addison-Wesley Developers Press, 1997. ISBN 0-201-63492-9.

External links[edit]

  • dllexport, dllimport on MSDN
  • Dynamic-Link Libraries on MSDN
  • Dynamic-Link Library Security on MSDN
  • Dynamic-Link Library Search Order on MSDN
  • Microsoft Security Advisory: Insecure library loading could allow remote code execution
  • What is a DLL? on Microsoft support site
  • Dynamic-Link Library Functions on MSDN
  • Microsoft Portable Executable and Common Object File Format Specification
  • Microsoft specification for dll files
  • Carpet Bombing and Directory Poisoning
  • MS09-014: Addressing the Safari Carpet Bomb vulnerability
  • More information about the DLL Preloading remote attack vector
  • An update on the DLL-preloading remote attack vector
  • Load Library Safely

This article is about the OS/2 and Windows implementation. For dynamic linking of libraries in general, see Dynamic linker.

Dynamic link library

Filename extension

.dll

Internet media type

application/vnd.microsoft.portable-executable

Uniform Type Identifier (UTI) com.microsoft.windows-dynamic-link-library
Magic number MZ
Developed by Microsoft
Container for Shared library

Dynamic-link library (DLL) is Microsoft’s implementation of the shared library concept in the Microsoft Windows and OS/2 operating systems. These libraries usually have the file extension DLL, OCX (for libraries containing ActiveX controls), or DRV (for legacy system drivers).
The file formats for DLLs are the same as for Windows EXE files – that is, Portable Executable (PE) for 32-bit and 64-bit Windows, and New Executable (NE) for 16-bit Windows. As with EXEs, DLLs can contain code, data, and resources, in any combination.

Data files with the same file format as a DLL, but with different file extensions and possibly containing only resource sections, can be called resource DLLs. Examples of such DLLs include icon libraries, sometimes having the extension ICL, and font files, having the extensions FON and FOT.[1]

Background[edit]

The first versions of Microsoft Windows ran programs together in a single address space. Every program was meant to co-operate by yielding the CPU to other programs so that the graphical user interface (GUI) could multitask and be maximally responsive. All operating-system level operations were provided by the underlying operating system: MS-DOS. All higher-level services were provided by Windows Libraries «Dynamic Link Library». The Drawing API, Graphics Device Interface (GDI), was implemented in a DLL called GDI.EXE, the user interface in USER.EXE. These extra layers on top of DOS had to be shared across all running Windows programs, not just to enable Windows to work in a machine with less than a megabyte of RAM, but to enable the programs to co-operate with each other. The code in GDI needed to translate drawing commands to operations on specific devices. On the display, it had to manipulate pixels in the frame buffer. When drawing to a printer, the API calls had to be transformed into requests to a printer. Although it could have been possible to provide hard-coded support for a limited set of devices (like the Color Graphics Adapter display, the HP LaserJet Printer Command Language), Microsoft chose a different approach. GDI would work by loading different pieces of code, called «device drivers», to work with different output devices.

The same architectural concept that allowed GDI to load different device drivers also allowed the Windows shell to load different Windows programs, and for these programs to invoke API calls from the shared USER and GDI libraries. That concept was «dynamic linking».

In a conventional non-shared static library, sections of code are simply added to the calling program when its executable is built at the «linking» phase; if two programs call the same routine, the routine is included in both the programs during the linking stage of the two. With dynamic linking, shared code is placed into a single, separate file. The programs that call this file are connected to it at run time, with the operating system (or, in the case of early versions of Windows, the OS-extension), performing the binding.

For those early versions of Windows (1.0 to 3.11), the DLLs were the foundation for the entire GUI. As such, display drivers were merely DLLs with a .DRV extension that provided custom implementations of the same drawing API through a unified device driver interface (DDI), and the Drawing (GDI) and GUI (USER) APIs were merely the function calls exported by the GDI and USER, system DLLs with .EXE extension.

This notion of building up the operating system from a collection of dynamically loaded libraries is a core concept of Windows that persists as of 2015.
DLLs provide the standard benefits of shared libraries, such as modularity. Modularity allows changes to be made to code and data in a single self-contained DLL shared by several applications without any change to the applications themselves.

Another benefit of modularity is the use of generic interfaces for plug-ins. A single interface may be developed which allows old as well as new modules to be integrated seamlessly at run-time into pre-existing applications, without any modification to the application itself. This concept of dynamic extensibility is taken to the extreme with the Component Object Model, the underpinnings of ActiveX.

In Windows 1.x, 2.x and 3.x, all Windows applications shared the same address space as well as the same memory. A DLL was only loaded once into this address space; from then on, all programs using the library accessed it. The library’s data was shared across all the programs. This could be used as an indirect form of inter-process communication, or it could accidentally corrupt the different programs. With the introduction of 32-bit libraries in Windows 95, every process ran in its own address space. While the DLL code may be shared, the data is private except where shared data is explicitly requested by the library. That said, large swathes of Windows 95, Windows 98 and Windows Me were built from 16-bit libraries, which limited the performance of the Pentium Pro microprocessor when launched, and ultimately limited the stability and scalability of the DOS-based versions of Windows.

Although DLLs are the core of the Windows architecture, they have several drawbacks, collectively called «DLL hell».[2]
As of 2015 Microsoft promotes .NET Framework as one solution to the problems of DLL hell, although they now promote virtualization-based solutions such as Microsoft Virtual PC and Microsoft Application Virtualization, because they offer superior isolation between applications. An alternative mitigating solution to DLL hell has been to implement side-by-side assembly.

Features[edit]

Since DLLs are essentially the same as EXEs, the choice of which to produce as part of the linking process is for clarity, since it is possible to export functions and data from either.

It is not possible to directly execute a DLL, since it requires an EXE for the operating system to load it through an entry point, hence the existence of utilities like RUNDLL.EXE or RUNDLL32.EXE which provide the entry point and minimal framework for DLLs that contain enough functionality to execute without much support.

DLLs provide a mechanism for shared code and data, allowing a developer of shared code/data to upgrade functionality without requiring applications to be re-linked or re-compiled. From the application development point of view, Windows and OS/2 can be thought of as a collection of DLLs that are upgraded, allowing applications for one version of the OS to work in a later one, provided that the OS vendor has ensured that the interfaces and functionality are compatible.

DLLs execute in the memory space of the calling process and with the same access permissions, which means there is little overhead in their use, but also that there is no protection for the calling program if the DLL has any sort of bug.

Memory management[edit]

In Windows API, DLL files are organized into sections. Each section has its own set of attributes, such as being writable or read-only, executable (for code) or non-executable (for data), and so on.

The code in a DLL is usually shared among all the processes that use the DLL; that is, they occupy a single place in physical memory, and do not take up space in the page file. Windows does not use position-independent code for its DLLs; instead, the code undergoes relocation as it is loaded, fixing addresses for all its entry points at locations which are free in the memory space of the first process to load the DLL. In older versions of Windows, in which all running processes occupied a single common address space, a single copy of the DLL’s code would always be sufficient for all the processes. However, in newer versions of Windows which use separate address spaces for each program, it is only possible to use the same relocated copy of the DLL in multiple programs if each program has the same virtual addresses free to accommodate the DLL’s code. If some programs (or their combination of already-loaded DLLs) do not have those addresses free, then an additional physical copy of the DLL’s code will need to be created, using a different set of relocated entry points. If the physical memory occupied by a code section is to be reclaimed, its contents are discarded, and later reloaded directly from the DLL file as necessary.

In contrast to code sections, the data sections of a DLL are usually private; that is, each process using the DLL has its own copy of all the DLL’s data. Optionally, data sections can be made shared, allowing inter-process communication via this shared memory area. However, because user restrictions do not apply to the use of shared DLL memory, this creates a security hole; namely, one process can corrupt the shared data, which will likely cause all other sharing processes to behave undesirably. For example, a process running under a guest account can in this way corrupt another process running under a privileged account. This is an important reason to avoid the use of shared sections in DLLs.

If a DLL is compressed by certain executable packers (e.g. UPX), all of its code sections are marked as read and write, and will be unshared. Read-and-write code sections, much like private data sections, are private to each process. Thus DLLs with shared data sections should not be compressed if they are intended to be used simultaneously by multiple programs, since each program instance would have to carry its own copy of the DLL, resulting in increased memory consumption.

Import libraries[edit]

Like static libraries, import libraries for DLLs are noted by the .lib file extension. For example, kernel32.dll, the primary dynamic library for Windows’s base functions such as file creation and memory management, is linked via kernel32.lib. The usual way to tell an import library from a proper static library is by size: the import library is much smaller as it only contains symbols referring to the actual DLL, to be processed at link-time. Both nevertheless are Unix ar format files.

Linking to dynamic libraries is usually handled by linking to an import library when building or linking to create an executable file. The created executable then contains an import address table (IAT) by which all DLL function calls are referenced (each referenced DLL function contains its own entry in the IAT). At run-time, the IAT is filled with appropriate addresses that point directly to a function in the separately loaded DLL.[3]

In Cygwin/MSYS and MinGW, import libraries are conventionally given the suffix .dll.a, combining both the Windows DLL suffix and the Unix ar suffix. The file format is similar, but the symbols used to mark the imports are different (_head_foo_dll vs __IMPORT_DESCRIPTOR_foo).[4] Although its GNU Binutils toolchain can generate import libraries and link to them, it is faster to link to the DLL directly.[5] An experimental tool in MinGW called genlib can be used to generate import libs with MSVC-style symbols.

Symbol resolution and binding[edit]

Each function exported by a DLL is identified by a numeric ordinal and optionally a name. Likewise, functions can be imported from a DLL either by ordinal or by name. The ordinal represents the position of the function’s address pointer in the DLL Export Address table. It is common for internal functions to be exported by ordinal only. For most Windows API functions only the names are preserved across different Windows releases; the ordinals are subject to change. Thus, one cannot reliably import Windows API functions by their ordinals.

Importing functions by ordinal provides only slightly better performance than importing them by name: export tables of DLLs are ordered by name, so a binary search can be used to find a function. The index of the found name is then used to look up the ordinal in the Export Ordinal table. In 16-bit Windows, the name table was not sorted, so the name lookup overhead was much more noticeable.

It is also possible to bind an executable to a specific version of a DLL, that is, to resolve the addresses of imported functions at compile-time. For bound imports, the linker saves the timestamp and checksum of the DLL to which the import is bound. At run-time, Windows checks to see if the same version of library is being used, and if so, Windows bypasses processing the imports. Otherwise, if the library is different from the one which was bound to, Windows processes the imports in a normal way.

Bound executables load somewhat faster if they are run in the same environment that they were compiled for, and exactly the same time if they are run in a different environment, so there is no drawback for binding the imports. For example, all the standard Windows applications are bound to the system DLLs of their respective Windows release. A good opportunity to bind an application’s imports to its target environment is during the application’s installation. This keeps the libraries «bound» until the next OS update. It does, however, change the checksum of the executable, so it is not something that can be done with signed programs, or programs that are managed by a configuration management tool that uses checksums (such as MD5 checksums) to manage file versions. As more recent Windows versions have moved away from having fixed addresses for every loaded library (for security reasons), the opportunity and value of binding an executable is decreasing.

Explicit run-time linking[edit]

DLL files may be explicitly loaded at run-time, a process referred to simply as run-time dynamic linking by Microsoft, by using the LoadLibrary (or LoadLibraryEx) API function. The GetProcAddress API function is used to look up exported symbols by name, and FreeLibrary – to unload the DLL. These functions are analogous to dlopen, dlsym, and dlclose in the POSIX standard API.

The procedure for explicit run-time linking is the same in any language that supports pointers to functions, since it depends on the Windows API rather than language constructs.

Delayed loading[edit]

Normally, an application that is linked against a DLL’s import library will fail to start if the DLL cannot be found, because Windows will not run the application unless it can find all of the DLLs that the application may need. However an application may be linked against an import library to allow delayed loading of the dynamic library.[6]
In this case, the operating system will not try to find or load the DLL when the application starts; instead, a stub is included in the application by the linker which will try to find and load the DLL through LoadLibrary and GetProcAddress when one of its functions is called. If the DLL cannot be found or loaded, or the called function does not exist, the application will generate an exception, which may be caught and handled appropriately. If the application does not handle the exception, it will be caught by the operating system, which will terminate the program with an error message.

The delayed loading mechanism also provides notification hooks, allowing the application to perform additional processing or error handling when the DLL is loaded and/or any DLL function is called.

Compiler and language considerations[edit]

Delphi[edit]

In a source file, the keyword library is used instead of program. At the end of the file, the functions to be exported are listed in exports clause.

Delphi does not need LIB files to import functions from DLLs; to link to a DLL, the external keyword is used in the function declaration to signal the DLL name, followed by name to name the symbol (if different) or index to identify the index.

Microsoft Visual Basic[edit]

In Visual Basic (VB), only run-time linking is supported; but in addition to using LoadLibrary and GetProcAddress API functions, declarations of imported functions are allowed.

When importing DLL functions through declarations, VB will generate a run-time error if the DLL file cannot be found. The developer can catch the error and handle it appropriately.

When creating DLLs in VB, the IDE will only allow creation of ActiveX DLLs, however methods have been created[7] to allow the user to explicitly tell the linker to include a .DEF file which defines the ordinal position and name of each exported function. This allows the user to create a standard Windows DLL using Visual Basic (Version 6 or lower) which can be referenced through a «Declare» statement.

C and C++[edit]

Microsoft Visual C++ (MSVC) provides several extensions to standard C++ which allow functions to be specified as imported or exported directly in the C++ code; these have been adopted by other Windows C and C++ compilers, including Windows versions of GCC. These extensions use the attribute __declspec before a function declaration. Note that when C functions are accessed from C++, they must also be declared as extern "C" in C++ code, to inform the compiler that the C linkage should be used.[8]

Besides specifying imported or exported functions using __declspec attributes, they may be listed in IMPORT or EXPORTS section of the DEF file used by the project. The DEF file is processed by the linker, rather than the compiler, and thus it is not specific to C++.

DLL compilation will produce both DLL and LIB files. The LIB file (import library) is used to link against a DLL at compile-time; it is not necessary for run-time linking. Unless the DLL is a Component Object Model (COM) server, the DLL file must be placed in one of the directories listed in the PATH environment variable, in the default system directory, or in the same directory as the program using it. COM server DLLs are registered using regsvr32.exe, which places the DLL’s location and its globally unique ID (GUID) in the registry. Programs can then use the DLL by looking up its GUID in the registry to find its location or create an instance of the COM object indirectly using its class identifier and interface identifier.

Programming examples[edit]

Using DLL imports[edit]

The following examples show how to use language-specific bindings to import symbols for linking against a DLL at compile-time.

Delphi

{$APPTYPE CONSOLE}

program Example;

// import function that adds two numbers
function AddNumbers(a, b : Double): Double; StdCall; external 'Example.dll';

// main program
var
   R: Double;

begin
  R := AddNumbers(1, 2);
  Writeln('The result was: ', R);
end.

C

Example.lib file must be included (assuming that Example.dll is generated) in the project (Add Existing Item option for Project!) before static linking. The file Example.lib is automatically generated by the compiler when compiling the DLL. Not executing the above statement would cause linking error as the linker would not know where to find the definition of AddNumbers. The DLL Example.dll may also have to be copied to the location where the .exe file would be generated by the following code.

#include <windows.h>
#include <stdio.h>

// Import function that adds two numbers
extern "C" __declspec(dllimport) double AddNumbers(double a, double b);

int main(int argc, char *argv[])
{
    double result = AddNumbers(1, 2);
    printf("The result was: %fn", result);
    return 0;
}

Using explicit run-time linking[edit]

The following examples show how to use the run-time loading and linking facilities using language-specific Windows API bindings.

Note that all of the four samples are vulnerable to DLL preloading attacks, since example.dll can be resolved to a place unintended by the author (the current working directory goes before system library locations), and thus to a malicious version of the library. See the reference for Microsoft’s guidance on safe library loading: one should use SetDllDirectoryW in kernel32 to remove the current-directory lookup before any libraries are loaded.[9]

Microsoft Visual Basic[edit]

Option Explicit
Declare Function AddNumbers Lib "Example.dll" _
(ByVal a As Double, ByVal b As Double) As Double

Sub Main()
	Dim Result As Double
	Result = AddNumbers(1, 2)
	Debug.Print "The result was: " & Result
End Sub

Delphi[edit]

program Example;
  {$APPTYPE CONSOLE}
  uses Windows;
  var
  AddNumbers:function (a, b: integer): Double; StdCall;
  LibHandle:HMODULE;
begin
  LibHandle := LoadLibrary('example.dll');
  if LibHandle <> 0 then
    AddNumbers := GetProcAddress(LibHandle, 'AddNumbers');
  if Assigned(AddNumbers) then
    Writeln( '1 + 2 = ', AddNumbers( 1, 2 ) );
  Readln;
end.

C[edit]

#include <windows.h>
#include <stdio.h>

// DLL function signature
typedef double (*importFunction)(double, double);

int main(int argc, char **argv)
{
	importFunction addNumbers;
	double result;
	HINSTANCE hinstLib;

	// Load DLL file
	hinstLib = LoadLibrary(TEXT("Example.dll"));
	if (hinstLib == NULL) {
		printf("ERROR: unable to load DLLn");
		return 1;
	}

	// Get function pointer
	addNumbers = (importFunction) GetProcAddress(hinstLib, "AddNumbers");
	if (addNumbers == NULL) {
		printf("ERROR: unable to find DLL functionn");
		FreeLibrary(hinstLib);
		return 1;
	}

	// Call function.
	result = addNumbers(1, 3);

	// Unload DLL file
	FreeLibrary(hinstLib);

	// Display result
	printf("The result was: %fn", result);

	return 0;
}

Python[edit]

The Python ctypes binding will use POSIX API on POSIX systems.

import ctypes

my_dll = ctypes.cdll.LoadLibrary("Example.dll")

# The following "restype" method specification is needed to make
# Python understand what type is returned by the function.
my_dll.AddNumbers.restype = ctypes.c_double

p = my_dll.AddNumbers(ctypes.c_double(1.0), ctypes.c_double(2.0))

print("The result was:", p)

Component Object Model[edit]

The Component Object Model (COM) defines a binary standard to host the implementation of objects in DLL and EXE files. It provides mechanisms to locate and version those files as well as a language-independent and machine-readable description of the interface. Hosting COM objects in a DLL is more lightweight and allows them to share resources with the client process. This allows COM objects to implement powerful back-ends to simple GUI front ends such as Visual Basic and ASP. They can also be programmed from scripting languages.[10]

DLL hijacking[edit]

Due to a vulnerability commonly known as DLL hijacking, DLL spoofing, DLL preloading or binary planting, many programs will load and execute a malicious DLL contained in the same folder as a data file opened by these programs.[11][12][13][14] The vulnerability was discovered by Georgi Guninski in 2000.[15]
In August 2010 it gained worldwide publicity after ACROS Security rediscovered it again and many hundreds of programs were found vulnerable.[16]
Programs that are run from unsafe locations, i.e. user-writable folders like the Downloads or the Temp directory, are almost always susceptible to this vulnerability.[17][18][19][20][21][22][23]

See also[edit]

  • Dependency Walker, a utility which displays exported and imported functions of DLL and EXE files
  • Dynamic library
  • Library (computing)
  • Linker (computing)
  • Loader (computing)
  • Moricons.dll
  • Object file
  • Shared library
  • Static library
  • DLL Hell

References[edit]

  1. ^
    Microsoft Corporation. «Creating a Resource-Only DLL». Microsoft Developer Network Library.
  2. ^ «The End of DLL Hell». Microsoft Corporation. Archived from the original on 2008-05-06. Retrieved 2009-07-11.
  3. ^ «Understanding the Import Address Table».
  4. ^ «Building and Using DLLs». The import library is a regular UNIX-like .a library, but it only contains the tiny bit of information needed to tell the OS how the program interacts with («imports») the dll. This information is linked into .exe.
  5. ^ «ld and WIN32». ld documentation.
  6. ^
    «Linker Support for Delay-Loaded DLLs». Microsoft Corporation. Retrieved 2009-07-11.
  7. ^ Petrusha, Ron (2005-04-26). «Creating a Windows DLL with Visual Basic». O’Reilly Media. Retrieved 2009-07-11.
  8. ^ MSDN, Using extern to Specify Linkage
  9. ^ «Secure loading of libraries to prevent DLL preloading attacks». Microsoft Support. Retrieved 28 October 2019.
  10. ^ Satran, Michael. «Component Object Model (COM)». msdn.microsoft.com.
  11. ^ DLL Spoofing in Windows
  12. ^ «DLL Preloading Attacks». msdn.com. Retrieved 25 March 2018.
  13. ^ «More information about the DLL Preloading remote attack vector». technet.com. Retrieved 25 March 2018.
  14. ^ «An update on the DLL-preloading remote attack vector». technet.com. Retrieved 25 March 2018.
  15. ^ «Double clicking on MS Office documents from Windows Explorer may execute arbitrary programs in some cases». www.guninski.com. Retrieved 25 March 2018.
  16. ^ «Binary Planting — The Official Web Site of a Forgotten Vulnerability . ACROS Security». www.binaryplanting.com. Retrieved 25 March 2018.
  17. ^ Carpet Bombing and Directory Poisoning
  18. ^ «Dev to Mozilla: Please dump ancient Windows install processes». theregister.co.uk. Retrieved 25 March 2018.
  19. ^ «Gpg4win — Security Advisory Gpg4win 2015-11-25». www.gpg4win.org. Retrieved 25 March 2018.
  20. ^ «McAfee KB — McAfee Security Bulletin: Security patch for several McAfee installers and uninstallers (CVE-2015-8991, CVE-2015-8992, and CVE-2015-8993) (TS102462)». service.mcafee.com. Retrieved 25 March 2018.
  21. ^ «fsc-2015-4 — F-Secure Labs». www.f-secure.com. Archived from the original on 31 July 2017. Retrieved 25 March 2018.
  22. ^ «ScanNow DLL Search Order Hijacking Vulnerability and Deprecation». rapid7.com. 21 December 2015. Retrieved 25 March 2018.
  23. ^ Team, VeraCrypt. «oss-sec: CVE-2016-1281: TrueCrypt and VeraCrypt Windows installers allow arbitrary code execution with elevation of privilege». seclists.org. Retrieved 25 March 2018.
  • Hart, Johnson. Windows System Programming Third Edition. Addison-Wesley, 2005. ISBN 0-321-25619-0.
  • Rector, Brent et al. Win32 Programming. Addison-Wesley Developers Press, 1997. ISBN 0-201-63492-9.

External links[edit]

  • dllexport, dllimport on MSDN
  • Dynamic-Link Libraries on MSDN
  • Dynamic-Link Library Security on MSDN
  • Dynamic-Link Library Search Order on MSDN
  • Microsoft Security Advisory: Insecure library loading could allow remote code execution
  • What is a DLL? on Microsoft support site
  • Dynamic-Link Library Functions on MSDN
  • Microsoft Portable Executable and Common Object File Format Specification
  • Microsoft specification for dll files
  • Carpet Bombing and Directory Poisoning
  • MS09-014: Addressing the Safari Carpet Bomb vulnerability
  • More information about the DLL Preloading remote attack vector
  • An update on the DLL-preloading remote attack vector
  • Load Library Safely

Что такое DLL файлы, и для чего они нужны? Аббревиатура DLL – обозначает «Динамически Подключаемую Библиотеку». Она установлена, во всех операционных системах Windows, и практически каждая программа или игра на компьютере пользуется данной библиотекой. В ней содержится информация о конфигурации системы, совместимости устройств, наборе команд для правильной работы и многое другое. Некоторые файлы для игр имеют в своих папках уже готовые библиотеки, остальные пользуются системными.dlll в папке

Зачем нужны DLL компоненты

Если вкратце: что такое DLL файлы? – это компоненты библиотеки, а нужна она для запуска программ, приложений и игр. Компьютер включился, и система работает исправно. Вы еще ничего не запускали и не открывали, а уже десятки DLL файлов используются. Простые часы, информация о конфигурации системы, порядок запуска программ, оформление и многое другое используют библиотеку. Для того чтобы в текстовом документе начали появляться символы, соответствующие вашему вводу, нужна библиотека. По умолчанию система не знает, что означает нажатая вами клавиша,─ в этом его помогают компоненты DLL. Аналогичная ситуация со всеми подключаемыми устройствами: принтером, мышью, клавиатурой, флеш-картой. Именно библиотека DLL файлов «рассказывает» им, как работать с параметрами вашей системы.

Работоспособность элементов

Важно обновлять периодически систему и библиотеку, неактуальные файлы приведут к отказу работы программы. К примеру, вы установили игры пятилетней и большей давности, они у вас работают нормально. Далее вы поставили новую часть игры, которой не более года. Она может у вас не запуститься. Система выдаст следующее оповещение: ошибка DLL, отсутствует файл. Оно означает, что файлы нерабочие или вовсе его нет на компьютер. Связано это с тем, что программы или игры, которые пользуются библиотекой, могут вносить изменения. К примеру, вы установили игру, но параметры разрядности системы и версию ОС указали неверно. 

Текущие файлы будут перезаписаны, и программа работать перестанет. Раз отсутствует DLL, значит, его нужно скачать и поместить в систему вручную. Но в большинстве случаев, новые игры требуют новых файлов, которых вообще не было в старых сборках системы, и решение одно — установить или обновить весь пакет.

У нас на сайте, Вы сможете  скачать как отдельный DLL, так и весь пакет, в котором будут все файлы обновленные. Найти отсутствующий файл вы можете либо через поиск, либо по первой букве в верхнем меню. Как установить DLL файл и зарегистрировать прочтите в другой статье, где мы описали этот процесс максимально подробно.

С самого рождения (или чуть позже) операционная система Windows использовала библиотеки динамической компоновки DLL (Dynamic Link Library), в которых содержались реализации наиболее часто применяемых функций. Наследники Windows — NT и Windows 95, а также OS/2 — тоже зависят от библиотек DLL в плане обеспечения значительной части их функциональных возможностей.

Рассмотрим ряд аспектов создания и использования библиотек DLL:

  • как статически подключать библиотеки DLL;
  • как динамически загружать библиотеки DLL;
  • как создавать библиотеки DLL;
  • как создавать расширения МFC библиотек DLL.

Использование DLL

Практически невозможно создать приложение Windows, в котором не использовались бы библиотеки DLL. В DLL содержатся все функции Win32 API и несчетное количество других функций операционных систем Win32.

Вообще говоря, DLL — это просто наборы функций, собранные в библиотеки. Однако, в отличие от своих статических родственников (файлов . lib), библиотеки DLL не присоединены непосредственно к выполняемым файлам с помощью редактора связей. В выполняемый файл занесена только информация об их местонахождении. В момент выполнения программы загружается вся библиотека целиком. Благодаря этому разные процессы могут пользоваться совместно одними и теми же библиотеками, находящимися в памяти. Такой подход позволяет сократить объем памяти, необходимый для нескольких приложений, использующих много общих библиотек, а также контролировать размеры ЕХЕ-файлов.

Однако, если библиотека используется только одним приложением, лучше сделать ее обычной, статической. Конечно, если входящие в ее состав функции будут использоваться только в одной программе, можно просто вставить в нее соответствующий файл с исходным текстом.

Чаще всего проект подключается к DLL статически, или неявно, на этапе компоновки. Загрузкой DLL при выполнении программы управляет операционная система. Однако, DLL можно загрузить и явно, или динамически, в ходе работы приложения.

Библиотеки импортирования

При статическом подключении DLL имя .lib-файла определяется среди прочих параметров редактора связей в командной строке или на вкладке «Link» диалогового окна «Project Settings» среды Developer Studio. Однако .lib-файл, используемый при неявном подключении DLL, — это не обычная статическая библиотека. Такие .lib-файлы называются библиотеками импортирования (import libraries). В них содержится не сам код библиотеки, а только ссылки на все функции, экспортируемые из файла DLL, в котором все и хранится. В результате библиотеки импортирования, как правило, имеют меньший размер, чем DLL-файлы. К способам их создания вернемся позднее. А сейчас рассмотрим другие вопросы, касающиеся неявного подключения динамических библиотек.

Согласование интерфейсов

При использовании собственных библиотек или библиотек независимых разработчиков придется обратить внимание на согласование вызова функции с ее прототипом.

Если бы мир был совершенен, то программистам не пришлось бы беспокоиться о согласовании интерфейсов функций при подключении библиотек — все они были бы одинаковыми. Однако мир далек от совершенства, и многие большие программы написаны с помощью различных библиотек без C++.

По умолчанию в Visual C++ интерфейсы функций согласуются по правилам C++. Это значит, что параметры заносятся в стек справа налево, вызывающая программа отвечает за их удаление из стека при выходе из функции и расширении ее имени. Расширение имен (name mangling) позволяет редактору связей различать перегруженные функции, т.е. функции с одинаковыми именами, но разными списками аргументов. Однако в старой библиотеке С функции с расширенными именами отсутствуют.

Хотя все остальные правила вызова функции в С идентичны правилам вызова функции в C++, в библиотеках С имена функций не расширяются. К ним только добавляется впереди символ подчеркивания (_).

Если необходимо подключить библиотеку на С к приложению на C++, все функции из этой библиотеки придется объявить как внешние в формате С:

    extern     "С" int MyOldCFunction(int myParam);

Объявления функций библиотеки обычно помещаются в файле заголовка этой библиотеки, хотя заголовки большинства библиотек С не рассчитаны на применение в проектах на C++. В этом случае необходимо создать копию файла заголовка и включить в нее модификатор extern «C» к объявлению всех используемых функций библиотеки. Модификатор extern «C» можно применить и к целому блоку, к которому с помощью директивы #tinclude подключен файл старого заголовка С. Таким образом, вместо модификации каждой функции в отдельности можно обойтись всего тремя строками:

    extern     "С" 
    {
        #include "MyCLib.h"
    }

В программах для старых версий Windows использовались также соглашения о вызове функций языка PASCAL для функций Windows API. В новых программах следует использовать модификатор winapi, преобразуемый в _stdcall. Хотя это и не стандартный интерфейс функций С или C++, но именно он используется для обращений к функциям Windows API. Однако обычно все это уже учтено в стандартных заголовках Windows.

Загрузка неявно подключаемой DLL

При запуске приложение пытается найти все файлы DLL, неявно подключенные к приложению, и поместить их в область оперативной памяти, занимаемую данным процессом. Поиск файлов DLL операционной системой осуществляется в следующей последовательности.

  • Каталог, в котором находится ЕХЕ-файл.
  • Текущий каталог процесса.
  • Системный каталог Windows.

Если библиотека DLL не обнаружена, приложение выводит диалоговое окно с сообщением о ее отсутствии и путях, по которым осуществлялся поиск. Затем процесс отключается.

Если нужная библиотека найдена, она помещается в оперативную память процесса, где и остается до его окончания. Теперь приложение может обращаться к функциям, содержащимся в DLL.

Динамическая загрузка и выгрузка DLL

Вместо того, чтобы Windows выполняла динамическое связывание с DLL при первой загрузке приложения в оперативную память, можно связать программу с модулем библиотеки во время выполнения программы (при таком способе в процессе создания приложения не нужно использовать библиотеку импорта). В частности, можно определить, какая из библиотек DLL доступна пользователю, или разрешить пользователю выбрать, какая из библиотек будет загружаться. Таким образом можно использовать разные DLL, в которых реализованы одни и те же функции, выполняющие различные действия. Например, приложение, предназначенное для независимой передачи данных, сможет в ходе выполнения принять решение, загружать ли DLL для протокола TCP/IP или для другого протокола.

Загрузка обычной DLL

Первое, что необходимо сделать при динамической загрузке DLL, — это поместить модуль библиотеки в память процесса. Данная операция выполняется с помощью функции ::LoadLibrary, имеющей единственный аргумент — имя загружаемого модуля. Соответствующий фрагмент программы должен выглядеть так:

    HINSTANCE hMyDll;
    ::
    if((hMyDll=::    LoadLibrary("MyDLL"))==NULL) { /* не удалось загрузить DLL */ }
    else { /* приложение имеет право пользоваться функциями DLL через hMyDll */ }

Стандартным расширением файла библиотеки Windows считает .dll, если не указать другое расширение. Если в имени файла указан и путь, то только он будет использоваться для поиска файла. В противном случае Windows будет искать файл по той же схеме, что и в случае неявно подключенных DLL, начиная с каталога, из которого загружается exe-файл, и продолжая в соответствии со значением PATH.

Когда Windows обнаружит файл, его полный путь будет сравнен с путем библиотек DLL, уже загруженных данным процессом. Если обнаружится тождество, вместо загрузки копии приложения возвращается дескриптор уже подключенной библиотеки.

Если файл обнаружен и библиотека успешно загрузилась, функция ::LoadLibrary возвращает ее дескриптор, который используется для доступа к функциям библиотеки.

Перед тем, как использовать функции библиотеки, необходимо получить их адрес. Для этого сначала следует воспользоваться директивой typedef для определения типа указателя на функцию и определить переменную этого нового типа, например:

        // тип PFN_MyFunction будет объявлять указатель на функцию, 
    // принимающую указатель на символьный буфер и выдающую значение типа int
    typedef int (WINAPI *PFN_MyFunction)(char *);
    ::
    PFN_MyFunction pfnMyFunction;

Затем следует получить дескриптор библиотеки, при помощи которого и определить адреса функций, например адрес функции с именем MyFunction:

    hMyDll=::LoadLibrary("MyDLL");
    pfnMyFunction=(PFN_MyFunction)::GetProcAddress(hMyDll,"MyFunction");
    ::
    int iCode=(*pfnMyFunction)("Hello");

Адрес функции определяется при помощи функции ::GetProcAddress, ей следует передать имя библиотеки и имя функции. Последнее должно передаваться в том виде, в котором экспортируется из DLL.

Можно также сослаться на функцию по порядковому номеру, по которому она экспортируется (при этом для создания библиотеки должен использоваться def-файл, об этом будет рассказано далее):

    pfnMyFunction=(PFN_MyFunction)::GetProcAddress(hMyDll,
                MAKEINTRESOURCE(1));

После завершения работы с библиотекой динамической компоновки, ее можно выгрузить из памяти процесса с помощью функции ::FreeLibrary:

    ::FreeLibrary(hMyDll);

Загрузка MFC-расширений динамических библиотек

При загрузке MFC-расширений для DLL (подробно о которых рассказывается далее) вместо функций LoadLibraryи FreeLibrary используются функции AfxLoadLibrary и AfxFreeLibrary. Последние почти идентичны функциям Win32 API. Они лишь гарантируют дополнительно, что структуры MFC, инициализированные расширением DLL, не были запорчены другими потоками.

Ресурсы DLL

Динамическая загрузка применима и к ресурсам DLL, используемым MFC для загрузки стандартных ресурсов приложения. Для этого сначала необходимо вызвать функцию LoadLibrary и разместить DLL в памяти. Затем с помощью функции AfxSetResourceHandle нужно подготовить окно программы к приему ресурсов из вновь загруженной библиотеки. В противном случае ресурсы будут загружаться из файлов, подключенных к выполняемому файлу процесса. Такой подход удобен, если нужно использовать различные наборы ресурсов, например для разных языков.

Замечание. С помощью функции LoadLibrary можно также загружать в память исполняемые файлы (не запускать их на выполнение!). Дескриптор выполняемого модуля может затем использоваться при обращении к функциям FindResource и LoadResource для поиска и загрузки ресурсов приложения. Выгружают модули из памяти также при помощи функции FreeLibrary.

Пример обычной DLL и способов загрузки

Приведем исходный код динамически подключаемой библиотеки, которая называется MyDLL и содержит одну функцию MyFunction, которая просто выводит сообщение.

Сначала в заголовочном файле определяется макроконтстанта EXPORT. Использование этого ключевого слова при определении некоторой функции динамически подключаемой библиотеке позволяет сообщить компоновщику, что эта функция доступна для использования другими программами, в результате чего он заносит ее в библиотеку импорта. Кроме этого, такая функция, точно так же, как и оконная процедура, должна определяться с помощью константы CALLBACK:

MyDLL.h
    #define EXPORT extern "C" __declspec (dllexport)
    EXPORT int CALLBACK MyFunction(char *str);

Файл библиотеки также несколько отличается от обычных файлов на языке C для Windows. В нем вместо функции WinMain имеется функция DllMain. Эта функция используется для выполнения инициализации, о чем будет рассказано позже. Для того, чтобы библиотека осталась после ее загрузки в памяти, и можно было вызывать ее функции, необходимо, чтобы ее возвращаемым значением было TRUE:

MyDLL.c
    #include <windows.h>
    #include "MyDLL.h"

    int WINAPI DllMain(HINSTANCE hInstance, DWORD fdReason, PVOID pvReserved)
    {
        return TRUE;
    }
    EXPORT int CALLBACK MyFunction(char *str)
    {
        MessageBox(NULL,str,"Function from DLL",MB_OK);
        return 1;
    }

После трансляции и компоновки этих файлов появляется два файла — MyDLL.dll (сама динамически подключаемая библиотека) и MyDLL.lib (ее библиотека импорта).

Пример неявного подключения DLL приложением

Приведем теперь исходный код простого приложения, которое использует функцию MyFunction из библиотеки MyDLL.dll:

    #include <windows.h>
    #include "MyDLL.h"

    int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
            LPSTR lpCmdLine, int nCmdShow)
    {
        int iCode=MyFunction("Hello");
        return 0;
    }

Эта программа выглядит как обычная программ для Windows, чем она в сущности и является. Тем не менее, следует обратить внимание, что в исходный ее текст помимо вызова функции MyFunction из DLL-библиотеки включен и заголовочный файл этой библиотеки MyDLL.h. Также необходимо на этапе компоновки приложения подключить к нему библиотеку импорта MyDLL.lib (процесс неявного подключения DLL к исполняемому модулю).

Чрезвычайно важно понимать, что сам код функции MyFunction не включается в файл MyApp.exe. Вместо этого там просто имеется ссылка на файл MyDLL.dll и ссылка на функцию MyFunction, которая находится в этом файле. Файл MyApp.exe требует запуска файла MyDLL.dll.

Заголовочный файл MyDLL.h включен в файл с исходным текстом программы MyApp.c точно так же, как туда включен файл windows.h. Включение библиотеки импорта MyDLL.lib для компоновки аналогично включению туда всех библиотек импорта Windows. Когда программа MyApp.exe работает, она подключается к библиотеке MyDLL.dll точно так же, как ко всем стандартным динамически подключаемым библиотекам Windows.

Пример динамической загрузки DLL приложением

Приведем теперь полностью исходный код простого приложения, которое использует функцию MyFunction из библиотеки MyDLL.dll, используя динамическую загрузку библиотеки:

    #include <windows.h>
    typedef int (WINAPI *PFN_MyFunction)(char *);

    int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
            LPSTR lpCmdLine, int nCmdShow)
    {
        HINSTANCE hMyDll;
        if((hMyDll=LoadLibrary("MyDLL"))==NULL) return 1;

        PFN_MyFunction pfnMyFunction;
        pfnMyFunction=(PFN_MyFunction)GetProcAddress(hMyDll,"MyFunction");
        int iCode=(*pfnMyFunction)("Hello");

        FreeLibrary(hMyDll);
        return 0;
    }

Создание DLL

Теперь, познакомившись с принципами работы библиотек DLL в приложениях, рассмотрим способы их создания. При разработке приложении функции, к которым обращается несколько процессов, желательно размещать в DLL. Это позволяет более рационально использовать память в Windows.

Проще всего создать новый проект DLL с помощью мастера AppWizard, который автоматически выполняет многие операции. Для простых DLL, таких как рассмотренные в этой главе, необходимо выбрать тип проекта Win32 Dynamic-Link Library. Новому проекту будут присвоены все необходимые параметры для создания библиотеки DLL. Файлы исходных текстов придется добавлять к проекту вручную.

Если же планируется в полной мере использовать функциональные возможности MFC, такие как документы и представления, или намерены создать сервер автоматизации OLE, лучше выбрать тип проекта MFC AppWizard (dll). В этом случае, помимо присвоения проекту параметров для подключения динамических библиотек, мастер проделает некоторую дополнительную работу. В проект будут добавлены необходимые ссылки на библиотеки MFC и файлы исходных текстов, содержащие описание и реализацию в библиотеке DLL объекта класса приложения, производного от CWinApp.

Иногда удобно сначала создать проект типа MFC AppWizard (dll) в качестве тестового приложения, а затем — библиотеку DLL в виде его составной части. В результате DLL в случае необходимости будет создаваться автоматически.

Функция DllMain

Большинство библиотек DLL — просто коллекции практически независимых друг от друга функций, экспортируемых в приложения и используемых в них. Кроме функций, предназначенных для экспортирования, в каждой библиотеке DLL есть функция DllMain. Эта функция предназначена для инициализации и очистки DLL. Она пришла на смену функциям LibMain и WEP, применявшимся в предыдущих версиях Windows. Структура простейшей функции DllMain может выглядеть, например, так:

    BOOL WINAPI DllMain (HANDLE hInst,DWORD dwReason, LPVOID IpReserved)
    {
        BOOL bAllWentWell=TRUE;
        switch (dwReason) 
        {
            case DLL_PROCESS_ATTACH:     // Инициализация процесса. 
                break;
            case DLL_THREAD_ATTACH:     // Инициализация потока.
                break;
            case DLL_THREAD_DETACH:     // Очистка структур потока.
                break;
            case DLL_PROCESS_DETACH:     // Очистка структур процесса.
                break;
        }
        if(bAllWentWell)     return TRUE;
        else            return FALSE;
    }

Функция DllMain вызывается в нескольких случаях. Причина ее вызова определяется параметром dwReason, который может принимать одно из следующих значений.

При первой загрузке библиотеки DLL процессом вызывается функция DllMain с dwReason, равным DLL_PROCESS_ATTACH. Каждый раз при создании процессом нового потока DllMainO вызывается с dwReason, равным DLL_THREAD_ATTACH (кроме первого потока, потому что в этом случае dwReason равен DLL_PROCESS_ATTACH).

По окончании работы процесса с DLL функция DllMain вызывается с параметром dwReason, равным DLL_PROCESS_DETACH. При уничтожении потока (кроме первого) dwReason будет равен DLL_THREAD_DETACH.

Все операции по инициализации и очистке для процессов и потоков, в которых нуждается DLL, необходимо выполнять на основании значения dwReason, как было показано в предыдущем примере. Инициализация процессов обычно ограничивается выделением ресурсов, совместно используемых потоками, в частности загрузкой разделяемых файлов и инициализацией библиотек. Инициализация потоков применяется для настройки режимов, свойственных только данному потоку, например для инициализации локальной памяти.

В состав DLL могут входить ресурсы, не принадлежащие вызывающему эту библиотеку приложению. Если функции DLL работают с ресурсами DLL, было бы, очевидно, полезно сохранить где-нибудь в укромном месте дескриптор hInst и использовать его при загрузке ресурсов из DLL. Указатель IpReserved зарезервирован для внутреннего использования Windows. Следовательно, приложение не должно претендовать на него. Можно лишь проверить его значение. Если библиотека DLL была загружена динамически, оно будет равно NULL. При статической загрузке этот указатель будет ненулевым.

В случае успешного завершения функция DllMain должна возвращать TRUE. В случае возникновения ошибки возвращается FALSE, и дальнейшие действия прекращаются.

Замечание. Если не написать собственной функции DllMain(), компилятор подключит стандартную версию, которая просто возвращает TRUE.

Экспортирование функций из DLL

Чтобы приложение могло обращаться к функциям динамической библиотеки, каждая из них должна занимать строку в таблице экспортируемых функций DLL. Есть два способа занести функцию в эту таблицу на этапе компиляции.

Метод __declspec (dllexport)

Можно экспортировать функцию из DLL, поставив в начале ее описания модификатор __declspec (dllexport) . Кроме того, в состав MFC входит несколько макросов, определяющих __declspec (dllexport), в том числе AFX_CLASS_EXPORT, AFX_DATA_EXPORT и AFX_API_EXPORT.

Метод __declspec применяется не так часто, как второй метод, работающий с файлами определения модуля (.def), и позволяет лучше управлять процессом экспортирования.

Файлы определения модуля

Синтаксис файлов с расширением .def в Visual C++ достаточно прямолинеен, главным образом потому, что сложные параметры, использовавшиеся в ранних версиях Windows, в Win32 более не применяются. Как станет ясно из следующего простого примера, .def-файл содержит имя и описание библиотеки, а также список экспортируемых функций:

MyDLL.def
    LIBRARY         "MyDLL"
        DESCRIPTION    'MyDLL - пример DLL-библиотеки'

    EXPORTS
        MyFunction     @1

В строке экспорта функции можно указать ее порядковый номер, поставив перед ним символ @. Этот номер будет затем использоваться при обращении к GetProcAddress (). На самом деле компилятор присваивает порядковые номера всем экспортируемым объектам. Однако способ, которым он это делает, отчасти непредсказуем, если не присвоить эти номера явно.

В строке экспорта можно использовать параметр NONAME. Он запрещает компилятору включать имя функции в таблицу экспортирования DLL:

        MyFunction     @1 NONAME

Иногда это позволяет сэкономить много места в файле DLL. Приложения, использующие библиотеку импортирования для неявного подключения DLL, не «заметят» разницы, поскольку при неявном подключении порядковые номера используются автоматически. Приложениям, загружающим библиотеки DLL динамически, потребуется передавать в GetProcAddress порядковый номер, а не имя функции.

При использовании вышеприведенного def-файл описания экспортируемых функций DLL-библиотеки может быть,например, не таким:

    #define EXPORT extern "C" __declspec (dllexport)
    EXPORT int CALLBACK MyFunction(char *str);
    a таким:
    extern "C" int CALLBACK MyFunction(char *str);

Экспортирование классов

Создание .def-файла для экспортирования даже простых классов из динамической библиотеки может оказаться довольно сложным делом. Понадобится явно экспортировать каждую функцию, которая может быть использована внешним приложением.

Если взглянуть на реализованный в классе файл распределения памяти, в нем можно заметить некоторые весьма необычные функции. Оказывается, здесь есть неявные конструкторы и деструкторы, функции, объявленные в макросах MFC, в частности _DECLARE_MESSAGE_MAP, а также функции, которые написанные программистом.

Хотя можно экспортировать каждую из этих функций в отдельности, есть более простой способ. Если в объявлении класса воспользоваться макромодификатором AFX_CLASS_EXPORT, компилятор сам позаботится об экспортировании необходимых функций, позволяющих приложению использовать класс, содержащийся в DLL.

Память DLL

В отличие от статических библиотек, которые, по существу, становятся частью кода приложения, библиотеки динамической компоновки в 16-разрядных версиях Windows работали с памятью несколько иначе. Под управлением Win 16 память DLL размещалась вне адресного пространства задачи. Размещение динамических библиотек в глобальной памяти обеспечивало возможность совместного использования их различными задачами.

В Win32 библиотека DLL располагается в области памяти загружающего ее процесса. Каждому процессу предоставляется отдельная копия «глобальной» памяти DLL, которая реинициализируется каждый раз, когда ее загружает новый процесс. Это означает, что динамическая библиотека не может использоваться совместно, в общей памяти, как это было в Winl6.

И все же, выполнив ряд замысловатых манипуляций над сегментом данных DLL, можно создать общую область памяти для всех процессов, использующих данную библиотеку.

Допустим, имеется массив целых чисел, который должен использоваться всеми процессами, загружающими данную DLL. Это можно запрограммировать следующим образом:

    #pragma data_seg(".myseg")
    int sharedlnts[10] ;
        // другие переменные общего пользования
    #pragma data_seg()
    #pragma comment(lib, "msvcrt" "-SECTION:.myseg,rws");

Все переменные, объявленные между директивами #pragma data_seg(), размещаются в сегменте .myseg. Директива #pragma comment () — не обычный комментарий. Она дает указание библиотеке выполняющей системы С пометить новый раздел как разрешенный для чтения, записи и совместного доступа.

Полная компиляция DLL

Если проект динамической библиотеки создан с помощью AppWizard и .def-файл модифицирован соответствующим образом — этого достаточно. Если же файлы проекта создаются вручную или другими способами без помощи AppWizard, в командную строку редактора связей следует включить параметр /DLL. В результате вместо автономного выполняемого файла будет создана библиотека DLL.

Если в .def-файле есть строка LIBRART, указывать явно параметр /DLL в командной строке редактора связей не нужно.

Для MFC предусмотрен ряд особых режимов, касающихся использования динамической библиотекой библиотек MFC. Этому вопросу посвящен следующий раздел.

DLL и MFC

Программист не обязан использовать MFC при создании динамических библиотек. Однако использование MFC открывает ряд очень важных возможностей.

Имеется два уровня использования структуры MFC в DLL. Первый из них — это обычная динамическая библиотека на основе MFC, MFC DLL (regular MFC DLL). Она может использовать MFC, но не может передавать указатели на объекты MFC между DLL и приложениями. Второй уровень реализован в динамических расширениях MFC (MFC extensions DLL). Использование этого вида динамических библиотек требует некоторых дополнительных усилий по настройке, но позволяет свободно обмениваться указателями на объекты MFC между DLL и приложением.

Обычные MFC DLL

Обычные MFC DLL позволяют применять MFC в динамических библиотеках. При этом приложения, обращающиеся к таким библиотекам, не обязательно должны быть построены на основе MFC. В обычных DLL можно использовать MFC любым способом, в том числе создавая в DLL новые классы на базе классов MFC и экспортируя их в приложения.

Однако обычные DLL не могут обмениваться с приложениями указателями на классы, производные от MFC.

Если приложению необходимо обмениваться с DLL указателями на объекты классов MFC или их производных, нужно использовать расширение DLL, описанное в следующем разделе.

Архитектура обычных DLL рассчитана на использование другими средами программирования, такими как Visual Basic и PowerBuilder.

При создании обычной библиотеки MFC DLL с помощью AppWizard выбирается новый проект типа MFC AppWizard (dll). В первом диалоговом окне мастера приложений необходимо выбрать один из режимов для обычных динамических библиотек: «Regular DLL with MFC statistically linked» или «Regular DLL using shared MFC DLL». Первый предусматривает статическое, а второй — динамическое подключение библиотек MFC. Впоследствии режим подключения MFC к DLL можно будет изменить с помощью комбинированного списка на вкладке «General» диалогового окна «Project settings».

Управление информацией о состоянии MFC

В каждом модуле процесса MFC содержится информация о его состоянии. Таким образом, информация о состоянии DLL отлична от информации о состоянии вызвавшего ее приложения. Поэтому любые экспортируемые из библиотеки функции, обращение к которым исходит непосредственно из приложений, должны сообщать MFC, какую информацию состояния использовать. В обычной MFC DLL, использующей динамические библиотеки MFC, перед вызовом любой подпрограммы MFC в начале экспортируемой функции нужно поместить следующую строку:

    AFX_MANAGE_STATE(AfxGetStaticModuleState()) ;

Данный оператор определяет использование соответствующей информации о состоянии во время выполнения функции, обратившейся к данной подпрограмме.

Динамические расширения MFC

MFC позволяет создавать такие библиотеки DLL, которые воспринимаются приложениями не как набор отдельных функций, а как расширения MFC. С помощью данного вида DLL можно создавать новые классы, производные от классов MFC, и использовать их в своих приложениях.

Чтобы обеспечить возможность свободного обмена указателями на объекты MFC между приложением и DLL, нужно создать динамическое расширение MFC. DLL этого типа подключаются к динамическим библиотекам MFC так же, как и любые приложения, использующие динамическое расширение MFC.

Чтобы создать новое динамическое расширение MFC, проще всего, воспользовавшись мастером приложении, присвоить проекту тип MFC AppWizard (dll) и на шаге 1 включить режим «MFC Extension DLL». В результате новому проекту будут присвоены все необходимые атрибуты динамического расширения MFC. Кроме того, будет создана функция DllMain для DLL, выполняющая ряд специфических операций по инициализации расширения DLL. Следует обратить внимание, что динамические библиотеки данного типа не содержат и не должны содержать объектов, производных от CWinApp.

Инициализация динамических расширений

Чтобы «вписаться» в структуру MFC, динамические расширения MFC требуют дополнительной начальной настройки. Соответствующие операции выполняются функцией DllMain. Рассмотрим пример этой функции, созданный мастером AppWizard.

    static AFX_EXTENSION_MODULE MyExtDLL = { NULL, NULL } ;
    extern "C" int APIENTRY
    DllMain(HINSTANCE hinstance, DWORD dwReason, LPVOID IpReserved)
    {
        if (dwReason == DLL_PROCESS_ATTACH)
        {
            TRACED("MYEXT.DLL Initializing!n") ;
            // Extension DLL one-time initialization
            AfxInitExtensionModule(MyExtDLL, hinstance) ;

            // Insert this DLL into the resource chain
            new CDynLinkLibrary(MyExtDLL);
        }
        else if (dwReason == DLL_PROCESS_DETACH)
        {
            TRACED("MYEXT.DLL Terminating!n") ;
        }
        return 1; // ok
    }

Самой важной частью этой функции является вызов AfxInitExtensionModule. Это инициализация динамической библиотеки, позволяющая ей корректно работать в составе структуры MFC. Аргументами данной функции являются передаваемый в DllMain дескриптор библиотеки DLL и структура AFX_EXTENSION_MODULE, содержащая информацию о подключаемой к MFC динамической библиотеке.

Нет необходимости инициализировать структуру AFX_EXTENSION_MODULE явно. Однако объявить ее нужно обязательно. Инициализацией же займется конструктор CDynLinkLibrary. В DLL необходимо создать класс CDynLinkLibrary. Его конструктор не только будет инициализировать структуру AFX_EXTENSION_MODULE, но и добавит новую библиотеку в список DLL, с которыми может работать MFC.

Загрузка динамических расширений MFC

Начиная с версии 4.0 MFC позволяет динамически загружать и выгружать DLL, в том числе и расширения. Для корректного выполнения этих операций над создаваемой DLL в ее функцию DllMain в момент отключения от процесса необходимо добавить вызов AfxTermExtensionModule. Последней функции в качестве параметра передается уже использовавшаяся выше структура AFX_EXTENSION_MODULE. Для этого в текст DllMain нужно добавить следующие строки.

    if(dwReason == DLL_PROCESS_DETACH) 
    {
        AfxTermExtensionModule(MyExtDLL);
    }

Кроме того, следует помнить, что новая библиотека DLL является динамическим расширением и должна загружаться и выгружаться динамически, с помощью функций AfxLoadLibrary и AfxFreeLibrary,а не LoadLibrary и FreeLibrary.

Экспортирование функций из динамических расширений

Рассмотрим теперь, как осуществляется экспортирование в приложение функций и классов из динамического расширения. Хотя добавить в DEF-файл все расширенные имена можно и вручную, лучше использовать модификаторы для объявлений экспортируемых классов и функций, такие как AFX_EXT_CLASS и AFX_EXT_API,например:

    class AFX_EXT_CLASS CMyClass : public CObject
    (
        // Your class declaration
    }
    void AFX_EXT_API MyFunc() ;

7.Какие диалоговые окна предоставляют собой интерфейс, посредством которого пользователь может ввести текстовую строку для поиска и, если необходимо, строку для замены?

8.Какие стандартные диалоги являются модальными, а какие нет? К чему приводит это различие?

Динамически подключаемые библиотеки

Динамически подключаемые библиотеки (dynamic-link libraries, DLLs) — краеугольный камень операционной системы Windows, начиная с самой первой ее версии. В DLL содержатся все функции интерфейса Win32 API. Три самых важных DLL-библиотеки: KERNEL32.DLL (управление памятью, процессами и потоками), USER32.DLL (поддержка пользовательского интерфейса, в том числе функции, связанные с созданием окон и передачей сообщений) и GDI32.DLL (графика и вывод текста).

В Windows есть и другие DLL, функции которых предназначены для более специализированных задач. Например, в ADVAPI32.DLL содержатся функции для

защиты объектов, работы с реестром и регистрации событий, в COMDLG32.DLL

— стандартные диалоговые окна, a LZ32.DLL поддерживает декомпрессию файлов.

Создание DLL

DLL является набором автономных функций, пригодных для использования любой программой, причем в DLL обычно отсутствует код, предназначенный для обработки циклов выборки сообщений или создания окон. Функции DLL пишутся в расчете на то, что их будет вызывать какое-то приложение (ЕХЕфайл) или другая DLL.

Создавая DLL, надо указывать компоновщику ключ /DLL. Он заставляет компоновщика записывать в конечный файл информацию, по которой загрузчик операционной системы определит, что данный файл — DLL, а не приложение.

Чтобы приложение (или другая DLL) могло вызывать функции из DLL,

исполняемый файл нужно сначала спроецировать на адресное пространство вызывающего процесса.

Это делается либо неявной компоновкой при загрузке, либо явной — в период выполнения.

Как только DLL спроецирована на адресное пространство вызывающего процесса,

еефункции доступны всем потокам этого процесса.

Когда поток вызывает из DLL какую-то функцию, та считывает свои параметры из стека потока и размещает в этом стеке собственные локальные переменные.

Кроме того, любые созданные кодом DLL объекты принадлежат вызывающему потоку или процессу — DLL в Win32 ничем не владеет.

Например, если функция из DLL вызывает VirtualAlloc, резервируется регион в адресном пространстве того процесса, которому принадлежит поток, обратившийся к функции

из DLL. Если DLL будет выгружена из адресного пространства процесса, зарезервированный регион не освободится, так как система не фиксирует того, что регион выделен библиотечной функцией. Считается, что он принадлежит процессу и поэтому освободится, только если поток этого процесса вызовет VirtualFree или завершится сам процесс.

Глобальные и статические переменные DLL-библиотеки обрабатываются точно так, как

переменные ЕХЕ – файла, т.е. не разделяются его параллельно выполняемыми экземплярами.

Когда процесс проецирует образ DLL файла на свое адресное пространство, система создает также экземпляры глобальных и статических переменных.

В 16-разрядной Windows DLL-библиотеки обрабатываются иначе, чем в Win32.

В первой DLL-библиотека при загрузке становится в некотором смысле частью операционной системы. Все приложения, выполняемые в данный момент, получают доступ к DLL и всем содержащимся в ней функциям.

В Win32-cpeдe DLL нужно спроецировать на адресное пространство процесса, прежде чем тот сможет вызывать ее функции.

Глобальные и статические данные DLL-библиотек в 16-разрядной Windows и Win32 тоже обрабатываются по-разному.

В первой каждая DLL имеет свой сегмент данных. В нем находятся все глобальные и статические переменные DLL, a также ее закрытая локальная куча. При вызове из DLL функции LocalAlloc соответствующая область памяти выделяется из сегмента данных DLL, размер которого, как и размер всех других сегментов, ограничен 64 Кб.

Вот пример использования DLL для разделения данных между двумя приложениями:

HGLOBAL g_hData = NULL;

void SetData(LPVOID IpvData,

int nSize) { LPVOID Ipv;

g_hData

=

LocalAlloc(LMEM_MOVEABLE,

nSize);

Ipv

=

LocalLock(g_hData);

memcpy(lpv,

IpvData,

nSize);

LocalUnlock(g_hData);

}

void GetData(LPVOID IpvData, int nSize)

{

LPVOID Ipv = LocalLock(g_hData);

memcpy(IpvData, Ipv, nSize);

LocalUnlock(g_hData);

}

Вызов SetData приводит к выделению блока памяти из сегмента данных DLL, копированию в него данных, на которые указывает параметр IpvData, и сохранению описателя блока в глобальной переменной g_hData. Теперь другое при-

ложение может вызвать GetData. Та, используя глобальную переменную g_hData, блокирует выделенную область локальной памяти, копирует данные из нее в буфер, идентифицируемый параметром IpvData, и возвращает управление.

В Win32: во-первых, у DLL в Win32 нет собственных локальных куч. Во-вторых,

глобальные и статические переменные не разделяются между разными проек-

циями одной DLL; система создает отдельный экземпляр глобальной переменной g_hData для каждого процесса, и значения, хранящиеся в разных экземплярах переменной, не обязательно одинаковы.

Проецирование DLL на адресное пространство процесса

Чтобы поток мог вызвать функцию из DLL-библиотеки, последнюю нужно, сначала спроецировать на адресное пространство процесса, которому принадлежит вызывающий поток. Сделать это можно следующими способами:

Неявная компоновка

Неявная компоновка (implicit linking). При сборке приложения компоновщику нужно указать набор LIB-файлов. Каждый такой файл содержит список функций данной

DLL. Обнаружив, что приложение ссылается на функции, упомянутые в LIB-файле для DLL, компоновщик внедряет имя этой DLL в конечный исполняемый файл.

Поиск DLL осуществляется в :

каталоге, содержащем ЕХЕ — файл;

текущем каталоге процесса;

системном каталоге Windows;

основном каталоге Windows;

каталогах, указанных в переменной окружения PATH.

Явная компоновка

Образ DLL-файла можно спроецировать на адресное пространство процесса явным образом для чего один из потоков должен вызвать либо LoadLibrary, либо LoadLibraryEx: HINSTANCE LoadLibrary(LPCTSTR IpszLibFile);

HINSTANCE LoadLibraryEx(LPCTSTR IpszLibFile, HANDLE hFile, DWORD dwFlags);

Обе функции ищут образ DLL-файла и пытаются спроецировать его на адресное пространство вызывающего процесса. Значение типа HINSTANCE, возвращаемое обеими

функциями, сообщает адрес виртуальной памяти, по которому спроецирован образ файла. Если спроецировать DLL на адрес пространство процесса не удалось, функции возвращают NULL.

Обратим внимание на 2 дополнительных параметра функции LoаdLibraryEx: hFile и dwFlags. Первый зарезервирован и должен быть NULL. Во втором можно передать либо 0,

либо комбинацию флагов DONT_RESOLVE_DLL_REFERENCES, LOAD_LIВRARY_AS_DATAFILE и LOAD_WITH_ALTERED_SEARCH_PATH.

Рассмотрим эти параметры:

DONT_RESOLVE_DLL_REFERENCES. Данный флаг заставляет систему

проецировать DLL, не обращаясь к DllMain и с ее помощью инициализирует библиотеку. При загрузке библиотеки система проверяет, используются ли ею другие DLL; если да, то загружает и их. При установке флага

DONT_RESOLVE_DLL_REFERENCES дополнительные DLL автоматически не загружаются.

LOAD_LIBRARY_AS_DATAFILE. DLL проецирует на адресное пространство процесса так, будто это файл данных. При этом система не тратит дополнительного времени на подготовку к исполнению какого-либо кода из данного файл. Этот флаг

стоит указать, если DLL содержит только ресурсы и никаких функций. Также флаг может потребоваться, если Вам нужны ресурсы, содержащиеся в какомнибудь ЕХЕ – файле.

LOAD_WITH_ALTERED_SEARCH_PATH. Изменяет алгоритм, используемый

LoadLibraryEx при поиске DLL-файла. Однако, если данный флаг установлен, функция ищет файл, просматривая каталоги в таком порядке:

1.Каталог, заданный в параметре IpszLibFile.

2.Текущий каталог процесса.

3.Системный каталог Windows.

4.Основной каталог Windows.

5.Каталоги, перечисленные в переменной окружения PATH.

И еще один фактор может повлиять на то, где система ищет файлы DLL. В реестре есть раздел:

HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerKnownDLLs

Здесь может содержаться набор параметров, имена которых совпадают с именами некоторых DLL-файлов. Значения параметров представляют собой строки, идентичные именам параметров, только дополненные расширением “.DLL.”.

Когда Вы вызываете LoadLibrary или LoadLibraryEx, каждая из них сначала

проверяет, указано ли имя DLL вместе с расширением “.DLL”. Если нет, поиск DLL ведется по уже знакомым Вам правилам.

Если же расширение “.DLL” указано, функция его отбрасывает и ищет в разделе реестра KnownDLLs параметр с идентичным именем. Если его нет, вновь применяются описанные ранее правила. Есть — система обращается к значению, связанному с параметром, и пытается загрузить определенную в нем DLL. При этом система ищет DLL в каталоге, на который указывает значение, связанное с параметром реестра DllDirectory.

Если DLL загружается явно, ее можно отключить от адресного пространства процесса функцией FreeLibrary.

BOOL FreeLibrary(HINSTANCE hinstDll);

При вызове FreeLibrary, Вы должны передать значение типа HINSTANCE, которое идентифицирует выгружаемую DLL. Это значение Вы получите, предварительно вызвав

LoadLibran или LoadLibraryEx.

Современные программы состоят из нескольких модулей, которые включают в себя массивы данных, классы,…

Современные программы состоят из нескольких модулей, которые включают в себя массивы данных, классы, сервисы, требуемые библиотеки. Такой подход разрешает при переписывании ПО не редактировать полностью код, а изменять только необходимые функции, которые заключены в составных частях. Так как открыть DLL файл стандартными средствами Windows невозможно, приходится использовать другие методы.

dll открыть

Файлы с расширением DLL – что это и для чего нужны

Файлы DLL – это динамически подключаемые библиотеки. Установленная в операционную систему программа может не иметь в своем составе всех нужных для работы данных, а использовать те, которые уже присутствуют в ОС. За счет этого также достигается экономия памяти – работающие программы используют одни и те же DLL.

Если же программа (или библиотека) будет повреждена, то это не скажется на работоспособности остального ПО.

Когда и как появились

Библиотеки DLL  появились одновременно с ОС Windows. Разработчики предполагали, что это облегчит программирование приложений и поможет упорядочить использование общих ресурсов в течение сеанса работы.

Но со временем выяснилось, что в ряде случаев возникает тупиковая ситуация, которая получила название «DLL hell». Такое случалось, когда два или более приложений требуют доступа к разным (и не совместимым друг с другом) библиотекам. В результате Windows начинала работать нестабильно.

Только в последних версиях ОС удалось создать механизм, предотвращающий возникновения сбоев – технологию Side-by-side assembly, который испытали в XP, но окончательно он стал применяться в Windows Vista.

чем открывать dll

При помощи каких программ открываются файлы с расширением .dll

Программный код ОС Windows – проприетарный. Это значит, что разработчики не предусмотрели штатных средств, применяя которые, пользователь сможет менять системный код. Для открытия DLL придется использовать специальные программные пакеты. А подключать имеющиеся DLL к разрабатываемой программе можно с применением ПО Microsoft.

В Windows 10

Пользователи, работающие в десятой версии Windows, не всегда знают, чем открыть DLL. Для подключения библиотеки к проекту понадобится либо Visual Studio, либо VisualFoxPro. Эти программные комплексы доступны для скачивания на официальном портале компании Microsoft. Для редактирования допускается использовать ResourceHacker – утилиту для ознакомления и редактирования различных типов файлов.

Чтобы открыть динамически подключаемую библиотеку, следует нажать в главном меню:

  1. Пункт «Файл».
  2. «Открыть».
  3. Выбрать требуемую библиотеку, воспользовавшись проводником.
  4. После завершения изменений закрыть файл, сохранив изменения.

открыть файл dll

    Из чего состоит рабочая область программы ResHacker:

    • верхняя главная панель – для запуска функциональных команд: открыть, скомпилировать, сохранить;
    • левое окно – содержит список объектов, которые входят в состав библиотеки;
    • центральная часть – текст программного кода.

      В Windows 7

      Проблема – чем открыть DLL для редактирования в операционной системе Windows 7 решается так же как и для 10 версии. Еще применяется утилита Resource Tuner – редактор ресурсов. Она дает возможность менять код в DLL на свое усмотрение и сохранять библиотеки.

      чем открывать dll файлы

      В онлайн-сервисах

      Это понадобится, если речь идет о страницах сайта. В DLL содержатся скрипты, которые отвечают за корректную работу сервера.

      Открыть библиотеки можно, используя браузеры:

      • Firefox;
      • Opera;
      • Chrome.

        Как открыть DLL, используя Visual Studio

        Программная среда Visual Studio дает возможность создавать, подключать DLL к текущему проекту и редактировать его. Для этого используется синтаксис языка программирования.

        open dll скачать

        Особенности работы с DLL файлами и возможные проблемы

        Некоторые DLL не удастся не только изменить, но даже открыть. Это происходит с защищенными библиотеками и проблема не решается без специальных программ для взлома.

        Пользователи также сталкиваются с отсутствием библиотек, необходимых для работы некоторых программ. ОС при этом выдает сообщение о том, что «файл не найден». Для устранения неисправности требуется отыскать недостающие DLL с помощью поисковых систем и скачать. Затем – поместить в требуемую папку.

        как читать dll

        В редких случаях библиотеки DLL придется зарегистрировать в ОС:

        1. В Windows 7 (и более поздних версиях) войти в каталог, содержащий требуемый файл.
        2. Нажать «Shift» + правую клавишу мышки.
        3. В появившемся меню выбрать строчку: «Открыть окно команд».
        4. Набрать: regsvr32 dllxxxx.dll, где «dllxxxx.dll» – название регистрируемой библиотеки.
        5. Нажать «Enter».

          В качестве итога

          Работой с DLL занимаются программисты, но опытным пользователям также полезно будет знать основы работы с динамически подключаемыми библиотеками. Это может пригодиться для изменения или извлечения данных из файлов прикладных программ.

          DLL (Шаблон:Lang-en — «библиотека динамической компоновки», «динамически подключаемая библиотека») в операционных системах Microsoft Windows и IBM OS/2 — динамическая библиотека, позволяющая многократное использование различными программными приложениями. K DLL относятся также элементы управления ActiveX и драйверы. В системах UNIX аналогичные функции выполняют так называемые общие объекты (Шаблон:Lang-en).

          Формат файлов DLL придерживается тех же соглашений, что и формат исполняемых файлов, сочетая код, таблицы и ресурсы, отличаясь лишь интерпретацией некоторых полей.

          Назначение[]

          Первоначально предполагалось, что введение DLL позволит эффективно организовать память и дисковое пространство, используя только один экземпляр библиотечного модуля для различных приложений. Это было особенно важно для ранних версий Microsoft Windows с жёсткими ограничениями по памяти.

          Далее предполагалось улучшить эффективность разработок и использования системных средств за счёт модульности. Замена DLL-программ с одной версии на другую должна была позволить независимо наращивать систему, не затрагивая приложений. Кроме того, динамические библиотеки могли использоваться разнотипными приложениями — например, Microsoft Office, Microsoft Visual Studio и т. п.

          В дальнейшем идея модульности выросла в концепции Component Object Model и System Object Model.

          Фактически полных преимуществ от внедрения динамически подключаемых библиотек получить не удалось по причине явления, называемого DLL hell («DLL-ад»). DLL hell возникает, когда несколько приложений требуют одновременно различные, не полностью совместимые версии библиотек, что приводит к сбоям в этих приложениях и к конфликтам типа DLL hell, резко снижая общую надёжность операционных систем. Поздние версии Microsoft Windows стали разрешать параллельное использование разных версий DLL (технология Side-by-side assembly), что свело на нет преимущества изначального принципа модульности.

          Ссылки[]

          Шаблон:Викиучебник

          • Dynamic-Link Libraries (Windows)Шаблон:Ref-en
          • «Tutorial for making and using DLL’s»
          • «Delay Load Dlls Error Recovery»
          • Полное описание процесса создания dll в Visual Studio

          Шаблон:Soft-stub
          Шаблон:Rq
          Шаблон:Перевести

           Просмотр этого шаблона Компоненты Microsoft Windows
          Основные

          Aero •
          ClearType •
          Диспетчер рабочего стола •
          DirectX •
          Панель задач
          (Пуск •

          Область уведомлений) •
          Проводник
          (Пространство имён •

          Специальные папки
          Ассоциации файлов) •
          Windows Search
          (Smart folders

          iFilters) •
          GDI •
          WIM
          SMB •
          .NET Framework •
          XPS •
          Active Scripting
          (WSH •

          VBScript •
          JScript) •
          COM
          (OLE •

          DCOM •
          ActiveX •
          Структурированное хранилище
          Сервер транзакций) •
          Теневая копия
          WDDM •
          UAA
          Консоль Win32

          Службы
          управления

          Архивация и восстановление
          COMMAND.COM •
          cmd.exe •
          Средство переноса данных •
          Просмотр событий
          Установщик •
          netsh.exe
          PowerShell •
          Отчёты о проблемах
          rundll32.exe •
          Программа подготовки системы (Sysprep) •
          Настройка системы (MSConfig) •
          Проверка системных файлов
          Индекс производительности •
          Центр обновления •
          Восстановление системы •
          Дефрагментация диска
          Диспетчер задач •
          Диспетчер устройств •
          Консоль управления •
          Очистка диска •
          Панель управления
          (элементы)

          Приложения

          Контакты •
          DVD Maker
          Факсы и сканирование
          Internet Explorer •
          Журнал
          Экранная лупа •
          Media Center •
          Проигрыватель Windows Media •
          Программа совместной работы
          Центр устройств Windows Mobile
          Центр мобильности •
          Экранный диктор
          Paint •
          Редактор личных символов
          Удалённый помощник
          Распознавание речи
          WordPad •
          Блокнот •
          Боковая панель •
          Звукозапись
          Календарь
          Калькулятор
          Ножницы
          Почта •
          Таблица символов •
          Исторические:
          Movie Maker •

          NetMeeting •
          Outlook Express •
          Диспетчер программ •
          Диспетчер файлов •
          Фотоальбом •
          Windows To Go

          Игры

          Chess Titans •
          Mahjong Titans
          Purble Place •
          Пасьянсы (Косынка
          Паук
          Солитер) •
          Сапёр
          Пинбол •
          Червы

          Ядро ОС

          Ntoskrnl.exe •
          Слой аппаратных абстракций (hal.dll) •
          Бездействие системы •
          svchost.exe •
          Реестр •
          Службы •
          Диспетчер управления сервисами
          DLL
          (формат модулей) •

          PE •
          NTLDR •
          Диспетчер загрузки
          Программа входа в систему (winlogon.exe) •
          Консоль восстановления
          Windows RE
          Windows PE •
          Защита ядра от изменений

          Службы

          Autorun.inf •
          Фоновая интеллектуальная служба передачи
          Файловая система стандартного журналирования
          Отчёты об ошибках
          Планировщик классов мультимедиа
          Теневая копия
          Планировщик задач •
          Беспроводная настройка

          Файловые
          системы

          ReFS •
          NTFS
          (Жёсткая ссылка

          Точка соединения •
          Точка монтирования
          Точка повторной обработки
          Символьная ссылка •
          TxF •
          EFS) •
          WinFS •
          FAT •
          exFAT •
          CDFS •
          UDF
          DFS •
          IFS

          Сервер

          Active Directory •
          Службы развёртывания •
          Служба репликации файлов
          DNS
          Домены
          Перенаправление папок
          Hyper-V •
          IIS •
          Media Services
          MSMQ
          Защита доступа к сети (NAP) •
          Службы печати для UNIX
          Удалённое разностное сжатие
          Службы удаленной установки
          Служба управления правами
          Перемещаемые профили пользователей •
          SharePoint •
          Диспетчер системных ресурсов
          Удаленный рабочий стол
          WSUS •
          Групповая политика •
          Координатор распределённых транзакций

          Архитектура

          NT •
          Диспетчер объектов
          Пакеты запроса ввода/вывода
          Диспетчер транзакций ядра
          Диспетчер логических дисков
          Диспетчер учетных записей безопасности
          Защита ресурсов
          lsass.exe
          csrss.exe •
          smss.exe •
          spoolsv.exe
          Запуск

          Безопасность

          BitLocker
          Защитник •
          Предотвращение выполнения данных
          Обязательный контроль целостности
          Защищённый канал данных
          UAC •
          UIPI
          Брандмауэр •
          Центр обеспечения безопасности •
          Защита файлов

          Совместимость

          Подсистема UNIX (Interix) •
          Виртуальная машина DOS •
          Windows on Windows •
          WOW64

          Шаблон:OS/2 API

          Понравилась статья? Поделить с друзьями:
        1. Для чего используется центр обеспечения безопасности windows
        2. Для чего используется технологический принцип windows drag and drop
        3. Для чего используется расширение в имени файла в oc ms windows
        4. Для чего нужна активация windows 10 на ноутбуке
        5. Для чего используется программа системный монитор windows