1//===- GOFFObjectFile.cpp - GOFF object file implementation -----*- C++ -*-===//
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// Implementation of the GOFFObjectFile class.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/Object/GOFFObjectFile.h"
14#include "llvm/BinaryFormat/GOFF.h"
15#include "llvm/Object/GOFF.h"
16#include "llvm/Support/DataExtractor.h"
17#include "llvm/Support/Debug.h"
18#include "llvm/Support/Errc.h"
19#include "llvm/Support/FormatVariadic.h"
20#include "llvm/Support/raw_ostream.h"
21
22#ifndef DEBUG_TYPE
23#define DEBUG_TYPE "goff"
24#endif
25
26using namespace llvm::object;
27using namespace llvm;
28
29// Return the type of the record.
30static GOFF::RecordType getRecordType(const uint8_t *PhysicalRecord) {
31 return GOFF::RecordType((PhysicalRecord[1] & 0xF0) >> 4);
32}
33
34// Return true if the record is a continuation record.
35static bool isContinuation(const uint8_t *PhysicalRecord) {
36 return PhysicalRecord[1] & 0x02;
37}
38
39// Return true if the record has a continuation.
40static bool isContinued(const uint8_t *PhysicalRecord) {
41 return PhysicalRecord[1] & 0x01;
42}
43
44// Helper function to get continuous data from a logical record
45// Includes PTV header + everything from first record + continuation payloads
46// Returns the number of physical records consumed (including the initial
47// record)
48Expected<unsigned>
49GOFFObjectFile::getContinuousData(SmallVectorImpl<uint8_t> &CompleteData,
50 int DataIndex, uint16_t DataLength,
51 const uint8_t *Record) const {
52
53 CompleteData.reserve(N: DataLength + GOFF::RecordLength - DataIndex);
54
55 // First record - include PTV header (bytes 0-2)
56 CompleteData.append(in_start: Record, in_end: Record + GOFF::RecordPrefixLength);
57 // Append everything from the first record before the start of the data.
58 CompleteData.append(in_start: Record + GOFF::RecordPrefixLength, in_end: Record + DataIndex);
59 // Append the data.
60 const uint8_t *Ptr = Record + DataIndex;
61 size_t SliceLength = std::min(
62 a: DataLength, b: static_cast<uint16_t>(GOFF::RecordLength - DataIndex));
63 CompleteData.append(in_start: Ptr, in_end: Ptr + SliceLength);
64 DataLength -= SliceLength;
65 Ptr += SliceLength;
66
67 unsigned BlocksConsumed = 1; // Count the initial record
68 // Continuation records.
69 while (DataLength > 0) {
70 // Ptr now points to the start of the next physical record.
71 // Check that this block is a Continuation.
72 assert(isContinuation(Ptr) && "Continuation bit must be set");
73 // Check that the last Continuation is terminated correctly.
74 if (DataLength <= GOFF::PayloadLength && isContinued(PhysicalRecord: Ptr))
75 return createStringError(EC: object_error::parse_failed,
76 S: "continued bit should not be set");
77
78 SliceLength =
79 std::min(a: DataLength, b: static_cast<uint16_t>(GOFF::PayloadLength));
80 Ptr += GOFF::RecordPrefixLength; // Skip the 3-byte prefix
81 CompleteData.append(in_start: Ptr, in_end: Ptr + SliceLength);
82 DataLength -= SliceLength;
83 // Advance to the start of the next record
84 Ptr += (GOFF::RecordLength - GOFF::RecordPrefixLength);
85 BlocksConsumed++;
86 }
87 return BlocksConsumed;
88}
89
90// Walk over the object file and populate FlattenedData.
91Error GOFFObjectFile::createFlattenedData() {
92 const uint8_t *It = base();
93 const uint8_t *End = base() + getData().size();
94
95 // First pass: validate continuation records.
96 const uint8_t *ValidateIt = It;
97 unsigned ValidateIndex = 0;
98 bool PrevContinued = false;
99 bool PrevWasContinuation = false;
100 GOFF::RecordType PrevRecordType = GOFF::RT_HDR;
101
102 while (ValidateIt < End) {
103 bool IsCont = isContinuation(PhysicalRecord: ValidateIt);
104 bool IsContd = isContinued(PhysicalRecord: ValidateIt);
105 GOFF::RecordType CurrentType = ::getRecordType(PhysicalRecord: ValidateIt);
106
107 if (IsCont) {
108 // Continuation record must be preceded by a continued record.
109 if (!PrevContinued) {
110 return createStringError(EC: object_error::parse_failed,
111 S: "record " + std::to_string(val: ValidateIndex) +
112 " is a continuation record that is not "
113 "preceded by a continued record");
114 }
115 // Continuation record type must match previous record type.
116 if (CurrentType != PrevRecordType) {
117 return createStringError(
118 EC: object_error::parse_failed,
119 S: "record " + std::to_string(val: ValidateIndex) +
120 " is a continuation record that does not match "
121 "the type of the previous record");
122 }
123 // Update PrevContinued for continuation records.
124 PrevContinued = IsContd;
125 } else {
126 // Check if previous non-continuation was marked as continued.
127 if (PrevContinued && !PrevWasContinuation) {
128 return createStringError(EC: object_error::parse_failed,
129 S: "record " + std::to_string(val: ValidateIndex) +
130 " is not a continuation record but the "
131 "preceding record is continued");
132 }
133 PrevRecordType = CurrentType;
134 PrevContinued = IsContd;
135 }
136
137 PrevWasContinuation = IsCont;
138 ValidateIt += GOFF::RecordLength;
139 ValidateIndex++;
140 }
141
142 // Second pass: process records now that we know they're valid.
143 while (It < End) {
144 // Skip continuation records - only process first physical record of each
145 // logical record.
146 if (isContinuation(PhysicalRecord: It)) {
147 It += GOFF::RecordLength;
148 continue;
149 }
150
151 GOFF::RecordType RecordType = ::getRecordType(PhysicalRecord: It);
152
153 // Call get continuous data based on record type.
154 int DataIndex = 0;
155 uint16_t DataLength = 0;
156 ArrayRef<uint8_t> Slice(It, GOFF::RecordLength);
157 DataExtractor DE(Slice, false);
158
159 switch (RecordType) {
160 case GOFF::RT_ESD: {
161 DataIndex = 72;
162 uint64_t Offset = 70;
163 DataLength = DE.getU16(offset_ptr: &Offset);
164 break;
165 }
166 case GOFF::RT_TXT: {
167 DataIndex = 24;
168 uint64_t Offset = 22;
169 DataLength = DE.getU16(offset_ptr: &Offset);
170 break;
171 }
172 case GOFF::RT_RLD: {
173 DataIndex = 6;
174 uint64_t Offset = 4;
175 DataLength = DE.getU16(offset_ptr: &Offset);
176 break;
177 }
178 case GOFF::RT_LEN: {
179 DataIndex = 8;
180 uint64_t Offset = 6;
181 DataLength = DE.getU16(offset_ptr: &Offset);
182 break;
183 }
184 case GOFF::RT_END: {
185 DataIndex = 26;
186 uint64_t Offset = 24;
187 DataLength = DE.getU16(offset_ptr: &Offset);
188 break;
189 }
190 case GOFF::RT_HDR: {
191 DataIndex = 60;
192 uint64_t Offset = 52;
193 DataLength = DE.getU16(offset_ptr: &Offset);
194 break;
195 }
196 }
197 // Get the flattened data for this logical record (including continuations).
198 SmallVector<uint8_t> CompleteData;
199 Expected<unsigned> BlocksConsumed =
200 getContinuousData(CompleteData, DataIndex, DataLength, Record: It);
201 if (!BlocksConsumed) {
202 // Log the error but don't fail construction - errors in continuation
203 // data will be caught when the data is actually accessed.
204 llvm::handleAllErrors(
205 E: BlocksConsumed.takeError(), Handlers: [](const llvm::ErrorInfoBase &EIB) {
206 llvm::errs() << "ERROR: " << EIB.message() << "\n";
207 });
208 // Skip this record and continue.
209 It += GOFF::RecordLength;
210 continue;
211 }
212 FlattenedData.push_back(Elt: {RecordType, std::move(CompleteData)});
213
214 // Move to next logical record using the number of blocks consumed.
215 It += (*BlocksConsumed) * GOFF::RecordLength;
216 }
217 return Error::success();
218}
219
220Expected<std::unique_ptr<ObjectFile>>
221ObjectFile::createGOFFObjectFile(MemoryBufferRef Object) {
222 Error Err = Error::success();
223 std::unique_ptr<GOFFObjectFile> Ret(new GOFFObjectFile(Object, Err));
224 if (Err)
225 return std::move(Err);
226 return std::move(Ret);
227}
228
229GOFFObjectFile::GOFFObjectFile(MemoryBufferRef Object, Error &Err)
230 : ObjectFile(Binary::ID_GOFF, Object) {
231 ErrorAsOutParameter ErrAsOutParam(Err);
232 // Object file isn't the right size, bail out early.
233 if ((Object.getBufferSize() % GOFF::RecordLength) != 0) {
234 Err = createStringError(
235 EC: object_error::unexpected_eof,
236 S: "object file is not the right size. Must be a multiple "
237 "of 80 bytes, but is " +
238 std::to_string(val: Object.getBufferSize()) + " bytes");
239 return;
240 }
241 // Object file doesn't start/end with HDR/END records.
242 // Bail out early.
243 if (Object.getBufferSize() != 0) {
244 if ((base()[1] & 0xF0) >> 4 != GOFF::RT_HDR) {
245 Err = createStringError(EC: object_error::parse_failed,
246 S: "object file must start with HDR record");
247 return;
248 }
249 if ((base()[Object.getBufferSize() - GOFF::RecordLength + 1] & 0xF0) >> 4 !=
250 GOFF::RT_END) {
251 Err = createStringError(EC: object_error::parse_failed,
252 S: "object file must end with END record");
253 return;
254 }
255 }
256
257 if (Error E = createFlattenedData()) {
258 Err = std::move(E);
259 return;
260 }
261
262 SectionEntryImpl DummySection;
263 SectionList.emplace_back(Args&: DummySection); // Dummy entry at index 0.
264
265 // Dummy relocation entry at index 0.
266 GOFFRelEntry DummyRelEntry;
267 DummyRelEntry.PEsdId = 0;
268 RelEntries.emplace_back(Args&: DummyRelEntry);
269
270 for (const auto &[RecordType, Data] : FlattenedData) {
271 const uint8_t *I = Data.data();
272 switch (RecordType) {
273 case GOFF::RT_ESD: {
274 // Save ESD record.
275 uint32_t EsdId;
276 ESDRecord::getEsdId(Record: I, EsdId);
277 EsdPtrs.grow(N: EsdId);
278 EsdPtrs[EsdId] = I;
279
280 // Determine and save the "sections" in GOFF.
281 // A section is saved as a tuple of the form
282 // case (1): (ED,child PR)
283 // - where the PR must have non-zero length.
284 // case (2a) (ED,0)
285 // - where the ED is of non-zero length.
286 // case (2b) (ED,0)
287 // - where the ED is zero length but
288 // contains a label (LD).
289 GOFF::ESDSymbolType SymbolType;
290 ESDRecord::getSymbolType(Record: I, SymbolType);
291 SectionEntryImpl Section;
292 uint32_t Length;
293 ESDRecord::getLength(Record: I, Length);
294 if (SymbolType == GOFF::ESD_ST_ElementDefinition) {
295 // case (2a)
296 if (Length != 0) {
297 Section.d.a = EsdId;
298 SectionList.emplace_back(Args&: Section);
299 }
300 } else if (SymbolType == GOFF::ESD_ST_PartReference) {
301 // case (1)
302 if (Length != 0) {
303 uint32_t SymEdId;
304 ESDRecord::getParentEsdId(Record: I, EsdId&: SymEdId);
305 Section.d.a = SymEdId;
306 Section.d.b = EsdId;
307 SectionList.emplace_back(Args&: Section);
308 }
309 } else if (SymbolType == GOFF::ESD_ST_LabelDefinition) {
310 // case (2b)
311 uint32_t SymEdId;
312 ESDRecord::getParentEsdId(Record: I, EsdId&: SymEdId);
313 const uint8_t *SymEdRecord = EsdPtrs[SymEdId];
314 uint32_t EdLength;
315 ESDRecord::getLength(Record: SymEdRecord, Length&: EdLength);
316 if (!EdLength) { // [ EDID, PRID ]
317 // LD child of a zero length parent ED.
318 // Add the section ED which was previously ignored.
319 Section.d.a = SymEdId;
320 SectionList.emplace_back(Args&: Section);
321 }
322 }
323 LLVM_DEBUG(dbgs() << " -- ESD " << EsdId << "\n");
324 break;
325 }
326 case GOFF::RT_TXT:
327 // Save TXT records.
328 TextPtrs.emplace_back(Args&: I);
329 LLVM_DEBUG(dbgs() << " -- TXT\n");
330 break;
331 case GOFF::RT_RLD:
332 setRelocationData(I);
333 LLVM_DEBUG(dbgs() << " -- RLD\n");
334 break;
335 case GOFF::RT_LEN:
336 LLVM_DEBUG(dbgs() << " -- LEN (GOFF record type) unhandled\n");
337 break;
338 case GOFF::RT_END:
339 LLVM_DEBUG(dbgs() << " -- END (GOFF record type) unhandled\n");
340 break;
341 case GOFF::RT_HDR:
342 LLVM_DEBUG(dbgs() << " -- HDR (GOFF record type) unhandled\n");
343 break;
344 }
345 }
346}
347
348const uint8_t *GOFFObjectFile::getSymbolEsdRecord(DataRefImpl Symb) const {
349 const uint8_t *EsdRecord = EsdPtrs[Symb.d.a];
350 return EsdRecord;
351}
352
353Expected<StringRef> GOFFObjectFile::getSymbolName(DataRefImpl Symb) const {
354 if (auto It = EsdNamesCache.find(Val: Symb.d.a); It != EsdNamesCache.end()) {
355 auto &StrPtr = It->second;
356 return StringRef(StrPtr.second.get(), StrPtr.first);
357 }
358
359 // Get the ESD record pointer from EsdPtrs (points to FlattenedData)
360 const uint8_t *EsdRecord = getSymbolEsdRecord(Symb);
361 // Extract name from the flattened ESD record
362 // Name length is at byte 70-71, name data starts at byte 72
363 uint16_t NameLength = ESDRecord::getNameLength(Record: EsdRecord);
364 SmallString<256> SymbolName;
365 if (NameLength > 0) {
366 // Name starts at byte 72 in the record (already flattened, no
367 // continuations)
368 const uint8_t *NameStart = EsdRecord + 72;
369 SymbolName.append(in_start: NameStart, in_end: NameStart + NameLength);
370 }
371
372 SmallString<256> SymbolNameConverted;
373 ConverterEBCDIC::convertToUTF8(Source: SymbolName, Result&: SymbolNameConverted);
374
375 size_t Size = SymbolNameConverted.size();
376 auto StrPtr = std::make_pair(x&: Size, y: std::make_unique<char[]>(num: Size));
377 char *Buf = StrPtr.second.get();
378 memcpy(dest: Buf, src: SymbolNameConverted.data(), n: Size);
379 EsdNamesCache[Symb.d.a] = std::move(StrPtr);
380 return StringRef(Buf, Size);
381}
382
383Expected<StringRef> GOFFObjectFile::getSymbolName(SymbolRef Symbol) const {
384 return getSymbolName(Symb: Symbol.getRawDataRefImpl());
385}
386
387Expected<uint64_t> GOFFObjectFile::getSymbolAddress(DataRefImpl Symb) const {
388 uint32_t Offset;
389 const uint8_t *EsdRecord = getSymbolEsdRecord(Symb);
390 ESDRecord::getOffset(Record: EsdRecord, Offset);
391 return static_cast<uint64_t>(Offset);
392}
393
394uint64_t GOFFObjectFile::getSymbolValueImpl(DataRefImpl Symb) const {
395 uint32_t Offset;
396 const uint8_t *EsdRecord = getSymbolEsdRecord(Symb);
397 ESDRecord::getOffset(Record: EsdRecord, Offset);
398 return static_cast<uint64_t>(Offset);
399}
400
401uint64_t GOFFObjectFile::getCommonSymbolSizeImpl(DataRefImpl Symb) const {
402 return 0;
403}
404
405bool GOFFObjectFile::isSymbolUnresolved(DataRefImpl Symb) const {
406 const uint8_t *Record = getSymbolEsdRecord(Symb);
407 GOFF::ESDSymbolType SymbolType;
408 ESDRecord::getSymbolType(Record, SymbolType);
409
410 if (SymbolType == GOFF::ESD_ST_ExternalReference)
411 return true;
412 if (SymbolType == GOFF::ESD_ST_PartReference) {
413 uint32_t Length;
414 ESDRecord::getLength(Record, Length);
415 if (Length == 0)
416 return true;
417 }
418 return false;
419}
420
421bool GOFFObjectFile::isSymbolIndirect(DataRefImpl Symb) const {
422 const uint8_t *Record = getSymbolEsdRecord(Symb);
423 bool Indirect;
424 ESDRecord::getIndirectReference(Record, Indirect);
425 return Indirect;
426}
427
428Expected<uint32_t> GOFFObjectFile::getSymbolFlags(DataRefImpl Symb) const {
429 uint32_t Flags = 0;
430 if (isSymbolUnresolved(Symb))
431 Flags |= SymbolRef::SF_Undefined;
432
433 const uint8_t *Record = getSymbolEsdRecord(Symb);
434
435 GOFF::ESDBindingStrength BindingStrength;
436 ESDRecord::getBindingStrength(Record, Strength&: BindingStrength);
437 if (BindingStrength == GOFF::ESD_BST_Weak)
438 Flags |= SymbolRef::SF_Weak;
439
440 GOFF::ESDBindingScope BindingScope;
441 ESDRecord::getBindingScope(Record, Scope&: BindingScope);
442
443 GOFF::ESDSymbolType Type;
444 ESDRecord::getSymbolType(Record, SymbolType&: Type);
445
446 if (Type != GOFF::ESD_ST_SectionDefinition &&
447 Type != GOFF::ESD_ST_ElementDefinition &&
448 BindingScope != GOFF::ESD_BSC_Section &&
449 BindingScope != GOFF::ESD_BSC_Module) {
450 Expected<StringRef> Name = getSymbolName(Symb);
451 if (Name && *Name != " ") { // Blank name is local.
452 Flags |= SymbolRef::SF_Global;
453 if (BindingScope == GOFF::ESD_BSC_ImportExport)
454 Flags |= SymbolRef::SF_Exported;
455 else if (!(Flags & SymbolRef::SF_Undefined))
456 Flags |= SymbolRef::SF_Hidden;
457 }
458 }
459
460 return Flags;
461}
462
463Expected<SymbolRef::Type>
464GOFFObjectFile::getSymbolType(DataRefImpl Symb) const {
465 const uint8_t *Record = getSymbolEsdRecord(Symb);
466 GOFF::ESDSymbolType SymbolType;
467 ESDRecord::getSymbolType(Record, SymbolType);
468 GOFF::ESDExecutable Executable;
469 ESDRecord::getExecutable(Record, Executable);
470
471 if (SymbolType != GOFF::ESD_ST_SectionDefinition &&
472 SymbolType != GOFF::ESD_ST_ElementDefinition &&
473 SymbolType != GOFF::ESD_ST_LabelDefinition &&
474 SymbolType != GOFF::ESD_ST_PartReference &&
475 SymbolType != GOFF::ESD_ST_ExternalReference) {
476 uint32_t EsdId;
477 ESDRecord::getEsdId(Record, EsdId);
478 return createStringError(EC: llvm::errc::invalid_argument,
479 Fmt: "ESD record %" PRIu32
480 " has invalid symbol type 0x%02" PRIX8,
481 Vals: EsdId, Vals: SymbolType);
482 }
483 switch (SymbolType) {
484 case GOFF::ESD_ST_SectionDefinition:
485 case GOFF::ESD_ST_ElementDefinition:
486 return SymbolRef::ST_Other;
487 case GOFF::ESD_ST_LabelDefinition:
488 case GOFF::ESD_ST_PartReference:
489 case GOFF::ESD_ST_ExternalReference:
490 if (Executable != GOFF::ESD_EXE_CODE && Executable != GOFF::ESD_EXE_DATA &&
491 Executable != GOFF::ESD_EXE_Unspecified) {
492 uint32_t EsdId;
493 ESDRecord::getEsdId(Record, EsdId);
494 return createStringError(EC: llvm::errc::invalid_argument,
495 Fmt: "ESD record %" PRIu32
496 " has unknown Executable type 0x%02X",
497 Vals: EsdId, Vals: Executable);
498 }
499 switch (Executable) {
500 case GOFF::ESD_EXE_CODE:
501 return SymbolRef::ST_Function;
502 case GOFF::ESD_EXE_DATA:
503 return SymbolRef::ST_Data;
504 case GOFF::ESD_EXE_Unspecified:
505 return SymbolRef::ST_Unknown;
506 }
507 llvm_unreachable("Unhandled ESDExecutable");
508 }
509 llvm_unreachable("Unhandled ESDSymbolType");
510}
511
512Expected<section_iterator>
513GOFFObjectFile::getSymbolSection(DataRefImpl Symb) const {
514 DataRefImpl Sec;
515
516 if (isSymbolUnresolved(Symb))
517 return section_iterator(SectionRef(Sec, this));
518
519 const uint8_t *SymEsdRecord = EsdPtrs[Symb.d.a];
520 uint32_t SymEdId;
521 ESDRecord::getParentEsdId(Record: SymEsdRecord, EsdId&: SymEdId);
522 const uint8_t *SymEdRecord = EsdPtrs[SymEdId];
523
524 for (size_t I = 0, E = SectionList.size(); I < E; ++I) {
525 bool Found;
526 const uint8_t *SectionPrRecord = getSectionPrEsdRecord(SectionIndex: I);
527 if (SectionPrRecord) {
528 Found = SymEsdRecord == SectionPrRecord;
529 } else {
530 const uint8_t *SectionEdRecord = getSectionEdEsdRecord(SectionIndex: I);
531 Found = SymEdRecord == SectionEdRecord;
532 }
533
534 if (Found) {
535 Sec.d.a = I;
536 return section_iterator(SectionRef(Sec, this));
537 }
538 }
539 return createStringError(EC: llvm::errc::invalid_argument,
540 S: "symbol with ESD id " + std::to_string(val: Symb.d.a) +
541 " refers to invalid section with ESD id " +
542 std::to_string(val: SymEdId));
543}
544
545uint32_t GOFFObjectFile::getZOSSymbolArchiveAttributes(DataRefImpl Symb) const {
546 const uint8_t *SymRecord = getSymbolEsdRecord(Symb);
547 uint32_t Attrs = 0;
548
549 // Bit 2 (0x4): 64-bit AMODE. If the child AMODE is unspecified,
550 // query the parent ED.
551 // TODO: The parent-walk path (child ESD_AMODE_None with a parent that has
552 // ESD_AMODE_64) cannot currently be tested as GOFFObjectWriter always emits
553 // ESD_AMODE_64 directly on LD/ER records and does not set AMODE on ED
554 // records. Full coverage requires yaml2obj GOFF ESD record support.
555 GOFF::ESDAmode Amode;
556 ESDRecord::getAmode(Record: SymRecord, Amode);
557 if (Amode == GOFF::ESD_AMODE_None) {
558 uint32_t ParentEsdId;
559 ESDRecord::getParentEsdId(Record: SymRecord, EsdId&: ParentEsdId);
560 if (ParentEsdId) {
561 const uint8_t *EdRecord = EsdPtrs[ParentEsdId];
562 ESDRecord::getAmode(Record: EdRecord, Amode);
563 }
564 }
565 if (Amode == GOFF::ESD_AMODE_64)
566 Attrs |= 0x4;
567
568 // Bit 1 (0x2): XPLink — LinkageType is ESD_LT_XPLink.
569 GOFF::ESDLinkageType LinkageType;
570 ESDRecord::getLinkageType(Record: SymRecord, Type&: LinkageType);
571 if (LinkageType == GOFF::ESD_LT_XPLink)
572 Attrs |= 0x2;
573
574 // Bit 0 (0x1): Writable Static Area.
575 GOFF::ESDNameSpaceId NameSpace;
576 ESDRecord::getNameSpaceId(Record: SymRecord, Id&: NameSpace);
577 if (NameSpace == GOFF::ESD_NS_Parts)
578 Attrs |= 0x1;
579
580 return Attrs;
581}
582
583uint64_t GOFFObjectFile::getSymbolSize(DataRefImpl Symb) const {
584 const uint8_t *Record = getSymbolEsdRecord(Symb);
585 uint32_t Length;
586 ESDRecord::getLength(Record, Length);
587 return Length;
588}
589
590const uint8_t *GOFFObjectFile::getSectionEdEsdRecord(DataRefImpl &Sec) const {
591 SectionEntryImpl EsdIds = SectionList[Sec.d.a];
592 const uint8_t *EsdRecord = EsdPtrs[EsdIds.d.a];
593 return EsdRecord;
594}
595
596const uint8_t *GOFFObjectFile::getSectionPrEsdRecord(DataRefImpl &Sec) const {
597 SectionEntryImpl EsdIds = SectionList[Sec.d.a];
598 const uint8_t *EsdRecord = nullptr;
599 if (EsdIds.d.b)
600 EsdRecord = EsdPtrs[EsdIds.d.b];
601 return EsdRecord;
602}
603
604const uint8_t *
605GOFFObjectFile::getSectionEdEsdRecord(uint32_t SectionIndex) const {
606 DataRefImpl Sec;
607 Sec.d.a = SectionIndex;
608 const uint8_t *EsdRecord = getSectionEdEsdRecord(Sec);
609 return EsdRecord;
610}
611
612const uint8_t *
613GOFFObjectFile::getSectionPrEsdRecord(uint32_t SectionIndex) const {
614 DataRefImpl Sec;
615 Sec.d.a = SectionIndex;
616 const uint8_t *EsdRecord = getSectionPrEsdRecord(Sec);
617 return EsdRecord;
618}
619
620uint32_t GOFFObjectFile::getSectionDefEsdId(DataRefImpl &Sec) const {
621 const uint8_t *EsdRecord = getSectionEdEsdRecord(Sec);
622 uint32_t Length;
623 ESDRecord::getLength(Record: EsdRecord, Length);
624 if (Length == 0) {
625 const uint8_t *PrEsdRecord = getSectionPrEsdRecord(Sec);
626 if (PrEsdRecord)
627 EsdRecord = PrEsdRecord;
628 }
629
630 uint32_t DefEsdId;
631 ESDRecord::getEsdId(Record: EsdRecord, EsdId&: DefEsdId);
632 LLVM_DEBUG(dbgs() << "Got def EsdId: " << DefEsdId << '\n');
633 return DefEsdId;
634}
635
636void GOFFObjectFile::moveSectionNext(DataRefImpl &Sec) const {
637 Sec.d.a++;
638 if ((Sec.d.a) >= SectionList.size())
639 Sec.d.a = 0;
640}
641
642Expected<StringRef> GOFFObjectFile::getSectionName(DataRefImpl Sec) const {
643 DataRefImpl EdSym;
644 SectionEntryImpl EsdIds = SectionList[Sec.d.a];
645 EdSym.d.a = EsdIds.d.a;
646 Expected<StringRef> Name = getSymbolName(Symb: EdSym);
647 if (Name) {
648 StringRef Res = *Name;
649 LLVM_DEBUG(dbgs() << "Got section: " << Res << '\n');
650 LLVM_DEBUG(dbgs() << "Final section name: " << Res << '\n');
651 Name = Res;
652 }
653 return Name;
654}
655
656uint64_t GOFFObjectFile::getSectionAddress(DataRefImpl Sec) const {
657 uint32_t Offset;
658 const uint8_t *EsdRecord = getSectionEdEsdRecord(Sec);
659 ESDRecord::getOffset(Record: EsdRecord, Offset);
660 return Offset;
661}
662
663uint64_t GOFFObjectFile::getSectionSize(DataRefImpl Sec) const {
664 uint32_t Length;
665 uint32_t DefEsdId = getSectionDefEsdId(Sec);
666 const uint8_t *EsdRecord = EsdPtrs[DefEsdId];
667 ESDRecord::getLength(Record: EsdRecord, Length);
668 LLVM_DEBUG(dbgs() << "Got section size: " << Length << '\n');
669 return static_cast<uint64_t>(Length);
670}
671
672// Unravel TXT records and expand fill characters to produce
673// a contiguous sequence of bytes.
674Expected<ArrayRef<uint8_t>>
675GOFFObjectFile::getSectionContents(DataRefImpl Sec) const {
676 if (auto It = SectionDataCache.find(Val: Sec.d.a); It != SectionDataCache.end()) {
677 auto &Buf = It->second;
678 return ArrayRef<uint8_t>(Buf);
679 }
680 uint64_t SectionSize = getSectionSize(Sec);
681 uint32_t DefEsdId = getSectionDefEsdId(Sec);
682
683 const uint8_t *EdEsdRecord = getSectionEdEsdRecord(Sec);
684 bool FillBytePresent;
685 ESDRecord::getFillBytePresent(Record: EdEsdRecord, Present&: FillBytePresent);
686 uint8_t FillByte = '\0';
687 if (FillBytePresent)
688 ESDRecord::getFillByteValue(Record: EdEsdRecord, Fill&: FillByte);
689
690 // Initialize section with fill byte.
691 SmallVector<uint8_t> Data(SectionSize, FillByte);
692
693 // Replace section with content from text records.
694 for (const uint8_t *TxtRecordPtr : TextPtrs) {
695 uint32_t TxtEsdId;
696 TXTRecord::getElementEsdId(Record: TxtRecordPtr, EsdId&: TxtEsdId);
697 LLVM_DEBUG(dbgs() << "Got txt EsdId: " << TxtEsdId << '\n');
698
699 if (TxtEsdId != DefEsdId)
700 continue;
701
702 uint32_t TxtDataOffset;
703 TXTRecord::getOffset(Record: TxtRecordPtr, Offset&: TxtDataOffset);
704
705 uint16_t TxtDataSize;
706 TXTRecord::getDataLength(Record: TxtRecordPtr, Length&: TxtDataSize);
707
708 LLVM_DEBUG(dbgs() << "Record offset " << TxtDataOffset << ", data size "
709 << TxtDataSize << "\n");
710
711 // Text data starts at byte 24 in the flattened record (already processed
712 // continuations)
713 const uint8_t *TxtData = TxtRecordPtr + 24;
714 assert(TxtDataSize <= Data.size() - TxtDataOffset &&
715 "Text data exceeds section size");
716 std::copy(first: TxtData, last: TxtData + TxtDataSize, result: Data.begin() + TxtDataOffset);
717 }
718 auto &Cache = SectionDataCache[Sec.d.a];
719 Cache = std::move(Data);
720 return ArrayRef<uint8_t>(Cache);
721}
722
723uint64_t GOFFObjectFile::getSectionAlignment(DataRefImpl Sec) const {
724 const uint8_t *EsdRecord = getSectionEdEsdRecord(Sec);
725 GOFF::ESDAlignment Pow2Alignment;
726 ESDRecord::getAlignment(Record: EsdRecord, Alignment&: Pow2Alignment);
727 return 1ULL << static_cast<uint64_t>(Pow2Alignment);
728}
729
730bool GOFFObjectFile::isSectionText(DataRefImpl Sec) const {
731 const uint8_t *EsdRecord = getSectionEdEsdRecord(Sec);
732 GOFF::ESDExecutable Executable;
733 ESDRecord::getExecutable(Record: EsdRecord, Executable);
734 return Executable == GOFF::ESD_EXE_CODE;
735}
736
737bool GOFFObjectFile::isSectionData(DataRefImpl Sec) const {
738 const uint8_t *EsdRecord = getSectionEdEsdRecord(Sec);
739 GOFF::ESDExecutable Executable;
740 ESDRecord::getExecutable(Record: EsdRecord, Executable);
741 return Executable == GOFF::ESD_EXE_DATA;
742}
743
744bool GOFFObjectFile::isSectionNoLoad(DataRefImpl Sec) const {
745 const uint8_t *EsdRecord = getSectionEdEsdRecord(Sec);
746 GOFF::ESDLoadingBehavior LoadingBehavior;
747 ESDRecord::getLoadingBehavior(Record: EsdRecord, Behavior&: LoadingBehavior);
748 return LoadingBehavior == GOFF::ESD_LB_NoLoad;
749}
750
751bool GOFFObjectFile::isSectionReadOnlyData(DataRefImpl Sec) const {
752 if (!isSectionData(Sec))
753 return false;
754
755 const uint8_t *EsdRecord = getSectionEdEsdRecord(Sec);
756 GOFF::ESDLoadingBehavior LoadingBehavior;
757 ESDRecord::getLoadingBehavior(Record: EsdRecord, Behavior&: LoadingBehavior);
758 return LoadingBehavior == GOFF::ESD_LB_Initial;
759}
760
761bool GOFFObjectFile::isSectionZeroInit(DataRefImpl Sec) const {
762 // GOFF uses fill characters and fill characters are applied
763 // on getSectionContents() - so we say false to zero init.
764 return false;
765}
766
767section_iterator GOFFObjectFile::section_begin() const {
768 DataRefImpl Sec;
769 moveSectionNext(Sec);
770 return section_iterator(SectionRef(Sec, this));
771}
772
773section_iterator GOFFObjectFile::section_end() const {
774 DataRefImpl Sec;
775 return section_iterator(SectionRef(Sec, this));
776}
777
778void GOFFObjectFile::moveSymbolNext(DataRefImpl &Symb) const {
779 for (uint32_t I = Symb.d.a + 1, E = EsdPtrs.size(); I < E; ++I) {
780 if (const uint8_t *EsdRecord = EsdPtrs[I]) {
781 GOFF::ESDSymbolType SymbolType;
782 ESDRecord::getSymbolType(Record: EsdRecord, SymbolType);
783 // Skip EDs - i.e. section symbols.
784 bool IgnoreSpecialGOFFSymbols = true;
785 bool SkipSymbol = ((SymbolType == GOFF::ESD_ST_ElementDefinition) ||
786 (SymbolType == GOFF::ESD_ST_SectionDefinition)) &&
787 IgnoreSpecialGOFFSymbols;
788 if (!SkipSymbol) {
789 Symb.d.a = I;
790 return;
791 }
792 }
793 }
794 Symb.d.a = 0;
795}
796
797basic_symbol_iterator GOFFObjectFile::symbol_begin() const {
798 DataRefImpl Symb;
799 moveSymbolNext(Symb);
800 return basic_symbol_iterator(SymbolRef(Symb, this));
801}
802
803basic_symbol_iterator GOFFObjectFile::symbol_end() const {
804 DataRefImpl Symb;
805 return basic_symbol_iterator(SymbolRef(Symb, this));
806}
807
808inline constexpr uint8_t SAME_R_ID = 0x80;
809inline constexpr uint8_t SAME_P_ID = 0x40;
810inline constexpr uint8_t SAME_OFFSET = 0x20;
811inline constexpr uint8_t EXT_ATTR_PRESENT = 0x04;
812inline constexpr uint8_t BYTE_OFFSET_8 = 0x02;
813
814// Populate the relocation entries.
815void GOFFObjectFile::setRelocationData(const uint8_t *RldRecord) {
816 SmallVector<uint8_t, 8> RelocationData;
817 int DataIndex = 6;
818 uint16_t DataLength;
819 RLDRecord::getDataLength(Record: RldRecord, Length&: DataLength);
820
821 // The record is already flattened if it's continued.
822 const uint8_t *RldI = RldRecord + DataIndex;
823 const uint8_t *RldE = RldI + DataLength;
824 uint32_t CurREsdId = 0;
825 uint32_t CurPEsdId = 0;
826 uint64_t CurPOffset = 0;
827 for (const uint8_t *Rld = RldI; Rld < RldE;) {
828 GOFFRelEntry RelEntry;
829 uint8_t Flags = Rld[0];
830 int32_t Length = 8;
831 if (!(Flags & SAME_R_ID)) {
832 CurREsdId = support::endian::read32be(P: &Rld[Length]);
833 Length += 4;
834 }
835 if (!(Flags & SAME_P_ID)) {
836 CurPEsdId = support::endian::read32be(P: &Rld[Length]);
837 Length += 4;
838 }
839 if (!(Flags & SAME_OFFSET)) {
840 if (Flags & BYTE_OFFSET_8) {
841 CurPOffset = support::endian::read64be(P: &Rld[Length]);
842 Length += 8;
843 } else {
844 CurPOffset = support::endian::read32be(P: &Rld[Length]);
845 Length += 4;
846 }
847 }
848 if (Flags & EXT_ATTR_PRESENT)
849 Length += 8;
850
851 RelEntry.PEsdId = CurPEsdId;
852 RelEntry.REsdId = CurREsdId;
853 RelEntry.POffset = CurPOffset;
854 RelEntry.RelType = getRldType(Rld);
855 RelEntries.emplace_back(Args&: RelEntry);
856
857 Rld += Length;
858 assert(Rld <= RldE && "RLD length?");
859 }
860}
861
862void GOFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
863 for (size_t I = Rel.d.b + 1, E = RelEntries.size(); I < E; ++I) {
864 const GOFFRelEntry &RelEntry = RelEntries[I];
865 if (Rel.d.a == RelEntry.PEsdId) {
866 Rel.d.b = I;
867 return;
868 }
869 }
870
871 Rel.d.b = 0;
872}
873
874uint64_t GOFFObjectFile::getRelocationOffset(DataRefImpl Rel) const {
875 assert(Rel.d.b > 0 && Rel.d.b < RelEntries.size() &&
876 "Rel Index out of boundary");
877 const GOFFRelEntry &RelEntry = RelEntries[Rel.d.b];
878 return RelEntry.POffset;
879}
880
881symbol_iterator GOFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
882 assert(Rel.d.b > 0 && Rel.d.b < RelEntries.size() &&
883 "Rel Index out of boundary");
884 const GOFFRelEntry &RelEntry = RelEntries[Rel.d.b];
885 DataRefImpl RefSym;
886 RefSym.d.a = RelEntry.REsdId;
887 return basic_symbol_iterator(SymbolRef(RefSym, this));
888}
889
890uint64_t GOFFObjectFile::getRelocationType(DataRefImpl Rel) const {
891 assert(Rel.d.b > 0 && Rel.d.b < RelEntries.size() &&
892 "Rel Index out of boundary");
893 const GOFFRelEntry &RelEntry = RelEntries[Rel.d.b];
894 return RelEntry.RelType;
895}
896
897void GOFFObjectFile::getRelocationTypeName(
898 DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
899 uint64_t RelType = getRelocationType(Rel);
900 std::string HexStr = formatv(Fmt: "R_{0:x-8}", Vals&: RelType).str();
901 Result.append(in_start: HexStr.begin(), in_end: HexStr.end());
902}
903
904relocation_iterator GOFFObjectFile::section_rel_begin(DataRefImpl Sec) const {
905 DataRefImpl Rel;
906 Rel.d.a = getSectionDefEsdId(Sec);
907 Rel.d.b = 0;
908 moveRelocationNext(Rel);
909 return relocation_iterator(RelocationRef(Rel, this));
910}
911
912relocation_iterator GOFFObjectFile::section_rel_end(DataRefImpl Sec) const {
913 DataRefImpl Rel;
914 Rel.d.a = getSectionDefEsdId(Sec);
915 Rel.d.b = 0;
916 return relocation_iterator(RelocationRef(Rel, this));
917}
918