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