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