Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

Dynamic-link library

From Wikipedia, the free encyclopedia
Sharable executable library in Windows and OS/2
This article is about the OS/2 and Windows implementation. For dynamic linking of libraries in general, seeDynamic linker.
Not to be confused withDynamically loaded library.
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 number4D 5A (MZ inASCII)
Developed byMicrosoft
Container forShared library

Adynamic-link library (DLL) is ashared library in theMicrosoftWindows orOS/2operating system. A DLL can containexecutable code (functions),data, andresources.

A DLL file often hasfile extension.dll even though this is not required. The extension is sometimes used to describe the content of the file. For example,.ocx is a common extension for anActiveX control and.drv for a legacy (16-bit)device driver.

A DLL that contains only resources can be called aresource DLL. Examples include anicon library, with common extension.icl, and afont library with common extensions.fon and.fot.[1]

Thefile format of a DLL is the same as for anexecutable (a.k.a.EXE). The main difference between a DLL file and an EXE file is that a DLL cannot be run directly since the operating system requires anentry point to start execution. Windows provides a utility program (RUNDLL.EXE/RUNDLL32.EXE) to execute a function exposed by a DLL. Since they have the same format, an EXE can be used as a DLL. Consuming code can load an EXE via the same mechanism as loading a DLL.

Background

[edit]

The first versions ofMicrosoft Windows ran programs together in a singleaddress space. Every program was meant to co-operate by yielding the CPU to other programs so that thegraphical 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 DrawingAPI,Graphics Device Interface (GDI), was implemented in a DLL calledGDI.EXE, the user interface inUSER.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 theColor Graphics Adapter display, the HP LaserJetPrinter 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 theWindows 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-sharedstatic 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 unifieddevice 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[update].DLLs provide the standard benefits ofshared libraries, such asmodularity. 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 theComponent Object Model, the underpinnings ofActiveX.

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 ofinter-process communication, or it could accidentally corrupt the different programs. With the introduction of32-bit libraries inWindows 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 ofWindows 95,Windows 98 andWindows Me were built from 16-bit libraries, which limited the performance of thePentium Pro microprocessor when launched, and ultimately limited the stability and scalability of the DOS-based versions of Windows.

Limitations

[edit]

Although the DLL technology is core to the Windows architecture, it has drawbacks.

DLL hell

[edit]

DLL hell describes the bad behavior of an application when the wrong version of a DLL is consumed.[2] Mitigation strategies include:

Shared memory space

[edit]

The executable code of a DLL runs 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.

Features

[edit]

Upgradability

[edit]

The DLL technology allows for an application to be modified without requiring consuming components to be re-compiled or re-linked. A DLL can be replaced so that the next time the application runs it uses the new DLL version. To work correctly, the DLL changes must maintainbackward compatibility.

Even the operating system can be upgraded since it is exposed to the applications via DLLs. System DLLs can be replaced so that the next time the applications run, they use the new system DLLs.

Memory management

[edit]

InWindows API, DLL files are organized intosections. 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 thepage file. Windows does not useposition-independent code for its DLLs; instead, the code undergoesrelocation 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, allowinginter-process communication via this shared memory area. However, because user restrictions do not apply to the use of shared DLL memory, this creates asecurity 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 certainexecutable 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 viakernel32.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 Unixar 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 itsGNU 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 abinary 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 tobind an executable to a specific version of a DLL, that is, to resolve the addresses of imported functions at compile-time. For bound imports, thelinker 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 asMD5 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 asrun-time dynamic linking by Microsoft, by using theLoadLibrary (orLoadLibraryEx) API function. TheGetProcAddress API function is used to look up exported symbols by name, andFreeLibrary – to unload the DLL. These functions are analogous todlopen,dlsym, anddlclose in thePOSIX standard API.

The procedure for explicit run-time linking is the same in any language that supportspointers to functions, since it depends on theWindows 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 throughLoadLibrary andGetProcAddress 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 anexception, 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 notificationhooks, allowing the application to perform additional processing orerror 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 keywordlibrary is used instead ofprogram. At the end of the file, the functions to be exported are listed inexports clause.

Delphi does not needLIB files to import functions from DLLs; to link to a DLL, theexternal keyword is used in the function declaration to signal the DLL name, followed byname to name the symbol (if different) orindex to identify the index.

Microsoft Visual Basic

[edit]

InVisual Basic (VB), only run-time linking is supported; but in addition to usingLoadLibrary andGetProcAddress API functions,declarations of imported functions are allowed.

