llvm-objdump.cpp 100 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776
  1. //===-- llvm-objdump.cpp - Object file dumping utility for llvm -----------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This program is a utility that works like binutils "objdump", that is, it
  10. // dumps out a plethora of information about an object file depending on the
  11. // flags.
  12. //
  13. // The flags and output of this program should be near identical to those of
  14. // binutils objdump.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #include "llvm-objdump.h"
  18. #include "COFFDump.h"
  19. #include "ELFDump.h"
  20. #include "MachODump.h"
  21. #include "ObjdumpOptID.h"
  22. #include "SourcePrinter.h"
  23. #include "WasmDump.h"
  24. #include "XCOFFDump.h"
  25. #include "llvm/ADT/IndexedMap.h"
  26. #include "llvm/ADT/Optional.h"
  27. #include "llvm/ADT/STLExtras.h"
  28. #include "llvm/ADT/SetOperations.h"
  29. #include "llvm/ADT/SmallSet.h"
  30. #include "llvm/ADT/StringExtras.h"
  31. #include "llvm/ADT/StringSet.h"
  32. #include "llvm/ADT/Triple.h"
  33. #include "llvm/ADT/Twine.h"
  34. #include "llvm/DebugInfo/DWARF/DWARFContext.h"
  35. #include "llvm/DebugInfo/Symbolize/Symbolize.h"
  36. #include "llvm/Demangle/Demangle.h"
  37. #include "llvm/MC/MCAsmInfo.h"
  38. #include "llvm/MC/MCContext.h"
  39. #include "llvm/MC/MCDisassembler/MCDisassembler.h"
  40. #include "llvm/MC/MCDisassembler/MCRelocationInfo.h"
  41. #include "llvm/MC/MCInst.h"
  42. #include "llvm/MC/MCInstPrinter.h"
  43. #include "llvm/MC/MCInstrAnalysis.h"
  44. #include "llvm/MC/MCInstrInfo.h"
  45. #include "llvm/MC/MCObjectFileInfo.h"
  46. #include "llvm/MC/MCRegisterInfo.h"
  47. #include "llvm/MC/MCSubtargetInfo.h"
  48. #include "llvm/MC/MCTargetOptions.h"
  49. #include "llvm/MC/TargetRegistry.h"
  50. #include "llvm/Object/Archive.h"
  51. #include "llvm/Object/COFF.h"
  52. #include "llvm/Object/COFFImportFile.h"
  53. #include "llvm/Object/ELFObjectFile.h"
  54. #include "llvm/Object/FaultMapParser.h"
  55. #include "llvm/Object/MachO.h"
  56. #include "llvm/Object/MachOUniversal.h"
  57. #include "llvm/Object/ObjectFile.h"
  58. #include "llvm/Object/Wasm.h"
  59. #include "llvm/Option/Arg.h"
  60. #include "llvm/Option/ArgList.h"
  61. #include "llvm/Option/Option.h"
  62. #include "llvm/Support/Casting.h"
  63. #include "llvm/Support/Debug.h"
  64. #include "llvm/Support/Errc.h"
  65. #include "llvm/Support/FileSystem.h"
  66. #include "llvm/Support/Format.h"
  67. #include "llvm/Support/FormatVariadic.h"
  68. #include "llvm/Support/GraphWriter.h"
  69. #include "llvm/Support/Host.h"
  70. #include "llvm/Support/InitLLVM.h"
  71. #include "llvm/Support/MemoryBuffer.h"
  72. #include "llvm/Support/SourceMgr.h"
  73. #include "llvm/Support/StringSaver.h"
  74. #include "llvm/Support/TargetSelect.h"
  75. #include "llvm/Support/WithColor.h"
  76. #include "llvm/Support/raw_ostream.h"
  77. #include <algorithm>
  78. #include <cctype>
  79. #include <cstring>
  80. #include <system_error>
  81. #include <unordered_map>
  82. #include <utility>
  83. using namespace llvm;
  84. using namespace llvm::object;
  85. using namespace llvm::objdump;
  86. using namespace llvm::opt;
  87. namespace {
  88. class CommonOptTable : public opt::OptTable {
  89. public:
  90. CommonOptTable(ArrayRef<Info> OptionInfos, const char *Usage,
  91. const char *Description)
  92. : OptTable(OptionInfos), Usage(Usage), Description(Description) {
  93. setGroupedShortOptions(true);
  94. }
  95. void printHelp(StringRef Argv0, bool ShowHidden = false) const {
  96. Argv0 = sys::path::filename(Argv0);
  97. opt::OptTable::printHelp(outs(), (Argv0 + Usage).str().c_str(), Description,
  98. ShowHidden, ShowHidden);
  99. // TODO Replace this with OptTable API once it adds extrahelp support.
  100. outs() << "\nPass @FILE as argument to read options from FILE.\n";
  101. }
  102. private:
  103. const char *Usage;
  104. const char *Description;
  105. };
  106. // ObjdumpOptID is in ObjdumpOptID.h
  107. #define PREFIX(NAME, VALUE) const char *const OBJDUMP_##NAME[] = VALUE;
  108. #include "ObjdumpOpts.inc"
  109. #undef PREFIX
  110. static constexpr opt::OptTable::Info ObjdumpInfoTable[] = {
  111. #define OBJDUMP_nullptr nullptr
  112. #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
  113. HELPTEXT, METAVAR, VALUES) \
  114. {OBJDUMP_##PREFIX, NAME, HELPTEXT, \
  115. METAVAR, OBJDUMP_##ID, opt::Option::KIND##Class, \
  116. PARAM, FLAGS, OBJDUMP_##GROUP, \
  117. OBJDUMP_##ALIAS, ALIASARGS, VALUES},
  118. #include "ObjdumpOpts.inc"
  119. #undef OPTION
  120. #undef OBJDUMP_nullptr
  121. };
  122. class ObjdumpOptTable : public CommonOptTable {
  123. public:
  124. ObjdumpOptTable()
  125. : CommonOptTable(ObjdumpInfoTable, " [options] <input object files>",
  126. "llvm object file dumper") {}
  127. };
  128. enum OtoolOptID {
  129. OTOOL_INVALID = 0, // This is not an option ID.
  130. #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
  131. HELPTEXT, METAVAR, VALUES) \
  132. OTOOL_##ID,
  133. #include "OtoolOpts.inc"
  134. #undef OPTION
  135. };
  136. #define PREFIX(NAME, VALUE) const char *const OTOOL_##NAME[] = VALUE;
  137. #include "OtoolOpts.inc"
  138. #undef PREFIX
  139. static constexpr opt::OptTable::Info OtoolInfoTable[] = {
  140. #define OTOOL_nullptr nullptr
  141. #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
  142. HELPTEXT, METAVAR, VALUES) \
  143. {OTOOL_##PREFIX, NAME, HELPTEXT, \
  144. METAVAR, OTOOL_##ID, opt::Option::KIND##Class, \
  145. PARAM, FLAGS, OTOOL_##GROUP, \
  146. OTOOL_##ALIAS, ALIASARGS, VALUES},
  147. #include "OtoolOpts.inc"
  148. #undef OPTION
  149. #undef OTOOL_nullptr
  150. };
  151. class OtoolOptTable : public CommonOptTable {
  152. public:
  153. OtoolOptTable()
  154. : CommonOptTable(OtoolInfoTable, " [option...] [file...]",
  155. "Mach-O object file displaying tool") {}
  156. };
  157. } // namespace
  158. #define DEBUG_TYPE "objdump"
  159. static uint64_t AdjustVMA;
  160. static bool AllHeaders;
  161. static std::string ArchName;
  162. bool objdump::ArchiveHeaders;
  163. bool objdump::Demangle;
  164. bool objdump::Disassemble;
  165. bool objdump::DisassembleAll;
  166. bool objdump::SymbolDescription;
  167. static std::vector<std::string> DisassembleSymbols;
  168. static bool DisassembleZeroes;
  169. static std::vector<std::string> DisassemblerOptions;
  170. DIDumpType objdump::DwarfDumpType;
  171. static bool DynamicRelocations;
  172. static bool FaultMapSection;
  173. static bool FileHeaders;
  174. bool objdump::SectionContents;
  175. static std::vector<std::string> InputFilenames;
  176. bool objdump::PrintLines;
  177. static bool MachOOpt;
  178. std::string objdump::MCPU;
  179. std::vector<std::string> objdump::MAttrs;
  180. bool objdump::ShowRawInsn;
  181. bool objdump::LeadingAddr;
  182. static bool RawClangAST;
  183. bool objdump::Relocations;
  184. bool objdump::PrintImmHex;
  185. bool objdump::PrivateHeaders;
  186. std::vector<std::string> objdump::FilterSections;
  187. bool objdump::SectionHeaders;
  188. static bool ShowLMA;
  189. bool objdump::PrintSource;
  190. static uint64_t StartAddress;
  191. static bool HasStartAddressFlag;
  192. static uint64_t StopAddress = UINT64_MAX;
  193. static bool HasStopAddressFlag;
  194. bool objdump::SymbolTable;
  195. static bool SymbolizeOperands;
  196. static bool DynamicSymbolTable;
  197. std::string objdump::TripleName;
  198. bool objdump::UnwindInfo;
  199. static bool Wide;
  200. std::string objdump::Prefix;
  201. uint32_t objdump::PrefixStrip;
  202. DebugVarsFormat objdump::DbgVariables = DVDisabled;
  203. int objdump::DbgIndent = 52;
  204. static StringSet<> DisasmSymbolSet;
  205. StringSet<> objdump::FoundSectionSet;
  206. static StringRef ToolName;
  207. namespace {
  208. struct FilterResult {
  209. // True if the section should not be skipped.
  210. bool Keep;
  211. // True if the index counter should be incremented, even if the section should
  212. // be skipped. For example, sections may be skipped if they are not included
  213. // in the --section flag, but we still want those to count toward the section
  214. // count.
  215. bool IncrementIndex;
  216. };
  217. } // namespace
  218. static FilterResult checkSectionFilter(object::SectionRef S) {
  219. if (FilterSections.empty())
  220. return {/*Keep=*/true, /*IncrementIndex=*/true};
  221. Expected<StringRef> SecNameOrErr = S.getName();
  222. if (!SecNameOrErr) {
  223. consumeError(SecNameOrErr.takeError());
  224. return {/*Keep=*/false, /*IncrementIndex=*/false};
  225. }
  226. StringRef SecName = *SecNameOrErr;
  227. // StringSet does not allow empty key so avoid adding sections with
  228. // no name (such as the section with index 0) here.
  229. if (!SecName.empty())
  230. FoundSectionSet.insert(SecName);
  231. // Only show the section if it's in the FilterSections list, but always
  232. // increment so the indexing is stable.
  233. return {/*Keep=*/is_contained(FilterSections, SecName),
  234. /*IncrementIndex=*/true};
  235. }
  236. SectionFilter objdump::ToolSectionFilter(object::ObjectFile const &O,
  237. uint64_t *Idx) {
  238. // Start at UINT64_MAX so that the first index returned after an increment is
  239. // zero (after the unsigned wrap).
  240. if (Idx)
  241. *Idx = UINT64_MAX;
  242. return SectionFilter(
  243. [Idx](object::SectionRef S) {
  244. FilterResult Result = checkSectionFilter(S);
  245. if (Idx != nullptr && Result.IncrementIndex)
  246. *Idx += 1;
  247. return Result.Keep;
  248. },
  249. O);
  250. }
  251. std::string objdump::getFileNameForError(const object::Archive::Child &C,
  252. unsigned Index) {
  253. Expected<StringRef> NameOrErr = C.getName();
  254. if (NameOrErr)
  255. return std::string(NameOrErr.get());
  256. // If we have an error getting the name then we print the index of the archive
  257. // member. Since we are already in an error state, we just ignore this error.
  258. consumeError(NameOrErr.takeError());
  259. return "<file index: " + std::to_string(Index) + ">";
  260. }
  261. void objdump::reportWarning(const Twine &Message, StringRef File) {
  262. // Output order between errs() and outs() matters especially for archive
  263. // files where the output is per member object.
  264. outs().flush();
  265. WithColor::warning(errs(), ToolName)
  266. << "'" << File << "': " << Message << "\n";
  267. }
  268. [[noreturn]] void objdump::reportError(StringRef File, const Twine &Message) {
  269. outs().flush();
  270. WithColor::error(errs(), ToolName) << "'" << File << "': " << Message << "\n";
  271. exit(1);
  272. }
  273. [[noreturn]] void objdump::reportError(Error E, StringRef FileName,
  274. StringRef ArchiveName,
  275. StringRef ArchitectureName) {
  276. assert(E);
  277. outs().flush();
  278. WithColor::error(errs(), ToolName);
  279. if (ArchiveName != "")
  280. errs() << ArchiveName << "(" << FileName << ")";
  281. else
  282. errs() << "'" << FileName << "'";
  283. if (!ArchitectureName.empty())
  284. errs() << " (for architecture " << ArchitectureName << ")";
  285. errs() << ": ";
  286. logAllUnhandledErrors(std::move(E), errs());
  287. exit(1);
  288. }
  289. static void reportCmdLineWarning(const Twine &Message) {
  290. WithColor::warning(errs(), ToolName) << Message << "\n";
  291. }
  292. [[noreturn]] static void reportCmdLineError(const Twine &Message) {
  293. WithColor::error(errs(), ToolName) << Message << "\n";
  294. exit(1);
  295. }
  296. static void warnOnNoMatchForSections() {
  297. SetVector<StringRef> MissingSections;
  298. for (StringRef S : FilterSections) {
  299. if (FoundSectionSet.count(S))
  300. return;
  301. // User may specify a unnamed section. Don't warn for it.
  302. if (!S.empty())
  303. MissingSections.insert(S);
  304. }
  305. // Warn only if no section in FilterSections is matched.
  306. for (StringRef S : MissingSections)
  307. reportCmdLineWarning("section '" + S +
  308. "' mentioned in a -j/--section option, but not "
  309. "found in any input file");
  310. }
  311. static const Target *getTarget(const ObjectFile *Obj) {
  312. // Figure out the target triple.
  313. Triple TheTriple("unknown-unknown-unknown");
  314. if (TripleName.empty()) {
  315. TheTriple = Obj->makeTriple();
  316. } else {
  317. TheTriple.setTriple(Triple::normalize(TripleName));
  318. auto Arch = Obj->getArch();
  319. if (Arch == Triple::arm || Arch == Triple::armeb)
  320. Obj->setARMSubArch(TheTriple);
  321. }
  322. // Get the target specific parser.
  323. std::string Error;
  324. const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
  325. Error);
  326. if (!TheTarget)
  327. reportError(Obj->getFileName(), "can't find target: " + Error);
  328. // Update the triple name and return the found target.
  329. TripleName = TheTriple.getTriple();
  330. return TheTarget;
  331. }
  332. bool objdump::isRelocAddressLess(RelocationRef A, RelocationRef B) {
  333. return A.getOffset() < B.getOffset();
  334. }
  335. static Error getRelocationValueString(const RelocationRef &Rel,
  336. SmallVectorImpl<char> &Result) {
  337. const ObjectFile *Obj = Rel.getObject();
  338. if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
  339. return getELFRelocationValueString(ELF, Rel, Result);
  340. if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
  341. return getCOFFRelocationValueString(COFF, Rel, Result);
  342. if (auto *Wasm = dyn_cast<WasmObjectFile>(Obj))
  343. return getWasmRelocationValueString(Wasm, Rel, Result);
  344. if (auto *MachO = dyn_cast<MachOObjectFile>(Obj))
  345. return getMachORelocationValueString(MachO, Rel, Result);
  346. if (auto *XCOFF = dyn_cast<XCOFFObjectFile>(Obj))
  347. return getXCOFFRelocationValueString(XCOFF, Rel, Result);
  348. llvm_unreachable("unknown object file format");
  349. }
  350. /// Indicates whether this relocation should hidden when listing
  351. /// relocations, usually because it is the trailing part of a multipart
  352. /// relocation that will be printed as part of the leading relocation.
  353. static bool getHidden(RelocationRef RelRef) {
  354. auto *MachO = dyn_cast<MachOObjectFile>(RelRef.getObject());
  355. if (!MachO)
  356. return false;
  357. unsigned Arch = MachO->getArch();
  358. DataRefImpl Rel = RelRef.getRawDataRefImpl();
  359. uint64_t Type = MachO->getRelocationType(Rel);
  360. // On arches that use the generic relocations, GENERIC_RELOC_PAIR
  361. // is always hidden.
  362. if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc)
  363. return Type == MachO::GENERIC_RELOC_PAIR;
  364. if (Arch == Triple::x86_64) {
  365. // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
  366. // an X86_64_RELOC_SUBTRACTOR.
  367. if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
  368. DataRefImpl RelPrev = Rel;
  369. RelPrev.d.a--;
  370. uint64_t PrevType = MachO->getRelocationType(RelPrev);
  371. if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
  372. return true;
  373. }
  374. }
  375. return false;
  376. }
  377. namespace {
  378. /// Get the column at which we want to start printing the instruction
  379. /// disassembly, taking into account anything which appears to the left of it.
  380. unsigned getInstStartColumn(const MCSubtargetInfo &STI) {
  381. return !ShowRawInsn ? 16 : STI.getTargetTriple().isX86() ? 40 : 24;
  382. }
  383. static bool isAArch64Elf(const ObjectFile *Obj) {
  384. const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj);
  385. return Elf && Elf->getEMachine() == ELF::EM_AARCH64;
  386. }
  387. static bool isArmElf(const ObjectFile *Obj) {
  388. const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj);
  389. return Elf && Elf->getEMachine() == ELF::EM_ARM;
  390. }
  391. static bool hasMappingSymbols(const ObjectFile *Obj) {
  392. return isArmElf(Obj) || isAArch64Elf(Obj);
  393. }
  394. static void printRelocation(formatted_raw_ostream &OS, StringRef FileName,
  395. const RelocationRef &Rel, uint64_t Address,
  396. bool Is64Bits) {
  397. StringRef Fmt = Is64Bits ? "\t\t%016" PRIx64 ": " : "\t\t\t%08" PRIx64 ": ";
  398. SmallString<16> Name;
  399. SmallString<32> Val;
  400. Rel.getTypeName(Name);
  401. if (Error E = getRelocationValueString(Rel, Val))
  402. reportError(std::move(E), FileName);
  403. OS << format(Fmt.data(), Address) << Name << "\t" << Val;
  404. }
  405. class PrettyPrinter {
  406. public:
  407. virtual ~PrettyPrinter() = default;
  408. virtual void
  409. printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
  410. object::SectionedAddress Address, formatted_raw_ostream &OS,
  411. StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP,
  412. StringRef ObjectFilename, std::vector<RelocationRef> *Rels,
  413. LiveVariablePrinter &LVP) {
  414. if (SP && (PrintSource || PrintLines))
  415. SP->printSourceLine(OS, Address, ObjectFilename, LVP);
  416. LVP.printBetweenInsts(OS, false);
  417. size_t Start = OS.tell();
  418. if (LeadingAddr)
  419. OS << format("%8" PRIx64 ":", Address.Address);
  420. if (ShowRawInsn) {
  421. OS << ' ';
  422. dumpBytes(Bytes, OS);
  423. }
  424. // The output of printInst starts with a tab. Print some spaces so that
  425. // the tab has 1 column and advances to the target tab stop.
  426. unsigned TabStop = getInstStartColumn(STI);
  427. unsigned Column = OS.tell() - Start;
  428. OS.indent(Column < TabStop - 1 ? TabStop - 1 - Column : 7 - Column % 8);
  429. if (MI) {
  430. // See MCInstPrinter::printInst. On targets where a PC relative immediate
  431. // is relative to the next instruction and the length of a MCInst is
  432. // difficult to measure (x86), this is the address of the next
  433. // instruction.
  434. uint64_t Addr =
  435. Address.Address + (STI.getTargetTriple().isX86() ? Bytes.size() : 0);
  436. IP.printInst(MI, Addr, "", STI, OS);
  437. } else
  438. OS << "\t<unknown>";
  439. }
  440. };
  441. PrettyPrinter PrettyPrinterInst;
  442. class HexagonPrettyPrinter : public PrettyPrinter {
  443. public:
  444. void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
  445. formatted_raw_ostream &OS) {
  446. uint32_t opcode =
  447. (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
  448. if (LeadingAddr)
  449. OS << format("%8" PRIx64 ":", Address);
  450. if (ShowRawInsn) {
  451. OS << "\t";
  452. dumpBytes(Bytes.slice(0, 4), OS);
  453. OS << format("\t%08" PRIx32, opcode);
  454. }
  455. }
  456. void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
  457. object::SectionedAddress Address, formatted_raw_ostream &OS,
  458. StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP,
  459. StringRef ObjectFilename, std::vector<RelocationRef> *Rels,
  460. LiveVariablePrinter &LVP) override {
  461. if (SP && (PrintSource || PrintLines))
  462. SP->printSourceLine(OS, Address, ObjectFilename, LVP, "");
  463. if (!MI) {
  464. printLead(Bytes, Address.Address, OS);
  465. OS << " <unknown>";
  466. return;
  467. }
  468. std::string Buffer;
  469. {
  470. raw_string_ostream TempStream(Buffer);
  471. IP.printInst(MI, Address.Address, "", STI, TempStream);
  472. }
  473. StringRef Contents(Buffer);
  474. // Split off bundle attributes
  475. auto PacketBundle = Contents.rsplit('\n');
  476. // Split off first instruction from the rest
  477. auto HeadTail = PacketBundle.first.split('\n');
  478. auto Preamble = " { ";
  479. auto Separator = "";
  480. // Hexagon's packets require relocations to be inline rather than
  481. // clustered at the end of the packet.
  482. std::vector<RelocationRef>::const_iterator RelCur = Rels->begin();
  483. std::vector<RelocationRef>::const_iterator RelEnd = Rels->end();
  484. auto PrintReloc = [&]() -> void {
  485. while ((RelCur != RelEnd) && (RelCur->getOffset() <= Address.Address)) {
  486. if (RelCur->getOffset() == Address.Address) {
  487. printRelocation(OS, ObjectFilename, *RelCur, Address.Address, false);
  488. return;
  489. }
  490. ++RelCur;
  491. }
  492. };
  493. while (!HeadTail.first.empty()) {
  494. OS << Separator;
  495. Separator = "\n";
  496. if (SP && (PrintSource || PrintLines))
  497. SP->printSourceLine(OS, Address, ObjectFilename, LVP, "");
  498. printLead(Bytes, Address.Address, OS);
  499. OS << Preamble;
  500. Preamble = " ";
  501. StringRef Inst;
  502. auto Duplex = HeadTail.first.split('\v');
  503. if (!Duplex.second.empty()) {
  504. OS << Duplex.first;
  505. OS << "; ";
  506. Inst = Duplex.second;
  507. }
  508. else
  509. Inst = HeadTail.first;
  510. OS << Inst;
  511. HeadTail = HeadTail.second.split('\n');
  512. if (HeadTail.first.empty())
  513. OS << " } " << PacketBundle.second;
  514. PrintReloc();
  515. Bytes = Bytes.slice(4);
  516. Address.Address += 4;
  517. }
  518. }
  519. };
  520. HexagonPrettyPrinter HexagonPrettyPrinterInst;
  521. class AMDGCNPrettyPrinter : public PrettyPrinter {
  522. public:
  523. void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
  524. object::SectionedAddress Address, formatted_raw_ostream &OS,
  525. StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP,
  526. StringRef ObjectFilename, std::vector<RelocationRef> *Rels,
  527. LiveVariablePrinter &LVP) override {
  528. if (SP && (PrintSource || PrintLines))
  529. SP->printSourceLine(OS, Address, ObjectFilename, LVP);
  530. if (MI) {
  531. SmallString<40> InstStr;
  532. raw_svector_ostream IS(InstStr);
  533. IP.printInst(MI, Address.Address, "", STI, IS);
  534. OS << left_justify(IS.str(), 60);
  535. } else {
  536. // an unrecognized encoding - this is probably data so represent it
  537. // using the .long directive, or .byte directive if fewer than 4 bytes
  538. // remaining
  539. if (Bytes.size() >= 4) {
  540. OS << format("\t.long 0x%08" PRIx32 " ",
  541. support::endian::read32<support::little>(Bytes.data()));
  542. OS.indent(42);
  543. } else {
  544. OS << format("\t.byte 0x%02" PRIx8, Bytes[0]);
  545. for (unsigned int i = 1; i < Bytes.size(); i++)
  546. OS << format(", 0x%02" PRIx8, Bytes[i]);
  547. OS.indent(55 - (6 * Bytes.size()));
  548. }
  549. }
  550. OS << format("// %012" PRIX64 ":", Address.Address);
  551. if (Bytes.size() >= 4) {
  552. // D should be casted to uint32_t here as it is passed by format to
  553. // snprintf as vararg.
  554. for (uint32_t D : makeArrayRef(
  555. reinterpret_cast<const support::little32_t *>(Bytes.data()),
  556. Bytes.size() / 4))
  557. OS << format(" %08" PRIX32, D);
  558. } else {
  559. for (unsigned char B : Bytes)
  560. OS << format(" %02" PRIX8, B);
  561. }
  562. if (!Annot.empty())
  563. OS << " // " << Annot;
  564. }
  565. };
  566. AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst;
  567. class BPFPrettyPrinter : public PrettyPrinter {
  568. public:
  569. void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
  570. object::SectionedAddress Address, formatted_raw_ostream &OS,
  571. StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP,
  572. StringRef ObjectFilename, std::vector<RelocationRef> *Rels,
  573. LiveVariablePrinter &LVP) override {
  574. if (SP && (PrintSource || PrintLines))
  575. SP->printSourceLine(OS, Address, ObjectFilename, LVP);
  576. if (LeadingAddr)
  577. OS << format("%8" PRId64 ":", Address.Address / 8);
  578. if (ShowRawInsn) {
  579. OS << "\t";
  580. dumpBytes(Bytes, OS);
  581. }
  582. if (MI)
  583. IP.printInst(MI, Address.Address, "", STI, OS);
  584. else
  585. OS << "\t<unknown>";
  586. }
  587. };
  588. BPFPrettyPrinter BPFPrettyPrinterInst;
  589. PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
  590. switch(Triple.getArch()) {
  591. default:
  592. return PrettyPrinterInst;
  593. case Triple::hexagon:
  594. return HexagonPrettyPrinterInst;
  595. case Triple::amdgcn:
  596. return AMDGCNPrettyPrinterInst;
  597. case Triple::bpfel:
  598. case Triple::bpfeb:
  599. return BPFPrettyPrinterInst;
  600. }
  601. }
  602. }
  603. static uint8_t getElfSymbolType(const ObjectFile *Obj, const SymbolRef &Sym) {
  604. assert(Obj->isELF());
  605. if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
  606. return unwrapOrError(Elf32LEObj->getSymbol(Sym.getRawDataRefImpl()),
  607. Obj->getFileName())
  608. ->getType();
  609. if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
  610. return unwrapOrError(Elf64LEObj->getSymbol(Sym.getRawDataRefImpl()),
  611. Obj->getFileName())
  612. ->getType();
  613. if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
  614. return unwrapOrError(Elf32BEObj->getSymbol(Sym.getRawDataRefImpl()),
  615. Obj->getFileName())
  616. ->getType();
  617. if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
  618. return unwrapOrError(Elf64BEObj->getSymbol(Sym.getRawDataRefImpl()),
  619. Obj->getFileName())
  620. ->getType();
  621. llvm_unreachable("Unsupported binary format");
  622. }
  623. template <class ELFT> static void
  624. addDynamicElfSymbols(const ELFObjectFile<ELFT> *Obj,
  625. std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
  626. for (auto Symbol : Obj->getDynamicSymbolIterators()) {
  627. uint8_t SymbolType = Symbol.getELFType();
  628. if (SymbolType == ELF::STT_SECTION)
  629. continue;
  630. uint64_t Address = unwrapOrError(Symbol.getAddress(), Obj->getFileName());
  631. // ELFSymbolRef::getAddress() returns size instead of value for common
  632. // symbols which is not desirable for disassembly output. Overriding.
  633. if (SymbolType == ELF::STT_COMMON)
  634. Address = unwrapOrError(Obj->getSymbol(Symbol.getRawDataRefImpl()),
  635. Obj->getFileName())
  636. ->st_value;
  637. StringRef Name = unwrapOrError(Symbol.getName(), Obj->getFileName());
  638. if (Name.empty())
  639. continue;
  640. section_iterator SecI =
  641. unwrapOrError(Symbol.getSection(), Obj->getFileName());
  642. if (SecI == Obj->section_end())
  643. continue;
  644. AllSymbols[*SecI].emplace_back(Address, Name, SymbolType);
  645. }
  646. }
  647. static void
  648. addDynamicElfSymbols(const ObjectFile *Obj,
  649. std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
  650. assert(Obj->isELF());
  651. if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
  652. addDynamicElfSymbols(Elf32LEObj, AllSymbols);
  653. else if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
  654. addDynamicElfSymbols(Elf64LEObj, AllSymbols);
  655. else if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
  656. addDynamicElfSymbols(Elf32BEObj, AllSymbols);
  657. else if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
  658. addDynamicElfSymbols(Elf64BEObj, AllSymbols);
  659. else
  660. llvm_unreachable("Unsupported binary format");
  661. }
  662. static Optional<SectionRef> getWasmCodeSection(const WasmObjectFile *Obj) {
  663. for (auto SecI : Obj->sections()) {
  664. const WasmSection &Section = Obj->getWasmSection(SecI);
  665. if (Section.Type == wasm::WASM_SEC_CODE)
  666. return SecI;
  667. }
  668. return None;
  669. }
  670. static void
  671. addMissingWasmCodeSymbols(const WasmObjectFile *Obj,
  672. std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
  673. Optional<SectionRef> Section = getWasmCodeSection(Obj);
  674. if (!Section)
  675. return;
  676. SectionSymbolsTy &Symbols = AllSymbols[*Section];
  677. std::set<uint64_t> SymbolAddresses;
  678. for (const auto &Sym : Symbols)
  679. SymbolAddresses.insert(Sym.Addr);
  680. for (const wasm::WasmFunction &Function : Obj->functions()) {
  681. uint64_t Address = Function.CodeSectionOffset;
  682. // Only add fallback symbols for functions not already present in the symbol
  683. // table.
  684. if (SymbolAddresses.count(Address))
  685. continue;
  686. // This function has no symbol, so it should have no SymbolName.
  687. assert(Function.SymbolName.empty());
  688. // We use DebugName for the name, though it may be empty if there is no
  689. // "name" custom section, or that section is missing a name for this
  690. // function.
  691. StringRef Name = Function.DebugName;
  692. Symbols.emplace_back(Address, Name, ELF::STT_NOTYPE);
  693. }
  694. }
  695. static void addPltEntries(const ObjectFile *Obj,
  696. std::map<SectionRef, SectionSymbolsTy> &AllSymbols,
  697. StringSaver &Saver) {
  698. Optional<SectionRef> Plt = None;
  699. for (const SectionRef &Section : Obj->sections()) {
  700. Expected<StringRef> SecNameOrErr = Section.getName();
  701. if (!SecNameOrErr) {
  702. consumeError(SecNameOrErr.takeError());
  703. continue;
  704. }
  705. if (*SecNameOrErr == ".plt")
  706. Plt = Section;
  707. }
  708. if (!Plt)
  709. return;
  710. if (auto *ElfObj = dyn_cast<ELFObjectFileBase>(Obj)) {
  711. for (auto PltEntry : ElfObj->getPltAddresses()) {
  712. if (PltEntry.first) {
  713. SymbolRef Symbol(*PltEntry.first, ElfObj);
  714. uint8_t SymbolType = getElfSymbolType(Obj, Symbol);
  715. if (Expected<StringRef> NameOrErr = Symbol.getName()) {
  716. if (!NameOrErr->empty())
  717. AllSymbols[*Plt].emplace_back(
  718. PltEntry.second, Saver.save((*NameOrErr + "@plt").str()),
  719. SymbolType);
  720. continue;
  721. } else {
  722. // The warning has been reported in disassembleObject().
  723. consumeError(NameOrErr.takeError());
  724. }
  725. }
  726. reportWarning("PLT entry at 0x" + Twine::utohexstr(PltEntry.second) +
  727. " references an invalid symbol",
  728. Obj->getFileName());
  729. }
  730. }
  731. }
  732. // Normally the disassembly output will skip blocks of zeroes. This function
  733. // returns the number of zero bytes that can be skipped when dumping the
  734. // disassembly of the instructions in Buf.
  735. static size_t countSkippableZeroBytes(ArrayRef<uint8_t> Buf) {
  736. // Find the number of leading zeroes.
  737. size_t N = 0;
  738. while (N < Buf.size() && !Buf[N])
  739. ++N;
  740. // We may want to skip blocks of zero bytes, but unless we see
  741. // at least 8 of them in a row.
  742. if (N < 8)
  743. return 0;
  744. // We skip zeroes in multiples of 4 because do not want to truncate an
  745. // instruction if it starts with a zero byte.
  746. return N & ~0x3;
  747. }
  748. // Returns a map from sections to their relocations.
  749. static std::map<SectionRef, std::vector<RelocationRef>>
  750. getRelocsMap(object::ObjectFile const &Obj) {
  751. std::map<SectionRef, std::vector<RelocationRef>> Ret;
  752. uint64_t I = (uint64_t)-1;
  753. for (SectionRef Sec : Obj.sections()) {
  754. ++I;
  755. Expected<section_iterator> RelocatedOrErr = Sec.getRelocatedSection();
  756. if (!RelocatedOrErr)
  757. reportError(Obj.getFileName(),
  758. "section (" + Twine(I) +
  759. "): failed to get a relocated section: " +
  760. toString(RelocatedOrErr.takeError()));
  761. section_iterator Relocated = *RelocatedOrErr;
  762. if (Relocated == Obj.section_end() || !checkSectionFilter(*Relocated).Keep)
  763. continue;
  764. std::vector<RelocationRef> &V = Ret[*Relocated];
  765. append_range(V, Sec.relocations());
  766. // Sort relocations by address.
  767. llvm::stable_sort(V, isRelocAddressLess);
  768. }
  769. return Ret;
  770. }
  771. // Used for --adjust-vma to check if address should be adjusted by the
  772. // specified value for a given section.
  773. // For ELF we do not adjust non-allocatable sections like debug ones,
  774. // because they are not loadable.
  775. // TODO: implement for other file formats.
  776. static bool shouldAdjustVA(const SectionRef &Section) {
  777. const ObjectFile *Obj = Section.getObject();
  778. if (Obj->isELF())
  779. return ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC;
  780. return false;
  781. }
  782. typedef std::pair<uint64_t, char> MappingSymbolPair;
  783. static char getMappingSymbolKind(ArrayRef<MappingSymbolPair> MappingSymbols,
  784. uint64_t Address) {
  785. auto It =
  786. partition_point(MappingSymbols, [Address](const MappingSymbolPair &Val) {
  787. return Val.first <= Address;
  788. });
  789. // Return zero for any address before the first mapping symbol; this means
  790. // we should use the default disassembly mode, depending on the target.
  791. if (It == MappingSymbols.begin())
  792. return '\x00';
  793. return (It - 1)->second;
  794. }
  795. static uint64_t dumpARMELFData(uint64_t SectionAddr, uint64_t Index,
  796. uint64_t End, const ObjectFile *Obj,
  797. ArrayRef<uint8_t> Bytes,
  798. ArrayRef<MappingSymbolPair> MappingSymbols,
  799. raw_ostream &OS) {
  800. support::endianness Endian =
  801. Obj->isLittleEndian() ? support::little : support::big;
  802. OS << format("%8" PRIx64 ":\t", SectionAddr + Index);
  803. if (Index + 4 <= End) {
  804. dumpBytes(Bytes.slice(Index, 4), OS);
  805. OS << "\t.word\t"
  806. << format_hex(support::endian::read32(Bytes.data() + Index, Endian),
  807. 10);
  808. return 4;
  809. }
  810. if (Index + 2 <= End) {
  811. dumpBytes(Bytes.slice(Index, 2), OS);
  812. OS << "\t\t.short\t"
  813. << format_hex(support::endian::read16(Bytes.data() + Index, Endian),
  814. 6);
  815. return 2;
  816. }
  817. dumpBytes(Bytes.slice(Index, 1), OS);
  818. OS << "\t\t.byte\t" << format_hex(Bytes[0], 4);
  819. return 1;
  820. }
  821. static void dumpELFData(uint64_t SectionAddr, uint64_t Index, uint64_t End,
  822. ArrayRef<uint8_t> Bytes) {
  823. // print out data up to 8 bytes at a time in hex and ascii
  824. uint8_t AsciiData[9] = {'\0'};
  825. uint8_t Byte;
  826. int NumBytes = 0;
  827. for (; Index < End; ++Index) {
  828. if (NumBytes == 0)
  829. outs() << format("%8" PRIx64 ":", SectionAddr + Index);
  830. Byte = Bytes.slice(Index)[0];
  831. outs() << format(" %02x", Byte);
  832. AsciiData[NumBytes] = isPrint(Byte) ? Byte : '.';
  833. uint8_t IndentOffset = 0;
  834. NumBytes++;
  835. if (Index == End - 1 || NumBytes > 8) {
  836. // Indent the space for less than 8 bytes data.
  837. // 2 spaces for byte and one for space between bytes
  838. IndentOffset = 3 * (8 - NumBytes);
  839. for (int Excess = NumBytes; Excess < 8; Excess++)
  840. AsciiData[Excess] = '\0';
  841. NumBytes = 8;
  842. }
  843. if (NumBytes == 8) {
  844. AsciiData[8] = '\0';
  845. outs() << std::string(IndentOffset, ' ') << " ";
  846. outs() << reinterpret_cast<char *>(AsciiData);
  847. outs() << '\n';
  848. NumBytes = 0;
  849. }
  850. }
  851. }
  852. SymbolInfoTy objdump::createSymbolInfo(const ObjectFile *Obj,
  853. const SymbolRef &Symbol) {
  854. const StringRef FileName = Obj->getFileName();
  855. const uint64_t Addr = unwrapOrError(Symbol.getAddress(), FileName);
  856. const StringRef Name = unwrapOrError(Symbol.getName(), FileName);
  857. if (Obj->isXCOFF() && SymbolDescription) {
  858. const auto *XCOFFObj = cast<XCOFFObjectFile>(Obj);
  859. DataRefImpl SymbolDRI = Symbol.getRawDataRefImpl();
  860. const uint32_t SymbolIndex = XCOFFObj->getSymbolIndex(SymbolDRI.p);
  861. Optional<XCOFF::StorageMappingClass> Smc =
  862. getXCOFFSymbolCsectSMC(XCOFFObj, Symbol);
  863. return SymbolInfoTy(Addr, Name, Smc, SymbolIndex,
  864. isLabel(XCOFFObj, Symbol));
  865. } else
  866. return SymbolInfoTy(Addr, Name,
  867. Obj->isELF() ? getElfSymbolType(Obj, Symbol)
  868. : (uint8_t)ELF::STT_NOTYPE);
  869. }
  870. static SymbolInfoTy createDummySymbolInfo(const ObjectFile *Obj,
  871. const uint64_t Addr, StringRef &Name,
  872. uint8_t Type) {
  873. if (Obj->isXCOFF() && SymbolDescription)
  874. return SymbolInfoTy(Addr, Name, None, None, false);
  875. else
  876. return SymbolInfoTy(Addr, Name, Type);
  877. }
  878. static void
  879. collectLocalBranchTargets(ArrayRef<uint8_t> Bytes, const MCInstrAnalysis *MIA,
  880. MCDisassembler *DisAsm, MCInstPrinter *IP,
  881. const MCSubtargetInfo *STI, uint64_t SectionAddr,
  882. uint64_t Start, uint64_t End,
  883. std::unordered_map<uint64_t, std::string> &Labels) {
  884. // So far only supports PowerPC and X86.
  885. if (!STI->getTargetTriple().isPPC() && !STI->getTargetTriple().isX86())
  886. return;
  887. Labels.clear();
  888. unsigned LabelCount = 0;
  889. Start += SectionAddr;
  890. End += SectionAddr;
  891. uint64_t Index = Start;
  892. while (Index < End) {
  893. // Disassemble a real instruction and record function-local branch labels.
  894. MCInst Inst;
  895. uint64_t Size;
  896. bool Disassembled = DisAsm->getInstruction(
  897. Inst, Size, Bytes.slice(Index - SectionAddr), Index, nulls());
  898. if (Size == 0)
  899. Size = 1;
  900. if (Disassembled && MIA) {
  901. uint64_t Target;
  902. bool TargetKnown = MIA->evaluateBranch(Inst, Index, Size, Target);
  903. // On PowerPC, if the address of a branch is the same as the target, it
  904. // means that it's a function call. Do not mark the label for this case.
  905. if (TargetKnown && (Target >= Start && Target < End) &&
  906. !Labels.count(Target) &&
  907. !(STI->getTargetTriple().isPPC() && Target == Index))
  908. Labels[Target] = ("L" + Twine(LabelCount++)).str();
  909. }
  910. Index += Size;
  911. }
  912. }
  913. // Create an MCSymbolizer for the target and add it to the MCDisassembler.
  914. // This is currently only used on AMDGPU, and assumes the format of the
  915. // void * argument passed to AMDGPU's createMCSymbolizer.
  916. static void addSymbolizer(
  917. MCContext &Ctx, const Target *Target, StringRef TripleName,
  918. MCDisassembler *DisAsm, uint64_t SectionAddr, ArrayRef<uint8_t> Bytes,
  919. SectionSymbolsTy &Symbols,
  920. std::vector<std::unique_ptr<std::string>> &SynthesizedLabelNames) {
  921. std::unique_ptr<MCRelocationInfo> RelInfo(
  922. Target->createMCRelocationInfo(TripleName, Ctx));
  923. if (!RelInfo)
  924. return;
  925. std::unique_ptr<MCSymbolizer> Symbolizer(Target->createMCSymbolizer(
  926. TripleName, nullptr, nullptr, &Symbols, &Ctx, std::move(RelInfo)));
  927. MCSymbolizer *SymbolizerPtr = &*Symbolizer;
  928. DisAsm->setSymbolizer(std::move(Symbolizer));
  929. if (!SymbolizeOperands)
  930. return;
  931. // Synthesize labels referenced by branch instructions by
  932. // disassembling, discarding the output, and collecting the referenced
  933. // addresses from the symbolizer.
  934. for (size_t Index = 0; Index != Bytes.size();) {
  935. MCInst Inst;
  936. uint64_t Size;
  937. DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), SectionAddr + Index,
  938. nulls());
  939. if (Size == 0)
  940. Size = 1;
  941. Index += Size;
  942. }
  943. ArrayRef<uint64_t> LabelAddrsRef = SymbolizerPtr->getReferencedAddresses();
  944. // Copy and sort to remove duplicates.
  945. std::vector<uint64_t> LabelAddrs;
  946. LabelAddrs.insert(LabelAddrs.end(), LabelAddrsRef.begin(),
  947. LabelAddrsRef.end());
  948. llvm::sort(LabelAddrs);
  949. LabelAddrs.resize(std::unique(LabelAddrs.begin(), LabelAddrs.end()) -
  950. LabelAddrs.begin());
  951. // Add the labels.
  952. for (unsigned LabelNum = 0; LabelNum != LabelAddrs.size(); ++LabelNum) {
  953. auto Name = std::make_unique<std::string>();
  954. *Name = (Twine("L") + Twine(LabelNum)).str();
  955. SynthesizedLabelNames.push_back(std::move(Name));
  956. Symbols.push_back(SymbolInfoTy(
  957. LabelAddrs[LabelNum], *SynthesizedLabelNames.back(), ELF::STT_NOTYPE));
  958. }
  959. llvm::stable_sort(Symbols);
  960. // Recreate the symbolizer with the new symbols list.
  961. RelInfo.reset(Target->createMCRelocationInfo(TripleName, Ctx));
  962. Symbolizer.reset(Target->createMCSymbolizer(
  963. TripleName, nullptr, nullptr, &Symbols, &Ctx, std::move(RelInfo)));
  964. DisAsm->setSymbolizer(std::move(Symbolizer));
  965. }
  966. static StringRef getSegmentName(const MachOObjectFile *MachO,
  967. const SectionRef &Section) {
  968. if (MachO) {
  969. DataRefImpl DR = Section.getRawDataRefImpl();
  970. StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
  971. return SegmentName;
  972. }
  973. return "";
  974. }
  975. static void emitPostInstructionInfo(formatted_raw_ostream &FOS,
  976. const MCAsmInfo &MAI,
  977. const MCSubtargetInfo &STI,
  978. StringRef Comments,
  979. LiveVariablePrinter &LVP) {
  980. do {
  981. if (!Comments.empty()) {
  982. // Emit a line of comments.
  983. StringRef Comment;
  984. std::tie(Comment, Comments) = Comments.split('\n');
  985. // MAI.getCommentColumn() assumes that instructions are printed at the
  986. // position of 8, while getInstStartColumn() returns the actual position.
  987. unsigned CommentColumn =
  988. MAI.getCommentColumn() - 8 + getInstStartColumn(STI);
  989. FOS.PadToColumn(CommentColumn);
  990. FOS << MAI.getCommentString() << ' ' << Comment;
  991. }
  992. LVP.printAfterInst(FOS);
  993. FOS << '\n';
  994. } while (!Comments.empty());
  995. FOS.flush();
  996. }
  997. static void disassembleObject(const Target *TheTarget, const ObjectFile *Obj,
  998. MCContext &Ctx, MCDisassembler *PrimaryDisAsm,
  999. MCDisassembler *SecondaryDisAsm,
  1000. const MCInstrAnalysis *MIA, MCInstPrinter *IP,
  1001. const MCSubtargetInfo *PrimarySTI,
  1002. const MCSubtargetInfo *SecondarySTI,
  1003. PrettyPrinter &PIP,
  1004. SourcePrinter &SP, bool InlineRelocs) {
  1005. const MCSubtargetInfo *STI = PrimarySTI;
  1006. MCDisassembler *DisAsm = PrimaryDisAsm;
  1007. bool PrimaryIsThumb = false;
  1008. if (isArmElf(Obj))
  1009. PrimaryIsThumb = STI->checkFeatures("+thumb-mode");
  1010. std::map<SectionRef, std::vector<RelocationRef>> RelocMap;
  1011. if (InlineRelocs)
  1012. RelocMap = getRelocsMap(*Obj);
  1013. bool Is64Bits = Obj->getBytesInAddress() > 4;
  1014. // Create a mapping from virtual address to symbol name. This is used to
  1015. // pretty print the symbols while disassembling.
  1016. std::map<SectionRef, SectionSymbolsTy> AllSymbols;
  1017. SectionSymbolsTy AbsoluteSymbols;
  1018. const StringRef FileName = Obj->getFileName();
  1019. const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj);
  1020. for (const SymbolRef &Symbol : Obj->symbols()) {
  1021. Expected<StringRef> NameOrErr = Symbol.getName();
  1022. if (!NameOrErr) {
  1023. reportWarning(toString(NameOrErr.takeError()), FileName);
  1024. continue;
  1025. }
  1026. if (NameOrErr->empty() && !(Obj->isXCOFF() && SymbolDescription))
  1027. continue;
  1028. if (Obj->isELF() && getElfSymbolType(Obj, Symbol) == ELF::STT_SECTION)
  1029. continue;
  1030. if (MachO) {
  1031. // __mh_(execute|dylib|dylinker|bundle|preload|object)_header are special
  1032. // symbols that support MachO header introspection. They do not bind to
  1033. // code locations and are irrelevant for disassembly.
  1034. if (NameOrErr->startswith("__mh_") && NameOrErr->endswith("_header"))
  1035. continue;
  1036. // Don't ask a Mach-O STAB symbol for its section unless you know that
  1037. // STAB symbol's section field refers to a valid section index. Otherwise
  1038. // the symbol may error trying to load a section that does not exist.
  1039. DataRefImpl SymDRI = Symbol.getRawDataRefImpl();
  1040. uint8_t NType = (MachO->is64Bit() ?
  1041. MachO->getSymbol64TableEntry(SymDRI).n_type:
  1042. MachO->getSymbolTableEntry(SymDRI).n_type);
  1043. if (NType & MachO::N_STAB)
  1044. continue;
  1045. }
  1046. section_iterator SecI = unwrapOrError(Symbol.getSection(), FileName);
  1047. if (SecI != Obj->section_end())
  1048. AllSymbols[*SecI].push_back(createSymbolInfo(Obj, Symbol));
  1049. else
  1050. AbsoluteSymbols.push_back(createSymbolInfo(Obj, Symbol));
  1051. }
  1052. if (AllSymbols.empty() && Obj->isELF())
  1053. addDynamicElfSymbols(Obj, AllSymbols);
  1054. if (Obj->isWasm())
  1055. addMissingWasmCodeSymbols(cast<WasmObjectFile>(Obj), AllSymbols);
  1056. BumpPtrAllocator A;
  1057. StringSaver Saver(A);
  1058. addPltEntries(Obj, AllSymbols, Saver);
  1059. // Create a mapping from virtual address to section. An empty section can
  1060. // cause more than one section at the same address. Sort such sections to be
  1061. // before same-addressed non-empty sections so that symbol lookups prefer the
  1062. // non-empty section.
  1063. std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
  1064. for (SectionRef Sec : Obj->sections())
  1065. SectionAddresses.emplace_back(Sec.getAddress(), Sec);
  1066. llvm::stable_sort(SectionAddresses, [](const auto &LHS, const auto &RHS) {
  1067. if (LHS.first != RHS.first)
  1068. return LHS.first < RHS.first;
  1069. return LHS.second.getSize() < RHS.second.getSize();
  1070. });
  1071. // Linked executables (.exe and .dll files) typically don't include a real
  1072. // symbol table but they might contain an export table.
  1073. if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
  1074. for (const auto &ExportEntry : COFFObj->export_directories()) {
  1075. StringRef Name;
  1076. if (Error E = ExportEntry.getSymbolName(Name))
  1077. reportError(std::move(E), Obj->getFileName());
  1078. if (Name.empty())
  1079. continue;
  1080. uint32_t RVA;
  1081. if (Error E = ExportEntry.getExportRVA(RVA))
  1082. reportError(std::move(E), Obj->getFileName());
  1083. uint64_t VA = COFFObj->getImageBase() + RVA;
  1084. auto Sec = partition_point(
  1085. SectionAddresses, [VA](const std::pair<uint64_t, SectionRef> &O) {
  1086. return O.first <= VA;
  1087. });
  1088. if (Sec != SectionAddresses.begin()) {
  1089. --Sec;
  1090. AllSymbols[Sec->second].emplace_back(VA, Name, ELF::STT_NOTYPE);
  1091. } else
  1092. AbsoluteSymbols.emplace_back(VA, Name, ELF::STT_NOTYPE);
  1093. }
  1094. }
  1095. // Sort all the symbols, this allows us to use a simple binary search to find
  1096. // Multiple symbols can have the same address. Use a stable sort to stabilize
  1097. // the output.
  1098. StringSet<> FoundDisasmSymbolSet;
  1099. for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
  1100. llvm::stable_sort(SecSyms.second);
  1101. llvm::stable_sort(AbsoluteSymbols);
  1102. std::unique_ptr<DWARFContext> DICtx;
  1103. LiveVariablePrinter LVP(*Ctx.getRegisterInfo(), *STI);
  1104. if (DbgVariables != DVDisabled) {
  1105. DICtx = DWARFContext::create(*Obj);
  1106. for (const std::unique_ptr<DWARFUnit> &CU : DICtx->compile_units())
  1107. LVP.addCompileUnit(CU->getUnitDIE(false));
  1108. }
  1109. LLVM_DEBUG(LVP.dump());
  1110. for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
  1111. if (FilterSections.empty() && !DisassembleAll &&
  1112. (!Section.isText() || Section.isVirtual()))
  1113. continue;
  1114. uint64_t SectionAddr = Section.getAddress();
  1115. uint64_t SectSize = Section.getSize();
  1116. if (!SectSize)
  1117. continue;
  1118. // Get the list of all the symbols in this section.
  1119. SectionSymbolsTy &Symbols = AllSymbols[Section];
  1120. std::vector<MappingSymbolPair> MappingSymbols;
  1121. if (hasMappingSymbols(Obj)) {
  1122. for (const auto &Symb : Symbols) {
  1123. uint64_t Address = Symb.Addr;
  1124. StringRef Name = Symb.Name;
  1125. if (Name.startswith("$d"))
  1126. MappingSymbols.emplace_back(Address - SectionAddr, 'd');
  1127. if (Name.startswith("$x"))
  1128. MappingSymbols.emplace_back(Address - SectionAddr, 'x');
  1129. if (Name.startswith("$a"))
  1130. MappingSymbols.emplace_back(Address - SectionAddr, 'a');
  1131. if (Name.startswith("$t"))
  1132. MappingSymbols.emplace_back(Address - SectionAddr, 't');
  1133. }
  1134. }
  1135. llvm::sort(MappingSymbols);
  1136. ArrayRef<uint8_t> Bytes = arrayRefFromStringRef(
  1137. unwrapOrError(Section.getContents(), Obj->getFileName()));
  1138. std::vector<std::unique_ptr<std::string>> SynthesizedLabelNames;
  1139. if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
  1140. // AMDGPU disassembler uses symbolizer for printing labels
  1141. addSymbolizer(Ctx, TheTarget, TripleName, DisAsm, SectionAddr, Bytes,
  1142. Symbols, SynthesizedLabelNames);
  1143. }
  1144. StringRef SegmentName = getSegmentName(MachO, Section);
  1145. StringRef SectionName = unwrapOrError(Section.getName(), Obj->getFileName());
  1146. // If the section has no symbol at the start, just insert a dummy one.
  1147. if (Symbols.empty() || Symbols[0].Addr != 0) {
  1148. Symbols.insert(Symbols.begin(),
  1149. createDummySymbolInfo(Obj, SectionAddr, SectionName,
  1150. Section.isText() ? ELF::STT_FUNC
  1151. : ELF::STT_OBJECT));
  1152. }
  1153. SmallString<40> Comments;
  1154. raw_svector_ostream CommentStream(Comments);
  1155. uint64_t VMAAdjustment = 0;
  1156. if (shouldAdjustVA(Section))
  1157. VMAAdjustment = AdjustVMA;
  1158. // In executable and shared objects, r_offset holds a virtual address.
  1159. // Subtract SectionAddr from the r_offset field of a relocation to get
  1160. // the section offset.
  1161. uint64_t RelAdjustment = Obj->isRelocatableObject() ? 0 : SectionAddr;
  1162. uint64_t Size;
  1163. uint64_t Index;
  1164. bool PrintedSection = false;
  1165. std::vector<RelocationRef> Rels = RelocMap[Section];
  1166. std::vector<RelocationRef>::const_iterator RelCur = Rels.begin();
  1167. std::vector<RelocationRef>::const_iterator RelEnd = Rels.end();
  1168. // Disassemble symbol by symbol.
  1169. for (unsigned SI = 0, SE = Symbols.size(); SI != SE; ++SI) {
  1170. std::string SymbolName = Symbols[SI].Name.str();
  1171. if (Demangle)
  1172. SymbolName = demangle(SymbolName);
  1173. // Skip if --disassemble-symbols is not empty and the symbol is not in
  1174. // the list.
  1175. if (!DisasmSymbolSet.empty() && !DisasmSymbolSet.count(SymbolName))
  1176. continue;
  1177. uint64_t Start = Symbols[SI].Addr;
  1178. if (Start < SectionAddr || StopAddress <= Start)
  1179. continue;
  1180. else
  1181. FoundDisasmSymbolSet.insert(SymbolName);
  1182. // The end is the section end, the beginning of the next symbol, or
  1183. // --stop-address.
  1184. uint64_t End = std::min<uint64_t>(SectionAddr + SectSize, StopAddress);
  1185. if (SI + 1 < SE)
  1186. End = std::min(End, Symbols[SI + 1].Addr);
  1187. if (Start >= End || End <= StartAddress)
  1188. continue;
  1189. Start -= SectionAddr;
  1190. End -= SectionAddr;
  1191. if (!PrintedSection) {
  1192. PrintedSection = true;
  1193. outs() << "\nDisassembly of section ";
  1194. if (!SegmentName.empty())
  1195. outs() << SegmentName << ",";
  1196. outs() << SectionName << ":\n";
  1197. }
  1198. outs() << '\n';
  1199. if (LeadingAddr)
  1200. outs() << format(Is64Bits ? "%016" PRIx64 " " : "%08" PRIx64 " ",
  1201. SectionAddr + Start + VMAAdjustment);
  1202. if (Obj->isXCOFF() && SymbolDescription) {
  1203. outs() << getXCOFFSymbolDescription(Symbols[SI], SymbolName) << ":\n";
  1204. } else
  1205. outs() << '<' << SymbolName << ">:\n";
  1206. // Don't print raw contents of a virtual section. A virtual section
  1207. // doesn't have any contents in the file.
  1208. if (Section.isVirtual()) {
  1209. outs() << "...\n";
  1210. continue;
  1211. }
  1212. auto Status = DisAsm->onSymbolStart(Symbols[SI], Size,
  1213. Bytes.slice(Start, End - Start),
  1214. SectionAddr + Start, CommentStream);
  1215. // To have round trippable disassembly, we fall back to decoding the
  1216. // remaining bytes as instructions.
  1217. //
  1218. // If there is a failure, we disassemble the failed region as bytes before
  1219. // falling back. The target is expected to print nothing in this case.
  1220. //
  1221. // If there is Success or SoftFail i.e no 'real' failure, we go ahead by
  1222. // Size bytes before falling back.
  1223. // So if the entire symbol is 'eaten' by the target:
  1224. // Start += Size // Now Start = End and we will never decode as
  1225. // // instructions
  1226. //
  1227. // Right now, most targets return None i.e ignore to treat a symbol
  1228. // separately. But WebAssembly decodes preludes for some symbols.
  1229. //
  1230. if (Status.hasValue()) {
  1231. if (Status.getValue() == MCDisassembler::Fail) {
  1232. outs() << "// Error in decoding " << SymbolName
  1233. << " : Decoding failed region as bytes.\n";
  1234. for (uint64_t I = 0; I < Size; ++I) {
  1235. outs() << "\t.byte\t " << format_hex(Bytes[I], 1, /*Upper=*/true)
  1236. << "\n";
  1237. }
  1238. }
  1239. } else {
  1240. Size = 0;
  1241. }
  1242. Start += Size;
  1243. Index = Start;
  1244. if (SectionAddr < StartAddress)
  1245. Index = std::max<uint64_t>(Index, StartAddress - SectionAddr);
  1246. // If there is a data/common symbol inside an ELF text section and we are
  1247. // only disassembling text (applicable all architectures), we are in a
  1248. // situation where we must print the data and not disassemble it.
  1249. if (Obj->isELF() && !DisassembleAll && Section.isText()) {
  1250. uint8_t SymTy = Symbols[SI].Type;
  1251. if (SymTy == ELF::STT_OBJECT || SymTy == ELF::STT_COMMON) {
  1252. dumpELFData(SectionAddr, Index, End, Bytes);
  1253. Index = End;
  1254. }
  1255. }
  1256. bool CheckARMELFData = hasMappingSymbols(Obj) &&
  1257. Symbols[SI].Type != ELF::STT_OBJECT &&
  1258. !DisassembleAll;
  1259. bool DumpARMELFData = false;
  1260. formatted_raw_ostream FOS(outs());
  1261. std::unordered_map<uint64_t, std::string> AllLabels;
  1262. if (SymbolizeOperands)
  1263. collectLocalBranchTargets(Bytes, MIA, DisAsm, IP, PrimarySTI,
  1264. SectionAddr, Index, End, AllLabels);
  1265. while (Index < End) {
  1266. // ARM and AArch64 ELF binaries can interleave data and text in the
  1267. // same section. We rely on the markers introduced to understand what
  1268. // we need to dump. If the data marker is within a function, it is
  1269. // denoted as a word/short etc.
  1270. if (CheckARMELFData) {
  1271. char Kind = getMappingSymbolKind(MappingSymbols, Index);
  1272. DumpARMELFData = Kind == 'd';
  1273. if (SecondarySTI) {
  1274. if (Kind == 'a') {
  1275. STI = PrimaryIsThumb ? SecondarySTI : PrimarySTI;
  1276. DisAsm = PrimaryIsThumb ? SecondaryDisAsm : PrimaryDisAsm;
  1277. } else if (Kind == 't') {
  1278. STI = PrimaryIsThumb ? PrimarySTI : SecondarySTI;
  1279. DisAsm = PrimaryIsThumb ? PrimaryDisAsm : SecondaryDisAsm;
  1280. }
  1281. }
  1282. }
  1283. if (DumpARMELFData) {
  1284. Size = dumpARMELFData(SectionAddr, Index, End, Obj, Bytes,
  1285. MappingSymbols, FOS);
  1286. } else {
  1287. // When -z or --disassemble-zeroes are given we always dissasemble
  1288. // them. Otherwise we might want to skip zero bytes we see.
  1289. if (!DisassembleZeroes) {
  1290. uint64_t MaxOffset = End - Index;
  1291. // For --reloc: print zero blocks patched by relocations, so that
  1292. // relocations can be shown in the dump.
  1293. if (RelCur != RelEnd)
  1294. MaxOffset = std::min(RelCur->getOffset() - RelAdjustment - Index,
  1295. MaxOffset);
  1296. if (size_t N =
  1297. countSkippableZeroBytes(Bytes.slice(Index, MaxOffset))) {
  1298. FOS << "\t\t..." << '\n';
  1299. Index += N;
  1300. continue;
  1301. }
  1302. }
  1303. // Print local label if there's any.
  1304. auto Iter = AllLabels.find(SectionAddr + Index);
  1305. if (Iter != AllLabels.end())
  1306. FOS << "<" << Iter->second << ">:\n";
  1307. // Disassemble a real instruction or a data when disassemble all is
  1308. // provided
  1309. MCInst Inst;
  1310. bool Disassembled =
  1311. DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
  1312. SectionAddr + Index, CommentStream);
  1313. if (Size == 0)
  1314. Size = 1;
  1315. LVP.update({Index, Section.getIndex()},
  1316. {Index + Size, Section.getIndex()}, Index + Size != End);
  1317. IP->setCommentStream(CommentStream);
  1318. PIP.printInst(
  1319. *IP, Disassembled ? &Inst : nullptr, Bytes.slice(Index, Size),
  1320. {SectionAddr + Index + VMAAdjustment, Section.getIndex()}, FOS,
  1321. "", *STI, &SP, Obj->getFileName(), &Rels, LVP);
  1322. IP->setCommentStream(llvm::nulls());
  1323. // If disassembly has failed, avoid analysing invalid/incomplete
  1324. // instruction information. Otherwise, try to resolve the target
  1325. // address (jump target or memory operand address) and print it on the
  1326. // right of the instruction.
  1327. if (Disassembled && MIA) {
  1328. // Branch targets are printed just after the instructions.
  1329. llvm::raw_ostream *TargetOS = &FOS;
  1330. uint64_t Target;
  1331. bool PrintTarget =
  1332. MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target);
  1333. if (!PrintTarget)
  1334. if (Optional<uint64_t> MaybeTarget =
  1335. MIA->evaluateMemoryOperandAddress(
  1336. Inst, STI, SectionAddr + Index, Size)) {
  1337. Target = *MaybeTarget;
  1338. PrintTarget = true;
  1339. // Do not print real address when symbolizing.
  1340. if (!SymbolizeOperands) {
  1341. // Memory operand addresses are printed as comments.
  1342. TargetOS = &CommentStream;
  1343. *TargetOS << "0x" << Twine::utohexstr(Target);
  1344. }
  1345. }
  1346. if (PrintTarget) {
  1347. // In a relocatable object, the target's section must reside in
  1348. // the same section as the call instruction or it is accessed
  1349. // through a relocation.
  1350. //
  1351. // In a non-relocatable object, the target may be in any section.
  1352. // In that case, locate the section(s) containing the target
  1353. // address and find the symbol in one of those, if possible.
  1354. //
  1355. // N.B. We don't walk the relocations in the relocatable case yet.
  1356. std::vector<const SectionSymbolsTy *> TargetSectionSymbols;
  1357. if (!Obj->isRelocatableObject()) {
  1358. auto It = llvm::partition_point(
  1359. SectionAddresses,
  1360. [=](const std::pair<uint64_t, SectionRef> &O) {
  1361. return O.first <= Target;
  1362. });
  1363. uint64_t TargetSecAddr = 0;
  1364. while (It != SectionAddresses.begin()) {
  1365. --It;
  1366. if (TargetSecAddr == 0)
  1367. TargetSecAddr = It->first;
  1368. if (It->first != TargetSecAddr)
  1369. break;
  1370. TargetSectionSymbols.push_back(&AllSymbols[It->second]);
  1371. }
  1372. } else {
  1373. TargetSectionSymbols.push_back(&Symbols);
  1374. }
  1375. TargetSectionSymbols.push_back(&AbsoluteSymbols);
  1376. // Find the last symbol in the first candidate section whose
  1377. // offset is less than or equal to the target. If there are no
  1378. // such symbols, try in the next section and so on, before finally
  1379. // using the nearest preceding absolute symbol (if any), if there
  1380. // are no other valid symbols.
  1381. const SymbolInfoTy *TargetSym = nullptr;
  1382. for (const SectionSymbolsTy *TargetSymbols :
  1383. TargetSectionSymbols) {
  1384. auto It = llvm::partition_point(
  1385. *TargetSymbols,
  1386. [=](const SymbolInfoTy &O) { return O.Addr <= Target; });
  1387. if (It != TargetSymbols->begin()) {
  1388. TargetSym = &*(It - 1);
  1389. break;
  1390. }
  1391. }
  1392. // Print the labels corresponding to the target if there's any.
  1393. bool LabelAvailable = AllLabels.count(Target);
  1394. if (TargetSym != nullptr) {
  1395. uint64_t TargetAddress = TargetSym->Addr;
  1396. uint64_t Disp = Target - TargetAddress;
  1397. std::string TargetName = TargetSym->Name.str();
  1398. if (Demangle)
  1399. TargetName = demangle(TargetName);
  1400. *TargetOS << " <";
  1401. if (!Disp) {
  1402. // Always Print the binary symbol precisely corresponding to
  1403. // the target address.
  1404. *TargetOS << TargetName;
  1405. } else if (!LabelAvailable) {
  1406. // Always Print the binary symbol plus an offset if there's no
  1407. // local label corresponding to the target address.
  1408. *TargetOS << TargetName << "+0x" << Twine::utohexstr(Disp);
  1409. } else {
  1410. *TargetOS << AllLabels[Target];
  1411. }
  1412. *TargetOS << ">";
  1413. } else if (LabelAvailable) {
  1414. *TargetOS << " <" << AllLabels[Target] << ">";
  1415. }
  1416. // By convention, each record in the comment stream should be
  1417. // terminated.
  1418. if (TargetOS == &CommentStream)
  1419. *TargetOS << "\n";
  1420. }
  1421. }
  1422. }
  1423. assert(Ctx.getAsmInfo());
  1424. emitPostInstructionInfo(FOS, *Ctx.getAsmInfo(), *STI,
  1425. CommentStream.str(), LVP);
  1426. Comments.clear();
  1427. // Hexagon does this in pretty printer
  1428. if (Obj->getArch() != Triple::hexagon) {
  1429. // Print relocation for instruction and data.
  1430. while (RelCur != RelEnd) {
  1431. uint64_t Offset = RelCur->getOffset() - RelAdjustment;
  1432. // If this relocation is hidden, skip it.
  1433. if (getHidden(*RelCur) || SectionAddr + Offset < StartAddress) {
  1434. ++RelCur;
  1435. continue;
  1436. }
  1437. // Stop when RelCur's offset is past the disassembled
  1438. // instruction/data. Note that it's possible the disassembled data
  1439. // is not the complete data: we might see the relocation printed in
  1440. // the middle of the data, but this matches the binutils objdump
  1441. // output.
  1442. if (Offset >= Index + Size)
  1443. break;
  1444. // When --adjust-vma is used, update the address printed.
  1445. if (RelCur->getSymbol() != Obj->symbol_end()) {
  1446. Expected<section_iterator> SymSI =
  1447. RelCur->getSymbol()->getSection();
  1448. if (SymSI && *SymSI != Obj->section_end() &&
  1449. shouldAdjustVA(**SymSI))
  1450. Offset += AdjustVMA;
  1451. }
  1452. printRelocation(FOS, Obj->getFileName(), *RelCur,
  1453. SectionAddr + Offset, Is64Bits);
  1454. LVP.printAfterOtherLine(FOS, true);
  1455. ++RelCur;
  1456. }
  1457. }
  1458. Index += Size;
  1459. }
  1460. }
  1461. }
  1462. StringSet<> MissingDisasmSymbolSet =
  1463. set_difference(DisasmSymbolSet, FoundDisasmSymbolSet);
  1464. for (StringRef Sym : MissingDisasmSymbolSet.keys())
  1465. reportWarning("failed to disassemble missing symbol " + Sym, FileName);
  1466. }
  1467. static void disassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
  1468. const Target *TheTarget = getTarget(Obj);
  1469. // Package up features to be passed to target/subtarget
  1470. SubtargetFeatures Features = Obj->getFeatures();
  1471. if (!MAttrs.empty())
  1472. for (unsigned I = 0; I != MAttrs.size(); ++I)
  1473. Features.AddFeature(MAttrs[I]);
  1474. std::unique_ptr<const MCRegisterInfo> MRI(
  1475. TheTarget->createMCRegInfo(TripleName));
  1476. if (!MRI)
  1477. reportError(Obj->getFileName(),
  1478. "no register info for target " + TripleName);
  1479. // Set up disassembler.
  1480. MCTargetOptions MCOptions;
  1481. std::unique_ptr<const MCAsmInfo> AsmInfo(
  1482. TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions));
  1483. if (!AsmInfo)
  1484. reportError(Obj->getFileName(),
  1485. "no assembly info for target " + TripleName);
  1486. if (MCPU.empty())
  1487. MCPU = Obj->tryGetCPUName().getValueOr("").str();
  1488. std::unique_ptr<const MCSubtargetInfo> STI(
  1489. TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString()));
  1490. if (!STI)
  1491. reportError(Obj->getFileName(),
  1492. "no subtarget info for target " + TripleName);
  1493. std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
  1494. if (!MII)
  1495. reportError(Obj->getFileName(),
  1496. "no instruction info for target " + TripleName);
  1497. MCContext Ctx(Triple(TripleName), AsmInfo.get(), MRI.get(), STI.get());
  1498. // FIXME: for now initialize MCObjectFileInfo with default values
  1499. std::unique_ptr<MCObjectFileInfo> MOFI(
  1500. TheTarget->createMCObjectFileInfo(Ctx, /*PIC=*/false));
  1501. Ctx.setObjectFileInfo(MOFI.get());
  1502. std::unique_ptr<MCDisassembler> DisAsm(
  1503. TheTarget->createMCDisassembler(*STI, Ctx));
  1504. if (!DisAsm)
  1505. reportError(Obj->getFileName(), "no disassembler for target " + TripleName);
  1506. // If we have an ARM object file, we need a second disassembler, because
  1507. // ARM CPUs have two different instruction sets: ARM mode, and Thumb mode.
  1508. // We use mapping symbols to switch between the two assemblers, where
  1509. // appropriate.
  1510. std::unique_ptr<MCDisassembler> SecondaryDisAsm;
  1511. std::unique_ptr<const MCSubtargetInfo> SecondarySTI;
  1512. if (isArmElf(Obj) && !STI->checkFeatures("+mclass")) {
  1513. if (STI->checkFeatures("+thumb-mode"))
  1514. Features.AddFeature("-thumb-mode");
  1515. else
  1516. Features.AddFeature("+thumb-mode");
  1517. SecondarySTI.reset(TheTarget->createMCSubtargetInfo(TripleName, MCPU,
  1518. Features.getString()));
  1519. SecondaryDisAsm.reset(TheTarget->createMCDisassembler(*SecondarySTI, Ctx));
  1520. }
  1521. std::unique_ptr<const MCInstrAnalysis> MIA(
  1522. TheTarget->createMCInstrAnalysis(MII.get()));
  1523. int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
  1524. std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
  1525. Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
  1526. if (!IP)
  1527. reportError(Obj->getFileName(),
  1528. "no instruction printer for target " + TripleName);
  1529. IP->setPrintImmHex(PrintImmHex);
  1530. IP->setPrintBranchImmAsAddress(true);
  1531. IP->setSymbolizeOperands(SymbolizeOperands);
  1532. IP->setMCInstrAnalysis(MIA.get());
  1533. PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
  1534. SourcePrinter SP(Obj, TheTarget->getName());
  1535. for (StringRef Opt : DisassemblerOptions)
  1536. if (!IP->applyTargetSpecificCLOption(Opt))
  1537. reportError(Obj->getFileName(),
  1538. "Unrecognized disassembler option: " + Opt);
  1539. disassembleObject(TheTarget, Obj, Ctx, DisAsm.get(), SecondaryDisAsm.get(),
  1540. MIA.get(), IP.get(), STI.get(), SecondarySTI.get(), PIP,
  1541. SP, InlineRelocs);
  1542. }
  1543. void objdump::printRelocations(const ObjectFile *Obj) {
  1544. StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
  1545. "%08" PRIx64;
  1546. // Regular objdump doesn't print relocations in non-relocatable object
  1547. // files.
  1548. if (!Obj->isRelocatableObject())
  1549. return;
  1550. // Build a mapping from relocation target to a vector of relocation
  1551. // sections. Usually, there is an only one relocation section for
  1552. // each relocated section.
  1553. MapVector<SectionRef, std::vector<SectionRef>> SecToRelSec;
  1554. uint64_t Ndx;
  1555. for (const SectionRef &Section : ToolSectionFilter(*Obj, &Ndx)) {
  1556. if (Section.relocation_begin() == Section.relocation_end())
  1557. continue;
  1558. Expected<section_iterator> SecOrErr = Section.getRelocatedSection();
  1559. if (!SecOrErr)
  1560. reportError(Obj->getFileName(),
  1561. "section (" + Twine(Ndx) +
  1562. "): unable to get a relocation target: " +
  1563. toString(SecOrErr.takeError()));
  1564. SecToRelSec[**SecOrErr].push_back(Section);
  1565. }
  1566. for (std::pair<SectionRef, std::vector<SectionRef>> &P : SecToRelSec) {
  1567. StringRef SecName = unwrapOrError(P.first.getName(), Obj->getFileName());
  1568. outs() << "\nRELOCATION RECORDS FOR [" << SecName << "]:\n";
  1569. uint32_t OffsetPadding = (Obj->getBytesInAddress() > 4 ? 16 : 8);
  1570. uint32_t TypePadding = 24;
  1571. outs() << left_justify("OFFSET", OffsetPadding) << " "
  1572. << left_justify("TYPE", TypePadding) << " "
  1573. << "VALUE\n";
  1574. for (SectionRef Section : P.second) {
  1575. for (const RelocationRef &Reloc : Section.relocations()) {
  1576. uint64_t Address = Reloc.getOffset();
  1577. SmallString<32> RelocName;
  1578. SmallString<32> ValueStr;
  1579. if (Address < StartAddress || Address > StopAddress || getHidden(Reloc))
  1580. continue;
  1581. Reloc.getTypeName(RelocName);
  1582. if (Error E = getRelocationValueString(Reloc, ValueStr))
  1583. reportError(std::move(E), Obj->getFileName());
  1584. outs() << format(Fmt.data(), Address) << " "
  1585. << left_justify(RelocName, TypePadding) << " " << ValueStr
  1586. << "\n";
  1587. }
  1588. }
  1589. }
  1590. }
  1591. void objdump::printDynamicRelocations(const ObjectFile *Obj) {
  1592. // For the moment, this option is for ELF only
  1593. if (!Obj->isELF())
  1594. return;
  1595. const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj);
  1596. if (!Elf || !any_of(Elf->sections(), [](const ELFSectionRef Sec) {
  1597. return Sec.getType() == ELF::SHT_DYNAMIC;
  1598. })) {
  1599. reportError(Obj->getFileName(), "not a dynamic object");
  1600. return;
  1601. }
  1602. std::vector<SectionRef> DynRelSec = Obj->dynamic_relocation_sections();
  1603. if (DynRelSec.empty())
  1604. return;
  1605. outs() << "\nDYNAMIC RELOCATION RECORDS\n";
  1606. const uint32_t OffsetPadding = (Obj->getBytesInAddress() > 4 ? 16 : 8);
  1607. const uint32_t TypePadding = 24;
  1608. outs() << left_justify("OFFSET", OffsetPadding) << ' '
  1609. << left_justify("TYPE", TypePadding) << " VALUE\n";
  1610. StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
  1611. for (const SectionRef &Section : DynRelSec)
  1612. for (const RelocationRef &Reloc : Section.relocations()) {
  1613. uint64_t Address = Reloc.getOffset();
  1614. SmallString<32> RelocName;
  1615. SmallString<32> ValueStr;
  1616. Reloc.getTypeName(RelocName);
  1617. if (Error E = getRelocationValueString(Reloc, ValueStr))
  1618. reportError(std::move(E), Obj->getFileName());
  1619. outs() << format(Fmt.data(), Address) << ' '
  1620. << left_justify(RelocName, TypePadding) << ' ' << ValueStr << '\n';
  1621. }
  1622. }
  1623. // Returns true if we need to show LMA column when dumping section headers. We
  1624. // show it only when the platform is ELF and either we have at least one section
  1625. // whose VMA and LMA are different and/or when --show-lma flag is used.
  1626. static bool shouldDisplayLMA(const ObjectFile *Obj) {
  1627. if (!Obj->isELF())
  1628. return false;
  1629. for (const SectionRef &S : ToolSectionFilter(*Obj))
  1630. if (S.getAddress() != getELFSectionLMA(S))
  1631. return true;
  1632. return ShowLMA;
  1633. }
  1634. static size_t getMaxSectionNameWidth(const ObjectFile *Obj) {
  1635. // Default column width for names is 13 even if no names are that long.
  1636. size_t MaxWidth = 13;
  1637. for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
  1638. StringRef Name = unwrapOrError(Section.getName(), Obj->getFileName());
  1639. MaxWidth = std::max(MaxWidth, Name.size());
  1640. }
  1641. return MaxWidth;
  1642. }
  1643. void objdump::printSectionHeaders(const ObjectFile *Obj) {
  1644. size_t NameWidth = getMaxSectionNameWidth(Obj);
  1645. size_t AddressWidth = 2 * Obj->getBytesInAddress();
  1646. bool HasLMAColumn = shouldDisplayLMA(Obj);
  1647. outs() << "\nSections:\n";
  1648. if (HasLMAColumn)
  1649. outs() << "Idx " << left_justify("Name", NameWidth) << " Size "
  1650. << left_justify("VMA", AddressWidth) << " "
  1651. << left_justify("LMA", AddressWidth) << " Type\n";
  1652. else
  1653. outs() << "Idx " << left_justify("Name", NameWidth) << " Size "
  1654. << left_justify("VMA", AddressWidth) << " Type\n";
  1655. uint64_t Idx;
  1656. for (const SectionRef &Section : ToolSectionFilter(*Obj, &Idx)) {
  1657. StringRef Name = unwrapOrError(Section.getName(), Obj->getFileName());
  1658. uint64_t VMA = Section.getAddress();
  1659. if (shouldAdjustVA(Section))
  1660. VMA += AdjustVMA;
  1661. uint64_t Size = Section.getSize();
  1662. std::string Type = Section.isText() ? "TEXT" : "";
  1663. if (Section.isData())
  1664. Type += Type.empty() ? "DATA" : ", DATA";
  1665. if (Section.isBSS())
  1666. Type += Type.empty() ? "BSS" : ", BSS";
  1667. if (Section.isDebugSection())
  1668. Type += Type.empty() ? "DEBUG" : ", DEBUG";
  1669. if (HasLMAColumn)
  1670. outs() << format("%3" PRIu64 " %-*s %08" PRIx64 " ", Idx, NameWidth,
  1671. Name.str().c_str(), Size)
  1672. << format_hex_no_prefix(VMA, AddressWidth) << " "
  1673. << format_hex_no_prefix(getELFSectionLMA(Section), AddressWidth)
  1674. << " " << Type << "\n";
  1675. else
  1676. outs() << format("%3" PRIu64 " %-*s %08" PRIx64 " ", Idx, NameWidth,
  1677. Name.str().c_str(), Size)
  1678. << format_hex_no_prefix(VMA, AddressWidth) << " " << Type << "\n";
  1679. }
  1680. }
  1681. void objdump::printSectionContents(const ObjectFile *Obj) {
  1682. const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj);
  1683. for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
  1684. StringRef Name = unwrapOrError(Section.getName(), Obj->getFileName());
  1685. uint64_t BaseAddr = Section.getAddress();
  1686. uint64_t Size = Section.getSize();
  1687. if (!Size)
  1688. continue;
  1689. outs() << "Contents of section ";
  1690. StringRef SegmentName = getSegmentName(MachO, Section);
  1691. if (!SegmentName.empty())
  1692. outs() << SegmentName << ",";
  1693. outs() << Name << ":\n";
  1694. if (Section.isBSS()) {
  1695. outs() << format("<skipping contents of bss section at [%04" PRIx64
  1696. ", %04" PRIx64 ")>\n",
  1697. BaseAddr, BaseAddr + Size);
  1698. continue;
  1699. }
  1700. StringRef Contents = unwrapOrError(Section.getContents(), Obj->getFileName());
  1701. // Dump out the content as hex and printable ascii characters.
  1702. for (std::size_t Addr = 0, End = Contents.size(); Addr < End; Addr += 16) {
  1703. outs() << format(" %04" PRIx64 " ", BaseAddr + Addr);
  1704. // Dump line of hex.
  1705. for (std::size_t I = 0; I < 16; ++I) {
  1706. if (I != 0 && I % 4 == 0)
  1707. outs() << ' ';
  1708. if (Addr + I < End)
  1709. outs() << hexdigit((Contents[Addr + I] >> 4) & 0xF, true)
  1710. << hexdigit(Contents[Addr + I] & 0xF, true);
  1711. else
  1712. outs() << " ";
  1713. }
  1714. // Print ascii.
  1715. outs() << " ";
  1716. for (std::size_t I = 0; I < 16 && Addr + I < End; ++I) {
  1717. if (isPrint(static_cast<unsigned char>(Contents[Addr + I]) & 0xFF))
  1718. outs() << Contents[Addr + I];
  1719. else
  1720. outs() << ".";
  1721. }
  1722. outs() << "\n";
  1723. }
  1724. }
  1725. }
  1726. void objdump::printSymbolTable(const ObjectFile *O, StringRef ArchiveName,
  1727. StringRef ArchitectureName, bool DumpDynamic) {
  1728. if (O->isCOFF() && !DumpDynamic) {
  1729. outs() << "\nSYMBOL TABLE:\n";
  1730. printCOFFSymbolTable(cast<const COFFObjectFile>(O));
  1731. return;
  1732. }
  1733. const StringRef FileName = O->getFileName();
  1734. if (!DumpDynamic) {
  1735. outs() << "\nSYMBOL TABLE:\n";
  1736. for (auto I = O->symbol_begin(); I != O->symbol_end(); ++I)
  1737. printSymbol(O, *I, {}, FileName, ArchiveName, ArchitectureName,
  1738. DumpDynamic);
  1739. return;
  1740. }
  1741. outs() << "\nDYNAMIC SYMBOL TABLE:\n";
  1742. if (!O->isELF()) {
  1743. reportWarning(
  1744. "this operation is not currently supported for this file format",
  1745. FileName);
  1746. return;
  1747. }
  1748. const ELFObjectFileBase *ELF = cast<const ELFObjectFileBase>(O);
  1749. auto Symbols = ELF->getDynamicSymbolIterators();
  1750. Expected<std::vector<VersionEntry>> SymbolVersionsOrErr =
  1751. ELF->readDynsymVersions();
  1752. if (!SymbolVersionsOrErr) {
  1753. reportWarning(toString(SymbolVersionsOrErr.takeError()), FileName);
  1754. SymbolVersionsOrErr = std::vector<VersionEntry>();
  1755. (void)!SymbolVersionsOrErr;
  1756. }
  1757. for (auto &Sym : Symbols)
  1758. printSymbol(O, Sym, *SymbolVersionsOrErr, FileName, ArchiveName,
  1759. ArchitectureName, DumpDynamic);
  1760. }
  1761. void objdump::printSymbol(const ObjectFile *O, const SymbolRef &Symbol,
  1762. ArrayRef<VersionEntry> SymbolVersions,
  1763. StringRef FileName, StringRef ArchiveName,
  1764. StringRef ArchitectureName, bool DumpDynamic) {
  1765. const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(O);
  1766. uint64_t Address = unwrapOrError(Symbol.getAddress(), FileName, ArchiveName,
  1767. ArchitectureName);
  1768. if ((Address < StartAddress) || (Address > StopAddress))
  1769. return;
  1770. SymbolRef::Type Type =
  1771. unwrapOrError(Symbol.getType(), FileName, ArchiveName, ArchitectureName);
  1772. uint32_t Flags =
  1773. unwrapOrError(Symbol.getFlags(), FileName, ArchiveName, ArchitectureName);
  1774. // Don't ask a Mach-O STAB symbol for its section unless you know that
  1775. // STAB symbol's section field refers to a valid section index. Otherwise
  1776. // the symbol may error trying to load a section that does not exist.
  1777. bool IsSTAB = false;
  1778. if (MachO) {
  1779. DataRefImpl SymDRI = Symbol.getRawDataRefImpl();
  1780. uint8_t NType =
  1781. (MachO->is64Bit() ? MachO->getSymbol64TableEntry(SymDRI).n_type
  1782. : MachO->getSymbolTableEntry(SymDRI).n_type);
  1783. if (NType & MachO::N_STAB)
  1784. IsSTAB = true;
  1785. }
  1786. section_iterator Section = IsSTAB
  1787. ? O->section_end()
  1788. : unwrapOrError(Symbol.getSection(), FileName,
  1789. ArchiveName, ArchitectureName);
  1790. StringRef Name;
  1791. if (Type == SymbolRef::ST_Debug && Section != O->section_end()) {
  1792. if (Expected<StringRef> NameOrErr = Section->getName())
  1793. Name = *NameOrErr;
  1794. else
  1795. consumeError(NameOrErr.takeError());
  1796. } else {
  1797. Name = unwrapOrError(Symbol.getName(), FileName, ArchiveName,
  1798. ArchitectureName);
  1799. }
  1800. bool Global = Flags & SymbolRef::SF_Global;
  1801. bool Weak = Flags & SymbolRef::SF_Weak;
  1802. bool Absolute = Flags & SymbolRef::SF_Absolute;
  1803. bool Common = Flags & SymbolRef::SF_Common;
  1804. bool Hidden = Flags & SymbolRef::SF_Hidden;
  1805. char GlobLoc = ' ';
  1806. if ((Section != O->section_end() || Absolute) && !Weak)
  1807. GlobLoc = Global ? 'g' : 'l';
  1808. char IFunc = ' ';
  1809. if (O->isELF()) {
  1810. if (ELFSymbolRef(Symbol).getELFType() == ELF::STT_GNU_IFUNC)
  1811. IFunc = 'i';
  1812. if (ELFSymbolRef(Symbol).getBinding() == ELF::STB_GNU_UNIQUE)
  1813. GlobLoc = 'u';
  1814. }
  1815. char Debug = ' ';
  1816. if (DumpDynamic)
  1817. Debug = 'D';
  1818. else if (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
  1819. Debug = 'd';
  1820. char FileFunc = ' ';
  1821. if (Type == SymbolRef::ST_File)
  1822. FileFunc = 'f';
  1823. else if (Type == SymbolRef::ST_Function)
  1824. FileFunc = 'F';
  1825. else if (Type == SymbolRef::ST_Data)
  1826. FileFunc = 'O';
  1827. const char *Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
  1828. outs() << format(Fmt, Address) << " "
  1829. << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
  1830. << (Weak ? 'w' : ' ') // Weak?
  1831. << ' ' // Constructor. Not supported yet.
  1832. << ' ' // Warning. Not supported yet.
  1833. << IFunc // Indirect reference to another symbol.
  1834. << Debug // Debugging (d) or dynamic (D) symbol.
  1835. << FileFunc // Name of function (F), file (f) or object (O).
  1836. << ' ';
  1837. if (Absolute) {
  1838. outs() << "*ABS*";
  1839. } else if (Common) {
  1840. outs() << "*COM*";
  1841. } else if (Section == O->section_end()) {
  1842. if (O->isXCOFF()) {
  1843. XCOFFSymbolRef XCOFFSym = dyn_cast<const XCOFFObjectFile>(O)->toSymbolRef(
  1844. Symbol.getRawDataRefImpl());
  1845. if (XCOFF::N_DEBUG == XCOFFSym.getSectionNumber())
  1846. outs() << "*DEBUG*";
  1847. else
  1848. outs() << "*UND*";
  1849. } else
  1850. outs() << "*UND*";
  1851. } else {
  1852. StringRef SegmentName = getSegmentName(MachO, *Section);
  1853. if (!SegmentName.empty())
  1854. outs() << SegmentName << ",";
  1855. StringRef SectionName = unwrapOrError(Section->getName(), FileName);
  1856. outs() << SectionName;
  1857. if (O->isXCOFF()) {
  1858. Optional<SymbolRef> SymRef = getXCOFFSymbolContainingSymbolRef(
  1859. dyn_cast<const XCOFFObjectFile>(O), Symbol);
  1860. if (SymRef) {
  1861. Expected<StringRef> NameOrErr = SymRef.getValue().getName();
  1862. if (NameOrErr) {
  1863. outs() << " (csect:";
  1864. std::string SymName(NameOrErr.get());
  1865. if (Demangle)
  1866. SymName = demangle(SymName);
  1867. if (SymbolDescription)
  1868. SymName = getXCOFFSymbolDescription(
  1869. createSymbolInfo(O, SymRef.getValue()), SymName);
  1870. outs() << ' ' << SymName;
  1871. outs() << ") ";
  1872. } else
  1873. reportWarning(toString(NameOrErr.takeError()), FileName);
  1874. }
  1875. }
  1876. }
  1877. if (Common)
  1878. outs() << '\t' << format(Fmt, static_cast<uint64_t>(Symbol.getAlignment()));
  1879. else if (O->isXCOFF())
  1880. outs() << '\t'
  1881. << format(Fmt, dyn_cast<const XCOFFObjectFile>(O)->getSymbolSize(
  1882. Symbol.getRawDataRefImpl()));
  1883. else if (O->isELF())
  1884. outs() << '\t' << format(Fmt, ELFSymbolRef(Symbol).getSize());
  1885. if (O->isELF()) {
  1886. if (!SymbolVersions.empty()) {
  1887. const VersionEntry &Ver =
  1888. SymbolVersions[Symbol.getRawDataRefImpl().d.b - 1];
  1889. std::string Str;
  1890. if (!Ver.Name.empty())
  1891. Str = Ver.IsVerDef ? ' ' + Ver.Name : '(' + Ver.Name + ')';
  1892. outs() << ' ' << left_justify(Str, 12);
  1893. }
  1894. uint8_t Other = ELFSymbolRef(Symbol).getOther();
  1895. switch (Other) {
  1896. case ELF::STV_DEFAULT:
  1897. break;
  1898. case ELF::STV_INTERNAL:
  1899. outs() << " .internal";
  1900. break;
  1901. case ELF::STV_HIDDEN:
  1902. outs() << " .hidden";
  1903. break;
  1904. case ELF::STV_PROTECTED:
  1905. outs() << " .protected";
  1906. break;
  1907. default:
  1908. outs() << format(" 0x%02x", Other);
  1909. break;
  1910. }
  1911. } else if (Hidden) {
  1912. outs() << " .hidden";
  1913. }
  1914. std::string SymName(Name);
  1915. if (Demangle)
  1916. SymName = demangle(SymName);
  1917. if (O->isXCOFF() && SymbolDescription)
  1918. SymName = getXCOFFSymbolDescription(createSymbolInfo(O, Symbol), SymName);
  1919. outs() << ' ' << SymName << '\n';
  1920. }
  1921. static void printUnwindInfo(const ObjectFile *O) {
  1922. outs() << "Unwind info:\n\n";
  1923. if (const COFFObjectFile *Coff = dyn_cast<COFFObjectFile>(O))
  1924. printCOFFUnwindInfo(Coff);
  1925. else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O))
  1926. printMachOUnwindInfo(MachO);
  1927. else
  1928. // TODO: Extract DWARF dump tool to objdump.
  1929. WithColor::error(errs(), ToolName)
  1930. << "This operation is only currently supported "
  1931. "for COFF and MachO object files.\n";
  1932. }
  1933. /// Dump the raw contents of the __clangast section so the output can be piped
  1934. /// into llvm-bcanalyzer.
  1935. static void printRawClangAST(const ObjectFile *Obj) {
  1936. if (outs().is_displayed()) {
  1937. WithColor::error(errs(), ToolName)
  1938. << "The -raw-clang-ast option will dump the raw binary contents of "
  1939. "the clang ast section.\n"
  1940. "Please redirect the output to a file or another program such as "
  1941. "llvm-bcanalyzer.\n";
  1942. return;
  1943. }
  1944. StringRef ClangASTSectionName("__clangast");
  1945. if (Obj->isCOFF()) {
  1946. ClangASTSectionName = "clangast";
  1947. }
  1948. Optional<object::SectionRef> ClangASTSection;
  1949. for (auto Sec : ToolSectionFilter(*Obj)) {
  1950. StringRef Name;
  1951. if (Expected<StringRef> NameOrErr = Sec.getName())
  1952. Name = *NameOrErr;
  1953. else
  1954. consumeError(NameOrErr.takeError());
  1955. if (Name == ClangASTSectionName) {
  1956. ClangASTSection = Sec;
  1957. break;
  1958. }
  1959. }
  1960. if (!ClangASTSection)
  1961. return;
  1962. StringRef ClangASTContents = unwrapOrError(
  1963. ClangASTSection.getValue().getContents(), Obj->getFileName());
  1964. outs().write(ClangASTContents.data(), ClangASTContents.size());
  1965. }
  1966. static void printFaultMaps(const ObjectFile *Obj) {
  1967. StringRef FaultMapSectionName;
  1968. if (Obj->isELF()) {
  1969. FaultMapSectionName = ".llvm_faultmaps";
  1970. } else if (Obj->isMachO()) {
  1971. FaultMapSectionName = "__llvm_faultmaps";
  1972. } else {
  1973. WithColor::error(errs(), ToolName)
  1974. << "This operation is only currently supported "
  1975. "for ELF and Mach-O executable files.\n";
  1976. return;
  1977. }
  1978. Optional<object::SectionRef> FaultMapSection;
  1979. for (auto Sec : ToolSectionFilter(*Obj)) {
  1980. StringRef Name;
  1981. if (Expected<StringRef> NameOrErr = Sec.getName())
  1982. Name = *NameOrErr;
  1983. else
  1984. consumeError(NameOrErr.takeError());
  1985. if (Name == FaultMapSectionName) {
  1986. FaultMapSection = Sec;
  1987. break;
  1988. }
  1989. }
  1990. outs() << "FaultMap table:\n";
  1991. if (!FaultMapSection.hasValue()) {
  1992. outs() << "<not found>\n";
  1993. return;
  1994. }
  1995. StringRef FaultMapContents =
  1996. unwrapOrError(FaultMapSection.getValue().getContents(), Obj->getFileName());
  1997. FaultMapParser FMP(FaultMapContents.bytes_begin(),
  1998. FaultMapContents.bytes_end());
  1999. outs() << FMP;
  2000. }
  2001. static void printPrivateFileHeaders(const ObjectFile *O, bool OnlyFirst) {
  2002. if (O->isELF()) {
  2003. printELFFileHeader(O);
  2004. printELFDynamicSection(O);
  2005. printELFSymbolVersionInfo(O);
  2006. return;
  2007. }
  2008. if (O->isCOFF())
  2009. return printCOFFFileHeader(cast<object::COFFObjectFile>(*O));
  2010. if (O->isWasm())
  2011. return printWasmFileHeader(O);
  2012. if (O->isMachO()) {
  2013. printMachOFileHeader(O);
  2014. if (!OnlyFirst)
  2015. printMachOLoadCommands(O);
  2016. return;
  2017. }
  2018. reportError(O->getFileName(), "Invalid/Unsupported object file format");
  2019. }
  2020. static void printFileHeaders(const ObjectFile *O) {
  2021. if (!O->isELF() && !O->isCOFF())
  2022. reportError(O->getFileName(), "Invalid/Unsupported object file format");
  2023. Triple::ArchType AT = O->getArch();
  2024. outs() << "architecture: " << Triple::getArchTypeName(AT) << "\n";
  2025. uint64_t Address = unwrapOrError(O->getStartAddress(), O->getFileName());
  2026. StringRef Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
  2027. outs() << "start address: "
  2028. << "0x" << format(Fmt.data(), Address) << "\n";
  2029. }
  2030. static void printArchiveChild(StringRef Filename, const Archive::Child &C) {
  2031. Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
  2032. if (!ModeOrErr) {
  2033. WithColor::error(errs(), ToolName) << "ill-formed archive entry.\n";
  2034. consumeError(ModeOrErr.takeError());
  2035. return;
  2036. }
  2037. sys::fs::perms Mode = ModeOrErr.get();
  2038. outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
  2039. outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
  2040. outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
  2041. outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
  2042. outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
  2043. outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
  2044. outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
  2045. outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
  2046. outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
  2047. outs() << " ";
  2048. outs() << format("%d/%d %6" PRId64 " ", unwrapOrError(C.getUID(), Filename),
  2049. unwrapOrError(C.getGID(), Filename),
  2050. unwrapOrError(C.getRawSize(), Filename));
  2051. StringRef RawLastModified = C.getRawLastModified();
  2052. unsigned Seconds;
  2053. if (RawLastModified.getAsInteger(10, Seconds))
  2054. outs() << "(date: \"" << RawLastModified
  2055. << "\" contains non-decimal chars) ";
  2056. else {
  2057. // Since ctime(3) returns a 26 character string of the form:
  2058. // "Sun Sep 16 01:03:52 1973\n\0"
  2059. // just print 24 characters.
  2060. time_t t = Seconds;
  2061. outs() << format("%.24s ", ctime(&t));
  2062. }
  2063. StringRef Name = "";
  2064. Expected<StringRef> NameOrErr = C.getName();
  2065. if (!NameOrErr) {
  2066. consumeError(NameOrErr.takeError());
  2067. Name = unwrapOrError(C.getRawName(), Filename);
  2068. } else {
  2069. Name = NameOrErr.get();
  2070. }
  2071. outs() << Name << "\n";
  2072. }
  2073. // For ELF only now.
  2074. static bool shouldWarnForInvalidStartStopAddress(ObjectFile *Obj) {
  2075. if (const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj)) {
  2076. if (Elf->getEType() != ELF::ET_REL)
  2077. return true;
  2078. }
  2079. return false;
  2080. }
  2081. static void checkForInvalidStartStopAddress(ObjectFile *Obj,
  2082. uint64_t Start, uint64_t Stop) {
  2083. if (!shouldWarnForInvalidStartStopAddress(Obj))
  2084. return;
  2085. for (const SectionRef &Section : Obj->sections())
  2086. if (ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC) {
  2087. uint64_t BaseAddr = Section.getAddress();
  2088. uint64_t Size = Section.getSize();
  2089. if ((Start < BaseAddr + Size) && Stop > BaseAddr)
  2090. return;
  2091. }
  2092. if (!HasStartAddressFlag)
  2093. reportWarning("no section has address less than 0x" +
  2094. Twine::utohexstr(Stop) + " specified by --stop-address",
  2095. Obj->getFileName());
  2096. else if (!HasStopAddressFlag)
  2097. reportWarning("no section has address greater than or equal to 0x" +
  2098. Twine::utohexstr(Start) + " specified by --start-address",
  2099. Obj->getFileName());
  2100. else
  2101. reportWarning("no section overlaps the range [0x" +
  2102. Twine::utohexstr(Start) + ",0x" + Twine::utohexstr(Stop) +
  2103. ") specified by --start-address/--stop-address",
  2104. Obj->getFileName());
  2105. }
  2106. static void dumpObject(ObjectFile *O, const Archive *A = nullptr,
  2107. const Archive::Child *C = nullptr) {
  2108. // Avoid other output when using a raw option.
  2109. if (!RawClangAST) {
  2110. outs() << '\n';
  2111. if (A)
  2112. outs() << A->getFileName() << "(" << O->getFileName() << ")";
  2113. else
  2114. outs() << O->getFileName();
  2115. outs() << ":\tfile format " << O->getFileFormatName().lower() << "\n";
  2116. }
  2117. if (HasStartAddressFlag || HasStopAddressFlag)
  2118. checkForInvalidStartStopAddress(O, StartAddress, StopAddress);
  2119. // Note: the order here matches GNU objdump for compatability.
  2120. StringRef ArchiveName = A ? A->getFileName() : "";
  2121. if (ArchiveHeaders && !MachOOpt && C)
  2122. printArchiveChild(ArchiveName, *C);
  2123. if (FileHeaders)
  2124. printFileHeaders(O);
  2125. if (PrivateHeaders || FirstPrivateHeader)
  2126. printPrivateFileHeaders(O, FirstPrivateHeader);
  2127. if (SectionHeaders)
  2128. printSectionHeaders(O);
  2129. if (SymbolTable)
  2130. printSymbolTable(O, ArchiveName);
  2131. if (DynamicSymbolTable)
  2132. printSymbolTable(O, ArchiveName, /*ArchitectureName=*/"",
  2133. /*DumpDynamic=*/true);
  2134. if (DwarfDumpType != DIDT_Null) {
  2135. std::unique_ptr<DIContext> DICtx = DWARFContext::create(*O);
  2136. // Dump the complete DWARF structure.
  2137. DIDumpOptions DumpOpts;
  2138. DumpOpts.DumpType = DwarfDumpType;
  2139. DICtx->dump(outs(), DumpOpts);
  2140. }
  2141. if (Relocations && !Disassemble)
  2142. printRelocations(O);
  2143. if (DynamicRelocations)
  2144. printDynamicRelocations(O);
  2145. if (SectionContents)
  2146. printSectionContents(O);
  2147. if (Disassemble)
  2148. disassembleObject(O, Relocations);
  2149. if (UnwindInfo)
  2150. printUnwindInfo(O);
  2151. // Mach-O specific options:
  2152. if (ExportsTrie)
  2153. printExportsTrie(O);
  2154. if (Rebase)
  2155. printRebaseTable(O);
  2156. if (Bind)
  2157. printBindTable(O);
  2158. if (LazyBind)
  2159. printLazyBindTable(O);
  2160. if (WeakBind)
  2161. printWeakBindTable(O);
  2162. // Other special sections:
  2163. if (RawClangAST)
  2164. printRawClangAST(O);
  2165. if (FaultMapSection)
  2166. printFaultMaps(O);
  2167. }
  2168. static void dumpObject(const COFFImportFile *I, const Archive *A,
  2169. const Archive::Child *C = nullptr) {
  2170. StringRef ArchiveName = A ? A->getFileName() : "";
  2171. // Avoid other output when using a raw option.
  2172. if (!RawClangAST)
  2173. outs() << '\n'
  2174. << ArchiveName << "(" << I->getFileName() << ")"
  2175. << ":\tfile format COFF-import-file"
  2176. << "\n\n";
  2177. if (ArchiveHeaders && !MachOOpt && C)
  2178. printArchiveChild(ArchiveName, *C);
  2179. if (SymbolTable)
  2180. printCOFFSymbolTable(I);
  2181. }
  2182. /// Dump each object file in \a a;
  2183. static void dumpArchive(const Archive *A) {
  2184. Error Err = Error::success();
  2185. unsigned I = -1;
  2186. for (auto &C : A->children(Err)) {
  2187. ++I;
  2188. Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
  2189. if (!ChildOrErr) {
  2190. if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
  2191. reportError(std::move(E), getFileNameForError(C, I), A->getFileName());
  2192. continue;
  2193. }
  2194. if (ObjectFile *O = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
  2195. dumpObject(O, A, &C);
  2196. else if (COFFImportFile *I = dyn_cast<COFFImportFile>(&*ChildOrErr.get()))
  2197. dumpObject(I, A, &C);
  2198. else
  2199. reportError(errorCodeToError(object_error::invalid_file_type),
  2200. A->getFileName());
  2201. }
  2202. if (Err)
  2203. reportError(std::move(Err), A->getFileName());
  2204. }
  2205. /// Open file and figure out how to dump it.
  2206. static void dumpInput(StringRef file) {
  2207. // If we are using the Mach-O specific object file parser, then let it parse
  2208. // the file and process the command line options. So the -arch flags can
  2209. // be used to select specific slices, etc.
  2210. if (MachOOpt) {
  2211. parseInputMachO(file);
  2212. return;
  2213. }
  2214. // Attempt to open the binary.
  2215. OwningBinary<Binary> OBinary = unwrapOrError(createBinary(file), file);
  2216. Binary &Binary = *OBinary.getBinary();
  2217. if (Archive *A = dyn_cast<Archive>(&Binary))
  2218. dumpArchive(A);
  2219. else if (ObjectFile *O = dyn_cast<ObjectFile>(&Binary))
  2220. dumpObject(O);
  2221. else if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Binary))
  2222. parseInputMachO(UB);
  2223. else
  2224. reportError(errorCodeToError(object_error::invalid_file_type), file);
  2225. }
  2226. template <typename T>
  2227. static void parseIntArg(const llvm::opt::InputArgList &InputArgs, int ID,
  2228. T &Value) {
  2229. if (const opt::Arg *A = InputArgs.getLastArg(ID)) {
  2230. StringRef V(A->getValue());
  2231. if (!llvm::to_integer(V, Value, 0)) {
  2232. reportCmdLineError(A->getSpelling() +
  2233. ": expected a non-negative integer, but got '" + V +
  2234. "'");
  2235. }
  2236. }
  2237. }
  2238. static void invalidArgValue(const opt::Arg *A) {
  2239. reportCmdLineError("'" + StringRef(A->getValue()) +
  2240. "' is not a valid value for '" + A->getSpelling() + "'");
  2241. }
  2242. static std::vector<std::string>
  2243. commaSeparatedValues(const llvm::opt::InputArgList &InputArgs, int ID) {
  2244. std::vector<std::string> Values;
  2245. for (StringRef Value : InputArgs.getAllArgValues(ID)) {
  2246. llvm::SmallVector<StringRef, 2> SplitValues;
  2247. llvm::SplitString(Value, SplitValues, ",");
  2248. for (StringRef SplitValue : SplitValues)
  2249. Values.push_back(SplitValue.str());
  2250. }
  2251. return Values;
  2252. }
  2253. static void parseOtoolOptions(const llvm::opt::InputArgList &InputArgs) {
  2254. MachOOpt = true;
  2255. FullLeadingAddr = true;
  2256. PrintImmHex = true;
  2257. ArchName = InputArgs.getLastArgValue(OTOOL_arch).str();
  2258. LinkOptHints = InputArgs.hasArg(OTOOL_C);
  2259. if (InputArgs.hasArg(OTOOL_d))
  2260. FilterSections.push_back("__DATA,__data");
  2261. DylibId = InputArgs.hasArg(OTOOL_D);
  2262. UniversalHeaders = InputArgs.hasArg(OTOOL_f);
  2263. DataInCode = InputArgs.hasArg(OTOOL_G);
  2264. FirstPrivateHeader = InputArgs.hasArg(OTOOL_h);
  2265. IndirectSymbols = InputArgs.hasArg(OTOOL_I);
  2266. ShowRawInsn = InputArgs.hasArg(OTOOL_j);
  2267. PrivateHeaders = InputArgs.hasArg(OTOOL_l);
  2268. DylibsUsed = InputArgs.hasArg(OTOOL_L);
  2269. MCPU = InputArgs.getLastArgValue(OTOOL_mcpu_EQ).str();
  2270. ObjcMetaData = InputArgs.hasArg(OTOOL_o);
  2271. DisSymName = InputArgs.getLastArgValue(OTOOL_p).str();
  2272. InfoPlist = InputArgs.hasArg(OTOOL_P);
  2273. Relocations = InputArgs.hasArg(OTOOL_r);
  2274. if (const Arg *A = InputArgs.getLastArg(OTOOL_s)) {
  2275. auto Filter = (A->getValue(0) + StringRef(",") + A->getValue(1)).str();
  2276. FilterSections.push_back(Filter);
  2277. }
  2278. if (InputArgs.hasArg(OTOOL_t))
  2279. FilterSections.push_back("__TEXT,__text");
  2280. Verbose = InputArgs.hasArg(OTOOL_v) || InputArgs.hasArg(OTOOL_V) ||
  2281. InputArgs.hasArg(OTOOL_o);
  2282. SymbolicOperands = InputArgs.hasArg(OTOOL_V);
  2283. if (InputArgs.hasArg(OTOOL_x))
  2284. FilterSections.push_back(",__text");
  2285. LeadingAddr = LeadingHeaders = !InputArgs.hasArg(OTOOL_X);
  2286. InputFilenames = InputArgs.getAllArgValues(OTOOL_INPUT);
  2287. if (InputFilenames.empty())
  2288. reportCmdLineError("no input file");
  2289. for (const Arg *A : InputArgs) {
  2290. const Option &O = A->getOption();
  2291. if (O.getGroup().isValid() && O.getGroup().getID() == OTOOL_grp_obsolete) {
  2292. reportCmdLineWarning(O.getPrefixedName() +
  2293. " is obsolete and not implemented");
  2294. }
  2295. }
  2296. }
  2297. static void parseObjdumpOptions(const llvm::opt::InputArgList &InputArgs) {
  2298. parseIntArg(InputArgs, OBJDUMP_adjust_vma_EQ, AdjustVMA);
  2299. AllHeaders = InputArgs.hasArg(OBJDUMP_all_headers);
  2300. ArchName = InputArgs.getLastArgValue(OBJDUMP_arch_name_EQ).str();
  2301. ArchiveHeaders = InputArgs.hasArg(OBJDUMP_archive_headers);
  2302. Demangle = InputArgs.hasArg(OBJDUMP_demangle);
  2303. Disassemble = InputArgs.hasArg(OBJDUMP_disassemble);
  2304. DisassembleAll = InputArgs.hasArg(OBJDUMP_disassemble_all);
  2305. SymbolDescription = InputArgs.hasArg(OBJDUMP_symbol_description);
  2306. DisassembleSymbols =
  2307. commaSeparatedValues(InputArgs, OBJDUMP_disassemble_symbols_EQ);
  2308. DisassembleZeroes = InputArgs.hasArg(OBJDUMP_disassemble_zeroes);
  2309. if (const opt::Arg *A = InputArgs.getLastArg(OBJDUMP_dwarf_EQ)) {
  2310. DwarfDumpType = StringSwitch<DIDumpType>(A->getValue())
  2311. .Case("frames", DIDT_DebugFrame)
  2312. .Default(DIDT_Null);
  2313. if (DwarfDumpType == DIDT_Null)
  2314. invalidArgValue(A);
  2315. }
  2316. DynamicRelocations = InputArgs.hasArg(OBJDUMP_dynamic_reloc);
  2317. FaultMapSection = InputArgs.hasArg(OBJDUMP_fault_map_section);
  2318. FileHeaders = InputArgs.hasArg(OBJDUMP_file_headers);
  2319. SectionContents = InputArgs.hasArg(OBJDUMP_full_contents);
  2320. PrintLines = InputArgs.hasArg(OBJDUMP_line_numbers);
  2321. InputFilenames = InputArgs.getAllArgValues(OBJDUMP_INPUT);
  2322. MachOOpt = InputArgs.hasArg(OBJDUMP_macho);
  2323. MCPU = InputArgs.getLastArgValue(OBJDUMP_mcpu_EQ).str();
  2324. MAttrs = commaSeparatedValues(InputArgs, OBJDUMP_mattr_EQ);
  2325. ShowRawInsn = !InputArgs.hasArg(OBJDUMP_no_show_raw_insn);
  2326. LeadingAddr = !InputArgs.hasArg(OBJDUMP_no_leading_addr);
  2327. RawClangAST = InputArgs.hasArg(OBJDUMP_raw_clang_ast);
  2328. Relocations = InputArgs.hasArg(OBJDUMP_reloc);
  2329. PrintImmHex =
  2330. InputArgs.hasFlag(OBJDUMP_print_imm_hex, OBJDUMP_no_print_imm_hex, false);
  2331. PrivateHeaders = InputArgs.hasArg(OBJDUMP_private_headers);
  2332. FilterSections = InputArgs.getAllArgValues(OBJDUMP_section_EQ);
  2333. SectionHeaders = InputArgs.hasArg(OBJDUMP_section_headers);
  2334. ShowLMA = InputArgs.hasArg(OBJDUMP_show_lma);
  2335. PrintSource = InputArgs.hasArg(OBJDUMP_source);
  2336. parseIntArg(InputArgs, OBJDUMP_start_address_EQ, StartAddress);
  2337. HasStartAddressFlag = InputArgs.hasArg(OBJDUMP_start_address_EQ);
  2338. parseIntArg(InputArgs, OBJDUMP_stop_address_EQ, StopAddress);
  2339. HasStopAddressFlag = InputArgs.hasArg(OBJDUMP_stop_address_EQ);
  2340. SymbolTable = InputArgs.hasArg(OBJDUMP_syms);
  2341. SymbolizeOperands = InputArgs.hasArg(OBJDUMP_symbolize_operands);
  2342. DynamicSymbolTable = InputArgs.hasArg(OBJDUMP_dynamic_syms);
  2343. TripleName = InputArgs.getLastArgValue(OBJDUMP_triple_EQ).str();
  2344. UnwindInfo = InputArgs.hasArg(OBJDUMP_unwind_info);
  2345. Wide = InputArgs.hasArg(OBJDUMP_wide);
  2346. Prefix = InputArgs.getLastArgValue(OBJDUMP_prefix).str();
  2347. parseIntArg(InputArgs, OBJDUMP_prefix_strip, PrefixStrip);
  2348. if (const opt::Arg *A = InputArgs.getLastArg(OBJDUMP_debug_vars_EQ)) {
  2349. DbgVariables = StringSwitch<DebugVarsFormat>(A->getValue())
  2350. .Case("ascii", DVASCII)
  2351. .Case("unicode", DVUnicode)
  2352. .Default(DVInvalid);
  2353. if (DbgVariables == DVInvalid)
  2354. invalidArgValue(A);
  2355. }
  2356. parseIntArg(InputArgs, OBJDUMP_debug_vars_indent_EQ, DbgIndent);
  2357. parseMachOOptions(InputArgs);
  2358. // Parse -M (--disassembler-options) and deprecated
  2359. // --x86-asm-syntax={att,intel}.
  2360. //
  2361. // Note, for x86, the asm dialect (AssemblerDialect) is initialized when the
  2362. // MCAsmInfo is constructed. MCInstPrinter::applyTargetSpecificCLOption is
  2363. // called too late. For now we have to use the internal cl::opt option.
  2364. const char *AsmSyntax = nullptr;
  2365. for (const auto *A : InputArgs.filtered(OBJDUMP_disassembler_options_EQ,
  2366. OBJDUMP_x86_asm_syntax_att,
  2367. OBJDUMP_x86_asm_syntax_intel)) {
  2368. switch (A->getOption().getID()) {
  2369. case OBJDUMP_x86_asm_syntax_att:
  2370. AsmSyntax = "--x86-asm-syntax=att";
  2371. continue;
  2372. case OBJDUMP_x86_asm_syntax_intel:
  2373. AsmSyntax = "--x86-asm-syntax=intel";
  2374. continue;
  2375. }
  2376. SmallVector<StringRef, 2> Values;
  2377. llvm::SplitString(A->getValue(), Values, ",");
  2378. for (StringRef V : Values) {
  2379. if (V == "att")
  2380. AsmSyntax = "--x86-asm-syntax=att";
  2381. else if (V == "intel")
  2382. AsmSyntax = "--x86-asm-syntax=intel";
  2383. else
  2384. DisassemblerOptions.push_back(V.str());
  2385. }
  2386. }
  2387. if (AsmSyntax) {
  2388. const char *Argv[] = {"llvm-objdump", AsmSyntax};
  2389. llvm::cl::ParseCommandLineOptions(2, Argv);
  2390. }
  2391. // objdump defaults to a.out if no filenames specified.
  2392. if (InputFilenames.empty())
  2393. InputFilenames.push_back("a.out");
  2394. }
  2395. int main(int argc, char **argv) {
  2396. using namespace llvm;
  2397. InitLLVM X(argc, argv);
  2398. ToolName = argv[0];
  2399. std::unique_ptr<CommonOptTable> T;
  2400. OptSpecifier Unknown, HelpFlag, HelpHiddenFlag, VersionFlag;
  2401. StringRef Stem = sys::path::stem(ToolName);
  2402. auto Is = [=](StringRef Tool) {
  2403. // We need to recognize the following filenames:
  2404. //
  2405. // llvm-objdump -> objdump
  2406. // llvm-otool-10.exe -> otool
  2407. // powerpc64-unknown-freebsd13-objdump -> objdump
  2408. auto I = Stem.rfind_insensitive(Tool);
  2409. return I != StringRef::npos &&
  2410. (I + Tool.size() == Stem.size() || !isAlnum(Stem[I + Tool.size()]));
  2411. };
  2412. if (Is("otool")) {
  2413. T = std::make_unique<OtoolOptTable>();
  2414. Unknown = OTOOL_UNKNOWN;
  2415. HelpFlag = OTOOL_help;
  2416. HelpHiddenFlag = OTOOL_help_hidden;
  2417. VersionFlag = OTOOL_version;
  2418. } else {
  2419. T = std::make_unique<ObjdumpOptTable>();
  2420. Unknown = OBJDUMP_UNKNOWN;
  2421. HelpFlag = OBJDUMP_help;
  2422. HelpHiddenFlag = OBJDUMP_help_hidden;
  2423. VersionFlag = OBJDUMP_version;
  2424. }
  2425. BumpPtrAllocator A;
  2426. StringSaver Saver(A);
  2427. opt::InputArgList InputArgs =
  2428. T->parseArgs(argc, argv, Unknown, Saver,
  2429. [&](StringRef Msg) { reportCmdLineError(Msg); });
  2430. if (InputArgs.size() == 0 || InputArgs.hasArg(HelpFlag)) {
  2431. T->printHelp(ToolName);
  2432. return 0;
  2433. }
  2434. if (InputArgs.hasArg(HelpHiddenFlag)) {
  2435. T->printHelp(ToolName, /*ShowHidden=*/true);
  2436. return 0;
  2437. }
  2438. // Initialize targets and assembly printers/parsers.
  2439. InitializeAllTargetInfos();
  2440. InitializeAllTargetMCs();
  2441. InitializeAllDisassemblers();
  2442. if (InputArgs.hasArg(VersionFlag)) {
  2443. cl::PrintVersionMessage();
  2444. if (!Is("otool")) {
  2445. outs() << '\n';
  2446. TargetRegistry::printRegisteredTargetsForVersion(outs());
  2447. }
  2448. return 0;
  2449. }
  2450. if (Is("otool"))
  2451. parseOtoolOptions(InputArgs);
  2452. else
  2453. parseObjdumpOptions(InputArgs);
  2454. if (StartAddress >= StopAddress)
  2455. reportCmdLineError("start address should be less than stop address");
  2456. // Removes trailing separators from prefix.
  2457. while (!Prefix.empty() && sys::path::is_separator(Prefix.back()))
  2458. Prefix.pop_back();
  2459. if (AllHeaders)
  2460. ArchiveHeaders = FileHeaders = PrivateHeaders = Relocations =
  2461. SectionHeaders = SymbolTable = true;
  2462. if (DisassembleAll || PrintSource || PrintLines ||
  2463. !DisassembleSymbols.empty())
  2464. Disassemble = true;
  2465. if (!ArchiveHeaders && !Disassemble && DwarfDumpType == DIDT_Null &&
  2466. !DynamicRelocations && !FileHeaders && !PrivateHeaders && !RawClangAST &&
  2467. !Relocations && !SectionHeaders && !SectionContents && !SymbolTable &&
  2468. !DynamicSymbolTable && !UnwindInfo && !FaultMapSection &&
  2469. !(MachOOpt &&
  2470. (Bind || DataInCode || DylibId || DylibsUsed || ExportsTrie ||
  2471. FirstPrivateHeader || FunctionStarts || IndirectSymbols || InfoPlist ||
  2472. LazyBind || LinkOptHints || ObjcMetaData || Rebase || Rpaths ||
  2473. UniversalHeaders || WeakBind || !FilterSections.empty()))) {
  2474. T->printHelp(ToolName);
  2475. return 2;
  2476. }
  2477. DisasmSymbolSet.insert(DisassembleSymbols.begin(), DisassembleSymbols.end());
  2478. llvm::for_each(InputFilenames, dumpInput);
  2479. warnOnNoMatchForSections();
  2480. return EXIT_SUCCESS;
  2481. }