Tutorial 6: Import Table

PyCon 2012:Python 3迁移与virtualenv普及的关键转折点 Python 3迁移并非始于2015年,而是由PyCon 2012这一技术分水岭正式锚定——它标志着生态从‘能用’迈向‘敢用’的质变。其核心原理在于基础设施协同演进:virtualenv的稳定普及解决了依赖隔离难题,PyPI包数量突破7000个构建了可规模化的协作基础,Django 1.4的时区支持则倒逼数据库与部署流程升级。这一系列变化共同降低了Python 3落地的工程成本,使迁移从理论共识转为生产必需。典型应用场景包括老旧Django系统的渐进式升级、共享主机环境下的无权限部署,以及PyPI包元数据合 阅读详情

We will learn about import table in this tutorial. Let me warn you first. This tutorial is a long and difficult one for those who aren't familiar with the import table. You may need to read this tutorial several times and may even have to examine the related structures under a debugger.

Download the example.

Theory:

First of all, you should know what an import function is. An import function is a function that is not in the caller's module but is called by the module, thus the name "import". The import functions actually reside in one or more DLLs. Only the information about the functions is kept in the caller's module. That information includes the function names and the names of the DLLs in which they reside.
Now how can we find out where in the PE file the information is kept? We must turn to the data directory for the answer. I'll refresh your memory a bit. Below is the PE header:

IMAGE_NT_HEADERS STRUCT
   Signature dd ?
   FileHeader IMAGE_FILE_HEADER <>
   OptionalHeader IMAGE_OPTIONAL_HEADER <>
IMAGE_NT_HEADERS ENDS

The last member of the optional header is the data directory:

IMAGE_OPTIONAL_HEADER32 STRUCT
   ....
   LoaderFlags dd ?
   NumberOfRvaAndSizes dd ?
   DataDirectory IMAGE_DATA_DIRECTORY 16 dup(<>)
IMAGE_OPTIONAL_HEADER32 ENDS

The data directory is an array of IMAGE_DATA_DIRECTORY structure. A total of 16 members. If you remember the section table as the root directory of the sections in a PE file, you should also think of the data directory as the root directory of the logical components stored inside those sections. To be precise, the data directory contains the locations and sizes of the important data structures in the PE file. Each member contains information about an important data structure.

Member
Info inside
0
Export symbols
1
Import symbols
2
Resources
3
Exception
4
Security
5
Base relocation
6
Debug
7
Copyright string
8
Unknown
9
Thread local storage (TLS)
10
Load configuration
11
Bound Import
12
Import Address Table
13
Delay Import
14
COM descriptor

Only the members painted in gold are known to me. Now that you know what each member of the data directory contains, we can learn about the member in detail. Each member of the data directory is a structure called IMAGE_DATA_DIRECTORY which has the following definition:

IMAGE_DATA_DIRECTORY STRUCT
  VirtualAddress dd ?
  isize dd ?
IMAGE_DATA_DIRECTORY ENDS

VirtualAddress is actually the relative virtual address (RVA) of the data structure. For example, if this structure is for import symbols, this field contains the RVA of the IMAGE_IMPORT_DESCRIPTOR array.
isize contains the size in bytes of the data structure referred to by VirtualAddress.

Here's the general scheme on finding important data structures in a PE file:

  1. From the DOS header, you go to the PE header
  2. Obtain the address of the data directory in the optional header.
  3. Multiply the size of IMAGE_DATA_DIRECTORY with the member index you want: for example if you want to know where the import symbols are, you must multiply the size of IMAGE_DATA_DIRECTORY (8 bytes) with 1.
  4. Add the result to the address of the data directory and you have the address of the IMAGE_DATA_DIRECTORY structure that contains the info about the desired data structure.

Now we will enter into the real discussion about the import table. The address of the import table is contained in the VirtualAddress field of the second member of the data directory. The import table is actually an array of IMAGE_IMPORT_DESCRIPTOR structures. Each structure contains information about a DLL the PE file imports symbols from. For example, if the PE file imports functions from 10 different DLLs, there will be 10 members in this array. The array is terminated by the member which contain all zeroes. Now we can examine the structure in detail:

IMAGE_IMPORT_DESCRIPTOR STRUCT
  union
    Characteristics dd ?
    OriginalFirstThunk dd ?
  ends
  TimeDateStamp dd ?
  ForwarderChain dd ?
  Name1 dd ?
  FirstThunk dd ?
IMAGE_IMPORT_DESCRIPTOR ENDS

The first member of this structure is a union. Actually, the union only provides the alias for OriginalFirstThunk, so you can call it "Characteristics". This member contains the the RVA of an array of IMAGE_THUNK_DATA structures.
What is IMAGE_THUNK_DATA? It's a union of dword size. Usually, we interpret it as the pointer to an IMAGE_IMPORT_BY_NAME structure. Note that IMAGE_THUNK_DATA contains the pointer to an IMAGE_IMPORT_BY_NAME structure: not the structure itself.
Look at it this way: There are several IMAGE_IMPORT_BY_NAME structures. We collect the RVA of those structures (IMAGE_THUNK_DATAs) into an array, terminate it with 0. Then we put the RVA of the array into OriginalFirstThunk.
The IMAGE_IMPORT_BY_NAME structure contains information about an import function. Now let's see what IMAGE_IMPORT_BY_NAME structure looks like:

IMAGE_IMPORT_BY_NAME STRUCT
  Hint dw ?
  Name1 db ?
IMAGE_IMPORT_BY_NAME ENDS

