1 //===- llvm/MC/MCWinCOFFStreamer.cpp --------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains an implementation of a Windows COFF object file streamer.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/ADT/SmallString.h"
14 #include "llvm/ADT/SmallVector.h"
15 #include "llvm/ADT/Triple.h"
16 #include "llvm/ADT/Twine.h"
17 #include "llvm/BinaryFormat/COFF.h"
18 #include "llvm/MC/MCAsmBackend.h"
19 #include "llvm/MC/MCAssembler.h"
20 #include "llvm/MC/MCCodeEmitter.h"
21 #include "llvm/MC/MCContext.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCFixup.h"
24 #include "llvm/MC/MCFragment.h"
25 #include "llvm/MC/MCObjectFileInfo.h"
26 #include "llvm/MC/MCObjectStreamer.h"
27 #include "llvm/MC/MCObjectWriter.h"
28 #include "llvm/MC/MCSection.h"
29 #include "llvm/MC/MCSymbolCOFF.h"
30 #include "llvm/MC/MCWinCOFFStreamer.h"
31 #include "llvm/Support/Casting.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/SMLoc.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include <algorithm>
37 #include <cassert>
38 #include <cstdint>
39 
40 using namespace llvm;
41 
42 #define DEBUG_TYPE "WinCOFFStreamer"
43 
MCWinCOFFStreamer(MCContext & Context,std::unique_ptr<MCAsmBackend> MAB,std::unique_ptr<MCCodeEmitter> CE,std::unique_ptr<MCObjectWriter> OW)44 MCWinCOFFStreamer::MCWinCOFFStreamer(MCContext &Context,
45                                      std::unique_ptr<MCAsmBackend> MAB,
46                                      std::unique_ptr<MCCodeEmitter> CE,
47                                      std::unique_ptr<MCObjectWriter> OW)
48     : MCObjectStreamer(Context, std::move(MAB), std::move(OW), std::move(CE)),
49       CurSymbol(nullptr) {}
50 
emitInstToData(const MCInst & Inst,const MCSubtargetInfo & STI)51 void MCWinCOFFStreamer::emitInstToData(const MCInst &Inst,
52                                        const MCSubtargetInfo &STI) {
53   MCDataFragment *DF = getOrCreateDataFragment();
54 
55   SmallVector<MCFixup, 4> Fixups;
56   SmallString<256> Code;
57   raw_svector_ostream VecOS(Code);
58   getAssembler().getEmitter().encodeInstruction(Inst, VecOS, Fixups, STI);
59 
60   // Add the fixups and data.
61   for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
62     Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
63     DF->getFixups().push_back(Fixups[i]);
64   }
65   DF->setHasInstructions(STI);
66   DF->getContents().append(Code.begin(), Code.end());
67 }
68 
InitSections(bool NoExecStack)69 void MCWinCOFFStreamer::InitSections(bool NoExecStack) {
70   // FIXME: this is identical to the ELF one.
71   // This emulates the same behavior of GNU as. This makes it easier
72   // to compare the output as the major sections are in the same order.
73   SwitchSection(getContext().getObjectFileInfo()->getTextSection());
74   emitCodeAlignment(4);
75 
76   SwitchSection(getContext().getObjectFileInfo()->getDataSection());
77   emitCodeAlignment(4);
78 
79   SwitchSection(getContext().getObjectFileInfo()->getBSSSection());
80   emitCodeAlignment(4);
81 
82   SwitchSection(getContext().getObjectFileInfo()->getTextSection());
83 }
84 
emitLabel(MCSymbol * S,SMLoc Loc)85 void MCWinCOFFStreamer::emitLabel(MCSymbol *S, SMLoc Loc) {
86   auto *Symbol = cast<MCSymbolCOFF>(S);
87   MCObjectStreamer::emitLabel(Symbol, Loc);
88 }
89 
emitAssemblerFlag(MCAssemblerFlag Flag)90 void MCWinCOFFStreamer::emitAssemblerFlag(MCAssemblerFlag Flag) {
91   // Let the target do whatever target specific stuff it needs to do.
92   getAssembler().getBackend().handleAssemblerFlag(Flag);
93 
94   switch (Flag) {
95   // None of these require COFF specific handling.
96   case MCAF_SyntaxUnified:
97   case MCAF_Code16:
98   case MCAF_Code32:
99   case MCAF_Code64:
100     break;
101   case MCAF_SubsectionsViaSymbols:
102     llvm_unreachable("COFF doesn't support .subsections_via_symbols");
103   }
104 }
105 
emitThumbFunc(MCSymbol * Func)106 void MCWinCOFFStreamer::emitThumbFunc(MCSymbol *Func) {
107   llvm_unreachable("not implemented");
108 }
109 
emitSymbolAttribute(MCSymbol * S,MCSymbolAttr Attribute)110 bool MCWinCOFFStreamer::emitSymbolAttribute(MCSymbol *S,
111                                             MCSymbolAttr Attribute) {
112   auto *Symbol = cast<MCSymbolCOFF>(S);
113   getAssembler().registerSymbol(*Symbol);
114 
115   switch (Attribute) {
116   default: return false;
117   case MCSA_WeakReference:
118   case MCSA_Weak:
119     Symbol->setIsWeakExternal();
120     Symbol->setExternal(true);
121     break;
122   case MCSA_Global:
123     Symbol->setExternal(true);
124     break;
125   case MCSA_AltEntry:
126     llvm_unreachable("COFF doesn't support the .alt_entry attribute");
127   }
128 
129   return true;
130 }
131 
emitSymbolDesc(MCSymbol * Symbol,unsigned DescValue)132 void MCWinCOFFStreamer::emitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
133   llvm_unreachable("not implemented");
134 }
135 
BeginCOFFSymbolDef(MCSymbol const * S)136 void MCWinCOFFStreamer::BeginCOFFSymbolDef(MCSymbol const *S) {
137   auto *Symbol = cast<MCSymbolCOFF>(S);
138   if (CurSymbol)
139     Error("starting a new symbol definition without completing the "
140           "previous one");
141   CurSymbol = Symbol;
142 }
143 
EmitCOFFSymbolStorageClass(int StorageClass)144 void MCWinCOFFStreamer::EmitCOFFSymbolStorageClass(int StorageClass) {
145   if (!CurSymbol) {
146     Error("storage class specified outside of symbol definition");
147     return;
148   }
149 
150   if (StorageClass & ~COFF::SSC_Invalid) {
151     Error("storage class value '" + Twine(StorageClass) +
152                "' out of range");
153     return;
154   }
155 
156   getAssembler().registerSymbol(*CurSymbol);
157   cast<MCSymbolCOFF>(CurSymbol)->setClass((uint16_t)StorageClass);
158 }
159 
EmitCOFFSymbolType(int Type)160 void MCWinCOFFStreamer::EmitCOFFSymbolType(int Type) {
161   if (!CurSymbol) {
162     Error("symbol type specified outside of a symbol definition");
163     return;
164   }
165 
166   if (Type & ~0xffff) {
167     Error("type value '" + Twine(Type) + "' out of range");
168     return;
169   }
170 
171   getAssembler().registerSymbol(*CurSymbol);
172   cast<MCSymbolCOFF>(CurSymbol)->setType((uint16_t)Type);
173 }
174 
EndCOFFSymbolDef()175 void MCWinCOFFStreamer::EndCOFFSymbolDef() {
176   if (!CurSymbol)
177     Error("ending symbol definition without starting one");
178   CurSymbol = nullptr;
179 }
180 
EmitCOFFSafeSEH(MCSymbol const * Symbol)181 void MCWinCOFFStreamer::EmitCOFFSafeSEH(MCSymbol const *Symbol) {
182   // SafeSEH is a feature specific to 32-bit x86.  It does not exist (and is
183   // unnecessary) on all platforms which use table-based exception dispatch.
184   if (getContext().getTargetTriple().getArch() != Triple::x86)
185     return;
186 
187   const MCSymbolCOFF *CSymbol = cast<MCSymbolCOFF>(Symbol);
188   if (CSymbol->isSafeSEH())
189     return;
190 
191   MCSection *SXData = getContext().getObjectFileInfo()->getSXDataSection();
192   getAssembler().registerSection(*SXData);
193   if (SXData->getAlignment() < 4)
194     SXData->setAlignment(Align(4));
195 
196   new MCSymbolIdFragment(Symbol, SXData);
197 
198   getAssembler().registerSymbol(*Symbol);
199   CSymbol->setIsSafeSEH();
200 
201   // The Microsoft linker requires that the symbol type of a handler be
202   // function. Go ahead and oblige it here.
203   CSymbol->setType(COFF::IMAGE_SYM_DTYPE_FUNCTION
204                    << COFF::SCT_COMPLEX_TYPE_SHIFT);
205 }
206 
EmitCOFFSymbolIndex(MCSymbol const * Symbol)207 void MCWinCOFFStreamer::EmitCOFFSymbolIndex(MCSymbol const *Symbol) {
208   MCSection *Sec = getCurrentSectionOnly();
209   getAssembler().registerSection(*Sec);
210   if (Sec->getAlignment() < 4)
211     Sec->setAlignment(Align(4));
212 
213   new MCSymbolIdFragment(Symbol, getCurrentSectionOnly());
214 
215   getAssembler().registerSymbol(*Symbol);
216 }
217 
EmitCOFFSectionIndex(const MCSymbol * Symbol)218 void MCWinCOFFStreamer::EmitCOFFSectionIndex(const MCSymbol *Symbol) {
219   visitUsedSymbol(*Symbol);
220   MCDataFragment *DF = getOrCreateDataFragment();
221   const MCSymbolRefExpr *SRE = MCSymbolRefExpr::create(Symbol, getContext());
222   MCFixup Fixup = MCFixup::create(DF->getContents().size(), SRE, FK_SecRel_2);
223   DF->getFixups().push_back(Fixup);
224   DF->getContents().resize(DF->getContents().size() + 2, 0);
225 }
226 
EmitCOFFSecRel32(const MCSymbol * Symbol,uint64_t Offset)227 void MCWinCOFFStreamer::EmitCOFFSecRel32(const MCSymbol *Symbol,
228                                          uint64_t Offset) {
229   visitUsedSymbol(*Symbol);
230   MCDataFragment *DF = getOrCreateDataFragment();
231   // Create Symbol A for the relocation relative reference.
232   const MCExpr *MCE = MCSymbolRefExpr::create(Symbol, getContext());
233   // Add the constant offset, if given.
234   if (Offset)
235     MCE = MCBinaryExpr::createAdd(
236         MCE, MCConstantExpr::create(Offset, getContext()), getContext());
237   // Build the secrel32 relocation.
238   MCFixup Fixup = MCFixup::create(DF->getContents().size(), MCE, FK_SecRel_4);
239   // Record the relocation.
240   DF->getFixups().push_back(Fixup);
241   // Emit 4 bytes (zeros) to the object file.
242   DF->getContents().resize(DF->getContents().size() + 4, 0);
243 }
244 
EmitCOFFImgRel32(const MCSymbol * Symbol,int64_t Offset)245 void MCWinCOFFStreamer::EmitCOFFImgRel32(const MCSymbol *Symbol,
246                                          int64_t Offset) {
247   visitUsedSymbol(*Symbol);
248   MCDataFragment *DF = getOrCreateDataFragment();
249   // Create Symbol A for the relocation relative reference.
250   const MCExpr *MCE = MCSymbolRefExpr::create(
251       Symbol, MCSymbolRefExpr::VK_COFF_IMGREL32, getContext());
252   // Add the constant offset, if given.
253   if (Offset)
254     MCE = MCBinaryExpr::createAdd(
255         MCE, MCConstantExpr::create(Offset, getContext()), getContext());
256   // Build the imgrel relocation.
257   MCFixup Fixup = MCFixup::create(DF->getContents().size(), MCE, FK_Data_4);
258   // Record the relocation.
259   DF->getFixups().push_back(Fixup);
260   // Emit 4 bytes (zeros) to the object file.
261   DF->getContents().resize(DF->getContents().size() + 4, 0);
262 }
263 
emitCommonSymbol(MCSymbol * S,uint64_t Size,unsigned ByteAlignment)264 void MCWinCOFFStreamer::emitCommonSymbol(MCSymbol *S, uint64_t Size,
265                                          unsigned ByteAlignment) {
266   auto *Symbol = cast<MCSymbolCOFF>(S);
267 
268   const Triple &T = getContext().getTargetTriple();
269   if (T.isWindowsMSVCEnvironment()) {
270     if (ByteAlignment > 32)
271       report_fatal_error("alignment is limited to 32-bytes");
272 
273     // Round size up to alignment so that we will honor the alignment request.
274     Size = std::max(Size, static_cast<uint64_t>(ByteAlignment));
275   }
276 
277   getAssembler().registerSymbol(*Symbol);
278   Symbol->setExternal(true);
279   Symbol->setCommon(Size, ByteAlignment);
280 
281   if (!T.isWindowsMSVCEnvironment() && ByteAlignment > 1) {
282     SmallString<128> Directive;
283     raw_svector_ostream OS(Directive);
284     const MCObjectFileInfo *MFI = getContext().getObjectFileInfo();
285 
286     OS << " -aligncomm:\"" << Symbol->getName() << "\","
287        << Log2_32_Ceil(ByteAlignment);
288 
289     PushSection();
290     SwitchSection(MFI->getDrectveSection());
291     emitBytes(Directive);
292     PopSection();
293   }
294 }
295 
emitLocalCommonSymbol(MCSymbol * S,uint64_t Size,unsigned ByteAlignment)296 void MCWinCOFFStreamer::emitLocalCommonSymbol(MCSymbol *S, uint64_t Size,
297                                               unsigned ByteAlignment) {
298   auto *Symbol = cast<MCSymbolCOFF>(S);
299 
300   MCSection *Section = getContext().getObjectFileInfo()->getBSSSection();
301   PushSection();
302   SwitchSection(Section);
303   emitValueToAlignment(ByteAlignment, 0, 1, 0);
304   emitLabel(Symbol);
305   Symbol->setExternal(false);
306   emitZeros(Size);
307   PopSection();
308 }
309 
emitWeakReference(MCSymbol * AliasS,const MCSymbol * Symbol)310 void MCWinCOFFStreamer::emitWeakReference(MCSymbol *AliasS,
311                                           const MCSymbol *Symbol) {
312   auto *Alias = cast<MCSymbolCOFF>(AliasS);
313   emitSymbolAttribute(Alias, MCSA_Weak);
314 
315   getAssembler().registerSymbol(*Symbol);
316   Alias->setVariableValue(MCSymbolRefExpr::create(
317       Symbol, MCSymbolRefExpr::VK_WEAKREF, getContext()));
318 }
319 
emitZerofill(MCSection * Section,MCSymbol * Symbol,uint64_t Size,unsigned ByteAlignment,SMLoc Loc)320 void MCWinCOFFStreamer::emitZerofill(MCSection *Section, MCSymbol *Symbol,
321                                      uint64_t Size, unsigned ByteAlignment,
322                                      SMLoc Loc) {
323   llvm_unreachable("not implemented");
324 }
325 
emitTBSSSymbol(MCSection * Section,MCSymbol * Symbol,uint64_t Size,unsigned ByteAlignment)326 void MCWinCOFFStreamer::emitTBSSSymbol(MCSection *Section, MCSymbol *Symbol,
327                                        uint64_t Size, unsigned ByteAlignment) {
328   llvm_unreachable("not implemented");
329 }
330 
331 // TODO: Implement this if you want to emit .comment section in COFF obj files.
emitIdent(StringRef IdentString)332 void MCWinCOFFStreamer::emitIdent(StringRef IdentString) {
333   llvm_unreachable("not implemented");
334 }
335 
EmitWinEHHandlerData(SMLoc Loc)336 void MCWinCOFFStreamer::EmitWinEHHandlerData(SMLoc Loc) {
337   llvm_unreachable("not implemented");
338 }
339 
emitCGProfileEntry(const MCSymbolRefExpr * From,const MCSymbolRefExpr * To,uint64_t Count)340 void MCWinCOFFStreamer::emitCGProfileEntry(const MCSymbolRefExpr *From,
341                                            const MCSymbolRefExpr *To,
342                                            uint64_t Count) {
343   // Ignore temporary symbols for now.
344   if (!From->getSymbol().isTemporary() && !To->getSymbol().isTemporary())
345     getAssembler().CGProfile.push_back({From, To, Count});
346 }
347 
finalizeCGProfileEntry(const MCSymbolRefExpr * & SRE)348 void MCWinCOFFStreamer::finalizeCGProfileEntry(const MCSymbolRefExpr *&SRE) {
349   const MCSymbol *S = &SRE->getSymbol();
350   bool Created;
351   getAssembler().registerSymbol(*S, &Created);
352   if (Created)
353     cast<MCSymbolCOFF>(S)->setExternal(true);
354 }
355 
finalizeCGProfile()356 void MCWinCOFFStreamer::finalizeCGProfile() {
357   for (MCAssembler::CGProfileEntry &E : getAssembler().CGProfile) {
358     finalizeCGProfileEntry(E.From);
359     finalizeCGProfileEntry(E.To);
360   }
361 }
362 
finishImpl()363 void MCWinCOFFStreamer::finishImpl() {
364   finalizeCGProfile();
365 
366   MCObjectStreamer::finishImpl();
367 }
368 
Error(const Twine & Msg) const369 void MCWinCOFFStreamer::Error(const Twine &Msg) const {
370   getContext().reportError(SMLoc(), Msg);
371 }
372