blob: f40e1abb048e03b4786f186628b7119cba845821 [file] [log] [blame]
Chris Lattner2c52b792010-07-11 22:07:02 +00001//===-- llvm/MC/WinCOFFObjectWriter.cpp -------------------------*- 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// This file contains an implementation of a Win32 COFF object file writer.
11//
12//===----------------------------------------------------------------------===//
13
Rafael Espindola908d2ed2011-12-24 02:14:02 +000014#include "llvm/MC/MCWinCOFFObjectWriter.h"
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000015#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/StringMap.h"
17#include "llvm/ADT/StringRef.h"
David Blaikief564ab62014-04-15 05:25:03 +000018#include "llvm/ADT/STLExtras.h"
Nico Riecka37acf72013-07-06 12:13:10 +000019#include "llvm/ADT/Twine.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000020#include "llvm/MC/MCAsmLayout.h"
21#include "llvm/MC/MCAssembler.h"
22#include "llvm/MC/MCContext.h"
23#include "llvm/MC/MCExpr.h"
24#include "llvm/MC/MCObjectWriter.h"
25#include "llvm/MC/MCSection.h"
26#include "llvm/MC/MCSectionCOFF.h"
27#include "llvm/MC/MCSymbol.h"
28#include "llvm/MC/MCValue.h"
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000029#include "llvm/Support/COFF.h"
30#include "llvm/Support/Debug.h"
31#include "llvm/Support/ErrorHandling.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000032#include "llvm/Support/TimeValue.h"
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000033#include <cstdio>
34
Chris Lattner2c52b792010-07-11 22:07:02 +000035using namespace llvm;
36
Chandler Carruthf58e3762014-04-22 03:04:17 +000037#define DEBUG_TYPE "WinCOFFObjectWriter"
38
Chris Lattner2c52b792010-07-11 22:07:02 +000039namespace {
Dmitri Gribenko226fea52013-01-13 16:01:15 +000040typedef SmallString<COFF::NameSize> name;
Chris Lattner2c52b792010-07-11 22:07:02 +000041
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000042enum AuxiliaryType {
43 ATFunctionDefinition,
44 ATbfAndefSymbol,
45 ATWeakExternal,
46 ATFile,
47 ATSectionDefinition
48};
Chris Lattner2c52b792010-07-11 22:07:02 +000049
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000050struct AuxSymbol {
51 AuxiliaryType AuxType;
52 COFF::Auxiliary Aux;
53};
Chris Lattner2c52b792010-07-11 22:07:02 +000054
Michael J. Spencerd6283772010-09-27 08:58:26 +000055class COFFSymbol;
56class COFFSection;
57
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000058class COFFSymbol {
59public:
60 COFF::symbol Data;
Chris Lattner2c52b792010-07-11 22:07:02 +000061
Dmitri Gribenko226fea52013-01-13 16:01:15 +000062 typedef SmallVector<AuxSymbol, 1> AuxiliarySymbols;
Chris Lattner2c52b792010-07-11 22:07:02 +000063
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000064 name Name;
Michael J. Spencerce2e5352010-09-27 21:17:39 +000065 int Index;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000066 AuxiliarySymbols Aux;
67 COFFSymbol *Other;
Michael J. Spencerd6283772010-09-27 08:58:26 +000068 COFFSection *Section;
69 int Relocations;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000070
71 MCSymbolData const *MCData;
72
Dmitri Gribenko226fea52013-01-13 16:01:15 +000073 COFFSymbol(StringRef name);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000074 void set_name_offset(uint32_t Offset);
Michael J. Spencerd6283772010-09-27 08:58:26 +000075
76 bool should_keep() const;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000077};
78
79// This class contains staging data for a COFF relocation entry.
80struct COFFRelocation {
81 COFF::relocation Data;
82 COFFSymbol *Symb;
83
Craig Topperbb694de2014-04-13 04:57:38 +000084 COFFRelocation() : Symb(nullptr) {}
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000085 static size_t size() { return COFF::RelocationSize; }
86};
87
88typedef std::vector<COFFRelocation> relocations;
89
90class COFFSection {
91public:
92 COFF::section Header;
93
94 std::string Name;
Michael J. Spencerce2e5352010-09-27 21:17:39 +000095 int Number;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000096 MCSectionData const *MCData;
Michael J. Spencerd6283772010-09-27 08:58:26 +000097 COFFSymbol *Symbol;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000098 relocations Relocations;
99
Dmitri Gribenko226fea52013-01-13 16:01:15 +0000100 COFFSection(StringRef name);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000101 static size_t size();
102};
103
104// This class holds the COFF string table.
105class StringTable {
Dmitri Gribenko226fea52013-01-13 16:01:15 +0000106 typedef StringMap<size_t> map;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000107 map Map;
108
109 void update_length();
110public:
111 std::vector<char> Data;
112
113 StringTable();
114 size_t size() const;
Dmitri Gribenko226fea52013-01-13 16:01:15 +0000115 size_t insert(StringRef String);
Yaron Kerencca43c12014-09-16 21:31:04 +0000116 void clear() {
117 Map.clear();
118 Data.resize(4);
119 update_length();
120 }
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000121};
122
123class WinCOFFObjectWriter : public MCObjectWriter {
124public:
125
David Blaikief564ab62014-04-15 05:25:03 +0000126 typedef std::vector<std::unique_ptr<COFFSymbol>> symbols;
127 typedef std::vector<std::unique_ptr<COFFSection>> sections;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000128
Michael J. Spencer17990d52010-10-16 08:25:57 +0000129 typedef DenseMap<MCSymbol const *, COFFSymbol *> symbol_map;
130 typedef DenseMap<MCSection const *, COFFSection *> section_map;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000131
Ahmed Charles56440fd2014-03-06 05:51:42 +0000132 std::unique_ptr<MCWinCOFFObjectTargetWriter> TargetObjectWriter;
Rafael Espindola908d2ed2011-12-24 02:14:02 +0000133
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000134 // Root level file contents.
135 COFF::header Header;
136 sections Sections;
137 symbols Symbols;
138 StringTable Strings;
139
140 // Maps used during object file creation.
141 section_map SectionMap;
142 symbol_map SymbolMap;
143
David Majnemer4d571592014-09-15 19:42:42 +0000144 bool UseBigObj;
145
Rafael Espindola908d2ed2011-12-24 02:14:02 +0000146 WinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW, raw_ostream &OS);
Yaron Kerencca43c12014-09-16 21:31:04 +0000147
148 void reset() override {
149 memset(&Header, 0, sizeof(Header));
150 Header.Machine = TargetObjectWriter->getMachine();
151 Sections.clear();
152 Symbols.clear();
153 Strings.clear();
154 SectionMap.clear();
155 SymbolMap.clear();
156 MCObjectWriter::reset();
157 }
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000158
Michael J. Spencer17990d52010-10-16 08:25:57 +0000159 COFFSymbol *createSymbol(StringRef Name);
160 COFFSymbol *GetOrCreateCOFFSymbol(const MCSymbol * Symbol);
161 COFFSection *createSection(StringRef Name);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000162
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000163 template <typename object_t, typename list_t>
Dmitri Gribenko226fea52013-01-13 16:01:15 +0000164 object_t *createCOFFEntity(StringRef Name, list_t &List);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000165
166 void DefineSection(MCSectionData const &SectionData);
Reid Klecknerc1e76212013-09-17 23:18:05 +0000167 void DefineSymbol(MCSymbolData const &SymbolData, MCAssembler &Assembler,
168 const MCAsmLayout &Layout);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000169
Michael J. Spencerd6283772010-09-27 08:58:26 +0000170 void MakeSymbolReal(COFFSymbol &S, size_t Index);
171 void MakeSectionReal(COFFSection &S, size_t Number);
172
David Majnemer299674e2014-07-13 04:31:19 +0000173 bool ExportSymbol(const MCSymbol &Symbol, MCAssembler &Asm);
Reid Kleckner8b2ad2a2013-11-18 23:08:12 +0000174
Michael J. Spencerd6283772010-09-27 08:58:26 +0000175 bool IsPhysicalSection(COFFSection *S);
176
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000177 // Entity writing methods.
178
179 void WriteFileHeader(const COFF::header &Header);
David Blaikief564ab62014-04-15 05:25:03 +0000180 void WriteSymbol(const COFFSymbol &S);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000181 void WriteAuxiliarySymbols(const COFFSymbol::AuxiliarySymbols &S);
182 void WriteSectionHeader(const COFF::section &S);
183 void WriteRelocation(const COFF::relocation &R);
184
185 // MCObjectWriter interface implementation.
186
Craig Topper34a61bc2014-03-08 07:02:02 +0000187 void ExecutePostLayoutBinding(MCAssembler &Asm,
188 const MCAsmLayout &Layout) override;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000189
Craig Topper34a61bc2014-03-08 07:02:02 +0000190 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
191 const MCFragment *Fragment, const MCFixup &Fixup,
Rafael Espindola5904e122014-03-29 06:26:49 +0000192 MCValue Target, bool &IsPCRel,
193 uint64_t &FixedValue) override;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000194
Craig Topper34a61bc2014-03-08 07:02:02 +0000195 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000196};
Chris Lattner2c52b792010-07-11 22:07:02 +0000197}
198
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000199static inline void write_uint32_le(void *Data, uint32_t const &Value) {
200 uint8_t *Ptr = reinterpret_cast<uint8_t *>(Data);
201 Ptr[0] = (Value & 0x000000FF) >> 0;
202 Ptr[1] = (Value & 0x0000FF00) >> 8;
203 Ptr[2] = (Value & 0x00FF0000) >> 16;
204 Ptr[3] = (Value & 0xFF000000) >> 24;
205}
206
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000207//------------------------------------------------------------------------------
208// Symbol class implementation
209
Dmitri Gribenko226fea52013-01-13 16:01:15 +0000210COFFSymbol::COFFSymbol(StringRef name)
Michael J. Spencerd6283772010-09-27 08:58:26 +0000211 : Name(name.begin(), name.end())
Craig Topperbb694de2014-04-13 04:57:38 +0000212 , Other(nullptr)
213 , Section(nullptr)
Michael J. Spencerd6283772010-09-27 08:58:26 +0000214 , Relocations(0)
Craig Topperbb694de2014-04-13 04:57:38 +0000215 , MCData(nullptr) {
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000216 memset(&Data, 0, sizeof(Data));
217}
218
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000219// In the case that the name does not fit within 8 bytes, the offset
220// into the string table is stored in the last 4 bytes instead, leaving
221// the first 4 bytes as 0.
222void COFFSymbol::set_name_offset(uint32_t Offset) {
223 write_uint32_le(Data.Name + 0, 0);
224 write_uint32_le(Data.Name + 4, Offset);
225}
226
Michael J. Spencerd6283772010-09-27 08:58:26 +0000227/// logic to decide if the symbol should be reported in the symbol table
228bool COFFSymbol::should_keep() const {
229 // no section means its external, keep it
Craig Topperbb694de2014-04-13 04:57:38 +0000230 if (!Section)
Michael J. Spencerd6283772010-09-27 08:58:26 +0000231 return true;
232
233 // if it has relocations pointing at it, keep it
234 if (Relocations > 0) {
235 assert(Section->Number != -1 && "Sections with relocations must be real!");
236 return true;
237 }
238
239 // if the section its in is being droped, drop it
240 if (Section->Number == -1)
241 return false;
242
243 // if it is the section symbol, keep it
244 if (Section->Symbol == this)
245 return true;
246
247 // if its temporary, drop it
248 if (MCData && MCData->getSymbol().isTemporary())
249 return false;
250
251 // otherwise, keep it
252 return true;
253}
254
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000255//------------------------------------------------------------------------------
256// Section class implementation
257
Dmitri Gribenko226fea52013-01-13 16:01:15 +0000258COFFSection::COFFSection(StringRef name)
Michael J. Spencerd6283772010-09-27 08:58:26 +0000259 : Name(name)
Craig Topperbb694de2014-04-13 04:57:38 +0000260 , MCData(nullptr)
261 , Symbol(nullptr) {
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000262 memset(&Header, 0, sizeof(Header));
263}
264
265size_t COFFSection::size() {
266 return COFF::SectionSize;
267}
268
269//------------------------------------------------------------------------------
270// StringTable class implementation
271
272/// Write the length of the string table into Data.
273/// The length of the string table includes uint32 length header.
274void StringTable::update_length() {
275 write_uint32_le(&Data.front(), Data.size());
276}
277
278StringTable::StringTable() {
279 // The string table data begins with the length of the entire string table
280 // including the length header. Allocate space for this header.
281 Data.resize(4);
Michael J. Spencer5ca95bc2011-11-08 19:52:32 +0000282 update_length();
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000283}
284
285size_t StringTable::size() const {
286 return Data.size();
287}
288
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000289/// Add String to the table iff it is not already there.
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000290/// @returns the index into the string table where the string is now located.
Dmitri Gribenko226fea52013-01-13 16:01:15 +0000291size_t StringTable::insert(StringRef String) {
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000292 map::iterator i = Map.find(String);
293
294 if (i != Map.end())
295 return i->second;
296
297 size_t Offset = Data.size();
298
299 // Insert string data into string table.
300 Data.insert(Data.end(), String.begin(), String.end());
301 Data.push_back('\0');
302
303 // Put a reference to it in the map.
304 Map[String] = Offset;
305
306 // Update the internal length field.
307 update_length();
308
309 return Offset;
310}
311
312//------------------------------------------------------------------------------
313// WinCOFFObjectWriter class implementation
314
Rafael Espindola908d2ed2011-12-24 02:14:02 +0000315WinCOFFObjectWriter::WinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW,
316 raw_ostream &OS)
David Majnemer4d571592014-09-15 19:42:42 +0000317 : MCObjectWriter(OS, true), TargetObjectWriter(MOTW) {
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000318 memset(&Header, 0, sizeof(Header));
Michael J. Spencer377aa202010-08-21 05:58:13 +0000319
Rafael Espindola908d2ed2011-12-24 02:14:02 +0000320 Header.Machine = TargetObjectWriter->getMachine();
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000321}
322
Michael J. Spencer17990d52010-10-16 08:25:57 +0000323COFFSymbol *WinCOFFObjectWriter::createSymbol(StringRef Name) {
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000324 return createCOFFEntity<COFFSymbol>(Name, Symbols);
325}
326
Michael J. Spencer17990d52010-10-16 08:25:57 +0000327COFFSymbol *WinCOFFObjectWriter::GetOrCreateCOFFSymbol(const MCSymbol * Symbol){
328 symbol_map::iterator i = SymbolMap.find(Symbol);
329 if (i != SymbolMap.end())
330 return i->second;
331 COFFSymbol *RetSymbol
332 = createCOFFEntity<COFFSymbol>(Symbol->getName(), Symbols);
333 SymbolMap[Symbol] = RetSymbol;
334 return RetSymbol;
335}
336
Dmitri Gribenko226fea52013-01-13 16:01:15 +0000337COFFSection *WinCOFFObjectWriter::createSection(StringRef Name) {
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000338 return createCOFFEntity<COFFSection>(Name, Sections);
339}
340
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000341/// A template used to lookup or create a symbol/section, and initialize it if
342/// needed.
343template <typename object_t, typename list_t>
Dmitri Gribenko226fea52013-01-13 16:01:15 +0000344object_t *WinCOFFObjectWriter::createCOFFEntity(StringRef Name,
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000345 list_t &List) {
David Blaikief564ab62014-04-15 05:25:03 +0000346 List.push_back(make_unique<object_t>(Name));
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000347
David Blaikief564ab62014-04-15 05:25:03 +0000348 return List.back().get();
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000349}
350
351/// This function takes a section data object from the assembler
352/// and creates the associated COFF section staging object.
353void WinCOFFObjectWriter::DefineSection(MCSectionData const &SectionData) {
Michael J. Spencerbe52c622010-10-09 11:00:37 +0000354 assert(SectionData.getSection().getVariant() == MCSection::SV_COFF
Alp Tokerf907b892013-12-05 05:44:44 +0000355 && "Got non-COFF section in the COFF backend!");
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000356 // FIXME: Not sure how to verify this (at least in a debug build).
357 MCSectionCOFF const &Sec =
358 static_cast<MCSectionCOFF const &>(SectionData.getSection());
359
360 COFFSection *coff_section = createSection(Sec.getSectionName());
361 COFFSymbol *coff_symbol = createSymbol(Sec.getSectionName());
Rafael Espindola0766ae02014-06-06 19:26:12 +0000362 if (Sec.getSelection() != COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE) {
363 if (const MCSymbol *S = Sec.getCOMDATSymbol()) {
364 COFFSymbol *COMDATSymbol = GetOrCreateCOFFSymbol(S);
365 if (COMDATSymbol->Section)
366 report_fatal_error("two sections have the same comdat");
367 COMDATSymbol->Section = coff_section;
368 }
369 }
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000370
Michael J. Spencerd6283772010-09-27 08:58:26 +0000371 coff_section->Symbol = coff_symbol;
372 coff_symbol->Section = coff_section;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000373 coff_symbol->Data.StorageClass = COFF::IMAGE_SYM_CLASS_STATIC;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000374
375 // In this case the auxiliary symbol is a Section Definition.
376 coff_symbol->Aux.resize(1);
377 memset(&coff_symbol->Aux[0], 0, sizeof(coff_symbol->Aux[0]));
378 coff_symbol->Aux[0].AuxType = ATSectionDefinition;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000379 coff_symbol->Aux[0].Aux.SectionDefinition.Selection = Sec.getSelection();
380
381 coff_section->Header.Characteristics = Sec.getCharacteristics();
382
383 uint32_t &Characteristics = coff_section->Header.Characteristics;
384 switch (SectionData.getAlignment()) {
385 case 1: Characteristics |= COFF::IMAGE_SCN_ALIGN_1BYTES; break;
386 case 2: Characteristics |= COFF::IMAGE_SCN_ALIGN_2BYTES; break;
387 case 4: Characteristics |= COFF::IMAGE_SCN_ALIGN_4BYTES; break;
388 case 8: Characteristics |= COFF::IMAGE_SCN_ALIGN_8BYTES; break;
389 case 16: Characteristics |= COFF::IMAGE_SCN_ALIGN_16BYTES; break;
390 case 32: Characteristics |= COFF::IMAGE_SCN_ALIGN_32BYTES; break;
391 case 64: Characteristics |= COFF::IMAGE_SCN_ALIGN_64BYTES; break;
392 case 128: Characteristics |= COFF::IMAGE_SCN_ALIGN_128BYTES; break;
393 case 256: Characteristics |= COFF::IMAGE_SCN_ALIGN_256BYTES; break;
394 case 512: Characteristics |= COFF::IMAGE_SCN_ALIGN_512BYTES; break;
395 case 1024: Characteristics |= COFF::IMAGE_SCN_ALIGN_1024BYTES; break;
396 case 2048: Characteristics |= COFF::IMAGE_SCN_ALIGN_2048BYTES; break;
397 case 4096: Characteristics |= COFF::IMAGE_SCN_ALIGN_4096BYTES; break;
398 case 8192: Characteristics |= COFF::IMAGE_SCN_ALIGN_8192BYTES; break;
399 default:
400 llvm_unreachable("unsupported section alignment");
401 }
402
403 // Bind internal COFF section to MC section.
404 coff_section->MCData = &SectionData;
Michael J. Spencer17990d52010-10-16 08:25:57 +0000405 SectionMap[&SectionData.getSection()] = coff_section;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000406}
407
Rafael Espindolaff68cb72014-05-01 00:10:17 +0000408static uint64_t getSymbolValue(const MCSymbolData &Data,
409 const MCAsmLayout &Layout) {
410 if (Data.isCommon() && Data.isExternal())
411 return Data.getCommonSize();
412
413 uint64_t Res;
414 if (!Layout.getSymbolOffset(&Data, Res))
415 return 0;
416
417 return Res;
418}
419
David Majnemera9bdb322014-04-08 22:33:40 +0000420/// This function takes a symbol data object from the assembler
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000421/// and creates the associated COFF symbol staging object.
Peter Collingbourne89886872013-04-22 18:48:56 +0000422void WinCOFFObjectWriter::DefineSymbol(MCSymbolData const &SymbolData,
Reid Klecknerc1e76212013-09-17 23:18:05 +0000423 MCAssembler &Assembler,
424 const MCAsmLayout &Layout) {
Peter Collingbourne89886872013-04-22 18:48:56 +0000425 MCSymbol const &Symbol = SymbolData.getSymbol();
Michael J. Spencer54b24e12013-01-29 22:10:07 +0000426 COFFSymbol *coff_symbol = GetOrCreateCOFFSymbol(&Symbol);
Peter Collingbourne89886872013-04-22 18:48:56 +0000427 SymbolMap[&Symbol] = coff_symbol;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000428
Michael J. Spencer17990d52010-10-16 08:25:57 +0000429 if (SymbolData.getFlags() & COFF::SF_WeakExternal) {
430 coff_symbol->Data.StorageClass = COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL;
431
Michael J. Spencer54b24e12013-01-29 22:10:07 +0000432 if (Symbol.isVariable()) {
Peter Collingbourne89886872013-04-22 18:48:56 +0000433 const MCSymbolRefExpr *SymRef =
434 dyn_cast<MCSymbolRefExpr>(Symbol.getVariableValue());
Michael J. Spencer17990d52010-10-16 08:25:57 +0000435
Peter Collingbourne89886872013-04-22 18:48:56 +0000436 if (!SymRef)
437 report_fatal_error("Weak externals may only alias symbols");
Michael J. Spencer17990d52010-10-16 08:25:57 +0000438
Peter Collingbourne89886872013-04-22 18:48:56 +0000439 coff_symbol->Other = GetOrCreateCOFFSymbol(&SymRef->getSymbol());
Michael J. Spencer17990d52010-10-16 08:25:57 +0000440 } else {
441 std::string WeakName = std::string(".weak.")
Michael J. Spencer54b24e12013-01-29 22:10:07 +0000442 + Symbol.getName().str()
Michael J. Spencer17990d52010-10-16 08:25:57 +0000443 + ".default";
444 COFFSymbol *WeakDefault = createSymbol(WeakName);
445 WeakDefault->Data.SectionNumber = COFF::IMAGE_SYM_ABSOLUTE;
446 WeakDefault->Data.StorageClass = COFF::IMAGE_SYM_CLASS_EXTERNAL;
447 WeakDefault->Data.Type = 0;
448 WeakDefault->Data.Value = 0;
449 coff_symbol->Other = WeakDefault;
450 }
451
452 // Setup the Weak External auxiliary symbol.
453 coff_symbol->Aux.resize(1);
454 memset(&coff_symbol->Aux[0], 0, sizeof(coff_symbol->Aux[0]));
455 coff_symbol->Aux[0].AuxType = ATWeakExternal;
456 coff_symbol->Aux[0].Aux.WeakExternal.TagIndex = 0;
457 coff_symbol->Aux[0].Aux.WeakExternal.Characteristics =
458 COFF::IMAGE_WEAK_EXTERN_SEARCH_LIBRARY;
Peter Collingbourne89886872013-04-22 18:48:56 +0000459
460 coff_symbol->MCData = &SymbolData;
461 } else {
Rafael Espindolaea9f9d42014-05-01 19:02:03 +0000462 const MCSymbolData &ResSymData = Assembler.getSymbolData(Symbol);
Rafael Espindola575f79a2014-05-01 13:37:57 +0000463 const MCSymbol *Base = Layout.getBaseSymbol(Symbol);
Rafael Espindolaff68cb72014-05-01 00:10:17 +0000464 coff_symbol->Data.Value = getSymbolValue(ResSymData, Layout);
Reid Klecknerc1e76212013-09-17 23:18:05 +0000465
Peter Collingbourne89886872013-04-22 18:48:56 +0000466 coff_symbol->Data.Type = (ResSymData.getFlags() & 0x0000FFFF) >> 0;
467 coff_symbol->Data.StorageClass = (ResSymData.getFlags() & 0x00FF0000) >> 16;
468
469 // If no storage class was specified in the streamer, define it here.
470 if (coff_symbol->Data.StorageClass == 0) {
David Majnemer299674e2014-07-13 04:31:19 +0000471 bool IsExternal =
472 ResSymData.isExternal() ||
473 (!ResSymData.getFragment() && !ResSymData.getSymbol().isVariable());
Peter Collingbourne89886872013-04-22 18:48:56 +0000474
David Majnemer299674e2014-07-13 04:31:19 +0000475 coff_symbol->Data.StorageClass = IsExternal
476 ? COFF::IMAGE_SYM_CLASS_EXTERNAL
477 : COFF::IMAGE_SYM_CLASS_STATIC;
Peter Collingbourne89886872013-04-22 18:48:56 +0000478 }
479
Rafael Espindola575f79a2014-05-01 13:37:57 +0000480 if (!Base) {
Reid Klecknerc1e76212013-09-17 23:18:05 +0000481 coff_symbol->Data.SectionNumber = COFF::IMAGE_SYM_ABSOLUTE;
Rafael Espindola575f79a2014-05-01 13:37:57 +0000482 } else {
483 const MCSymbolData &BaseData = Assembler.getSymbolData(*Base);
Rafael Espindola0766ae02014-06-06 19:26:12 +0000484 if (BaseData.Fragment) {
485 COFFSection *Sec =
Rafael Espindola575f79a2014-05-01 13:37:57 +0000486 SectionMap[&BaseData.Fragment->getParent()->getSection()];
Rafael Espindola0766ae02014-06-06 19:26:12 +0000487
488 if (coff_symbol->Section && coff_symbol->Section != Sec)
489 report_fatal_error("conflicting sections for symbol");
490
491 coff_symbol->Section = Sec;
492 }
Rafael Espindola575f79a2014-05-01 13:37:57 +0000493 }
Peter Collingbourne89886872013-04-22 18:48:56 +0000494
495 coff_symbol->MCData = &ResSymData;
Michael J. Spencer17990d52010-10-16 08:25:57 +0000496 }
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000497}
498
Nico Rieck01143f92014-02-25 09:50:40 +0000499// Maximum offsets for different string table entry encodings.
500static const unsigned Max6DecimalOffset = 999999;
501static const unsigned Max7DecimalOffset = 9999999;
502static const uint64_t MaxBase64Offset = 0xFFFFFFFFFULL; // 64^6, including 0
503
Nico Rieck9d2c15e2014-02-22 16:12:20 +0000504// Encode a string table entry offset in base 64, padded to 6 chars, and
505// prefixed with a double slash: '//AAAAAA', '//AAAAAB', ...
506// Buffer must be at least 8 bytes large. No terminating null appended.
507static void encodeBase64StringEntry(char* Buffer, uint64_t Value) {
Nico Rieck01143f92014-02-25 09:50:40 +0000508 assert(Value > Max7DecimalOffset && Value <= MaxBase64Offset &&
Nico Rieck9d2c15e2014-02-22 16:12:20 +0000509 "Illegal section name encoding for value");
510
511 static const char Alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
512 "abcdefghijklmnopqrstuvwxyz"
513 "0123456789+/";
514
515 Buffer[0] = '/';
516 Buffer[1] = '/';
517
518 char* Ptr = Buffer + 7;
519 for (unsigned i = 0; i < 6; ++i) {
520 unsigned Rem = Value % 64;
521 Value /= 64;
522 *(Ptr--) = Alphabet[Rem];
523 }
524}
525
Michael J. Spencerd6283772010-09-27 08:58:26 +0000526/// making a section real involves assigned it a number and putting
527/// name into the string table if needed
528void WinCOFFObjectWriter::MakeSectionReal(COFFSection &S, size_t Number) {
529 if (S.Name.size() > COFF::NameSize) {
Nico Rieck2c9c89b2013-07-29 12:30:12 +0000530 uint64_t StringTableEntry = Strings.insert(S.Name.c_str());
Michael J. Spencerd6283772010-09-27 08:58:26 +0000531
Nico Rieck01143f92014-02-25 09:50:40 +0000532 if (StringTableEntry <= Max6DecimalOffset) {
Nico Rieck2c9c89b2013-07-29 12:30:12 +0000533 std::sprintf(S.Header.Name, "/%d", unsigned(StringTableEntry));
Nico Rieck01143f92014-02-25 09:50:40 +0000534 } else if (StringTableEntry <= Max7DecimalOffset) {
Nico Rieck2c9c89b2013-07-29 12:30:12 +0000535 // With seven digits, we have to skip the terminating null. Because
536 // sprintf always appends it, we use a larger temporary buffer.
537 char buffer[9] = { };
538 std::sprintf(buffer, "/%d", unsigned(StringTableEntry));
539 std::memcpy(S.Header.Name, buffer, 8);
Nico Rieck01143f92014-02-25 09:50:40 +0000540 } else if (StringTableEntry <= MaxBase64Offset) {
Nico Rieck9d2c15e2014-02-22 16:12:20 +0000541 // Starting with 10,000,000, offsets are encoded as base64.
542 encodeBase64StringEntry(S.Header.Name, StringTableEntry);
Nico Rieck2c9c89b2013-07-29 12:30:12 +0000543 } else {
Nico Rieck9d2c15e2014-02-22 16:12:20 +0000544 report_fatal_error("COFF string table is greater than 64 GB.");
Nico Rieck2c9c89b2013-07-29 12:30:12 +0000545 }
Michael J. Spencerd6283772010-09-27 08:58:26 +0000546 } else
547 std::memcpy(S.Header.Name, S.Name.c_str(), S.Name.size());
548
549 S.Number = Number;
550 S.Symbol->Data.SectionNumber = S.Number;
551 S.Symbol->Aux[0].Aux.SectionDefinition.Number = S.Number;
552}
553
554void WinCOFFObjectWriter::MakeSymbolReal(COFFSymbol &S, size_t Index) {
555 if (S.Name.size() > COFF::NameSize) {
556 size_t StringTableEntry = Strings.insert(S.Name.c_str());
557
558 S.set_name_offset(StringTableEntry);
559 } else
560 std::memcpy(S.Data.Name, S.Name.c_str(), S.Name.size());
561 S.Index = Index;
562}
563
David Majnemer299674e2014-07-13 04:31:19 +0000564bool WinCOFFObjectWriter::ExportSymbol(const MCSymbol &Symbol,
Reid Kleckner8b2ad2a2013-11-18 23:08:12 +0000565 MCAssembler &Asm) {
566 // This doesn't seem to be right. Strings referred to from the .data section
567 // need symbols so they can be linked to code in the .text section right?
568
David Majnemer299674e2014-07-13 04:31:19 +0000569 // return Asm.isSymbolLinkerVisible(Symbol);
570
571 // Non-temporary labels should always be visible to the linker.
572 if (!Symbol.isTemporary())
573 return true;
574
575 // Absolute temporary labels are never visible.
576 if (!Symbol.isInSection())
577 return false;
Reid Kleckner8b2ad2a2013-11-18 23:08:12 +0000578
579 // For now, all non-variable symbols are exported,
580 // the linker will sort the rest out for us.
David Majnemer299674e2014-07-13 04:31:19 +0000581 return !Symbol.isVariable();
Reid Kleckner8b2ad2a2013-11-18 23:08:12 +0000582}
583
Michael J. Spencerd6283772010-09-27 08:58:26 +0000584bool WinCOFFObjectWriter::IsPhysicalSection(COFFSection *S) {
585 return (S->Header.Characteristics
586 & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) == 0;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000587}
588
589//------------------------------------------------------------------------------
590// entity writing methods
591
592void WinCOFFObjectWriter::WriteFileHeader(const COFF::header &Header) {
David Majnemer4d571592014-09-15 19:42:42 +0000593 if (UseBigObj) {
594 WriteLE16(COFF::IMAGE_FILE_MACHINE_UNKNOWN);
595 WriteLE16(0xFFFF);
596 WriteLE16(COFF::BigObjHeader::MinBigObjectVersion);
597 WriteLE16(Header.Machine);
598 WriteLE32(Header.TimeDateStamp);
599 for (uint8_t MagicChar : COFF::BigObjMagic)
600 Write8(MagicChar);
David Majnemer15f7ed92014-09-15 20:28:38 +0000601 WriteLE32(0);
602 WriteLE32(0);
603 WriteLE32(0);
604 WriteLE32(0);
David Majnemer4d571592014-09-15 19:42:42 +0000605 WriteLE32(Header.NumberOfSections);
606 WriteLE32(Header.PointerToSymbolTable);
607 WriteLE32(Header.NumberOfSymbols);
608 } else {
609 WriteLE16(Header.Machine);
610 WriteLE16(static_cast<int16_t>(Header.NumberOfSections));
611 WriteLE32(Header.TimeDateStamp);
612 WriteLE32(Header.PointerToSymbolTable);
613 WriteLE32(Header.NumberOfSymbols);
614 WriteLE16(Header.SizeOfOptionalHeader);
615 WriteLE16(Header.Characteristics);
616 }
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000617}
618
David Blaikief564ab62014-04-15 05:25:03 +0000619void WinCOFFObjectWriter::WriteSymbol(const COFFSymbol &S) {
620 WriteBytes(StringRef(S.Data.Name, COFF::NameSize));
621 WriteLE32(S.Data.Value);
David Majnemer4d571592014-09-15 19:42:42 +0000622 if (UseBigObj)
623 WriteLE32(S.Data.SectionNumber);
624 else
625 WriteLE16(static_cast<int16_t>(S.Data.SectionNumber));
David Blaikief564ab62014-04-15 05:25:03 +0000626 WriteLE16(S.Data.Type);
627 Write8(S.Data.StorageClass);
628 Write8(S.Data.NumberOfAuxSymbols);
629 WriteAuxiliarySymbols(S.Aux);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000630}
631
632void WinCOFFObjectWriter::WriteAuxiliarySymbols(
633 const COFFSymbol::AuxiliarySymbols &S) {
634 for(COFFSymbol::AuxiliarySymbols::const_iterator i = S.begin(), e = S.end();
635 i != e; ++i) {
636 switch(i->AuxType) {
637 case ATFunctionDefinition:
638 WriteLE32(i->Aux.FunctionDefinition.TagIndex);
639 WriteLE32(i->Aux.FunctionDefinition.TotalSize);
640 WriteLE32(i->Aux.FunctionDefinition.PointerToLinenumber);
641 WriteLE32(i->Aux.FunctionDefinition.PointerToNextFunction);
642 WriteZeros(sizeof(i->Aux.FunctionDefinition.unused));
David Majnemer4d571592014-09-15 19:42:42 +0000643 if (UseBigObj)
644 WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000645 break;
646 case ATbfAndefSymbol:
647 WriteZeros(sizeof(i->Aux.bfAndefSymbol.unused1));
648 WriteLE16(i->Aux.bfAndefSymbol.Linenumber);
649 WriteZeros(sizeof(i->Aux.bfAndefSymbol.unused2));
650 WriteLE32(i->Aux.bfAndefSymbol.PointerToNextFunction);
651 WriteZeros(sizeof(i->Aux.bfAndefSymbol.unused3));
David Majnemer4d571592014-09-15 19:42:42 +0000652 if (UseBigObj)
653 WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000654 break;
655 case ATWeakExternal:
656 WriteLE32(i->Aux.WeakExternal.TagIndex);
657 WriteLE32(i->Aux.WeakExternal.Characteristics);
658 WriteZeros(sizeof(i->Aux.WeakExternal.unused));
David Majnemer4d571592014-09-15 19:42:42 +0000659 if (UseBigObj)
660 WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000661 break;
662 case ATFile:
David Majnemer4d571592014-09-15 19:42:42 +0000663 WriteBytes(
664 StringRef(reinterpret_cast<const char *>(&i->Aux),
665 UseBigObj ? COFF::Symbol32Size : COFF::Symbol16Size));
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000666 break;
667 case ATSectionDefinition:
668 WriteLE32(i->Aux.SectionDefinition.Length);
669 WriteLE16(i->Aux.SectionDefinition.NumberOfRelocations);
670 WriteLE16(i->Aux.SectionDefinition.NumberOfLinenumbers);
671 WriteLE32(i->Aux.SectionDefinition.CheckSum);
David Majnemer4d571592014-09-15 19:42:42 +0000672 WriteLE16(static_cast<int16_t>(i->Aux.SectionDefinition.Number));
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000673 Write8(i->Aux.SectionDefinition.Selection);
674 WriteZeros(sizeof(i->Aux.SectionDefinition.unused));
David Majnemer4d571592014-09-15 19:42:42 +0000675 WriteLE16(static_cast<int16_t>(i->Aux.SectionDefinition.Number >> 16));
676 if (UseBigObj)
677 WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000678 break;
679 }
680 }
681}
682
683void WinCOFFObjectWriter::WriteSectionHeader(const COFF::section &S) {
684 WriteBytes(StringRef(S.Name, COFF::NameSize));
685
686 WriteLE32(S.VirtualSize);
687 WriteLE32(S.VirtualAddress);
688 WriteLE32(S.SizeOfRawData);
689 WriteLE32(S.PointerToRawData);
690 WriteLE32(S.PointerToRelocations);
691 WriteLE32(S.PointerToLineNumbers);
692 WriteLE16(S.NumberOfRelocations);
693 WriteLE16(S.NumberOfLineNumbers);
694 WriteLE32(S.Characteristics);
695}
696
697void WinCOFFObjectWriter::WriteRelocation(const COFF::relocation &R) {
698 WriteLE32(R.VirtualAddress);
699 WriteLE32(R.SymbolTableIndex);
700 WriteLE16(R.Type);
Chris Lattner2c52b792010-07-11 22:07:02 +0000701}
702
703////////////////////////////////////////////////////////////////////////////////
704// MCObjectWriter interface implementations
705
Rafael Espindola93e3cf02010-12-07 00:27:36 +0000706void WinCOFFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
707 const MCAsmLayout &Layout) {
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000708 // "Define" each section & symbol. This creates section & symbol
Michael J. Spencerd6283772010-09-27 08:58:26 +0000709 // entries in the staging area.
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000710 for (const auto & Section : Asm)
711 DefineSection(Section);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000712
David Blaikie583a31c2014-04-18 18:24:25 +0000713 for (MCSymbolData &SD : Asm.symbols())
David Majnemer299674e2014-07-13 04:31:19 +0000714 if (ExportSymbol(SD.getSymbol(), Asm))
David Blaikie583a31c2014-04-18 18:24:25 +0000715 DefineSymbol(SD, Asm, Layout);
Chris Lattner2c52b792010-07-11 22:07:02 +0000716}
717
718void WinCOFFObjectWriter::RecordRelocation(const MCAssembler &Asm,
719 const MCAsmLayout &Layout,
720 const MCFragment *Fragment,
721 const MCFixup &Fixup,
722 MCValue Target,
Rafael Espindola5904e122014-03-29 06:26:49 +0000723 bool &IsPCRel,
Chris Lattner2c52b792010-07-11 22:07:02 +0000724 uint64_t &FixedValue) {
Craig Topperbb694de2014-04-13 04:57:38 +0000725 assert(Target.getSymA() && "Relocation must reference a symbol!");
Michael J. Spencerccd28d02010-08-24 21:04:52 +0000726
Reid Klecknerdae7b4e2013-07-15 19:41:21 +0000727 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
728 const MCSymbol &A = Symbol.AliasedSymbol();
Timur Iskhodzhanov3e4ac4e2014-01-30 21:13:05 +0000729 if (!Asm.hasSymbolData(A))
730 Asm.getContext().FatalError(
731 Fixup.getLoc(),
732 Twine("symbol '") + A.getName() + "' can not be undefined");
733
David Blaikie908f4d42014-04-24 16:59:40 +0000734 const MCSymbolData &A_SD = Asm.getSymbolData(A);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000735
736 MCSectionData const *SectionData = Fragment->getParent();
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000737
Michael J. Spencerccd28d02010-08-24 21:04:52 +0000738 // Mark this symbol as requiring an entry in the symbol table.
Michael J. Spencer17990d52010-10-16 08:25:57 +0000739 assert(SectionMap.find(&SectionData->getSection()) != SectionMap.end() &&
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000740 "Section must already have been defined in ExecutePostLayoutBinding!");
Michael J. Spencer17990d52010-10-16 08:25:57 +0000741 assert(SymbolMap.find(&A_SD.getSymbol()) != SymbolMap.end() &&
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000742 "Symbol must already have been defined in ExecutePostLayoutBinding!");
743
Michael J. Spencer17990d52010-10-16 08:25:57 +0000744 COFFSection *coff_section = SectionMap[&SectionData->getSection()];
745 COFFSymbol *coff_symbol = SymbolMap[&A_SD.getSymbol()];
Rafael Espindolaed164772011-04-20 14:01:45 +0000746 const MCSymbolRefExpr *SymB = Target.getSymB();
David Majnemera45a1762014-01-06 07:39:46 +0000747 bool CrossSection = false;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000748
David Majnemera45a1762014-01-06 07:39:46 +0000749 if (SymB) {
750 const MCSymbol *B = &SymB->getSymbol();
David Blaikie908f4d42014-04-24 16:59:40 +0000751 const MCSymbolData &B_SD = Asm.getSymbolData(*B);
David Majnemera45a1762014-01-06 07:39:46 +0000752 if (!B_SD.getFragment())
753 Asm.getContext().FatalError(
754 Fixup.getLoc(),
755 Twine("symbol '") + B->getName() +
756 "' can not be undefined in a subtraction expression");
757
758 if (!A_SD.getFragment())
759 Asm.getContext().FatalError(
760 Fixup.getLoc(),
761 Twine("symbol '") + Symbol.getName() +
762 "' can not be undefined in a subtraction expression");
763
764 CrossSection = &Symbol.getSection() != &B->getSection();
Michael J. Spencerccd28d02010-08-24 21:04:52 +0000765
Rafael Espindolac3dc4862011-04-21 18:36:50 +0000766 // Offset of the symbol in the section
767 int64_t a = Layout.getSymbolOffset(&B_SD);
Michael J. Spencerccd28d02010-08-24 21:04:52 +0000768
Rafael Espindolac3dc4862011-04-21 18:36:50 +0000769 // Ofeset of the relocation in the section
770 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
771
772 FixedValue = b - a;
Michael J. Spencerccd28d02010-08-24 21:04:52 +0000773 // In the case where we have SymbA and SymB, we just need to store the delta
774 // between the two symbols. Update FixedValue to account for the delta, and
775 // skip recording the relocation.
Rafael Espindolaed164772011-04-20 14:01:45 +0000776 if (!CrossSection)
777 return;
Michael J. Spencerccd28d02010-08-24 21:04:52 +0000778 } else {
779 FixedValue = Target.getConstant();
780 }
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000781
782 COFFRelocation Reloc;
783
Daniel Dunbar727be432010-07-31 21:08:54 +0000784 Reloc.Data.SymbolTableIndex = 0;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000785 Reloc.Data.VirtualAddress = Layout.getFragmentOffset(Fragment);
Michael J. Spencerd6283772010-09-27 08:58:26 +0000786
Michael J. Spencera65d17a2010-10-05 19:48:12 +0000787 // Turn relocations for temporary symbols into section relocations.
Rafael Espindolaed164772011-04-20 14:01:45 +0000788 if (coff_symbol->MCData->getSymbol().isTemporary() || CrossSection) {
Michael J. Spencerd6283772010-09-27 08:58:26 +0000789 Reloc.Symb = coff_symbol->Section->Symbol;
Michael J. Spencera3b34ed2010-10-05 19:48:03 +0000790 FixedValue += Layout.getFragmentOffset(coff_symbol->MCData->Fragment)
791 + coff_symbol->MCData->getOffset();
Michael J. Spencerd6283772010-09-27 08:58:26 +0000792 } else
793 Reloc.Symb = coff_symbol;
794
795 ++Reloc.Symb->Relocations;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000796
797 Reloc.Data.VirtualAddress += Fixup.getOffset();
Nico Rieck1da45292013-04-10 23:28:17 +0000798 Reloc.Data.Type = TargetObjectWriter->getRelocType(Target, Fixup,
799 CrossSection);
Rafael Espindolae61724a2011-12-22 22:21:47 +0000800
801 // FIXME: Can anyone explain what this does other than adjust for the size
802 // of the offset?
Saleem Abdulrasool2c080512014-04-13 20:47:55 +0000803 if ((Header.Machine == COFF::IMAGE_FILE_MACHINE_AMD64 &&
804 Reloc.Data.Type == COFF::IMAGE_REL_AMD64_REL32) ||
805 (Header.Machine == COFF::IMAGE_FILE_MACHINE_I386 &&
806 Reloc.Data.Type == COFF::IMAGE_REL_I386_REL32))
Michael J. Spencerccd28d02010-08-24 21:04:52 +0000807 FixedValue += 4;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000808
Saleem Abdulrasool84b952b2014-04-27 03:48:22 +0000809 if (Header.Machine == COFF::IMAGE_FILE_MACHINE_ARMNT) {
810 switch (Reloc.Data.Type) {
811 case COFF::IMAGE_REL_ARM_ABSOLUTE:
812 case COFF::IMAGE_REL_ARM_ADDR32:
813 case COFF::IMAGE_REL_ARM_ADDR32NB:
814 case COFF::IMAGE_REL_ARM_TOKEN:
815 case COFF::IMAGE_REL_ARM_SECTION:
816 case COFF::IMAGE_REL_ARM_SECREL:
817 break;
818 case COFF::IMAGE_REL_ARM_BRANCH11:
819 case COFF::IMAGE_REL_ARM_BLX11:
820 // IMAGE_REL_ARM_BRANCH11 and IMAGE_REL_ARM_BLX11 are only used for
821 // pre-ARMv7, which implicitly rules it out of ARMNT (it would be valid
822 // for Windows CE).
823 case COFF::IMAGE_REL_ARM_BRANCH24:
824 case COFF::IMAGE_REL_ARM_BLX24:
825 case COFF::IMAGE_REL_ARM_MOV32A:
826 // IMAGE_REL_ARM_BRANCH24, IMAGE_REL_ARM_BLX24, IMAGE_REL_ARM_MOV32A are
827 // only used for ARM mode code, which is documented as being unsupported
Alp Tokerbeaca192014-05-15 01:52:21 +0000828 // by Windows on ARM. Empirical proof indicates that masm is able to
Saleem Abdulrasool84b952b2014-04-27 03:48:22 +0000829 // generate the relocations however the rest of the MSVC toolchain is
830 // unable to handle it.
831 llvm_unreachable("unsupported relocation");
832 break;
833 case COFF::IMAGE_REL_ARM_MOV32T:
834 break;
835 case COFF::IMAGE_REL_ARM_BRANCH20T:
836 case COFF::IMAGE_REL_ARM_BRANCH24T:
837 case COFF::IMAGE_REL_ARM_BLX23T:
838 // IMAGE_REL_BRANCH20T, IMAGE_REL_ARM_BRANCH24T, IMAGE_REL_ARM_BLX23T all
839 // perform a 4 byte adjustment to the relocation. Relative branches are
840 // offset by 4 on ARM, however, because there is no RELA relocations, all
841 // branches are offset by 4.
842 FixedValue = FixedValue + 4;
843 break;
844 }
845 }
846
Saleem Abdulrasool54bed122014-05-21 23:17:50 +0000847 if (TargetObjectWriter->recordRelocation(Fixup))
848 coff_section->Relocations.push_back(Reloc);
Chris Lattner2c52b792010-07-11 22:07:02 +0000849}
850
Rafael Espindolabce26a12010-10-05 15:11:03 +0000851void WinCOFFObjectWriter::WriteObject(MCAssembler &Asm,
Chris Lattner2c52b792010-07-11 22:07:02 +0000852 const MCAsmLayout &Layout) {
David Majnemer4d571592014-09-15 19:42:42 +0000853 size_t SectionsSize = Sections.size();
854 if (SectionsSize > static_cast<size_t>(INT32_MAX))
855 report_fatal_error(
856 "PE COFF object files can't have more than 2147483647 sections");
Michael J. Spencerd6283772010-09-27 08:58:26 +0000857
David Majnemer4d571592014-09-15 19:42:42 +0000858 // Assign symbol and section indexes and offsets.
859 int32_t NumberOfSections = static_cast<int32_t>(SectionsSize);
860
861 UseBigObj = NumberOfSections > COFF::MaxNumberOfSections16;
862
863 DenseMap<COFFSection *, int32_t> SectionIndices(
864 NextPowerOf2(NumberOfSections));
865 size_t Number = 1;
David Majnemer9ab5ff12014-08-28 04:02:50 +0000866 for (const auto &Section : Sections) {
David Majnemer4d571592014-09-15 19:42:42 +0000867 SectionIndices[Section.get()] = Number;
Saleem Abdulrasoole9bd9162014-06-06 21:40:16 +0000868 MakeSectionReal(*Section, Number);
David Majnemer4d571592014-09-15 19:42:42 +0000869 ++Number;
Michael J. Spencerd6283772010-09-27 08:58:26 +0000870 }
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000871
David Majnemer4d571592014-09-15 19:42:42 +0000872 Header.NumberOfSections = NumberOfSections;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000873 Header.NumberOfSymbols = 0;
874
David Majnemer4d571592014-09-15 19:42:42 +0000875 for (auto FI = Asm.file_names_begin(), FE = Asm.file_names_end();
876 FI != FE; ++FI) {
877 // round up to calculate the number of auxiliary symbols required
878 unsigned SymbolSize = UseBigObj ? COFF::Symbol32Size : COFF::Symbol16Size;
879 unsigned Count = (FI->size() + SymbolSize - 1) / SymbolSize;
880
881 COFFSymbol *file = createSymbol(".file");
882 file->Data.SectionNumber = COFF::IMAGE_SYM_DEBUG;
883 file->Data.StorageClass = COFF::IMAGE_SYM_CLASS_FILE;
884 file->Aux.resize(Count);
885
886 unsigned Offset = 0;
887 unsigned Length = FI->size();
888 for (auto & Aux : file->Aux) {
889 Aux.AuxType = ATFile;
890
891 if (Length > SymbolSize) {
892 memcpy(&Aux.Aux, FI->c_str() + Offset, SymbolSize);
893 Length = Length - SymbolSize;
894 } else {
895 memcpy(&Aux.Aux, FI->c_str() + Offset, Length);
896 memset((char *)&Aux.Aux + Length, 0, SymbolSize - Length);
897 break;
898 }
899
900 Offset += SymbolSize;
901 }
902 }
903
David Majnemer9ab5ff12014-08-28 04:02:50 +0000904 for (auto &Symbol : Symbols) {
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000905 // Update section number & offset for symbols that have them.
Rafael Espindola575f79a2014-05-01 13:37:57 +0000906 if (Symbol->Section)
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000907 Symbol->Data.SectionNumber = Symbol->Section->Number;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000908
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000909 if (Symbol->should_keep()) {
910 MakeSymbolReal(*Symbol, Header.NumberOfSymbols++);
Michael J. Spencerd6283772010-09-27 08:58:26 +0000911
912 // Update auxiliary symbol info.
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000913 Symbol->Data.NumberOfAuxSymbols = Symbol->Aux.size();
914 Header.NumberOfSymbols += Symbol->Data.NumberOfAuxSymbols;
Michael J. Spencerd6283772010-09-27 08:58:26 +0000915 } else
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000916 Symbol->Index = -1;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000917 }
918
919 // Fixup weak external references.
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000920 for (auto & Symbol : Symbols) {
921 if (Symbol->Other) {
922 assert(Symbol->Index != -1);
923 assert(Symbol->Aux.size() == 1 && "Symbol must contain one aux symbol!");
924 assert(Symbol->Aux[0].AuxType == ATWeakExternal &&
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000925 "Symbol's aux symbol must be a Weak External!");
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000926 Symbol->Aux[0].Aux.WeakExternal.TagIndex = Symbol->Other->Index;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000927 }
928 }
929
Nico Riecka37acf72013-07-06 12:13:10 +0000930 // Fixup associative COMDAT sections.
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000931 for (auto & Section : Sections) {
932 if (Section->Symbol->Aux[0].Aux.SectionDefinition.Selection !=
Nico Riecka37acf72013-07-06 12:13:10 +0000933 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
934 continue;
935
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000936 const MCSectionCOFF &MCSec =
937 static_cast<const MCSectionCOFF &>(Section->MCData->getSection());
Nico Riecka37acf72013-07-06 12:13:10 +0000938
Rafael Espindola0766ae02014-06-06 19:26:12 +0000939 const MCSymbol *COMDAT = MCSec.getCOMDATSymbol();
940 assert(COMDAT);
941 COFFSymbol *COMDATSymbol = GetOrCreateCOFFSymbol(COMDAT);
942 assert(COMDATSymbol);
943 COFFSection *Assoc = COMDATSymbol->Section;
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000944 if (!Assoc)
Rafael Espindola0766ae02014-06-06 19:26:12 +0000945 report_fatal_error(
946 Twine("Missing associated COMDAT section for section ") +
947 MCSec.getSectionName());
Nico Riecka37acf72013-07-06 12:13:10 +0000948
949 // Skip this section if the associated section is unused.
950 if (Assoc->Number == -1)
951 continue;
952
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000953 Section->Symbol->Aux[0].Aux.SectionDefinition.Number = SectionIndices[Assoc];
Nico Riecka37acf72013-07-06 12:13:10 +0000954 }
955
956
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000957 // Assign file offsets to COFF object file structures.
958
959 unsigned offset = 0;
960
David Majnemer4d571592014-09-15 19:42:42 +0000961 if (UseBigObj)
962 offset += COFF::Header32Size;
963 else
964 offset += COFF::Header16Size;
Michael J. Spencerd6283772010-09-27 08:58:26 +0000965 offset += COFF::SectionSize * Header.NumberOfSections;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000966
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000967 for (const auto & Section : Asm) {
968 COFFSection *Sec = SectionMap[&Section.getSection()];
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000969
Michael J. Spencerd6283772010-09-27 08:58:26 +0000970 if (Sec->Number == -1)
971 continue;
972
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000973 Sec->Header.SizeOfRawData = Layout.getSectionAddressSize(&Section);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000974
Michael J. Spencerd6283772010-09-27 08:58:26 +0000975 if (IsPhysicalSection(Sec)) {
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000976 Sec->Header.PointerToRawData = offset;
977
978 offset += Sec->Header.SizeOfRawData;
979 }
980
981 if (Sec->Relocations.size() > 0) {
Michael J. Spencerfa39bd22012-03-15 09:03:03 +0000982 bool RelocationsOverflow = Sec->Relocations.size() >= 0xffff;
983
984 if (RelocationsOverflow) {
David Majnemer9ab5ff12014-08-28 04:02:50 +0000985 // Signal overflow by setting NumberOfRelocations to max value. Actual
Michael J. Spencerfa39bd22012-03-15 09:03:03 +0000986 // size is found in reloc #0. Microsoft tools understand this.
987 Sec->Header.NumberOfRelocations = 0xffff;
988 } else {
989 Sec->Header.NumberOfRelocations = Sec->Relocations.size();
990 }
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000991 Sec->Header.PointerToRelocations = offset;
992
Michael J. Spencerfa39bd22012-03-15 09:03:03 +0000993 if (RelocationsOverflow) {
994 // Reloc #0 will contain actual count, so make room for it.
995 offset += COFF::RelocationSize;
996 }
997
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000998 offset += COFF::RelocationSize * Sec->Relocations.size();
999
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +00001000 for (auto & Relocation : Sec->Relocations) {
1001 assert(Relocation.Symb->Index != -1);
1002 Relocation.Data.SymbolTableIndex = Relocation.Symb->Index;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +00001003 }
1004 }
1005
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +00001006 assert(Sec->Symbol->Aux.size() == 1 &&
1007 "Section's symbol must have one aux!");
Michael J. Spencerd6283772010-09-27 08:58:26 +00001008 AuxSymbol &Aux = Sec->Symbol->Aux[0];
Michael J. Spencerb5fc1382010-07-26 02:17:32 +00001009 assert(Aux.AuxType == ATSectionDefinition &&
1010 "Section's symbol's aux symbol must be a Section Definition!");
1011 Aux.Aux.SectionDefinition.Length = Sec->Header.SizeOfRawData;
1012 Aux.Aux.SectionDefinition.NumberOfRelocations =
1013 Sec->Header.NumberOfRelocations;
1014 Aux.Aux.SectionDefinition.NumberOfLinenumbers =
1015 Sec->Header.NumberOfLineNumbers;
1016 }
1017
1018 Header.PointerToSymbolTable = offset;
1019
Rafael Espindola5ac4ad22013-12-04 02:26:54 +00001020 // We want a deterministic output. It looks like GNU as also writes 0 in here.
Rafael Espindola9201e6b2013-12-04 02:02:55 +00001021 Header.TimeDateStamp = 0;
Michael J. Spencera6cfbeb2010-08-03 04:43:33 +00001022
Michael J. Spencerb5fc1382010-07-26 02:17:32 +00001023 // Write it all to disk...
1024 WriteFileHeader(Header);
1025
1026 {
1027 sections::iterator i, ie;
1028 MCAssembler::const_iterator j, je;
1029
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +00001030 for (auto & Section : Sections) {
1031 if (Section->Number != -1) {
1032 if (Section->Relocations.size() >= 0xffff)
1033 Section->Header.Characteristics |= COFF::IMAGE_SCN_LNK_NRELOC_OVFL;
1034 WriteSectionHeader(Section->Header);
Michael J. Spencerfa39bd22012-03-15 09:03:03 +00001035 }
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +00001036 }
Michael J. Spencerb5fc1382010-07-26 02:17:32 +00001037
1038 for (i = Sections.begin(), ie = Sections.end(),
1039 j = Asm.begin(), je = Asm.end();
Michael J. Spencerd6283772010-09-27 08:58:26 +00001040 (i != ie) && (j != je); ++i, ++j) {
1041
1042 if ((*i)->Number == -1)
1043 continue;
1044
Michael J. Spencerb5fc1382010-07-26 02:17:32 +00001045 if ((*i)->Header.PointerToRawData != 0) {
1046 assert(OS.tell() == (*i)->Header.PointerToRawData &&
1047 "Section::PointerToRawData is insane!");
1048
Jim Grosbach18e2fe42011-12-06 00:03:48 +00001049 Asm.writeSectionData(j, Layout);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +00001050 }
1051
1052 if ((*i)->Relocations.size() > 0) {
1053 assert(OS.tell() == (*i)->Header.PointerToRelocations &&
1054 "Section::PointerToRelocations is insane!");
1055
Michael J. Spencerfa39bd22012-03-15 09:03:03 +00001056 if ((*i)->Relocations.size() >= 0xffff) {
1057 // In case of overflow, write actual relocation count as first
1058 // relocation. Including the synthetic reloc itself (+ 1).
1059 COFF::relocation r;
1060 r.VirtualAddress = (*i)->Relocations.size() + 1;
1061 r.SymbolTableIndex = 0;
1062 r.Type = 0;
1063 WriteRelocation(r);
1064 }
1065
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +00001066 for (const auto & Relocation : (*i)->Relocations)
1067 WriteRelocation(Relocation.Data);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +00001068 } else
1069 assert((*i)->Header.PointerToRelocations == 0 &&
1070 "Section::PointerToRelocations is insane!");
1071 }
1072 }
1073
1074 assert(OS.tell() == Header.PointerToSymbolTable &&
1075 "Header::PointerToSymbolTable is insane!");
1076
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +00001077 for (auto & Symbol : Symbols)
1078 if (Symbol->Index != -1)
1079 WriteSymbol(*Symbol);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +00001080
1081 OS.write((char const *)&Strings.Data.front(), Strings.Data.size());
Chris Lattner2c52b792010-07-11 22:07:02 +00001082}
1083
Rafael Espindola908d2ed2011-12-24 02:14:02 +00001084MCWinCOFFObjectTargetWriter::MCWinCOFFObjectTargetWriter(unsigned Machine_) :
1085 Machine(Machine_) {
1086}
1087
Juergen Ributzkad12ccbd2013-11-19 00:57:56 +00001088// Pin the vtable to this file.
1089void MCWinCOFFObjectTargetWriter::anchor() {}
1090
Chris Lattner2c52b792010-07-11 22:07:02 +00001091//------------------------------------------------------------------------------
1092// WinCOFFObjectWriter factory function
1093
1094namespace llvm {
Rafael Espindola908d2ed2011-12-24 02:14:02 +00001095 MCObjectWriter *createWinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW,
1096 raw_ostream &OS) {
1097 return new WinCOFFObjectWriter(MOTW, OS);
Chris Lattner2c52b792010-07-11 22:07:02 +00001098 }
Michael J. Spencerc2129372010-07-26 03:01:28 +00001099}