blob: 5ffa107da9afc7ca6f8ec42db261c9a9fcfd169a [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"
Hans Wennborgba80b5d2014-09-28 00:22:27 +000031#include "llvm/Support/Endian.h"
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000032#include "llvm/Support/ErrorHandling.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000033#include "llvm/Support/TimeValue.h"
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000034#include <cstdio>
35
Chris Lattner2c52b792010-07-11 22:07:02 +000036using namespace llvm;
37
Chandler Carruthf58e3762014-04-22 03:04:17 +000038#define DEBUG_TYPE "WinCOFFObjectWriter"
39
Chris Lattner2c52b792010-07-11 22:07:02 +000040namespace {
Dmitri Gribenko226fea52013-01-13 16:01:15 +000041typedef SmallString<COFF::NameSize> name;
Chris Lattner2c52b792010-07-11 22:07:02 +000042
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000043enum AuxiliaryType {
44 ATFunctionDefinition,
45 ATbfAndefSymbol,
46 ATWeakExternal,
47 ATFile,
48 ATSectionDefinition
49};
Chris Lattner2c52b792010-07-11 22:07:02 +000050
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000051struct AuxSymbol {
52 AuxiliaryType AuxType;
53 COFF::Auxiliary Aux;
54};
Chris Lattner2c52b792010-07-11 22:07:02 +000055
Michael J. Spencerd6283772010-09-27 08:58:26 +000056class COFFSymbol;
57class COFFSection;
58
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000059class COFFSymbol {
60public:
61 COFF::symbol Data;
Chris Lattner2c52b792010-07-11 22:07:02 +000062
Dmitri Gribenko226fea52013-01-13 16:01:15 +000063 typedef SmallVector<AuxSymbol, 1> AuxiliarySymbols;
Chris Lattner2c52b792010-07-11 22:07:02 +000064
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000065 name Name;
Michael J. Spencerce2e5352010-09-27 21:17:39 +000066 int Index;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000067 AuxiliarySymbols Aux;
68 COFFSymbol *Other;
Michael J. Spencerd6283772010-09-27 08:58:26 +000069 COFFSection *Section;
70 int Relocations;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000071
72 MCSymbolData const *MCData;
73
Dmitri Gribenko226fea52013-01-13 16:01:15 +000074 COFFSymbol(StringRef name);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000075 void set_name_offset(uint32_t Offset);
Michael J. Spencerd6283772010-09-27 08:58:26 +000076
77 bool should_keep() const;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000078};
79
80// This class contains staging data for a COFF relocation entry.
81struct COFFRelocation {
82 COFF::relocation Data;
83 COFFSymbol *Symb;
84
Craig Topperbb694de2014-04-13 04:57:38 +000085 COFFRelocation() : Symb(nullptr) {}
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000086 static size_t size() { return COFF::RelocationSize; }
87};
88
89typedef std::vector<COFFRelocation> relocations;
90
91class COFFSection {
92public:
93 COFF::section Header;
94
95 std::string Name;
Michael J. Spencerce2e5352010-09-27 21:17:39 +000096 int Number;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000097 MCSectionData const *MCData;
Michael J. Spencerd6283772010-09-27 08:58:26 +000098 COFFSymbol *Symbol;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000099 relocations Relocations;
100
Dmitri Gribenko226fea52013-01-13 16:01:15 +0000101 COFFSection(StringRef name);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000102 static size_t size();
103};
104
105// This class holds the COFF string table.
106class StringTable {
Dmitri Gribenko226fea52013-01-13 16:01:15 +0000107 typedef StringMap<size_t> map;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000108 map Map;
109
110 void update_length();
111public:
112 std::vector<char> Data;
113
114 StringTable();
115 size_t size() const;
Dmitri Gribenko226fea52013-01-13 16:01:15 +0000116 size_t insert(StringRef String);
Yaron Kerencca43c12014-09-16 21:31:04 +0000117 void clear() {
118 Map.clear();
119 Data.resize(4);
120 update_length();
121 }
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000122};
123
124class WinCOFFObjectWriter : public MCObjectWriter {
125public:
126
David Blaikief564ab62014-04-15 05:25:03 +0000127 typedef std::vector<std::unique_ptr<COFFSymbol>> symbols;
128 typedef std::vector<std::unique_ptr<COFFSection>> sections;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000129
Michael J. Spencer17990d52010-10-16 08:25:57 +0000130 typedef DenseMap<MCSymbol const *, COFFSymbol *> symbol_map;
131 typedef DenseMap<MCSection const *, COFFSection *> section_map;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000132
Ahmed Charles56440fd2014-03-06 05:51:42 +0000133 std::unique_ptr<MCWinCOFFObjectTargetWriter> TargetObjectWriter;
Rafael Espindola908d2ed2011-12-24 02:14:02 +0000134
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000135 // Root level file contents.
136 COFF::header Header;
137 sections Sections;
138 symbols Symbols;
139 StringTable Strings;
140
141 // Maps used during object file creation.
142 section_map SectionMap;
143 symbol_map SymbolMap;
144
David Majnemer4d571592014-09-15 19:42:42 +0000145 bool UseBigObj;
146
Rafael Espindola908d2ed2011-12-24 02:14:02 +0000147 WinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW, raw_ostream &OS);
Yaron Kerencca43c12014-09-16 21:31:04 +0000148
149 void reset() override {
150 memset(&Header, 0, sizeof(Header));
151 Header.Machine = TargetObjectWriter->getMachine();
152 Sections.clear();
153 Symbols.clear();
154 Strings.clear();
155 SectionMap.clear();
156 SymbolMap.clear();
157 MCObjectWriter::reset();
158 }
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000159
Michael J. Spencer17990d52010-10-16 08:25:57 +0000160 COFFSymbol *createSymbol(StringRef Name);
161 COFFSymbol *GetOrCreateCOFFSymbol(const MCSymbol * Symbol);
162 COFFSection *createSection(StringRef Name);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000163
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000164 template <typename object_t, typename list_t>
Dmitri Gribenko226fea52013-01-13 16:01:15 +0000165 object_t *createCOFFEntity(StringRef Name, list_t &List);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000166
167 void DefineSection(MCSectionData const &SectionData);
Reid Klecknerc1e76212013-09-17 23:18:05 +0000168 void DefineSymbol(MCSymbolData const &SymbolData, MCAssembler &Assembler,
169 const MCAsmLayout &Layout);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000170
Michael J. Spencerd6283772010-09-27 08:58:26 +0000171 void MakeSymbolReal(COFFSymbol &S, size_t Index);
172 void MakeSectionReal(COFFSection &S, size_t Number);
173
David Majnemer299674e2014-07-13 04:31:19 +0000174 bool ExportSymbol(const MCSymbol &Symbol, MCAssembler &Asm);
Reid Kleckner8b2ad2a2013-11-18 23:08:12 +0000175
Michael J. Spencerd6283772010-09-27 08:58:26 +0000176 bool IsPhysicalSection(COFFSection *S);
177
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000178 // Entity writing methods.
179
180 void WriteFileHeader(const COFF::header &Header);
David Blaikief564ab62014-04-15 05:25:03 +0000181 void WriteSymbol(const COFFSymbol &S);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000182 void WriteAuxiliarySymbols(const COFFSymbol::AuxiliarySymbols &S);
183 void WriteSectionHeader(const COFF::section &S);
184 void WriteRelocation(const COFF::relocation &R);
185
186 // MCObjectWriter interface implementation.
187
Craig Topper34a61bc2014-03-08 07:02:02 +0000188 void ExecutePostLayoutBinding(MCAssembler &Asm,
189 const MCAsmLayout &Layout) override;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000190
Craig Topper34a61bc2014-03-08 07:02:02 +0000191 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
192 const MCFragment *Fragment, const MCFixup &Fixup,
Rafael Espindola5904e122014-03-29 06:26:49 +0000193 MCValue Target, bool &IsPCRel,
194 uint64_t &FixedValue) override;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000195
Craig Topper34a61bc2014-03-08 07:02:02 +0000196 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000197};
Chris Lattner2c52b792010-07-11 22:07:02 +0000198}
199
Hans Wennborgba80b5d2014-09-28 00:22:27 +0000200static inline void write_uint32_le(void *Data, uint32_t Value) {
201 support::endian::write<uint32_t, support::little, support::unaligned>(Data,
202 Value);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000203}
204
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000205//------------------------------------------------------------------------------
206// Symbol class implementation
207
Dmitri Gribenko226fea52013-01-13 16:01:15 +0000208COFFSymbol::COFFSymbol(StringRef name)
Michael J. Spencerd6283772010-09-27 08:58:26 +0000209 : Name(name.begin(), name.end())
Craig Topperbb694de2014-04-13 04:57:38 +0000210 , Other(nullptr)
211 , Section(nullptr)
Michael J. Spencerd6283772010-09-27 08:58:26 +0000212 , Relocations(0)
Craig Topperbb694de2014-04-13 04:57:38 +0000213 , MCData(nullptr) {
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000214 memset(&Data, 0, sizeof(Data));
215}
216
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000217// In the case that the name does not fit within 8 bytes, the offset
218// into the string table is stored in the last 4 bytes instead, leaving
219// the first 4 bytes as 0.
220void COFFSymbol::set_name_offset(uint32_t Offset) {
221 write_uint32_le(Data.Name + 0, 0);
222 write_uint32_le(Data.Name + 4, Offset);
223}
224
Michael J. Spencerd6283772010-09-27 08:58:26 +0000225/// logic to decide if the symbol should be reported in the symbol table
226bool COFFSymbol::should_keep() const {
227 // no section means its external, keep it
Craig Topperbb694de2014-04-13 04:57:38 +0000228 if (!Section)
Michael J. Spencerd6283772010-09-27 08:58:26 +0000229 return true;
230
231 // if it has relocations pointing at it, keep it
232 if (Relocations > 0) {
233 assert(Section->Number != -1 && "Sections with relocations must be real!");
234 return true;
235 }
236
237 // if the section its in is being droped, drop it
238 if (Section->Number == -1)
239 return false;
240
241 // if it is the section symbol, keep it
242 if (Section->Symbol == this)
243 return true;
244
245 // if its temporary, drop it
246 if (MCData && MCData->getSymbol().isTemporary())
247 return false;
248
249 // otherwise, keep it
250 return true;
251}
252
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000253//------------------------------------------------------------------------------
254// Section class implementation
255
Dmitri Gribenko226fea52013-01-13 16:01:15 +0000256COFFSection::COFFSection(StringRef name)
Michael J. Spencerd6283772010-09-27 08:58:26 +0000257 : Name(name)
Craig Topperbb694de2014-04-13 04:57:38 +0000258 , MCData(nullptr)
259 , Symbol(nullptr) {
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000260 memset(&Header, 0, sizeof(Header));
261}
262
263size_t COFFSection::size() {
264 return COFF::SectionSize;
265}
266
267//------------------------------------------------------------------------------
268// StringTable class implementation
269
270/// Write the length of the string table into Data.
271/// The length of the string table includes uint32 length header.
272void StringTable::update_length() {
273 write_uint32_le(&Data.front(), Data.size());
274}
275
276StringTable::StringTable() {
277 // The string table data begins with the length of the entire string table
278 // including the length header. Allocate space for this header.
279 Data.resize(4);
Michael J. Spencer5ca95bc2011-11-08 19:52:32 +0000280 update_length();
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000281}
282
283size_t StringTable::size() const {
284 return Data.size();
285}
286
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000287/// Add String to the table iff it is not already there.
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000288/// @returns the index into the string table where the string is now located.
Dmitri Gribenko226fea52013-01-13 16:01:15 +0000289size_t StringTable::insert(StringRef String) {
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000290 map::iterator i = Map.find(String);
291
292 if (i != Map.end())
293 return i->second;
294
295 size_t Offset = Data.size();
296
297 // Insert string data into string table.
298 Data.insert(Data.end(), String.begin(), String.end());
299 Data.push_back('\0');
300
301 // Put a reference to it in the map.
302 Map[String] = Offset;
303
304 // Update the internal length field.
305 update_length();
306
307 return Offset;
308}
309
310//------------------------------------------------------------------------------
311// WinCOFFObjectWriter class implementation
312
Rafael Espindola908d2ed2011-12-24 02:14:02 +0000313WinCOFFObjectWriter::WinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW,
314 raw_ostream &OS)
David Majnemer4d571592014-09-15 19:42:42 +0000315 : MCObjectWriter(OS, true), TargetObjectWriter(MOTW) {
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000316 memset(&Header, 0, sizeof(Header));
Michael J. Spencer377aa202010-08-21 05:58:13 +0000317
Rafael Espindola908d2ed2011-12-24 02:14:02 +0000318 Header.Machine = TargetObjectWriter->getMachine();
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000319}
320
Michael J. Spencer17990d52010-10-16 08:25:57 +0000321COFFSymbol *WinCOFFObjectWriter::createSymbol(StringRef Name) {
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000322 return createCOFFEntity<COFFSymbol>(Name, Symbols);
323}
324
Michael J. Spencer17990d52010-10-16 08:25:57 +0000325COFFSymbol *WinCOFFObjectWriter::GetOrCreateCOFFSymbol(const MCSymbol * Symbol){
326 symbol_map::iterator i = SymbolMap.find(Symbol);
327 if (i != SymbolMap.end())
328 return i->second;
329 COFFSymbol *RetSymbol
330 = createCOFFEntity<COFFSymbol>(Symbol->getName(), Symbols);
331 SymbolMap[Symbol] = RetSymbol;
332 return RetSymbol;
333}
334
Dmitri Gribenko226fea52013-01-13 16:01:15 +0000335COFFSection *WinCOFFObjectWriter::createSection(StringRef Name) {
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000336 return createCOFFEntity<COFFSection>(Name, Sections);
337}
338
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000339/// A template used to lookup or create a symbol/section, and initialize it if
340/// needed.
341template <typename object_t, typename list_t>
Dmitri Gribenko226fea52013-01-13 16:01:15 +0000342object_t *WinCOFFObjectWriter::createCOFFEntity(StringRef Name,
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000343 list_t &List) {
David Blaikief564ab62014-04-15 05:25:03 +0000344 List.push_back(make_unique<object_t>(Name));
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000345
David Blaikief564ab62014-04-15 05:25:03 +0000346 return List.back().get();
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000347}
348
349/// This function takes a section data object from the assembler
350/// and creates the associated COFF section staging object.
351void WinCOFFObjectWriter::DefineSection(MCSectionData const &SectionData) {
Michael J. Spencerbe52c622010-10-09 11:00:37 +0000352 assert(SectionData.getSection().getVariant() == MCSection::SV_COFF
Alp Tokerf907b892013-12-05 05:44:44 +0000353 && "Got non-COFF section in the COFF backend!");
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000354 // FIXME: Not sure how to verify this (at least in a debug build).
355 MCSectionCOFF const &Sec =
356 static_cast<MCSectionCOFF const &>(SectionData.getSection());
357
358 COFFSection *coff_section = createSection(Sec.getSectionName());
359 COFFSymbol *coff_symbol = createSymbol(Sec.getSectionName());
Rafael Espindola0766ae02014-06-06 19:26:12 +0000360 if (Sec.getSelection() != COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE) {
361 if (const MCSymbol *S = Sec.getCOMDATSymbol()) {
362 COFFSymbol *COMDATSymbol = GetOrCreateCOFFSymbol(S);
363 if (COMDATSymbol->Section)
364 report_fatal_error("two sections have the same comdat");
365 COMDATSymbol->Section = coff_section;
366 }
367 }
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000368
Michael J. Spencerd6283772010-09-27 08:58:26 +0000369 coff_section->Symbol = coff_symbol;
370 coff_symbol->Section = coff_section;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000371 coff_symbol->Data.StorageClass = COFF::IMAGE_SYM_CLASS_STATIC;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000372
373 // In this case the auxiliary symbol is a Section Definition.
374 coff_symbol->Aux.resize(1);
375 memset(&coff_symbol->Aux[0], 0, sizeof(coff_symbol->Aux[0]));
376 coff_symbol->Aux[0].AuxType = ATSectionDefinition;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000377 coff_symbol->Aux[0].Aux.SectionDefinition.Selection = Sec.getSelection();
378
379 coff_section->Header.Characteristics = Sec.getCharacteristics();
380
381 uint32_t &Characteristics = coff_section->Header.Characteristics;
382 switch (SectionData.getAlignment()) {
383 case 1: Characteristics |= COFF::IMAGE_SCN_ALIGN_1BYTES; break;
384 case 2: Characteristics |= COFF::IMAGE_SCN_ALIGN_2BYTES; break;
385 case 4: Characteristics |= COFF::IMAGE_SCN_ALIGN_4BYTES; break;
386 case 8: Characteristics |= COFF::IMAGE_SCN_ALIGN_8BYTES; break;
387 case 16: Characteristics |= COFF::IMAGE_SCN_ALIGN_16BYTES; break;
388 case 32: Characteristics |= COFF::IMAGE_SCN_ALIGN_32BYTES; break;
389 case 64: Characteristics |= COFF::IMAGE_SCN_ALIGN_64BYTES; break;
390 case 128: Characteristics |= COFF::IMAGE_SCN_ALIGN_128BYTES; break;
391 case 256: Characteristics |= COFF::IMAGE_SCN_ALIGN_256BYTES; break;
392 case 512: Characteristics |= COFF::IMAGE_SCN_ALIGN_512BYTES; break;
393 case 1024: Characteristics |= COFF::IMAGE_SCN_ALIGN_1024BYTES; break;
394 case 2048: Characteristics |= COFF::IMAGE_SCN_ALIGN_2048BYTES; break;
395 case 4096: Characteristics |= COFF::IMAGE_SCN_ALIGN_4096BYTES; break;
396 case 8192: Characteristics |= COFF::IMAGE_SCN_ALIGN_8192BYTES; break;
397 default:
398 llvm_unreachable("unsupported section alignment");
399 }
400
401 // Bind internal COFF section to MC section.
402 coff_section->MCData = &SectionData;
Michael J. Spencer17990d52010-10-16 08:25:57 +0000403 SectionMap[&SectionData.getSection()] = coff_section;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000404}
405
Rafael Espindolaff68cb72014-05-01 00:10:17 +0000406static uint64_t getSymbolValue(const MCSymbolData &Data,
407 const MCAsmLayout &Layout) {
408 if (Data.isCommon() && Data.isExternal())
409 return Data.getCommonSize();
410
411 uint64_t Res;
412 if (!Layout.getSymbolOffset(&Data, Res))
413 return 0;
414
415 return Res;
416}
417
David Majnemera9bdb322014-04-08 22:33:40 +0000418/// This function takes a symbol data object from the assembler
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000419/// and creates the associated COFF symbol staging object.
Peter Collingbourne89886872013-04-22 18:48:56 +0000420void WinCOFFObjectWriter::DefineSymbol(MCSymbolData const &SymbolData,
Reid Klecknerc1e76212013-09-17 23:18:05 +0000421 MCAssembler &Assembler,
422 const MCAsmLayout &Layout) {
Peter Collingbourne89886872013-04-22 18:48:56 +0000423 MCSymbol const &Symbol = SymbolData.getSymbol();
Michael J. Spencer54b24e12013-01-29 22:10:07 +0000424 COFFSymbol *coff_symbol = GetOrCreateCOFFSymbol(&Symbol);
Peter Collingbourne89886872013-04-22 18:48:56 +0000425 SymbolMap[&Symbol] = coff_symbol;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000426
Michael J. Spencer17990d52010-10-16 08:25:57 +0000427 if (SymbolData.getFlags() & COFF::SF_WeakExternal) {
428 coff_symbol->Data.StorageClass = COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL;
429
Michael J. Spencer54b24e12013-01-29 22:10:07 +0000430 if (Symbol.isVariable()) {
Peter Collingbourne89886872013-04-22 18:48:56 +0000431 const MCSymbolRefExpr *SymRef =
432 dyn_cast<MCSymbolRefExpr>(Symbol.getVariableValue());
Michael J. Spencer17990d52010-10-16 08:25:57 +0000433
Peter Collingbourne89886872013-04-22 18:48:56 +0000434 if (!SymRef)
435 report_fatal_error("Weak externals may only alias symbols");
Michael J. Spencer17990d52010-10-16 08:25:57 +0000436
Peter Collingbourne89886872013-04-22 18:48:56 +0000437 coff_symbol->Other = GetOrCreateCOFFSymbol(&SymRef->getSymbol());
Michael J. Spencer17990d52010-10-16 08:25:57 +0000438 } else {
439 std::string WeakName = std::string(".weak.")
Michael J. Spencer54b24e12013-01-29 22:10:07 +0000440 + Symbol.getName().str()
Michael J. Spencer17990d52010-10-16 08:25:57 +0000441 + ".default";
442 COFFSymbol *WeakDefault = createSymbol(WeakName);
443 WeakDefault->Data.SectionNumber = COFF::IMAGE_SYM_ABSOLUTE;
444 WeakDefault->Data.StorageClass = COFF::IMAGE_SYM_CLASS_EXTERNAL;
445 WeakDefault->Data.Type = 0;
446 WeakDefault->Data.Value = 0;
447 coff_symbol->Other = WeakDefault;
448 }
449
450 // Setup the Weak External auxiliary symbol.
451 coff_symbol->Aux.resize(1);
452 memset(&coff_symbol->Aux[0], 0, sizeof(coff_symbol->Aux[0]));
453 coff_symbol->Aux[0].AuxType = ATWeakExternal;
454 coff_symbol->Aux[0].Aux.WeakExternal.TagIndex = 0;
455 coff_symbol->Aux[0].Aux.WeakExternal.Characteristics =
456 COFF::IMAGE_WEAK_EXTERN_SEARCH_LIBRARY;
Peter Collingbourne89886872013-04-22 18:48:56 +0000457
458 coff_symbol->MCData = &SymbolData;
459 } else {
Rafael Espindolaea9f9d42014-05-01 19:02:03 +0000460 const MCSymbolData &ResSymData = Assembler.getSymbolData(Symbol);
Rafael Espindola575f79a2014-05-01 13:37:57 +0000461 const MCSymbol *Base = Layout.getBaseSymbol(Symbol);
Rafael Espindolaff68cb72014-05-01 00:10:17 +0000462 coff_symbol->Data.Value = getSymbolValue(ResSymData, Layout);
Reid Klecknerc1e76212013-09-17 23:18:05 +0000463
Peter Collingbourne89886872013-04-22 18:48:56 +0000464 coff_symbol->Data.Type = (ResSymData.getFlags() & 0x0000FFFF) >> 0;
465 coff_symbol->Data.StorageClass = (ResSymData.getFlags() & 0x00FF0000) >> 16;
466
467 // If no storage class was specified in the streamer, define it here.
468 if (coff_symbol->Data.StorageClass == 0) {
David Majnemer299674e2014-07-13 04:31:19 +0000469 bool IsExternal =
470 ResSymData.isExternal() ||
471 (!ResSymData.getFragment() && !ResSymData.getSymbol().isVariable());
Peter Collingbourne89886872013-04-22 18:48:56 +0000472
David Majnemer299674e2014-07-13 04:31:19 +0000473 coff_symbol->Data.StorageClass = IsExternal
474 ? COFF::IMAGE_SYM_CLASS_EXTERNAL
475 : COFF::IMAGE_SYM_CLASS_STATIC;
Peter Collingbourne89886872013-04-22 18:48:56 +0000476 }
477
Rafael Espindola575f79a2014-05-01 13:37:57 +0000478 if (!Base) {
Reid Klecknerc1e76212013-09-17 23:18:05 +0000479 coff_symbol->Data.SectionNumber = COFF::IMAGE_SYM_ABSOLUTE;
Rafael Espindola575f79a2014-05-01 13:37:57 +0000480 } else {
481 const MCSymbolData &BaseData = Assembler.getSymbolData(*Base);
Rafael Espindola0766ae02014-06-06 19:26:12 +0000482 if (BaseData.Fragment) {
483 COFFSection *Sec =
Rafael Espindola575f79a2014-05-01 13:37:57 +0000484 SectionMap[&BaseData.Fragment->getParent()->getSection()];
Rafael Espindola0766ae02014-06-06 19:26:12 +0000485
486 if (coff_symbol->Section && coff_symbol->Section != Sec)
487 report_fatal_error("conflicting sections for symbol");
488
489 coff_symbol->Section = Sec;
490 }
Rafael Espindola575f79a2014-05-01 13:37:57 +0000491 }
Peter Collingbourne89886872013-04-22 18:48:56 +0000492
493 coff_symbol->MCData = &ResSymData;
Michael J. Spencer17990d52010-10-16 08:25:57 +0000494 }
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000495}
496
Nico Rieck01143f92014-02-25 09:50:40 +0000497// Maximum offsets for different string table entry encodings.
498static const unsigned Max6DecimalOffset = 999999;
499static const unsigned Max7DecimalOffset = 9999999;
500static const uint64_t MaxBase64Offset = 0xFFFFFFFFFULL; // 64^6, including 0
501
Nico Rieck9d2c15e2014-02-22 16:12:20 +0000502// Encode a string table entry offset in base 64, padded to 6 chars, and
503// prefixed with a double slash: '//AAAAAA', '//AAAAAB', ...
504// Buffer must be at least 8 bytes large. No terminating null appended.
505static void encodeBase64StringEntry(char* Buffer, uint64_t Value) {
Nico Rieck01143f92014-02-25 09:50:40 +0000506 assert(Value > Max7DecimalOffset && Value <= MaxBase64Offset &&
Nico Rieck9d2c15e2014-02-22 16:12:20 +0000507 "Illegal section name encoding for value");
508
509 static const char Alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
510 "abcdefghijklmnopqrstuvwxyz"
511 "0123456789+/";
512
513 Buffer[0] = '/';
514 Buffer[1] = '/';
515
516 char* Ptr = Buffer + 7;
517 for (unsigned i = 0; i < 6; ++i) {
518 unsigned Rem = Value % 64;
519 Value /= 64;
520 *(Ptr--) = Alphabet[Rem];
521 }
522}
523
Michael J. Spencerd6283772010-09-27 08:58:26 +0000524/// making a section real involves assigned it a number and putting
525/// name into the string table if needed
526void WinCOFFObjectWriter::MakeSectionReal(COFFSection &S, size_t Number) {
527 if (S.Name.size() > COFF::NameSize) {
Nico Rieck2c9c89b2013-07-29 12:30:12 +0000528 uint64_t StringTableEntry = Strings.insert(S.Name.c_str());
Michael J. Spencerd6283772010-09-27 08:58:26 +0000529
Nico Rieck01143f92014-02-25 09:50:40 +0000530 if (StringTableEntry <= Max6DecimalOffset) {
Nico Rieck2c9c89b2013-07-29 12:30:12 +0000531 std::sprintf(S.Header.Name, "/%d", unsigned(StringTableEntry));
Nico Rieck01143f92014-02-25 09:50:40 +0000532 } else if (StringTableEntry <= Max7DecimalOffset) {
Nico Rieck2c9c89b2013-07-29 12:30:12 +0000533 // With seven digits, we have to skip the terminating null. Because
534 // sprintf always appends it, we use a larger temporary buffer.
535 char buffer[9] = { };
536 std::sprintf(buffer, "/%d", unsigned(StringTableEntry));
537 std::memcpy(S.Header.Name, buffer, 8);
Nico Rieck01143f92014-02-25 09:50:40 +0000538 } else if (StringTableEntry <= MaxBase64Offset) {
Nico Rieck9d2c15e2014-02-22 16:12:20 +0000539 // Starting with 10,000,000, offsets are encoded as base64.
540 encodeBase64StringEntry(S.Header.Name, StringTableEntry);
Nico Rieck2c9c89b2013-07-29 12:30:12 +0000541 } else {
Nico Rieck9d2c15e2014-02-22 16:12:20 +0000542 report_fatal_error("COFF string table is greater than 64 GB.");
Nico Rieck2c9c89b2013-07-29 12:30:12 +0000543 }
Michael J. Spencerd6283772010-09-27 08:58:26 +0000544 } else
545 std::memcpy(S.Header.Name, S.Name.c_str(), S.Name.size());
546
547 S.Number = Number;
548 S.Symbol->Data.SectionNumber = S.Number;
549 S.Symbol->Aux[0].Aux.SectionDefinition.Number = S.Number;
550}
551
552void WinCOFFObjectWriter::MakeSymbolReal(COFFSymbol &S, size_t Index) {
553 if (S.Name.size() > COFF::NameSize) {
554 size_t StringTableEntry = Strings.insert(S.Name.c_str());
555
556 S.set_name_offset(StringTableEntry);
557 } else
558 std::memcpy(S.Data.Name, S.Name.c_str(), S.Name.size());
559 S.Index = Index;
560}
561
David Majnemer299674e2014-07-13 04:31:19 +0000562bool WinCOFFObjectWriter::ExportSymbol(const MCSymbol &Symbol,
Reid Kleckner8b2ad2a2013-11-18 23:08:12 +0000563 MCAssembler &Asm) {
564 // This doesn't seem to be right. Strings referred to from the .data section
565 // need symbols so they can be linked to code in the .text section right?
566
David Majnemer299674e2014-07-13 04:31:19 +0000567 // return Asm.isSymbolLinkerVisible(Symbol);
568
569 // Non-temporary labels should always be visible to the linker.
570 if (!Symbol.isTemporary())
571 return true;
572
573 // Absolute temporary labels are never visible.
574 if (!Symbol.isInSection())
575 return false;
Reid Kleckner8b2ad2a2013-11-18 23:08:12 +0000576
577 // For now, all non-variable symbols are exported,
578 // the linker will sort the rest out for us.
David Majnemer299674e2014-07-13 04:31:19 +0000579 return !Symbol.isVariable();
Reid Kleckner8b2ad2a2013-11-18 23:08:12 +0000580}
581
Michael J. Spencerd6283772010-09-27 08:58:26 +0000582bool WinCOFFObjectWriter::IsPhysicalSection(COFFSection *S) {
583 return (S->Header.Characteristics
584 & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) == 0;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000585}
586
587//------------------------------------------------------------------------------
588// entity writing methods
589
590void WinCOFFObjectWriter::WriteFileHeader(const COFF::header &Header) {
David Majnemer4d571592014-09-15 19:42:42 +0000591 if (UseBigObj) {
592 WriteLE16(COFF::IMAGE_FILE_MACHINE_UNKNOWN);
593 WriteLE16(0xFFFF);
594 WriteLE16(COFF::BigObjHeader::MinBigObjectVersion);
595 WriteLE16(Header.Machine);
596 WriteLE32(Header.TimeDateStamp);
597 for (uint8_t MagicChar : COFF::BigObjMagic)
598 Write8(MagicChar);
David Majnemer15f7ed92014-09-15 20:28:38 +0000599 WriteLE32(0);
600 WriteLE32(0);
601 WriteLE32(0);
602 WriteLE32(0);
David Majnemer4d571592014-09-15 19:42:42 +0000603 WriteLE32(Header.NumberOfSections);
604 WriteLE32(Header.PointerToSymbolTable);
605 WriteLE32(Header.NumberOfSymbols);
606 } else {
607 WriteLE16(Header.Machine);
608 WriteLE16(static_cast<int16_t>(Header.NumberOfSections));
609 WriteLE32(Header.TimeDateStamp);
610 WriteLE32(Header.PointerToSymbolTable);
611 WriteLE32(Header.NumberOfSymbols);
612 WriteLE16(Header.SizeOfOptionalHeader);
613 WriteLE16(Header.Characteristics);
614 }
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000615}
616
David Blaikief564ab62014-04-15 05:25:03 +0000617void WinCOFFObjectWriter::WriteSymbol(const COFFSymbol &S) {
618 WriteBytes(StringRef(S.Data.Name, COFF::NameSize));
619 WriteLE32(S.Data.Value);
David Majnemer4d571592014-09-15 19:42:42 +0000620 if (UseBigObj)
621 WriteLE32(S.Data.SectionNumber);
622 else
623 WriteLE16(static_cast<int16_t>(S.Data.SectionNumber));
David Blaikief564ab62014-04-15 05:25:03 +0000624 WriteLE16(S.Data.Type);
625 Write8(S.Data.StorageClass);
626 Write8(S.Data.NumberOfAuxSymbols);
627 WriteAuxiliarySymbols(S.Aux);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000628}
629
630void WinCOFFObjectWriter::WriteAuxiliarySymbols(
631 const COFFSymbol::AuxiliarySymbols &S) {
632 for(COFFSymbol::AuxiliarySymbols::const_iterator i = S.begin(), e = S.end();
633 i != e; ++i) {
634 switch(i->AuxType) {
635 case ATFunctionDefinition:
636 WriteLE32(i->Aux.FunctionDefinition.TagIndex);
637 WriteLE32(i->Aux.FunctionDefinition.TotalSize);
638 WriteLE32(i->Aux.FunctionDefinition.PointerToLinenumber);
639 WriteLE32(i->Aux.FunctionDefinition.PointerToNextFunction);
640 WriteZeros(sizeof(i->Aux.FunctionDefinition.unused));
David Majnemer4d571592014-09-15 19:42:42 +0000641 if (UseBigObj)
642 WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000643 break;
644 case ATbfAndefSymbol:
645 WriteZeros(sizeof(i->Aux.bfAndefSymbol.unused1));
646 WriteLE16(i->Aux.bfAndefSymbol.Linenumber);
647 WriteZeros(sizeof(i->Aux.bfAndefSymbol.unused2));
648 WriteLE32(i->Aux.bfAndefSymbol.PointerToNextFunction);
649 WriteZeros(sizeof(i->Aux.bfAndefSymbol.unused3));
David Majnemer4d571592014-09-15 19:42:42 +0000650 if (UseBigObj)
651 WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000652 break;
653 case ATWeakExternal:
654 WriteLE32(i->Aux.WeakExternal.TagIndex);
655 WriteLE32(i->Aux.WeakExternal.Characteristics);
656 WriteZeros(sizeof(i->Aux.WeakExternal.unused));
David Majnemer4d571592014-09-15 19:42:42 +0000657 if (UseBigObj)
658 WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000659 break;
660 case ATFile:
David Majnemer4d571592014-09-15 19:42:42 +0000661 WriteBytes(
662 StringRef(reinterpret_cast<const char *>(&i->Aux),
663 UseBigObj ? COFF::Symbol32Size : COFF::Symbol16Size));
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000664 break;
665 case ATSectionDefinition:
666 WriteLE32(i->Aux.SectionDefinition.Length);
667 WriteLE16(i->Aux.SectionDefinition.NumberOfRelocations);
668 WriteLE16(i->Aux.SectionDefinition.NumberOfLinenumbers);
669 WriteLE32(i->Aux.SectionDefinition.CheckSum);
David Majnemer4d571592014-09-15 19:42:42 +0000670 WriteLE16(static_cast<int16_t>(i->Aux.SectionDefinition.Number));
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000671 Write8(i->Aux.SectionDefinition.Selection);
672 WriteZeros(sizeof(i->Aux.SectionDefinition.unused));
David Majnemer4d571592014-09-15 19:42:42 +0000673 WriteLE16(static_cast<int16_t>(i->Aux.SectionDefinition.Number >> 16));
674 if (UseBigObj)
675 WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000676 break;
677 }
678 }
679}
680
681void WinCOFFObjectWriter::WriteSectionHeader(const COFF::section &S) {
682 WriteBytes(StringRef(S.Name, COFF::NameSize));
683
684 WriteLE32(S.VirtualSize);
685 WriteLE32(S.VirtualAddress);
686 WriteLE32(S.SizeOfRawData);
687 WriteLE32(S.PointerToRawData);
688 WriteLE32(S.PointerToRelocations);
689 WriteLE32(S.PointerToLineNumbers);
690 WriteLE16(S.NumberOfRelocations);
691 WriteLE16(S.NumberOfLineNumbers);
692 WriteLE32(S.Characteristics);
693}
694
695void WinCOFFObjectWriter::WriteRelocation(const COFF::relocation &R) {
696 WriteLE32(R.VirtualAddress);
697 WriteLE32(R.SymbolTableIndex);
698 WriteLE16(R.Type);
Chris Lattner2c52b792010-07-11 22:07:02 +0000699}
700
701////////////////////////////////////////////////////////////////////////////////
702// MCObjectWriter interface implementations
703
Rafael Espindola93e3cf02010-12-07 00:27:36 +0000704void WinCOFFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
705 const MCAsmLayout &Layout) {
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000706 // "Define" each section & symbol. This creates section & symbol
Michael J. Spencerd6283772010-09-27 08:58:26 +0000707 // entries in the staging area.
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000708 for (const auto & Section : Asm)
709 DefineSection(Section);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000710
David Blaikie583a31c2014-04-18 18:24:25 +0000711 for (MCSymbolData &SD : Asm.symbols())
David Majnemer299674e2014-07-13 04:31:19 +0000712 if (ExportSymbol(SD.getSymbol(), Asm))
David Blaikie583a31c2014-04-18 18:24:25 +0000713 DefineSymbol(SD, Asm, Layout);
Chris Lattner2c52b792010-07-11 22:07:02 +0000714}
715
716void WinCOFFObjectWriter::RecordRelocation(const MCAssembler &Asm,
717 const MCAsmLayout &Layout,
718 const MCFragment *Fragment,
719 const MCFixup &Fixup,
720 MCValue Target,
Rafael Espindola5904e122014-03-29 06:26:49 +0000721 bool &IsPCRel,
Chris Lattner2c52b792010-07-11 22:07:02 +0000722 uint64_t &FixedValue) {
Craig Topperbb694de2014-04-13 04:57:38 +0000723 assert(Target.getSymA() && "Relocation must reference a symbol!");
Michael J. Spencerccd28d02010-08-24 21:04:52 +0000724
Reid Klecknerdae7b4e2013-07-15 19:41:21 +0000725 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
726 const MCSymbol &A = Symbol.AliasedSymbol();
Timur Iskhodzhanov3e4ac4e2014-01-30 21:13:05 +0000727 if (!Asm.hasSymbolData(A))
728 Asm.getContext().FatalError(
729 Fixup.getLoc(),
730 Twine("symbol '") + A.getName() + "' can not be undefined");
731
David Blaikie908f4d42014-04-24 16:59:40 +0000732 const MCSymbolData &A_SD = Asm.getSymbolData(A);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000733
734 MCSectionData const *SectionData = Fragment->getParent();
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000735
Michael J. Spencerccd28d02010-08-24 21:04:52 +0000736 // Mark this symbol as requiring an entry in the symbol table.
Michael J. Spencer17990d52010-10-16 08:25:57 +0000737 assert(SectionMap.find(&SectionData->getSection()) != SectionMap.end() &&
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000738 "Section must already have been defined in ExecutePostLayoutBinding!");
Michael J. Spencer17990d52010-10-16 08:25:57 +0000739 assert(SymbolMap.find(&A_SD.getSymbol()) != SymbolMap.end() &&
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000740 "Symbol must already have been defined in ExecutePostLayoutBinding!");
741
Michael J. Spencer17990d52010-10-16 08:25:57 +0000742 COFFSection *coff_section = SectionMap[&SectionData->getSection()];
743 COFFSymbol *coff_symbol = SymbolMap[&A_SD.getSymbol()];
Rafael Espindolaed164772011-04-20 14:01:45 +0000744 const MCSymbolRefExpr *SymB = Target.getSymB();
David Majnemera45a1762014-01-06 07:39:46 +0000745 bool CrossSection = false;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000746
David Majnemera45a1762014-01-06 07:39:46 +0000747 if (SymB) {
748 const MCSymbol *B = &SymB->getSymbol();
David Blaikie908f4d42014-04-24 16:59:40 +0000749 const MCSymbolData &B_SD = Asm.getSymbolData(*B);
David Majnemera45a1762014-01-06 07:39:46 +0000750 if (!B_SD.getFragment())
751 Asm.getContext().FatalError(
752 Fixup.getLoc(),
753 Twine("symbol '") + B->getName() +
754 "' can not be undefined in a subtraction expression");
755
756 if (!A_SD.getFragment())
757 Asm.getContext().FatalError(
758 Fixup.getLoc(),
759 Twine("symbol '") + Symbol.getName() +
760 "' can not be undefined in a subtraction expression");
761
762 CrossSection = &Symbol.getSection() != &B->getSection();
Michael J. Spencerccd28d02010-08-24 21:04:52 +0000763
Rafael Espindolac3dc4862011-04-21 18:36:50 +0000764 // Offset of the symbol in the section
765 int64_t a = Layout.getSymbolOffset(&B_SD);
Michael J. Spencerccd28d02010-08-24 21:04:52 +0000766
Rafael Espindolac3dc4862011-04-21 18:36:50 +0000767 // Ofeset of the relocation in the section
768 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
769
770 FixedValue = b - a;
Michael J. Spencerccd28d02010-08-24 21:04:52 +0000771 // In the case where we have SymbA and SymB, we just need to store the delta
772 // between the two symbols. Update FixedValue to account for the delta, and
773 // skip recording the relocation.
Rafael Espindolaed164772011-04-20 14:01:45 +0000774 if (!CrossSection)
775 return;
Michael J. Spencerccd28d02010-08-24 21:04:52 +0000776 } else {
777 FixedValue = Target.getConstant();
778 }
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000779
780 COFFRelocation Reloc;
781
Daniel Dunbar727be432010-07-31 21:08:54 +0000782 Reloc.Data.SymbolTableIndex = 0;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000783 Reloc.Data.VirtualAddress = Layout.getFragmentOffset(Fragment);
Michael J. Spencerd6283772010-09-27 08:58:26 +0000784
Michael J. Spencera65d17a2010-10-05 19:48:12 +0000785 // Turn relocations for temporary symbols into section relocations.
Rafael Espindolaed164772011-04-20 14:01:45 +0000786 if (coff_symbol->MCData->getSymbol().isTemporary() || CrossSection) {
Michael J. Spencerd6283772010-09-27 08:58:26 +0000787 Reloc.Symb = coff_symbol->Section->Symbol;
Michael J. Spencera3b34ed2010-10-05 19:48:03 +0000788 FixedValue += Layout.getFragmentOffset(coff_symbol->MCData->Fragment)
789 + coff_symbol->MCData->getOffset();
Michael J. Spencerd6283772010-09-27 08:58:26 +0000790 } else
791 Reloc.Symb = coff_symbol;
792
793 ++Reloc.Symb->Relocations;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000794
795 Reloc.Data.VirtualAddress += Fixup.getOffset();
Nico Rieck1da45292013-04-10 23:28:17 +0000796 Reloc.Data.Type = TargetObjectWriter->getRelocType(Target, Fixup,
797 CrossSection);
Rafael Espindolae61724a2011-12-22 22:21:47 +0000798
799 // FIXME: Can anyone explain what this does other than adjust for the size
800 // of the offset?
Saleem Abdulrasool2c080512014-04-13 20:47:55 +0000801 if ((Header.Machine == COFF::IMAGE_FILE_MACHINE_AMD64 &&
802 Reloc.Data.Type == COFF::IMAGE_REL_AMD64_REL32) ||
803 (Header.Machine == COFF::IMAGE_FILE_MACHINE_I386 &&
804 Reloc.Data.Type == COFF::IMAGE_REL_I386_REL32))
Michael J. Spencerccd28d02010-08-24 21:04:52 +0000805 FixedValue += 4;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000806
Saleem Abdulrasool84b952b2014-04-27 03:48:22 +0000807 if (Header.Machine == COFF::IMAGE_FILE_MACHINE_ARMNT) {
808 switch (Reloc.Data.Type) {
809 case COFF::IMAGE_REL_ARM_ABSOLUTE:
810 case COFF::IMAGE_REL_ARM_ADDR32:
811 case COFF::IMAGE_REL_ARM_ADDR32NB:
812 case COFF::IMAGE_REL_ARM_TOKEN:
813 case COFF::IMAGE_REL_ARM_SECTION:
814 case COFF::IMAGE_REL_ARM_SECREL:
815 break;
816 case COFF::IMAGE_REL_ARM_BRANCH11:
817 case COFF::IMAGE_REL_ARM_BLX11:
818 // IMAGE_REL_ARM_BRANCH11 and IMAGE_REL_ARM_BLX11 are only used for
819 // pre-ARMv7, which implicitly rules it out of ARMNT (it would be valid
820 // for Windows CE).
821 case COFF::IMAGE_REL_ARM_BRANCH24:
822 case COFF::IMAGE_REL_ARM_BLX24:
823 case COFF::IMAGE_REL_ARM_MOV32A:
824 // IMAGE_REL_ARM_BRANCH24, IMAGE_REL_ARM_BLX24, IMAGE_REL_ARM_MOV32A are
825 // only used for ARM mode code, which is documented as being unsupported
Alp Tokerbeaca192014-05-15 01:52:21 +0000826 // by Windows on ARM. Empirical proof indicates that masm is able to
Saleem Abdulrasool84b952b2014-04-27 03:48:22 +0000827 // generate the relocations however the rest of the MSVC toolchain is
828 // unable to handle it.
829 llvm_unreachable("unsupported relocation");
830 break;
831 case COFF::IMAGE_REL_ARM_MOV32T:
832 break;
833 case COFF::IMAGE_REL_ARM_BRANCH20T:
834 case COFF::IMAGE_REL_ARM_BRANCH24T:
835 case COFF::IMAGE_REL_ARM_BLX23T:
836 // IMAGE_REL_BRANCH20T, IMAGE_REL_ARM_BRANCH24T, IMAGE_REL_ARM_BLX23T all
837 // perform a 4 byte adjustment to the relocation. Relative branches are
838 // offset by 4 on ARM, however, because there is no RELA relocations, all
839 // branches are offset by 4.
840 FixedValue = FixedValue + 4;
841 break;
842 }
843 }
844
Saleem Abdulrasool54bed122014-05-21 23:17:50 +0000845 if (TargetObjectWriter->recordRelocation(Fixup))
846 coff_section->Relocations.push_back(Reloc);
Chris Lattner2c52b792010-07-11 22:07:02 +0000847}
848
Rafael Espindolabce26a12010-10-05 15:11:03 +0000849void WinCOFFObjectWriter::WriteObject(MCAssembler &Asm,
Chris Lattner2c52b792010-07-11 22:07:02 +0000850 const MCAsmLayout &Layout) {
David Majnemer4d571592014-09-15 19:42:42 +0000851 size_t SectionsSize = Sections.size();
852 if (SectionsSize > static_cast<size_t>(INT32_MAX))
853 report_fatal_error(
854 "PE COFF object files can't have more than 2147483647 sections");
Michael J. Spencerd6283772010-09-27 08:58:26 +0000855
David Majnemer4d571592014-09-15 19:42:42 +0000856 // Assign symbol and section indexes and offsets.
857 int32_t NumberOfSections = static_cast<int32_t>(SectionsSize);
858
859 UseBigObj = NumberOfSections > COFF::MaxNumberOfSections16;
860
861 DenseMap<COFFSection *, int32_t> SectionIndices(
862 NextPowerOf2(NumberOfSections));
863 size_t Number = 1;
David Majnemer9ab5ff12014-08-28 04:02:50 +0000864 for (const auto &Section : Sections) {
David Majnemer4d571592014-09-15 19:42:42 +0000865 SectionIndices[Section.get()] = Number;
Saleem Abdulrasoole9bd9162014-06-06 21:40:16 +0000866 MakeSectionReal(*Section, Number);
David Majnemer4d571592014-09-15 19:42:42 +0000867 ++Number;
Michael J. Spencerd6283772010-09-27 08:58:26 +0000868 }
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000869
David Majnemer4d571592014-09-15 19:42:42 +0000870 Header.NumberOfSections = NumberOfSections;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000871 Header.NumberOfSymbols = 0;
872
David Majnemer4d571592014-09-15 19:42:42 +0000873 for (auto FI = Asm.file_names_begin(), FE = Asm.file_names_end();
874 FI != FE; ++FI) {
875 // round up to calculate the number of auxiliary symbols required
876 unsigned SymbolSize = UseBigObj ? COFF::Symbol32Size : COFF::Symbol16Size;
877 unsigned Count = (FI->size() + SymbolSize - 1) / SymbolSize;
878
879 COFFSymbol *file = createSymbol(".file");
880 file->Data.SectionNumber = COFF::IMAGE_SYM_DEBUG;
881 file->Data.StorageClass = COFF::IMAGE_SYM_CLASS_FILE;
882 file->Aux.resize(Count);
883
884 unsigned Offset = 0;
885 unsigned Length = FI->size();
886 for (auto & Aux : file->Aux) {
887 Aux.AuxType = ATFile;
888
889 if (Length > SymbolSize) {
890 memcpy(&Aux.Aux, FI->c_str() + Offset, SymbolSize);
891 Length = Length - SymbolSize;
892 } else {
893 memcpy(&Aux.Aux, FI->c_str() + Offset, Length);
894 memset((char *)&Aux.Aux + Length, 0, SymbolSize - Length);
895 break;
896 }
897
898 Offset += SymbolSize;
899 }
900 }
901
David Majnemer9ab5ff12014-08-28 04:02:50 +0000902 for (auto &Symbol : Symbols) {
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000903 // Update section number & offset for symbols that have them.
Rafael Espindola575f79a2014-05-01 13:37:57 +0000904 if (Symbol->Section)
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000905 Symbol->Data.SectionNumber = Symbol->Section->Number;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000906
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000907 if (Symbol->should_keep()) {
908 MakeSymbolReal(*Symbol, Header.NumberOfSymbols++);
Michael J. Spencerd6283772010-09-27 08:58:26 +0000909
910 // Update auxiliary symbol info.
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000911 Symbol->Data.NumberOfAuxSymbols = Symbol->Aux.size();
912 Header.NumberOfSymbols += Symbol->Data.NumberOfAuxSymbols;
Michael J. Spencerd6283772010-09-27 08:58:26 +0000913 } else
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000914 Symbol->Index = -1;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000915 }
916
917 // Fixup weak external references.
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000918 for (auto & Symbol : Symbols) {
919 if (Symbol->Other) {
920 assert(Symbol->Index != -1);
921 assert(Symbol->Aux.size() == 1 && "Symbol must contain one aux symbol!");
922 assert(Symbol->Aux[0].AuxType == ATWeakExternal &&
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000923 "Symbol's aux symbol must be a Weak External!");
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000924 Symbol->Aux[0].Aux.WeakExternal.TagIndex = Symbol->Other->Index;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000925 }
926 }
927
Nico Riecka37acf72013-07-06 12:13:10 +0000928 // Fixup associative COMDAT sections.
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000929 for (auto & Section : Sections) {
930 if (Section->Symbol->Aux[0].Aux.SectionDefinition.Selection !=
Nico Riecka37acf72013-07-06 12:13:10 +0000931 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
932 continue;
933
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000934 const MCSectionCOFF &MCSec =
935 static_cast<const MCSectionCOFF &>(Section->MCData->getSection());
Nico Riecka37acf72013-07-06 12:13:10 +0000936
Rafael Espindola0766ae02014-06-06 19:26:12 +0000937 const MCSymbol *COMDAT = MCSec.getCOMDATSymbol();
938 assert(COMDAT);
939 COFFSymbol *COMDATSymbol = GetOrCreateCOFFSymbol(COMDAT);
940 assert(COMDATSymbol);
941 COFFSection *Assoc = COMDATSymbol->Section;
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000942 if (!Assoc)
Rafael Espindola0766ae02014-06-06 19:26:12 +0000943 report_fatal_error(
944 Twine("Missing associated COMDAT section for section ") +
945 MCSec.getSectionName());
Nico Riecka37acf72013-07-06 12:13:10 +0000946
947 // Skip this section if the associated section is unused.
948 if (Assoc->Number == -1)
949 continue;
950
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000951 Section->Symbol->Aux[0].Aux.SectionDefinition.Number = SectionIndices[Assoc];
Nico Riecka37acf72013-07-06 12:13:10 +0000952 }
953
954
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000955 // Assign file offsets to COFF object file structures.
956
957 unsigned offset = 0;
958
David Majnemer4d571592014-09-15 19:42:42 +0000959 if (UseBigObj)
960 offset += COFF::Header32Size;
961 else
962 offset += COFF::Header16Size;
Michael J. Spencerd6283772010-09-27 08:58:26 +0000963 offset += COFF::SectionSize * Header.NumberOfSections;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000964
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000965 for (const auto & Section : Asm) {
966 COFFSection *Sec = SectionMap[&Section.getSection()];
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000967
Michael J. Spencerd6283772010-09-27 08:58:26 +0000968 if (Sec->Number == -1)
969 continue;
970
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000971 Sec->Header.SizeOfRawData = Layout.getSectionAddressSize(&Section);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000972
Michael J. Spencerd6283772010-09-27 08:58:26 +0000973 if (IsPhysicalSection(Sec)) {
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000974 Sec->Header.PointerToRawData = offset;
975
976 offset += Sec->Header.SizeOfRawData;
977 }
978
979 if (Sec->Relocations.size() > 0) {
Michael J. Spencerfa39bd22012-03-15 09:03:03 +0000980 bool RelocationsOverflow = Sec->Relocations.size() >= 0xffff;
981
982 if (RelocationsOverflow) {
David Majnemer9ab5ff12014-08-28 04:02:50 +0000983 // Signal overflow by setting NumberOfRelocations to max value. Actual
Michael J. Spencerfa39bd22012-03-15 09:03:03 +0000984 // size is found in reloc #0. Microsoft tools understand this.
985 Sec->Header.NumberOfRelocations = 0xffff;
986 } else {
987 Sec->Header.NumberOfRelocations = Sec->Relocations.size();
988 }
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000989 Sec->Header.PointerToRelocations = offset;
990
Michael J. Spencerfa39bd22012-03-15 09:03:03 +0000991 if (RelocationsOverflow) {
992 // Reloc #0 will contain actual count, so make room for it.
993 offset += COFF::RelocationSize;
994 }
995
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000996 offset += COFF::RelocationSize * Sec->Relocations.size();
997
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000998 for (auto & Relocation : Sec->Relocations) {
999 assert(Relocation.Symb->Index != -1);
1000 Relocation.Data.SymbolTableIndex = Relocation.Symb->Index;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +00001001 }
1002 }
1003
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +00001004 assert(Sec->Symbol->Aux.size() == 1 &&
1005 "Section's symbol must have one aux!");
Michael J. Spencerd6283772010-09-27 08:58:26 +00001006 AuxSymbol &Aux = Sec->Symbol->Aux[0];
Michael J. Spencerb5fc1382010-07-26 02:17:32 +00001007 assert(Aux.AuxType == ATSectionDefinition &&
1008 "Section's symbol's aux symbol must be a Section Definition!");
1009 Aux.Aux.SectionDefinition.Length = Sec->Header.SizeOfRawData;
1010 Aux.Aux.SectionDefinition.NumberOfRelocations =
1011 Sec->Header.NumberOfRelocations;
1012 Aux.Aux.SectionDefinition.NumberOfLinenumbers =
1013 Sec->Header.NumberOfLineNumbers;
1014 }
1015
1016 Header.PointerToSymbolTable = offset;
1017
Rafael Espindola5ac4ad22013-12-04 02:26:54 +00001018 // We want a deterministic output. It looks like GNU as also writes 0 in here.
Rafael Espindola9201e6b2013-12-04 02:02:55 +00001019 Header.TimeDateStamp = 0;
Michael J. Spencera6cfbeb2010-08-03 04:43:33 +00001020
Michael J. Spencerb5fc1382010-07-26 02:17:32 +00001021 // Write it all to disk...
1022 WriteFileHeader(Header);
1023
1024 {
1025 sections::iterator i, ie;
1026 MCAssembler::const_iterator j, je;
1027
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +00001028 for (auto & Section : Sections) {
1029 if (Section->Number != -1) {
1030 if (Section->Relocations.size() >= 0xffff)
1031 Section->Header.Characteristics |= COFF::IMAGE_SCN_LNK_NRELOC_OVFL;
1032 WriteSectionHeader(Section->Header);
Michael J. Spencerfa39bd22012-03-15 09:03:03 +00001033 }
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +00001034 }
Michael J. Spencerb5fc1382010-07-26 02:17:32 +00001035
1036 for (i = Sections.begin(), ie = Sections.end(),
1037 j = Asm.begin(), je = Asm.end();
Michael J. Spencerd6283772010-09-27 08:58:26 +00001038 (i != ie) && (j != je); ++i, ++j) {
1039
1040 if ((*i)->Number == -1)
1041 continue;
1042
Michael J. Spencerb5fc1382010-07-26 02:17:32 +00001043 if ((*i)->Header.PointerToRawData != 0) {
1044 assert(OS.tell() == (*i)->Header.PointerToRawData &&
1045 "Section::PointerToRawData is insane!");
1046
Jim Grosbach18e2fe42011-12-06 00:03:48 +00001047 Asm.writeSectionData(j, Layout);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +00001048 }
1049
1050 if ((*i)->Relocations.size() > 0) {
1051 assert(OS.tell() == (*i)->Header.PointerToRelocations &&
1052 "Section::PointerToRelocations is insane!");
1053
Michael J. Spencerfa39bd22012-03-15 09:03:03 +00001054 if ((*i)->Relocations.size() >= 0xffff) {
1055 // In case of overflow, write actual relocation count as first
1056 // relocation. Including the synthetic reloc itself (+ 1).
1057 COFF::relocation r;
1058 r.VirtualAddress = (*i)->Relocations.size() + 1;
1059 r.SymbolTableIndex = 0;
1060 r.Type = 0;
1061 WriteRelocation(r);
1062 }
1063
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +00001064 for (const auto & Relocation : (*i)->Relocations)
1065 WriteRelocation(Relocation.Data);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +00001066 } else
1067 assert((*i)->Header.PointerToRelocations == 0 &&
1068 "Section::PointerToRelocations is insane!");
1069 }
1070 }
1071
1072 assert(OS.tell() == Header.PointerToSymbolTable &&
1073 "Header::PointerToSymbolTable is insane!");
1074
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +00001075 for (auto & Symbol : Symbols)
1076 if (Symbol->Index != -1)
1077 WriteSymbol(*Symbol);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +00001078
1079 OS.write((char const *)&Strings.Data.front(), Strings.Data.size());
Chris Lattner2c52b792010-07-11 22:07:02 +00001080}
1081
Rafael Espindola908d2ed2011-12-24 02:14:02 +00001082MCWinCOFFObjectTargetWriter::MCWinCOFFObjectTargetWriter(unsigned Machine_) :
1083 Machine(Machine_) {
1084}
1085
Juergen Ributzkad12ccbd2013-11-19 00:57:56 +00001086// Pin the vtable to this file.
1087void MCWinCOFFObjectTargetWriter::anchor() {}
1088
Chris Lattner2c52b792010-07-11 22:07:02 +00001089//------------------------------------------------------------------------------
1090// WinCOFFObjectWriter factory function
1091
1092namespace llvm {
Rafael Espindola908d2ed2011-12-24 02:14:02 +00001093 MCObjectWriter *createWinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW,
1094 raw_ostream &OS) {
1095 return new WinCOFFObjectWriter(MOTW, OS);
Chris Lattner2c52b792010-07-11 22:07:02 +00001096 }
Michael J. Spencerc2129372010-07-26 03:01:28 +00001097}