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