bindexplib.cxx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. /*-------------------------------------------------------------------------
  4. Portions of this source have been derived from the 'bindexplib' tool
  5. provided by the CERN ROOT Data Analysis Framework project (root.cern.ch).
  6. Permission has been granted by Pere Mato <[email protected]> to distribute
  7. this derived work under the CMake license.
  8. -------------------------------------------------------------------------*/
  9. /*
  10. *----------------------------------------------------------------------
  11. * Program: dumpexts.exe
  12. * Author: Gordon Chaffee
  13. *
  14. * History: The real functionality of this file was written by
  15. * Matt Pietrek in 1993 in his pedump utility. I've
  16. * modified it to dump the externals in a bunch of object
  17. * files to create a .def file.
  18. *
  19. * Notes: Visual C++ puts an underscore before each exported symbol.
  20. * This file removes them. I don't know if this is a problem
  21. * this other compilers. If _MSC_VER is defined,
  22. * the underscore is removed. If not, it isn't. To get a
  23. * full dump of an object file, use the -f option. This can
  24. * help determine the something that may be different with a
  25. * compiler other than Visual C++.
  26. * ======================================
  27. * Corrections (Axel 2006-04-04):
  28. * Conversion to C++. Mostly.
  29. *
  30. * Extension (Axel 2006-03-15)
  31. * As soon as an object file contains an /EXPORT directive (which
  32. * is generated by the compiler when a symbol is declared as
  33. * __declspec(dllexport) no to-be-exported symbols are printed,
  34. * as the linker will see these directives, and if those directives
  35. * are present we only export selectively (i.e. we trust the
  36. * programmer).
  37. *
  38. * ======================================
  39. * ======================================
  40. * Corrections (Valery Fine 23/02/98):
  41. *
  42. * The "(vector) deleting destructor" MUST not be exported
  43. * To recognize it the following test are introduced:
  44. * "@@UAEPAXI@Z" scalar deleting dtor
  45. * "@@QAEPAXI@Z" vector deleting dtor
  46. * "AEPAXI@Z" vector deleting dtor with thunk adjustor
  47. * ======================================
  48. * Corrections (Valery Fine 12/02/97):
  49. *
  50. * It created a wrong EXPORTS for the global pointers and constants.
  51. * The Section Header has been involved to discover the missing information
  52. * Now the pointers are correctly supplied with "DATA" descriptor
  53. * the constants with no extra descriptor.
  54. *
  55. * Corrections (Valery Fine 16/09/96):
  56. *
  57. * It didn't work for C++ code with global variables and class definitions
  58. * The DumpExternalObject function has been introduced to generate .DEF
  59. *file
  60. *
  61. * Author: Valery Fine 16/09/96 (E-mail: [email protected])
  62. *----------------------------------------------------------------------
  63. */
  64. #include "bindexplib.h"
  65. #include <cstddef> // IWYU pragma: keep
  66. #include <sstream>
  67. #include <vector>
  68. #ifdef _WIN32
  69. # include <windows.h>
  70. # include "cmsys/Encoding.hxx"
  71. #endif
  72. #include "cmsys/FStream.hxx"
  73. #include "cmSystemTools.h"
  74. #ifdef _WIN32
  75. # ifndef IMAGE_FILE_MACHINE_ARM
  76. # define IMAGE_FILE_MACHINE_ARM 0x01c0 // ARM Little-Endian
  77. # endif
  78. # ifndef IMAGE_FILE_MACHINE_THUMB
  79. # define IMAGE_FILE_MACHINE_THUMB 0x01c2 // ARM Thumb/Thumb-2 Little-Endian
  80. # endif
  81. # ifndef IMAGE_FILE_MACHINE_ARMNT
  82. # define IMAGE_FILE_MACHINE_ARMNT 0x01c4 // ARM Thumb-2 Little-Endian
  83. # endif
  84. # ifndef IMAGE_FILE_MACHINE_ARM64
  85. # define IMAGE_FILE_MACHINE_ARM64 0xaa64 // ARM64 Little-Endian
  86. # endif
  87. typedef struct cmANON_OBJECT_HEADER_BIGOBJ
  88. {
  89. /* same as ANON_OBJECT_HEADER_V2 */
  90. WORD Sig1; // Must be IMAGE_FILE_MACHINE_UNKNOWN
  91. WORD Sig2; // Must be 0xffff
  92. WORD Version; // >= 2 (implies the Flags field is present)
  93. WORD Machine; // Actual machine - IMAGE_FILE_MACHINE_xxx
  94. DWORD TimeDateStamp;
  95. CLSID ClassID; // {D1BAA1C7-BAEE-4ba9-AF20-FAF66AA4DCB8}
  96. DWORD SizeOfData; // Size of data that follows the header
  97. DWORD Flags; // 0x1 -> contains metadata
  98. DWORD MetaDataSize; // Size of CLR metadata
  99. DWORD MetaDataOffset; // Offset of CLR metadata
  100. /* bigobj specifics */
  101. DWORD NumberOfSections; // extended from WORD
  102. DWORD PointerToSymbolTable;
  103. DWORD NumberOfSymbols;
  104. } cmANON_OBJECT_HEADER_BIGOBJ;
  105. typedef struct _cmIMAGE_SYMBOL_EX
  106. {
  107. union
  108. {
  109. BYTE ShortName[8];
  110. struct
  111. {
  112. DWORD Short; // if 0, use LongName
  113. DWORD Long; // offset into string table
  114. } Name;
  115. DWORD LongName[2]; // PBYTE [2]
  116. } N;
  117. DWORD Value;
  118. LONG SectionNumber;
  119. WORD Type;
  120. BYTE StorageClass;
  121. BYTE NumberOfAuxSymbols;
  122. } cmIMAGE_SYMBOL_EX;
  123. typedef cmIMAGE_SYMBOL_EX UNALIGNED* cmPIMAGE_SYMBOL_EX;
  124. PIMAGE_SECTION_HEADER GetSectionHeaderOffset(
  125. PIMAGE_FILE_HEADER pImageFileHeader)
  126. {
  127. return (PIMAGE_SECTION_HEADER)((DWORD_PTR)pImageFileHeader +
  128. IMAGE_SIZEOF_FILE_HEADER +
  129. pImageFileHeader->SizeOfOptionalHeader);
  130. }
  131. PIMAGE_SECTION_HEADER GetSectionHeaderOffset(
  132. cmANON_OBJECT_HEADER_BIGOBJ* pImageFileHeader)
  133. {
  134. return (PIMAGE_SECTION_HEADER)((DWORD_PTR)pImageFileHeader +
  135. sizeof(cmANON_OBJECT_HEADER_BIGOBJ));
  136. }
  137. /*
  138. + * Utility func, strstr with size
  139. + */
  140. const char* StrNStr(const char* start, const char* find, size_t& size)
  141. {
  142. size_t len;
  143. const char* hint;
  144. if (!start || !find || !size) {
  145. size = 0;
  146. return 0;
  147. }
  148. len = strlen(find);
  149. while ((hint = (const char*)memchr(start, find[0], size - len + 1))) {
  150. size -= (hint - start);
  151. if (!strncmp(hint, find, len))
  152. return hint;
  153. start = hint + 1;
  154. }
  155. size = 0;
  156. return 0;
  157. }
  158. template <
  159. // cmANON_OBJECT_HEADER_BIGOBJ or IMAGE_FILE_HEADER
  160. class ObjectHeaderType,
  161. // cmPIMAGE_SYMBOL_EX or PIMAGE_SYMBOL
  162. class SymbolTableType>
  163. class DumpSymbols
  164. {
  165. public:
  166. /*
  167. *----------------------------------------------------------------------
  168. * Constructor --
  169. *
  170. * Initialize variables from pointer to object header.
  171. *
  172. *----------------------------------------------------------------------
  173. */
  174. DumpSymbols(ObjectHeaderType* ih, std::set<std::string>& symbols,
  175. std::set<std::string>& dataSymbols, bool isI386)
  176. : Symbols(symbols)
  177. , DataSymbols(dataSymbols)
  178. {
  179. this->ObjectImageHeader = ih;
  180. this->SymbolTable =
  181. (SymbolTableType*)((DWORD_PTR)this->ObjectImageHeader +
  182. this->ObjectImageHeader->PointerToSymbolTable);
  183. this->SectionHeaders = GetSectionHeaderOffset(this->ObjectImageHeader);
  184. this->SymbolCount = this->ObjectImageHeader->NumberOfSymbols;
  185. this->IsI386 = isI386;
  186. }
  187. /*
  188. *----------------------------------------------------------------------
  189. * DumpObjFile --
  190. *
  191. * Dump an object file's exported symbols.
  192. *----------------------------------------------------------------------
  193. */
  194. void DumpObjFile() { this->DumpExternalsObjects(); }
  195. /*
  196. *----------------------------------------------------------------------
  197. * DumpExternalsObjects --
  198. *
  199. * Dumps a COFF symbol table from an OBJ.
  200. *----------------------------------------------------------------------
  201. */
  202. void DumpExternalsObjects()
  203. {
  204. unsigned i;
  205. PSTR stringTable;
  206. std::string symbol;
  207. DWORD SectChar;
  208. /*
  209. * The string table apparently starts right after the symbol table
  210. */
  211. stringTable = (PSTR) & this->SymbolTable[this->SymbolCount];
  212. SymbolTableType* pSymbolTable = this->SymbolTable;
  213. for (i = 0; i < this->SymbolCount; i++) {
  214. if (pSymbolTable->SectionNumber > 0 &&
  215. (pSymbolTable->Type == 0x20 || pSymbolTable->Type == 0x0)) {
  216. if (pSymbolTable->StorageClass == IMAGE_SYM_CLASS_EXTERNAL) {
  217. /*
  218. * The name of the Function entry points
  219. */
  220. if (pSymbolTable->N.Name.Short != 0) {
  221. symbol.clear();
  222. symbol.insert(0, (const char*)pSymbolTable->N.ShortName, 8);
  223. } else {
  224. symbol = stringTable + pSymbolTable->N.Name.Long;
  225. }
  226. // clear out any leading spaces
  227. while (isspace(symbol[0]))
  228. symbol.erase(0, 1);
  229. // if it starts with _ and has an @ then it is a __cdecl
  230. // so remove the @ stuff for the export
  231. if (symbol[0] == '_') {
  232. std::string::size_type posAt = symbol.find('@');
  233. if (posAt != std::string::npos) {
  234. symbol.erase(posAt);
  235. }
  236. }
  237. // For i386 builds we need to remove _
  238. if (this->IsI386 && symbol[0] == '_') {
  239. symbol.erase(0, 1);
  240. }
  241. // Check whether it is "Scalar deleting destructor" and "Vector
  242. // deleting destructor"
  243. // if scalarPrefix and vectorPrefix are not found then print
  244. // the symbol
  245. const char* scalarPrefix = "??_G";
  246. const char* vectorPrefix = "??_E";
  247. // The original code had a check for
  248. // symbol.find("real@") == std::string::npos)
  249. // but this disallows member functions with the name "real".
  250. if (symbol.compare(0, 4, scalarPrefix) &&
  251. symbol.compare(0, 4, vectorPrefix)) {
  252. SectChar = this->SectionHeaders[pSymbolTable->SectionNumber - 1]
  253. .Characteristics;
  254. // skip symbols containing a dot or are from managed code
  255. if (symbol.find('.') == std::string::npos &&
  256. !SymbolIsFromManagedCode(symbol)) {
  257. if (!pSymbolTable->Type && (SectChar & IMAGE_SCN_MEM_WRITE)) {
  258. // Read only (i.e. constants) must be excluded
  259. this->DataSymbols.insert(symbol);
  260. } else {
  261. if (pSymbolTable->Type || !(SectChar & IMAGE_SCN_MEM_READ) ||
  262. (SectChar & IMAGE_SCN_MEM_EXECUTE)) {
  263. this->Symbols.insert(symbol);
  264. }
  265. }
  266. }
  267. }
  268. }
  269. }
  270. /*
  271. * Take into account any aux symbols
  272. */
  273. i += pSymbolTable->NumberOfAuxSymbols;
  274. pSymbolTable += pSymbolTable->NumberOfAuxSymbols;
  275. pSymbolTable++;
  276. }
  277. }
  278. private:
  279. bool SymbolIsFromManagedCode(std::string const& symbol)
  280. {
  281. return symbol == "__t2m" || symbol == "__m2mep" || symbol == "__mep" ||
  282. symbol.find("$$F") != std::string::npos ||
  283. symbol.find("$$J") != std::string::npos;
  284. }
  285. std::set<std::string>& Symbols;
  286. std::set<std::string>& DataSymbols;
  287. DWORD_PTR SymbolCount;
  288. PIMAGE_SECTION_HEADER SectionHeaders;
  289. ObjectHeaderType* ObjectImageHeader;
  290. SymbolTableType* SymbolTable;
  291. bool IsI386;
  292. };
  293. #endif
  294. bool DumpFileWithLlvmNm(std::string const& nmPath, const char* filename,
  295. std::set<std::string>& symbols,
  296. std::set<std::string>& dataSymbols)
  297. {
  298. std::string output;
  299. // break up command line into a vector
  300. std::vector<std::string> command;
  301. command.push_back(nmPath);
  302. command.emplace_back("--no-weak");
  303. command.emplace_back("--defined-only");
  304. command.emplace_back("--format=posix");
  305. command.emplace_back(filename);
  306. // run the command
  307. int exit_code = 0;
  308. cmSystemTools::RunSingleCommand(command, &output, &output, &exit_code,
  309. nullptr, cmSystemTools::OUTPUT_NONE);
  310. if (exit_code != 0) {
  311. fprintf(stderr, "llvm-nm returned an error: %s\n", output.c_str());
  312. return false;
  313. }
  314. std::istringstream ss(output);
  315. std::string line;
  316. while (std::getline(ss, line)) {
  317. if (line.empty()) { // last line
  318. continue;
  319. }
  320. size_t sym_end = line.find(' ');
  321. if (sym_end == std::string::npos) {
  322. fprintf(stderr, "Couldn't parse llvm-nm output line: %s\n",
  323. line.c_str());
  324. return false;
  325. }
  326. if (line.size() < sym_end + 1) {
  327. fprintf(stderr, "Couldn't parse llvm-nm output line: %s\n",
  328. line.c_str());
  329. return false;
  330. }
  331. const char sym_type = line[sym_end + 1];
  332. line.resize(sym_end);
  333. switch (sym_type) {
  334. case 'D':
  335. dataSymbols.insert(line);
  336. break;
  337. case 'T':
  338. symbols.insert(line);
  339. break;
  340. }
  341. }
  342. return true;
  343. }
  344. bool DumpFile(std::string const& nmPath, const char* filename,
  345. std::set<std::string>& symbols,
  346. std::set<std::string>& dataSymbols)
  347. {
  348. #ifndef _WIN32
  349. return DumpFileWithLlvmNm(nmPath, filename, symbols, dataSymbols);
  350. #else
  351. HANDLE hFile;
  352. HANDLE hFileMapping;
  353. LPVOID lpFileBase;
  354. hFile = CreateFileW(cmsys::Encoding::ToWide(filename).c_str(), GENERIC_READ,
  355. FILE_SHARE_READ, NULL, OPEN_EXISTING,
  356. FILE_ATTRIBUTE_NORMAL, 0);
  357. if (hFile == INVALID_HANDLE_VALUE) {
  358. fprintf(stderr, "Couldn't open file '%s' with CreateFile()\n", filename);
  359. return false;
  360. }
  361. hFileMapping = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
  362. if (hFileMapping == 0) {
  363. CloseHandle(hFile);
  364. fprintf(stderr, "Couldn't open file mapping with CreateFileMapping()\n");
  365. return false;
  366. }
  367. lpFileBase = MapViewOfFile(hFileMapping, FILE_MAP_READ, 0, 0, 0);
  368. if (lpFileBase == 0) {
  369. CloseHandle(hFileMapping);
  370. CloseHandle(hFile);
  371. fprintf(stderr, "Couldn't map view of file with MapViewOfFile()\n");
  372. return false;
  373. }
  374. const PIMAGE_DOS_HEADER dosHeader = (PIMAGE_DOS_HEADER)lpFileBase;
  375. if (dosHeader->e_magic == IMAGE_DOS_SIGNATURE) {
  376. fprintf(stderr, "File is an executable. I don't dump those.\n");
  377. return false;
  378. } else {
  379. const PIMAGE_FILE_HEADER imageHeader = (PIMAGE_FILE_HEADER)lpFileBase;
  380. /* Does it look like a COFF OBJ file??? */
  381. if (((imageHeader->Machine == IMAGE_FILE_MACHINE_I386) ||
  382. (imageHeader->Machine == IMAGE_FILE_MACHINE_AMD64) ||
  383. (imageHeader->Machine == IMAGE_FILE_MACHINE_ARM) ||
  384. (imageHeader->Machine == IMAGE_FILE_MACHINE_ARMNT) ||
  385. (imageHeader->Machine == IMAGE_FILE_MACHINE_ARM64)) &&
  386. (imageHeader->Characteristics == 0)) {
  387. /*
  388. * The tests above are checking for IMAGE_FILE_HEADER.Machine
  389. * if it contains supported machine formats (currently ARM and x86)
  390. * and IMAGE_FILE_HEADER.Characteristics == 0 indicating that
  391. * this is not linked COFF OBJ file;
  392. */
  393. DumpSymbols<IMAGE_FILE_HEADER, IMAGE_SYMBOL> symbolDumper(
  394. (PIMAGE_FILE_HEADER)lpFileBase, symbols, dataSymbols,
  395. (imageHeader->Machine == IMAGE_FILE_MACHINE_I386));
  396. symbolDumper.DumpObjFile();
  397. } else {
  398. // check for /bigobj and llvm LTO format
  399. cmANON_OBJECT_HEADER_BIGOBJ* h =
  400. (cmANON_OBJECT_HEADER_BIGOBJ*)lpFileBase;
  401. if (h->Sig1 == 0x0 && h->Sig2 == 0xffff) {
  402. // bigobj
  403. DumpSymbols<cmANON_OBJECT_HEADER_BIGOBJ, cmIMAGE_SYMBOL_EX>
  404. symbolDumper((cmANON_OBJECT_HEADER_BIGOBJ*)lpFileBase, symbols,
  405. dataSymbols, (h->Machine == IMAGE_FILE_MACHINE_I386));
  406. symbolDumper.DumpObjFile();
  407. } else if (
  408. // BCexCODE - llvm bitcode
  409. (h->Sig1 == 0x4342 && h->Sig2 == 0xDEC0) ||
  410. // 0x0B17C0DE - llvm bitcode BC wrapper
  411. (h->Sig1 == 0x0B17 && h->Sig2 == 0xC0DE)) {
  412. return DumpFileWithLlvmNm(nmPath, filename, symbols, dataSymbols);
  413. } else {
  414. printf("unrecognized file format in '%s, %u'\n", filename,
  415. imageHeader->Machine);
  416. return false;
  417. }
  418. }
  419. }
  420. UnmapViewOfFile(lpFileBase);
  421. CloseHandle(hFileMapping);
  422. CloseHandle(hFile);
  423. return true;
  424. #endif
  425. }
  426. bool bindexplib::AddObjectFile(const char* filename)
  427. {
  428. return DumpFile(this->NmPath, filename, this->Symbols, this->DataSymbols);
  429. }
  430. bool bindexplib::AddDefinitionFile(const char* filename)
  431. {
  432. cmsys::ifstream infile(filename);
  433. if (!infile) {
  434. fprintf(stderr, "Couldn't open definition file '%s'\n", filename);
  435. return false;
  436. }
  437. std::string str;
  438. while (std::getline(infile, str)) {
  439. // skip the LIBRARY and EXPORTS lines (if any)
  440. if ((str.compare(0, 7, "LIBRARY") == 0) ||
  441. (str.compare(0, 7, "EXPORTS") == 0)) {
  442. continue;
  443. }
  444. // remove leading tabs & spaces
  445. str.erase(0, str.find_first_not_of(" \t"));
  446. std::size_t found = str.find(" \t DATA");
  447. if (found != std::string::npos) {
  448. str.erase(found, std::string::npos);
  449. this->DataSymbols.insert(str);
  450. } else {
  451. this->Symbols.insert(str);
  452. }
  453. }
  454. infile.close();
  455. return true;
  456. }
  457. void bindexplib::WriteFile(FILE* file)
  458. {
  459. fprintf(file, "EXPORTS \n");
  460. for (std::string const& ds : this->DataSymbols) {
  461. fprintf(file, "\t%s \t DATA\n", ds.c_str());
  462. }
  463. for (std::string const& s : this->Symbols) {
  464. fprintf(file, "\t%s\n", s.c_str());
  465. }
  466. }
  467. void bindexplib::SetNmPath(std::string const& nm)
  468. {
  469. this->NmPath = nm;
  470. }