Hint contains the index into the export table of the DLL the function resides in. This field is for use by the PE loader so it can look up the function in the DLL's export table quickly.This value is not essential and some linkers may set the value in this field to 0.
Name1 contains the name of the import function. The name is an ASCIIZ string. Note that Name1's size is defined as byte but it's really a variable-sized field. It's just that there is no way to represent a variable-sized field in a structure. The structure is provided so that you can refer to the data structure with descriptive names.

TimeDateStamp and ForwarderChain are advanced stuff: We will talk about them after you have firm grasp of the other members.

Name1 contains the RVA to the name of the DLL, in short, the pointer to the name of the DLL. The string is an ASCIIZ one.

FirstThunk is very similar to OriginalFirstThunk, ie. it contains an RVA of an array of IMAGE_THUNK_DATA structures(a different array though).
Ok, if you're still confused, look at it this way: There are several IMAGE_IMPORT_BY_NAME structures. You create two arrays, then fill them with the RVAs of those IMAGE_IMPORT_BY_NAME structures, so both arrays contain exactly the same values (i.e. exact duplicate). Now you assign the RVA of the first array to OriginalFirstThunk and the RVA of the second array to FirstThunk.

OriginalFirstThunkIMAGE_IMPORT_BY_NAMEFirstThunk

|

 
 
|
IMAGE_THUNK_DATA
IMAGE_THUNK_DATA
IMAGE_THUNK_DATA
IMAGE_THUNK_DATA
...
IMAGE_THUNK_DATA
--->
--->
--->
--->
--->
--->
Function 1
Function 2
Function 3
Function 4
...
Function n
<---
<---
<---
<---
<---
<---
IMAGE_THUNK_DATA
IMAGE_THUNK_DATA
IMAGE_THUNK_DATA
IMAGE_THUNK_DATA
...
IMAGE_THUNK_DATA

Now you should be able to understand what I mean. Don't be confused by the name IMAGE_THUNK_DATA: it's only an RVA into IMAGE_IMPORT_BY_NAME structure. If you replace the word IMAGE_THUNK_DATA with RVA in your mind, you'll perhaps see it more clearly. The number of array elements in OriginalFirstThunk and FirstThunk array depends on the functions the PE file imports from the DLL. For example, if the PE file imports 10 functions from kernel32.dll, Name1 in the IMAGE_IMPORT_DESCRIPTOR structure will contain the RVA of the string "kernel32.dll" and there will be 10 IMAGE_THUNK_DATAs in each array.
The next question is: why do we need two arrays that are exactly the same? To answer that question, we need to know that when the PE file is loaded into memory, the PE loader will look at the IMAGE_THUNK_DATAs and IMAGE_IMPORT_BY_NAMEs and determine the addresses of the import functions. Then it replaces the IMAGE_THUNK_DATAs in the array pointed to by FirstThunk with the real addresses of the functions. Thus when the PE file is ready to run, the above picture is changed to:

OriginalFirstThunk IMAGE_IMPORT_BY_NAME FirstThunk

|

 
 
|
IMAGE_THUNK_DATA
IMAGE_THUNK_DATA
IMAGE_THUNK_DATA
IMAGE_THUNK_DATA
...
IMAGE_THUNK_DATA
--->
--->
--->
--->
--->
--->
Function 1
Function 2
Function 3
Function 4
...
Function n
   
 
 
 
 
 
Address of Function 1
Address of Function 2
Address of Function 3
Address of Function 4
...
Address of Function n

