blob: 26ac181a0be11f8e49920ad300dfe871720c1805 [file] [log] [blame]
Eric Christopher9cad53c2013-04-03 18:31:38 +00001//===-- COFFDumper.cpp - COFF-specific dumper -------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief This file implements the COFF-specific dumper for llvm-readobj.
12///
13//===----------------------------------------------------------------------===//
14
15#include "llvm-readobj.h"
Eric Christopher9cad53c2013-04-03 18:31:38 +000016#include "Error.h"
Chandler Carruth07baed52014-01-13 08:04:33 +000017#include "ObjDumper.h"
Eric Christopher9cad53c2013-04-03 18:31:38 +000018#include "StreamWriter.h"
Eric Christopher9cad53c2013-04-03 18:31:38 +000019#include "llvm/ADT/DenseMap.h"
20#include "llvm/ADT/SmallString.h"
21#include "llvm/Object/COFF.h"
22#include "llvm/Object/ObjectFile.h"
Chandler Carruth07baed52014-01-13 08:04:33 +000023#include "llvm/Support/COFF.h"
Eric Christopher9cad53c2013-04-03 18:31:38 +000024#include "llvm/Support/Casting.h"
25#include "llvm/Support/Compiler.h"
Timur Iskhodzhanov48703be2013-12-19 11:37:14 +000026#include "llvm/Support/DataExtractor.h"
Eric Christopher9cad53c2013-04-03 18:31:38 +000027#include "llvm/Support/Format.h"
28#include "llvm/Support/SourceMgr.h"
29#include "llvm/Support/Win64EH.h"
30#include "llvm/Support/raw_ostream.h"
31#include "llvm/Support/system_error.h"
Eric Christopher9cad53c2013-04-03 18:31:38 +000032#include <algorithm>
33#include <cstring>
34#include <time.h>
35
36using namespace llvm;
37using namespace llvm::object;
38using namespace llvm::Win64EH;
39
40namespace {
41
42class COFFDumper : public ObjDumper {
43public:
44 COFFDumper(const llvm::object::COFFObjectFile *Obj, StreamWriter& Writer)
45 : ObjDumper(Writer)
46 , Obj(Obj) {
47 cacheRelocations();
48 }
49
Craig Topper73156022014-03-02 09:09:27 +000050 virtual void printFileHeaders() override;
51 virtual void printSections() override;
52 virtual void printRelocations() override;
53 virtual void printSymbols() override;
54 virtual void printDynamicSymbols() override;
55 virtual void printUnwindInfo() override;
Eric Christopher9cad53c2013-04-03 18:31:38 +000056
57private:
Alexey Samsonov27dc8392014-03-18 06:53:02 +000058 void printSymbol(const SymbolRef &Sym);
59 void printRelocation(const SectionRef &Section, const RelocationRef &Reloc);
Rui Ueyamaed64342b2013-07-19 23:23:29 +000060 void printDataDirectory(uint32_t Index, const std::string &FieldName);
Eric Christopher9cad53c2013-04-03 18:31:38 +000061 void printX64UnwindInfo();
62
Rui Ueyama10ed9dd2014-01-26 04:15:52 +000063 template <class PEHeader> void printPEHeader(const PEHeader *Hdr);
64 void printBaseOfDataField(const pe32_header *Hdr);
65 void printBaseOfDataField(const pe32plus_header *Hdr);
66
Eric Christopher9cad53c2013-04-03 18:31:38 +000067 void printRuntimeFunction(
68 const RuntimeFunction& RTF,
69 uint64_t OffsetInSection,
70 const std::vector<RelocationRef> &Rels);
71
72 void printUnwindInfo(
73 const Win64EH::UnwindInfo& UI,
74 uint64_t OffsetInSection,
75 const std::vector<RelocationRef> &Rels);
76
Alexey Samsonov27dc8392014-03-18 06:53:02 +000077 void printUnwindCode(const Win64EH::UnwindInfo &UI, ArrayRef<UnwindCode> UCs);
Eric Christopher9cad53c2013-04-03 18:31:38 +000078
Alexey Samsonov27dc8392014-03-18 06:53:02 +000079 void printCodeViewLineTables(const SectionRef &Section);
Timur Iskhodzhanov48703be2013-12-19 11:37:14 +000080
Eric Christopher9cad53c2013-04-03 18:31:38 +000081 void cacheRelocations();
82
83 error_code getSectionContents(
84 const std::vector<RelocationRef> &Rels,
85 uint64_t Offset,
86 ArrayRef<uint8_t> &Contents,
87 uint64_t &Addr);
88
89 error_code getSection(
90 const std::vector<RelocationRef> &Rels,
91 uint64_t Offset,
92 const coff_section **Section,
93 uint64_t *AddrPtr);
94
95 typedef DenseMap<const coff_section*, std::vector<RelocationRef> > RelocMapTy;
96
97 const llvm::object::COFFObjectFile *Obj;
98 RelocMapTy RelocMap;
99 std::vector<RelocationRef> EmptyRelocs;
100};
101
102} // namespace
103
104
105namespace llvm {
106
Ahmed Charles56440fd2014-03-06 05:51:42 +0000107error_code createCOFFDumper(const object::ObjectFile *Obj, StreamWriter &Writer,
108 std::unique_ptr<ObjDumper> &Result) {
Eric Christopher9cad53c2013-04-03 18:31:38 +0000109 const COFFObjectFile *COFFObj = dyn_cast<COFFObjectFile>(Obj);
110 if (!COFFObj)
111 return readobj_error::unsupported_obj_file_format;
112
113 Result.reset(new COFFDumper(COFFObj, Writer));
114 return readobj_error::success;
115}
116
117} // namespace llvm
118
119
120// Returns the name of the unwind code.
121static StringRef getUnwindCodeTypeName(uint8_t Code) {
122 switch(Code) {
123 default: llvm_unreachable("Invalid unwind code");
124 case UOP_PushNonVol: return "PUSH_NONVOL";
125 case UOP_AllocLarge: return "ALLOC_LARGE";
126 case UOP_AllocSmall: return "ALLOC_SMALL";
127 case UOP_SetFPReg: return "SET_FPREG";
128 case UOP_SaveNonVol: return "SAVE_NONVOL";
129 case UOP_SaveNonVolBig: return "SAVE_NONVOL_FAR";
130 case UOP_SaveXMM128: return "SAVE_XMM128";
131 case UOP_SaveXMM128Big: return "SAVE_XMM128_FAR";
132 case UOP_PushMachFrame: return "PUSH_MACHFRAME";
133 }
134}
135
136// Returns the name of a referenced register.
137static StringRef getUnwindRegisterName(uint8_t Reg) {
138 switch(Reg) {
139 default: llvm_unreachable("Invalid register");
140 case 0: return "RAX";
141 case 1: return "RCX";
142 case 2: return "RDX";
143 case 3: return "RBX";
144 case 4: return "RSP";
145 case 5: return "RBP";
146 case 6: return "RSI";
147 case 7: return "RDI";
148 case 8: return "R8";
149 case 9: return "R9";
150 case 10: return "R10";
151 case 11: return "R11";
152 case 12: return "R12";
153 case 13: return "R13";
154 case 14: return "R14";
155 case 15: return "R15";
156 }
157}
158
159// Calculates the number of array slots required for the unwind code.
160static unsigned getNumUsedSlots(const UnwindCode &UnwindCode) {
161 switch (UnwindCode.getUnwindOp()) {
162 default: llvm_unreachable("Invalid unwind code");
163 case UOP_PushNonVol:
164 case UOP_AllocSmall:
165 case UOP_SetFPReg:
166 case UOP_PushMachFrame:
167 return 1;
168 case UOP_SaveNonVol:
169 case UOP_SaveXMM128:
170 return 2;
171 case UOP_SaveNonVolBig:
172 case UOP_SaveXMM128Big:
173 return 3;
174 case UOP_AllocLarge:
175 return (UnwindCode.getOpInfo() == 0) ? 2 : 3;
176 }
177}
178
179// Given a symbol sym this functions returns the address and section of it.
180static error_code resolveSectionAndAddress(const COFFObjectFile *Obj,
181 const SymbolRef &Sym,
182 const coff_section *&ResolvedSection,
183 uint64_t &ResolvedAddr) {
184 if (error_code EC = Sym.getAddress(ResolvedAddr))
185 return EC;
186
Rafael Espindolab5155a52014-02-10 20:24:04 +0000187 section_iterator iter(Obj->section_begin());
Eric Christopher9cad53c2013-04-03 18:31:38 +0000188 if (error_code EC = Sym.getSection(iter))
189 return EC;
190
Alexey Samsonov27dc8392014-03-18 06:53:02 +0000191 ResolvedSection = Obj->getCOFFSection(*iter);
Eric Christopher9cad53c2013-04-03 18:31:38 +0000192 return object_error::success;
193}
194
195// Given a vector of relocations for a section and an offset into this section
196// the function returns the symbol used for the relocation at the offset.
197static error_code resolveSymbol(const std::vector<RelocationRef> &Rels,
198 uint64_t Offset, SymbolRef &Sym) {
Saleem Abdulrasool4a6f5832014-05-20 05:18:06 +0000199 for (const auto &Relocation : Rels) {
Eric Christopher9cad53c2013-04-03 18:31:38 +0000200 uint64_t Ofs;
Saleem Abdulrasool4a6f5832014-05-20 05:18:06 +0000201 if (error_code EC = Relocation.getOffset(Ofs))
Eric Christopher9cad53c2013-04-03 18:31:38 +0000202 return EC;
203
204 if (Ofs == Offset) {
Saleem Abdulrasool4a6f5832014-05-20 05:18:06 +0000205 Sym = *Relocation.getSymbol();
Eric Christopher9cad53c2013-04-03 18:31:38 +0000206 return readobj_error::success;
207 }
208 }
209
210 return readobj_error::unknown_symbol;
211}
212
213// Given a vector of relocations for a section and an offset into this section
214// the function returns the name of the symbol used for the relocation at the
215// offset.
216static error_code resolveSymbolName(const std::vector<RelocationRef> &Rels,
217 uint64_t Offset, StringRef &Name) {
218 SymbolRef Sym;
219 if (error_code EC = resolveSymbol(Rels, Offset, Sym)) return EC;
220 if (error_code EC = Sym.getName(Name)) return EC;
221 return object_error::success;
222}
223
224static const EnumEntry<COFF::MachineTypes> ImageFileMachineType[] = {
225 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_UNKNOWN ),
226 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_AM33 ),
227 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_AMD64 ),
228 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_ARM ),
Saleem Abdulrasool5e1780e2014-03-11 03:08:37 +0000229 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_ARMNT ),
Eric Christopher9cad53c2013-04-03 18:31:38 +0000230 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_EBC ),
231 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_I386 ),
232 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_IA64 ),
233 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_M32R ),
234 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_MIPS16 ),
235 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_MIPSFPU ),
236 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_MIPSFPU16),
237 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_POWERPC ),
238 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_POWERPCFP),
239 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_R4000 ),
240 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_SH3 ),
241 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_SH3DSP ),
242 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_SH4 ),
243 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_SH5 ),
244 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_THUMB ),
245 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_WCEMIPSV2)
246};
247
248static const EnumEntry<COFF::Characteristics> ImageFileCharacteristics[] = {
249 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_RELOCS_STRIPPED ),
250 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_EXECUTABLE_IMAGE ),
251 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_LINE_NUMS_STRIPPED ),
252 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_LOCAL_SYMS_STRIPPED ),
253 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_AGGRESSIVE_WS_TRIM ),
254 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_LARGE_ADDRESS_AWARE ),
255 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_BYTES_REVERSED_LO ),
256 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_32BIT_MACHINE ),
257 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_DEBUG_STRIPPED ),
258 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP),
259 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_NET_RUN_FROM_SWAP ),
260 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_SYSTEM ),
261 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_DLL ),
262 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_UP_SYSTEM_ONLY ),
263 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_BYTES_REVERSED_HI )
264};
265
Rui Ueyama82ebd8e2013-06-12 19:10:33 +0000266static const EnumEntry<COFF::WindowsSubsystem> PEWindowsSubsystem[] = {
267 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_UNKNOWN ),
268 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_NATIVE ),
269 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_WINDOWS_GUI ),
270 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_WINDOWS_CUI ),
271 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_POSIX_CUI ),
272 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_WINDOWS_CE_GUI ),
273 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_EFI_APPLICATION ),
274 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER),
275 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER ),
276 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_EFI_ROM ),
277 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_XBOX ),
278};
279
280static const EnumEntry<COFF::DLLCharacteristics> PEDLLCharacteristics[] = {
Rui Ueyama06dc5e72014-01-27 04:22:24 +0000281 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA ),
Rui Ueyama82ebd8e2013-06-12 19:10:33 +0000282 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE ),
283 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY ),
284 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_NX_COMPAT ),
285 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_NO_ISOLATION ),
286 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_NO_SEH ),
287 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_NO_BIND ),
288 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_WDM_DRIVER ),
289 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_TERMINAL_SERVER_AWARE),
290};
291
Eric Christopher9cad53c2013-04-03 18:31:38 +0000292static const EnumEntry<COFF::SectionCharacteristics>
293ImageSectionCharacteristics[] = {
294 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_TYPE_NO_PAD ),
295 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_CNT_CODE ),
296 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_CNT_INITIALIZED_DATA ),
297 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_CNT_UNINITIALIZED_DATA),
298 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_OTHER ),
299 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_INFO ),
300 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_REMOVE ),
301 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_COMDAT ),
302 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_GPREL ),
303 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_PURGEABLE ),
304 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_16BIT ),
305 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_LOCKED ),
306 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_PRELOAD ),
307 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_1BYTES ),
308 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_2BYTES ),
309 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_4BYTES ),
310 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_8BYTES ),
311 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_16BYTES ),
312 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_32BYTES ),
313 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_64BYTES ),
314 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_128BYTES ),
315 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_256BYTES ),
316 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_512BYTES ),
317 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_1024BYTES ),
318 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_2048BYTES ),
319 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_4096BYTES ),
320 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_8192BYTES ),
321 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_NRELOC_OVFL ),
322 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_DISCARDABLE ),
323 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_NOT_CACHED ),
324 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_NOT_PAGED ),
325 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_SHARED ),
326 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_EXECUTE ),
327 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_READ ),
328 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_WRITE )
329};
330
331static const EnumEntry<COFF::SymbolBaseType> ImageSymType[] = {
332 { "Null" , COFF::IMAGE_SYM_TYPE_NULL },
333 { "Void" , COFF::IMAGE_SYM_TYPE_VOID },
334 { "Char" , COFF::IMAGE_SYM_TYPE_CHAR },
335 { "Short" , COFF::IMAGE_SYM_TYPE_SHORT },
336 { "Int" , COFF::IMAGE_SYM_TYPE_INT },
337 { "Long" , COFF::IMAGE_SYM_TYPE_LONG },
338 { "Float" , COFF::IMAGE_SYM_TYPE_FLOAT },
339 { "Double", COFF::IMAGE_SYM_TYPE_DOUBLE },
340 { "Struct", COFF::IMAGE_SYM_TYPE_STRUCT },
341 { "Union" , COFF::IMAGE_SYM_TYPE_UNION },
342 { "Enum" , COFF::IMAGE_SYM_TYPE_ENUM },
343 { "MOE" , COFF::IMAGE_SYM_TYPE_MOE },
344 { "Byte" , COFF::IMAGE_SYM_TYPE_BYTE },
345 { "Word" , COFF::IMAGE_SYM_TYPE_WORD },
346 { "UInt" , COFF::IMAGE_SYM_TYPE_UINT },
347 { "DWord" , COFF::IMAGE_SYM_TYPE_DWORD }
348};
349
350static const EnumEntry<COFF::SymbolComplexType> ImageSymDType[] = {
351 { "Null" , COFF::IMAGE_SYM_DTYPE_NULL },
352 { "Pointer" , COFF::IMAGE_SYM_DTYPE_POINTER },
353 { "Function", COFF::IMAGE_SYM_DTYPE_FUNCTION },
354 { "Array" , COFF::IMAGE_SYM_DTYPE_ARRAY }
355};
356
357static const EnumEntry<COFF::SymbolStorageClass> ImageSymClass[] = {
358 { "EndOfFunction" , COFF::IMAGE_SYM_CLASS_END_OF_FUNCTION },
359 { "Null" , COFF::IMAGE_SYM_CLASS_NULL },
360 { "Automatic" , COFF::IMAGE_SYM_CLASS_AUTOMATIC },
361 { "External" , COFF::IMAGE_SYM_CLASS_EXTERNAL },
362 { "Static" , COFF::IMAGE_SYM_CLASS_STATIC },
363 { "Register" , COFF::IMAGE_SYM_CLASS_REGISTER },
364 { "ExternalDef" , COFF::IMAGE_SYM_CLASS_EXTERNAL_DEF },
365 { "Label" , COFF::IMAGE_SYM_CLASS_LABEL },
366 { "UndefinedLabel" , COFF::IMAGE_SYM_CLASS_UNDEFINED_LABEL },
367 { "MemberOfStruct" , COFF::IMAGE_SYM_CLASS_MEMBER_OF_STRUCT },
368 { "Argument" , COFF::IMAGE_SYM_CLASS_ARGUMENT },
369 { "StructTag" , COFF::IMAGE_SYM_CLASS_STRUCT_TAG },
370 { "MemberOfUnion" , COFF::IMAGE_SYM_CLASS_MEMBER_OF_UNION },
371 { "UnionTag" , COFF::IMAGE_SYM_CLASS_UNION_TAG },
372 { "TypeDefinition" , COFF::IMAGE_SYM_CLASS_TYPE_DEFINITION },
373 { "UndefinedStatic", COFF::IMAGE_SYM_CLASS_UNDEFINED_STATIC },
374 { "EnumTag" , COFF::IMAGE_SYM_CLASS_ENUM_TAG },
375 { "MemberOfEnum" , COFF::IMAGE_SYM_CLASS_MEMBER_OF_ENUM },
376 { "RegisterParam" , COFF::IMAGE_SYM_CLASS_REGISTER_PARAM },
377 { "BitField" , COFF::IMAGE_SYM_CLASS_BIT_FIELD },
378 { "Block" , COFF::IMAGE_SYM_CLASS_BLOCK },
379 { "Function" , COFF::IMAGE_SYM_CLASS_FUNCTION },
380 { "EndOfStruct" , COFF::IMAGE_SYM_CLASS_END_OF_STRUCT },
381 { "File" , COFF::IMAGE_SYM_CLASS_FILE },
382 { "Section" , COFF::IMAGE_SYM_CLASS_SECTION },
383 { "WeakExternal" , COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL },
384 { "CLRToken" , COFF::IMAGE_SYM_CLASS_CLR_TOKEN }
385};
386
387static const EnumEntry<COFF::COMDATType> ImageCOMDATSelect[] = {
388 { "NoDuplicates", COFF::IMAGE_COMDAT_SELECT_NODUPLICATES },
389 { "Any" , COFF::IMAGE_COMDAT_SELECT_ANY },
390 { "SameSize" , COFF::IMAGE_COMDAT_SELECT_SAME_SIZE },
391 { "ExactMatch" , COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH },
392 { "Associative" , COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE },
393 { "Largest" , COFF::IMAGE_COMDAT_SELECT_LARGEST },
394 { "Newest" , COFF::IMAGE_COMDAT_SELECT_NEWEST }
395};
396
397static const EnumEntry<COFF::WeakExternalCharacteristics>
398WeakExternalCharacteristics[] = {
399 { "NoLibrary", COFF::IMAGE_WEAK_EXTERN_SEARCH_NOLIBRARY },
400 { "Library" , COFF::IMAGE_WEAK_EXTERN_SEARCH_LIBRARY },
401 { "Alias" , COFF::IMAGE_WEAK_EXTERN_SEARCH_ALIAS }
402};
403
404static const EnumEntry<unsigned> UnwindFlags[] = {
405 { "ExceptionHandler", Win64EH::UNW_ExceptionHandler },
406 { "TerminateHandler", Win64EH::UNW_TerminateHandler },
407 { "ChainInfo" , Win64EH::UNW_ChainInfo }
408};
409
410static const EnumEntry<unsigned> UnwindOpInfo[] = {
411 { "RAX", 0 },
412 { "RCX", 1 },
413 { "RDX", 2 },
414 { "RBX", 3 },
415 { "RSP", 4 },
416 { "RBP", 5 },
417 { "RSI", 6 },
418 { "RDI", 7 },
419 { "R8", 8 },
420 { "R9", 9 },
421 { "R10", 10 },
422 { "R11", 11 },
423 { "R12", 12 },
424 { "R13", 13 },
425 { "R14", 14 },
426 { "R15", 15 }
427};
428
Eric Christopher9cad53c2013-04-03 18:31:38 +0000429static uint64_t getOffsetOfLSDA(const Win64EH::UnwindInfo& UI) {
430 return static_cast<const char*>(UI.getLanguageSpecificData())
431 - reinterpret_cast<const char*>(&UI);
432}
433
434static uint32_t getLargeSlotValue(ArrayRef<UnwindCode> UCs) {
435 if (UCs.size() < 3)
436 return 0;
437
438 return UCs[1].FrameOffset + (static_cast<uint32_t>(UCs[2].FrameOffset) << 16);
439}
440
441template<typename T>
442static error_code getSymbolAuxData(const COFFObjectFile *Obj,
443 const coff_symbol *Symbol, const T* &Aux) {
444 ArrayRef<uint8_t> AuxData = Obj->getSymbolAuxData(Symbol);
445 Aux = reinterpret_cast<const T*>(AuxData.data());
446 return readobj_error::success;
447}
448
449static std::string formatSymbol(const std::vector<RelocationRef> &Rels,
450 uint64_t Offset, uint32_t Disp) {
451 std::string Buffer;
452 raw_string_ostream Str(Buffer);
453
454 StringRef Sym;
455 if (resolveSymbolName(Rels, Offset, Sym)) {
Benjamin Kramer48b6a882013-07-06 20:01:46 +0000456 Str << format(" (0x%" PRIX64 ")", Offset);
Eric Christopher9cad53c2013-04-03 18:31:38 +0000457 return Str.str();
458 }
459
460 Str << Sym;
461 if (Disp > 0) {
Benjamin Kramer48b6a882013-07-06 20:01:46 +0000462 Str << format(" +0x%X (0x%" PRIX64 ")", Disp, Offset);
Eric Christopher9cad53c2013-04-03 18:31:38 +0000463 } else {
Benjamin Kramer48b6a882013-07-06 20:01:46 +0000464 Str << format(" (0x%" PRIX64 ")", Offset);
Eric Christopher9cad53c2013-04-03 18:31:38 +0000465 }
466
467 return Str.str();
468}
469
470// Given a vector of relocations for a section and an offset into this section
471// the function resolves the symbol used for the relocation at the offset and
472// returns the section content and the address inside the content pointed to
473// by the symbol.
474error_code COFFDumper::getSectionContents(
475 const std::vector<RelocationRef> &Rels, uint64_t Offset,
476 ArrayRef<uint8_t> &Contents, uint64_t &Addr) {
477
478 SymbolRef Sym;
479 const coff_section *Section;
480
481 if (error_code EC = resolveSymbol(Rels, Offset, Sym))
482 return EC;
483 if (error_code EC = resolveSectionAndAddress(Obj, Sym, Section, Addr))
484 return EC;
485 if (error_code EC = Obj->getSectionContents(Section, Contents))
486 return EC;
487
488 return object_error::success;
489}
490
491error_code COFFDumper::getSection(
492 const std::vector<RelocationRef> &Rels, uint64_t Offset,
493 const coff_section **SectionPtr, uint64_t *AddrPtr) {
494
495 SymbolRef Sym;
496 if (error_code EC = resolveSymbol(Rels, Offset, Sym))
497 return EC;
498
499 const coff_section *Section;
500 uint64_t Addr;
501 if (error_code EC = resolveSectionAndAddress(Obj, Sym, Section, Addr))
502 return EC;
503
504 if (SectionPtr)
505 *SectionPtr = Section;
506 if (AddrPtr)
507 *AddrPtr = Addr;
508
509 return object_error::success;
510}
511
512void COFFDumper::cacheRelocations() {
Alexey Samsonov27dc8392014-03-18 06:53:02 +0000513 for (const SectionRef &S : Obj->sections()) {
514 const coff_section *Section = Obj->getCOFFSection(S);
Eric Christopher9cad53c2013-04-03 18:31:38 +0000515
Alexey Samsonov27dc8392014-03-18 06:53:02 +0000516 for (const RelocationRef &Reloc : S.relocations())
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000517 RelocMap[Section].push_back(Reloc);
Eric Christopher9cad53c2013-04-03 18:31:38 +0000518
519 // Sort relocations by address.
520 std::sort(RelocMap[Section].begin(), RelocMap[Section].end(),
521 relocAddressLess);
522 }
523}
524
Rui Ueyamaed64342b2013-07-19 23:23:29 +0000525void COFFDumper::printDataDirectory(uint32_t Index, const std::string &FieldName) {
526 const data_directory *Data;
527 if (Obj->getDataDirectory(Index, Data))
528 return;
529 W.printHex(FieldName + "RVA", Data->RelativeVirtualAddress);
530 W.printHex(FieldName + "Size", Data->Size);
531}
532
Eric Christopher9cad53c2013-04-03 18:31:38 +0000533void COFFDumper::printFileHeaders() {
Rui Ueyama82ebd8e2013-06-12 19:10:33 +0000534 // Print COFF header
Craig Toppere6cb63e2014-04-25 04:24:47 +0000535 const coff_file_header *COFFHeader = nullptr;
Rui Ueyama82ebd8e2013-06-12 19:10:33 +0000536 if (error(Obj->getCOFFHeader(COFFHeader)))
Eric Christopher9cad53c2013-04-03 18:31:38 +0000537 return;
538
Rui Ueyama82ebd8e2013-06-12 19:10:33 +0000539 time_t TDS = COFFHeader->TimeDateStamp;
Eric Christopher9cad53c2013-04-03 18:31:38 +0000540 char FormattedTime[20] = { };
541 strftime(FormattedTime, 20, "%Y-%m-%d %H:%M:%S", gmtime(&TDS));
542
543 {
544 DictScope D(W, "ImageFileHeader");
Rui Ueyama82ebd8e2013-06-12 19:10:33 +0000545 W.printEnum ("Machine", COFFHeader->Machine,
Eric Christopher9cad53c2013-04-03 18:31:38 +0000546 makeArrayRef(ImageFileMachineType));
Rui Ueyama82ebd8e2013-06-12 19:10:33 +0000547 W.printNumber("SectionCount", COFFHeader->NumberOfSections);
548 W.printHex ("TimeDateStamp", FormattedTime, COFFHeader->TimeDateStamp);
549 W.printHex ("PointerToSymbolTable", COFFHeader->PointerToSymbolTable);
550 W.printNumber("SymbolCount", COFFHeader->NumberOfSymbols);
551 W.printNumber("OptionalHeaderSize", COFFHeader->SizeOfOptionalHeader);
552 W.printFlags ("Characteristics", COFFHeader->Characteristics,
Eric Christopher9cad53c2013-04-03 18:31:38 +0000553 makeArrayRef(ImageFileCharacteristics));
554 }
Rui Ueyama82ebd8e2013-06-12 19:10:33 +0000555
556 // Print PE header. This header does not exist if this is an object file and
557 // not an executable.
Craig Toppere6cb63e2014-04-25 04:24:47 +0000558 const pe32_header *PEHeader = nullptr;
Rui Ueyama82ebd8e2013-06-12 19:10:33 +0000559 if (error(Obj->getPE32Header(PEHeader)))
560 return;
Rui Ueyama10ed9dd2014-01-26 04:15:52 +0000561 if (PEHeader)
562 printPEHeader<pe32_header>(PEHeader);
Rui Ueyama82ebd8e2013-06-12 19:10:33 +0000563
Craig Toppere6cb63e2014-04-25 04:24:47 +0000564 const pe32plus_header *PEPlusHeader = nullptr;
Rui Ueyama10ed9dd2014-01-26 04:15:52 +0000565 if (error(Obj->getPE32PlusHeader(PEPlusHeader)))
566 return;
567 if (PEPlusHeader)
568 printPEHeader<pe32plus_header>(PEPlusHeader);
569}
Rui Ueyamaed64342b2013-07-19 23:23:29 +0000570
Rui Ueyama10ed9dd2014-01-26 04:15:52 +0000571template <class PEHeader>
572void COFFDumper::printPEHeader(const PEHeader *Hdr) {
573 DictScope D(W, "ImageOptionalHeader");
574 W.printNumber("MajorLinkerVersion", Hdr->MajorLinkerVersion);
575 W.printNumber("MinorLinkerVersion", Hdr->MinorLinkerVersion);
576 W.printNumber("SizeOfCode", Hdr->SizeOfCode);
577 W.printNumber("SizeOfInitializedData", Hdr->SizeOfInitializedData);
578 W.printNumber("SizeOfUninitializedData", Hdr->SizeOfUninitializedData);
579 W.printHex ("AddressOfEntryPoint", Hdr->AddressOfEntryPoint);
580 W.printHex ("BaseOfCode", Hdr->BaseOfCode);
581 printBaseOfDataField(Hdr);
582 W.printHex ("ImageBase", Hdr->ImageBase);
583 W.printNumber("SectionAlignment", Hdr->SectionAlignment);
584 W.printNumber("FileAlignment", Hdr->FileAlignment);
585 W.printNumber("MajorOperatingSystemVersion",
586 Hdr->MajorOperatingSystemVersion);
587 W.printNumber("MinorOperatingSystemVersion",
588 Hdr->MinorOperatingSystemVersion);
589 W.printNumber("MajorImageVersion", Hdr->MajorImageVersion);
590 W.printNumber("MinorImageVersion", Hdr->MinorImageVersion);
591 W.printNumber("MajorSubsystemVersion", Hdr->MajorSubsystemVersion);
592 W.printNumber("MinorSubsystemVersion", Hdr->MinorSubsystemVersion);
593 W.printNumber("SizeOfImage", Hdr->SizeOfImage);
594 W.printNumber("SizeOfHeaders", Hdr->SizeOfHeaders);
595 W.printEnum ("Subsystem", Hdr->Subsystem, makeArrayRef(PEWindowsSubsystem));
596 W.printFlags ("Subsystem", Hdr->DLLCharacteristics,
597 makeArrayRef(PEDLLCharacteristics));
598 W.printNumber("SizeOfStackReserve", Hdr->SizeOfStackReserve);
599 W.printNumber("SizeOfStackCommit", Hdr->SizeOfStackCommit);
600 W.printNumber("SizeOfHeapReserve", Hdr->SizeOfHeapReserve);
601 W.printNumber("SizeOfHeapCommit", Hdr->SizeOfHeapCommit);
602 W.printNumber("NumberOfRvaAndSize", Hdr->NumberOfRvaAndSize);
Rui Ueyamaed64342b2013-07-19 23:23:29 +0000603
Rui Ueyama10ed9dd2014-01-26 04:15:52 +0000604 if (Hdr->NumberOfRvaAndSize > 0) {
605 DictScope D(W, "DataDirectory");
606 static const char * const directory[] = {
607 "ExportTable", "ImportTable", "ResourceTable", "ExceptionTable",
608 "CertificateTable", "BaseRelocationTable", "Debug", "Architecture",
609 "GlobalPtr", "TLSTable", "LoadConfigTable", "BoundImport", "IAT",
610 "DelayImportDescriptor", "CLRRuntimeHeader", "Reserved"
611 };
612
613 for (uint32_t i = 0; i < Hdr->NumberOfRvaAndSize; ++i) {
614 printDataDirectory(i, directory[i]);
Rui Ueyamaed64342b2013-07-19 23:23:29 +0000615 }
Rui Ueyama82ebd8e2013-06-12 19:10:33 +0000616 }
Eric Christopher9cad53c2013-04-03 18:31:38 +0000617}
618
Rui Ueyama10ed9dd2014-01-26 04:15:52 +0000619void COFFDumper::printBaseOfDataField(const pe32_header *Hdr) {
620 W.printHex("BaseOfData", Hdr->BaseOfData);
621}
622
623void COFFDumper::printBaseOfDataField(const pe32plus_header *) {}
624
Alexey Samsonov27dc8392014-03-18 06:53:02 +0000625void COFFDumper::printCodeViewLineTables(const SectionRef &Section) {
Timur Iskhodzhanov48703be2013-12-19 11:37:14 +0000626 StringRef Data;
Alexey Samsonov27dc8392014-03-18 06:53:02 +0000627 if (error(Section.getContents(Data)))
628 return;
Timur Iskhodzhanov48703be2013-12-19 11:37:14 +0000629
630 SmallVector<StringRef, 10> FunctionNames;
631 StringMap<StringRef> FunctionLineTables;
632 StringRef FileIndexToStringOffsetTable;
633 StringRef StringTable;
634
635 ListScope D(W, "CodeViewLineTables");
636 {
637 DataExtractor DE(Data, true, 4);
638 uint32_t Offset = 0,
639 Magic = DE.getU32(&Offset);
640 W.printHex("Magic", Magic);
641 if (Magic != COFF::DEBUG_SECTION_MAGIC) {
642 error(object_error::parse_failed);
643 return;
644 }
645
646 bool Finished = false;
647 while (DE.isValidOffset(Offset) && !Finished) {
648 // The section consists of a number of subsection in the following format:
649 // |Type|PayloadSize|Payload...|
650 uint32_t SubSectionType = DE.getU32(&Offset),
651 PayloadSize = DE.getU32(&Offset);
652 ListScope S(W, "Subsection");
653 W.printHex("Type", SubSectionType);
654 W.printHex("PayloadSize", PayloadSize);
655 if (PayloadSize > Data.size() - Offset) {
656 error(object_error::parse_failed);
657 return;
658 }
659
660 // Print the raw contents to simplify debugging if anything goes wrong
661 // afterwards.
662 StringRef Contents = Data.substr(Offset, PayloadSize);
663 W.printBinaryBlock("Contents", Contents);
664
665 switch (SubSectionType) {
666 case COFF::DEBUG_LINE_TABLE_SUBSECTION: {
667 // Holds a PC to file:line table. Some data to parse this subsection is
668 // stored in the other subsections, so just check sanity and store the
669 // pointers for deferred processing.
670
671 if (PayloadSize < 12) {
672 // There should be at least three words to store two function
673 // relocations and size of the code.
674 error(object_error::parse_failed);
675 return;
676 }
677
678 StringRef FunctionName;
Alexey Samsonov27dc8392014-03-18 06:53:02 +0000679 if (error(resolveSymbolName(RelocMap[Obj->getCOFFSection(Section)],
680 Offset, FunctionName)))
Timur Iskhodzhanov48703be2013-12-19 11:37:14 +0000681 return;
682 W.printString("FunctionName", FunctionName);
683 if (FunctionLineTables.count(FunctionName) != 0) {
684 // Saw debug info for this function already?
685 error(object_error::parse_failed);
686 return;
687 }
688
689 FunctionLineTables[FunctionName] = Contents;
690 FunctionNames.push_back(FunctionName);
691 break;
692 }
693 case COFF::DEBUG_STRING_TABLE_SUBSECTION:
Craig Toppere6cb63e2014-04-25 04:24:47 +0000694 if (PayloadSize == 0 || StringTable.data() != nullptr ||
Timur Iskhodzhanov48703be2013-12-19 11:37:14 +0000695 Contents.back() != '\0') {
696 // Empty or duplicate or non-null-terminated subsection.
697 error(object_error::parse_failed);
698 return;
699 }
700 StringTable = Contents;
701 break;
702 case COFF::DEBUG_INDEX_SUBSECTION:
703 // Holds the translation table from file indices
704 // to offsets in the string table.
705
Craig Toppere6cb63e2014-04-25 04:24:47 +0000706 if (PayloadSize == 0 ||
707 FileIndexToStringOffsetTable.data() != nullptr) {
Timur Iskhodzhanov48703be2013-12-19 11:37:14 +0000708 // Empty or duplicate subsection.
709 error(object_error::parse_failed);
710 return;
711 }
712 FileIndexToStringOffsetTable = Contents;
713 break;
714 }
715 Offset += PayloadSize;
716
717 // Align the reading pointer by 4.
718 Offset += (-Offset) % 4;
719 }
720 }
721
722 // Dump the line tables now that we've read all the subsections and know all
723 // the required information.
724 for (unsigned I = 0, E = FunctionNames.size(); I != E; ++I) {
725 StringRef Name = FunctionNames[I];
726 ListScope S(W, "FunctionLineTable");
727 W.printString("FunctionName", Name);
728
729 DataExtractor DE(FunctionLineTables[Name], true, 4);
730 uint32_t Offset = 8; // Skip relocations.
731 uint32_t FunctionSize = DE.getU32(&Offset);
732 W.printHex("CodeSize", FunctionSize);
733 while (DE.isValidOffset(Offset)) {
734 // For each range of lines with the same filename, we have a segment
735 // in the line table. The filename string is accessed using double
736 // indirection to the string table subsection using the index subsection.
737 uint32_t OffsetInIndex = DE.getU32(&Offset),
738 SegmentLength = DE.getU32(&Offset),
739 FullSegmentSize = DE.getU32(&Offset);
740 if (FullSegmentSize != 12 + 8 * SegmentLength) {
741 error(object_error::parse_failed);
742 return;
743 }
744
745 uint32_t FilenameOffset;
746 {
747 DataExtractor SDE(FileIndexToStringOffsetTable, true, 4);
748 uint32_t OffsetInSDE = OffsetInIndex;
749 if (!SDE.isValidOffset(OffsetInSDE)) {
750 error(object_error::parse_failed);
751 return;
752 }
753 FilenameOffset = SDE.getU32(&OffsetInSDE);
754 }
755
756 if (FilenameOffset == 0 || FilenameOffset + 1 >= StringTable.size() ||
757 StringTable.data()[FilenameOffset - 1] != '\0') {
758 // Each string in an F3 subsection should be preceded by a null
759 // character.
760 error(object_error::parse_failed);
761 return;
762 }
763
764 StringRef Filename(StringTable.data() + FilenameOffset);
765 ListScope S(W, "FilenameSegment");
766 W.printString("Filename", Filename);
767 for (unsigned J = 0; J != SegmentLength && DE.isValidOffset(Offset);
768 ++J) {
769 // Then go the (PC, LineNumber) pairs. The line number is stored in the
770 // least significant 31 bits of the respective word in the table.
771 uint32_t PC = DE.getU32(&Offset),
772 LineNumber = DE.getU32(&Offset) & 0x7fffffff;
773 if (PC >= FunctionSize) {
774 error(object_error::parse_failed);
775 return;
776 }
777 char Buffer[32];
778 format("+0x%X", PC).snprint(Buffer, 32);
779 W.printNumber(Buffer, LineNumber);
780 }
781 }
782 }
783}
784
Eric Christopher9cad53c2013-04-03 18:31:38 +0000785void COFFDumper::printSections() {
Eric Christopher9cad53c2013-04-03 18:31:38 +0000786 ListScope SectionsD(W, "Sections");
787 int SectionNumber = 0;
Alexey Samsonov27dc8392014-03-18 06:53:02 +0000788 for (const SectionRef &Sec : Obj->sections()) {
Eric Christopher9cad53c2013-04-03 18:31:38 +0000789 ++SectionNumber;
Alexey Samsonov27dc8392014-03-18 06:53:02 +0000790 const coff_section *Section = Obj->getCOFFSection(Sec);
Eric Christopher9cad53c2013-04-03 18:31:38 +0000791
792 StringRef Name;
Alexey Samsonov27dc8392014-03-18 06:53:02 +0000793 if (error(Sec.getName(Name)))
794 Name = "";
Eric Christopher9cad53c2013-04-03 18:31:38 +0000795
796 DictScope D(W, "Section");
797 W.printNumber("Number", SectionNumber);
798 W.printBinary("Name", Name, Section->Name);
799 W.printHex ("VirtualSize", Section->VirtualSize);
800 W.printHex ("VirtualAddress", Section->VirtualAddress);
801 W.printNumber("RawDataSize", Section->SizeOfRawData);
802 W.printHex ("PointerToRawData", Section->PointerToRawData);
803 W.printHex ("PointerToRelocations", Section->PointerToRelocations);
804 W.printHex ("PointerToLineNumbers", Section->PointerToLinenumbers);
805 W.printNumber("RelocationCount", Section->NumberOfRelocations);
806 W.printNumber("LineNumberCount", Section->NumberOfLinenumbers);
807 W.printFlags ("Characteristics", Section->Characteristics,
808 makeArrayRef(ImageSectionCharacteristics),
809 COFF::SectionCharacteristics(0x00F00000));
810
811 if (opts::SectionRelocations) {
812 ListScope D(W, "Relocations");
Alexey Samsonov27dc8392014-03-18 06:53:02 +0000813 for (const RelocationRef &Reloc : Sec.relocations())
814 printRelocation(Sec, Reloc);
Eric Christopher9cad53c2013-04-03 18:31:38 +0000815 }
816
817 if (opts::SectionSymbols) {
818 ListScope D(W, "Symbols");
Alexey Samsonov27dc8392014-03-18 06:53:02 +0000819 for (const SymbolRef &Symbol : Obj->symbols()) {
Eric Christopher9cad53c2013-04-03 18:31:38 +0000820 bool Contained = false;
Alexey Samsonov27dc8392014-03-18 06:53:02 +0000821 if (Sec.containsSymbol(Symbol, Contained) || !Contained)
Eric Christopher9cad53c2013-04-03 18:31:38 +0000822 continue;
823
Alexey Samsonov27dc8392014-03-18 06:53:02 +0000824 printSymbol(Symbol);
Eric Christopher9cad53c2013-04-03 18:31:38 +0000825 }
826 }
827
Timur Iskhodzhanov48703be2013-12-19 11:37:14 +0000828 if (Name == ".debug$S" && opts::CodeViewLineTables)
Alexey Samsonov27dc8392014-03-18 06:53:02 +0000829 printCodeViewLineTables(Sec);
Timur Iskhodzhanov48703be2013-12-19 11:37:14 +0000830
Eric Christopher9cad53c2013-04-03 18:31:38 +0000831 if (opts::SectionData) {
832 StringRef Data;
Alexey Samsonov27dc8392014-03-18 06:53:02 +0000833 if (error(Sec.getContents(Data)))
834 break;
Eric Christopher9cad53c2013-04-03 18:31:38 +0000835
836 W.printBinaryBlock("SectionData", Data);
837 }
838 }
839}
840
841void COFFDumper::printRelocations() {
842 ListScope D(W, "Relocations");
843
Eric Christopher9cad53c2013-04-03 18:31:38 +0000844 int SectionNumber = 0;
Alexey Samsonov27dc8392014-03-18 06:53:02 +0000845 for (const SectionRef &Section : Obj->sections()) {
Eric Christopher9cad53c2013-04-03 18:31:38 +0000846 ++SectionNumber;
Eric Christopher9cad53c2013-04-03 18:31:38 +0000847 StringRef Name;
Alexey Samsonov27dc8392014-03-18 06:53:02 +0000848 if (error(Section.getName(Name)))
Eric Christopher9cad53c2013-04-03 18:31:38 +0000849 continue;
850
851 bool PrintedGroup = false;
Alexey Samsonov27dc8392014-03-18 06:53:02 +0000852 for (const RelocationRef &Reloc : Section.relocations()) {
Eric Christopher9cad53c2013-04-03 18:31:38 +0000853 if (!PrintedGroup) {
854 W.startLine() << "Section (" << SectionNumber << ") " << Name << " {\n";
855 W.indent();
856 PrintedGroup = true;
857 }
858
Alexey Samsonov27dc8392014-03-18 06:53:02 +0000859 printRelocation(Section, Reloc);
Eric Christopher9cad53c2013-04-03 18:31:38 +0000860 }
861
862 if (PrintedGroup) {
863 W.unindent();
864 W.startLine() << "}\n";
865 }
866 }
867}
868
Alexey Samsonov27dc8392014-03-18 06:53:02 +0000869void COFFDumper::printRelocation(const SectionRef &Section,
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000870 const RelocationRef &Reloc) {
Eric Christopher9cad53c2013-04-03 18:31:38 +0000871 uint64_t Offset;
872 uint64_t RelocType;
873 SmallString<32> RelocName;
Eric Christopher9cad53c2013-04-03 18:31:38 +0000874 StringRef SymbolName;
875 StringRef Contents;
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000876 if (error(Reloc.getOffset(Offset)))
877 return;
878 if (error(Reloc.getType(RelocType)))
879 return;
880 if (error(Reloc.getTypeName(RelocName)))
881 return;
882 symbol_iterator Symbol = Reloc.getSymbol();
883 if (error(Symbol->getName(SymbolName)))
884 return;
Alexey Samsonov27dc8392014-03-18 06:53:02 +0000885 if (error(Section.getContents(Contents)))
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000886 return;
Eric Christopher9cad53c2013-04-03 18:31:38 +0000887
Nico Rieckf3f0b792013-04-12 04:01:52 +0000888 if (opts::ExpandRelocs) {
889 DictScope Group(W, "Relocation");
890 W.printHex("Offset", Offset);
891 W.printNumber("Type", RelocName, RelocType);
892 W.printString("Symbol", SymbolName.size() > 0 ? SymbolName : "-");
893 } else {
894 raw_ostream& OS = W.startLine();
895 OS << W.hex(Offset)
896 << " " << RelocName
897 << " " << (SymbolName.size() > 0 ? SymbolName : "-")
898 << "\n";
899 }
Eric Christopher9cad53c2013-04-03 18:31:38 +0000900}
901
902void COFFDumper::printSymbols() {
903 ListScope Group(W, "Symbols");
904
Alexey Samsonov27dc8392014-03-18 06:53:02 +0000905 for (const SymbolRef &Symbol : Obj->symbols())
906 printSymbol(Symbol);
Eric Christopher9cad53c2013-04-03 18:31:38 +0000907}
908
Alexey Samsonov27dc8392014-03-18 06:53:02 +0000909void COFFDumper::printDynamicSymbols() { ListScope Group(W, "DynamicSymbols"); }
Eric Christopher9cad53c2013-04-03 18:31:38 +0000910
Alexey Samsonov27dc8392014-03-18 06:53:02 +0000911void COFFDumper::printSymbol(const SymbolRef &Sym) {
Eric Christopher9cad53c2013-04-03 18:31:38 +0000912 DictScope D(W, "Symbol");
913
Alexey Samsonov27dc8392014-03-18 06:53:02 +0000914 const coff_symbol *Symbol = Obj->getCOFFSymbol(Sym);
Eric Christopher9cad53c2013-04-03 18:31:38 +0000915 const coff_section *Section;
916 if (error_code EC = Obj->getSection(Symbol->SectionNumber, Section)) {
917 W.startLine() << "Invalid section number: " << EC.message() << "\n";
918 W.flush();
919 return;
920 }
921
922 StringRef SymbolName;
923 if (Obj->getSymbolName(Symbol, SymbolName))
924 SymbolName = "";
925
Nico Riecka8de6532013-04-22 08:34:46 +0000926 StringRef SectionName = "";
927 if (Section)
928 Obj->getSectionName(Section, SectionName);
Eric Christopher9cad53c2013-04-03 18:31:38 +0000929
930 W.printString("Name", SymbolName);
931 W.printNumber("Value", Symbol->Value);
932 W.printNumber("Section", SectionName, Symbol->SectionNumber);
933 W.printEnum ("BaseType", Symbol->getBaseType(), makeArrayRef(ImageSymType));
934 W.printEnum ("ComplexType", Symbol->getComplexType(),
935 makeArrayRef(ImageSymDType));
936 W.printEnum ("StorageClass", Symbol->StorageClass,
937 makeArrayRef(ImageSymClass));
938 W.printNumber("AuxSymbolCount", Symbol->NumberOfAuxSymbols);
939
940 for (unsigned I = 0; I < Symbol->NumberOfAuxSymbols; ++I) {
David Majnemerddf28f22014-03-19 04:47:47 +0000941 if (Symbol->isFunctionDefinition()) {
Eric Christopher9cad53c2013-04-03 18:31:38 +0000942 const coff_aux_function_definition *Aux;
943 if (error(getSymbolAuxData(Obj, Symbol + I, Aux)))
944 break;
945
946 DictScope AS(W, "AuxFunctionDef");
947 W.printNumber("TagIndex", Aux->TagIndex);
948 W.printNumber("TotalSize", Aux->TotalSize);
David Majnemerf3a2af52014-03-19 04:33:27 +0000949 W.printHex("PointerToLineNumber", Aux->PointerToLinenumber);
Eric Christopher9cad53c2013-04-03 18:31:38 +0000950 W.printHex("PointerToNextFunction", Aux->PointerToNextFunction);
951 W.printBinary("Unused", makeArrayRef(Aux->Unused));
952
David Majnemerddf28f22014-03-19 04:47:47 +0000953 } else if (Symbol->isWeakExternal()) {
David Majnemerf3a2af52014-03-19 04:33:27 +0000954 const coff_aux_weak_external *Aux;
Eric Christopher9cad53c2013-04-03 18:31:38 +0000955 if (error(getSymbolAuxData(Obj, Symbol + I, Aux)))
956 break;
957
958 const coff_symbol *Linked;
959 StringRef LinkedName;
960 error_code EC;
961 if ((EC = Obj->getSymbol(Aux->TagIndex, Linked)) ||
962 (EC = Obj->getSymbolName(Linked, LinkedName))) {
963 LinkedName = "";
964 error(EC);
965 }
966
967 DictScope AS(W, "AuxWeakExternal");
968 W.printNumber("Linked", LinkedName, Aux->TagIndex);
969 W.printEnum ("Search", Aux->Characteristics,
970 makeArrayRef(WeakExternalCharacteristics));
David Majnemerf3a2af52014-03-19 04:33:27 +0000971 W.printBinary("Unused", makeArrayRef(Aux->Unused));
Eric Christopher9cad53c2013-04-03 18:31:38 +0000972
David Majnemerddf28f22014-03-19 04:47:47 +0000973 } else if (Symbol->isFileRecord()) {
Saleem Abdulrasool38103702014-04-13 22:54:15 +0000974 const coff_aux_file *Aux;
Eric Christopher9cad53c2013-04-03 18:31:38 +0000975 if (error(getSymbolAuxData(Obj, Symbol + I, Aux)))
976 break;
977
Nico Rieck0ab8e602013-04-22 08:35:11 +0000978 DictScope AS(W, "AuxFileRecord");
Saleem Abdulrasoold38c6b12014-04-14 02:37:23 +0000979
980 StringRef Name(Aux->FileName,
981 Symbol->NumberOfAuxSymbols * COFF::SymbolSize);
982 W.printString("FileName", Name.rtrim(StringRef("\0", 1)));
Saleem Abdulrasool3b5e0012014-04-16 04:15:29 +0000983 break;
David Majnemerddf28f22014-03-19 04:47:47 +0000984 } else if (Symbol->isSectionDefinition()) {
Eric Christopher9cad53c2013-04-03 18:31:38 +0000985 const coff_aux_section_definition *Aux;
986 if (error(getSymbolAuxData(Obj, Symbol + I, Aux)))
987 break;
988
989 DictScope AS(W, "AuxSectionDef");
990 W.printNumber("Length", Aux->Length);
991 W.printNumber("RelocationCount", Aux->NumberOfRelocations);
992 W.printNumber("LineNumberCount", Aux->NumberOfLinenumbers);
993 W.printHex("Checksum", Aux->CheckSum);
994 W.printNumber("Number", Aux->Number);
995 W.printEnum("Selection", Aux->Selection, makeArrayRef(ImageCOMDATSelect));
996 W.printBinary("Unused", makeArrayRef(Aux->Unused));
997
Nico Riecka711dee2013-04-22 08:34:59 +0000998 if (Section && Section->Characteristics & COFF::IMAGE_SCN_LNK_COMDAT
Eric Christopher9cad53c2013-04-03 18:31:38 +0000999 && Aux->Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE) {
1000 const coff_section *Assoc;
1001 StringRef AssocName;
1002 error_code EC;
1003 if ((EC = Obj->getSection(Aux->Number, Assoc)) ||
1004 (EC = Obj->getSectionName(Assoc, AssocName))) {
1005 AssocName = "";
1006 error(EC);
1007 }
1008
1009 W.printNumber("AssocSection", AssocName, Aux->Number);
1010 }
David Majnemerddf28f22014-03-19 04:47:47 +00001011 } else if (Symbol->isCLRToken()) {
Eric Christopher9cad53c2013-04-03 18:31:38 +00001012 const coff_aux_clr_token *Aux;
1013 if (error(getSymbolAuxData(Obj, Symbol + I, Aux)))
1014 break;
1015
Nico Rieck8678acd2014-03-17 01:46:52 +00001016 const coff_symbol *ReferredSym;
1017 StringRef ReferredName;
1018 error_code EC;
1019 if ((EC = Obj->getSymbol(Aux->SymbolTableIndex, ReferredSym)) ||
1020 (EC = Obj->getSymbolName(ReferredSym, ReferredName))) {
1021 ReferredName = "";
1022 error(EC);
1023 }
1024
Eric Christopher9cad53c2013-04-03 18:31:38 +00001025 DictScope AS(W, "AuxCLRToken");
1026 W.printNumber("AuxType", Aux->AuxType);
1027 W.printNumber("Reserved", Aux->Reserved);
Nico Rieck8678acd2014-03-17 01:46:52 +00001028 W.printNumber("SymbolTableIndex", ReferredName, Aux->SymbolTableIndex);
David Majnemerf3a2af52014-03-19 04:33:27 +00001029 W.printBinary("Unused", makeArrayRef(Aux->Unused));
Eric Christopher9cad53c2013-04-03 18:31:38 +00001030
1031 } else {
1032 W.startLine() << "<unhandled auxiliary record>\n";
1033 }
1034 }
1035}
1036
1037void COFFDumper::printUnwindInfo() {
1038 const coff_file_header *Header;
Rui Ueyama82ebd8e2013-06-12 19:10:33 +00001039 if (error(Obj->getCOFFHeader(Header)))
Eric Christopher9cad53c2013-04-03 18:31:38 +00001040 return;
1041
1042 ListScope D(W, "UnwindInformation");
1043 if (Header->Machine != COFF::IMAGE_FILE_MACHINE_AMD64) {
1044 W.startLine() << "Unsupported image machine type "
1045 "(currently only AMD64 is supported).\n";
1046 return;
1047 }
1048
1049 printX64UnwindInfo();
1050}
1051
1052void COFFDumper::printX64UnwindInfo() {
Alexey Samsonov27dc8392014-03-18 06:53:02 +00001053 for (const SectionRef &Section : Obj->sections()) {
Eric Christopher9cad53c2013-04-03 18:31:38 +00001054 StringRef Name;
Alexey Samsonov27dc8392014-03-18 06:53:02 +00001055 if (error(Section.getName(Name)))
Eric Christopher9cad53c2013-04-03 18:31:38 +00001056 continue;
1057 if (Name != ".pdata" && !Name.startswith(".pdata$"))
1058 continue;
1059
Alexey Samsonov27dc8392014-03-18 06:53:02 +00001060 const coff_section *PData = Obj->getCOFFSection(Section);
Eric Christopher9cad53c2013-04-03 18:31:38 +00001061
1062 ArrayRef<uint8_t> Contents;
Alexey Samsonov27dc8392014-03-18 06:53:02 +00001063 if (error(Obj->getSectionContents(PData, Contents)) || Contents.empty())
Eric Christopher9cad53c2013-04-03 18:31:38 +00001064 continue;
1065
1066 ArrayRef<RuntimeFunction> RFs(
1067 reinterpret_cast<const RuntimeFunction *>(Contents.data()),
1068 Contents.size() / sizeof(RuntimeFunction));
1069
1070 for (const RuntimeFunction *I = RFs.begin(), *E = RFs.end(); I < E; ++I) {
1071 const uint64_t OffsetInSection = std::distance(RFs.begin(), I)
1072 * sizeof(RuntimeFunction);
1073
1074 printRuntimeFunction(*I, OffsetInSection, RelocMap[PData]);
1075 }
1076 }
1077}
1078
1079void COFFDumper::printRuntimeFunction(
1080 const RuntimeFunction& RTF,
1081 uint64_t OffsetInSection,
1082 const std::vector<RelocationRef> &Rels) {
1083
1084 DictScope D(W, "RuntimeFunction");
1085 W.printString("StartAddress",
1086 formatSymbol(Rels, OffsetInSection + 0, RTF.StartAddress));
1087 W.printString("EndAddress",
1088 formatSymbol(Rels, OffsetInSection + 4, RTF.EndAddress));
1089 W.printString("UnwindInfoAddress",
1090 formatSymbol(Rels, OffsetInSection + 8, RTF.UnwindInfoOffset));
1091
Craig Toppere6cb63e2014-04-25 04:24:47 +00001092 const coff_section* XData = nullptr;
Eric Christopher9cad53c2013-04-03 18:31:38 +00001093 uint64_t UnwindInfoOffset = 0;
1094 if (error(getSection(Rels, OffsetInSection + 8, &XData, &UnwindInfoOffset)))
1095 return;
1096
1097 ArrayRef<uint8_t> XContents;
1098 if (error(Obj->getSectionContents(XData, XContents)) || XContents.empty())
1099 return;
1100
1101 UnwindInfoOffset += RTF.UnwindInfoOffset;
1102 if (UnwindInfoOffset > XContents.size())
1103 return;
1104
1105 const Win64EH::UnwindInfo *UI =
1106 reinterpret_cast<const Win64EH::UnwindInfo *>(
1107 XContents.data() + UnwindInfoOffset);
1108
1109 printUnwindInfo(*UI, UnwindInfoOffset, RelocMap[XData]);
1110}
1111
1112void COFFDumper::printUnwindInfo(
1113 const Win64EH::UnwindInfo& UI,
1114 uint64_t OffsetInSection,
1115 const std::vector<RelocationRef> &Rels) {
1116 DictScope D(W, "UnwindInfo");
1117 W.printNumber("Version", UI.getVersion());
1118 W.printFlags("Flags", UI.getFlags(), makeArrayRef(UnwindFlags));
1119 W.printNumber("PrologSize", UI.PrologSize);
1120 if (UI.getFrameRegister() != 0) {
1121 W.printEnum("FrameRegister", UI.getFrameRegister(),
1122 makeArrayRef(UnwindOpInfo));
1123 W.printHex("FrameOffset", UI.getFrameOffset());
1124 } else {
1125 W.printString("FrameRegister", StringRef("-"));
1126 W.printString("FrameOffset", StringRef("-"));
1127 }
1128
1129 W.printNumber("UnwindCodeCount", UI.NumCodes);
1130 {
1131 ListScope CodesD(W, "UnwindCodes");
1132 ArrayRef<UnwindCode> UCs(&UI.UnwindCodes[0], UI.NumCodes);
1133 for (const UnwindCode *I = UCs.begin(), *E = UCs.end(); I < E; ++I) {
1134 unsigned UsedSlots = getNumUsedSlots(*I);
1135 if (UsedSlots > UCs.size()) {
1136 errs() << "Corrupt unwind data";
1137 return;
1138 }
1139 printUnwindCode(UI, ArrayRef<UnwindCode>(I, E));
1140 I += UsedSlots - 1;
1141 }
1142 }
1143
1144 uint64_t LSDAOffset = OffsetInSection + getOffsetOfLSDA(UI);
1145 if (UI.getFlags() & (UNW_ExceptionHandler | UNW_TerminateHandler)) {
1146 W.printString("Handler", formatSymbol(Rels, LSDAOffset,
1147 UI.getLanguageSpecificHandlerOffset()));
1148 } else if (UI.getFlags() & UNW_ChainInfo) {
1149 const RuntimeFunction *Chained = UI.getChainedFunctionEntry();
1150 if (Chained) {
1151 DictScope D(W, "Chained");
1152 W.printString("StartAddress", formatSymbol(Rels, LSDAOffset + 0,
1153 Chained->StartAddress));
1154 W.printString("EndAddress", formatSymbol(Rels, LSDAOffset + 4,
1155 Chained->EndAddress));
1156 W.printString("UnwindInfoAddress", formatSymbol(Rels, LSDAOffset + 8,
1157 Chained->UnwindInfoOffset));
1158 }
1159 }
1160}
1161
1162// Prints one unwind code. Because an unwind code can occupy up to 3 slots in
1163// the unwind codes array, this function requires that the correct number of
1164// slots is provided.
1165void COFFDumper::printUnwindCode(const Win64EH::UnwindInfo& UI,
1166 ArrayRef<UnwindCode> UCs) {
1167 assert(UCs.size() >= getNumUsedSlots(UCs[0]));
1168
1169 W.startLine() << format("0x%02X: ", unsigned(UCs[0].u.CodeOffset))
1170 << getUnwindCodeTypeName(UCs[0].getUnwindOp());
1171
1172 uint32_t AllocSize = 0;
1173
1174 switch (UCs[0].getUnwindOp()) {
1175 case UOP_PushNonVol:
1176 outs() << " reg=" << getUnwindRegisterName(UCs[0].getOpInfo());
1177 break;
1178
1179 case UOP_AllocLarge:
1180 if (UCs[0].getOpInfo() == 0) {
1181 AllocSize = UCs[1].FrameOffset * 8;
1182 } else {
1183 AllocSize = getLargeSlotValue(UCs);
1184 }
1185 outs() << " size=" << AllocSize;
1186 break;
1187 case UOP_AllocSmall:
1188 outs() << " size=" << ((UCs[0].getOpInfo() + 1) * 8);
1189 break;
1190 case UOP_SetFPReg:
1191 if (UI.getFrameRegister() == 0) {
1192 outs() << " reg=<invalid>";
1193 } else {
1194 outs() << " reg=" << getUnwindRegisterName(UI.getFrameRegister())
1195 << format(", offset=0x%X", UI.getFrameOffset() * 16);
1196 }
1197 break;
1198 case UOP_SaveNonVol:
1199 outs() << " reg=" << getUnwindRegisterName(UCs[0].getOpInfo())
1200 << format(", offset=0x%X", UCs[1].FrameOffset * 8);
1201 break;
1202 case UOP_SaveNonVolBig:
1203 outs() << " reg=" << getUnwindRegisterName(UCs[0].getOpInfo())
1204 << format(", offset=0x%X", getLargeSlotValue(UCs));
1205 break;
1206 case UOP_SaveXMM128:
1207 outs() << " reg=XMM" << static_cast<uint32_t>(UCs[0].getOpInfo())
1208 << format(", offset=0x%X", UCs[1].FrameOffset * 16);
1209 break;
1210 case UOP_SaveXMM128Big:
1211 outs() << " reg=XMM" << static_cast<uint32_t>(UCs[0].getOpInfo())
1212 << format(", offset=0x%X", getLargeSlotValue(UCs));
1213 break;
1214 case UOP_PushMachFrame:
1215 outs() << " errcode=" << (UCs[0].getOpInfo() == 0 ? "no" : "yes");
1216 break;
1217 }
1218
1219 outs() << "\n";
1220}