LLVM 23.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"
20#include "llvm/MC/MCValue.h"
22#include "llvm/Support/Debug.h"
23#include "llvm/Support/Endian.h"
25
26using namespace llvm;
27
28#define DEBUG_TYPE "goff-writer"
29
30namespace {
31// Common flag values on records.
32
33// Flag: This record is continued.
34constexpr uint8_t RecContinued = GOFF::Flags(7, 1, 1);
35
36// Flag: This record is a continuation.
37constexpr uint8_t RecContinuation = GOFF::Flags(6, 1, 1);
38
39// The GOFFOstream is responsible to write the data into the fixed physical
40// records of the format. A user of this class announces the begin of a new
41// logical record. While writing the payload, the physical records are created
42// for the data. Possible fill bytes at the end of a physical record are written
43// automatically. In principle, the GOFFOstream is agnostic of the endianness of
44// the payload. However, it also supports writing data in big endian byte order.
45//
46// The physical records use the flag field to indicate if the there is a
47// successor and predecessor record. To be able to set these flags while
48// writing, the basic implementation idea is to always buffer the last seen
49// physical record.
50class GOFFOstream {
51 /// The underlying raw_pwrite_stream.
53
54 /// The number of logical records emitted so far.
55 uint32_t LogicalRecords = 0;
56
57 /// The number of physical records emitted so far.
58 uint32_t PhysicalRecords = 0;
59
60 /// The size of the buffer. Same as the payload size of a physical record.
61 static constexpr uint8_t BufferSize = GOFF::PayloadLength;
62
63 /// Current position in buffer.
64 char *BufferPtr = Buffer;
65
66 /// Static allocated buffer for the stream.
67 char Buffer[BufferSize];
68
69 /// The type of the current logical record, and the flags (aka continued and
70 /// continuation indicators) for the previous (physical) record.
71 uint8_t TypeAndFlags = 0;
72
73public:
74 GOFFOstream(raw_pwrite_stream &OS);
75 ~GOFFOstream();
76
77 raw_pwrite_stream &getOS() { return OS; }
78 size_t getWrittenSize() const { return PhysicalRecords * GOFF::RecordLength; }
79 uint32_t getNumLogicalRecords() { return LogicalRecords; }
80
81 /// Write the specified bytes.
82 void write(const char *Ptr, size_t Size);
83
84 /// Write zeroes, up to a maximum of 16 bytes.
85 void write_zeros(unsigned NumZeros);
86
87 /// Support for endian-specific data.
88 template <typename value_type> void writebe(value_type Value) {
89 Value =
91 write((const char *)&Value, sizeof(value_type));
92 }
93
94 /// Begin a new logical record. Implies finalizing the previous record.
95 void newRecord(GOFF::RecordType Type);
96
97 /// Ends a logical record.
98 void finalizeRecord();
99
100private:
101 /// Updates the continued/continuation flags, and writes the record prefix of
102 /// a physical record.
103 void updateFlagsAndWritePrefix(bool IsContinued);
104
105 /// Returns the remaining size in the buffer.
106 size_t getRemainingSize();
107};
108} // namespace
109
110GOFFOstream::GOFFOstream(raw_pwrite_stream &OS) : OS(OS) {}
111
112GOFFOstream::~GOFFOstream() { finalizeRecord(); }
113
114void GOFFOstream::updateFlagsAndWritePrefix(bool IsContinued) {
115 // Update the flags based on the previous state and the flag IsContinued.
116 if (TypeAndFlags & RecContinued)
117 TypeAndFlags |= RecContinuation;
118 if (IsContinued)
119 TypeAndFlags |= RecContinued;
120 else
121 TypeAndFlags &= ~RecContinued;
122
123 OS << static_cast<unsigned char>(GOFF::PTVPrefix) // Record Type
124 << static_cast<unsigned char>(TypeAndFlags) // Continuation
125 << static_cast<unsigned char>(0); // Version
126
127 ++PhysicalRecords;
128}
129
130size_t GOFFOstream::getRemainingSize() {
131 return size_t(&Buffer[BufferSize] - BufferPtr);
132}
133
134void GOFFOstream::write(const char *Ptr, size_t Size) {
135 size_t RemainingSize = getRemainingSize();
136
137 // Data fits into the buffer.
138 if (LLVM_LIKELY(Size <= RemainingSize)) {
139 memcpy(BufferPtr, Ptr, Size);
140 BufferPtr += Size;
141 return;
142 }
143
144 // Otherwise the buffer is partially filled or full, and data does not fit
145 // into it.
146 updateFlagsAndWritePrefix(/*IsContinued=*/true);
147 OS.write(Buffer, size_t(BufferPtr - Buffer));
148 if (RemainingSize > 0) {
149 OS.write(Ptr, RemainingSize);
150 Ptr += RemainingSize;
151 Size -= RemainingSize;
152 }
153
154 while (Size > BufferSize) {
155 updateFlagsAndWritePrefix(/*IsContinued=*/true);
156 OS.write(Ptr, BufferSize);
157 Ptr += BufferSize;
158 Size -= BufferSize;
159 }
160
161 // The remaining bytes fit into the buffer.
162 memcpy(Buffer, Ptr, Size);
163 BufferPtr = &Buffer[Size];
164}
165
166void GOFFOstream::write_zeros(unsigned NumZeros) {
167 assert(NumZeros <= 16 && "Range for zeros too large");
168
169 // Handle the common case first: all fits in the buffer.
170 size_t RemainingSize = getRemainingSize();
171 if (LLVM_LIKELY(RemainingSize >= NumZeros)) {
172 memset(BufferPtr, 0, NumZeros);
173 BufferPtr += NumZeros;
174 return;
175 }
176
177 // Otherwise some field value is cleared.
178 static char Zeros[16] = {
179 0,
180 };
181 write(Zeros, NumZeros);
182}
183
184void GOFFOstream::newRecord(GOFF::RecordType Type) {
185 finalizeRecord();
186 TypeAndFlags = Type << 4;
187 ++LogicalRecords;
188}
189
190void GOFFOstream::finalizeRecord() {
191 if (Buffer == BufferPtr)
192 return;
193 updateFlagsAndWritePrefix(/*IsContinued=*/false);
194 OS.write(Buffer, size_t(BufferPtr - Buffer));
195 OS.write_zeros(getRemainingSize());
196 BufferPtr = Buffer;
197}
198
199namespace {
200// A GOFFSymbol holds all the data required for writing an ESD record.
201class GOFFSymbol {
202public:
203 std::string Name;
204 uint32_t EsdId;
205 uint32_t ParentEsdId;
206 uint64_t Offset = 0; // Offset of the symbol into the section. LD only.
207 // Offset is only 32 bit, the larger type is used to
208 // enable error checking.
211
212 GOFF::BehavioralAttributes BehavAttrs;
213 GOFF::SymbolFlags SymbolFlags;
214 uint32_t SortKey = 0;
215 uint32_t SectionLength = 0;
216 uint32_t ADAEsdId = 0;
217 uint32_t EASectionEDEsdId = 0;
218 uint32_t EASectionOffset = 0;
219 uint8_t FillByteValue = 0;
220
221 GOFFSymbol() : EsdId(0), ParentEsdId(0) {}
222
223 GOFFSymbol(StringRef Name, uint32_t EsdID, const GOFF::SDAttr &Attr)
224 : Name(Name.data(), Name.size()), EsdId(EsdID), ParentEsdId(0),
226 BehavAttrs.setTaskingBehavior(Attr.TaskingBehavior);
227 BehavAttrs.setBindingScope(Attr.BindingScope);
228 }
229
230 GOFFSymbol(StringRef Name, uint32_t EsdID, uint32_t ParentEsdID,
231 const GOFF::EDAttr &Attr)
232 : Name(Name.data(), Name.size()), EsdId(EsdID), ParentEsdId(ParentEsdID),
234 this->NameSpace = Attr.NameSpace;
235 // We always set a fill byte value.
236 this->FillByteValue = Attr.FillByteValue;
237 SymbolFlags.setFillBytePresence(1);
238 SymbolFlags.setReservedQwords(Attr.ReservedQwords);
239 // TODO Do we need/should set the "mangled" flag?
240 BehavAttrs.setReadOnly(Attr.IsReadOnly);
241 BehavAttrs.setRmode(Attr.Rmode);
242 BehavAttrs.setTextStyle(Attr.TextStyle);
243 BehavAttrs.setBindingAlgorithm(Attr.BindAlgorithm);
244 BehavAttrs.setLoadingBehavior(Attr.LoadBehavior);
245 BehavAttrs.setAlignment(Attr.Alignment);
246 }
247
248 GOFFSymbol(StringRef Name, uint32_t EsdID, uint32_t ParentEsdID,
249 GOFF::ESDNameSpaceId NameSpace, const GOFF::LDAttr &Attr)
250 : Name(Name.data(), Name.size()), EsdId(EsdID), ParentEsdId(ParentEsdID),
251 SymbolType(GOFF::ESD_ST_LabelDefinition), NameSpace(NameSpace) {
252 SymbolFlags.setRenameable(Attr.IsRenamable);
253 BehavAttrs.setExecutable(Attr.Executable);
254 BehavAttrs.setBindingStrength(Attr.BindingStrength);
255 BehavAttrs.setLinkageType(Attr.Linkage);
256 BehavAttrs.setAmode(Attr.Amode);
257 BehavAttrs.setBindingScope(Attr.BindingScope);
258 }
259
260 GOFFSymbol(StringRef Name, uint32_t EsdID, uint32_t ParentEsdID,
261 const GOFF::EDAttr &EDAttr, const GOFF::PRAttr &Attr)
262 : Name(Name.data(), Name.size()), EsdId(EsdID), ParentEsdId(ParentEsdID),
263 SymbolType(GOFF::ESD_ST_PartReference), NameSpace(EDAttr.NameSpace) {
264 SymbolFlags.setRenameable(Attr.IsRenamable);
265 BehavAttrs.setExecutable(Attr.Executable);
266 BehavAttrs.setLinkageType(Attr.Linkage);
267 BehavAttrs.setBindingScope(Attr.BindingScope);
268 BehavAttrs.setAlignment(EDAttr.Alignment);
269 }
270
271 GOFFSymbol(StringRef Name, uint32_t EsdID, uint32_t ParentEsdID,
272 const GOFF::ERAttr &Attr)
273 : Name(Name.data(), Name.size()), EsdId(EsdID), ParentEsdId(ParentEsdID),
275 NameSpace(GOFF::ESD_NS_NormalName) {
276 BehavAttrs.setExecutable(Attr.Executable);
277 BehavAttrs.setBindingStrength(Attr.BindingStrength);
278 BehavAttrs.setLinkageType(Attr.Linkage);
279 BehavAttrs.setAmode(Attr.Amode);
280 BehavAttrs.setBindingScope(Attr.BindingScope);
281 BehavAttrs.setIndirectReference(Attr.IsIndirectReference);
282 }
283};
284
285class GOFFWriter {
286 GOFFOstream OS;
287 MCAssembler &Asm;
288 MCSectionGOFF *RootSD;
289
290 /// Saved relocation data collected in recordRelocations().
291 std::vector<GOFFRelocationEntry> &Relocations;
292
293 void writeHeader();
294 void writeSymbol(const GOFFSymbol &Symbol);
295 void writeText(const MCSectionGOFF *MC);
296 void writeRelocations();
297 void writeEnd();
298
299 void defineSectionSymbols(const MCSectionGOFF &Section);
300 void defineLabel(const MCSymbolGOFF &Symbol);
301 void defineExtern(const MCSymbolGOFF &Symbol);
302 void defineSymbols();
303
304public:
305 GOFFWriter(raw_pwrite_stream &OS, MCAssembler &Asm, MCSectionGOFF *RootSD,
306 std::vector<GOFFRelocationEntry> &Relocations);
307 uint64_t writeObject();
308};
309} // namespace
310
311GOFFWriter::GOFFWriter(raw_pwrite_stream &OS, MCAssembler &Asm,
312 MCSectionGOFF *RootSD,
313 std::vector<GOFFRelocationEntry> &Relocations)
314 : OS(OS), Asm(Asm), RootSD(RootSD), Relocations(Relocations) {}
315
316void GOFFWriter::defineSectionSymbols(const MCSectionGOFF &Section) {
317 if (Section.isSD()) {
318 GOFFSymbol SD(Section.getExternalName(), Section.getOrdinal(),
319 Section.getSDAttributes());
320 writeSymbol(SD);
321 }
322
323 if (Section.isED()) {
324 GOFFSymbol ED(Section.getExternalName(), Section.getOrdinal(),
325 Section.getParent()->getOrdinal(), Section.getEDAttributes());
326 ED.SectionLength = Asm.getSectionAddressSize(Section);
327 writeSymbol(ED);
328 }
329
330 if (Section.isPR()) {
331 MCSectionGOFF *Parent = Section.getParent();
332 GOFFSymbol PR(Section.getExternalName(), Section.getOrdinal(),
333 Parent->getOrdinal(), Parent->getEDAttributes(),
334 Section.getPRAttributes());
335 PR.SectionLength = Asm.getSectionAddressSize(Section);
336 if (Section.requiresNonZeroLength()) {
337 // We cannot have a zero-length section for data. If we do,
338 // artificially inflate it. Use 2 bytes to avoid odd alignments. Note:
339 // if this is ever changed, you will need to update the code in
340 // SystemZAsmPrinter::emitCEEMAIN and SystemZAsmPrinter::emitCELQMAIN to
341 // generate -1 if there is no ADA
342 if (!PR.SectionLength)
343 PR.SectionLength = 2;
344 }
345 writeSymbol(PR);
346 }
347}
348
349void GOFFWriter::defineLabel(const MCSymbolGOFF &Symbol) {
350 MCSectionGOFF &Section = static_cast<MCSectionGOFF &>(Symbol.getSection());
351 GOFFSymbol LD(Symbol.getExternalName(), Symbol.getIndex(),
352 Section.getOrdinal(), Section.getEDAttributes().NameSpace,
353 GOFF::LDAttr{false, Symbol.getCodeData(),
354 Symbol.getBindingStrength(), Symbol.getLinkage(),
355 GOFF::ESD_AMODE_64, Symbol.getBindingScope()});
356 if (Symbol.getADA())
357 LD.ADAEsdId = Symbol.getADA()->getOrdinal();
358 LD.Offset = Asm.getSymbolOffset(Symbol);
359 writeSymbol(LD);
360}
361
362void GOFFWriter::defineExtern(const MCSymbolGOFF &Symbol) {
363 GOFFSymbol ER(Symbol.getExternalName(), Symbol.getIndex(),
364 RootSD->getOrdinal(),
365 GOFF::ERAttr{Symbol.isIndirect(), Symbol.getCodeData(),
366 Symbol.getBindingStrength(), Symbol.getLinkage(),
367 GOFF::ESD_AMODE_64, Symbol.getBindingScope()});
368 writeSymbol(ER);
369}
370
371void GOFFWriter::defineSymbols() {
372 unsigned Ordinal = 0;
373 // Process all sections.
374 for (MCSection &S : Asm) {
375 auto &Section = static_cast<MCSectionGOFF &>(S);
376 Section.setOrdinal(++Ordinal);
377 defineSectionSymbols(Section);
378 }
379
380 // Process all symbols
381 for (const MCSymbol &Sym : Asm.symbols()) {
382 if (Sym.isTemporary())
383 continue;
384 auto &Symbol = static_cast<const MCSymbolGOFF &>(Sym);
385 if (!Symbol.isDefined()) {
386 Symbol.setIndex(++Ordinal);
387 defineExtern(Symbol);
388 } else if (Symbol.isInEDSection()) {
389 Symbol.setIndex(++Ordinal);
390 defineLabel(Symbol);
391 } else {
392 // Symbol is in PR section, the symbol refers to the section.
393 Symbol.setIndex(Symbol.getSection().getOrdinal());
394 }
395 }
396}
397
398void GOFFWriter::writeHeader() {
399 OS.newRecord(GOFF::RT_HDR);
400 OS.write_zeros(1); // Reserved
401 OS.writebe<uint32_t>(0); // Target Hardware Environment
402 OS.writebe<uint32_t>(0); // Target Operating System Environment
403 OS.write_zeros(2); // Reserved
404 OS.writebe<uint16_t>(0); // CCSID
405 OS.write_zeros(16); // Character Set name
406 OS.write_zeros(16); // Language Product Identifier
407 OS.writebe<uint32_t>(1); // Architecture Level
408 OS.writebe<uint16_t>(0); // Module Properties Length
409 OS.write_zeros(6); // Reserved
410}
411
412void GOFFWriter::writeSymbol(const GOFFSymbol &Symbol) {
413 if (Symbol.Offset >= (((uint64_t)1) << 31))
414 report_fatal_error("ESD offset out of range");
415
416 // All symbol names are in EBCDIC.
417 SmallString<256> Name;
419
420 // Check length here since this number is technically signed but we need uint
421 // for writing to records.
422 if (Name.size() >= GOFF::MaxDataLength)
423 report_fatal_error("Symbol max name length exceeded");
424 uint16_t NameLength = Name.size();
425
426 OS.newRecord(GOFF::RT_ESD);
427 OS.writebe<uint8_t>(Symbol.SymbolType); // Symbol Type
428 OS.writebe<uint32_t>(Symbol.EsdId); // ESDID
429 OS.writebe<uint32_t>(Symbol.ParentEsdId); // Parent or Owning ESDID
430 OS.writebe<uint32_t>(0); // Reserved
431 OS.writebe<uint32_t>(
432 static_cast<uint32_t>(Symbol.Offset)); // Offset or Address
433 OS.writebe<uint32_t>(0); // Reserved
434 OS.writebe<uint32_t>(Symbol.SectionLength); // Length
435 OS.writebe<uint32_t>(Symbol.EASectionEDEsdId); // Extended Attribute ESDID
436 OS.writebe<uint32_t>(Symbol.EASectionOffset); // Extended Attribute Offset
437 OS.writebe<uint32_t>(0); // Reserved
438 OS.writebe<uint8_t>(Symbol.NameSpace); // Name Space ID
439 OS.writebe<uint8_t>(Symbol.SymbolFlags); // Flags
440 OS.writebe<uint8_t>(Symbol.FillByteValue); // Fill-Byte Value
441 OS.writebe<uint8_t>(0); // Reserved
442 OS.writebe<uint32_t>(Symbol.ADAEsdId); // ADA ESDID
443 OS.writebe<uint32_t>(Symbol.SortKey); // Sort Priority
444 OS.writebe<uint64_t>(0); // Reserved
445 for (auto F : Symbol.BehavAttrs.Attr)
446 OS.writebe<uint8_t>(F); // Behavioral Attributes
447 OS.writebe<uint16_t>(NameLength); // Name Length
448 OS.write(Name.data(), NameLength); // Name
449}
450
451namespace {
452/// Adapter stream to write a text section.
453class TextStream : public raw_ostream {
454 /// The underlying GOFFOstream.
455 GOFFOstream &OS;
456
457 /// The buffer size is the maximum number of bytes in a TXT section.
458 static constexpr size_t BufferSize = GOFF::MaxDataLength;
459
460 /// Static allocated buffer for the stream, used by the raw_ostream class. The
461 /// buffer is sized to hold the payload of a logical TXT record.
462 char Buffer[BufferSize];
463
464 /// The offset for the next TXT record. This is equal to the number of bytes
465 /// written.
466 size_t Offset;
467
468 /// The Esdid of the GOFF section.
469 const uint32_t EsdId;
470
471 /// The record style.
472 const GOFF::ESDTextStyle RecordStyle;
473
474 /// See raw_ostream::write_impl.
475 void write_impl(const char *Ptr, size_t Size) override;
476
477 uint64_t current_pos() const override { return Offset; }
478
479public:
480 explicit TextStream(GOFFOstream &OS, uint32_t EsdId,
481 GOFF::ESDTextStyle RecordStyle)
482 : OS(OS), Offset(0), EsdId(EsdId), RecordStyle(RecordStyle) {
483 SetBuffer(Buffer, sizeof(Buffer));
484 }
485
486 ~TextStream() override { flush(); }
487};
488} // namespace
489
490void TextStream::write_impl(const char *Ptr, size_t Size) {
491 size_t WrittenLength = 0;
492
493 // We only have signed 32bits of offset.
494 if (Offset + Size > std::numeric_limits<int32_t>::max())
495 report_fatal_error("TXT section too large");
496
497 while (WrittenLength < Size) {
498 size_t ToWriteLength =
499 std::min(Size - WrittenLength, size_t(GOFF::MaxDataLength));
500
501 OS.newRecord(GOFF::RT_TXT);
502 OS.writebe<uint8_t>(GOFF::Flags(4, 4, RecordStyle)); // Text Record Style
503 OS.writebe<uint32_t>(EsdId); // Element ESDID
504 OS.writebe<uint32_t>(0); // Reserved
505 OS.writebe<uint32_t>(static_cast<uint32_t>(Offset)); // Offset
506 OS.writebe<uint32_t>(0); // Text Field True Length
507 OS.writebe<uint16_t>(0); // Text Encoding
508 OS.writebe<uint16_t>(ToWriteLength); // Data Length
509 OS.write(Ptr + WrittenLength, ToWriteLength); // Data
510
511 WrittenLength += ToWriteLength;
512 Offset += ToWriteLength;
513 }
514}
515
516void GOFFWriter::writeText(const MCSectionGOFF *Section) {
517 // A BSS section contains only zeros, no need to write this.
518 if (Section->isBSS())
519 return;
520
521 TextStream S(OS, Section->getOrdinal(), Section->getTextStyle());
522 Asm.writeSectionData(S, Section);
523}
524
525namespace {
526// RelocDataItemBuffer provides a static buffer for relocation data items.
527class RelocDataItemBuffer {
528 char Buffer[GOFF::MaxDataLength];
529 char *Ptr;
530
531public:
532 RelocDataItemBuffer() : Ptr(Buffer) {}
533 const char *data() { return Buffer; }
534 size_t size() { return Ptr - Buffer; }
535 void reset() { Ptr = Buffer; }
536 bool fits(size_t S) { return size() + S < GOFF::MaxDataLength; }
537 template <typename T> void writebe(T Val) {
538 assert(fits(sizeof(T)) && "Out-of-bounds write");
540 Ptr += sizeof(T);
541 }
542};
543} // namespace
544
545void GOFFWriter::writeRelocations() {
546 // Set the IDs in the relocation entries.
547 for (auto &RelocEntry : Relocations) {
548 auto GetRptr = [](const MCSymbolGOFF *Sym) -> uint32_t {
549 if (Sym->isTemporary())
550 return static_cast<MCSectionGOFF &>(Sym->getSection())
551 .getBeginSymbol()
552 ->getIndex();
553 return Sym->getIndex();
554 };
555
556 RelocEntry.PEsdId = RelocEntry.Pptr->getOrdinal();
557 RelocEntry.REsdId = GetRptr(RelocEntry.Rptr);
558 }
559
560 // Sort relocation data items by the P pointer to save space.
561 std::sort(
562 Relocations.begin(), Relocations.end(),
563 [](const GOFFRelocationEntry &Left, const GOFFRelocationEntry &Right) {
564 return std::tie(Left.PEsdId, Left.REsdId, Left.POffset) <
565 std::tie(Right.PEsdId, Right.REsdId, Right.POffset);
566 });
567
568 // Construct the compressed relocation data items, and write them out.
569 RelocDataItemBuffer Buffer;
570 for (auto I = Relocations.begin(), E = Relocations.end(); I != E;) {
571 Buffer.reset();
572
573 uint32_t PrevResdId = -1;
574 uint32_t PrevPesdId = -1;
575 uint64_t PrevPOffset = -1;
576 for (; I != E; ++I) {
577 const GOFFRelocationEntry &Rel = *I;
578
579 bool SameREsdId = (Rel.REsdId == PrevResdId);
580 bool SamePEsdId = (Rel.PEsdId == PrevPesdId);
581 bool SamePOffset = (Rel.POffset == PrevPOffset);
582 bool EightByteOffset = ((Rel.POffset >> 32) & 0xffffffff);
583
584 // Calculate size of relocation data item, and check if it still fits into
585 // the record.
586 size_t ItemSize = 8; // Smallest size of a relocation data item.
587 if (!SameREsdId)
588 ItemSize += 4;
589 if (!SamePEsdId)
590 ItemSize += 4;
591 if (!SamePOffset)
592 ItemSize += (EightByteOffset ? 8 : 4);
593 if (!Buffer.fits(ItemSize))
594 break;
595
596 GOFF::Flags RelocFlags[6];
597 RelocFlags[0].set(0, 1, SameREsdId);
598 RelocFlags[0].set(1, 1, SamePEsdId);
599 RelocFlags[0].set(2, 1, SamePOffset);
600 RelocFlags[0].set(6, 1, EightByteOffset);
601
602 RelocFlags[1].set(0, 4, Rel.ReferenceType);
603 RelocFlags[1].set(4, 4, Rel.ReferentType);
604
605 RelocFlags[2].set(0, 7, Rel.Action);
606 RelocFlags[2].set(7, 1, Rel.FetchStore);
607
608 RelocFlags[4].set(0, 8, Rel.TargetLength);
609
610 for (auto F : RelocFlags)
611 Buffer.writebe<uint8_t>(F);
612 Buffer.writebe<uint16_t>(0); // Reserved.
613 if (!SameREsdId)
614 Buffer.writebe<uint32_t>(Rel.REsdId);
615 if (!SamePEsdId)
616 Buffer.writebe<uint32_t>(Rel.PEsdId);
617 if (!SamePOffset) {
618 if (EightByteOffset)
619 Buffer.writebe<uint64_t>(Rel.POffset);
620 else
621 Buffer.writebe<uint32_t>(Rel.POffset);
622 }
623
624 PrevResdId = Rel.REsdId;
625 PrevPesdId = Rel.PEsdId;
626 PrevPOffset = Rel.POffset;
627 }
628
629 OS.newRecord(GOFF::RT_RLD);
630 OS.writebe<uint8_t>(0); // Reserved.
631 OS.writebe<uint16_t>(Buffer.size()); // Length (of the relocation data).
632 OS.write(Buffer.data(), Buffer.size()); // Relocation Directory Data Items.
633 }
634}
635
636void GOFFWriter::writeEnd() {
637 uint8_t F = GOFF::END_EPR_None;
638 uint8_t AMODE = 0;
639 uint32_t ESDID = 0;
640
641 // TODO Set Flags/AMODE/ESDID for entry point.
642
643 OS.newRecord(GOFF::RT_END);
644 OS.writebe<uint8_t>(GOFF::Flags(6, 2, F)); // Indicator flags
645 OS.writebe<uint8_t>(AMODE); // AMODE
646 OS.write_zeros(3); // Reserved
647 // The record count is the number of logical records. In principle, this value
648 // is available as OS.logicalRecords(). However, some tools rely on this field
649 // being zero.
650 OS.writebe<uint32_t>(0); // Record Count
651 OS.writebe<uint32_t>(ESDID); // ESDID (of entry point)
652}
653
654uint64_t GOFFWriter::writeObject() {
655 writeHeader();
656
657 defineSymbols();
658
659 for (const MCSection &Section : Asm)
660 writeText(static_cast<const MCSectionGOFF *>(&Section));
661
662 writeRelocations();
663
664 writeEnd();
665
666 // Make sure all records are written.
667 OS.finalizeRecord();
668
669 LLVM_DEBUG(dbgs() << "Wrote " << OS.getNumLogicalRecords()
670 << " logical records.");
671
672 return OS.getWrittenSize();
673}
674
676 std::unique_ptr<MCGOFFObjectTargetWriter> MOTW, raw_pwrite_stream &OS)
677 : TargetObjectWriter(std::move(MOTW)), OS(OS) {}
678
680
682 const MCFixup &Fixup, MCValue Target,
683 uint64_t &FixedValue) {
684 const MCFixupKindInfo &FKI =
685 Asm->getBackend().getFixupKindInfo(Fixup.getKind());
686 const uint32_t Length = FKI.TargetSize / 8;
687 assert(FKI.TargetSize % 8 == 0 && "Target Size not multiple of 8");
688 const uint64_t FixupOffset = Asm->getFragmentOffset(F) + Fixup.getOffset();
689
690 unsigned RelocType = TargetObjectWriter->getRelocType(Target, Fixup);
691
692 const MCSectionGOFF *PSection = static_cast<MCSectionGOFF *>(F.getParent());
693 const auto &A = *static_cast<const MCSymbolGOFF *>(Target.getAddSym());
694 const MCSymbolGOFF *B = static_cast<const MCSymbolGOFF *>(Target.getSubSym());
696 if (A.isUndefined()) {
697 Asm->reportError(
698 Fixup.getLoc(),
699 Twine("symbol ")
700 .concat(A.getExternalName())
701 .concat(" must be defined for a relative immediate relocation"));
702 return;
703 }
704 if (&A.getSection() != PSection) {
705 MCSectionGOFF &GOFFSection = static_cast<MCSectionGOFF &>(A.getSection());
706 Asm->reportError(Fixup.getLoc(),
707 Twine("relative immediate relocation section mismatch: ")
708 .concat(GOFFSection.getExternalName())
709 .concat(" of symbol ")
710 .concat(A.getExternalName())
711 .concat(" <-> ")
712 .concat(PSection->getExternalName()));
713 return;
714 }
715 if (B) {
716 Asm->reportError(
717 Fixup.getLoc(),
718 Twine("subtractive symbol ")
719 .concat(B->getExternalName())
720 .concat(" not supported for a relative immediate relocation"));
721 return;
722 }
723 FixedValue = Asm->getSymbolOffset(A) - FixupOffset + Target.getConstant();
724 return;
725 }
726 FixedValue = Target.getConstant();
727
728 // The symbol only has a section-relative offset if it is a temporary symbol.
729 FixedValue += A.isTemporary() ? Asm->getSymbolOffset(A) : 0;
730 A.setUsedInReloc();
731 if (B) {
732 FixedValue -= B->isTemporary() ? Asm->getSymbolOffset(*B) : 0;
733 B->setUsedInReloc();
734 }
735
736 // UseQCon causes class offsets versus absolute addresses to be used. This
737 // is analogous to using QCONs in older OBJ object file format.
738 bool UseQCon = RelocType == MCGOFFObjectTargetWriter::Reloc_Type_QCon;
739
740 GOFF::RLDFetchStore FetchStore =
745 assert((FetchStore == GOFF::RLDFetchStore::RLD_FS_Fetch || B == nullptr) &&
746 "No dependent relocations expected");
747
749 enum GOFF::RLDReferentType ReferentType = GOFF::RLD_RO_Label;
750 if (UseQCon) {
752 ReferentType = GOFF::RLD_RO_Class;
753 }
756
757 auto DumpReloc = [&PSection, &ReferenceType, &FixupOffset,
758 &FixedValue](const char *N, const MCSymbolGOFF *Sym) {
759 const char *Con;
760 switch (ReferenceType) {
762 Con = "ACon";
763 break;
765 Con = "QCon";
766 break;
768 Con = "VCon";
769 break;
770 default:
771 Con = "(unknown)";
772 }
773 dbgs() << "Reloc " << N << ": " << Con
774 << " Rptr: " << Sym->getExternalName()
775 << " Pptr: " << PSection->getExternalName()
776 << " Offset: " << FixupOffset << " Fixed Imm: " << FixedValue
777 << "\n";
778 };
779 (void)DumpReloc;
780
781 // Save relocation data for later writing.
782 LLVM_DEBUG(DumpReloc("A", &A));
783 Relocations.emplace_back(PSection, &A, ReferenceType, ReferentType,
784 GOFF::RLD_ACT_Add, FetchStore, FixupOffset, Length);
785 if (B) {
786 LLVM_DEBUG(DumpReloc("B", B));
787 Relocations.emplace_back(
788 PSection, B, ReferenceType, ReferentType, GOFF::RLD_ACT_Subtract,
790 }
791}
792
794 uint64_t Size = GOFFWriter(OS, *Asm, RootSD, Relocations).writeObject();
795 return Size;
796}
797
798std::unique_ptr<MCObjectWriter>
799llvm::createGOFFObjectWriter(std::unique_ptr<MCGOFFObjectTargetWriter> MOTW,
800 raw_pwrite_stream &OS) {
801 return std::make_unique<GOFFObjectWriter>(std::move(MOTW), OS);
802}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
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:335
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
PowerPC TLS Dynamic Call Fixup
static Split data
#define LLVM_DEBUG(...)
Definition Debug.h:114
GOFFObjectWriter(std::unique_ptr< MCGOFFObjectTargetWriter > MOTW, raw_pwrite_stream &OS)
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:216
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:61
GOFF::EDAttr getEDAttributes() const
StringRef getExternalName() const
unsigned getOrdinal() const
Definition MCSection.h:622
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:45
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)
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
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
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)
Definition Endian.h:44
void write(void *memory, value_type value, endianness endian)
Write a value to memory with a particular endianness.
Definition Endian.h:96
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
@ Offset
Definition DWP.cpp:532
@ Length
Definition DWP.cpp:532
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:1669
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:1152
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
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:1917
LLVM_ABI Error write(MCStreamer &Out, ArrayRef< std::string > Inputs, OnCuIndexOverflow OverflowOptValue, Dwarf64StrOffsetsPromotion StrOffsetsOptValue)
Definition DWP.cpp:677
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:870
#define N
GOFF::RLDReferenceType ReferenceType
GOFF::RLDFetchStore FetchStore
GOFF::RLDReferentType ReferentType
GOFF::ESDReserveQwords ReservedQwords
GOFF::ESDRmode Rmode
GOFF::ESDAlignment Alignment
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::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.