pe_info.hpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. // Copyright 2014 Renato Tegon Forti, Antony Polukhin.
  2. // Copyright 2015-2019 Antony Polukhin.
  3. //
  4. // Distributed under the Boost Software License, Version 1.0.
  5. // (See accompanying file LICENSE_1_0.txt
  6. // or copy at http://www.boost.org/LICENSE_1_0.txt)
  7. #ifndef BOOST_DLL_DETAIL_WINDOWS_PE_INFO_HPP
  8. #define BOOST_DLL_DETAIL_WINDOWS_PE_INFO_HPP
  9. #include <boost/dll/config.hpp>
  10. #ifdef BOOST_HAS_PRAGMA_ONCE
  11. # pragma once
  12. #endif
  13. #include <cstring>
  14. #include <fstream>
  15. #include <boost/assert.hpp>
  16. #include <boost/cstdint.hpp>
  17. #include <boost/dll/detail/x_info_interface.hpp>
  18. namespace boost { namespace dll { namespace detail {
  19. // reference:
  20. // http://www.joachim-bauch.de/tutorials/loading-a-dll-from-memory/
  21. // http://msdn.microsoft.com/en-us/magazine/ms809762.aspx
  22. // http://msdn.microsoft.com/en-us/magazine/cc301808.aspx
  23. //
  24. // Basic Windows typedefs. We can not use <boost/winapi/basic_types.hpp> header
  25. // because that header must be included only on Windows platform
  26. typedef unsigned char BYTE_;
  27. typedef unsigned short WORD_;
  28. typedef boost::uint32_t DWORD_;
  29. typedef boost::int32_t LONG_;
  30. typedef boost::uint32_t ULONG_;
  31. typedef boost::int64_t LONGLONG_;
  32. typedef boost::uint64_t ULONGLONG_;
  33. struct IMAGE_DOS_HEADER_ { // 32/64 independent header
  34. boost::dll::detail::WORD_ e_magic; // Magic number
  35. boost::dll::detail::WORD_ e_cblp; // Bytes on last page of file
  36. boost::dll::detail::WORD_ e_cp; // Pages in file
  37. boost::dll::detail::WORD_ e_crlc; // Relocations
  38. boost::dll::detail::WORD_ e_cparhdr; // Size of header in paragraphs
  39. boost::dll::detail::WORD_ e_minalloc; // Minimum extra paragraphs needed
  40. boost::dll::detail::WORD_ e_maxalloc; // Maximum extra paragraphs needed
  41. boost::dll::detail::WORD_ e_ss; // Initial (relative) SS value
  42. boost::dll::detail::WORD_ e_sp; // Initial SP value
  43. boost::dll::detail::WORD_ e_csum; // Checksum
  44. boost::dll::detail::WORD_ e_ip; // Initial IP value
  45. boost::dll::detail::WORD_ e_cs; // Initial (relative) CS value
  46. boost::dll::detail::WORD_ e_lfarlc; // File address of relocation table
  47. boost::dll::detail::WORD_ e_ovno; // Overlay number
  48. boost::dll::detail::WORD_ e_res[4]; // Reserved words
  49. boost::dll::detail::WORD_ e_oemid; // OEM identifier (for e_oeminfo)
  50. boost::dll::detail::WORD_ e_oeminfo; // OEM information; e_oemid specific
  51. boost::dll::detail::WORD_ e_res2[10]; // Reserved words
  52. boost::dll::detail::LONG_ e_lfanew; // File address of new exe header
  53. };
  54. struct IMAGE_FILE_HEADER_ { // 32/64 independent header
  55. boost::dll::detail::WORD_ Machine;
  56. boost::dll::detail::WORD_ NumberOfSections;
  57. boost::dll::detail::DWORD_ TimeDateStamp;
  58. boost::dll::detail::DWORD_ PointerToSymbolTable;
  59. boost::dll::detail::DWORD_ NumberOfSymbols;
  60. boost::dll::detail::WORD_ SizeOfOptionalHeader;
  61. boost::dll::detail::WORD_ Characteristics;
  62. };
  63. struct IMAGE_DATA_DIRECTORY_ { // 32/64 independent header
  64. boost::dll::detail::DWORD_ VirtualAddress;
  65. boost::dll::detail::DWORD_ Size;
  66. };
  67. struct IMAGE_EXPORT_DIRECTORY_ { // 32/64 independent header
  68. boost::dll::detail::DWORD_ Characteristics;
  69. boost::dll::detail::DWORD_ TimeDateStamp;
  70. boost::dll::detail::WORD_ MajorVersion;
  71. boost::dll::detail::WORD_ MinorVersion;
  72. boost::dll::detail::DWORD_ Name;
  73. boost::dll::detail::DWORD_ Base;
  74. boost::dll::detail::DWORD_ NumberOfFunctions;
  75. boost::dll::detail::DWORD_ NumberOfNames;
  76. boost::dll::detail::DWORD_ AddressOfFunctions;
  77. boost::dll::detail::DWORD_ AddressOfNames;
  78. boost::dll::detail::DWORD_ AddressOfNameOrdinals;
  79. };
  80. struct IMAGE_SECTION_HEADER_ { // 32/64 independent header
  81. static const std::size_t IMAGE_SIZEOF_SHORT_NAME_ = 8;
  82. boost::dll::detail::BYTE_ Name[IMAGE_SIZEOF_SHORT_NAME_];
  83. union {
  84. boost::dll::detail::DWORD_ PhysicalAddress;
  85. boost::dll::detail::DWORD_ VirtualSize;
  86. } Misc;
  87. boost::dll::detail::DWORD_ VirtualAddress;
  88. boost::dll::detail::DWORD_ SizeOfRawData;
  89. boost::dll::detail::DWORD_ PointerToRawData;
  90. boost::dll::detail::DWORD_ PointerToRelocations;
  91. boost::dll::detail::DWORD_ PointerToLinenumbers;
  92. boost::dll::detail::WORD_ NumberOfRelocations;
  93. boost::dll::detail::WORD_ NumberOfLinenumbers;
  94. boost::dll::detail::DWORD_ Characteristics;
  95. };
  96. template <class AddressOffsetT>
  97. struct IMAGE_OPTIONAL_HEADER_template {
  98. static const std::size_t IMAGE_NUMBEROF_DIRECTORY_ENTRIES_ = 16;
  99. boost::dll::detail::WORD_ Magic;
  100. boost::dll::detail::BYTE_ MajorLinkerVersion;
  101. boost::dll::detail::BYTE_ MinorLinkerVersion;
  102. boost::dll::detail::DWORD_ SizeOfCode;
  103. boost::dll::detail::DWORD_ SizeOfInitializedData;
  104. boost::dll::detail::DWORD_ SizeOfUninitializedData;
  105. boost::dll::detail::DWORD_ AddressOfEntryPoint;
  106. union {
  107. boost::dll::detail::DWORD_ BaseOfCode;
  108. unsigned char padding_[sizeof(AddressOffsetT) == 8 ? 4 : 8]; // in x64 version BaseOfData does not exist
  109. } BaseOfCode_and_BaseOfData;
  110. AddressOffsetT ImageBase;
  111. boost::dll::detail::DWORD_ SectionAlignment;
  112. boost::dll::detail::DWORD_ FileAlignment;
  113. boost::dll::detail::WORD_ MajorOperatingSystemVersion;
  114. boost::dll::detail::WORD_ MinorOperatingSystemVersion;
  115. boost::dll::detail::WORD_ MajorImageVersion;
  116. boost::dll::detail::WORD_ MinorImageVersion;
  117. boost::dll::detail::WORD_ MajorSubsystemVersion;
  118. boost::dll::detail::WORD_ MinorSubsystemVersion;
  119. boost::dll::detail::DWORD_ Win32VersionValue;
  120. boost::dll::detail::DWORD_ SizeOfImage;
  121. boost::dll::detail::DWORD_ SizeOfHeaders;
  122. boost::dll::detail::DWORD_ CheckSum;
  123. boost::dll::detail::WORD_ Subsystem;
  124. boost::dll::detail::WORD_ DllCharacteristics;
  125. AddressOffsetT SizeOfStackReserve;
  126. AddressOffsetT SizeOfStackCommit;
  127. AddressOffsetT SizeOfHeapReserve;
  128. AddressOffsetT SizeOfHeapCommit;
  129. boost::dll::detail::DWORD_ LoaderFlags;
  130. boost::dll::detail::DWORD_ NumberOfRvaAndSizes;
  131. IMAGE_DATA_DIRECTORY_ DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES_];
  132. };
  133. typedef IMAGE_OPTIONAL_HEADER_template<boost::dll::detail::DWORD_> IMAGE_OPTIONAL_HEADER32_;
  134. typedef IMAGE_OPTIONAL_HEADER_template<boost::dll::detail::ULONGLONG_> IMAGE_OPTIONAL_HEADER64_;
  135. template <class AddressOffsetT>
  136. struct IMAGE_NT_HEADERS_template {
  137. boost::dll::detail::DWORD_ Signature;
  138. IMAGE_FILE_HEADER_ FileHeader;
  139. IMAGE_OPTIONAL_HEADER_template<AddressOffsetT> OptionalHeader;
  140. };
  141. typedef IMAGE_NT_HEADERS_template<boost::dll::detail::DWORD_> IMAGE_NT_HEADERS32_;
  142. typedef IMAGE_NT_HEADERS_template<boost::dll::detail::ULONGLONG_> IMAGE_NT_HEADERS64_;
  143. template <class AddressOffsetT>
  144. class pe_info: public x_info_interface {
  145. std::ifstream& f_;
  146. typedef IMAGE_NT_HEADERS_template<AddressOffsetT> header_t;
  147. typedef IMAGE_EXPORT_DIRECTORY_ exports_t;
  148. typedef IMAGE_SECTION_HEADER_ section_t;
  149. typedef IMAGE_DOS_HEADER_ dos_t;
  150. template <class T>
  151. inline void read_raw(T& value, std::size_t size = sizeof(T)) const {
  152. f_.read(reinterpret_cast<char*>(&value), size);
  153. }
  154. public:
  155. static bool parsing_supported(std::ifstream& f) {
  156. dos_t dos;
  157. f.seekg(0);
  158. f.read(reinterpret_cast<char*>(&dos), sizeof(dos));
  159. // 'MZ' and 'ZM' according to Wikipedia
  160. if (dos.e_magic != 0x4D5A && dos.e_magic != 0x5A4D) {
  161. return false;
  162. }
  163. header_t h;
  164. f.seekg(dos.e_lfanew);
  165. f.read(reinterpret_cast<char*>(&h), sizeof(h));
  166. return h.Signature == 0x00004550 // 'PE00'
  167. && h.OptionalHeader.Magic == (sizeof(boost::uint32_t) == sizeof(AddressOffsetT) ? 0x10B : 0x20B);
  168. }
  169. explicit pe_info(std::ifstream& f) BOOST_NOEXCEPT
  170. : f_(f)
  171. {}
  172. private:
  173. inline header_t header() {
  174. header_t h;
  175. dos_t dos;
  176. f_.seekg(0);
  177. read_raw(dos);
  178. f_.seekg(dos.e_lfanew);
  179. read_raw(h);
  180. return h;
  181. }
  182. inline exports_t exports(const header_t& h) {
  183. exports_t exports;
  184. static const unsigned int IMAGE_DIRECTORY_ENTRY_EXPORT_ = 0;
  185. const std::size_t exp_virtual_address = h.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT_].VirtualAddress;
  186. const std::size_t real_offset = get_file_offset(exp_virtual_address, h);
  187. BOOST_ASSERT(real_offset);
  188. f_.seekg(real_offset);
  189. read_raw(exports);
  190. return exports;
  191. }
  192. std::size_t get_file_offset(std::size_t virtual_address, const header_t& h) {
  193. section_t image_section_header;
  194. { // f_.seekg to the beginning on section headers
  195. dos_t dos;
  196. f_.seekg(0);
  197. read_raw(dos);
  198. f_.seekg(dos.e_lfanew + sizeof(header_t));
  199. }
  200. for (std::size_t i = 0;i < h.FileHeader.NumberOfSections;++i) {
  201. read_raw(image_section_header);
  202. if (virtual_address >= image_section_header.VirtualAddress
  203. && virtual_address < image_section_header.VirtualAddress + image_section_header.SizeOfRawData)
  204. {
  205. return image_section_header.PointerToRawData + virtual_address - image_section_header.VirtualAddress;
  206. }
  207. }
  208. return 0;
  209. }
  210. public:
  211. std::vector<std::string> sections() {
  212. std::vector<std::string> ret;
  213. const header_t h = header();
  214. ret.reserve(h.FileHeader.NumberOfSections);
  215. // get names, e.g: .text .rdata .data .rsrc .reloc
  216. section_t image_section_header;
  217. char name_helper[section_t::IMAGE_SIZEOF_SHORT_NAME_ + 1];
  218. std::memset(name_helper, 0, sizeof(name_helper));
  219. for (std::size_t i = 0;i < h.FileHeader.NumberOfSections;++i) {
  220. // There is no terminating null character if the string is exactly eight characters long
  221. read_raw(image_section_header);
  222. std::memcpy(name_helper, image_section_header.Name, section_t::IMAGE_SIZEOF_SHORT_NAME_);
  223. if (name_helper[0] != '/') {
  224. ret.push_back(name_helper);
  225. } else {
  226. // For longer names, image_section_header.Name contains a slash (/) followed by ASCII representation of a decimal number.
  227. // this number is an offset into the string table.
  228. // TODO: fixme
  229. ret.push_back(name_helper);
  230. }
  231. }
  232. return ret;
  233. }
  234. std::vector<std::string> symbols() {
  235. std::vector<std::string> ret;
  236. const header_t h = header();
  237. const exports_t exprt = exports(h);
  238. const std::size_t exported_symbols = exprt.NumberOfNames;
  239. const std::size_t fixed_names_addr = get_file_offset(exprt.AddressOfNames, h);
  240. ret.reserve(exported_symbols);
  241. boost::dll::detail::DWORD_ name_offset;
  242. std::string symbol_name;
  243. for (std::size_t i = 0;i < exported_symbols;++i) {
  244. f_.seekg(fixed_names_addr + i * sizeof(name_offset));
  245. read_raw(name_offset);
  246. f_.seekg(get_file_offset(name_offset, h));
  247. getline(f_, symbol_name, '\0');
  248. ret.push_back(symbol_name);
  249. }
  250. return ret;
  251. }
  252. std::vector<std::string> symbols(const char* section_name) {
  253. std::vector<std::string> ret;
  254. const header_t h = header();
  255. std::size_t section_begin_addr = 0;
  256. std::size_t section_end_addr = 0;
  257. { // getting address range for the section
  258. section_t image_section_header;
  259. char name_helper[section_t::IMAGE_SIZEOF_SHORT_NAME_ + 1];
  260. std::memset(name_helper, 0, sizeof(name_helper));
  261. for (std::size_t i = 0;i < h.FileHeader.NumberOfSections;++i) {
  262. // There is no terminating null character if the string is exactly eight characters long
  263. read_raw(image_section_header);
  264. std::memcpy(name_helper, image_section_header.Name, section_t::IMAGE_SIZEOF_SHORT_NAME_);
  265. if (!std::strcmp(section_name, name_helper)) {
  266. section_begin_addr = image_section_header.PointerToRawData;
  267. section_end_addr = section_begin_addr + image_section_header.SizeOfRawData;
  268. }
  269. }
  270. // returning empty result if section was not found
  271. if(section_begin_addr == 0 || section_end_addr == 0)
  272. return ret;
  273. }
  274. const exports_t exprt = exports(h);
  275. const std::size_t exported_symbols = exprt.NumberOfFunctions;
  276. const std::size_t fixed_names_addr = get_file_offset(exprt.AddressOfNames, h);
  277. const std::size_t fixed_ordinals_addr = get_file_offset(exprt.AddressOfNameOrdinals, h);
  278. const std::size_t fixed_functions_addr = get_file_offset(exprt.AddressOfFunctions, h);
  279. ret.reserve(exported_symbols);
  280. boost::dll::detail::DWORD_ ptr;
  281. boost::dll::detail::WORD_ ordinal;
  282. std::string symbol_name;
  283. for (std::size_t i = 0;i < exported_symbols;++i) {
  284. // getting ordinal
  285. f_.seekg(fixed_ordinals_addr + i * sizeof(ordinal));
  286. read_raw(ordinal);
  287. // getting function addr
  288. f_.seekg(fixed_functions_addr + ordinal * sizeof(ptr));
  289. read_raw(ptr);
  290. ptr = static_cast<boost::dll::detail::DWORD_>( get_file_offset(ptr, h) );
  291. if (ptr >= section_end_addr || ptr < section_begin_addr) {
  292. continue;
  293. }
  294. f_.seekg(fixed_names_addr + i * sizeof(ptr));
  295. read_raw(ptr);
  296. f_.seekg(get_file_offset(ptr, h));
  297. getline(f_, symbol_name, '\0');
  298. ret.push_back(symbol_name);
  299. }
  300. return ret;
  301. }
  302. // a test method to get dependents modules,
  303. // who my plugin imports (1st level only)
  304. /*
  305. e.g. for myself I get:
  306. KERNEL32.dll
  307. MSVCP110D.dll
  308. boost_system-vc-mt-gd-1_56.dll
  309. MSVCR110D.dll
  310. */
  311. /*
  312. std::vector<std::string> depend_of(boost::dll::fs::error_code &ec) BOOST_NOEXCEPT {
  313. std::vector<std::string> ret;
  314. IMAGE_DOS_HEADER* image_dos_header = (IMAGE_DOS_HEADER*)native();
  315. if(!image_dos_header) {
  316. // ERROR_BAD_EXE_FORMAT
  317. ec = boost::dll::fs::make_error_code(
  318. boost::dll::fs::errc::executable_format_error
  319. );
  320. return ret;
  321. }
  322. IMAGE_OPTIONAL_HEADER* image_optional_header = (IMAGE_OPTIONAL_HEADER*)((boost::dll::detail::BYTE_*)native() + image_dos_header->e_lfanew + 24);
  323. if(!image_optional_header) {
  324. // ERROR_BAD_EXE_FORMAT
  325. ec = boost::dll::fs::make_error_code(
  326. boost::dll::fs::errc::executable_format_error
  327. );
  328. return ret;
  329. }
  330. IMAGE_IMPORT_DESCRIPTOR* image_import_descriptor = (IMAGE_IMPORT_DESCRIPTOR*)((boost::dll::detail::BYTE_*)native() + image_optional_header->DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress);
  331. if(!image_import_descriptor) {
  332. // ERROR_BAD_EXE_FORMAT
  333. ec = boost::dll::fs::make_error_code(
  334. boost::dll::fs::errc::executable_format_error
  335. );
  336. return ret;
  337. }
  338. while(image_import_descriptor->FirstThunk) {
  339. std::string module_name = reinterpret_cast<char*>((boost::dll::detail::BYTE_*)native() + image_import_descriptor->Name);
  340. if(module_name.size()) {
  341. ret.push_back(module_name);
  342. }
  343. image_import_descriptor++;
  344. }
  345. return ret;
  346. }
  347. */
  348. };
  349. typedef pe_info<boost::dll::detail::DWORD_> pe_info32;
  350. typedef pe_info<boost::dll::detail::ULONGLONG_> pe_info64;
  351. }}} // namespace boost::dll::detail
  352. #endif // BOOST_DLL_DETAIL_WINDOWS_PE_INFO_HPP