ObjDumper.cpp 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. //===-- ObjDumper.cpp - Base dumper class -----------------------*- C++ -*-===//
  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. /// \file
  10. /// This file implements ObjDumper.
  11. ///
  12. //===----------------------------------------------------------------------===//
  13. #include "ObjDumper.h"
  14. #include "llvm-readobj.h"
  15. #include "llvm/Object/ObjectFile.h"
  16. #include "llvm/Support/Error.h"
  17. #include "llvm/Support/FormatVariadic.h"
  18. #include "llvm/Support/ScopedPrinter.h"
  19. #include "llvm/Support/raw_ostream.h"
  20. #include <map>
  21. namespace llvm {
  22. static inline Error createError(const Twine &Msg) {
  23. return createStringError(object::object_error::parse_failed, Msg);
  24. }
  25. ObjDumper::ObjDumper(ScopedPrinter &Writer, StringRef ObjName) : W(Writer) {
  26. // Dumper reports all non-critical errors as warnings.
  27. // It does not print the same warning more than once.
  28. WarningHandler = [=](const Twine &Msg) {
  29. if (Warnings.insert(Msg.str()).second)
  30. reportWarning(createError(Msg), ObjName);
  31. return Error::success();
  32. };
  33. }
  34. ObjDumper::~ObjDumper() {}
  35. void ObjDumper::reportUniqueWarning(Error Err) const {
  36. reportUniqueWarning(toString(std::move(Err)));
  37. }
  38. void ObjDumper::reportUniqueWarning(const Twine &Msg) const {
  39. cantFail(WarningHandler(Msg),
  40. "WarningHandler should always return ErrorSuccess");
  41. }
  42. static void printAsPrintable(raw_ostream &W, const uint8_t *Start, size_t Len) {
  43. for (size_t i = 0; i < Len; i++)
  44. W << (isPrint(Start[i]) ? static_cast<char>(Start[i]) : '.');
  45. }
  46. static std::vector<object::SectionRef>
  47. getSectionRefsByNameOrIndex(const object::ObjectFile &Obj,
  48. ArrayRef<std::string> Sections) {
  49. std::vector<object::SectionRef> Ret;
  50. std::map<std::string, bool> SecNames;
  51. std::map<unsigned, bool> SecIndices;
  52. unsigned SecIndex;
  53. for (StringRef Section : Sections) {
  54. if (!Section.getAsInteger(0, SecIndex))
  55. SecIndices.emplace(SecIndex, false);
  56. else
  57. SecNames.emplace(std::string(Section), false);
  58. }
  59. SecIndex = Obj.isELF() ? 0 : 1;
  60. for (object::SectionRef SecRef : Obj.sections()) {
  61. StringRef SecName = unwrapOrError(Obj.getFileName(), SecRef.getName());
  62. auto NameIt = SecNames.find(std::string(SecName));
  63. if (NameIt != SecNames.end())
  64. NameIt->second = true;
  65. auto IndexIt = SecIndices.find(SecIndex);
  66. if (IndexIt != SecIndices.end())
  67. IndexIt->second = true;
  68. if (NameIt != SecNames.end() || IndexIt != SecIndices.end())
  69. Ret.push_back(SecRef);
  70. SecIndex++;
  71. }
  72. for (const std::pair<const std::string, bool> &S : SecNames)
  73. if (!S.second)
  74. reportWarning(
  75. createError(formatv("could not find section '{0}'", S.first).str()),
  76. Obj.getFileName());
  77. for (std::pair<unsigned, bool> S : SecIndices)
  78. if (!S.second)
  79. reportWarning(
  80. createError(formatv("could not find section {0}", S.first).str()),
  81. Obj.getFileName());
  82. return Ret;
  83. }
  84. void ObjDumper::printSectionsAsString(const object::ObjectFile &Obj,
  85. ArrayRef<std::string> Sections) {
  86. bool First = true;
  87. for (object::SectionRef Section :
  88. getSectionRefsByNameOrIndex(Obj, Sections)) {
  89. StringRef SectionName = unwrapOrError(Obj.getFileName(), Section.getName());
  90. if (!First)
  91. W.startLine() << '\n';
  92. First = false;
  93. W.startLine() << "String dump of section '" << SectionName << "':\n";
  94. StringRef SectionContent =
  95. unwrapOrError(Obj.getFileName(), Section.getContents());
  96. const uint8_t *SecContent = SectionContent.bytes_begin();
  97. const uint8_t *CurrentWord = SecContent;
  98. const uint8_t *SecEnd = SectionContent.bytes_end();
  99. while (CurrentWord <= SecEnd) {
  100. size_t WordSize = strnlen(reinterpret_cast<const char *>(CurrentWord),
  101. SecEnd - CurrentWord);
  102. if (!WordSize) {
  103. CurrentWord++;
  104. continue;
  105. }
  106. W.startLine() << format("[%6tx] ", CurrentWord - SecContent);
  107. printAsPrintable(W.startLine(), CurrentWord, WordSize);
  108. W.startLine() << '\n';
  109. CurrentWord += WordSize + 1;
  110. }
  111. }
  112. }
  113. void ObjDumper::printSectionsAsHex(const object::ObjectFile &Obj,
  114. ArrayRef<std::string> Sections) {
  115. bool First = true;
  116. for (object::SectionRef Section :
  117. getSectionRefsByNameOrIndex(Obj, Sections)) {
  118. StringRef SectionName = unwrapOrError(Obj.getFileName(), Section.getName());
  119. if (!First)
  120. W.startLine() << '\n';
  121. First = false;
  122. W.startLine() << "Hex dump of section '" << SectionName << "':\n";
  123. StringRef SectionContent =
  124. unwrapOrError(Obj.getFileName(), Section.getContents());
  125. const uint8_t *SecContent = SectionContent.bytes_begin();
  126. const uint8_t *SecEnd = SecContent + SectionContent.size();
  127. for (const uint8_t *SecPtr = SecContent; SecPtr < SecEnd; SecPtr += 16) {
  128. const uint8_t *TmpSecPtr = SecPtr;
  129. uint8_t i;
  130. uint8_t k;
  131. W.startLine() << format_hex(Section.getAddress() + (SecPtr - SecContent),
  132. 10);
  133. W.startLine() << ' ';
  134. for (i = 0; TmpSecPtr < SecEnd && i < 4; ++i) {
  135. for (k = 0; TmpSecPtr < SecEnd && k < 4; k++, TmpSecPtr++) {
  136. uint8_t Val = *(reinterpret_cast<const uint8_t *>(TmpSecPtr));
  137. W.startLine() << format_hex_no_prefix(Val, 2);
  138. }
  139. W.startLine() << ' ';
  140. }
  141. // We need to print the correct amount of spaces to match the format.
  142. // We are adding the (4 - i) last rows that are 8 characters each.
  143. // Then, the (4 - i) spaces that are in between the rows.
  144. // Least, if we cut in a middle of a row, we add the remaining characters,
  145. // which is (8 - (k * 2)).
  146. if (i < 4)
  147. W.startLine() << format("%*c", (4 - i) * 8 + (4 - i), ' ');
  148. if (k < 4)
  149. W.startLine() << format("%*c", 8 - k * 2, ' ');
  150. TmpSecPtr = SecPtr;
  151. for (i = 0; TmpSecPtr + i < SecEnd && i < 16; ++i)
  152. W.startLine() << (isPrint(TmpSecPtr[i])
  153. ? static_cast<char>(TmpSecPtr[i])
  154. : '.');
  155. W.startLine() << '\n';
  156. }
  157. }
  158. }
  159. } // namespace llvm