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