The array of RVAs pointed to by OriginalFirstThunk remains unchanged so that if the need arises to find the names of import functions, the PE loader can still find them.
There is a little twist on this *straightforward* scheme. Some functions are exported by ordinal only. It means you don't call the functions by their names: you call them by their positions. In this case, there will be no IMAGE_IMPORT_BY_NAME structure for that function in the caller's module. Instead, the IMAGE_THUNK_DATA for that function will contain the ordinal of the function in the low word and the most significant bit (MSB) of IMAGE_THUNK_DATA set to 1. For example, if a function is exported by ordinal only and its ordinal is 1234h, the IMAGE_THUNK_DATA for that function will be 80001234h. Microsoft provides a handy constant for testing the MSB of a dword, IMAGE_ORDINAL_FLAG32. It has the value of 80000000h.
Suppose that we want to list the names of ALL import functions of a PE file, we need to follow the steps below:

  1. Verify that the file is a valid PE
  2. From the DOS header, go to the PE header
  3. Obtain the address of the data directory in OptionalHeader
  4. Go to the 2nd member of the data directory. Extract the value of VirtualAddress
  5. Use that value to go to the first IMAGE_IMPORT_DESCRIPTOR structure
  6. Check the value of OriginalFirstThunk. If it's not zero, follow the RVA in OriginalFirstThunk to the RVA array. If OriginalFirstThunk is zero, use the value in FirstThunk instead. Some linkers generate PE files with 0 in OriginalFirstThunk. This is considered a bug. Just to be on the safe side, we check the value in OriginalFirstThunk first.
  7. For each member in the array, we check the value of the member against IMAGE_ORDINAL_FLAG32. If the most significant bit of the member is 1, then the function is exported by ordinal and we can extract the ordinal number from the low word of the member.
  8. If the most significant bit of the member is 0, use the value in the member as the RVA into the IMAGE_IMPORT_BY_NAME, skip Hint, and you're at the name of the function.
  9. Skip to the next array member, and retrieve the names until the end of the array is reached (it's null -terminated). Now we are done extracting the names of the functions imported from a DLL. We go to the next DLL.
  10. Skip to the next IMAGE_IMPORT_DESCRIPTOR and process it. Do that until the end of the array is reached (IMAGE_IMPORT_DESCRIPTOR array is terminated by a member with all zeroes in its fields).

Example:

This example opens a PE file and reads the names of all import functions of that file into an edit control. It also shows the values in the IMAGE_IMPORT_DESCRIPTOR structures.

.386
.model flat,stdcall
option casemap:none
include /masm32/include/windows.inc
include /masm32/include/kernel32.inc
include /masm32/include/comdlg32.inc
include /masm32/include/user32.inc
includelib /masm32/lib/user32.lib
includelib /masm32/lib/kernel32.lib
includelib /masm32/lib/comdlg32.lib

IDD_MAINDLG equ 101
IDC_EDIT equ 1000
IDM_OPEN equ 40001
IDM_EXIT equ 40003

DlgProc proto :DWORD,:DWORD,:DWORD,:DWORD
ShowImportFunctions proto :DWORD
ShowTheFunctions proto :DWORD,:DWORD
AppendText proto :DWORD,:DWORD

SEH struct
PrevLink dd ? ; the address of the previous seh structure
CurrentHandler dd ? ; the address of the new exception handler
SafeOffset dd ? ; The offset where it's safe to continue execution
PrevEsp dd ? ; the old value in esp
PrevEbp dd ? ; The old value in ebp
SEH ends

.data
AppName db "PE tutorial no.6",0
ofn OPENFILENAME <>
FilterString db "Executable Files (*.exe, *.dll)",0,"*.exe;*.dll",0
             db "All Files",0,"*.*",0,0
FileOpenError db "Cannot open the file for reading",0
FileOpenMappingError db "Cannot open the file for memory mapping",0
FileMappingError db "Cannot map the file into memory",0
NotValidPE db "This file is not a valid PE",0
CRLF db 0Dh,0Ah,0
ImportDescriptor db 0Dh,0Ah,"================[ IMAGE_IMPORT_DESCRIPTOR ]=============",0
IDTemplate db "OriginalFirstThunk = %lX",0Dh,0Ah
           db "TimeDateStamp = %lX",0Dh,0Ah
           db "ForwarderChain = %lX",0Dh,0Ah
           db "Name = %s",0Dh,0Ah
           db "FirstThunk = %lX",0
NameHeader db 0Dh,0Ah,"Hint Function",0Dh,0Ah
           db "-----------------------------------------",0
NameTemplate db "%u %s",0
OrdinalTemplate db "%u (ord.)",0

.data?
buffer db 512 dup(?)
hFile dd ?
hMapping dd ?
pMapping dd ?
ValidPE dd ?

.code
start:
invoke GetModuleHandle,NULL
invoke DialogBoxParam, eax, IDD_MAINDLG,NULL,addr DlgProc, 0
invoke ExitProcess, 0

DlgProc proc hDlg:DWORD, uMsg:DWORD, wParam:DWORD, lParam:DWORD
.if uMsg==WM_INITDIALOG
  invoke SendDlgItemMessage,hDlg,IDC_EDIT,EM_SETLIMITTEXT,0,0
.elseif uMsg==WM_CLOSE
  invoke EndDialog,hDlg,0
.elseif uMsg==WM_COMMAND
  .if lParam==0
    mov eax,wParam
    .if ax==IDM_OPEN
      invoke ShowImportFunctions,hDlg
    .else ; IDM_EXIT
      invoke SendMessage,hDlg,WM_CLOSE,0,0
    .endif
  .endif
.else
  mov eax,FALSE
  ret
.endif
mov eax,TRUE
ret
DlgProc endp

SEHHandler proc C pExcept:DWORD, pFrame:DWORD, pContext:DWORD, pDispatch:DWORD
  mov edx,pFrame
  assume edx:ptr SEH
  mov eax,pContext
  assume eax:ptr CONTEXT
  push [edx].SafeOffset
  pop [eax].regEip
  push [edx].PrevEsp
  pop [eax].regEsp
  push [edx].PrevEbp
  pop [eax].regEbp
  mov ValidPE, FALSE
  mov eax,ExceptionContinueExecution
  ret
SEHHandler endp

ShowImportFunctions proc uses edi hDlg:DWORD
  LOCAL seh:SEH
  mov ofn.lStructSize,SIZEOF
  ofn mov ofn.lpstrFilter, OFFSET FilterString
  mov ofn.lpstrFile, OFFSET buffer
  mov ofn.nMaxFile,512
  mov ofn.Flags, OFN_FILEMUSTEXIST or OFN_PATHMUSTEXIST or OFN_LONGNAMES or OFN_EXPLORER or OFN_HIDEREADONLY
  invoke GetOpenFileName, ADDR ofn
  .if eax==TRUE
    invoke CreateFile, addr buffer, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL
    .if eax!=INVALID_HANDLE_VALUE
      mov hFile, eax
      invoke CreateFileMapping, hFile, NULL, PAGE_READONLY,0,0,0
      .if eax!=NULL
        mov hMapping, eax
        invoke MapViewOfFile,hMapping,FILE_MAP_READ,0,0,0
        .if eax!=NULL
          mov pMapping,eax
          assume fs:nothing
          push fs:[0]
          pop seh.PrevLink
          mov seh.CurrentHandler,offset SEHHandler
          mov seh.SafeOffset,offset FinalExit
          lea eax,seh
          mov fs:[0], eax
          mov seh.PrevEsp,esp
          mov seh.PrevEbp,ebp
          mov edi, pMapping
          assume edi:ptr IMAGE_DOS_HEADER
          .if [edi].e_magic==IMAGE_DOS_SIGNATURE
            add edi, [edi].e_lfanew
            assume edi:ptr IMAGE_NT_HEADERS
            .if [edi].Signature==IMAGE_NT_SIGNATURE
              mov ValidPE, TRUE
            .else
              mov ValidPE, FALSE
            .endif
          .else
            mov ValidPE,FALSE
          .endif
FinalExit:
          push seh.PrevLink
          pop fs:[0]
          .if ValidPE==TRUE
            invoke ShowTheFunctions, hDlg, edi
          .else
            invoke MessageBox,0, addr NotValidPE, addr AppName, MB_OK+MB_ICONERROR
          .endif
          invoke UnmapViewOfFile, pMapping
      .else
          invoke MessageBox, 0, addr FileMappingError, addr AppName, MB_OK+MB_ICONERROR
      .endif
      invoke CloseHandle,hMapping
    .else
      invoke MessageBox, 0, addr FileOpenMappingError, addr AppName, MB_OK+MB_ICONERROR
    .endif
    invoke CloseHandle, hFile
   .else
   invoke MessageBox, 0, addr FileOpenError, addr AppName, MB_OK+MB_ICONERROR
   .endif
 .endif
 ret
ShowImportFunctions endp

AppendText proc hDlg:DWORD,pText:DWORD
   invoke SendDlgItemMessage,hDlg,IDC_EDIT,EM_REPLACESEL,0,pText
   invoke SendDlgItemMessage,hDlg,IDC_EDIT,EM_REPLACESEL,0,addr CRLF
   invoke SendDlgItemMessage,hDlg,IDC_EDIT,EM_SETSEL,-1,0
   ret
AppendText endp

RVAToOffset PROC uses edi esi edx ecx pFileMap:DWORD,RVA:DWORD
   mov esi,pFileMap
   assume esi:ptr IMAGE_DOS_HEADER
   add esi,[esi].e_lfanew
   assume esi:ptr IMAGE_NT_HEADERS
   mov edi,RVA ; edi == RVA
   mov edx,esi
   add edx,sizeof IMAGE_NT_HEADERS
   mov cx,[esi].FileHeader.NumberOfSections
   movzx ecx,cx
   assume edx:ptr IMAGE_SECTION_HEADER
   .while ecx>0 ; check all sections
     .if edi>=[edx].VirtualAddress
       mov eax,[edx].VirtualAddress
       add eax,[edx].SizeOfRawData
       .if edi<eax ; The address is in this section
         mov eax,[edx].VirtualAddress
         sub edi,eax
         mov eax,[edx].PointerToRawData
         add eax,edi ; eax == file offset
         ret
       .endif
     .endif
     add edx,sizeof IMAGE_SECTION_HEADER
     dec ecx
   .endw
   assume edx:nothing
   assume esi:nothing
   mov eax,edi
   ret
RVAToOffset endp

ShowTheFunctions proc uses esi ecx ebx hDlg:DWORD, pNTHdr:DWORD
   LOCAL temp[512]:BYTE
   invoke SetDlgItemText,hDlg,IDC_EDIT,0
   invoke AppendText,hDlg,addr buffer
   mov edi,pNTHdr
   assume edi:ptr IMAGE_NT_HEADERS
   mov edi, [edi].OptionalHeader.DataDirectory[sizeof IMAGE_DATA_DIRECTORY].VirtualAddress
   invoke RVAToOffset,pMapping,edi
   mov edi,eax
   add edi,pMapping
   assume edi:ptr IMAGE_IMPORT_DESCRIPTOR
   .while !([edi].OriginalFirstThunk==0 && [edi].TimeDateStamp==0 && [edi].ForwarderChain==0 && [edi].Name1==0 && [edi].FirstThunk==0)
     invoke AppendText,hDlg,addr ImportDescriptor
     invoke RVAToOffset,pMapping, [edi].Name1
     mov edx,eax
     add edx,pMapping
     invoke wsprintf, addr temp, addr IDTemplate, [edi].OriginalFirstThunk,[edi].TimeDateStamp,[edi].ForwarderChain,edx,[edi].FirstThunk      invoke AppendText,hDlg,addr temp
     .if [edi].OriginalFirstThunk==0
        mov esi,[edi].FirstThunk
     .else
        mov esi,[edi].OriginalFirstThunk
     .endif
     invoke RVAToOffset,pMapping,esi
     add eax,pMapping
     mov esi,eax
     invoke AppendText,hDlg,addr NameHeader
     .while dword ptr [esi]!=0
       test dword ptr [esi],IMAGE_ORDINAL_FLAG32
       jnz ImportByOrdinal
       invoke RVAToOffset,pMapping,dword ptr [esi]
       mov edx,eax
       add edx,pMapping
       assume edx:ptr IMAGE_IMPORT_BY_NAME
       mov cx, [edx].Hint
       movzx ecx,cx
       invoke wsprintf,addr temp,addr NameTemplate,ecx,addr [edx].Name1
       jmp ShowTheText
ImportByOrdinal:
       mov edx,dword ptr [esi]
       and edx,0FFFFh
       invoke wsprintf,addr temp,addr OrdinalTemplate,edx
ShowTheText:
       invoke AppendText,hDlg,addr temp
       add esi,4
    .endw
    add edi,sizeof IMAGE_IMPORT_DESCRIPTOR
  .endw
  ret
ShowTheFunctions endp
end start

Analysis:

The program shows an open file dialog box when the user clicks Open in the menu. It verifies that the file is a valid PE and then calls ShowTheFunctions.

ShowTheFunctions proc uses esi ecx ebx hDlg:DWORD, pNTHdr:DWORD
   LOCAL temp[512]:BYTE

Reserve 512 bytes of stack space for string operation.

   invoke SetDlgItemText,hDlg,IDC_EDIT,0

Clear the text in the edit control

   invoke AppendText,hDlg,addr buffer

Insert the name of the PE file into the edit control. AppendText just sends EM_REPLACESEL messages to append the text to the edit control. Note that it sends EM_SETSEL with wParam=-1 and lParam=0 to the edit control to move the cursor to the end of the text.

   mov edi,pNTHdr
   assume edi:ptr IMAGE_NT_HEADERS
   mov edi, [edi].OptionalHeader.DataDirectory[sizeof IMAGE_DATA_DIRECTORY].VirtualAddress

Obtain the RVA of the import symbols. edi at first points to the PE header. We use it to go to the 2nd member of the data directory array and obtain the value of VirtualAddress member.

   invoke RVAToOffset,pMapping,edi
   mov edi,eax
   add edi,pMapping

Here comes one of the pitfalls for newcomers to PE programming. Most of the addresses in the PE file are RVAs and RVAs are meaningful only when the PE file is loaded into memory by the PE loader. In our case, we do map the file into memory but not the way the PE loader does. Thus we cannot use those RVAs directly. Somehow we have to convert those RVAs into file offsets. I write RVAToOffset function just for this purpose. I won't analyze it in detail here. Suffice to say that it checks the submitted RVA against the starting-ending RVAs of all sections in the PE file and use the value in PointerToRawData field in the IMAGE_SECTION_HEADER structure to convert the RVA to file offset.
To use this function, you pass it two parameters: the pointer to the memory mapped file and the RVA you want to convert. It returns the file offset in eax. In the above snippet, we must add the pointer to the memory mapped file to the file offset to convert it to virtual address. Seems complicated, huh? :)

   assume edi:ptr IMAGE_IMPORT_DESCRIPTOR
   .while !([edi].OriginalFirstThunk==0 && [edi].TimeDateStamp==0 && [edi].ForwarderChain==0 && [edi].Name1==0 && [edi].FirstThunk==0)