When importing DLL functions through declarations, VB will generate a run-time error if theDLL 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]

MicrosoftVisual C++ (MSVC) provides several extensions to standardC++ which allow functions to be specified as imported or exported directly in the C++ code; these have been adopted by other WindowsC and C++ compilers, including Windows versions ofGCC. These extensions use the attribute__declspec before a function declaration. Note that when C functions are accessed from C++, they must also be declared asextern "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 theDEF file used by the project. TheDEF file is processed by the linker, rather than the compiler, and thus it is not specific to C++.

DLL compilation will produce bothDLL andLIB files. TheLIB 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 aComponent Object Model (COM) server, theDLL 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 theregistry 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

[edit]
{$APPTYPE CONSOLE}programExample;// import function that adds two numbersfunctionAddNumbers(a,b:Double):Double;StdCall;external'Example.dll';// main programvarR:Double;beginR:=AddNumbers(1,2);Writeln('The result was: ',R);end.

C

[edit]

Example.lib file must be included (assuming thatExample.dll is generated) in the project before static linking. The fileExample.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 ofAddNumbers. The DLL fileExample.dll may also have to be copied to the location where the executable would be generated by the following code:

#include<stdio.h>#include<windows.h>// Import function that adds two numbersextern"C"__declspec(dllimport)doubleAddNumbers(doublea,doubleb);intmain(intargc,char*argv[]){doubleresult=AddNumbers(1,2);printf("The result was: %f\n",result);return0;}

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 toDLL preloading attacks, since example.dll can be resolved to a place unintended by the author (unless explicitly excluded the application directory goesbefore system library locations, and withoutHKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\SafeDllSearchMode[9] orHKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\CWDIllegalInDLLSearch[10] the current working directory is looked up before the system library directories), and thus to a malicious version of the library. See the reference for Microsoft's guidance on safe library loading: one should useSetDefaultDllDirectories inkernel32 to remove both the application directory and the current working directory from the DLL search path, or useSetDllDirectoryW inkernel32 to remove the current working directory from the DLL search path.[11]

Microsoft Visual Basic

[edit]
OptionExplicitDeclareFunctionAddNumbersLib"Example.dll"_(ByValaAsDouble,ByValbAsDouble)AsDoubleSubMain()DimResultAsDoubleResult=AddNumbers(1,2)Debug.Print"The result was: "&ResultEndSub

Delphi

[edit]
programExample;{$APPTYPE CONSOLE}usesWindows;varAddNumbers:function(a,b:integer):Double;StdCall;LibHandle:HMODULE;beginLibHandle:=LoadLibrary('example.dll');ifLibHandle<>0thenAddNumbers:=GetProcAddress(LibHandle,'AddNumbers');ifAssigned(AddNumbers)thenWriteln('1 + 2 = ',AddNumbers(1,2));Readln;end.

C

[edit]
#include<stdio.h>#include<windows.h>// DLL function signaturetypedefdouble(*ImportedFunction)(double,double);intmain(intargc,char*argv[]){ImportedFunctionaddNumbers;doubleresult;HINSTANCEhinstLib;// Load DLL filehinstLib=LoadLibrary(TEXT("Example.dll"));if(!hinstLib){printf("ERROR: unable to load DLL\n");return1;}// Get function pointeraddNumbers=(ImportedFunction)GetProcAddress(hinstLib,"AddNumbers");if(!addNumbers){printf("ERROR: unable to find DLL function\n");FreeLibrary(hinstLib);return1;}// Call function.result=addNumbers(1,3);// Unload DLL fileFreeLibrary(hinstLib);// Display resultprintf("The result was: %f\n",result);return0;}

Python

[edit]
The Python interpreter uses thectypes module which provides aforeign function interface (FFI) which allows calls to functions in shared libraries.

The Python ctypes binding will use POSIX API on POSIX systems.[12]

importctypesmy_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_doublep=my_dll.AddNumbers(ctypes.c_double(1.0),ctypes.c_double(2.0))print("The result was:",p)

Component Object Model

[edit]

TheComponent Object Model (COM) defines a binary standard to host the implementation ofobjects 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.[13]

DLL hijacking

[edit]

Due to avulnerability 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.[14][15][16][17] The vulnerability was discovered by Georgi Guninski in 2000.[18]In August 2010 it gained worldwide publicity after ACROS Security rediscovered it and many hundreds of programs were found vulnerable.[19]Programs that are run from unsafe locations, i.e. user-writable folders like theDownloads or theTemp directory, are almost always susceptible to this vulnerability.[20][21][22][23][24][25][26]

