blob: cd40da7d6cc291bd6336a065e3de5fb9f51d4fe3 [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) {
199 for (std::vector<RelocationRef>::const_iterator RelI = Rels.begin(),
200 RelE = Rels.end();
201 RelI != RelE; ++RelI) {
202 uint64_t Ofs;
203 if (error_code EC = RelI->getOffset(Ofs))
204 return EC;
205
206 if (Ofs == Offset) {
Rafael Espindola806f0062013-06-05 01:33:53 +0000207 Sym = *RelI->getSymbol();
Eric Christopher9cad53c2013-04-03 18:31:38 +0000208 return readobj_error::success;
209 }
210 }
211
212 return readobj_error::unknown_symbol;
213}
214
215// Given a vector of relocations for a section and an offset into this section
216// the function returns the name of the symbol used for the relocation at the
217// offset.
218static error_code resolveSymbolName(const std::vector<RelocationRef> &Rels,
219 uint64_t Offset, StringRef &Name) {
220 SymbolRef Sym;
221 if (error_code EC = resolveSymbol(Rels, Offset, Sym)) return EC;
222 if (error_code EC = Sym.getName(Name)) return EC;
223 return object_error::success;
224}
225
226static const EnumEntry<COFF::MachineTypes> ImageFileMachineType[] = {
227 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_UNKNOWN ),
228 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_AM33 ),
229 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_AMD64 ),
230 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_ARM ),
Saleem Abdulrasool5e1780e2014-03-11 03:08:37 +0000231 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_ARMNT ),
Eric Christopher9cad53c2013-04-03 18:31:38 +0000232 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_EBC ),
233 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_I386 ),
234 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_IA64 ),
235 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_M32R ),
236 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_MIPS16 ),
237 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_MIPSFPU ),
238 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_MIPSFPU16),
239 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_POWERPC ),
240 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_POWERPCFP),
241 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_R4000 ),
242 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_SH3 ),
243 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_SH3DSP ),
244 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_SH4 ),
245 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_SH5 ),
246 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_THUMB ),
247 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_WCEMIPSV2)
248};
249
250static const EnumEntry<COFF::Characteristics> ImageFileCharacteristics[] = {
251 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_RELOCS_STRIPPED ),
252 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_EXECUTABLE_IMAGE ),
253 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_LINE_NUMS_STRIPPED ),
254 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_LOCAL_SYMS_STRIPPED ),
255 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_AGGRESSIVE_WS_TRIM ),
256 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_LARGE_ADDRESS_AWARE ),
257 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_BYTES_REVERSED_LO ),
258 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_32BIT_MACHINE ),
259 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_DEBUG_STRIPPED ),
260 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP),
261 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_NET_RUN_FROM_SWAP ),
262 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_SYSTEM ),
263 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_DLL ),
264 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_UP_SYSTEM_ONLY ),
265 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_BYTES_REVERSED_HI )
266};
267
Rui Ueyama82ebd8e2013-06-12 19:10:33 +0000268static const EnumEntry<COFF::WindowsSubsystem> PEWindowsSubsystem[] = {
269 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_UNKNOWN ),
270 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_NATIVE ),
271 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_WINDOWS_GUI ),
272 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_WINDOWS_CUI ),
273 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_POSIX_CUI ),
274 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_WINDOWS_CE_GUI ),
275 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_EFI_APPLICATION ),
276 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER),
277 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER ),
278 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_EFI_ROM ),
279 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_XBOX ),
280};
281
282static const EnumEntry<COFF::DLLCharacteristics> PEDLLCharacteristics[] = {
Rui Ueyama06dc5e72014-01-27 04:22:24 +0000283 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA ),
Rui Ueyama82ebd8e2013-06-12 19:10:33 +0000284 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE ),
285 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY ),
286 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_NX_COMPAT ),
287 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_NO_ISOLATION ),
288 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_NO_SEH ),
289 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_NO_BIND ),
290 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_WDM_DRIVER ),
291 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_TERMINAL_SERVER_AWARE),
292};
293
Eric Christopher9cad53c2013-04-03 18:31:38 +0000294static const EnumEntry<COFF::SectionCharacteristics>
295ImageSectionCharacteristics[] = {
296 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_TYPE_NO_PAD ),
297 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_CNT_CODE ),
298 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_CNT_INITIALIZED_DATA ),
299 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_CNT_UNINITIALIZED_DATA),
300 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_OTHER ),
301 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_INFO ),
302 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_REMOVE ),
303 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_COMDAT ),
304 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_GPREL ),
305 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_PURGEABLE ),
306 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_16BIT ),
307 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_LOCKED ),
308 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_PRELOAD ),
309 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_1BYTES ),
310 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_2BYTES ),
311 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_4BYTES ),
312 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_8BYTES ),
313 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_16BYTES ),
314 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_32BYTES ),
315 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_64BYTES ),
316 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_128BYTES ),
317 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_256BYTES ),
318 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_512BYTES ),
319 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_1024BYTES ),
320 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_2048BYTES ),
321 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_4096BYTES ),
322 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_8192BYTES ),
323 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_NRELOC_OVFL ),
324 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_DISCARDABLE ),
325 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_NOT_CACHED ),
326 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_NOT_PAGED ),
327 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_SHARED ),
328 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_EXECUTE ),
329 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_READ ),
330 LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_WRITE )
331};
332
333static const EnumEntry<COFF::SymbolBaseType> ImageSymType[] = {
334 { "Null" , COFF::IMAGE_SYM_TYPE_NULL },
335 { "Void" , COFF::IMAGE_SYM_TYPE_VOID },
336 { "Char" , COFF::IMAGE_SYM_TYPE_CHAR },
337 { "Short" , COFF::IMAGE_SYM_TYPE_SHORT },
338 { "Int" , COFF::IMAGE_SYM_TYPE_INT },
339 { "Long" , COFF::IMAGE_SYM_TYPE_LONG },
340 { "Float" , COFF::IMAGE_SYM_TYPE_FLOAT },
341 { "Double", COFF::IMAGE_SYM_TYPE_DOUBLE },
342 { "Struct", COFF::IMAGE_SYM_TYPE_STRUCT },
343 { "Union" , COFF::IMAGE_SYM_TYPE_UNION },
344 { "Enum" , COFF::IMAGE_SYM_TYPE_ENUM },
345 { "MOE" , COFF::IMAGE_SYM_TYPE_MOE },
346 { "Byte" , COFF::IMAGE_SYM_TYPE_BYTE },
347 { "Word" , COFF::IMAGE_SYM_TYPE_WORD },
348 { "UInt" , COFF::IMAGE_SYM_TYPE_UINT },
349 { "DWord" , COFF::IMAGE_SYM_TYPE_DWORD }
350};
351
352static const EnumEntry<COFF::SymbolComplexType> ImageSymDType[] = {
353 { "Null" , COFF::IMAGE_SYM_DTYPE_NULL },
354 { "Pointer" , COFF::IMAGE_SYM_DTYPE_POINTER },
355 { "Function", COFF::IMAGE_SYM_DTYPE_FUNCTION },
356 { "Array" , COFF::IMAGE_SYM_DTYPE_ARRAY }
357};
358
359static const EnumEntry<COFF::SymbolStorageClass> ImageSymClass[] = {
360 { "EndOfFunction" , COFF::IMAGE_SYM_CLASS_END_OF_FUNCTION },
361 { "Null" , COFF::IMAGE_SYM_CLASS_NULL },
362 { "Automatic" , COFF::IMAGE_SYM_CLASS_AUTOMATIC },
363 { "External" , COFF::IMAGE_SYM_CLASS_EXTERNAL },
364 { "Static" , COFF::IMAGE_SYM_CLASS_STATIC },
365 { "Register" , COFF::IMAGE_SYM_CLASS_REGISTER },
366 { "ExternalDef" , COFF::IMAGE_SYM_CLASS_EXTERNAL_DEF },
367 { "Label" , COFF::IMAGE_SYM_CLASS_LABEL },
368 { "UndefinedLabel" , COFF::IMAGE_SYM_CLASS_UNDEFINED_LABEL },
369 { "MemberOfStruct" , COFF::IMAGE_SYM_CLASS_MEMBER_OF_STRUCT },
370 { "Argument" , COFF::IMAGE_SYM_CLASS_ARGUMENT },
371 { "StructTag" , COFF::IMAGE_SYM_CLASS_STRUCT_TAG },
372 { "MemberOfUnion" , COFF::IMAGE_SYM_CLASS_MEMBER_OF_UNION },
373 { "UnionTag" , COFF::IMAGE_SYM_CLASS_UNION_TAG },
374 { "TypeDefinition" , COFF::IMAGE_SYM_CLASS_TYPE_DEFINITION },
375 { "UndefinedStatic", COFF::IMAGE_SYM_CLASS_UNDEFINED_STATIC },
376 { "EnumTag" , COFF::IMAGE_SYM_CLASS_ENUM_TAG },
377 { "MemberOfEnum" , COFF::IMAGE_SYM_CLASS_MEMBER_OF_ENUM },
378 { "RegisterParam" , COFF::IMAGE_SYM_CLASS_REGISTER_PARAM },
379 { "BitField" , COFF::IMAGE_SYM_CLASS_BIT_FIELD },
380 { "Block" , COFF::IMAGE_SYM_CLASS_BLOCK },
381 { "Function" , COFF::IMAGE_SYM_CLASS_FUNCTION },
382 { "EndOfStruct" , COFF::IMAGE_SYM_CLASS_END_OF_STRUCT },
383 { "File" , COFF::IMAGE_SYM_CLASS_FILE },
384 { "Section" , COFF::IMAGE_SYM_CLASS_SECTION },
385 { "WeakExternal" , COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL },
386 { "CLRToken" , COFF::IMAGE_SYM_CLASS_CLR_TOKEN }
387};
388
389static const EnumEntry<COFF::COMDATType> ImageCOMDATSelect[] = {
390 { "NoDuplicates", COFF::IMAGE_COMDAT_SELECT_NODUPLICATES },
391 { "Any" , COFF::IMAGE_COMDAT_SELECT_ANY },
392 { "SameSize" , COFF::IMAGE_COMDAT_SELECT_SAME_SIZE },
393 { "ExactMatch" , COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH },
394 { "Associative" , COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE },
395 { "Largest" , COFF::IMAGE_COMDAT_SELECT_LARGEST },
396 { "Newest" , COFF::IMAGE_COMDAT_SELECT_NEWEST }
397};
398
399static const EnumEntry<COFF::WeakExternalCharacteristics>
400WeakExternalCharacteristics[] = {
401 { "NoLibrary", COFF::IMAGE_WEAK_EXTERN_SEARCH_NOLIBRARY },
402 { "Library" , COFF::IMAGE_WEAK_EXTERN_SEARCH_LIBRARY },
403 { "Alias" , COFF::IMAGE_WEAK_EXTERN_SEARCH_ALIAS }
404};
405
406static const EnumEntry<unsigned> UnwindFlags[] = {
407 { "ExceptionHandler", Win64EH::UNW_ExceptionHandler },
408 { "TerminateHandler", Win64EH::UNW_TerminateHandler },
409 { "ChainInfo" , Win64EH::UNW_ChainInfo }
410};
411
412static const EnumEntry<unsigned> UnwindOpInfo[] = {
413 { "RAX", 0 },
414 { "RCX", 1 },
415 { "RDX", 2 },
416 { "RBX", 3 },
417 { "RSP", 4 },
418 { "RBP", 5 },
419 { "RSI", 6 },
420 { "RDI", 7 },
421 { "R8", 8 },
422 { "R9", 9 },
423 { "R10", 10 },
424 { "R11", 11 },
425 { "R12", 12 },
426 { "R13", 13 },
427 { "R14", 14 },
428 { "R15", 15 }
429};
430
431// Some additional COFF structures not defined by llvm::object.
432namespace {
Eric Christopher9cad53c2013-04-03 18:31:38 +0000433 struct coff_aux_file_record {
434 char FileName[18];
435 };
Eric Christopher9cad53c2013-04-03 18:31:38 +0000436} // namespace
437
438static uint64_t getOffsetOfLSDA(const Win64EH::UnwindInfo& UI) {
439 return static_cast<const char*>(UI.getLanguageSpecificData())
440 - reinterpret_cast<const char*>(&UI);
441}
442
443static uint32_t getLargeSlotValue(ArrayRef<UnwindCode> UCs) {
444 if (UCs.size() < 3)
445 return 0;
446
447 return UCs[1].FrameOffset + (static_cast<uint32_t>(UCs[2].FrameOffset) << 16);
448}
449
450template<typename T>
451static error_code getSymbolAuxData(const COFFObjectFile *Obj,
452 const coff_symbol *Symbol, const T* &Aux) {
453 ArrayRef<uint8_t> AuxData = Obj->getSymbolAuxData(Symbol);
454 Aux = reinterpret_cast<const T*>(AuxData.data());
455 return readobj_error::success;
456}
457
458static std::string formatSymbol(const std::vector<RelocationRef> &Rels,
459 uint64_t Offset, uint32_t Disp) {
460 std::string Buffer;
461 raw_string_ostream Str(Buffer);
462
463 StringRef Sym;
464 if (resolveSymbolName(Rels, Offset, Sym)) {
Benjamin Kramer48b6a882013-07-06 20:01:46 +0000465 Str << format(" (0x%" PRIX64 ")", Offset);
Eric Christopher9cad53c2013-04-03 18:31:38 +0000466 return Str.str();
467 }
468
469 Str << Sym;
470 if (Disp > 0) {
Benjamin Kramer48b6a882013-07-06 20:01:46 +0000471 Str << format(" +0x%X (0x%" PRIX64 ")", Disp, Offset);
Eric Christopher9cad53c2013-04-03 18:31:38 +0000472 } else {
Benjamin Kramer48b6a882013-07-06 20:01:46 +0000473 Str << format(" (0x%" PRIX64 ")", Offset);
Eric Christopher9cad53c2013-04-03 18:31:38 +0000474 }
475
476 return Str.str();
477}
478
479// Given a vector of relocations for a section and an offset into this section
480// the function resolves the symbol used for the relocation at the offset and
481// returns the section content and the address inside the content pointed to
482// by the symbol.
483error_code COFFDumper::getSectionContents(
484 const std::vector<RelocationRef> &Rels, uint64_t Offset,
485 ArrayRef<uint8_t> &Contents, uint64_t &Addr) {
486
487 SymbolRef Sym;
488 const coff_section *Section;
489
490 if (error_code EC = resolveSymbol(Rels, Offset, Sym))
491 return EC;
492 if (error_code EC = resolveSectionAndAddress(Obj, Sym, Section, Addr))
493 return EC;
494 if (error_code EC = Obj->getSectionContents(Section, Contents))
495 return EC;
496
497 return object_error::success;
498}
499
500error_code COFFDumper::getSection(
501 const std::vector<RelocationRef> &Rels, uint64_t Offset,
502 const coff_section **SectionPtr, uint64_t *AddrPtr) {
503
504 SymbolRef Sym;
505 if (error_code EC = resolveSymbol(Rels, Offset, Sym))
506 return EC;
507
508 const coff_section *Section;
509 uint64_t Addr;
510 if (error_code EC = resolveSectionAndAddress(Obj, Sym, Section, Addr))
511 return EC;
512
513 if (SectionPtr)
514 *SectionPtr = Section;
515 if (AddrPtr)
516 *AddrPtr = Addr;
517
518 return object_error::success;
519}
520
521void COFFDumper::cacheRelocations() {
Alexey Samsonov27dc8392014-03-18 06:53:02 +0000522 for (const SectionRef &S : Obj->sections()) {
523 const coff_section *Section = Obj->getCOFFSection(S);
Eric Christopher9cad53c2013-04-03 18:31:38 +0000524
Alexey Samsonov27dc8392014-03-18 06:53:02 +0000525 for (const RelocationRef &Reloc : S.relocations())
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000526 RelocMap[Section].push_back(Reloc);
Eric Christopher9cad53c2013-04-03 18:31:38 +0000527
528 // Sort relocations by address.
529 std::sort(RelocMap[Section].begin(), RelocMap[Section].end(),
530 relocAddressLess);
531 }
532}
533
Rui Ueyamaed64342b2013-07-19 23:23:29 +0000534void COFFDumper::printDataDirectory(uint32_t Index, const std::string &FieldName) {
535 const data_directory *Data;
536 if (Obj->getDataDirectory(Index, Data))
537 return;
538 W.printHex(FieldName + "RVA", Data->RelativeVirtualAddress);
539 W.printHex(FieldName + "Size", Data->Size);
540}
541
Eric Christopher9cad53c2013-04-03 18:31:38 +0000542void COFFDumper::printFileHeaders() {
Rui Ueyama82ebd8e2013-06-12 19:10:33 +0000543 // Print COFF header
544 const coff_file_header *COFFHeader = 0;
545 if (error(Obj->getCOFFHeader(COFFHeader)))
Eric Christopher9cad53c2013-04-03 18:31:38 +0000546 return;
547
Rui Ueyama82ebd8e2013-06-12 19:10:33 +0000548 time_t TDS = COFFHeader->TimeDateStamp;
Eric Christopher9cad53c2013-04-03 18:31:38 +0000549 char FormattedTime[20] = { };
550 strftime(FormattedTime, 20, "%Y-%m-%d %H:%M:%S", gmtime(&TDS));
551
552 {
553 DictScope D(W, "ImageFileHeader");
Rui Ueyama82ebd8e2013-06-12 19:10:33 +0000554 W.printEnum ("Machine", COFFHeader->Machine,
Eric Christopher9cad53c2013-04-03 18:31:38 +0000555 makeArrayRef(ImageFileMachineType));
Rui Ueyama82ebd8e2013-06-12 19:10:33 +0000556 W.printNumber("SectionCount", COFFHeader->NumberOfSections);
557 W.printHex ("TimeDateStamp", FormattedTime, COFFHeader->TimeDateStamp);
558 W.printHex ("PointerToSymbolTable", COFFHeader->PointerToSymbolTable);
559 W.printNumber("SymbolCount", COFFHeader->NumberOfSymbols);
560 W.printNumber("OptionalHeaderSize", COFFHeader->SizeOfOptionalHeader);
561 W.printFlags ("Characteristics", COFFHeader->Characteristics,
Eric Christopher9cad53c2013-04-03 18:31:38 +0000562 makeArrayRef(ImageFileCharacteristics));
563 }
Rui Ueyama82ebd8e2013-06-12 19:10:33 +0000564
565 // Print PE header. This header does not exist if this is an object file and
566 // not an executable.
567 const pe32_header *PEHeader = 0;
568 if (error(Obj->getPE32Header(PEHeader)))
569 return;
Rui Ueyama10ed9dd2014-01-26 04:15:52 +0000570 if (PEHeader)
571 printPEHeader<pe32_header>(PEHeader);
Rui Ueyama82ebd8e2013-06-12 19:10:33 +0000572
Rui Ueyama10ed9dd2014-01-26 04:15:52 +0000573 const pe32plus_header *PEPlusHeader = 0;
574 if (error(Obj->getPE32PlusHeader(PEPlusHeader)))
575 return;
576 if (PEPlusHeader)
577 printPEHeader<pe32plus_header>(PEPlusHeader);
578}
Rui Ueyamaed64342b2013-07-19 23:23:29 +0000579
Rui Ueyama10ed9dd2014-01-26 04:15:52 +0000580template <class PEHeader>
581void COFFDumper::printPEHeader(const PEHeader *Hdr) {
582 DictScope D(W, "ImageOptionalHeader");
583 W.printNumber("MajorLinkerVersion", Hdr->MajorLinkerVersion);
584 W.printNumber("MinorLinkerVersion", Hdr->MinorLinkerVersion);
585 W.printNumber("SizeOfCode", Hdr->SizeOfCode);
586 W.printNumber("SizeOfInitializedData", Hdr->SizeOfInitializedData);
587 W.printNumber("SizeOfUninitializedData", Hdr->SizeOfUninitializedData);
588 W.printHex ("AddressOfEntryPoint", Hdr->AddressOfEntryPoint);
589 W.printHex ("BaseOfCode", Hdr->BaseOfCode);
590 printBaseOfDataField(Hdr);
591 W.printHex ("ImageBase", Hdr->ImageBase);
592 W.printNumber("SectionAlignment", Hdr->SectionAlignment);
593 W.printNumber("FileAlignment", Hdr->FileAlignment);
594 W.printNumber("MajorOperatingSystemVersion",
595 Hdr->MajorOperatingSystemVersion);
596 W.printNumber("MinorOperatingSystemVersion",
597 Hdr->MinorOperatingSystemVersion);
598 W.printNumber("MajorImageVersion", Hdr->MajorImageVersion);
599 W.printNumber("MinorImageVersion", Hdr->MinorImageVersion);
600 W.printNumber("MajorSubsystemVersion", Hdr->MajorSubsystemVersion);
601 W.printNumber("MinorSubsystemVersion", Hdr->MinorSubsystemVersion);
602 W.printNumber("SizeOfImage", Hdr->SizeOfImage);
603 W.printNumber("SizeOfHeaders", Hdr->SizeOfHeaders);
604 W.printEnum ("Subsystem", Hdr->Subsystem, makeArrayRef(PEWindowsSubsystem));
605 W.printFlags ("Subsystem", Hdr->DLLCharacteristics,
606 makeArrayRef(PEDLLCharacteristics));
607 W.printNumber("SizeOfStackReserve", Hdr->SizeOfStackReserve);
608 W.printNumber("SizeOfStackCommit", Hdr->SizeOfStackCommit);
609 W.printNumber("SizeOfHeapReserve", Hdr->SizeOfHeapReserve);
610 W.printNumber("SizeOfHeapCommit", Hdr->SizeOfHeapCommit);
611 W.printNumber("NumberOfRvaAndSize", Hdr->NumberOfRvaAndSize);
Rui Ueyamaed64342b2013-07-19 23:23:29 +0000612
Rui Ueyama10ed9dd2014-01-26 04:15:52 +0000613 if (Hdr->NumberOfRvaAndSize > 0) {
614 DictScope D(W, "DataDirectory");
615 static const char * const directory[] = {
616 "ExportTable", "ImportTable", "ResourceTable", "ExceptionTable",
617 "CertificateTable", "BaseRelocationTable", "Debug", "Architecture",
618 "GlobalPtr", "TLSTable", "LoadConfigTable", "BoundImport", "IAT",
619 "DelayImportDescriptor", "CLRRuntimeHeader", "Reserved"
620 };
621
622 for (uint32_t i = 0; i < Hdr->NumberOfRvaAndSize; ++i) {
623 printDataDirectory(i, directory[i]);
Rui Ueyamaed64342b2013-07-19 23:23:29 +0000624 }
Rui Ueyama82ebd8e2013-06-12 19:10:33 +0000625 }
Eric Christopher9cad53c2013-04-03 18:31:38 +0000626}
627
Rui Ueyama10ed9dd2014-01-26 04:15:52 +0000628void COFFDumper::printBaseOfDataField(const pe32_header *Hdr) {
629 W.printHex("BaseOfData", Hdr->BaseOfData);
630}
631
632void COFFDumper::printBaseOfDataField(const pe32plus_header *) {}
633
Alexey Samsonov27dc8392014-03-18 06:53:02 +0000634void COFFDumper::printCodeViewLineTables(const SectionRef &Section) {
Timur Iskhodzhanov48703be2013-12-19 11:37:14 +0000635 StringRef Data;
Alexey Samsonov27dc8392014-03-18 06:53:02 +0000636 if (error(Section.getContents(Data)))
637 return;
Timur Iskhodzhanov48703be2013-12-19 11:37:14 +0000638
639 SmallVector<StringRef, 10> FunctionNames;
640 StringMap<StringRef> FunctionLineTables;
641 StringRef FileIndexToStringOffsetTable;
642 StringRef StringTable;
643
644 ListScope D(W, "CodeViewLineTables");
645 {
646 DataExtractor DE(Data, true, 4);
647 uint32_t Offset = 0,
648 Magic = DE.getU32(&Offset);
649 W.printHex("Magic", Magic);
650 if (Magic != COFF::DEBUG_SECTION_MAGIC) {
651 error(object_error::parse_failed);
652 return;
653 }
654
655 bool Finished = false;
656 while (DE.isValidOffset(Offset) && !Finished) {
657 // The section consists of a number of subsection in the following format:
658 // |Type|PayloadSize|Payload...|
659 uint32_t SubSectionType = DE.getU32(&Offset),
660 PayloadSize = DE.getU32(&Offset);
661 ListScope S(W, "Subsection");
662 W.printHex("Type", SubSectionType);
663 W.printHex("PayloadSize", PayloadSize);
664 if (PayloadSize > Data.size() - Offset) {
665 error(object_error::parse_failed);
666 return;
667 }
668
669 // Print the raw contents to simplify debugging if anything goes wrong
670 // afterwards.
671 StringRef Contents = Data.substr(Offset, PayloadSize);
672 W.printBinaryBlock("Contents", Contents);
673
674 switch (SubSectionType) {
675 case COFF::DEBUG_LINE_TABLE_SUBSECTION: {
676 // Holds a PC to file:line table. Some data to parse this subsection is
677 // stored in the other subsections, so just check sanity and store the
678 // pointers for deferred processing.
679
680 if (PayloadSize < 12) {
681 // There should be at least three words to store two function
682 // relocations and size of the code.
683 error(object_error::parse_failed);
684 return;
685 }
686
687 StringRef FunctionName;
Alexey Samsonov27dc8392014-03-18 06:53:02 +0000688 if (error(resolveSymbolName(RelocMap[Obj->getCOFFSection(Section)],
689 Offset, FunctionName)))
Timur Iskhodzhanov48703be2013-12-19 11:37:14 +0000690 return;
691 W.printString("FunctionName", FunctionName);
692 if (FunctionLineTables.count(FunctionName) != 0) {
693 // Saw debug info for this function already?
694 error(object_error::parse_failed);
695 return;
696 }
697
698 FunctionLineTables[FunctionName] = Contents;
699 FunctionNames.push_back(FunctionName);
700 break;
701 }
702 case COFF::DEBUG_STRING_TABLE_SUBSECTION:
703 if (PayloadSize == 0 || StringTable.data() != 0 ||
704 Contents.back() != '\0') {
705 // Empty or duplicate or non-null-terminated subsection.
706 error(object_error::parse_failed);
707 return;
708 }
709 StringTable = Contents;
710 break;
711 case COFF::DEBUG_INDEX_SUBSECTION:
712 // Holds the translation table from file indices
713 // to offsets in the string table.
714
715 if (PayloadSize == 0 || FileIndexToStringOffsetTable.data() != 0) {
716 // Empty or duplicate subsection.
717 error(object_error::parse_failed);
718 return;
719 }
720 FileIndexToStringOffsetTable = Contents;
721 break;
722 }
723 Offset += PayloadSize;
724
725 // Align the reading pointer by 4.
726 Offset += (-Offset) % 4;
727 }
728 }
729
730 // Dump the line tables now that we've read all the subsections and know all
731 // the required information.
732 for (unsigned I = 0, E = FunctionNames.size(); I != E; ++I) {
733 StringRef Name = FunctionNames[I];
734 ListScope S(W, "FunctionLineTable");
735 W.printString("FunctionName", Name);
736
737 DataExtractor DE(FunctionLineTables[Name], true, 4);
738 uint32_t Offset = 8; // Skip relocations.
739 uint32_t FunctionSize = DE.getU32(&Offset);
740 W.printHex("CodeSize", FunctionSize);
741 while (DE.isValidOffset(Offset)) {
742 // For each range of lines with the same filename, we have a segment
743 // in the line table. The filename string is accessed using double
744 // indirection to the string table subsection using the index subsection.
745 uint32_t OffsetInIndex = DE.getU32(&Offset),
746 SegmentLength = DE.getU32(&Offset),
747 FullSegmentSize = DE.getU32(&Offset);
748 if (FullSegmentSize != 12 + 8 * SegmentLength) {
749 error(object_error::parse_failed);
750 return;
751 }
752
753 uint32_t FilenameOffset;
754 {
755 DataExtractor SDE(FileIndexToStringOffsetTable, true, 4);
756 uint32_t OffsetInSDE = OffsetInIndex;
757 if (!SDE.isValidOffset(OffsetInSDE)) {
758 error(object_error::parse_failed);
759 return;
760 }
761 FilenameOffset = SDE.getU32(&OffsetInSDE);
762 }
763
764 if (FilenameOffset == 0 || FilenameOffset + 1 >= StringTable.size() ||
765 StringTable.data()[FilenameOffset - 1] != '\0') {
766 // Each string in an F3 subsection should be preceded by a null
767 // character.
768 error(object_error::parse_failed);
769 return;
770 }
771
772 StringRef Filename(StringTable.data() + FilenameOffset);
773 ListScope S(W, "FilenameSegment");
774 W.printString("Filename", Filename);
775 for (unsigned J = 0; J != SegmentLength && DE.isValidOffset(Offset);
776 ++J) {
777 // Then go the (PC, LineNumber) pairs. The line number is stored in the
778 // least significant 31 bits of the respective word in the table.
779 uint32_t PC = DE.getU32(&Offset),
780 LineNumber = DE.getU32(&Offset) & 0x7fffffff;
781 if (PC >= FunctionSize) {
782 error(object_error::parse_failed);
783 return;
784 }
785 char Buffer[32];
786 format("+0x%X", PC).snprint(Buffer, 32);
787 W.printNumber(Buffer, LineNumber);
788 }
789 }
790 }
791}
792
Eric Christopher9cad53c2013-04-03 18:31:38 +0000793void COFFDumper::printSections() {
Eric Christopher9cad53c2013-04-03 18:31:38 +0000794 ListScope SectionsD(W, "Sections");
795 int SectionNumber = 0;
Alexey Samsonov27dc8392014-03-18 06:53:02 +0000796 for (const SectionRef &Sec : Obj->sections()) {
Eric Christopher9cad53c2013-04-03 18:31:38 +0000797 ++SectionNumber;
Alexey Samsonov27dc8392014-03-18 06:53:02 +0000798 const coff_section *Section = Obj->getCOFFSection(Sec);
Eric Christopher9cad53c2013-04-03 18:31:38 +0000799
800 StringRef Name;
Alexey Samsonov27dc8392014-03-18 06:53:02 +0000801 if (error(Sec.getName(Name)))
802 Name = "";
Eric Christopher9cad53c2013-04-03 18:31:38 +0000803
804 DictScope D(W, "Section");
805 W.printNumber("Number", SectionNumber);
806 W.printBinary("Name", Name, Section->Name);
807 W.printHex ("VirtualSize", Section->VirtualSize);
808 W.printHex ("VirtualAddress", Section->VirtualAddress);
809 W.printNumber("RawDataSize", Section->SizeOfRawData);
810 W.printHex ("PointerToRawData", Section->PointerToRawData);
811 W.printHex ("PointerToRelocations", Section->PointerToRelocations);
812 W.printHex ("PointerToLineNumbers", Section->PointerToLinenumbers);
813 W.printNumber("RelocationCount", Section->NumberOfRelocations);
814 W.printNumber("LineNumberCount", Section->NumberOfLinenumbers);
815 W.printFlags ("Characteristics", Section->Characteristics,
816 makeArrayRef(ImageSectionCharacteristics),
817 COFF::SectionCharacteristics(0x00F00000));
818
819 if (opts::SectionRelocations) {
820 ListScope D(W, "Relocations");
Alexey Samsonov27dc8392014-03-18 06:53:02 +0000821 for (const RelocationRef &Reloc : Sec.relocations())
822 printRelocation(Sec, Reloc);
Eric Christopher9cad53c2013-04-03 18:31:38 +0000823 }
824
825 if (opts::SectionSymbols) {
826 ListScope D(W, "Symbols");
Alexey Samsonov27dc8392014-03-18 06:53:02 +0000827 for (const SymbolRef &Symbol : Obj->symbols()) {
Eric Christopher9cad53c2013-04-03 18:31:38 +0000828 bool Contained = false;
Alexey Samsonov27dc8392014-03-18 06:53:02 +0000829 if (Sec.containsSymbol(Symbol, Contained) || !Contained)
Eric Christopher9cad53c2013-04-03 18:31:38 +0000830 continue;
831
Alexey Samsonov27dc8392014-03-18 06:53:02 +0000832 printSymbol(Symbol);
Eric Christopher9cad53c2013-04-03 18:31:38 +0000833 }
834 }
835
Timur Iskhodzhanov48703be2013-12-19 11:37:14 +0000836 if (Name == ".debug$S" && opts::CodeViewLineTables)
Alexey Samsonov27dc8392014-03-18 06:53:02 +0000837 printCodeViewLineTables(Sec);
Timur Iskhodzhanov48703be2013-12-19 11:37:14 +0000838
Eric Christopher9cad53c2013-04-03 18:31:38 +0000839 if (opts::SectionData) {
840 StringRef Data;
Alexey Samsonov27dc8392014-03-18 06:53:02 +0000841 if (error(Sec.getContents(Data)))
842 break;
Eric Christopher9cad53c2013-04-03 18:31:38 +0000843
844 W.printBinaryBlock("SectionData", Data);
845 }
846 }
847}
848
849void COFFDumper::printRelocations() {
850 ListScope D(W, "Relocations");
851
Eric Christopher9cad53c2013-04-03 18:31:38 +0000852 int SectionNumber = 0;
Alexey Samsonov27dc8392014-03-18 06:53:02 +0000853 for (const SectionRef &Section : Obj->sections()) {
Eric Christopher9cad53c2013-04-03 18:31:38 +0000854 ++SectionNumber;
Eric Christopher9cad53c2013-04-03 18:31:38 +0000855 StringRef Name;
Alexey Samsonov27dc8392014-03-18 06:53:02 +0000856 if (error(Section.getName(Name)))
Eric Christopher9cad53c2013-04-03 18:31:38 +0000857 continue;
858
859 bool PrintedGroup = false;
Alexey Samsonov27dc8392014-03-18 06:53:02 +0000860 for (const RelocationRef &Reloc : Section.relocations()) {
Eric Christopher9cad53c2013-04-03 18:31:38 +0000861 if (!PrintedGroup) {
862 W.startLine() << "Section (" << SectionNumber << ") " << Name << " {\n";
863 W.indent();
864 PrintedGroup = true;
865 }
866
Alexey Samsonov27dc8392014-03-18 06:53:02 +0000867 printRelocation(Section, Reloc);
Eric Christopher9cad53c2013-04-03 18:31:38 +0000868 }
869
870 if (PrintedGroup) {
871 W.unindent();
872 W.startLine() << "}\n";
873 }
874 }
875}
876
Alexey Samsonov27dc8392014-03-18 06:53:02 +0000877void COFFDumper::printRelocation(const SectionRef &Section,
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000878 const RelocationRef &Reloc) {
Eric Christopher9cad53c2013-04-03 18:31:38 +0000879 uint64_t Offset;
880 uint64_t RelocType;
881 SmallString<32> RelocName;
Eric Christopher9cad53c2013-04-03 18:31:38 +0000882 StringRef SymbolName;
883 StringRef Contents;
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000884 if (error(Reloc.getOffset(Offset)))
885 return;
886 if (error(Reloc.getType(RelocType)))
887 return;
888 if (error(Reloc.getTypeName(RelocName)))
889 return;
890 symbol_iterator Symbol = Reloc.getSymbol();
891 if (error(Symbol->getName(SymbolName)))
892 return;
Alexey Samsonov27dc8392014-03-18 06:53:02 +0000893 if (error(Section.getContents(Contents)))
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000894 return;
Eric Christopher9cad53c2013-04-03 18:31:38 +0000895
Nico Rieckf3f0b792013-04-12 04:01:52 +0000896 if (opts::ExpandRelocs) {
897 DictScope Group(W, "Relocation");
898 W.printHex("Offset", Offset);
899 W.printNumber("Type", RelocName, RelocType);
900 W.printString("Symbol", SymbolName.size() > 0 ? SymbolName : "-");
901 } else {
902 raw_ostream& OS = W.startLine();
903 OS << W.hex(Offset)
904 << " " << RelocName
905 << " " << (SymbolName.size() > 0 ? SymbolName : "-")
906 << "\n";
907 }
Eric Christopher9cad53c2013-04-03 18:31:38 +0000908}
909
910void COFFDumper::printSymbols() {
911 ListScope Group(W, "Symbols");
912
Alexey Samsonov27dc8392014-03-18 06:53:02 +0000913 for (const SymbolRef &Symbol : Obj->symbols())
914 printSymbol(Symbol);
Eric Christopher9cad53c2013-04-03 18:31:38 +0000915}
916
Alexey Samsonov27dc8392014-03-18 06:53:02 +0000917void COFFDumper::printDynamicSymbols() { ListScope Group(W, "DynamicSymbols"); }
Eric Christopher9cad53c2013-04-03 18:31:38 +0000918
Alexey Samsonov27dc8392014-03-18 06:53:02 +0000919void COFFDumper::printSymbol(const SymbolRef &Sym) {
Eric Christopher9cad53c2013-04-03 18:31:38 +0000920 DictScope D(W, "Symbol");
921
Alexey Samsonov27dc8392014-03-18 06:53:02 +0000922 const coff_symbol *Symbol = Obj->getCOFFSymbol(Sym);
Eric Christopher9cad53c2013-04-03 18:31:38 +0000923 const coff_section *Section;
924 if (error_code EC = Obj->getSection(Symbol->SectionNumber, Section)) {
925 W.startLine() << "Invalid section number: " << EC.message() << "\n";
926 W.flush();
927 return;
928 }
929
930 StringRef SymbolName;
931 if (Obj->getSymbolName(Symbol, SymbolName))
932 SymbolName = "";
933
Nico Riecka8de6532013-04-22 08:34:46 +0000934 StringRef SectionName = "";
935 if (Section)
936 Obj->getSectionName(Section, SectionName);
Eric Christopher9cad53c2013-04-03 18:31:38 +0000937
938 W.printString("Name", SymbolName);
939 W.printNumber("Value", Symbol->Value);
940 W.printNumber("Section", SectionName, Symbol->SectionNumber);
941 W.printEnum ("BaseType", Symbol->getBaseType(), makeArrayRef(ImageSymType));
942 W.printEnum ("ComplexType", Symbol->getComplexType(),
943 makeArrayRef(ImageSymDType));
944 W.printEnum ("StorageClass", Symbol->StorageClass,
945 makeArrayRef(ImageSymClass));
946 W.printNumber("AuxSymbolCount", Symbol->NumberOfAuxSymbols);
947
948 for (unsigned I = 0; I < Symbol->NumberOfAuxSymbols; ++I) {
David Majnemerddf28f22014-03-19 04:47:47 +0000949 if (Symbol->isFunctionDefinition()) {
Eric Christopher9cad53c2013-04-03 18:31:38 +0000950 const coff_aux_function_definition *Aux;
951 if (error(getSymbolAuxData(Obj, Symbol + I, Aux)))
952 break;
953
954 DictScope AS(W, "AuxFunctionDef");
955 W.printNumber("TagIndex", Aux->TagIndex);
956 W.printNumber("TotalSize", Aux->TotalSize);
David Majnemerf3a2af52014-03-19 04:33:27 +0000957 W.printHex("PointerToLineNumber", Aux->PointerToLinenumber);
Eric Christopher9cad53c2013-04-03 18:31:38 +0000958 W.printHex("PointerToNextFunction", Aux->PointerToNextFunction);
959 W.printBinary("Unused", makeArrayRef(Aux->Unused));
960
David Majnemerddf28f22014-03-19 04:47:47 +0000961 } else if (Symbol->isWeakExternal()) {
David Majnemerf3a2af52014-03-19 04:33:27 +0000962 const coff_aux_weak_external *Aux;
Eric Christopher9cad53c2013-04-03 18:31:38 +0000963 if (error(getSymbolAuxData(Obj, Symbol + I, Aux)))
964 break;
965
966 const coff_symbol *Linked;
967 StringRef LinkedName;
968 error_code EC;
969 if ((EC = Obj->getSymbol(Aux->TagIndex, Linked)) ||
970 (EC = Obj->getSymbolName(Linked, LinkedName))) {
971 LinkedName = "";
972 error(EC);
973 }
974
975 DictScope AS(W, "AuxWeakExternal");
976 W.printNumber("Linked", LinkedName, Aux->TagIndex);
977 W.printEnum ("Search", Aux->Characteristics,
978 makeArrayRef(WeakExternalCharacteristics));
David Majnemerf3a2af52014-03-19 04:33:27 +0000979 W.printBinary("Unused", makeArrayRef(Aux->Unused));
Eric Christopher9cad53c2013-04-03 18:31:38 +0000980
David Majnemerddf28f22014-03-19 04:47:47 +0000981 } else if (Symbol->isFileRecord()) {
Eric Christopher9cad53c2013-04-03 18:31:38 +0000982 const coff_aux_file_record *Aux;
983 if (error(getSymbolAuxData(Obj, Symbol + I, Aux)))
984 break;
985
Nico Rieck0ab8e602013-04-22 08:35:11 +0000986 DictScope AS(W, "AuxFileRecord");
987 W.printString("FileName", StringRef(Aux->FileName));
988
David Majnemerddf28f22014-03-19 04:47:47 +0000989 } else if (Symbol->isSectionDefinition()) {
Eric Christopher9cad53c2013-04-03 18:31:38 +0000990 const coff_aux_section_definition *Aux;
991 if (error(getSymbolAuxData(Obj, Symbol + I, Aux)))
992 break;
993
994 DictScope AS(W, "AuxSectionDef");
995 W.printNumber("Length", Aux->Length);
996 W.printNumber("RelocationCount", Aux->NumberOfRelocations);
997 W.printNumber("LineNumberCount", Aux->NumberOfLinenumbers);
998 W.printHex("Checksum", Aux->CheckSum);
999 W.printNumber("Number", Aux->Number);
1000 W.printEnum("Selection", Aux->Selection, makeArrayRef(ImageCOMDATSelect));
1001 W.printBinary("Unused", makeArrayRef(Aux->Unused));
1002
Nico Riecka711dee2013-04-22 08:34:59 +00001003 if (Section && Section->Characteristics & COFF::IMAGE_SCN_LNK_COMDAT
Eric Christopher9cad53c2013-04-03 18:31:38 +00001004 && Aux->Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE) {
1005 const coff_section *Assoc;
1006 StringRef AssocName;
1007 error_code EC;
1008 if ((EC = Obj->getSection(Aux->Number, Assoc)) ||
1009 (EC = Obj->getSectionName(Assoc, AssocName))) {
1010 AssocName = "";
1011 error(EC);
1012 }
1013
1014 W.printNumber("AssocSection", AssocName, Aux->Number);
1015 }
David Majnemerddf28f22014-03-19 04:47:47 +00001016 } else if (Symbol->isCLRToken()) {
Eric Christopher9cad53c2013-04-03 18:31:38 +00001017 const coff_aux_clr_token *Aux;
1018 if (error(getSymbolAuxData(Obj, Symbol + I, Aux)))
1019 break;
1020
Nico Rieck8678acd2014-03-17 01:46:52 +00001021 const coff_symbol *ReferredSym;
1022 StringRef ReferredName;
1023 error_code EC;
1024 if ((EC = Obj->getSymbol(Aux->SymbolTableIndex, ReferredSym)) ||
1025 (EC = Obj->getSymbolName(ReferredSym, ReferredName))) {
1026 ReferredName = "";
1027 error(EC);
1028 }
1029
Eric Christopher9cad53c2013-04-03 18:31:38 +00001030 DictScope AS(W, "AuxCLRToken");
1031 W.printNumber("AuxType", Aux->AuxType);
1032 W.printNumber("Reserved", Aux->Reserved);
Nico Rieck8678acd2014-03-17 01:46:52 +00001033 W.printNumber("SymbolTableIndex", ReferredName, Aux->SymbolTableIndex);
David Majnemerf3a2af52014-03-19 04:33:27 +00001034 W.printBinary("Unused", makeArrayRef(Aux->Unused));
Eric Christopher9cad53c2013-04-03 18:31:38 +00001035
1036 } else {
1037 W.startLine() << "<unhandled auxiliary record>\n";
1038 }
1039 }
1040}
1041
1042void COFFDumper::printUnwindInfo() {
1043 const coff_file_header *Header;
Rui Ueyama82ebd8e2013-06-12 19:10:33 +00001044 if (error(Obj->getCOFFHeader(Header)))
Eric Christopher9cad53c2013-04-03 18:31:38 +00001045 return;
1046
1047 ListScope D(W, "UnwindInformation");
1048 if (Header->Machine != COFF::IMAGE_FILE_MACHINE_AMD64) {
1049 W.startLine() << "Unsupported image machine type "
1050 "(currently only AMD64 is supported).\n";
1051 return;
1052 }
1053
1054 printX64UnwindInfo();
1055}
1056
1057void COFFDumper::printX64UnwindInfo() {
Alexey Samsonov27dc8392014-03-18 06:53:02 +00001058 for (const SectionRef &Section : Obj->sections()) {
Eric Christopher9cad53c2013-04-03 18:31:38 +00001059 StringRef Name;
Alexey Samsonov27dc8392014-03-18 06:53:02 +00001060 if (error(Section.getName(Name)))
Eric Christopher9cad53c2013-04-03 18:31:38 +00001061 continue;
1062 if (Name != ".pdata" && !Name.startswith(".pdata$"))
1063 continue;
1064
Alexey Samsonov27dc8392014-03-18 06:53:02 +00001065 const coff_section *PData = Obj->getCOFFSection(Section);
Eric Christopher9cad53c2013-04-03 18:31:38 +00001066
1067 ArrayRef<uint8_t> Contents;
Alexey Samsonov27dc8392014-03-18 06:53:02 +00001068 if (error(Obj->getSectionContents(PData, Contents)) || Contents.empty())
Eric Christopher9cad53c2013-04-03 18:31:38 +00001069 continue;
1070
1071 ArrayRef<RuntimeFunction> RFs(
1072 reinterpret_cast<const RuntimeFunction *>(Contents.data()),
1073 Contents.size() / sizeof(RuntimeFunction));
1074
1075 for (const RuntimeFunction *I = RFs.begin(), *E = RFs.end(); I < E; ++I) {
1076 const uint64_t OffsetInSection = std::distance(RFs.begin(), I)
1077 * sizeof(RuntimeFunction);
1078
1079 printRuntimeFunction(*I, OffsetInSection, RelocMap[PData]);
1080 }
1081 }
1082}
1083
1084void COFFDumper::printRuntimeFunction(
1085 const RuntimeFunction& RTF,
1086 uint64_t OffsetInSection,
1087 const std::vector<RelocationRef> &Rels) {
1088
1089 DictScope D(W, "RuntimeFunction");
1090 W.printString("StartAddress",
1091 formatSymbol(Rels, OffsetInSection + 0, RTF.StartAddress));
1092 W.printString("EndAddress",
1093 formatSymbol(Rels, OffsetInSection + 4, RTF.EndAddress));
1094 W.printString("UnwindInfoAddress",
1095 formatSymbol(Rels, OffsetInSection + 8, RTF.UnwindInfoOffset));
1096
1097 const coff_section* XData = 0;
1098 uint64_t UnwindInfoOffset = 0;
1099 if (error(getSection(Rels, OffsetInSection + 8, &XData, &UnwindInfoOffset)))
1100 return;
1101
1102 ArrayRef<uint8_t> XContents;
1103 if (error(Obj->getSectionContents(XData, XContents)) || XContents.empty())
1104 return;
1105
1106 UnwindInfoOffset += RTF.UnwindInfoOffset;
1107 if (UnwindInfoOffset > XContents.size())
1108 return;
1109
1110 const Win64EH::UnwindInfo *UI =
1111 reinterpret_cast<const Win64EH::UnwindInfo *>(
1112 XContents.data() + UnwindInfoOffset);
1113
1114 printUnwindInfo(*UI, UnwindInfoOffset, RelocMap[XData]);
1115}
1116
1117void COFFDumper::printUnwindInfo(
1118 const Win64EH::UnwindInfo& UI,
1119 uint64_t OffsetInSection,
1120 const std::vector<RelocationRef> &Rels) {
1121 DictScope D(W, "UnwindInfo");
1122 W.printNumber("Version", UI.getVersion());
1123 W.printFlags("Flags", UI.getFlags(), makeArrayRef(UnwindFlags));
1124 W.printNumber("PrologSize", UI.PrologSize);
1125 if (UI.getFrameRegister() != 0) {
1126 W.printEnum("FrameRegister", UI.getFrameRegister(),
1127 makeArrayRef(UnwindOpInfo));
1128 W.printHex("FrameOffset", UI.getFrameOffset());
1129 } else {
1130 W.printString("FrameRegister", StringRef("-"));
1131 W.printString("FrameOffset", StringRef("-"));
1132 }
1133
1134 W.printNumber("UnwindCodeCount", UI.NumCodes);
1135 {
1136 ListScope CodesD(W, "UnwindCodes");
1137 ArrayRef<UnwindCode> UCs(&UI.UnwindCodes[0], UI.NumCodes);
1138 for (const UnwindCode *I = UCs.begin(), *E = UCs.end(); I < E; ++I) {
1139 unsigned UsedSlots = getNumUsedSlots(*I);
1140 if (UsedSlots > UCs.size()) {
1141 errs() << "Corrupt unwind data";
1142 return;
1143 }
1144 printUnwindCode(UI, ArrayRef<UnwindCode>(I, E));
1145 I += UsedSlots - 1;
1146 }
1147 }
1148
1149 uint64_t LSDAOffset = OffsetInSection + getOffsetOfLSDA(UI);
1150 if (UI.getFlags() & (UNW_ExceptionHandler | UNW_TerminateHandler)) {
1151 W.printString("Handler", formatSymbol(Rels, LSDAOffset,
1152 UI.getLanguageSpecificHandlerOffset()));
1153 } else if (UI.getFlags() & UNW_ChainInfo) {
1154 const RuntimeFunction *Chained = UI.getChainedFunctionEntry();
1155 if (Chained) {
1156 DictScope D(W, "Chained");
1157 W.printString("StartAddress", formatSymbol(Rels, LSDAOffset + 0,
1158 Chained->StartAddress));
1159 W.printString("EndAddress", formatSymbol(Rels, LSDAOffset + 4,
1160 Chained->EndAddress));
1161 W.printString("UnwindInfoAddress", formatSymbol(Rels, LSDAOffset + 8,
1162 Chained->UnwindInfoOffset));
1163 }
1164 }
1165}
1166
1167// Prints one unwind code. Because an unwind code can occupy up to 3 slots in
1168// the unwind codes array, this function requires that the correct number of
1169// slots is provided.
1170void COFFDumper::printUnwindCode(const Win64EH::UnwindInfo& UI,
1171 ArrayRef<UnwindCode> UCs) {
1172 assert(UCs.size() >= getNumUsedSlots(UCs[0]));
1173
1174 W.startLine() << format("0x%02X: ", unsigned(UCs[0].u.CodeOffset))
1175 << getUnwindCodeTypeName(UCs[0].getUnwindOp());
1176
1177 uint32_t AllocSize = 0;
1178
1179 switch (UCs[0].getUnwindOp()) {
1180 case UOP_PushNonVol:
1181 outs() << " reg=" << getUnwindRegisterName(UCs[0].getOpInfo());
1182 break;
1183
1184 case UOP_AllocLarge:
1185 if (UCs[0].getOpInfo() == 0) {
1186 AllocSize = UCs[1].FrameOffset * 8;
1187 } else {
1188 AllocSize = getLargeSlotValue(UCs);
1189 }
1190 outs() << " size=" << AllocSize;
1191 break;
1192 case UOP_AllocSmall:
1193 outs() << " size=" << ((UCs[0].getOpInfo() + 1) * 8);
1194 break;
1195 case UOP_SetFPReg:
1196 if (UI.getFrameRegister() == 0) {
1197 outs() << " reg=<invalid>";
1198 } else {
1199 outs() << " reg=" << getUnwindRegisterName(UI.getFrameRegister())
1200 << format(", offset=0x%X", UI.getFrameOffset() * 16);
1201 }
1202 break;
1203 case UOP_SaveNonVol:
1204 outs() << " reg=" << getUnwindRegisterName(UCs[0].getOpInfo())
1205 << format(", offset=0x%X", UCs[1].FrameOffset * 8);
1206 break;
1207 case UOP_SaveNonVolBig:
1208 outs() << " reg=" << getUnwindRegisterName(UCs[0].getOpInfo())
1209 << format(", offset=0x%X", getLargeSlotValue(UCs));
1210 break;
1211 case UOP_SaveXMM128:
1212 outs() << " reg=XMM" << static_cast<uint32_t>(UCs[0].getOpInfo())
1213 << format(", offset=0x%X", UCs[1].FrameOffset * 16);
1214 break;
1215 case UOP_SaveXMM128Big:
1216 outs() << " reg=XMM" << static_cast<uint32_t>(UCs[0].getOpInfo())
1217 << format(", offset=0x%X", getLargeSlotValue(UCs));
1218 break;
1219 case UOP_PushMachFrame:
1220 outs() << " errcode=" << (UCs[0].getOpInfo() == 0 ? "no" : "yes");
1221 break;
1222 }
1223
1224 outs() << "\n";
1225}