bindexplib.cxx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  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
  255. if (symbol.find('.') == std::string::npos) {
  256. if (!pSymbolTable->Type && (SectChar & IMAGE_SCN_MEM_WRITE)) {
  257. // Read only (i.e. constants) must be excluded
  258. this->DataSymbols.insert(symbol);
  259. } else {
  260. if (pSymbolTable->Type || !(SectChar & IMAGE_SCN_MEM_READ) ||
  261. (SectChar & IMAGE_SCN_MEM_EXECUTE)) {
  262. this->Symbols.insert(symbol);
  263. }
  264. }
  265. }
  266. }
  267. }
  268. }
  269. /*
  270. * Take into account any aux symbols
  271. */
  272. i += pSymbolTable->NumberOfAuxSymbols;
  273. pSymbolTable += pSymbolTable->NumberOfAuxSymbols;
  274. pSymbolTable++;
  275. }
  276. }
  277. private:
  278. std::set<std::string>& Symbols;
  279. std::set<std::string>& DataSymbols;
  280. DWORD_PTR SymbolCount;
  281. PIMAGE_SECTION_HEADER SectionHeaders;
  282. ObjectHeaderType* ObjectImageHeader;
  283. SymbolTableType* SymbolTable;
  284. bool IsI386;
  285. };
  286. #endif
  287. bool DumpFileWithLlvmNm(std::string const& nmPath, const char* filename,
  288. std::set<std::string>& symbols,
  289. std::set<std::string>& dataSymbols)
  290. {
  291. std::string output;
  292. // break up command line into a vector
  293. std::vector<std::string> command;
  294. command.push_back(nmPath);
  295. command.emplace_back("--no-weak");
  296. command.emplace_back("--defined-only");
  297. command.emplace_back("--format=posix");
  298. command.emplace_back(filename);
  299. // run the command
  300. int exit_code = 0;
  301. cmSystemTools::RunSingleCommand(command, &output, &output, &exit_code,
  302. nullptr, cmSystemTools::OUTPUT_NONE);
  303. if (exit_code != 0) {
  304. fprintf(stderr, "llvm-nm returned an error: %s\n", output.c_str());
  305. return false;
  306. }
  307. std::istringstream ss(output);
  308. std::string line;
  309. while (std::getline(ss, line)) {
  310. if (line.empty()) { // last line
  311. continue;
  312. }
  313. size_t sym_end = line.find(' ');
  314. if (sym_end == std::string::npos) {
  315. fprintf(stderr, "Couldn't parse llvm-nm output line: %s\n",
  316. line.c_str());
  317. return false;
  318. }
  319. if (line.size() < sym_end + 1) {
  320. fprintf(stderr, "Couldn't parse llvm-nm output line: %s\n",
  321. line.c_str());
  322. return false;
  323. }
  324. const char sym_type = line[sym_end + 1];
  325. line.resize(sym_end);
  326. switch (sym_type) {
  327. case 'D':
  328. dataSymbols.insert(line);
  329. break;
  330. case 'T':
  331. symbols.insert(line);
  332. break;
  333. }
  334. }
  335. return true;
  336. }
  337. bool DumpFile(std::string const& nmPath, const char* filename,
  338. std::set<std::string>& symbols,
  339. std::set<std::string>& dataSymbols)
  340. {
  341. #ifndef _WIN32
  342. return DumpFileWithLlvmNm(nmPath, filename, symbols, dataSymbols);
  343. #else
  344. HANDLE hFile;
  345. HANDLE hFileMapping;
  346. LPVOID lpFileBase;
  347. hFile = CreateFileW(cmsys::Encoding::ToWide(filename).c_str(), GENERIC_READ,
  348. FILE_SHARE_READ, NULL, OPEN_EXISTING,
  349. FILE_ATTRIBUTE_NORMAL, 0);
  350. if (hFile == INVALID_HANDLE_VALUE) {
  351. fprintf(stderr, "Couldn't open file '%s' with CreateFile()\n", filename);
  352. return false;
  353. }
  354. hFileMapping = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
  355. if (hFileMapping == 0) {
  356. CloseHandle(hFile);
  357. fprintf(stderr, "Couldn't open file mapping with CreateFileMapping()\n");
  358. return false;
  359. }
  360. lpFileBase = MapViewOfFile(hFileMapping, FILE_MAP_READ, 0, 0, 0);
  361. if (lpFileBase == 0) {
  362. CloseHandle(hFileMapping);
  363. CloseHandle(hFile);
  364. fprintf(stderr, "Couldn't map view of file with MapViewOfFile()\n");
  365. return false;
  366. }
  367. const PIMAGE_DOS_HEADER dosHeader = (PIMAGE_DOS_HEADER)lpFileBase;
  368. if (dosHeader->e_magic == IMAGE_DOS_SIGNATURE) {
  369. fprintf(stderr, "File is an executable. I don't dump those.\n");
  370. return false;
  371. } else {
  372. const PIMAGE_FILE_HEADER imageHeader = (PIMAGE_FILE_HEADER)lpFileBase;
  373. /* Does it look like a COFF OBJ file??? */
  374. if (((imageHeader->Machine == IMAGE_FILE_MACHINE_I386) ||
  375. (imageHeader->Machine == IMAGE_FILE_MACHINE_AMD64) ||
  376. (imageHeader->Machine == IMAGE_FILE_MACHINE_ARM) ||
  377. (imageHeader->Machine == IMAGE_FILE_MACHINE_ARMNT) ||
  378. (imageHeader->Machine == IMAGE_FILE_MACHINE_ARM64)) &&
  379. (imageHeader->Characteristics == 0)) {
  380. /*
  381. * The tests above are checking for IMAGE_FILE_HEADER.Machine
  382. * if it contains supported machine formats (currently ARM and x86)
  383. * and IMAGE_FILE_HEADER.Characteristics == 0 indicating that
  384. * this is not linked COFF OBJ file;
  385. */
  386. DumpSymbols<IMAGE_FILE_HEADER, IMAGE_SYMBOL> symbolDumper(
  387. (PIMAGE_FILE_HEADER)lpFileBase, symbols, dataSymbols,
  388. (imageHeader->Machine == IMAGE_FILE_MACHINE_I386));
  389. symbolDumper.DumpObjFile();
  390. } else {
  391. // check for /bigobj and llvm LTO format
  392. cmANON_OBJECT_HEADER_BIGOBJ* h =
  393. (cmANON_OBJECT_HEADER_BIGOBJ*)lpFileBase;
  394. if (h->Sig1 == 0x0 && h->Sig2 == 0xffff) {
  395. // bigobj
  396. DumpSymbols<cmANON_OBJECT_HEADER_BIGOBJ, cmIMAGE_SYMBOL_EX>
  397. symbolDumper((cmANON_OBJECT_HEADER_BIGOBJ*)lpFileBase, symbols,
  398. dataSymbols, (h->Machine == IMAGE_FILE_MACHINE_I386));
  399. symbolDumper.DumpObjFile();
  400. } else if (
  401. // BCexCODE - llvm bitcode
  402. (h->Sig1 == 0x4342 && h->Sig2 == 0xDEC0) ||
  403. // 0x0B17C0DE - llvm bitcode BC wrapper
  404. (h->Sig1 == 0x0B17 && h->Sig2 == 0xC0DE)) {
  405. return DumpFileWithLlvmNm(nmPath, filename, symbols, dataSymbols);
  406. } else {
  407. printf("unrecognized file format in '%s, %u'\n", filename,
  408. imageHeader->Machine);
  409. return false;
  410. }
  411. }
  412. }
  413. UnmapViewOfFile(lpFileBase);
  414. CloseHandle(hFileMapping);
  415. CloseHandle(hFile);
  416. return true;
  417. #endif
  418. }
  419. bool bindexplib::AddObjectFile(const char* filename)
  420. {
  421. return DumpFile(NmPath, filename, this->Symbols, this->DataSymbols);
  422. }
  423. bool bindexplib::AddDefinitionFile(const char* filename)
  424. {
  425. cmsys::ifstream infile(filename);
  426. if (!infile) {
  427. fprintf(stderr, "Couldn't open definition file '%s'\n", filename);
  428. return false;
  429. }
  430. std::string str;
  431. while (std::getline(infile, str)) {
  432. // skip the LIBRARY and EXPORTS lines (if any)
  433. if ((str.compare(0, 7, "LIBRARY") == 0) ||
  434. (str.compare(0, 7, "EXPORTS") == 0)) {
  435. continue;
  436. }
  437. // remove leading tabs & spaces
  438. str.erase(0, str.find_first_not_of(" \t"));
  439. std::size_t found = str.find(" \t DATA");
  440. if (found != std::string::npos) {
  441. str.erase(found, std::string::npos);
  442. this->DataSymbols.insert(str);
  443. } else {
  444. this->Symbols.insert(str);
  445. }
  446. }
  447. infile.close();
  448. return true;
  449. }
  450. void bindexplib::WriteFile(FILE* file)
  451. {
  452. fprintf(file, "EXPORTS \n");
  453. for (std::string const& ds : this->DataSymbols) {
  454. fprintf(file, "\t%s \t DATA\n", ds.c_str());
  455. }
  456. for (std::string const& s : this->Symbols) {
  457. fprintf(file, "\t%s\n", s.c_str());
  458. }
  459. }
  460. void bindexplib::SetNmPath(std::string const& nm)
  461. {
  462. NmPath = nm;
  463. }