I am working my way through Iczelion's tutorial Series, and in Tutorial #6, the Import table, I ran into something I do not understand.
To get to the Import table he uses this code
assume edi:ptr IMAGE_NT_HEADERS
mov edi,[edi].OptionalHeader.DataDirectory[sizeof IMAGE_DATA_DIRECTORY].VirtualAddress
IMAGE_DATA_DIRECTORY STRUCT for the import table is the second in the array, with subscript [1].
sizeof IMAGE_DATA_DIRECTORY is 8 bytes (2 DWORDs), so we are referring to the 9th structure in the array instead of the 2nd.
The code works perfectly though.
Just for practice, I rewrote Iczelion's program in C.
But to get the same results (list of dll's and imported function) in the my program I needed to use:
VirtAddr = pHeaders->OptionalHeader.DataDirectory[(sizeof(IMAGE_DATA_DIRECTORY)-7)].VirtualAddress;
Could somebody help me understand what is going on here?
For MASM the square brackets do not work as they do for C.
For C they serve as an array subscript operator, so to get the VirtualAddress member of the second element of the DataDirectory array, you would use:
VirtAddr = pHeaders->OptionalHeader.DataDirectory[1].VirtualAddress
For MASM, if the brackets do not enclose an indirect memory operand, [edi] for example, they cause the value of the expression in the brackets to be added to the preceding value. So for this operand:
[edi].OptionalHeader.DataDirectory[sizeof IMAGE_DATA_DIRECTORY].VirtualAddress
The size of the IMAGE_DATA_DIRECTORY structure is added to the offset of the DataDirectory array.
To illustrate, for this code:
assume edi:ptr IMAGE_NT_HEADERS
mov edi,[edi].OptionalHeader.DataDirectory[sizeof IMAGE_DATA_DIRECTORY].VirtualAddress
mov edi,[edi].OptionalHeader.DataDirectory[8].VirtualAddress
mov edi,[edi].OptionalHeader.DataDirectory[16].VirtualAddress
I get this listing:
assume edi:ptr IMAGE_NT_HEADERS
00000003 8B BF 00000080 mov edi,[edi].OptionalHeader.DataDirectory[sizeof IMAGE_DATA_DIRECTORY].VirtualAddress
00000009 8B BF 00000080 mov edi,[edi].OptionalHeader.DataDirectory[8].VirtualAddress
0000000F 8B BF 00000088 mov edi,[edi].OptionalHeader.DataDirectory[16].VirtualAddress
Note that OFFSET IMAGE_NT_HEADERS.OptionalHeader.DataDirectory = 78h
Great answer! Thanks a lot!