See also

[edit]
  • Dependency Walker – utility which displays exported and imported functions of DLL and EXE files
  • Dynamic library – Software library used via dynamic linking
  • Library (computing) – Collection of resources used to develop a computer program
  • Linker (computing) – Program that combines intermediate build files into an executable file
  • Loadable kernel module – Dynamically loadable module that extends a running operating system kernel
  • Loader (computing) – Part of an operating system
  • Moricons.dll – Graphical shell for early Windows systemsPages displaying short descriptions of redirect targets
  • Shared library – Software library designed for use in multiple programs
  • .exe – Filename extension for a native executable program

References

[edit]
  1. ^Microsoft Corporation (3 August 2021)."Creating a Resource-Only DLL".Microsoft Developer Network Library.
  2. ^"The End of DLL Hell". Microsoft Corporation. Archived fromthe original on 2008-05-06. Retrieved2009-07-11.
  3. ^"Understanding the Import Address Table".Sandsprite.com.Archived from the original on November 7, 2023. RetrievedNovember 7, 2023.
  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.[dead link]
  5. ^"ld and WIN32".ld documentation.
  6. ^"Linker Support for Delay-Loaded DLLs". Microsoft Corporation. Retrieved2009-07-11.
  7. ^Petrusha, Ron (2005-04-26)."Creating a Windows DLL with Visual Basic". O'Reilly Media. Retrieved2009-07-11.
  8. ^MSDN, Using extern to Specify Linkage
  9. ^"Dynamic-link library search order".Microsoft Developer Network. 9 February 2023. Retrieved9 February 2023.
  10. ^"A new CWDIllegalInDllSearch registry entry is available to control the DLL search path algorithm".Microsoft Support.
  11. ^"Secure loading of libraries to prevent DLL preloading attacks".Microsoft Support. Retrieved28 October 2019.
  12. ^"ctypes — A foreign function library for Python".Python documentation. Retrieved9 July 2025.
  13. ^Satran, Michael (21 August 2020)."Component Object Model (COM)".msdn.microsoft.com.
  14. ^Björklund, Andreas; Klövstedt, Johan; Westergren, Sven."DLL Spoofing in Windows"(PDF).Information Technology Department, Uppsala University.Archived(PDF) from the original on November 7, 2023. RetrievedNovember 7, 2023.
  15. ^"DLL Preloading Attacks".msdn.com. Retrieved25 March 2018.
  16. ^"More information about the DLL Preloading remote attack vector".technet.com. Retrieved25 March 2018.
  17. ^"An update on the DLL-preloading remote attack vector".technet.com. Retrieved25 March 2018.
  18. ^"Double clicking on MS Office documents from Windows Explorer may execute arbitrary programs in some cases".www.guninski.com. Retrieved25 March 2018.
  19. ^"Binary Planting - The Official Web Site of a Forgotten Vulnerability . ACROS Security".www.binaryplanting.com. Retrieved25 March 2018.
  20. ^Dormann, Will (September 4, 2008)."Carpet Bombing and Directory Poisoning".Carnegie Mellon University - SEI Blog.Archived from the original on November 7, 2023. RetrievedNovember 7, 2023.
  21. ^"Dev to Mozilla: Please dump ancient Windows install processes".theregister.co.uk. Retrieved25 March 2018.
  22. ^"Gpg4win - Security Advisory Gpg4win 2015-11-25".www.gpg4win.org. Retrieved25 March 2018.
  23. ^"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. Retrieved25 March 2018.
  24. ^"fsc-2015-4 - F-Secure Labs".www.f-secure.com. Archived fromthe original on 31 July 2017. Retrieved25 March 2018.
  25. ^"ScanNow DLL Search Order Hijacking Vulnerability and Deprecation".rapid7.com. 21 December 2015. Retrieved25 March 2018.
  26. ^Team, VeraCrypt."oss-sec: CVE-2016-1281: TrueCrypt and VeraCrypt Windows installers allow arbitrary code execution with elevation of privilege".seclists.org. Retrieved25 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]
Management
tools
Apps
Shell
Services
File systems
Server
Architecture
Security
Compatibility
API
Games
Discontinued
Games
Apps
Others
Spun off to
Microsoft Store
Retrieved from "https://en.wikipedia.org/w/index.php?title=Dynamic-link_library&oldid=1315644541"
Categories:
Hidden categories:

[8]ページ先頭

©2009-2025 Movatter.jp