edi now points to the first IMAGE_IMPORT_DESCRIPTOR structure. We will walk the array until we find the structure with zeroes in all members which denotes the end of the array.

     invoke AppendText,hDlg,addr ImportDescriptor
     invoke RVAToOffset,pMapping, [edi].Name1
     mov edx,eax
     add edx,pMapping

We want to display the values of the current IMAGE_IMPORT_DESCRIPTOR structure in the edit control. Name1 is different from the other members since it contains the RVA to the name of the dll. Thus we must convert it to a virtual address first.

     invoke wsprintf, addr temp, addr IDTemplate, [edi].OriginalFirstThunk,[edi].TimeDateStamp,[edi].ForwarderChain,edx,[edi].FirstThunk      invoke AppendText,hDlg,addr temp

Display the values of the current IMAGE_IMPORT_DESCRIPTOR.

     .if [edi].OriginalFirstThunk==0
        mov esi,[edi].FirstThunk
     .else
        mov esi,[edi].OriginalFirstThunk
     .endif

Next we prepare to walk the IMAGE_THUNK_DATA array. Normally we would choose to use the array pointed to by OriginalFirstThunk. However, some linkers errornously put 0 in OriginalFirstThunk thus we must check first if the value of OriginalFirstThunk is zero. If it is, we use the array pointed to by FirstThunk instead.

     invoke RVAToOffset,pMapping,esi
     add eax,pMapping
     mov esi,eax

