| 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 | |
| 13 | #include "llvm/BinaryFormat/GOFF.h" |
| 14 | #include "llvm/MC/MCAsmBackend.h" |
| 15 | #include "llvm/MC/MCAssembler.h" |
| 16 | #include "llvm/MC/MCGOFFAttributes.h" |
| 17 | #include "llvm/MC/MCGOFFObjectWriter.h" |
| 18 | #include "llvm/MC/MCSectionGOFF.h" |
| 19 | #include "llvm/MC/MCSymbolGOFF.h" |
| 20 | #include "llvm/MC/MCValue.h" |
| 21 | #include "llvm/Support/ConvertEBCDIC.h" |
| 22 | #include "llvm/Support/Debug.h" |
| 23 | #include "llvm/Support/Endian.h" |
| 24 | #include "llvm/Support/raw_ostream.h" |
| 25 | |
| 26 | using namespace llvm; |
| 27 | |
| 28 | #define DEBUG_TYPE "goff-writer" |
| 29 | |
| 30 | namespace { |
| 31 | // Common flag values on records. |
| 32 | |
| 33 | // Flag: This record is continued. |
| 34 | constexpr uint8_t RecContinued = GOFF::Flags(7, 1, 1); |
| 35 | |
| 36 | // Flag: This record is a continuation. |
| 37 | constexpr 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. |
| 50 | class GOFFOstream { |
| 51 | /// The underlying raw_pwrite_stream. |
| 52 | raw_pwrite_stream &OS; |
| 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 | |
| 73 | public: |
| 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 = |
| 90 | support::endian::byte_swap<value_type>(Value, llvm::endianness::big); |
| 91 | write(Ptr: (const char *)&Value, Size: 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 | |
| 100 | private: |
| 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 | |
| 110 | GOFFOstream::GOFFOstream(raw_pwrite_stream &OS) : OS(OS) {} |
| 111 | |
| 112 | GOFFOstream::~GOFFOstream() { finalizeRecord(); } |
| 113 | |
| 114 | void 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 | |
| 130 | size_t GOFFOstream::getRemainingSize() { |
| 131 | return size_t(&Buffer[BufferSize] - BufferPtr); |
| 132 | } |
| 133 | |
| 134 | void 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(dest: BufferPtr, src: Ptr, n: 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(Ptr: Buffer, Size: size_t(BufferPtr - Buffer)); |
| 148 | if (RemainingSize > 0) { |
| 149 | OS.write(Ptr, Size: RemainingSize); |
| 150 | Ptr += RemainingSize; |
| 151 | Size -= RemainingSize; |
| 152 | } |
| 153 | |
| 154 | while (Size > BufferSize) { |
| 155 | updateFlagsAndWritePrefix(/*IsContinued=*/true); |
| 156 | OS.write(Ptr, Size: BufferSize); |
| 157 | Ptr += BufferSize; |
| 158 | Size -= BufferSize; |
| 159 | } |
| 160 | |
| 161 | // The remaining bytes fit into the buffer. |
| 162 | memcpy(dest: Buffer, src: Ptr, n: Size); |
| 163 | BufferPtr = &Buffer[Size]; |
| 164 | } |
| 165 | |
| 166 | void 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(s: BufferPtr, c: 0, n: 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(Ptr: Zeros, Size: NumZeros); |
| 182 | } |
| 183 | |
| 184 | void GOFFOstream::newRecord(GOFF::RecordType Type) { |
| 185 | finalizeRecord(); |
| 186 | TypeAndFlags = Type << 4; |
| 187 | ++LogicalRecords; |
| 188 | } |
| 189 | |
| 190 | void GOFFOstream::finalizeRecord() { |
| 191 | if (Buffer == BufferPtr) |
| 192 | return; |
| 193 | updateFlagsAndWritePrefix(/*IsContinued=*/false); |
| 194 | OS.write(Ptr: Buffer, Size: size_t(BufferPtr - Buffer)); |
| 195 | OS.write_zeros(NumZeros: getRemainingSize()); |
| 196 | BufferPtr = Buffer; |
| 197 | } |
| 198 | |
| 199 | namespace { |
| 200 | // A GOFFSymbol holds all the data required for writing an ESD record. |
| 201 | class GOFFSymbol { |
| 202 | public: |
| 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. |
| 209 | GOFF::ESDSymbolType SymbolType; |
| 210 | GOFF::ESDNameSpaceId NameSpace = GOFF::ESD_NS_ProgramManagementBinder; |
| 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), |
| 225 | SymbolType(GOFF::ESD_ST_SectionDefinition) { |
| 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), |
| 233 | SymbolType(GOFF::ESD_ST_ElementDefinition) { |
| 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), |
| 274 | SymbolType(GOFF::ESD_ST_ExternalReference), |
| 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 | } |
| 282 | }; |
| 283 | |
| 284 | class GOFFWriter { |
| 285 | GOFFOstream OS; |
| 286 | MCAssembler &Asm; |
| 287 | MCSectionGOFF *RootSD; |
| 288 | |
| 289 | /// Saved relocation data collected in recordRelocations(). |
| 290 | std::vector<GOFFRelocationEntry> &Relocations; |
| 291 | |
| 292 | void writeHeader(); |
| 293 | void writeSymbol(const GOFFSymbol &Symbol); |
| 294 | void writeText(const MCSectionGOFF *MC); |
| 295 | void writeRelocations(); |
| 296 | void writeEnd(); |
| 297 | |
| 298 | void defineSectionSymbols(const MCSectionGOFF &Section); |
| 299 | void defineLabel(const MCSymbolGOFF &Symbol); |
| 300 | void defineExtern(const MCSymbolGOFF &Symbol); |
| 301 | void defineSymbols(); |
| 302 | |
| 303 | public: |
| 304 | GOFFWriter(raw_pwrite_stream &OS, MCAssembler &Asm, MCSectionGOFF *RootSD, |
| 305 | std::vector<GOFFRelocationEntry> &Relocations); |
| 306 | uint64_t writeObject(); |
| 307 | }; |
| 308 | } // namespace |
| 309 | |
| 310 | GOFFWriter::GOFFWriter(raw_pwrite_stream &OS, MCAssembler &Asm, |
| 311 | MCSectionGOFF *RootSD, |
| 312 | std::vector<GOFFRelocationEntry> &Relocations) |
| 313 | : OS(OS), Asm(Asm), RootSD(RootSD), Relocations(Relocations) {} |
| 314 | |
| 315 | void GOFFWriter::defineSectionSymbols(const MCSectionGOFF &Section) { |
| 316 | if (Section.isSD()) { |
| 317 | GOFFSymbol SD(Section.getName(), Section.getOrdinal(), |
| 318 | Section.getSDAttributes()); |
| 319 | writeSymbol(Symbol: SD); |
| 320 | } |
| 321 | |
| 322 | if (Section.isED()) { |
| 323 | GOFFSymbol ED(Section.getName(), Section.getOrdinal(), |
| 324 | Section.getParent()->getOrdinal(), Section.getEDAttributes()); |
| 325 | ED.SectionLength = Asm.getSectionAddressSize(Sec: Section); |
| 326 | writeSymbol(Symbol: ED); |
| 327 | } |
| 328 | |
| 329 | if (Section.isPR()) { |
| 330 | MCSectionGOFF *Parent = Section.getParent(); |
| 331 | GOFFSymbol PR(Section.getName(), Section.getOrdinal(), Parent->getOrdinal(), |
| 332 | Parent->getEDAttributes(), Section.getPRAttributes()); |
| 333 | PR.SectionLength = Asm.getSectionAddressSize(Sec: Section); |
| 334 | if (Section.requiresNonZeroLength()) { |
| 335 | // We cannot have a zero-length section for data. If we do, |
| 336 | // artificially inflate it. Use 2 bytes to avoid odd alignments. Note: |
| 337 | // if this is ever changed, you will need to update the code in |
| 338 | // SystemZAsmPrinter::emitCEEMAIN and SystemZAsmPrinter::emitCELQMAIN to |
| 339 | // generate -1 if there is no ADA |
| 340 | if (!PR.SectionLength) |
| 341 | PR.SectionLength = 2; |
| 342 | } |
| 343 | writeSymbol(Symbol: PR); |
| 344 | } |
| 345 | } |
| 346 | |
| 347 | void GOFFWriter::defineLabel(const MCSymbolGOFF &Symbol) { |
| 348 | MCSectionGOFF &Section = static_cast<MCSectionGOFF &>(Symbol.getSection()); |
| 349 | GOFFSymbol LD(Symbol.getName(), Symbol.getIndex(), Section.getOrdinal(), |
| 350 | Section.getEDAttributes().NameSpace, |
| 351 | GOFF::LDAttr{.IsRenamable: false, .Executable: Symbol.getCodeData(), |
| 352 | .BindingStrength: Symbol.getBindingStrength(), .Linkage: Symbol.getLinkage(), |
| 353 | .Amode: GOFF::ESD_AMODE_64, .BindingScope: Symbol.getBindingScope()}); |
| 354 | if (Symbol.getADA()) |
| 355 | LD.ADAEsdId = Symbol.getADA()->getOrdinal(); |
| 356 | LD.Offset = Asm.getSymbolOffset(S: Symbol); |
| 357 | writeSymbol(Symbol: LD); |
| 358 | } |
| 359 | |
| 360 | void GOFFWriter::defineExtern(const MCSymbolGOFF &Symbol) { |
| 361 | GOFFSymbol ER(Symbol.getName(), Symbol.getIndex(), RootSD->getOrdinal(), |
| 362 | GOFF::ERAttr{.Executable: Symbol.getCodeData(), .BindingStrength: Symbol.getBindingStrength(), |
| 363 | .Linkage: Symbol.getLinkage(), .Amode: GOFF::ESD_AMODE_64, |
| 364 | .BindingScope: Symbol.getBindingScope()}); |
| 365 | writeSymbol(Symbol: ER); |
| 366 | } |
| 367 | |
| 368 | void GOFFWriter::defineSymbols() { |
| 369 | unsigned Ordinal = 0; |
| 370 | // Process all sections. |
| 371 | for (MCSection &S : Asm) { |
| 372 | auto &Section = static_cast<MCSectionGOFF &>(S); |
| 373 | Section.setOrdinal(++Ordinal); |
| 374 | defineSectionSymbols(Section); |
| 375 | } |
| 376 | |
| 377 | // Process all symbols |
| 378 | for (const MCSymbol &Sym : Asm.symbols()) { |
| 379 | if (Sym.isTemporary()) |
| 380 | continue; |
| 381 | auto &Symbol = static_cast<const MCSymbolGOFF &>(Sym); |
| 382 | if (!Symbol.isDefined()) { |
| 383 | Symbol.setIndex(++Ordinal); |
| 384 | defineExtern(Symbol); |
| 385 | } else if (Symbol.isInEDSection()) { |
| 386 | Symbol.setIndex(++Ordinal); |
| 387 | defineLabel(Symbol); |
| 388 | } else { |
| 389 | // Symbol is in PR section, the symbol refers to the section. |
| 390 | Symbol.setIndex(Symbol.getSection().getOrdinal()); |
| 391 | } |
| 392 | } |
| 393 | } |
| 394 | |
| 395 | void GOFFWriter::() { |
| 396 | OS.newRecord(Type: GOFF::RT_HDR); |
| 397 | OS.write_zeros(NumZeros: 1); // Reserved |
| 398 | OS.writebe<uint32_t>(Value: 0); // Target Hardware Environment |
| 399 | OS.writebe<uint32_t>(Value: 0); // Target Operating System Environment |
| 400 | OS.write_zeros(NumZeros: 2); // Reserved |
| 401 | OS.writebe<uint16_t>(Value: 0); // CCSID |
| 402 | OS.write_zeros(NumZeros: 16); // Character Set name |
| 403 | OS.write_zeros(NumZeros: 16); // Language Product Identifier |
| 404 | OS.writebe<uint32_t>(Value: 1); // Architecture Level |
| 405 | OS.writebe<uint16_t>(Value: 0); // Module Properties Length |
| 406 | OS.write_zeros(NumZeros: 6); // Reserved |
| 407 | } |
| 408 | |
| 409 | void GOFFWriter::writeSymbol(const GOFFSymbol &Symbol) { |
| 410 | if (Symbol.Offset >= (((uint64_t)1) << 31)) |
| 411 | report_fatal_error(reason: "ESD offset out of range" ); |
| 412 | |
| 413 | // All symbol names are in EBCDIC. |
| 414 | SmallString<256> Name; |
| 415 | ConverterEBCDIC::convertToEBCDIC(Source: Symbol.Name, Result&: Name); |
| 416 | |
| 417 | // Check length here since this number is technically signed but we need uint |
| 418 | // for writing to records. |
| 419 | if (Name.size() >= GOFF::MaxDataLength) |
| 420 | report_fatal_error(reason: "Symbol max name length exceeded" ); |
| 421 | uint16_t NameLength = Name.size(); |
| 422 | |
| 423 | OS.newRecord(Type: GOFF::RT_ESD); |
| 424 | OS.writebe<uint8_t>(Value: Symbol.SymbolType); // Symbol Type |
| 425 | OS.writebe<uint32_t>(Value: Symbol.EsdId); // ESDID |
| 426 | OS.writebe<uint32_t>(Value: Symbol.ParentEsdId); // Parent or Owning ESDID |
| 427 | OS.writebe<uint32_t>(Value: 0); // Reserved |
| 428 | OS.writebe<uint32_t>( |
| 429 | Value: static_cast<uint32_t>(Symbol.Offset)); // Offset or Address |
| 430 | OS.writebe<uint32_t>(Value: 0); // Reserved |
| 431 | OS.writebe<uint32_t>(Value: Symbol.SectionLength); // Length |
| 432 | OS.writebe<uint32_t>(Value: Symbol.EASectionEDEsdId); // Extended Attribute ESDID |
| 433 | OS.writebe<uint32_t>(Value: Symbol.EASectionOffset); // Extended Attribute Offset |
| 434 | OS.writebe<uint32_t>(Value: 0); // Reserved |
| 435 | OS.writebe<uint8_t>(Value: Symbol.NameSpace); // Name Space ID |
| 436 | OS.writebe<uint8_t>(Value: Symbol.SymbolFlags); // Flags |
| 437 | OS.writebe<uint8_t>(Value: Symbol.FillByteValue); // Fill-Byte Value |
| 438 | OS.writebe<uint8_t>(Value: 0); // Reserved |
| 439 | OS.writebe<uint32_t>(Value: Symbol.ADAEsdId); // ADA ESDID |
| 440 | OS.writebe<uint32_t>(Value: Symbol.SortKey); // Sort Priority |
| 441 | OS.writebe<uint64_t>(Value: 0); // Reserved |
| 442 | for (auto F : Symbol.BehavAttrs.Attr) |
| 443 | OS.writebe<uint8_t>(Value: F); // Behavioral Attributes |
| 444 | OS.writebe<uint16_t>(Value: NameLength); // Name Length |
| 445 | OS.write(Ptr: Name.data(), Size: NameLength); // Name |
| 446 | } |
| 447 | |
| 448 | namespace { |
| 449 | /// Adapter stream to write a text section. |
| 450 | class TextStream : public raw_ostream { |
| 451 | /// The underlying GOFFOstream. |
| 452 | GOFFOstream &OS; |
| 453 | |
| 454 | /// The buffer size is the maximum number of bytes in a TXT section. |
| 455 | static constexpr size_t BufferSize = GOFF::MaxDataLength; |
| 456 | |
| 457 | /// Static allocated buffer for the stream, used by the raw_ostream class. The |
| 458 | /// buffer is sized to hold the payload of a logical TXT record. |
| 459 | char Buffer[BufferSize]; |
| 460 | |
| 461 | /// The offset for the next TXT record. This is equal to the number of bytes |
| 462 | /// written. |
| 463 | size_t Offset; |
| 464 | |
| 465 | /// The Esdid of the GOFF section. |
| 466 | const uint32_t EsdId; |
| 467 | |
| 468 | /// The record style. |
| 469 | const GOFF::ESDTextStyle RecordStyle; |
| 470 | |
| 471 | /// See raw_ostream::write_impl. |
| 472 | void write_impl(const char *Ptr, size_t Size) override; |
| 473 | |
| 474 | uint64_t current_pos() const override { return Offset; } |
| 475 | |
| 476 | public: |
| 477 | explicit TextStream(GOFFOstream &OS, uint32_t EsdId, |
| 478 | GOFF::ESDTextStyle RecordStyle) |
| 479 | : OS(OS), Offset(0), EsdId(EsdId), RecordStyle(RecordStyle) { |
| 480 | SetBuffer(BufferStart: Buffer, Size: sizeof(Buffer)); |
| 481 | } |
| 482 | |
| 483 | ~TextStream() override { flush(); } |
| 484 | }; |
| 485 | } // namespace |
| 486 | |
| 487 | void TextStream::write_impl(const char *Ptr, size_t Size) { |
| 488 | size_t WrittenLength = 0; |
| 489 | |
| 490 | // We only have signed 32bits of offset. |
| 491 | if (Offset + Size > std::numeric_limits<int32_t>::max()) |
| 492 | report_fatal_error(reason: "TXT section too large" ); |
| 493 | |
| 494 | while (WrittenLength < Size) { |
| 495 | size_t ToWriteLength = |
| 496 | std::min(a: Size - WrittenLength, b: size_t(GOFF::MaxDataLength)); |
| 497 | |
| 498 | OS.newRecord(Type: GOFF::RT_TXT); |
| 499 | OS.writebe<uint8_t>(Value: GOFF::Flags(4, 4, RecordStyle)); // Text Record Style |
| 500 | OS.writebe<uint32_t>(Value: EsdId); // Element ESDID |
| 501 | OS.writebe<uint32_t>(Value: 0); // Reserved |
| 502 | OS.writebe<uint32_t>(Value: static_cast<uint32_t>(Offset)); // Offset |
| 503 | OS.writebe<uint32_t>(Value: 0); // Text Field True Length |
| 504 | OS.writebe<uint16_t>(Value: 0); // Text Encoding |
| 505 | OS.writebe<uint16_t>(Value: ToWriteLength); // Data Length |
| 506 | OS.write(Ptr: Ptr + WrittenLength, Size: ToWriteLength); // Data |
| 507 | |
| 508 | WrittenLength += ToWriteLength; |
| 509 | Offset += ToWriteLength; |
| 510 | } |
| 511 | } |
| 512 | |
| 513 | void GOFFWriter::writeText(const MCSectionGOFF *Section) { |
| 514 | // A BSS section contains only zeros, no need to write this. |
| 515 | if (Section->isBSS()) |
| 516 | return; |
| 517 | |
| 518 | TextStream S(OS, Section->getOrdinal(), Section->getTextStyle()); |
| 519 | Asm.writeSectionData(OS&: S, Section); |
| 520 | } |
| 521 | |
| 522 | namespace { |
| 523 | // RelocDataItemBuffer provides a static buffer for relocation data items. |
| 524 | class RelocDataItemBuffer { |
| 525 | char Buffer[GOFF::MaxDataLength]; |
| 526 | char *Ptr; |
| 527 | |
| 528 | public: |
| 529 | RelocDataItemBuffer() : Ptr(Buffer) {} |
| 530 | const char *data() { return Buffer; } |
| 531 | size_t size() { return Ptr - Buffer; } |
| 532 | void reset() { Ptr = Buffer; } |
| 533 | bool fits(size_t S) { return size() + S < GOFF::MaxDataLength; } |
| 534 | template <typename T> void writebe(T Val) { |
| 535 | assert(fits(sizeof(T)) && "Out-of-bounds write" ); |
| 536 | support::endian::write<T, llvm::endianness::big>(Ptr, Val); |
| 537 | Ptr += sizeof(T); |
| 538 | } |
| 539 | }; |
| 540 | } // namespace |
| 541 | |
| 542 | void GOFFWriter::writeRelocations() { |
| 543 | // Set the IDs in the relocation entries. |
| 544 | for (auto &RelocEntry : Relocations) { |
| 545 | auto GetRptr = [](const MCSymbolGOFF *Sym) -> uint32_t { |
| 546 | if (Sym->isTemporary()) |
| 547 | return static_cast<MCSectionGOFF &>(Sym->getSection()) |
| 548 | .getBeginSymbol() |
| 549 | ->getIndex(); |
| 550 | return Sym->getIndex(); |
| 551 | }; |
| 552 | |
| 553 | RelocEntry.PEsdId = RelocEntry.Pptr->getOrdinal(); |
| 554 | RelocEntry.REsdId = GetRptr(RelocEntry.Rptr); |
| 555 | } |
| 556 | |
| 557 | // Sort relocation data items by the P pointer to save space. |
| 558 | std::sort( |
| 559 | first: Relocations.begin(), last: Relocations.end(), |
| 560 | comp: [](const GOFFRelocationEntry &Left, const GOFFRelocationEntry &Right) { |
| 561 | return std::tie(args: Left.PEsdId, args: Left.REsdId, args: Left.POffset) < |
| 562 | std::tie(args: Right.PEsdId, args: Right.REsdId, args: Right.POffset); |
| 563 | }); |
| 564 | |
| 565 | // Construct the compressed relocation data items, and write them out. |
| 566 | RelocDataItemBuffer Buffer; |
| 567 | for (auto I = Relocations.begin(), E = Relocations.end(); I != E;) { |
| 568 | Buffer.reset(); |
| 569 | |
| 570 | uint32_t PrevResdId = -1; |
| 571 | uint32_t PrevPesdId = -1; |
| 572 | uint64_t PrevPOffset = -1; |
| 573 | for (; I != E; ++I) { |
| 574 | const GOFFRelocationEntry &Rel = *I; |
| 575 | |
| 576 | bool SameREsdId = (Rel.REsdId == PrevResdId); |
| 577 | bool SamePEsdId = (Rel.PEsdId == PrevPesdId); |
| 578 | bool SamePOffset = (Rel.POffset == PrevPOffset); |
| 579 | bool EightByteOffset = ((Rel.POffset >> 32) & 0xffffffff); |
| 580 | |
| 581 | // Calculate size of relocation data item, and check if it still fits into |
| 582 | // the record. |
| 583 | size_t ItemSize = 8; // Smallest size of a relocation data item. |
| 584 | if (!SameREsdId) |
| 585 | ItemSize += 4; |
| 586 | if (!SamePEsdId) |
| 587 | ItemSize += 4; |
| 588 | if (!SamePOffset) |
| 589 | ItemSize += (EightByteOffset ? 8 : 4); |
| 590 | if (!Buffer.fits(S: ItemSize)) |
| 591 | break; |
| 592 | |
| 593 | GOFF::Flags RelocFlags[6]; |
| 594 | RelocFlags[0].set(BitIndex: 0, Length: 1, NewValue: SameREsdId); |
| 595 | RelocFlags[0].set(BitIndex: 1, Length: 1, NewValue: SamePEsdId); |
| 596 | RelocFlags[0].set(BitIndex: 2, Length: 1, NewValue: SamePOffset); |
| 597 | RelocFlags[0].set(BitIndex: 6, Length: 1, NewValue: EightByteOffset); |
| 598 | |
| 599 | RelocFlags[1].set(BitIndex: 0, Length: 4, NewValue: Rel.ReferenceType); |
| 600 | RelocFlags[1].set(BitIndex: 4, Length: 4, NewValue: Rel.ReferentType); |
| 601 | |
| 602 | RelocFlags[2].set(BitIndex: 0, Length: 7, NewValue: Rel.Action); |
| 603 | RelocFlags[2].set(BitIndex: 7, Length: 1, NewValue: Rel.FetchStore); |
| 604 | |
| 605 | RelocFlags[4].set(BitIndex: 0, Length: 8, NewValue: Rel.TargetLength); |
| 606 | |
| 607 | for (auto F : RelocFlags) |
| 608 | Buffer.writebe<uint8_t>(Val: F); |
| 609 | Buffer.writebe<uint16_t>(Val: 0); // Reserved. |
| 610 | if (!SameREsdId) |
| 611 | Buffer.writebe<uint32_t>(Val: Rel.REsdId); |
| 612 | if (!SamePEsdId) |
| 613 | Buffer.writebe<uint32_t>(Val: Rel.PEsdId); |
| 614 | if (!SamePOffset) { |
| 615 | if (EightByteOffset) |
| 616 | Buffer.writebe<uint64_t>(Val: Rel.POffset); |
| 617 | else |
| 618 | Buffer.writebe<uint32_t>(Val: Rel.POffset); |
| 619 | } |
| 620 | |
| 621 | PrevResdId = Rel.REsdId; |
| 622 | PrevPesdId = Rel.PEsdId; |
| 623 | PrevPOffset = Rel.POffset; |
| 624 | } |
| 625 | |
| 626 | OS.newRecord(Type: GOFF::RT_RLD); |
| 627 | OS.writebe<uint8_t>(Value: 0); // Reserved. |
| 628 | OS.writebe<uint16_t>(Value: Buffer.size()); // Length (of the relocation data). |
| 629 | OS.write(Ptr: Buffer.data(), Size: Buffer.size()); // Relocation Directory Data Items. |
| 630 | } |
| 631 | } |
| 632 | |
| 633 | void GOFFWriter::writeEnd() { |
| 634 | uint8_t F = GOFF::END_EPR_None; |
| 635 | uint8_t AMODE = 0; |
| 636 | uint32_t ESDID = 0; |
| 637 | |
| 638 | // TODO Set Flags/AMODE/ESDID for entry point. |
| 639 | |
| 640 | OS.newRecord(Type: GOFF::RT_END); |
| 641 | OS.writebe<uint8_t>(Value: GOFF::Flags(6, 2, F)); // Indicator flags |
| 642 | OS.writebe<uint8_t>(Value: AMODE); // AMODE |
| 643 | OS.write_zeros(NumZeros: 3); // Reserved |
| 644 | // The record count is the number of logical records. In principle, this value |
| 645 | // is available as OS.logicalRecords(). However, some tools rely on this field |
| 646 | // being zero. |
| 647 | OS.writebe<uint32_t>(Value: 0); // Record Count |
| 648 | OS.writebe<uint32_t>(Value: ESDID); // ESDID (of entry point) |
| 649 | } |
| 650 | |
| 651 | uint64_t GOFFWriter::writeObject() { |
| 652 | writeHeader(); |
| 653 | |
| 654 | defineSymbols(); |
| 655 | |
| 656 | for (const MCSection &Section : Asm) |
| 657 | writeText(Section: static_cast<const MCSectionGOFF *>(&Section)); |
| 658 | |
| 659 | writeRelocations(); |
| 660 | |
| 661 | writeEnd(); |
| 662 | |
| 663 | // Make sure all records are written. |
| 664 | OS.finalizeRecord(); |
| 665 | |
| 666 | LLVM_DEBUG(dbgs() << "Wrote " << OS.getNumLogicalRecords() |
| 667 | << " logical records." ); |
| 668 | |
| 669 | return OS.getWrittenSize(); |
| 670 | } |
| 671 | |
| 672 | GOFFObjectWriter::GOFFObjectWriter( |
| 673 | std::unique_ptr<MCGOFFObjectTargetWriter> MOTW, raw_pwrite_stream &OS) |
| 674 | : TargetObjectWriter(std::move(MOTW)), OS(OS) {} |
| 675 | |
| 676 | GOFFObjectWriter::~GOFFObjectWriter() = default; |
| 677 | |
| 678 | void GOFFObjectWriter::recordRelocation(const MCFragment &F, |
| 679 | const MCFixup &Fixup, MCValue Target, |
| 680 | uint64_t &FixedValue) { |
| 681 | const MCFixupKindInfo &FKI = |
| 682 | Asm->getBackend().getFixupKindInfo(Kind: Fixup.getKind()); |
| 683 | const uint32_t Length = FKI.TargetSize / 8; |
| 684 | assert(FKI.TargetSize % 8 == 0 && "Target Size not multiple of 8" ); |
| 685 | const uint64_t FixupOffset = Asm->getFragmentOffset(F) + Fixup.getOffset(); |
| 686 | |
| 687 | unsigned RelocType = TargetObjectWriter->getRelocType(Target, Fixup); |
| 688 | |
| 689 | const MCSectionGOFF *PSection = static_cast<MCSectionGOFF *>(F.getParent()); |
| 690 | const auto &A = *static_cast<const MCSymbolGOFF *>(Target.getAddSym()); |
| 691 | const MCSymbolGOFF *B = static_cast<const MCSymbolGOFF *>(Target.getSubSym()); |
| 692 | if (RelocType == MCGOFFObjectTargetWriter::Reloc_Type_RICon) { |
| 693 | if (A.isUndefined()) { |
| 694 | Asm->reportError( |
| 695 | L: Fixup.getLoc(), |
| 696 | Msg: Twine("symbol " ) |
| 697 | .concat(Suffix: A.getName()) |
| 698 | .concat(Suffix: " must be defined for a relative immediate relocation" )); |
| 699 | return; |
| 700 | } |
| 701 | if (&A.getSection() != PSection) { |
| 702 | Asm->reportError(L: Fixup.getLoc(), |
| 703 | Msg: Twine("relative immediate relocation section mismatch: " ) |
| 704 | .concat(Suffix: A.getSection().getName()) |
| 705 | .concat(Suffix: " of symbol " ) |
| 706 | .concat(Suffix: A.getName()) |
| 707 | .concat(Suffix: " <-> " ) |
| 708 | .concat(Suffix: PSection->getName())); |
| 709 | return; |
| 710 | } |
| 711 | if (B) { |
| 712 | Asm->reportError( |
| 713 | L: Fixup.getLoc(), |
| 714 | Msg: Twine("subtractive symbol " ) |
| 715 | .concat(Suffix: B->getName()) |
| 716 | .concat(Suffix: " not supported for a relative immediate relocation" )); |
| 717 | return; |
| 718 | } |
| 719 | FixedValue = Asm->getSymbolOffset(S: A) - FixupOffset + Target.getConstant(); |
| 720 | return; |
| 721 | } |
| 722 | FixedValue = Target.getConstant(); |
| 723 | |
| 724 | // The symbol only has a section-relative offset if it is a temporary symbol. |
| 725 | FixedValue += A.isTemporary() ? Asm->getSymbolOffset(S: A) : 0; |
| 726 | A.setUsedInReloc(); |
| 727 | if (B) { |
| 728 | FixedValue -= B->isTemporary() ? Asm->getSymbolOffset(S: *B) : 0; |
| 729 | B->setUsedInReloc(); |
| 730 | } |
| 731 | |
| 732 | // UseQCon causes class offsets versus absolute addresses to be used. This |
| 733 | // is analogous to using QCONs in older OBJ object file format. |
| 734 | bool UseQCon = RelocType == MCGOFFObjectTargetWriter::Reloc_Type_QCon; |
| 735 | |
| 736 | GOFF::RLDFetchStore FetchStore = |
| 737 | (RelocType == MCGOFFObjectTargetWriter::Reloc_Type_RCon || |
| 738 | RelocType == MCGOFFObjectTargetWriter::Reloc_Type_VCon) |
| 739 | ? GOFF::RLDFetchStore::RLD_FS_Store |
| 740 | : GOFF::RLDFetchStore::RLD_FS_Fetch; |
| 741 | assert((FetchStore == GOFF::RLDFetchStore::RLD_FS_Fetch || B == nullptr) && |
| 742 | "No dependent relocations expected" ); |
| 743 | |
| 744 | enum GOFF::RLDReferenceType ReferenceType = GOFF::RLD_RT_RAddress; |
| 745 | enum GOFF::RLDReferentType ReferentType = GOFF::RLD_RO_Label; |
| 746 | if (UseQCon) { |
| 747 | ReferenceType = GOFF::RLD_RT_ROffset; |
| 748 | ReferentType = GOFF::RLD_RO_Class; |
| 749 | } |
| 750 | if (RelocType == MCGOFFObjectTargetWriter::Reloc_Type_RCon) |
| 751 | ReferenceType = GOFF::RLD_RT_RTypeConstant; |
| 752 | |
| 753 | auto DumpReloc = [&PSection, &ReferenceType, &FixupOffset, |
| 754 | &FixedValue](const char *N, const MCSymbolGOFF *Sym) { |
| 755 | const char *Con; |
| 756 | switch (ReferenceType) { |
| 757 | case GOFF::RLDReferenceType::RLD_RT_RAddress: |
| 758 | Con = "ACon" ; |
| 759 | break; |
| 760 | case GOFF::RLDReferenceType::RLD_RT_ROffset: |
| 761 | Con = "QCon" ; |
| 762 | break; |
| 763 | case GOFF::RLDReferenceType::RLD_RT_RTypeConstant: |
| 764 | Con = "VCon" ; |
| 765 | break; |
| 766 | default: |
| 767 | Con = "(unknown)" ; |
| 768 | } |
| 769 | dbgs() << "Reloc " << N << ": " << Con << " Rptr: " << Sym->getName() |
| 770 | << " Pptr: " << PSection->getName() << " Offset: " << FixupOffset |
| 771 | << " Fixed Imm: " << FixedValue << "\n" ; |
| 772 | }; |
| 773 | (void)DumpReloc; |
| 774 | |
| 775 | // Save relocation data for later writing. |
| 776 | LLVM_DEBUG(DumpReloc("A" , &A)); |
| 777 | Relocations.emplace_back(args&: PSection, args: &A, args&: ReferenceType, args&: ReferentType, |
| 778 | args: GOFF::RLD_ACT_Add, args&: FetchStore, args: FixupOffset, args: Length); |
| 779 | if (B) { |
| 780 | LLVM_DEBUG(DumpReloc("B" , B)); |
| 781 | Relocations.emplace_back( |
| 782 | args&: PSection, args&: B, args&: ReferenceType, args&: ReferentType, args: GOFF::RLD_ACT_Subtract, |
| 783 | args: GOFF::RLDFetchStore::RLD_FS_Fetch, args: FixupOffset, args: Length); |
| 784 | } |
| 785 | } |
| 786 | |
| 787 | uint64_t GOFFObjectWriter::writeObject() { |
| 788 | uint64_t Size = GOFFWriter(OS, *Asm, RootSD, Relocations).writeObject(); |
| 789 | return Size; |
| 790 | } |
| 791 | |
| 792 | std::unique_ptr<MCObjectWriter> |
| 793 | llvm::createGOFFObjectWriter(std::unique_ptr<MCGOFFObjectTargetWriter> MOTW, |
| 794 | raw_pwrite_stream &OS) { |
| 795 | return std::make_unique<GOFFObjectWriter>(args: std::move(MOTW), args&: OS); |
| 796 | } |
| 797 | |