LLVM 24.0.0git
GOFFObjectWriter.cpp
Go to the documentation of this file.
1//===- lib/MC/GOFFObjectWriter.cpp - GOFF File Writer ---------------------===//
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 implements GOFF object file writer information.
10//
11//===----------------------------------------------------------------------===//
12
15#include "llvm/MC/MCAssembler.h"
21#include "llvm/MC/MCValue.h"
23#include "llvm/Support/Debug.h"
24#include "llvm/Support/Endian.h"
26
27using namespace llvm;
28
29#define DEBUG_TYPE "goff-writer"
30
31namespace {
32// Common flag values on records.
33
34// Flag: This record is continued.
35constexpr uint8_t RecContinued = GOFF::Flags(7, 1, 1);
36
37// Flag: This record is a continuation.
38constexpr uint8_t RecContinuation = GOFF::Flags(6, 1, 1);
39
40// The GOFFOstream is responsible to write the data into the fixed physical
41// records of the format. A user of this class announces the begin of a new
42// logical record. While writing the payload, the physical records are created
43// for the data. Possible fill bytes at the end of a physical record are written
44// automatically. In principle, the GOFFOstream is agnostic of the endianness of
45// the payload. However, it also supports writing data in big endian byte order.
46//
47// The physical records use the flag field to indicate if the there is a
48// successor and predecessor record. To be able to set these flags while
49// writing, the basic implementation idea is to always buffer the last seen
50// physical record.
51class GOFFOstream {
52 /// The underlying raw_pwrite_stream.
54
55 /// The number of logical records emitted so far.
56 uint32_t LogicalRecords = 0;
57
58 /// The number of physical records emitted so far.
59 uint32_t PhysicalRecords = 0;
60
61 /// The size of the buffer. Same as the payload size of a physical record.
62 static constexpr uint8_t BufferSize = GOFF::PayloadLength;
63
64 /// Current position in buffer.
65 char *BufferPtr = Buffer;
66
67 /// Static allocated buffer for the stream.
68 char Buffer[BufferSize];
69
70 /// The type of the current logical record, and the flags (aka continued and
71 /// continuation indicators) for the previous (physical) record.
72 uint8_t TypeAndFlags = 0;
73
74public:
75 GOFFOstream(raw_pwrite_stream &OS);
76 ~GOFFOstream();
77
78 raw_pwrite_stream &getOS() { return OS; }
79 size_t getWrittenSize() const { return PhysicalRecords * GOFF::RecordLength; }
80 uint32_t getNumLogicalRecords() { return LogicalRecords; }
81
82 /// Write the specified bytes.
83 void write(const char *Ptr, size_t Size);
84
85 /// Write zeroes, up to a maximum of 16 bytes.
86 void write_zeros(unsigned NumZeros);
87
88 /// Support for endian-specific data.
89 template <typename value_type> void writebe(value_type Value) {
90 Value =
92 write((const char *)&Value, sizeof(value_type));
93 }
94
95 /// Begin a new logical record. Implies finalizing the previous record.
96 void newRecord(GOFF::RecordType Type);
97
98 /// Ends a logical record.
99 void finalizeRecord();
100
101private:
102 /// Updates the continued/continuation flags, and writes the record prefix of
103 /// a physical record.
104 void updateFlagsAndWritePrefix(bool IsContinued);
105
106 /// Returns the remaining size in the buffer.
107 size_t getRemainingSize();
108};
109} // namespace
110
111GOFFOstream::GOFFOstream(raw_pwrite_stream &OS) : OS(OS) {}
112
113GOFFOstream::~GOFFOstream() { finalizeRecord(); }
114
115void GOFFOstream::updateFlagsAndWritePrefix(bool IsContinued) {
116 // Update the flags based on the previous state and the flag IsContinued.
117 if (TypeAndFlags & RecContinued)
118 TypeAndFlags |= RecContinuation;
119 if (IsContinued)
120 TypeAndFlags |= RecContinued;
121 else
122 TypeAndFlags &= ~RecContinued;
123
124 OS << static_cast<unsigned char>(GOFF::PTVPrefix) // Record Type
125 << static_cast<unsigned char>(TypeAndFlags) // Continuation
126 << static_cast<unsigned char>(0); // Version
127
128 ++PhysicalRecords;
129}
130
131size_t GOFFOstream::getRemainingSize() {
132 return size_t(&Buffer[BufferSize] - BufferPtr);
133}
134
135void GOFFOstream::write(const char *Ptr, size_t Size) {
136 size_t RemainingSize = getRemainingSize();
137
138 // Data fits into the buffer.
139 if (LLVM_LIKELY(Size <= RemainingSize)) {
140 memcpy(BufferPtr, Ptr, Size);
141 BufferPtr += Size;
142 return;
143 }
144
145 // Otherwise the buffer is partially filled or full, and data does not fit
146 // into it.
147 updateFlagsAndWritePrefix(/*IsContinued=*/true);
148 OS.write(Buffer, size_t(BufferPtr - Buffer));
149 if (RemainingSize > 0) {
150 OS.write(Ptr, RemainingSize);
151 Ptr += RemainingSize;
152 Size -= RemainingSize;
153 }
154
155 while (Size > BufferSize) {
156 updateFlagsAndWritePrefix(/*IsContinued=*/true);
157 OS.write(Ptr, BufferSize);
158 Ptr += BufferSize;
159 Size -= BufferSize;
160 }
161
162 // The remaining bytes fit into the buffer.
163 memcpy(Buffer, Ptr, Size);
164 BufferPtr = &Buffer[Size];
165}
166
167void GOFFOstream::write_zeros(unsigned NumZeros) {
168 assert(NumZeros <= 16 && "Range for zeros too large");
169
170 // Handle the common case first: all fits in the buffer.
171 size_t RemainingSize = getRemainingSize();
172 if (LLVM_LIKELY(RemainingSize >= NumZeros)) {
173 memset(BufferPtr, 0, NumZeros);
174 BufferPtr += NumZeros;
175 return;
176 }
177
178 // Otherwise some field value is cleared.
179 static char Zeros[16] = {
180 0,
181 };
182 write(Zeros, NumZeros);
183}
184
185void GOFFOstream::newRecord(GOFF::RecordType Type) {
186 finalizeRecord();
187 TypeAndFlags = Type << 4;
188 ++LogicalRecords;
189}
190
191void GOFFOstream::finalizeRecord() {
192 if (Buffer == BufferPtr)
193 return;
194 updateFlagsAndWritePrefix(/*IsContinued=*/false);
195 OS.write(Buffer, size_t(BufferPtr - Buffer));
196 OS.write_zeros(getRemainingSize());
197 BufferPtr = Buffer;
198}
199
200namespace {
201// A GOFFSymbol holds all the data required for writing an ESD record.
202class GOFFSymbol {
203public:
204 std::string Name;
205 uint32_t EsdId;
206 uint32_t ParentEsdId;
207 uint64_t Offset = 0; // Offset of the symbol into the section. LD only.
208 // Offset is only 32 bit, the larger type is used to
209 // enable error checking.
212
213 GOFF::BehavioralAttributes BehavAttrs;
214 GOFF::SymbolFlags SymbolFlags;
215 uint32_t SortKey = 0;
216 uint32_t SectionLength = 0;
217 uint32_t ADAEsdId = 0;
218 uint32_t EASectionEDEsdId = 0;
219 uint32_t EASectionOffset = 0;
220 uint8_t FillByteValue = 0;
221
222 GOFFSymbol() : EsdId(0), ParentEsdId(0) {}
223
224 GOFFSymbol(StringRef Name, uint32_t EsdID, const GOFF::SDAttr &Attr)
225 : Name(Name.data(), Name.size()), EsdId(EsdID), ParentEsdId(0),
227 BehavAttrs.setTaskingBehavior(Attr.TaskingBehavior);
228 BehavAttrs.setBindingScope(Attr.BindingScope);
229 }
230
231 GOFFSymbol(StringRef Name, uint32_t EsdID, uint32_t ParentEsdID,
232 const GOFF::EDAttr &Attr, GOFF::ESDAlignment Alignment)
233 : Name(Name.data(), Name.size()), EsdId(EsdID), ParentEsdId(ParentEsdID),
235 this->NameSpace = Attr.NameSpace;
236 // We always set a fill byte value.
237 this->FillByteValue = Attr.FillByteValue;
238 SymbolFlags.setFillBytePresence(1);
239 SymbolFlags.setReservedQwords(Attr.ReservedQwords);
240 // TODO Do we need/should set the "mangled" flag?
241 BehavAttrs.setReadOnly(Attr.IsReadOnly);
242 BehavAttrs.setRmode(Attr.Rmode);
243 BehavAttrs.setTextStyle(Attr.TextStyle);
244 BehavAttrs.setBindingAlgorithm(Attr.BindAlgorithm);
245 BehavAttrs.setLoadingBehavior(Attr.LoadBehavior);
246 BehavAttrs.setAlignment(Alignment);
247 }
248
249 GOFFSymbol(StringRef Name, uint32_t EsdID, uint32_t ParentEsdID,
250 GOFF::ESDNameSpaceId NameSpace, const GOFF::LDAttr &Attr)
251 : Name(Name.data(), Name.size()), EsdId(EsdID), ParentEsdId(ParentEsdID),
252 SymbolType(GOFF::ESD_ST_LabelDefinition), NameSpace(NameSpace) {
253 SymbolFlags.setRenameable(Attr.IsRenamable);
254 BehavAttrs.setExecutable(Attr.Executable);
255 BehavAttrs.setBindingStrength(Attr.BindingStrength);
256 BehavAttrs.setLinkageType(Attr.Linkage);
257 BehavAttrs.setAmode(Attr.Amode);
258 BehavAttrs.setBindingScope(Attr.BindingScope);
259 }
260
261 GOFFSymbol(StringRef Name, uint32_t EsdID, uint32_t ParentEsdID,
262 const GOFF::EDAttr &EDAttr, GOFF::ESDAlignment Alignment,
263 const GOFF::PRAttr &Attr)
264 : Name(Name.data(), Name.size()), EsdId(EsdID), ParentEsdId(ParentEsdID),
265 SymbolType(GOFF::ESD_ST_PartReference), NameSpace(EDAttr.NameSpace) {
266 SymbolFlags.setRenameable(Attr.IsRenamable);
267 BehavAttrs.setExecutable(Attr.Executable);
268 BehavAttrs.setBindingStrength(Attr.BindingStrength);
269 BehavAttrs.setLinkageType(Attr.Linkage);
270 // See
271 // https://www.ibm.com/docs/en/hla-and-tf/1.6.0?topic=statements-amode-instruction#amode__modcomb,
272 // Table 2. HLASM sets the AMODE based on the RMODE if no AMODE is given.
273 GOFF::ESDAmode Amode;
274 switch (EDAttr.Rmode) {
275 case GOFF::ESD_RMODE_24:
276 Amode = GOFF::ESD_AMODE_24;
277 break;
278 case GOFF::ESD_RMODE_31:
279 Amode = GOFF::ESD_AMODE_31;
280 break;
281 case GOFF::ESD_RMODE_64:
282 Amode = GOFF::ESD_AMODE_64;
283 break;
284 default:
285 Amode = GOFF::ESD_AMODE_None;
286 break;
287 }
288 BehavAttrs.setAmode(Amode);
289 BehavAttrs.setBindingScope(Attr.BindingScope);
290 BehavAttrs.setAlignment(Alignment);
291 }
292
293 GOFFSymbol(StringRef Name, uint32_t EsdID, uint32_t ParentEsdID,
294 const GOFF::ERAttr &Attr)
295 : Name(Name.data(), Name.size()), EsdId(EsdID), ParentEsdId(ParentEsdID),
297 NameSpace(GOFF::ESD_NS_NormalName) {
298 BehavAttrs.setExecutable(Attr.Executable);
299 BehavAttrs.setBindingStrength(Attr.BindingStrength);
300 BehavAttrs.setLinkageType(Attr.Linkage);
301 BehavAttrs.setAmode(Attr.Amode);
302 BehavAttrs.setBindingScope(Attr.BindingScope);
303 BehavAttrs.setIndirectReference(Attr.IsIndirectReference);
304 }
305};
306
307class GOFFWriter {
308 GOFFOstream OS;
309 MCAssembler &Asm;
310 MCSectionGOFF *RootSD;
311
312 /// Saved relocation data collected in recordRelocations().
313 std::vector<GOFFRelocationEntry> &Relocations;
314
315public:
316 enum DwoMode {
317 AllSections,
318 NonDwoOnly,
319 DwoOnly,
320 };
321
322private:
323 const DwoMode Mode;
324
325 void writeHeader();
326 void writeSymbol(const GOFFSymbol &Symbol);
327 void writeText(const MCSectionGOFF *MC);
328 void writeRelocations();
329 void writeEnd();
330
331 void defineSectionSymbols(const MCSectionGOFF &Section);
332 void defineLabel(const MCSymbolGOFF &Symbol);
333 void defineExtern(const MCSymbolGOFF &Symbol);
334 void defineSymbols();
335
336public:
337 GOFFWriter(raw_pwrite_stream &OS, MCAssembler &Asm, MCSectionGOFF *RootSD,
338 std::vector<GOFFRelocationEntry> &Relocations, DwoMode Mode);
339 uint64_t writeObject();
340};
341} // namespace
342
343GOFFWriter::GOFFWriter(raw_pwrite_stream &OS, MCAssembler &Asm,
344 MCSectionGOFF *RootSD,
345 std::vector<GOFFRelocationEntry> &Relocations,
346 DwoMode Mode)
347 : OS(OS), Asm(Asm), RootSD(RootSD), Relocations(Relocations), Mode(Mode) {}
348
349namespace {
350bool isDwoSection(const MCSection &Section) {
351 StringRef Name = Section.getName();
352 return (Name.ends_with(".dwo") && Name.starts_with(".debug_")) ||
353 (Name.ends_with("_DWO") && Name.starts_with("D_"));
354}
355
356bool isSectionToSkip(const MCSection &Section, GOFFWriter::DwoMode Mode) {
357 if (Mode == GOFFWriter::DwoOnly) {
358 if (!isDwoSection(Section))
359 return true;
360 } else if (Mode == GOFFWriter::NonDwoOnly) {
361 if (isDwoSection(Section))
362 return true;
363 }
364 return false;
365}
366} // namespace
367
368void GOFFWriter::defineSectionSymbols(const MCSectionGOFF &Section) {
369 if (isSectionToSkip(Section, Mode))
370 return;
371
372 if (Section.isSD()) {
373 GOFFSymbol SD(Section.getExternalName(), Section.getOrdinal(),
374 Section.getSDAttributes());
375 writeSymbol(SD);
376 }
377
378 if (Section.isED()) {
379 GOFFSymbol ED(Section.getExternalName(), Section.getOrdinal(),
380 Section.getParent()->getOrdinal(), Section.getEDAttributes(),
381 Section.getEDAlignment());
382 ED.SectionLength = Asm.getSectionAddressSize(Section);
383 writeSymbol(ED);
384 }
385
386 if (Section.isPR()) {
387 MCSectionGOFF *Parent = Section.getParent();
388 GOFFSymbol PR(Section.getExternalName(), Section.getOrdinal(),
389 Parent->getOrdinal(), Parent->getEDAttributes(),
390 Parent->getEDAlignment(), Section.getPRAttributes());
391 PR.SectionLength = Asm.getSectionAddressSize(Section);
392 if (Section.requiresNonZeroLength()) {
393 // We cannot have a zero-length section for data. If we do,
394 // artificially inflate it. Use 2 bytes to avoid odd alignments. Note:
395 // if this is ever changed, you will need to update the code in
396 // SystemZAsmPrinter::emitCEEMAIN and SystemZAsmPrinter::emitCELQMAIN to
397 // generate -1 if there is no ADA
398 if (!PR.SectionLength)
399 PR.SectionLength = 2;
400 }
401 writeSymbol(PR);
402 }
403}
404
405void GOFFWriter::defineLabel(const MCSymbolGOFF &Symbol) {
406 MCSectionGOFF &Section = static_cast<MCSectionGOFF &>(Symbol.getSection());
407 GOFFSymbol LD(Symbol.getExternalName(), Symbol.getIndex(),
408 Section.getOrdinal(), Section.getEDAttributes().NameSpace,
409 GOFF::LDAttr{false, Symbol.getCodeData(),
410 Symbol.getBindingStrength(), Symbol.getLinkage(),
411 GOFF::ESD_AMODE_64, Symbol.getBindingScope()});
412 if (Symbol.getADA())
413 LD.ADAEsdId = Symbol.getADA()->getOrdinal();
414 LD.Offset = Asm.getSymbolOffset(Symbol);
415 writeSymbol(LD);
416}
417
418void GOFFWriter::defineExtern(const MCSymbolGOFF &Symbol) {
419 if (Symbol.getCodeData() == GOFF::ESD_EXE_DATA) {
420 MCSectionGOFF *ED = Symbol.getADA()->getParent();
421 GOFFSymbol PR(Symbol.getExternalName(), Symbol.getIndex(), ED->getOrdinal(),
422 ED->getEDAttributes(), ED->getEDAlignment(),
423 GOFF::PRAttr{/*IsRenamable*/ false, Symbol.getCodeData(),
424 Symbol.getBindingStrength(), Symbol.getLinkage(),
425 Symbol.getBindingScope(), 0});
426 writeSymbol(PR);
427 } else {
428 GOFFSymbol ER(Symbol.getExternalName(), Symbol.getIndex(),
429 RootSD->getOrdinal(),
430 GOFF::ERAttr{Symbol.isIndirect(), Symbol.getCodeData(),
431 Symbol.getBindingStrength(), Symbol.getLinkage(),
432 GOFF::ESD_AMODE_64, Symbol.getBindingScope()});
433 writeSymbol(ER);
434 }
435}
436
437void GOFFWriter::defineSymbols() {
438 unsigned Ordinal = 0;
439 // Process all sections.
440 for (MCSection &S : Asm) {
441 auto &Section = static_cast<MCSectionGOFF &>(S);
442 Section.setOrdinal(++Ordinal);
443 defineSectionSymbols(Section);
444 }
445
446 // Process all symbols
447 for (const MCSymbol &Sym : Asm.symbols()) {
448 if (Sym.isTemporary())
449 continue;
450 auto &Symbol = static_cast<const MCSymbolGOFF &>(Sym);
451 if (!Symbol.isDefined()) {
452 if (Mode != DwoOnly) {
453 Symbol.setIndex(++Ordinal);
454 defineExtern(Symbol);
455 }
456 } else {
457 if (isSectionToSkip(Symbol.getSection(), Mode))
458 continue;
459 if (Symbol.isInEDSection()) {
460 Symbol.setIndex(++Ordinal);
461 defineLabel(Symbol);
462 } else {
463 // Symbol is in PR section, the symbol refers to the section.
464 Symbol.setIndex(Symbol.getSection().getOrdinal());
465 }
466 }
467 }
468}
469
470void GOFFWriter::writeHeader() {
471 OS.newRecord(GOFF::RT_HDR);
472 OS.write_zeros(1); // Reserved
473 OS.writebe<uint32_t>(0); // Target Hardware Environment
474 OS.writebe<uint32_t>(0); // Target Operating System Environment
475 OS.write_zeros(2); // Reserved
476 OS.writebe<uint16_t>(0); // CCSID
477 OS.write_zeros(16); // Character Set name
478 OS.write_zeros(16); // Language Product Identifier
479 OS.writebe<uint32_t>(1); // Architecture Level
480 OS.writebe<uint16_t>(0); // Module Properties Length
481 OS.write_zeros(6); // Reserved
482}
483
484void GOFFWriter::writeSymbol(const GOFFSymbol &Symbol) {
485 if (Symbol.Offset >= (((uint64_t)1) << 31))
486 report_fatal_error("ESD offset out of range");
487
488 // All symbol names are in EBCDIC.
489 SmallString<256> Name;
491
492 // Check length here since this number is technically signed but we need uint
493 // for writing to records.
494 if (Name.size() >= GOFF::MaxDataLength)
495 report_fatal_error("Symbol max name length exceeded");
496 uint16_t NameLength = Name.size();
497
498 OS.newRecord(GOFF::RT_ESD);
499 OS.writebe<uint8_t>(Symbol.SymbolType); // Symbol Type
500 OS.writebe<uint32_t>(Symbol.EsdId); // ESDID
501 OS.writebe<uint32_t>(Symbol.ParentEsdId); // Parent or Owning ESDID
502 OS.writebe<uint32_t>(0); // Reserved
503 OS.writebe<uint32_t>(
504 static_cast<uint32_t>(Symbol.Offset)); // Offset or Address
505 OS.writebe<uint32_t>(0); // Reserved
506 OS.writebe<uint32_t>(Symbol.SectionLength); // Length
507 OS.writebe<uint32_t>(Symbol.EASectionEDEsdId); // Extended Attribute ESDID
508 OS.writebe<uint32_t>(Symbol.EASectionOffset); // Extended Attribute Offset
509 OS.writebe<uint32_t>(0); // Reserved
510 OS.writebe<uint8_t>(Symbol.NameSpace); // Name Space ID
511 OS.writebe<uint8_t>(Symbol.SymbolFlags); // Flags
512 OS.writebe<uint8_t>(Symbol.FillByteValue); // Fill-Byte Value
513 OS.writebe<uint8_t>(0); // Reserved
514 OS.writebe<uint32_t>(Symbol.ADAEsdId); // ADA ESDID
515 OS.writebe<uint32_t>(Symbol.SortKey); // Sort Priority
516 OS.writebe<uint64_t>(0); // Reserved
517 for (auto F : Symbol.BehavAttrs.Attr)
518 OS.writebe<uint8_t>(F); // Behavioral Attributes
519 OS.writebe<uint16_t>(NameLength); // Name Length
520 OS.write(Name.data(), NameLength); // Name
521}
522
523namespace {
524/// Adapter stream to write a text section.
525class TextStream : public raw_ostream {
526 /// The underlying GOFFOstream.
527 GOFFOstream &OS;
528
529 /// The buffer size is the maximum number of bytes in a TXT section.
530 static constexpr size_t BufferSize = GOFF::MaxDataLength;
531
532 /// Static allocated buffer for the stream, used by the raw_ostream class. The
533 /// buffer is sized to hold the payload of a logical TXT record.
534 char Buffer[BufferSize];
535
536 /// The offset for the next TXT record. This is equal to the number of bytes
537 /// written.
538 size_t Offset;
539
540 /// The Esdid of the GOFF section.
541 const uint32_t EsdId;
542
543 /// The record style.
544 const GOFF::ESDTextStyle RecordStyle;
545
546 /// See raw_ostream::write_impl.
547 void write_impl(const char *Ptr, size_t Size) override;
548
549 uint64_t current_pos() const override { return Offset; }
550
551public:
552 explicit TextStream(GOFFOstream &OS, uint32_t EsdId,
553 GOFF::ESDTextStyle RecordStyle)
554 : OS(OS), Offset(0), EsdId(EsdId), RecordStyle(RecordStyle) {
555 SetBuffer(Buffer, sizeof(Buffer));
556 }
557
558 ~TextStream() override { flush(); }
559};
560} // namespace
561
562void TextStream::write_impl(const char *Ptr, size_t Size) {
563 size_t WrittenLength = 0;
564
565 // We only have signed 32bits of offset.
566 if (Offset + Size > std::numeric_limits<int32_t>::max())
567 report_fatal_error("TXT section too large");
568
569 while (WrittenLength < Size) {
570 size_t ToWriteLength =
571 std::min(Size - WrittenLength, size_t(GOFF::MaxDataLength));
572
573 OS.newRecord(GOFF::RT_TXT);
574 OS.writebe<uint8_t>(GOFF::Flags(4, 4, RecordStyle)); // Text Record Style
575 OS.writebe<uint32_t>(EsdId); // Element ESDID
576 OS.writebe<uint32_t>(0); // Reserved
577 OS.writebe<uint32_t>(static_cast<uint32_t>(Offset)); // Offset
578 OS.writebe<uint32_t>(0); // Text Field True Length
579 OS.writebe<uint16_t>(0); // Text Encoding
580 OS.writebe<uint16_t>(ToWriteLength); // Data Length
581 OS.write(Ptr + WrittenLength, ToWriteLength); // Data
582
583 WrittenLength += ToWriteLength;
584 Offset += ToWriteLength;
585 }
586}
587
588void GOFFWriter::writeText(const MCSectionGOFF *Section) {
589 // A BSS section contains only zeros, no need to write this.
590 if (Section->isBSS())
591 return;
592
593 TextStream S(OS, Section->getOrdinal(), Section->getTextStyle());
594 Asm.writeSectionData(S, Section);
595}
596
597namespace {
598// RelocDataItemBuffer provides a static buffer for relocation data items.
599class RelocDataItemBuffer {
600 char Buffer[GOFF::MaxDataLength];
601 char *Ptr;
602
603public:
604 RelocDataItemBuffer() : Ptr(Buffer) {}
605 const char *data() { return Buffer; }
606 size_t size() { return Ptr - Buffer; }
607 void reset() { Ptr = Buffer; }
608 bool fits(size_t S) { return size() + S < GOFF::MaxDataLength; }
609 template <typename T> void writebe(T Val) {
610 assert(fits(sizeof(T)) && "Out-of-bounds write");
612 Ptr += sizeof(T);
613 }
614};
615} // namespace
616
617void GOFFWriter::writeRelocations() {
618 // Set the IDs in the relocation entries.
619 for (auto &RelocEntry : Relocations) {
620 auto GetRptr = [](const MCSymbolGOFF *Sym) -> uint32_t {
621 if (Sym->isTemporary())
622 return static_cast<MCSectionGOFF &>(Sym->getSection()).getOrdinal();
623 return Sym->getIndex();
624 };
625
626 RelocEntry.PEsdId = RelocEntry.Pptr->getOrdinal();
627 RelocEntry.REsdId = GetRptr(RelocEntry.Rptr);
628 }
629
630 // Sort relocation data items by the P pointer to save space.
631 std::sort(
632 Relocations.begin(), Relocations.end(),
633 [](const GOFFRelocationEntry &Left, const GOFFRelocationEntry &Right) {
634 return std::tie(Left.PEsdId, Left.REsdId, Left.POffset) <
635 std::tie(Right.PEsdId, Right.REsdId, Right.POffset);
636 });
637
638 // Construct the compressed relocation data items, and write them out.
639 RelocDataItemBuffer Buffer;
640 for (auto I = Relocations.begin(), E = Relocations.end(); I != E;) {
641 Buffer.reset();
642
643 uint32_t PrevResdId = -1;
644 uint32_t PrevPesdId = -1;
645 uint64_t PrevPOffset = -1;
646 for (; I != E; ++I) {
647 const GOFFRelocationEntry &Rel = *I;
648
649 bool SameREsdId = (Rel.REsdId == PrevResdId);
650 bool SamePEsdId = (Rel.PEsdId == PrevPesdId);
651 bool SamePOffset = (Rel.POffset == PrevPOffset);
652 bool EightByteOffset = ((Rel.POffset >> 32) & 0xffffffff);
653
654 // Calculate size of relocation data item, and check if it still fits into
655 // the record.
656 size_t ItemSize = 8; // Smallest size of a relocation data item.
657 if (!SameREsdId)
658 ItemSize += 4;
659 if (!SamePEsdId)
660 ItemSize += 4;
661 if (!SamePOffset)
662 ItemSize += (EightByteOffset ? 8 : 4);
663 if (!Buffer.fits(ItemSize))
664 break;
665
666 GOFF::Flags RelocFlags[6];
667 RelocFlags[0].set(0, 1, SameREsdId);
668 RelocFlags[0].set(1, 1, SamePEsdId);
669 RelocFlags[0].set(2, 1, SamePOffset);
670 RelocFlags[0].set(6, 1, EightByteOffset);
671
672 RelocFlags[1].set(0, 4, Rel.ReferenceType);
673 RelocFlags[1].set(4, 4, Rel.ReferentType);
674
675 RelocFlags[2].set(0, 7, Rel.Action);
676 RelocFlags[2].set(7, 1, Rel.FetchStore);
677
678 RelocFlags[4].set(0, 8, Rel.TargetLength);
679
680 for (auto F : RelocFlags)
681 Buffer.writebe<uint8_t>(F);
682 Buffer.writebe<uint16_t>(0); // Reserved.
683 if (!SameREsdId)
684 Buffer.writebe<uint32_t>(Rel.REsdId);
685 if (!SamePEsdId)
686 Buffer.writebe<uint32_t>(Rel.PEsdId);
687 if (!SamePOffset) {
688 if (EightByteOffset)
689 Buffer.writebe<uint64_t>(Rel.POffset);
690 else
691 Buffer.writebe<uint32_t>(Rel.POffset);
692 }
693
694 PrevResdId = Rel.REsdId;
695 PrevPesdId = Rel.PEsdId;
696 PrevPOffset = Rel.POffset;
697 }
698
699 OS.newRecord(GOFF::RT_RLD);
700 OS.writebe<uint8_t>(0); // Reserved.
701 OS.writebe<uint16_t>(Buffer.size()); // Length (of the relocation data).
702 OS.write(Buffer.data(), Buffer.size()); // Relocation Directory Data Items.
703 }
704}
705
706void GOFFWriter::writeEnd() {
707 uint8_t F = GOFF::END_EPR_None;
708 uint8_t AMODE = 0;
709 uint32_t ESDID = 0;
710
711 // TODO Set Flags/AMODE/ESDID for entry point.
712
713 OS.newRecord(GOFF::RT_END);
714 OS.writebe<uint8_t>(GOFF::Flags(6, 2, F)); // Indicator flags
715 OS.writebe<uint8_t>(AMODE); // AMODE
716 OS.write_zeros(3); // Reserved
717 // The record count is the number of logical records. In principle, this value
718 // is available as OS.logicalRecords(). However, some tools rely on this field
719 // being zero.
720 OS.writebe<uint32_t>(0); // Record Count
721 OS.writebe<uint32_t>(ESDID); // ESDID (of entry point)
722}
723
724uint64_t GOFFWriter::writeObject() {
725 writeHeader();
726
727 defineSymbols();
728
729 for (const MCSection &Section : Asm)
730 writeText(static_cast<const MCSectionGOFF *>(&Section));
731
732 // Do not write relocations into the dwo file.
733 if (Mode != GOFFWriter::DwoOnly)
734 writeRelocations();
735
736 writeEnd();
737
738 // Make sure all records are written.
739 OS.finalizeRecord();
740
741 LLVM_DEBUG(dbgs() << "Wrote " << OS.getNumLogicalRecords()
742 << " logical records.");
743
744 return OS.getWrittenSize();
745}
746
748 std::unique_ptr<MCGOFFObjectTargetWriter> MOTW, raw_pwrite_stream &OS)
749 : TargetObjectWriter(std::move(MOTW)), OS(OS) {}
750
752 std::unique_ptr<MCGOFFObjectTargetWriter> MOTW, raw_pwrite_stream &OS,
753 raw_pwrite_stream &DwoOS)
754 : TargetObjectWriter(std::move(MOTW)), OS(OS), DwoOS(&DwoOS) {}
755
757
759 Relocations.clear();
760 RootSD = nullptr;
762}
763
765 const MCFixup &Fixup, MCValue Target,
766 uint64_t &FixedValue) {
767 const MCFixupKindInfo &FKI =
768 Asm->getBackend().getFixupKindInfo(Fixup.getKind());
769 const uint32_t Length = FKI.TargetSize / 8;
770 assert(FKI.TargetSize % 8 == 0 && "Target Size not multiple of 8");
771 const uint64_t FixupOffset = Asm->getFragmentOffset(F) + Fixup.getOffset();
772
773 unsigned RelocType = TargetObjectWriter->getRelocType(Target, Fixup);
774
775 const MCSectionGOFF *PSection = static_cast<MCSectionGOFF *>(F.getParent());
776 const auto &A = *static_cast<const MCSymbolGOFF *>(Target.getAddSym());
777 const MCSymbolGOFF *B = static_cast<const MCSymbolGOFF *>(Target.getSubSym());
779 if (A.isUndefined()) {
780 Asm->reportError(
781 Fixup.getLoc(),
782 Twine("symbol ")
783 .concat(A.getExternalName())
784 .concat(" must be defined for a relative immediate relocation"));
785 return;
786 }
787 if (&A.getSection() != PSection) {
788 MCSectionGOFF &GOFFSection = static_cast<MCSectionGOFF &>(A.getSection());
789 Asm->reportError(Fixup.getLoc(),
790 Twine("relative immediate relocation section mismatch: ")
791 .concat(GOFFSection.getExternalName())
792 .concat(" of symbol ")
793 .concat(A.getExternalName())
794 .concat(" <-> ")
795 .concat(PSection->getExternalName()));
796 return;
797 }
798 if (B) {
799 Asm->reportError(
800 Fixup.getLoc(),
801 Twine("subtractive symbol ")
802 .concat(B->getExternalName())
803 .concat(" not supported for a relative immediate relocation"));
804 return;
805 }
806 FixedValue = Asm->getSymbolOffset(A) - FixupOffset + Target.getConstant();
807 return;
808 }
809 FixedValue = Target.getConstant();
810
811 // The symbol only has a section-relative offset if it is a temporary symbol.
812 FixedValue += A.isTemporary() ? Asm->getSymbolOffset(A) : 0;
813 A.setUsedInReloc();
814 if (B) {
815 FixedValue -= B->isTemporary() ? Asm->getSymbolOffset(*B) : 0;
816 B->setUsedInReloc();
817 }
818
819 // UseQCon causes class offsets versus absolute addresses to be used. This
820 // is analogous to using QCONs in older OBJ object file format.
821 bool UseQCon = RelocType == MCGOFFObjectTargetWriter::Reloc_Type_QCon;
822
823 GOFF::RLDFetchStore FetchStore =
828 assert((FetchStore == GOFF::RLDFetchStore::RLD_FS_Fetch || B == nullptr) &&
829 "No dependent relocations expected");
830
832 enum GOFF::RLDReferentType ReferentType = GOFF::RLD_RO_Label;
833 if (UseQCon) {
835 ReferentType = GOFF::RLD_RO_Class;
836 }
839
840 auto DumpReloc = [&PSection, &ReferenceType, &FixupOffset,
841 &FixedValue](const char *N, const MCSymbolGOFF *Sym) {
842 const char *Con;
843 switch (ReferenceType) {
845 Con = "ACon";
846 break;
848 Con = "QCon";
849 break;
851 Con = "VCon";
852 break;
853 default:
854 Con = "(unknown)";
855 }
856 dbgs() << "Reloc " << N << ": " << Con
857 << " Rptr: " << Sym->getExternalName()
858 << " Pptr: " << PSection->getExternalName()
859 << " Offset: " << FixupOffset << " Fixed Imm: " << FixedValue
860 << "\n";
861 };
862 (void)DumpReloc;
863
864 // Save relocation data for later writing.
865 LLVM_DEBUG(DumpReloc("A", &A));
866 Relocations.emplace_back(PSection, &A, ReferenceType, ReferentType,
867 GOFF::RLD_ACT_Add, FetchStore, FixupOffset, Length);
868 if (B) {
869 LLVM_DEBUG(DumpReloc("B", B));
870 Relocations.emplace_back(
871 PSection, B, ReferenceType, ReferentType, GOFF::RLD_ACT_Subtract,
873 }
874}
875
877 uint64_t Size = 0;
878 if (DwoOS)
879 Size += GOFFWriter(*DwoOS, *Asm, RootSD, Relocations, GOFFWriter::DwoOnly)
880 .writeObject();
881 Size += GOFFWriter(OS, *Asm, RootSD, Relocations,
882 DwoOS ? GOFFWriter::NonDwoOnly : GOFFWriter::AllSections)
883 .writeObject();
884 return Size;
885}
886
887std::unique_ptr<MCObjectWriter>
888llvm::createGOFFObjectWriter(std::unique_ptr<MCGOFFObjectTargetWriter> MOTW,
889 raw_pwrite_stream &OS) {
890 return std::make_unique<GOFFObjectWriter>(std::move(MOTW), OS);
891}
892
893std::unique_ptr<MCObjectWriter>
894llvm::createGOFFObjectWriter(std::unique_ptr<MCGOFFObjectTargetWriter> MOTW,
896 return std::make_unique<GOFFObjectWriter>(std::move(MOTW), OS, DwoOS);
897}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_LIKELY(EXPR)
Definition Compiler.h:347
This file provides utility functions for converting between EBCDIC-1047 and UTF-8.
This file declares the MCSectionGOFF class, which contains all of the necessary machine code sections...
This file contains the MCSymbolGOFF class.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
static Split data
#define LLVM_DEBUG(...)
Definition Debug.h:119
static bool isDwoSection(const MCSection &Sec)
GOFFObjectWriter(std::unique_ptr< MCGOFFObjectTargetWriter > MOTW, raw_pwrite_stream &OS)
void reset() override
lifetime management
uint64_t writeObject() override
Write the object file and returns the number of bytes written.
~GOFFObjectWriter() override
void recordRelocation(const MCFragment &F, const MCFixup &Fixup, MCValue Target, uint64_t &FixedValue) override
Record a relocation entry.
constexpr void set(uint8_t BitIndex, uint8_t Length, T NewValue)
Definition GOFF.h:210
LLVM_ABI bool getSymbolOffset(const MCSymbol &S, uint64_t &Val) const
LLVM_ABI uint64_t getSectionAddressSize(const MCSection &Sec) const
Encode information on a single operation to perform on a byte sequence (e.g., an encoded instruction)...
Definition MCFixup.h:65
virtual void reset()
lifetime management
GOFF::EDAttr getEDAttributes() const
StringRef getExternalName() const
GOFF::ESDAlignment getEDAlignment() const
Instances of this class represent a uniqued identifier for a section in the current translation unit.
Definition MCSection.h:580
unsigned getOrdinal() const
Definition MCSection.h:673
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Target - Wrapper for Target specific information.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
Twine concat(const Twine &Suffix) const
Definition Twine.h:497
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM Value Representation.
Definition Value.h:75
raw_ostream & write_zeros(unsigned NumZeros)
write_zeros - Insert 'NumZeros' nulls.
raw_ostream & write(unsigned char C)
An abstract base class for streams implementations that also support a pwrite operation.
LLVM_ABI std::error_code convertToEBCDIC(StringRef Source, SmallVectorImpl< char > &Result)
Converts UTF-8 text containing only code points in the range U+0000 to U+00FF to EBCDIC-1047.
LLVM_ABI void writeHeader(support::endian::Writer &W, bool Is64Bit, uint8_t OSABI, uint8_t ABIVersion, uint16_t EMachine, uint32_t EFlags, uint64_t SHOff, uint16_t SHNum, uint16_t SHStrNdx)
Write an ELF file header (Elf32_Ehdr or Elf64_Ehdr) for an ET_REL object.
Definition ELFWriter.cpp:21
RecordType
Definition GOFF.h:44
@ RT_RLD
Definition GOFF.h:47
@ RT_TXT
Definition GOFF.h:46
@ RT_ESD
Definition GOFF.h:45
@ RT_HDR
Definition GOFF.h:50
@ RT_END
Definition GOFF.h:49
@ RLD_ACT_Subtract
Definition GOFF.h:178
@ RLD_ACT_Add
Definition GOFF.h:177
RLDFetchStore
Definition GOFF.h:181
@ RLD_FS_Store
Definition GOFF.h:181
@ RLD_FS_Fetch
Definition GOFF.h:181
constexpr uint8_t PayloadLength
Definition GOFF.h:30
ESDTextStyle
Definition GOFF.h:91
@ ESD_EXE_DATA
Definition GOFF.h:111
constexpr uint16_t MaxDataLength
Maximum data length before starting a new card for RLD and TXT data.
Definition GOFF.h:39
@ END_EPR_None
Definition GOFF.h:184
ESDAlignment
Definition GOFF.h:144
RLDReferenceType
Definition GOFF.h:160
@ RLD_RT_RAddress
Definition GOFF.h:161
@ RLD_RT_ROffset
Definition GOFF.h:162
@ RLD_RT_RTypeConstant
Definition GOFF.h:165
RLDReferentType
Definition GOFF.h:169
@ RLD_RO_Label
Definition GOFF.h:170
@ RLD_RO_Class
Definition GOFF.h:172
constexpr uint8_t PTVPrefix
Prefix byte on every record. This indicates GOFF format.
Definition GOFF.h:42
constexpr uint8_t RecordLength
Length of the parts of a physical GOFF record.
Definition GOFF.h:28
ESDNameSpaceId
Definition GOFF.h:61
@ ESD_NS_ProgramManagementBinder
Definition GOFF.h:62
@ ESD_NS_NormalName
Definition GOFF.h:63
ESDSymbolType
Definition GOFF.h:53
@ ESD_ST_PartReference
Definition GOFF.h:57
@ ESD_ST_ElementDefinition
Definition GOFF.h:55
@ ESD_ST_LabelDefinition
Definition GOFF.h:56
@ ESD_ST_SectionDefinition
Definition GOFF.h:54
@ ESD_ST_ExternalReference
Definition GOFF.h:58
SymbolFlags
Symbol flags.
Definition Symbol.h:25
value_type byte_swap(value_type value, endianness endian)
Swap the bytes of value to match the given endianness.
Definition Endian.h:45
void write(void *memory, value_type value, endianness endian)
Write a value to memory with a particular endianness.
Definition Endian.h:82
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
@ Length
Definition DWP.cpp:577
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
LLVM_ABI std::unique_ptr< MCObjectWriter > createGOFFObjectWriter(std::unique_ptr< MCGOFFObjectTargetWriter > MOTW, raw_pwrite_stream &OS)
Construct a new GOFF writer instance.
detail::concat_range< ValueT, RangeTs... > concat(RangeTs &&...Ranges)
Returns a concatenated range across two or more ranges.
Definition STLExtras.h:1167
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
LLVM_ABI Error write(DWPWriter &Out, ArrayRef< std::string > Inputs, OnCuIndexOverflow OverflowOptValue, Dwarf64StrOffsetsPromotion StrOffsetsOptValue, raw_pwrite_stream *OS=nullptr)
Definition DWP.cpp:746
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
#define N
GOFF::RLDReferenceType ReferenceType
GOFF::RLDFetchStore FetchStore
GOFF::RLDReferentType ReferentType
GOFF::ESDReserveQwords ReservedQwords
GOFF::ESDRmode Rmode
GOFF::ESDTextStyle TextStyle
GOFF::ESDLoadingBehavior LoadBehavior
GOFF::ESDNameSpaceId NameSpace
GOFF::ESDBindingAlgorithm BindAlgorithm
GOFF::ESDBindingScope BindingScope
GOFF::ESDBindingStrength BindingStrength
GOFF::ESDLinkageType Linkage
GOFF::ESDExecutable Executable
GOFF::ESDAmode Amode
GOFF::ESDAmode Amode
GOFF::ESDBindingStrength BindingStrength
GOFF::ESDExecutable Executable
GOFF::ESDBindingScope BindingScope
GOFF::ESDLinkageType Linkage
GOFF::ESDLinkageType Linkage
GOFF::ESDBindingStrength BindingStrength
GOFF::ESDBindingScope BindingScope
GOFF::ESDExecutable Executable
GOFF::ESDTaskingBehavior TaskingBehavior
GOFF::ESDBindingScope BindingScope
Target independent information on a fixup kind.
uint8_t TargetSize
The number of bits written by this fixup.