Again, the value in OriginalFirstThunk/FirstThunk is an RVA. We must convert it to virtual address.

     invoke AppendText,hDlg,addr NameHeader
     .while dword ptr [esi]!=0

Now we are ready to walk the array of IMAGE_THUNK_DATAs to look for the names of the functions imported from this DLL. We will walk the array until we find an entry which contains 0.

       test dword ptr [esi],IMAGE_ORDINAL_FLAG32
       jnz ImportByOrdinal

The first thing we do with the IMAGE_THUNK_DATA is to test it against IMAGE_ORDINAL_FLAG32. This test checks if the most significant bit of the IMAGE_THUNK_DATA is 1. If it is, the function is exported by ordinal so we have no need to process it further. We can extract its ordinal from the low word of the IMAGE_THUNK_DATA and go on with the next IMAGE_THUNK_DATA dword.

       invoke RVAToOffset,pMapping,dword ptr [esi]
       mov edx,eax
       add edx,pMapping
       assume edx:ptr IMAGE_IMPORT_BY_NAME

If the MSB of the IAMGE_THUNK_DATA is 0, it contains the RVA of IMAGE_IMPORT_BY_NAME structure. We need to convert it to virtual address first.

       mov cx, [edx].Hint
       movzx ecx,cx
       invoke wsprintf,addr temp,addr NameTemplate,ecx,addr [edx].Name1
       jmp ShowTheText

Hint is a word-sized field. We must convert it to a dword-sized value before submitting it to wsprintf. And we print both the hint and the function name in the edit control

ImportByOrdinal:
       mov edx,dword ptr [esi]
       and edx,0FFFFh
       invoke wsprintf,addr temp,addr OrdinalTemplate,edx

