Dll link Usage Details

Source: Internet
Author: User
Tags comparison table export class

Dll link Usage Details

About Dll

Dll and Exe are binary files in PE format. Dll is equivalent to the so file in Linux.

1 Base Address and RelativeVirtual Address)

BaseAddress and Relative Virtual Address are the concepts of PE files. When a PE file is loaded, the starting Address of the process space is the base Address, this value is the value of the Image Base in the PE file. In the exe file, the Image Base value is 0x40 0000; In the Dll, The ImageBase value is 0x1000 0000.

RVL is the offset from the base address. Because the base address may be occupied by other PES, the base address is redirected. Therefore, all addresses used in the PE are RVL.

 

2 about lib

The lib file generated in the Dll does not contain code and data. It is used to describe the dll export symbol. It is used to find the variables and functions in the Dll when linking the program, it contains the import symbols and "pile code" required by the program to link the Dll, so it plays a bonding and glue role.

 

3. Export functions and methods for adding symbols to Dll

<1> declspec (dllexport)

<2> use the def (module definition) File

 

4. Import Dll

Use two methods to use dll in a program

<1> implicit Loading

Use the H file, lib file, and dll file. In this case, the lib file serves as a link program.

<2> explicit Loading

Use the LoadLibrary function, the GetProcAddress function, and the FreeLibaray function for explicit loading. It is troublesome to use this method. It first needs to define a function pointer, then use the GetProcAddress function to return the function address based on the function name or serial number, and finally release the library.

The compiler may modify the name of a function and add various prefixes and suffixes. Therefore, you may not be able to find the function by name. Use the serial number of the function, because the serial number of the function may be changed due to the Dll upgrade. In this way, unexpected errors may occur when you use the serial number to search for the function.

 

5. symbol export table

The symbol export table provides a ing between the symbol name and the symbol address. You can use the symbol name to find the symbol address.

