Search code examples
c++windowsportable-executable

Reading number of sections of an executable fails


Somehow the following code outputs "Number of sections: 57344" which is clearly incorrect. Can anyone give me a hint what I am doing wrong?

#include <windows.h>
#include <iostream>
#include <vector>
#include <sstream>
#include <fstream>
#include <iterator>
#include <algorithm>

int main() {
std::string file_path = "C:\\foo.exe";
if(!file_path.size()) {
    cout << "No file was selected" << endl;
    return 1;
}
std::ifstream input( file_path.c_str(), std::ios::binary );
std::vector<unsigned char> buffer((
    std::istream_iterator<unsigned char>(input)), 
    (std::istream_iterator<unsigned char>()));

if(!buffer.size()) {
    cout << "Error reading file" << endl;
    return 1;
}
char * BinFile = (char*)&buffer[0];
IMAGE_DOS_HEADER* DOSHeader = (IMAGE_DOS_HEADER*)BinFile;
IMAGE_NT_HEADERS* NTHeader = (IMAGE_NT_HEADERS*)(BinFile + DOSHeader->e_lfanew);
cout << "Number of sections: " << NTHeader->FileHeader.NumberOfSections << endl;

return 0;
}

Solution

  • istream_iterator uses operator<< which as is unsuitable for binary data

    Use istream::read instead.

    You can get file size, by seeking to the end, then calling tellg. Resize vector accordingly and read directly to it.