In the case the function is exported by ordinal only, we zero out the high word and display the ordinal.

ShowTheText:
       invoke AppendText,hDlg,addr temp
       add esi,4

After inserting the function name/ordinal into the edit control, we skip to the next IMAGE_THUNK_DATA.

    .endw
    add edi,sizeof IMAGE_IMPORT_DESCRIPTOR

When all IMAGE_THUNK_DATA dwords in the array are processed, we skip to the next IMAGE_IMPORT_DESCRIPTOR to process the import functions from other DLLs.

Appendix:

It would be incomplete if I don't mention something about bound import. In order to explain what it is, I need to digress a bit. When the PE loader loads a PE file into memory, it examines the import table and loads the required DLLs into the process address space. Then it walks the IMAGE_THUNK_DATA array much like we did and replaces the IMAGE_THUNK_DATAs with the real addresses of the import functions. This step takes time. If somehow the programmer can predict the addresses of the functions correctly, the PE loader doesn't have to fix the IMAGE_THUNK_DATAs each time the PE file is run. Bound import is the product of that idea.
To put it in simple terms, there is a utility named bind.exe that comes with Microsoft compilers such as Visual Studio that examines the import table of a PE file and replaces the IMAGE_THUNK_DATA dwords with the addresses of the import functions.When the file is loaded, the PE loader must check if the addresses are valid. If the DLL versions do not match the ones in the PE files or if the DLLs need to be relocated, the PE loader knows that the precomputed addresses are not valid thus it must walk the array pointed to by OriginalFirstThunk to calculate the new addresses of import functions.
Bound import doesn't have much significance in our example because we use OriginalFirstThunk by default. For more information about the bound import, I recommmend LUEVELSMEYER's pe.txt.