typedef struct_IMAGE_EXPORT_DIRECTORY {    DWORD  Characteristics;       //not use,always 0    DWORD  TimeDateStamp;    //file generatetime    WORD   MajorVersion;          //notuse,always 0    WORD   MinorVersion;          //notuse,always 0    DWORD  Name;                       //model’sreal name    DWORD  Base;                         //base    DWORD  NumberOfFunctions;      //maximumof order    DWORD  NumberOfNames;           //numberof Names    DWORD  AddressOfFunctions;      // RVA from base of image    DWORD  AddressOfNames;                    // RVA from base of image    DWORD  AddressOfNameOrdinals;  // RVA from base of image}IMAGE_EXPORT_DIRECTORY, *PIMAGE_EXPORT_DIRECTORY;

Use dumpbin to view the dll information, including the following section:

Section contains the following exports forVCDll. dll

 

00000000 characteristics

52C0392A time date stamp Sun Dec 29 23:00:58 2013

0.00 version

1 ordinal base

3 number of functions

3 numberNames

 

Ordinal hint RVA name

 

1 0 0001113B? Mul @ YGHHH @ Z

2 1 00011d? Sub @ YAHHH @ Z

3 2 000110C3 add

We can see that this description corresponds to IMAGE_EXPORT_DIRECTORY.

Number of functions:

The maximum number of function numbers (so it does not necessarily represent the number of functions ). If you specify a function with the serial Number of 5 in the def file, the Number of functions is equal to 5 even if the function with the serial Number of 4 does not exist.

Number of Names:

 

AddressOfFunctions:

It points to EAT (Export Address Table), which stores the RVA of each function.

AddressOfNames:

It points to the function name table, which is sorted by ASCII encoding.

AddressOfNameOrdinals:

This is a comparison table of function names and serial numbers.

<1> advantages of serial number:

Early computer memory was very small. It would be a luxury to use a function name table to store functions, because adding hundreds of function names to the memory would occupy a lot of memory, to solve this problem, the serial number method is adopted. Each serial number corresponds to a function and the corresponding function address is directly found based on the serial number.

<2> serial number defects:

When the Dll is updated, the sequence number of the function may change. Therefore, if the Dll is updated, a function loading error may occur.

<3> necessity of Sequence Number:

When we find a function, we find the serial number for it. Therefore, the serial number must exist. On the contrary, the function name is not necessarily required, because when we find the function address based on the Function Name, first, find the serial number corresponding to the function name and then find the address based on the serial number. This is also the reason why AddressOfNameOrdinals exists.

<4> Search for functions by serial number

The value of the serial number-Base corresponding to the function is worth the index value. Based on this index value, find the relative offset address in the EAT and obtain the address of the function.

The comparison between the two figures shows that the value of NumberOfFunctions is not necessarily the same as that of NUmberOfNames. At the same time, the address of the function is searched based on the serial number.

 

6. exp File

When creating a Dll, the linker is the same as creating a static link. The first step is to scan all the target files, collect all the symbolic information, and create an export table, to facilitate the linker to put the exported table information in a temporary target file. in the edata segment, the target file is the exp file. This exp is a standard PE/COFF target file, but the extension is exp rather than obj.

The second time, use exp as a common target file and link it with other obj files and output it as a Dll. the edata segment is output to the Dll file and becomes the export table.

 

7. Export redirection

Relocate the export symbol to another Dll. to redirect a function, you can use the module definition file,

For example:

EXPORTS

Xxfunc = xx. dll. Oldfunc

 

8. Import tables

If a program uses functions and variables from a Dll, this behavior is called symbolic import. When a PE file is loaded, a job of the windows loader determines the addresses of all functions and symbols to be imported to achieve dynamic link.

The import table in PE is a struct array of IMAGE_IMPORT_DESCRIPTOR. Each member in the array corresponds to a Dll.

typedef struct_IMAGE_IMPORT_DESCRIPTOR {    union {        DWORD  Characteristics;            // 0 for terminating null import descriptor        DWORD  OriginalFirstThunk;         // RVA to original unbound IAT (PIMAGE_THUNK_DATA)    } DUMMYUNIONNAME;    DWORD  TimeDateStamp;                  // 0 if not bound,                                            // -1 if bound, and real date\time stamp                                            //     inIMAGE_DIRECTORY_ENTRY_BOUND_IMPORT (new BIND)                                            // O.W. date/time stamp of DLL bound to (Old BIND)     DWORD  ForwarderChain;                 // -1 if no forwarders    DWORD  Name;    DWORD  FirstThunk;                     // RVA to IAT (if bound this IAT has actual addresses)}IMAGE_IMPORT_DESCRIPTOR;

<1> FirstThunk

FirstThunk points to an IAT (ImportAddress Table), which is the most important structure in the imported Table. Each element of IAT corresponds to an imported symbol. When the dynamic link ing has not been relocated and the symbols are parsed, the sequence number or symbol name of the imported symbols represented by the elements in IAT; when the windows dynamic linker links the module, the element value is changed to the real address of the symbol by the dynamic linker.

If the highest bit of the IAT element is set to 1, the remaining 31 bits represent the sequence number. If not 1, the element value is the RVA pointing to IMAGE_IMPORT_BY_NAME,

typedef struct_IMAGE_IMPORT_BY_NAME {    WORD   Hint;    BYTE   Name[1];}IMAGE_IMPORT_BY_NAME, *PIMAGE_IMPORT_BY_NAME;

Hint indicates the most likely sequence number value of the import symbol, and Name [1] indicates the symbol Name. When a symbolic name is used for import, the linker will locate the symbolic position in the target export table based on the value of the Hint. If not, use the binary search method to find the symbolic position.

<2> OriginalFirstThunk

OriginalFirstThunk points to an INT (Import Name Table) array, which has the same value as IAT.


9. Delayed Loading

Before VisualC ++ 6.0, the only way to load a DLL at runtime is to use the LoadLibrary and GetProcAddress functions. When an executable file or DLL in the operating system is loaded, the operating system loads the DLL. Starting from Visual C ++ 6.0 and static DLL connections, the linker provides some options to delay DLL loading until the program calls the functions in the DLL.

When linking a dll that supports delayed loading, the linker will generate data similar to that of a common Dll, but the operating system will ignore the data, when the API in the Dll is called for the first time, the special pile code added to the linker is started, and the pile code is responsible for loading the Dll, it calls GetProcAddress to find the function address.

 

10 call the imported Function

Declspec (dllimport) xx func (xx) is used to declare that the function is an external module compiler when the lib library is generated. For the same function, two symbol definitions are generated. For the function func, one symbol is func, and the other is _ imp_func. Func points to the pile code, and _ imp_func points to the position of the func function in IAT. When delspec (dllimport) xx func (xx); is used, the compiler will add _ imp _ before the function to be imported during compilation _, to ensure the correct link to the _ imp_func function in the import/export database, if not, a normal func symbol will be generated to connect to the func symbol definition in the import/export database.

When declaring a function as declspec (dllimport) xx func (xx), the compiler will know that the function is imported externally, it generates an indirect jump command for CALL [XXX.

If declspec (dllimport) xx func (xx) is not added, the compiler will not distinguish whether it is defined in the module or imported externally. It will generate unified direct call commands, however, when a link is connected, external functions are directed to a piece of code,

The control is then handed over to the real address in IAT.

CALL 0x0040100C

....

0x0040100C

Jmp dword ptr [XXX]

It can be seen from this that if declspec (dllimport) is declared, a jump instruction will be reduced, so the function execution efficiency will be higher.

Additional: _ declspec (import) is used in the C ++ export class.

If _ declspec (import) is not applicable to the C ++ export class, static variables in the class cannot be parsed. So if there are static variables in the class, you must use _ declspec (import) to declare the function.

 


How to Use Dynamic Link Library

To create a dynamic Connection Library, follow these steps:

1. Create a Non-mfc dll Dynamic Link Library

1. Open File> New> Project and select Win32 Dynamic-Link Library> sample project.

-> Project name: DllDemo

2. Create a New. h file DllDemo. h

# Ifdef DllDemo_EXPORTS

# Define DllAPI _ declspec (dllexport)

# Else

# Define DllAPI _ declspec (dllimport)

Extern "C" // compiled as is

{

DllAPI int _ stdcall Max (int a, int B); // _ stdcall enables non-C/C ++ languages to call APIs

}

# Endif

3. Import the DllDemo. h file in the DllDemo. cpp file and implement the Max (int, int) function.

# Include "DllDemo. h"

DllAPI int _ stdcall Max (int a, int B)

{

If (a = B)

Return NULL;

Else if (a> B)

Return;

Else

Return B;

}

4. Compile the program to generate a dynamic Connection Library

2. Use the. def file to create a dynamic Connection Library DllDemo. dll.

1. Delete the DllDemo. h file in the DllDemo project.

2. In the DllDemo. cpp file header, delete the # include DllDemo. h Statement.

3. Add a text file named DllDemo. def to the project and write the following statement:

LIBRARY MyDll
EXPORTS
Max @ 1

4. Compile the program to generate a dynamic Connection Library.

Call steps for dynamic links:

1. implicit call

1. Establish the DllCnslTest Project

2. Copy the DllDemo. dll and DllDemo. lib files to the directory where the DllCnslTest project is located.

3. Add the following statement to DllCnslTest. h:

# Define DllAPI _ declspec (dllimport)

# Pragma comment (lib, "DllDemo. lib") // link to the DllDemo. lib file in the link editor.

Extern "C"

{

DllAPI int _ stdcall Max (int a, int B );

}

4. Add the following statement to the DllCnslTest. cpp file:

# Include "DllCnslTest. h" // or # include "DllDemo. h"

Void main ()

{

Int value;

Value = Max (2, 9 );

Printf ("The Max value is % d &... The remaining full text>
 
How does one view the function address inside the dynamic link library file?

I. Concept of Dynamic Link Library
Dynamic Link Library (DLL) is a program module that can be shared by other applications. It encapsulates some routines and resources that can be shared. The file extension of the dynamic link library is generally dll, or drv, sys, and fon. It is very similar to the executable file (exe, the difference is that although the DLL contains executable code, it cannot be executed independently, but should be called directly or indirectly by a Windows application.

Dynamic Links are relative to static links. The so-called static link refers to linking the function or process to be called to the executable file to become part of the executable file. In other words, the function and process code is in the program's exe file, which contains all the code required for running. When multiple programs call the same function, multiple copies of the function exist in the memory, which wastes valuable memory resources. The function code called by the dynamic link is not copied to the executable file of the application, instead, it only adds the description information of the called function (usually some relocation information ). Only when the application is loaded into the memory and starts to run, the connection between the application and the corresponding DLL is established under Windows Management. When you want to execute the functions in the called DLL, the corresponding function code in the DLL is transferred to Windows based on the relocation information generated by the link.

Generally, if an application uses a dynamic link library, the Win32 system ensures that only one copy of the DLL is in the memory, which is implemented through the memory ing file. The DLL is first transferred to the global stack of the Win32 system, and then mapped to the process address space that calls the DLL. In the Win32 system, each process has its own 32-bit linear address space. If a DLL is called by multiple processes, each process will receive an image of the DLL. Unlike a 16-bit Windows, a DLL in Win32 can be considered as the code of each process.

Ii. Advantages of Dynamic Link Library

1. Share code, resources, and data

The main purpose of using DLL is to share the code. The DLL code can be shared by all Windows applications.

2. Hide Implementation Details

The routines in DLL can be accessed by the application, but the application does not know the details of these routines.

3. Expand functions of development tools such as Delphi

Because the DLL is language-independent, you can create a DLL and call it by C ++, VB, or any language that supports dynamic link libraries. In this way, if one language is insufficient, it can be compensated by accessing the DLL created in another language.

Iii. Implementation of Dynamic Link Library

1. Load-time Dynamic Linking

The premise of this usage is that you have clearly known which functions in the DLL to be called before compilation. during compilation, only necessary link information is kept in the target file, excluding the DLL function code; when a program is executed, it uses the link information to load the DLL function code and link it to the execution space of the calling program in the memory. The main purpose is to facilitate code sharing.

2. Run-time Dynamic Linking

This method means that you do not know which DLL functions will be called before compilation, and decide which function to call based on your needs during the running process, use LoadLibrary and GetProcAddress to dynamically obtain the DLL function entry address.

Learn about DLL files in the dynamic link library

DLL is short for Dynamic Link Library, meaning Dynamic Link Library. In Windows, many applications are not a complete executable file. They are divided into relatively independent dynamic link libraries, that is, DLL files, which are placed in the system. When we execute a program, the corresponding DLL file will be called. An application may have multiple DLL files, and a DLL file may also be used by several applications. Such DLL files are called shared DLL files. DLL files are generally stored in the C: WindowsSystem directory.

1. How to know which applications are used... the remaining full text>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.