Pepsi_1
Pepsi_1

Reputation: 121

PE file format pointers using bitwise operators

I wanted to know the math behind these lines of code. Dealing with pointers. Can someone walk me through the math with the + operators and & bitwise operator in the if statement? I just don't understand it that well.

 // check signatures -- must be a PE
    pDosHeader = (PIMAGE_DOS_HEADER)hMap;
    if(pDosHeader->e_magic != IMAGE_DOS_SIGNATURE) goto cleanup;

    pNtHeaders = (PIMAGE_NT_HEADERS)((DWORD)hMap + pDosHeader->e_lfanew);
    if(pNtHeaders->Signature != IMAGE_NT_SIGNATURE) goto cleanup;

// Not dll
 if (pNtHeaders->FileHeader.Characteristics & IMAGE_FILE_DLL
  && pNtHeaders->FileHeader.Characteristics & IMAGE_FILE_EXECUTABLE_IMAGE) goto cleanup;

    // get last section's header...
    pSectionHeader = (PIMAGE_SECTION_HEADER)((DWORD)hMap + pDosHeader->e_lfanew + sizeof(IMAGE_NT_HEADERS));
    pSection = pSectionHeader;
 pSection += (pNtHeaders->FileHeader.NumberOfSections - 1);

Upvotes: 0

Views: 318

Answers (1)

cdarke
cdarke

Reputation: 44414

The + operator is just an arithmetic plus. When used with pointers it now becomes clearer why pointers in C and C++ are typed - it does not just add bytes to the address, but adds the size of whatever the type it is pointing at.

So, for example, if we had:

struct stuff x;
struct stuff *p = &x;    /* p now points at x */
p = p + 1;
/* the address at p has been incremented by the sizeof(struct stuff), 
    and is pointing at the next struct stuff in memeory */

The & used as a binary operator is bitwise AND, which carries bits that are set in both operands. For example:

unsigned int b = 99;      /* 99 is binary 01100011 */
unsigned int w = b & 6;   /*  6 is binary 00000110 */
/* w is now 2                 2 is binary 00000010 */

It looks like in your example code it is used to test if the bitmasks IMAGE_FILE_DLL and IMAGE_FILE_EXECUTABLE_IMAGE are set in the structure members.

Upvotes: 1

Related Questions