[Iczelion's Win32 Assembly Homepage]

 

第21章 分层架构软件测试 技术人员和客户代表对代码服务相关的技术进行详细的交流,由此确定代码审计的方案(哪些代码要审计、用什么方式审计、审计的时间、审计的要求等)代码审计报告提交和沟通之后,跟开发人员针对代码审查发现的问题进行修改,然后代码审查人员进行回归的检查,然后提交复查的报告;本层不需要了解其它层的实现细节,只需要考虑与本层相关的两层之间的接口和调用的情况。然后对客户要求的功能点进行人工的代码审查,对源代码的扫描结果进行人工的分析和确认;结合自动化扫描的结果和人工审查的结果生成测试对象的代码审查报告,最后提交给客户; 阅读详情

相关推荐

Camera 基础知识

Raw Sensor输出的Data格式为Raw,图像的效果处理使用BB端的ISP,BB端接收Raw data后进行一系列的图像处理(OB,Shading,AWB,Gamma,EE,ANR等),效果方面由BB端控制,需要针对不同的模组进行效果调试,Raw sensor是目前的主流,数据量比YUV Sensor小(RAW10 格式的sensor 1个pixel 10个bit)使用平台ISP处理,能支持较大的size。不过,相位对焦并不是那么完美,它对光线的要求就比较高,在弱光拍摄环境下,相位对焦就无能威力了。

手机-手表蓝牙开发工程师的博客 3062

PE结构讲解2--导入和导出表

本文为转载文章,整理自小甲鱼老师讲的PE结构课程; 一、导入表的结构 在 PE文件头的 IMAGE_OPTIONAL_HEADER32 结构中的 DataDirectory(数据目录表) 的第二个成员就是指向输入表(导入表)的。而输入表是以一个 IMAGE_IMPORT_DESCRIPTOR(简称IID) 的数组开始。每个被 PE文件链接进来的 DLL文...

weixin_34366546的博客 741

2021年软件测试面试题大全

简述测试流程: 1、阅读相关技术文档(如产品PRD、UI设计、产品流程图等)。 2、参加需求评审会议。 3、根据最终确定的需求文档编写测试计划。 4、编写测试用例(等价类划分法、边界值分析法等)。 5、用例评审(主要参与人员:开发、测试、产品、测试leader)。 6、开发提交代码至SVN或者GIT ,配管搭建测试环境。 7、执行测试用例,记录发现的问题。 8、验证bug与回归测试。 9、编写测试报告。 10、产品上线。 补充测试用例设计过程: 根据需求得出测试需求 设计测试方

hard_days的博客 20万+

iczelion pe tut6

 Tutorial 6: Import TableWe will learn about import table in this tutorial. Let me warn you first. This tutorial is a long and difficult one for those who arent familiar with the import table. Yo

jimgreen的专栏 862

嵌入式调光控制库:轻量级软启/渐变/记忆逻辑实现

调光控制是智能照明系统的核心基础功能,涉及亮度调节、人机交互与电气安全多重需求。其底层原理依赖于对相位角或PWM占空比的精确时序控制,并需融合软启动、渐变过渡、状态记忆等工程化逻辑。这类轻量级调光行为逻辑层,不直接操作硬件寄存器,而是以确定性、无动态内存、可配置的方式封装用户意图到目标亮度值(0–100%)的映射过程,显著提升产品鲁棒性与跨平台复用能力。广泛应用于TRIAC交流调光、LED直流PWM驱动及DALI/Matter等智能照明协议网关中,尤其适合资源受限的Cortex-M系列MCU和FreeRTO

weixin_28949937的博客 579

RTPS规范v2.3(中文版)

DDSI-RTPSv2.3,DDS发现互操作性-实时发布订阅通信协议,中文版

pony12的专栏 752

【ABAP系列】SAP ABAP 给初学者-解读function函数的export和import等参数

公众号:SAP Technical 本文作者:matinal 原文出处:http://www.cnblogs.com/SAPmatinal/ 原文链接:【ABAP系列】SAP ABAP 给初学者-解读function函数的export和import等参数 前言部分 大家可以关注我的公众号,公众号里的排版更好,阅读更舒适。 正文部分 1:很多人困惑funct...

ARICK2014的博客 1273

从零配置Archery:手把手教你用Docker部署多数据库审核系统(MySQL/PostgreSQL/ClickHouse)

本文详细介绍了如何从零开始使用Docker部署Archery多数据库审核系统,涵盖MySQL、PostgreSQL和ClickHouse的配置与整合。文章提供了生产级Docker-compose配置、审核规则定制、工单流程设置以及企业微信通知集成等实战指南,帮助团队构建统一的企业级SQL审计平台,提升数据库操作规范与安全。

e4f5g6h7的博客 941

14、QML, SQL and PySide Integration Tutorial

本教程与QtChat教程非常相似,但它侧重于解释如何使用QML将SQL数据库集成到PySide6应用程序中。

u013049912的博客 547

一窥Memory测试算法及自我修复机制

摘要 为了满足新一代设备的需求,Memory的大小每三年就会增加4倍。深亚微米设备包含大量面积更小、访问速度更快的Memory。针对此类设计制定自动测试策略可以减少ATE(自动测试设备)的时间和成本。 内存故障的行为与经典的“Stuck-At”故障不同。因此,Memory的故障模型(由于其阵列结构)与标准逻辑的设计也是不同的。Memory测试除了进行故障检测和定位,还可以实现用冗余单元对...

路科验证 2万+

22、光无线通信调制技术详解

本文详细介绍了光无线通信中的多种调制技术,包括开关键控(OOK)、脉冲位置调制(PPM)、数字脉冲间隔调制(DPIM)、副载波强度调制(SCM)、相移键控(PSK)、正交幅度调制(QAM)以及多载波调制(MCM)如OFDM和MSIM。文章分析了各类调制技术在带宽需求、功率效率、传输容量、传输速率和PAPR等方面的性能差异,并通过Matlab仿真展示了其在AWGN信道下的误码率表现。同时,对比了不同技术的适用场景,提出了调制选择流程,并结合室内光通信与自由空间光通信的应用案例,展望了未来调制技术向高频谱效率、

net55的博客 116

SQLAlchemy 数据库元数据(Database Metadata)实战指南:MetaData、Table、Column 与 ORM Declarative 全解析

本指南以 SQLAlchemy 官方教程中的 "Working with Database Metadata"([doc/build/tutorial/metadata.rst](https://link.gitcode.com/i/51b720270ed1fd29b2bf310a22fa74d5))为核心骨架,系统讲解 SQLAlchemy 数据库元数据的核心概念:如何用 `MetaData`、

gitblog_00106的博客 860

SCADA|KIO程序导出变量错误处理办法

雷工在使用KingSCADA3.52软件导出KIO变量时,遇到导出Excel格式文件报错的问题,错误提示为“ADODB.Connection未找到提供程序”。经过咨询技术人员,发现该功能需要安装Office软件,并与已安装的WPS软件兼容。雷工随后安装了Office2021版本,并进行了兼容性设置。安装过程中遇到无法启动的问题,通过删除安装目录、清理注册表、使用卸载软件和重启电脑等方法解决。安装完成后,雷工在WPS中设置了与Microsoft Office2003兼容的模式,最终成功解决了导出变量时的问题。

做有价值的事,积累有价值的笔记! 957

ECMAScript 6 入门:从标准演进、TC39 提案流程到 Babel 转码实战

> 本文是开源教程《ECMAScript 6 入门》(仓库 `gh_mirrors/es/es6tutorial`)第一章《ECMAScript 6 简介》的深度展开,完整介绍 ES6 的来龙去脉:它和 JavaScript、ES2015 究竟是什么关系,新语法如何经过 TC39 五阶段提案进入标准,以及如何用 Babel 转码器把 ES6 代码安全地运行在老环境里。读完本文,你将能理清 ECMA

gitblog_00706的博客 728

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

Apache Flink Python Table API 入门教程:从零构建并运行 PyFlink 词频统计作业

> 本文以 Apache Flink 官方中文文档《Table API 教程》为骨架,结合仓库内 PyFlink 源码与示例,完整讲解如何从零创建一个 Flink Python 项目:使用 `TableEnvironment` 注册文件系统源表与结果表、编写用户自定义表函数(UDTF)完成分词,再通过 `flat_map`/`group_by`/`select` 计算词频并将结果写入文件。读完本文

gitblog_00068的博客 311

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

使用 SQLModel 创建数据表:从定义 Table Model 到 Engine 与建库实战

本篇指南完整讲解如何用 **SQLModel**(SQL databases in Python,专为简单、兼容与稳健而设计的 ORM 框架)在 Python 中定义一张数据表模型,并通过 SQLAlchemy Engine 连接 SQLite 数据库、一键创建数据库文件和 `hero` 表。读者学完后将掌握:`table=True` 表模型的写法、`int | None` 可空列与主键 `id`

gitblog_00660的博客 419

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

SQLAlchemy 2.1 文档导航与实战入门指南:从安装、教程到 ORM/Core 参考全解析

SQLAlchemy 是 Python 生态中最具代表性的数据库工具包(The Database Toolkit for Python),本文基于当前仓库 [doc/build/index.rst](https://link.gitcode.com/i/8b2d44264344a40c2311ac0a1adec31e) 这一官方文档门户,系统梳理 SQLAlchemy 2.1 的文档体系与学习路径

gitblog_00551的博客 456

FlatBuffers Swift 开发指南:零拷贝序列化从 Schema 到 ByteBuffer 的完整实战

本文以官方 Swift 文档([swift/Sources/FlatBuffers/Documentation.docc/Documentation.md](https://link.gitcode.com/i/1b5437bff6dba60cb6c277fac196e4c5))为主线,系统讲解 FlatBuffers 内存高效序列化库在 Swift 平台上的完整使用链路:从编写 `.fbs` S

gitblog_00513的博客 232

使用 Airflow 构建端到端数据管道:从 CSV 下载到 Postgres 清洗入库的完整实战

本文是 Apache Airflow 入门系列教程的第三篇,将带你从零搭建一条"小而完整"的真实数据管道:从外部数据源下载 CSV 文件、加载到 Postgres 暂存表(staging table)、清洗去重后合并进目标表。读完本文,你将掌握 `SQLExecuteQueryOperator` 与 `PostgresHook` 的组合用法、Airflow UI 中 Connection(连接)的

gitblog_01152的博客 442

magpie:藏在菜单栏的本地模型中转站,7 天 2600 Star 的统一路由方案

往系统菜单栏装一个小图标之后,它悄悄变成了你机器上所有 AI 编程工具的"总入口":Claude Code 跑 Kimi、Codex 接 DeepSeek、Gemini CLI 挂智谱 GLM,点一下就能换,不用翻任何配置文件。这个项目叫 **magpie**,形态是"菜单栏图标 + 本地模型中转站",本身不训练、不跑任何大模型,只做一件事——把"哪个工具用哪个模型"统一管起来。上线 7 天,St

gitblog_00281的博客 217

Pydantic Fields 从入门到原理:Field() 与 FieldInfo 完整教程(Tutorial-Codebase-Knowledge Pydantic Core 系列)

本篇技术指南聚焦 Pydantic 的**字段定制机制**:以 `Field()` 函数为 `BaseModel` 的每个属性附加默认值、别名、约束与描述等元数据,并深入其内部载体 `FieldInfo` 的存储结构与生成流程。本文是当前仓库中 [Pydantic Core 系列教程](https://link.gitcode.com/i/ec4ce32323f8879566319416ccf39

gitblog_00707的博客 191

SatDump 卫星数据处理软件:快速上手 5 分钟跑通第一张气象云图

卫星过顶的窗口只有几分钟,错过就得再等一天。可等卫星真的到头顶,你还在软件里翻菜单、对参数,信号早就从瀑布图上溜走了。手头一份现成的基带录音,同样不知道从哪一步开始解。SatDump 是卫星数据处理软件,覆盖从 SDR 接收、解码到出图的完整链路,一台普通电脑就能跑。 [![SatDump 卫星数据处理实时接收瀑布图界面](https://raw.gitcode.com/GitHub_Trend

gitblog_00887的博客 931

Crawl4AI 结构化数据提取实战:深入解析 ExtractionStrategy 及其在 Tutorial-Codebase-Knowledge 教程中的应用

`ExtractionStrategy` 是 Crawl4AI 中负责从网页内容中提取**结构化数据**(如商品名称、价格、评分等字段)的核心抽象层。本教程以本项目 [Crawl4AI 系列教程](https://link.gitcode.com/i/cfd52e03649831469e6eaf61880e9b89) 第 6 章为骨架,系统讲解 `JsonCssExtractionStrategy

gitblog_00812的博客 161

Dear PyGui 表格 API 完全指南:从基础布局到排序、选择与性能裁剪

本指南围绕 Dear PyGui 的表格(Table)API 展开,它是一套低层(low-level)控件接口,既可用来渲染传统意义上的数据表格,也可以作为通用的界面布局机制。文中将逐步讲解表格的组成结构(列、行、单元格与内容项)、边框背景、列头、列宽策略、排序、选择与裁剪等核心能力,并对照本仓库源码([src/mvTables.cpp](https://link.gitcode.com/i/d9

gitblog_01188的博客 161

FlatBuffers Swift 使用指南:从 flatc 生成代码到 SPM 集成、读写与原地修改

本指南以 FlatBuffers 官方文档 [SwiftUsage.md](https://link.gitcode.com/i/21783e0a7a258ed37b3e388b852097e1) 为主体,系统讲解如何在 Swift 工程中使用 FlatBuffers:包括用 `flatc` 以 `--swift` 选项生成 Swift 代码、通过 Swift Package Manager 集成

gitblog_00069的博客 272

Prisma 数据库工作流指南:NDF 数据导入导出与直接 SQL 数据库访问

本指南系统讲解 Prisma 1.x 中数据库工作流的两大核心场景:**基于 Normalized Data Format(NDF)中间格式的数据导入/导出**,以及**通过 SQL 直接访问本地 Prisma 集群背后的 MySQL 数据库**。你将掌握从零初始化服务、灌入种子数据、导出 NDF、跨 stage 克隆服务、导入数据,到使用 CLI 与 raw API 完成数据搬运的完整链路,并了

gitblog_00844的博客 237
上一篇: Tutorial 5: Section Table
下一篇: Tutorial 7: Export Table
maplewasp
博客等级 码龄23年 22粉丝 17原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值