xref: /llvm-project-15.0.7/lld/ELF/MapFile.cpp (revision 1781d105)
1 //===- MapFile.cpp --------------------------------------------------------===//
2 //
3 //                             The LLVM Linker
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the -Map option. It shows lists in order and
11 // hierarchically the output sections, input sections, input files and
12 // symbol:
13 //
14 //   Address  Size     Align Out     In      Symbol
15 //   00201000 00000015     4 .text
16 //   00201000 0000000e     4         test.o:(.text)
17 //   0020100e 00000000     0                 local
18 //   00201005 00000000     0                 f(int)
19 //
20 //===----------------------------------------------------------------------===//
21 
22 #include "MapFile.h"
23 #include "InputFiles.h"
24 #include "LinkerScript.h"
25 #include "OutputSections.h"
26 #include "SymbolTable.h"
27 #include "Symbols.h"
28 #include "SyntheticSections.h"
29 #include "lld/Common/Strings.h"
30 #include "lld/Common/Threads.h"
31 #include "llvm/ADT/MapVector.h"
32 #include "llvm/ADT/SetVector.h"
33 #include "llvm/Support/raw_ostream.h"
34 
35 using namespace llvm;
36 using namespace llvm::object;
37 
38 using namespace lld;
39 using namespace lld::elf;
40 
41 typedef DenseMap<const SectionBase *, SmallVector<Symbol *, 4>> SymbolMapTy;
42 
43 static const std::string Indent8 = "        ";          // 8 spaces
44 static const std::string Indent16 = "                "; // 16 spaces
45 
46 // Print out the first three columns of a line.
47 static void writeHeader(raw_ostream &OS, uint64_t Addr, uint64_t Size,
48                         uint64_t Align) {
49   int W = Config->Is64 ? 16 : 8;
50   OS << format("%0*llx %0*llx %5lld ", W, Addr, W, Size, Align);
51 }
52 
53 // Returns a list of all symbols that we want to print out.
54 static std::vector<Symbol *> getSymbols() {
55   std::vector<Symbol *> V;
56   for (InputFile *File : ObjectFiles) {
57     for (Symbol *B : File->getSymbols()) {
58       if (auto *SS = dyn_cast<SharedSymbol>(B))
59         if (SS->CopyRelSec || SS->NeedsPltAddr)
60           V.push_back(SS);
61       if (auto *DR = dyn_cast<Defined>(B))
62         if (DR->File == File && !DR->isSection() && DR->Section &&
63             DR->Section->Live)
64           V.push_back(DR);
65     }
66   }
67   return V;
68 }
69 
70 // Returns a map from sections to their symbols.
71 static SymbolMapTy getSectionSyms(ArrayRef<Symbol *> Syms) {
72   SymbolMapTy Ret;
73   for (Symbol *S : Syms) {
74     if (auto *DR = dyn_cast<Defined>(S)) {
75       Ret[DR->Section].push_back(S);
76       continue;
77     }
78 
79     SharedSymbol *SS = cast<SharedSymbol>(S);
80     if (SS->CopyRelSec)
81       Ret[SS->CopyRelSec].push_back(S);
82     else
83       Ret[InX::Plt].push_back(S);
84   }
85 
86   // Sort symbols by address. We want to print out symbols in the
87   // order in the output file rather than the order they appeared
88   // in the input files.
89   for (auto &It : Ret) {
90     SmallVectorImpl<Symbol *> &V = It.second;
91     std::sort(V.begin(), V.end(),
92               [](Symbol *A, Symbol *B) { return A->getVA() < B->getVA(); });
93   }
94   return Ret;
95 }
96 
97 // Construct a map from symbols to their stringified representations.
98 // Demangling symbols (which is what toString() does) is slow, so
99 // we do that in batch using parallel-for.
100 static DenseMap<Symbol *, std::string>
101 getSymbolStrings(ArrayRef<Symbol *> Syms) {
102   std::vector<std::string> Str(Syms.size());
103   parallelForEachN(0, Syms.size(), [&](size_t I) {
104     raw_string_ostream OS(Str[I]);
105     writeHeader(OS, Syms[I]->getVA(), Syms[I]->getSize(), 0);
106     OS << Indent16 << toString(*Syms[I]);
107   });
108 
109   DenseMap<Symbol *, std::string> Ret;
110   for (size_t I = 0, E = Syms.size(); I < E; ++I)
111     Ret[Syms[I]] = std::move(Str[I]);
112   return Ret;
113 }
114 
115 // Print .eh_frame contents. Since the section consists of EhSectionPieces,
116 // we need a specialized printer for that section.
117 //
118 // .eh_frame tend to contain a lot of section pieces that are contiguous
119 // both in input file and output file. Such pieces are squashed before
120 // being displayed to make output compact.
121 static void printEhFrame(raw_ostream &OS, OutputSection *OSec) {
122   std::vector<EhSectionPiece> Pieces;
123 
124   auto Add = [&](const EhSectionPiece &P) {
125     // If P is adjacent to Last, squash the two.
126     if (!Pieces.empty()) {
127       EhSectionPiece &Last = Pieces.back();
128       if (Last.Sec == P.Sec && Last.InputOff + Last.Size == P.InputOff &&
129           Last.OutputOff + Last.Size == P.OutputOff) {
130         Last.Size += P.Size;
131         return;
132       }
133     }
134     Pieces.push_back(P);
135   };
136 
137   // Gather section pieces.
138   for (const CieRecord *Rec : InX::EhFrame->getCieRecords()) {
139     Add(*Rec->Cie);
140     for (const EhSectionPiece *Fde : Rec->Fdes)
141       Add(*Fde);
142   }
143 
144   // Print out section pieces.
145   for (EhSectionPiece &P : Pieces) {
146     writeHeader(OS, OSec->Addr + P.OutputOff, P.Size, 0);
147     OS << Indent8 << toString(P.Sec->File) << ":(" << P.Sec->Name << "+0x"
148        << Twine::utohexstr(P.InputOff) + ")\n";
149   }
150 }
151 
152 void elf::writeMapFile() {
153   if (Config->MapFile.empty())
154     return;
155 
156   // Open a map file for writing.
157   std::error_code EC;
158   raw_fd_ostream OS(Config->MapFile, EC, sys::fs::F_None);
159   if (EC) {
160     error("cannot open " + Config->MapFile + ": " + EC.message());
161     return;
162   }
163 
164   // Collect symbol info that we want to print out.
165   std::vector<Symbol *> Syms = getSymbols();
166   SymbolMapTy SectionSyms = getSectionSyms(Syms);
167   DenseMap<Symbol *, std::string> SymStr = getSymbolStrings(Syms);
168 
169   // Print out the header line.
170   int W = Config->Is64 ? 16 : 8;
171   OS << left_justify("Address", W) << ' ' << left_justify("Size", W)
172      << " Align Out     In      Symbol\n";
173 
174   // Print out file contents.
175   for (OutputSection *OSec : OutputSections) {
176     writeHeader(OS, OSec->Addr, OSec->Size, OSec->Alignment);
177     OS << OSec->Name << '\n';
178 
179     // Dump symbols for each input section.
180     for (BaseCommand *Base : OSec->SectionCommands) {
181       if (auto *ISD = dyn_cast<InputSectionDescription>(Base)) {
182         for (InputSection *IS : ISD->Sections) {
183           if (IS == InX::EhFrame) {
184             printEhFrame(OS, OSec);
185             continue;
186           }
187 
188           writeHeader(OS, IS->getVA(0), IS->getSize(), IS->Alignment);
189           OS << Indent8 << toString(IS) << '\n';
190           for (Symbol *Sym : SectionSyms[IS])
191             OS << SymStr[Sym] << '\n';
192         }
193         continue;
194       }
195 
196       if (auto *Cmd = dyn_cast<ByteCommand>(Base)) {
197         writeHeader(OS, OSec->Addr + Cmd->Offset, Cmd->Size, 1);
198         OS << Indent8 << Cmd->CommandString << '\n';
199         continue;
200       }
201 
202       if (auto *Cmd = dyn_cast<SymbolAssignment>(Base)) {
203         writeHeader(OS, Cmd->Addr, Cmd->Size, 1);
204         OS << Indent8 << Cmd->CommandString << '\n';
205         continue;
206       }
207     }
208   }
209 }
210 
211 static void print(StringRef A, StringRef B) {
212   outs() << left_justify(A, 49) << " " << B << "\n";
213 }
214 
215 // Output a cross reference table to stdout. This is for --cref.
216 //
217 // For each global symbol, we print out a file that defines the symbol
218 // followed by files that uses that symbol. Here is an example.
219 //
220 //     strlen     /lib/x86_64-linux-gnu/libc.so.6
221 //                tools/lld/tools/lld/CMakeFiles/lld.dir/lld.cpp.o
222 //                lib/libLLVMSupport.a(PrettyStackTrace.cpp.o)
223 //
224 // In this case, strlen is defined by libc.so.6 and used by other two
225 // files.
226 void elf::writeCrossReferenceTable() {
227   if (!Config->Cref)
228     return;
229 
230   // Collect symbols and files.
231   MapVector<Symbol *, SetVector<InputFile *>> Map;
232   for (InputFile *File : ObjectFiles) {
233     for (Symbol *Sym : File->getSymbols()) {
234       if (isa<SharedSymbol>(Sym))
235         Map[Sym].insert(File);
236       if (auto *D = dyn_cast<Defined>(Sym))
237         if (!D->isLocal() && (!D->Section || D->Section->Live))
238           Map[D].insert(File);
239     }
240   }
241 
242   // Print out a header.
243   outs() << "Cross Reference Table\n\n";
244   print("Symbol", "File");
245 
246   // Print out a table.
247   for (auto KV : Map) {
248     Symbol *Sym = KV.first;
249     SetVector<InputFile *> &Files = KV.second;
250 
251     print(toString(*Sym), toString(Sym->File));
252     for (InputFile *File : Files)
253       if (File != Sym->File)
254         print("", toString(File));
255   }
256 }
257