1//=== DIEAttributeCloner.cpp ----------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "DIEAttributeCloner.h"
10#include "llvm/DWARFLinker/Utils.h"
11#include "llvm/DebugInfo/DWARF/DWARFDebugMacro.h"
12
13using namespace llvm;
14using namespace dwarf_linker;
15using namespace dwarf_linker::parallel;
16
17void DIEAttributeCloner::clone() {
18 // Extract and clone every attribute.
19 DWARFDataExtractor Data = InUnit.getOrigUnit().getDebugInfoExtractor();
20
21 uint64_t Offset = InputDieEntry->getOffset();
22 // Point to the next DIE (generally there is always at least a NULL
23 // entry after the current one). If this is a lone
24 // DW_TAG_compile_unit without any children, point to the next unit.
25 uint64_t NextOffset = (InputDIEIdx + 1 < InUnit.getOrigUnit().getNumDIEs())
26 ? InUnit.getDIEAtIndex(Index: InputDIEIdx + 1).getOffset()
27 : InUnit.getOrigUnit().getNextUnitOffset();
28
29 // We could copy the data only if we need to apply a relocation to it. After
30 // testing, it seems there is no performance downside to doing the copy
31 // unconditionally, and it makes the code simpler.
32 SmallString<40> DIECopy(Data.getData().substr(Start: Offset, N: NextOffset - Offset));
33 Data =
34 DWARFDataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
35
36 // Modify the copy with relocated addresses.
37 InUnit.getContainingFile().Addresses->applyValidRelocs(Data: DIECopy, BaseOffset: Offset,
38 IsLittleEndian: Data.isLittleEndian());
39
40 // Reset the Offset to 0 as we will be working on the local copy of
41 // the data.
42 Offset = 0;
43
44 const auto *Abbrev = InputDieEntry->getAbbreviationDeclarationPtr();
45 Offset += getULEB128Size(Value: Abbrev->getCode());
46
47 // Set current output offset.
48 AttrOutOffset = OutUnit.isCompileUnit() ? OutDIE->getOffset() : 0;
49 for (const auto &AttrSpec : Abbrev->attributes()) {
50 // Check whether current attribute should be skipped.
51 if (shouldSkipAttribute(AttrSpec)) {
52 DWARFFormValue::skipValue(Form: AttrSpec.Form, DebugInfoData: Data, OffsetPtr: &Offset,
53 FormParams: InUnit.getFormParams());
54 continue;
55 }
56
57 DWARFFormValue Val = AttrSpec.getFormValue();
58 Val.extractValue(Data, OffsetPtr: &Offset, FormParams: InUnit.getFormParams(),
59 U: &InUnit.getOrigUnit());
60
61 // Clone current attribute.
62 switch (AttrSpec.Form) {
63 case dwarf::DW_FORM_strp:
64 case dwarf::DW_FORM_line_strp:
65 case dwarf::DW_FORM_string:
66 case dwarf::DW_FORM_strx:
67 case dwarf::DW_FORM_strx1:
68 case dwarf::DW_FORM_strx2:
69 case dwarf::DW_FORM_strx3:
70 case dwarf::DW_FORM_strx4:
71 AttrOutOffset += cloneStringAttr(Val, AttrSpec);
72 break;
73 case dwarf::DW_FORM_ref_addr:
74 case dwarf::DW_FORM_ref1:
75 case dwarf::DW_FORM_ref2:
76 case dwarf::DW_FORM_ref4:
77 case dwarf::DW_FORM_ref8:
78 case dwarf::DW_FORM_ref_udata:
79 AttrOutOffset += cloneDieRefAttr(Val, AttrSpec);
80 break;
81 case dwarf::DW_FORM_data1:
82 case dwarf::DW_FORM_data2:
83 case dwarf::DW_FORM_data4:
84 case dwarf::DW_FORM_data8:
85 case dwarf::DW_FORM_udata:
86 case dwarf::DW_FORM_sdata:
87 case dwarf::DW_FORM_sec_offset:
88 case dwarf::DW_FORM_flag:
89 case dwarf::DW_FORM_flag_present:
90 case dwarf::DW_FORM_rnglistx:
91 case dwarf::DW_FORM_loclistx:
92 case dwarf::DW_FORM_implicit_const:
93 AttrOutOffset += cloneScalarAttr(Val, AttrSpec);
94 break;
95 case dwarf::DW_FORM_block:
96 case dwarf::DW_FORM_block1:
97 case dwarf::DW_FORM_block2:
98 case dwarf::DW_FORM_block4:
99 case dwarf::DW_FORM_exprloc:
100 AttrOutOffset += cloneBlockAttr(Val, AttrSpec);
101 break;
102 case dwarf::DW_FORM_addr:
103 case dwarf::DW_FORM_addrx:
104 case dwarf::DW_FORM_addrx1:
105 case dwarf::DW_FORM_addrx2:
106 case dwarf::DW_FORM_addrx3:
107 case dwarf::DW_FORM_addrx4:
108 AttrOutOffset += cloneAddressAttr(Val, AttrSpec);
109 break;
110 default:
111 InUnit.warn(Warning: "unsupported attribute form " +
112 dwarf::FormEncodingString(Encoding: AttrSpec.Form) +
113 " in DieAttributeCloner::clone(). Dropping.",
114 DieEntry: InputDieEntry);
115 }
116 }
117
118 // We convert source strings into the indexed form for DWARFv5.
119 // Check if original unit already has DW_AT_str_offsets_base
120 // attribute.
121 if (InputDIEIdx == 0 && InUnit.getVersion() >= 5 &&
122 !AttrInfo.HasStringOffsetBaseAttr && OutUnit.isCompileUnit()) {
123 DebugInfoOutputSection.notePatchWithOffsetUpdate(
124 Patch: DebugOffsetPatch{AttrOutOffset,
125 &OutUnit->getOrCreateSectionDescriptor(
126 SectionKind: DebugSectionKind::DebugStrOffsets),
127 true},
128 PatchesOffsetsList&: PatchesOffsets);
129
130 AttrOutOffset +=
131 Generator
132 .addScalarAttribute(Attr: dwarf::DW_AT_str_offsets_base,
133 AttrForm: dwarf::DW_FORM_sec_offset,
134 Value: OutUnit->getDebugStrOffsetsHeaderSize())
135 .second;
136 }
137
138 // No DW_AT_addr_base: add one for the addrx-indexed entries. Except in
139 // update mode, where HasAddrBaseAttr is never set.
140 if (InputDIEIdx == 0 && InUnit.getVersion() >= 5 &&
141 !AttrInfo.HasAddrBaseAttr &&
142 !InUnit.getGlobalData().getOptions().UpdateIndexTablesOnly) {
143 DebugInfoOutputSection.notePatchWithOffsetUpdate(
144 Patch: DebugOffsetPatch{
145 AttrOutOffset,
146 &OutUnit->getOrCreateSectionDescriptor(SectionKind: DebugSectionKind::DebugAddr),
147 true},
148 PatchesOffsetsList&: PatchesOffsets);
149
150 AttrOutOffset += Generator
151 .addScalarAttribute(Attr: dwarf::DW_AT_addr_base,
152 AttrForm: dwarf::DW_FORM_sec_offset,
153 Value: OutUnit->getDebugAddrHeaderSize())
154 .second;
155 }
156}
157
158bool DIEAttributeCloner::shouldSkipAttribute(
159 DWARFAbbreviationDeclaration::AttributeSpec AttrSpec) {
160 switch (AttrSpec.Attr) {
161 default:
162 return false;
163 case dwarf::DW_AT_low_pc:
164 case dwarf::DW_AT_high_pc:
165 case dwarf::DW_AT_ranges:
166 if (InUnit.getGlobalData().getOptions().UpdateIndexTablesOnly)
167 return false;
168
169 // Skip address attribute if we are in function scope and function does not
170 // reference live address.
171 return InUnit.getDIEInfo(Idx: InputDIEIdx).getIsInFunctionScope() &&
172 !FuncAddressAdjustment.has_value();
173 case dwarf::DW_AT_rnglists_base:
174 // In case !Update the .debug_addr table is not generated/preserved.
175 // Thus instead of DW_FORM_rnglistx the DW_FORM_sec_offset is used.
176 // Since DW_AT_rnglists_base is used for only DW_FORM_rnglistx the
177 // DW_AT_rnglists_base is removed.
178 return !InUnit.getGlobalData().getOptions().UpdateIndexTablesOnly;
179 case dwarf::DW_AT_loclists_base:
180 // In case !Update the .debug_addr table is not generated/preserved.
181 // Thus instead of DW_FORM_loclistx the DW_FORM_sec_offset is used.
182 // Since DW_AT_loclists_base is used for only DW_FORM_loclistx the
183 // DW_AT_loclists_base is removed.
184 return !InUnit.getGlobalData().getOptions().UpdateIndexTablesOnly;
185 case dwarf::DW_AT_location:
186 case dwarf::DW_AT_frame_base:
187 if (InUnit.getGlobalData().getOptions().UpdateIndexTablesOnly)
188 return false;
189
190 // When location expression contains an address: skip this attribute
191 // if it does not reference live address.
192 if (HasLocationExpressionAddress)
193 return !VarAddressAdjustment.has_value();
194
195 // Skip location attribute if we are in function scope and function does not
196 // reference live address.
197 return InUnit.getDIEInfo(Idx: InputDIEIdx).getIsInFunctionScope() &&
198 !FuncAddressAdjustment.has_value();
199 }
200}
201
202size_t DIEAttributeCloner::cloneStringAttr(
203 const DWARFFormValue &Val,
204 const DWARFAbbreviationDeclaration::AttributeSpec &AttrSpec) {
205 std::optional<const char *> String = dwarf::toString(V: Val);
206 if (!String) {
207 InUnit.warn(Warning: "cann't read string attribute.");
208 return 0;
209 }
210
211 const DWARFFile &File = InUnit.getContainingFile();
212 std::string RemappedPath;
213 if (File.PrefixMap &&
214 isPathAttribute(Tag: InputDieEntry->getTag(), Attr: AttrSpec.Attr)) {
215 RemappedPath = File.remapPath(Path: *String);
216 String = RemappedPath.c_str();
217 }
218
219 StringEntry *StringInPool =
220 InUnit.getGlobalData().getStringPool().insert(NewValue: *String).first;
221
222 // Update attributes info.
223 if (AttrSpec.Attr == dwarf::DW_AT_name)
224 AttrInfo.Name = StringInPool;
225 else if (AttrSpec.Attr == dwarf::DW_AT_MIPS_linkage_name ||
226 AttrSpec.Attr == dwarf::DW_AT_linkage_name)
227 AttrInfo.MangledName = StringInPool;
228
229 if (AttrSpec.Form == dwarf::DW_FORM_line_strp) {
230 if (OutUnit.isTypeUnit()) {
231 DebugInfoOutputSection.notePatch(Patch: DebugTypeLineStrPatch{
232 AttrOutOffset, OutDIE, InUnit.getDieTypeEntry(Idx: InputDIEIdx),
233 StringInPool});
234 } else {
235 DebugInfoOutputSection.notePatchWithOffsetUpdate(
236 Patch: DebugLineStrPatch{{.PatchOffset: AttrOutOffset}, .String: StringInPool}, PatchesOffsetsList&: PatchesOffsets);
237 }
238 return Generator
239 .addStringPlaceholderAttribute(Attr: AttrSpec.Attr, AttrForm: dwarf::DW_FORM_line_strp)
240 .second;
241 }
242
243 if (Use_DW_FORM_strp) {
244 if (OutUnit.isTypeUnit()) {
245 DebugInfoOutputSection.notePatch(
246 Patch: DebugTypeStrPatch{AttrOutOffset, OutDIE,
247 InUnit.getDieTypeEntry(Idx: InputDIEIdx), StringInPool});
248 } else {
249 DebugInfoOutputSection.notePatchWithOffsetUpdate(
250 Patch: DebugStrPatch{{.PatchOffset: AttrOutOffset}, .String: StringInPool}, PatchesOffsetsList&: PatchesOffsets);
251 }
252
253 return Generator
254 .addStringPlaceholderAttribute(Attr: AttrSpec.Attr, AttrForm: dwarf::DW_FORM_strp)
255 .second;
256 }
257
258 return Generator
259 .addIndexedStringAttribute(Attr: AttrSpec.Attr, AttrForm: dwarf::DW_FORM_strx,
260 Idx: OutUnit->getDebugStrIndex(String: StringInPool))
261 .second;
262}
263
264size_t DIEAttributeCloner::cloneDieRefAttr(
265 const DWARFFormValue &Val,
266 const DWARFAbbreviationDeclaration::AttributeSpec &AttrSpec) {
267 if (AttrSpec.Attr == dwarf::DW_AT_sibling)
268 return 0;
269
270 std::optional<UnitEntryPairTy> RefDiePair =
271 InUnit.resolveDIEReference(RefValue: Val, CanResolveInterCUReferences: ResolveInterCUReferencesMode::Resolve);
272 if (!RefDiePair || !RefDiePair->DieEntry) {
273 // If the referenced DIE is not found, drop the attribute.
274 InUnit.warn(Warning: "could not find referenced DIE", DieEntry: InputDieEntry);
275 return 0;
276 }
277
278 TypeEntry *RefTypeName = nullptr;
279 const CompileUnit::DIEInfo &RefDIEInfo =
280 RefDiePair->CU->getDIEInfo(Entry: RefDiePair->DieEntry);
281 if (RefDIEInfo.needToPlaceInTypeTable())
282 RefTypeName = RefDiePair->CU->getDieTypeEntry(InputDieEntry: RefDiePair->DieEntry);
283
284 // The importing unit's DW_TAG_module skeleton can have a different
285 // DW_AT_LLVM_include_path than the unit built from the .pcm and the import
286 // must use the latter. The type pool already merges copies, so a reference
287 // with a type entry resolves correctly. Without one, the module's anchor is
288 // the only link between the two, and it is not known until the unit
289 // describing the module has been emitted.
290 if (RefDiePair->DieEntry->getTag() == dwarf::DW_TAG_module &&
291 AttrSpec.Attr == dwarf::DW_AT_import && !OutUnit.isTypeUnit() &&
292 !RefTypeName) {
293 SmallString<128> Path;
294 if (RefDiePair->CU->getModulePath(DieEntry: RefDiePair->DieEntry, Path)) {
295 ModuleAnchor *Anchor =
296 InUnit.getGlobalData().getModulePool().getOrCreate(Path);
297
298 DebugInfoOutputSection.notePatchWithOffsetUpdate(
299 Patch: DebugDieModuleRefPatch{
300 AttrOutOffset, RefDiePair->CU,
301 RefDiePair->CU->getDIEIndex(Die: RefDiePair->DieEntry), Anchor},
302 PatchesOffsetsList&: PatchesOffsets);
303 return Generator
304 .addScalarAttribute(Attr: AttrSpec.Attr, AttrForm: dwarf::DW_FORM_ref_addr, Value: 0xBADDEF)
305 .second;
306 }
307 }
308
309 if (OutUnit.isTypeUnit()) {
310 assert(RefTypeName && "Type name for referenced DIE is not set");
311 assert(InUnit.getDieTypeEntry(InputDIEIdx) &&
312 "Type name for DIE is not set");
313
314 DebugInfoOutputSection.notePatch(Patch: DebugType2TypeDieRefPatch{
315 AttrOutOffset, OutDIE, InUnit.getDieTypeEntry(Idx: InputDIEIdx),
316 RefTypeName});
317
318 return Generator
319 .addScalarAttribute(Attr: AttrSpec.Attr, AttrForm: dwarf::DW_FORM_ref4, Value: 0xBADDEF)
320 .second;
321 }
322
323 if (RefTypeName) {
324 DebugInfoOutputSection.notePatchWithOffsetUpdate(
325 Patch: DebugDieTypeRefPatch{AttrOutOffset, RefTypeName}, PatchesOffsetsList&: PatchesOffsets);
326
327 return Generator
328 .addScalarAttribute(Attr: AttrSpec.Attr, AttrForm: dwarf::DW_FORM_ref_addr, Value: 0xBADDEF)
329 .second;
330 }
331
332 // Get output offset for referenced DIE.
333 uint64_t OutDieOffset = RefDiePair->CU->getDieOutOffset(InputDieEntry: RefDiePair->DieEntry);
334
335 // Examine whether referenced DIE is in current compile unit.
336 bool IsLocal = OutUnit->getUniqueID() == RefDiePair->CU->getUniqueID();
337
338 // Set attribute form basing on the kind of referenced DIE(local or not?).
339 dwarf::Form NewForm = IsLocal ? dwarf::DW_FORM_ref4 : dwarf::DW_FORM_ref_addr;
340
341 // Check whether current attribute references already cloned DIE inside
342 // the same compilation unit. If true - write the already known offset value.
343 if (IsLocal && (OutDieOffset != 0))
344 return Generator.addScalarAttribute(Attr: AttrSpec.Attr, AttrForm: NewForm, Value: OutDieOffset)
345 .second;
346
347 // If offset value is not known at this point then create patch for the
348 // reference value and write dummy value into the attribute.
349 DebugInfoOutputSection.notePatchWithOffsetUpdate(
350 Patch: DebugDieRefPatch{AttrOutOffset, OutUnit.getAsCompileUnit(),
351 RefDiePair->CU,
352 RefDiePair->CU->getDIEIndex(Die: RefDiePair->DieEntry)},
353 PatchesOffsetsList&: PatchesOffsets);
354 return Generator.addScalarAttribute(Attr: AttrSpec.Attr, AttrForm: NewForm, Value: 0xBADDEF).second;
355}
356
357size_t DIEAttributeCloner::cloneScalarAttr(
358 const DWARFFormValue &Val,
359 const DWARFAbbreviationDeclaration::AttributeSpec &AttrSpec) {
360
361 // Create patches for attribute referencing other non invariant section.
362 // Invariant section could not be updated here as this section and
363 // reference to it do not change value in case --update.
364 switch (AttrSpec.Attr) {
365 case dwarf::DW_AT_macro_info: {
366 if (std::optional<uint64_t> Offset = Val.getAsSectionOffset()) {
367 const DWARFDebugMacro *Macro =
368 InUnit.getContainingFile().Dwarf->getDebugMacinfo();
369 if (Macro == nullptr || !Macro->hasEntryForOffset(Offset: *Offset))
370 return 0;
371
372 DebugInfoOutputSection.notePatchWithOffsetUpdate(
373 Patch: DebugOffsetPatch{AttrOutOffset,
374 &OutUnit->getOrCreateSectionDescriptor(
375 SectionKind: DebugSectionKind::DebugMacinfo)},
376 PatchesOffsetsList&: PatchesOffsets);
377 }
378 } break;
379 case dwarf::DW_AT_macros: {
380 if (std::optional<uint64_t> Offset = Val.getAsSectionOffset()) {
381 const DWARFDebugMacro *Macro =
382 InUnit.getContainingFile().Dwarf->getDebugMacro();
383 if (Macro == nullptr || !Macro->hasEntryForOffset(Offset: *Offset))
384 return 0;
385
386 DebugInfoOutputSection.notePatchWithOffsetUpdate(
387 Patch: DebugOffsetPatch{AttrOutOffset,
388 &OutUnit->getOrCreateSectionDescriptor(
389 SectionKind: DebugSectionKind::DebugMacro)},
390 PatchesOffsetsList&: PatchesOffsets);
391 }
392 } break;
393 case dwarf::DW_AT_stmt_list: {
394 DebugInfoOutputSection.notePatchWithOffsetUpdate(
395 Patch: DebugOffsetPatch{AttrOutOffset, &OutUnit->getOrCreateSectionDescriptor(
396 SectionKind: DebugSectionKind::DebugLine)},
397 PatchesOffsetsList&: PatchesOffsets);
398 } break;
399 case dwarf::DW_AT_str_offsets_base: {
400 DebugInfoOutputSection.notePatchWithOffsetUpdate(
401 Patch: DebugOffsetPatch{AttrOutOffset,
402 &OutUnit->getOrCreateSectionDescriptor(
403 SectionKind: DebugSectionKind::DebugStrOffsets),
404 true},
405 PatchesOffsetsList&: PatchesOffsets);
406
407 // Use size of .debug_str_offsets header as attribute value. The offset
408 // to .debug_str_offsets would be added later while patching.
409 AttrInfo.HasStringOffsetBaseAttr = true;
410 return Generator
411 .addScalarAttribute(Attr: AttrSpec.Attr, AttrForm: AttrSpec.Form,
412 Value: OutUnit->getDebugStrOffsetsHeaderSize())
413 .second;
414 } break;
415 case dwarf::DW_AT_decl_file: {
416 // Value of DW_AT_decl_file may exceed original form. Longer
417 // form can affect offsets to the following attributes. To not
418 // update offsets of the following attributes we always remove
419 // original DW_AT_decl_file and attach it to the last position
420 // later.
421 if (OutUnit.isTypeUnit()) {
422 if (std::optional<std::pair<StringRef, StringRef>> DirAndFilename =
423 InUnit.getDirAndFilenameFromLineTable(FileIdxValue: Val))
424 DebugInfoOutputSection.notePatch(Patch: DebugTypeDeclFilePatch{
425 OutDIE,
426 InUnit.getDieTypeEntry(Idx: InputDIEIdx),
427 OutUnit->getGlobalData()
428 .getStringPool()
429 .insert(NewValue: DirAndFilename->first)
430 .first,
431 OutUnit->getGlobalData()
432 .getStringPool()
433 .insert(NewValue: DirAndFilename->second)
434 .first,
435 });
436 return 0;
437 }
438 } break;
439 default: {
440 } break;
441 };
442
443 uint64_t Value;
444 if (AttrSpec.Attr == dwarf::DW_AT_const_value &&
445 (InputDieEntry->getTag() == dwarf::DW_TAG_variable ||
446 InputDieEntry->getTag() == dwarf::DW_TAG_constant))
447 AttrInfo.HasLiveAddress = true;
448
449 if (InUnit.getGlobalData().getOptions().UpdateIndexTablesOnly) {
450 if (auto OptionalValue = Val.getAsUnsignedConstant())
451 Value = *OptionalValue;
452 else if (auto OptionalValue = Val.getAsSignedConstant())
453 Value = *OptionalValue;
454 else if (auto OptionalValue = Val.getAsSectionOffset())
455 Value = *OptionalValue;
456 else {
457 InUnit.warn(Warning: "unsupported scalar attribute form. Dropping attribute.",
458 DieEntry: InputDieEntry);
459 return 0;
460 }
461
462 if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
463 AttrInfo.IsDeclaration = true;
464
465 if (AttrSpec.Form == dwarf::DW_FORM_loclistx)
466 return Generator.addLocListAttribute(Attr: AttrSpec.Attr, AttrForm: AttrSpec.Form, Value)
467 .second;
468
469 return Generator.addScalarAttribute(Attr: AttrSpec.Attr, AttrForm: AttrSpec.Form, Value)
470 .second;
471 }
472
473 dwarf::Form ResultingForm = AttrSpec.Form;
474 if (AttrSpec.Form == dwarf::DW_FORM_rnglistx) {
475 // DWARFLinker does not generate .debug_addr table. Thus we need to change
476 // all "addrx" related forms to "addr" version. Change DW_FORM_rnglistx
477 // to DW_FORM_sec_offset here.
478 std::optional<uint64_t> Index = Val.getAsSectionOffset();
479 if (!Index) {
480 InUnit.warn(Warning: "cann't read the attribute. Dropping.", DieEntry: InputDieEntry);
481 return 0;
482 }
483 std::optional<uint64_t> Offset =
484 InUnit.getOrigUnit().getRnglistOffset(Index: *Index);
485 if (!Offset) {
486 InUnit.warn(Warning: "cann't read the attribute. Dropping.", DieEntry: InputDieEntry);
487 return 0;
488 }
489
490 Value = *Offset;
491 ResultingForm = dwarf::DW_FORM_sec_offset;
492 } else if (AttrSpec.Form == dwarf::DW_FORM_loclistx) {
493 // DWARFLinker does not generate .debug_addr table. Thus we need to change
494 // all "addrx" related forms to "addr" version. Change DW_FORM_loclistx
495 // to DW_FORM_sec_offset here.
496 std::optional<uint64_t> Index = Val.getAsSectionOffset();
497 if (!Index) {
498 InUnit.warn(Warning: "cann't read the attribute. Dropping.", DieEntry: InputDieEntry);
499 return 0;
500 }
501 std::optional<uint64_t> Offset =
502 InUnit.getOrigUnit().getLoclistOffset(Index: *Index);
503 if (!Offset) {
504 InUnit.warn(Warning: "cann't read the attribute. Dropping.", DieEntry: InputDieEntry);
505 return 0;
506 }
507
508 Value = *Offset;
509 ResultingForm = dwarf::DW_FORM_sec_offset;
510 } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
511 InputDieEntry->getTag() == dwarf::DW_TAG_compile_unit) {
512 if (!OutUnit.isCompileUnit())
513 return 0;
514
515 std::optional<uint64_t> LowPC = OutUnit.getAsCompileUnit()->getLowPc();
516 if (!LowPC)
517 return 0;
518 // Dwarf >= 4 high_pc is an size, not an address.
519 Value = OutUnit.getAsCompileUnit()->getHighPc() - *LowPC;
520 } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
521 Value = *Val.getAsSectionOffset();
522 else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
523 Value = *Val.getAsSignedConstant();
524 else if (auto OptionalValue = Val.getAsUnsignedConstant())
525 Value = *OptionalValue;
526 else {
527 InUnit.warn(Warning: "unsupported scalar attribute form. Dropping attribute.",
528 DieEntry: InputDieEntry);
529 return 0;
530 }
531
532 if (AttrSpec.Attr == dwarf::DW_AT_ranges ||
533 AttrSpec.Attr == dwarf::DW_AT_start_scope) {
534 // Create patch for the range offset value.
535 DebugInfoOutputSection.notePatchWithOffsetUpdate(
536 Patch: DebugRangePatch{{.PatchOffset: AttrOutOffset},
537 .IsCompileUnitRanges: InputDieEntry->getTag() == dwarf::DW_TAG_compile_unit},
538 PatchesOffsetsList&: PatchesOffsets);
539 AttrInfo.HasRanges = true;
540 } else if (DWARFAttribute::mayHaveLocationList(Attr: AttrSpec.Attr) &&
541 dwarf::doesFormBelongToClass(Form: AttrSpec.Form,
542 FC: DWARFFormValue::FC_SectionOffset,
543 DwarfVersion: InUnit.getOrigUnit().getVersion())) {
544 int64_t AddrAdjustmentValue = 0;
545 if (VarAddressAdjustment)
546 AddrAdjustmentValue = *VarAddressAdjustment;
547 else if (FuncAddressAdjustment)
548 AddrAdjustmentValue = *FuncAddressAdjustment;
549
550 // Create patch for the location offset value.
551 DebugInfoOutputSection.notePatchWithOffsetUpdate(
552 Patch: DebugLocPatch{{.PatchOffset: AttrOutOffset}, .AddrAdjustmentValue: AddrAdjustmentValue}, PatchesOffsetsList&: PatchesOffsets);
553 } else if (AttrSpec.Attr == dwarf::DW_AT_addr_base) {
554 DebugInfoOutputSection.notePatchWithOffsetUpdate(
555 Patch: DebugOffsetPatch{
556 AttrOutOffset,
557 &OutUnit->getOrCreateSectionDescriptor(SectionKind: DebugSectionKind::DebugAddr),
558 true},
559 PatchesOffsetsList&: PatchesOffsets);
560
561 // Use size of .debug_addr header as attribute value. The offset to
562 // .debug_addr would be added later while patching.
563 AttrInfo.HasAddrBaseAttr = true;
564 return Generator
565 .addScalarAttribute(Attr: AttrSpec.Attr, AttrForm: AttrSpec.Form,
566 Value: OutUnit->getDebugAddrHeaderSize())
567 .second;
568 } else if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
569 AttrInfo.IsDeclaration = true;
570
571 // DW_AT_LLVM_stmt_sequence refers to line info in this unit's
572 // .debug_line contribution, which only exists for compile units.
573 // DependencyTracker can route a module-scope subprogram to a type
574 // unit when ODR deduplication applies (see
575 // DependencyTracker.cpp: DW_TAG_subprogram case), so drop the
576 // attribute on that path — mirroring how cloneBlockAttr handles
577 // type-unit placement.
578 if (AttrSpec.Attr == dwarf::DW_AT_LLVM_stmt_sequence &&
579 !OutUnit.isCompileUnit())
580 return 0;
581
582 // A compile unit's high_pc comes from the unit's own linked range and spans
583 // every symbol in it.
584 if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
585 InputDieEntry->getTag() != dwarf::DW_TAG_compile_unit)
586 Value = constrainHighPC(HighPC: Value, /*IsLength=*/true);
587
588 auto Result =
589 Generator.addScalarAttribute(Attr: AttrSpec.Attr, AttrForm: ResultingForm, Value);
590 // Record DW_AT_LLVM_stmt_sequence so the attribute value can be
591 // rewritten with the correct .debug_line offset after the line table
592 // for this CU has been emitted. We also register a DebugOffsetPatch so
593 // that the final-section offset of .debug_line gets added when the
594 // section is placed in the combined output.
595 if (AttrSpec.Attr == dwarf::DW_AT_LLVM_stmt_sequence) {
596 // Record the attribute's raw input stmt-sequence offset. Resolution
597 // to a first-row index — including the boundary-walk fallback for
598 // sequences the DWARF parser may not have registered — happens in
599 // a post-cloning pass (buildStmtSeqOffsetToFirstRowIndex), so that
600 // matches the classic linker's behaviour.
601 OutUnit.getAsCompileUnit()->noteStmtSeqListAttribute(V: &Result.first, InputStmtSeqOffset: Value);
602 DebugInfoOutputSection.notePatchWithOffsetUpdate(
603 Patch: DebugOffsetPatch{
604 AttrOutOffset,
605 &OutUnit->getOrCreateSectionDescriptor(SectionKind: DebugSectionKind::DebugLine),
606 /*AddLocalValue=*/true},
607 PatchesOffsetsList&: PatchesOffsets);
608 }
609 return Result.second;
610}
611
612static bool expressionDependsOnOriginUnit(const DWARFExpression &Expr) {
613 using Encoding = DWARFExpression::Operation::Encoding;
614
615 for (const DWARFExpression::Operation &Op : Expr) {
616 switch (Op.getCode()) {
617 case dwarf::DW_OP_addr:
618 case dwarf::DW_OP_addrx:
619 case dwarf::DW_OP_constx:
620 return true;
621 default:
622 break;
623 }
624
625 if (llvm::is_contained(Range: Op.getDescription().Op, Element: Encoding::BaseTypeRef))
626 return true;
627 }
628
629 return false;
630}
631
632size_t DIEAttributeCloner::cloneBlockAttr(
633 const DWARFFormValue &Val,
634 const DWARFAbbreviationDeclaration::AttributeSpec &AttrSpec) {
635
636 size_t NumberOfPatchesAtStart = PatchesOffsets.size();
637
638 // If the block is a DWARF Expression, clone it into the temporary
639 // buffer using cloneExpression(), otherwise copy the data directly.
640 SmallVector<uint8_t, 32> Buffer;
641 ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
642 if (DWARFAttribute::mayHaveLocationExpr(Attr: AttrSpec.Attr) &&
643 (Val.isFormClass(FC: DWARFFormValue::FC_Block) ||
644 Val.isFormClass(FC: DWARFFormValue::FC_Exprloc))) {
645 DataExtractor Data(Bytes, InUnit.getOrigUnit().isLittleEndian());
646 DWARFExpression Expr(Data, InUnit.getOrigUnit().getAddressByteSize(),
647 InUnit.getFormParams().Format);
648
649 // A type unit is shared by every compile unit that references the type, so
650 // an expression resolving against one origin unit has no single correct
651 // value there.
652 if (OutUnit.isTypeUnit() && expressionDependsOnOriginUnit(Expr))
653 return 0;
654
655 InUnit.cloneDieAttrExpression(InputExpression: Expr, OutputExpression&: Buffer, Section&: DebugInfoOutputSection,
656 VarAddressAdjustment, PatchesOffsets);
657 Bytes = Buffer;
658 }
659
660 // The expression location data might be updated and exceed the original size.
661 // Check whether the new data fits into the original form.
662 dwarf::Form ResultForm = AttrSpec.Form;
663 if ((ResultForm == dwarf::DW_FORM_block1 && Bytes.size() > UINT8_MAX) ||
664 (ResultForm == dwarf::DW_FORM_block2 && Bytes.size() > UINT16_MAX) ||
665 (ResultForm == dwarf::DW_FORM_block4 && Bytes.size() > UINT32_MAX))
666 ResultForm = dwarf::DW_FORM_block;
667
668 size_t FinalAttributeSize;
669 if (AttrSpec.Form == dwarf::DW_FORM_exprloc)
670 FinalAttributeSize =
671 Generator.addLocationAttribute(Attr: AttrSpec.Attr, AttrForm: ResultForm, Bytes).second;
672 else
673 FinalAttributeSize =
674 Generator.addBlockAttribute(Attr: AttrSpec.Attr, AttrForm: ResultForm, Bytes).second;
675
676 // Update patches offsets with the size of length field for Bytes.
677 for (size_t Idx = NumberOfPatchesAtStart; Idx < PatchesOffsets.size();
678 Idx++) {
679 assert(FinalAttributeSize > Bytes.size());
680 *PatchesOffsets[Idx] +=
681 (AttrOutOffset + (FinalAttributeSize - Bytes.size()));
682 }
683
684 if (HasLocationExpressionAddress)
685 AttrInfo.HasLiveAddress =
686 VarAddressAdjustment.has_value() ||
687 InUnit.getGlobalData().getOptions().UpdateIndexTablesOnly;
688
689 return FinalAttributeSize;
690}
691
692size_t DIEAttributeCloner::cloneAddressAttr(
693 const DWARFFormValue &Val,
694 const DWARFAbbreviationDeclaration::AttributeSpec &AttrSpec) {
695 if (AttrSpec.Attr == dwarf::DW_AT_low_pc)
696 AttrInfo.HasLiveAddress = true;
697
698 if (InUnit.getGlobalData().getOptions().UpdateIndexTablesOnly)
699 return Generator
700 .addScalarAttribute(Attr: AttrSpec.Attr, AttrForm: AttrSpec.Form, Value: Val.getRawUValue())
701 .second;
702
703 if (OutUnit.isTypeUnit())
704 return 0;
705
706 // Cloned Die may have address attributes relocated to a
707 // totally unrelated value. This can happen:
708 // - If high_pc is an address (Dwarf version == 2), then it might have been
709 // relocated to a totally unrelated value (because the end address in the
710 // object file might be start address of another function which got moved
711 // independently by the linker).
712 // - If address relocated in an inline_subprogram that happens at the
713 // beginning of its inlining function.
714 // To avoid above cases and to not apply relocation twice (in
715 // applyValidRelocs and here), read address attribute from InputDIE and apply
716 // Info.PCOffset here.
717
718 std::optional<DWARFFormValue> AddrAttribute =
719 InUnit.find(Die: InputDieEntry, Attrs: AttrSpec.Attr);
720 if (!AddrAttribute)
721 llvm_unreachable("Cann't find attribute");
722
723 std::optional<uint64_t> Addr = AddrAttribute->getAsAddress();
724 if (!Addr) {
725 InUnit.warn(Warning: "cann't read address attribute value.");
726 return 0;
727 }
728
729 if (InputDieEntry->getTag() == dwarf::DW_TAG_compile_unit &&
730 AttrSpec.Attr == dwarf::DW_AT_low_pc) {
731 if (std::optional<uint64_t> LowPC = OutUnit.getAsCompileUnit()->getLowPc())
732 Addr = *LowPC;
733 else
734 return 0;
735 } else if (InputDieEntry->getTag() == dwarf::DW_TAG_compile_unit &&
736 AttrSpec.Attr == dwarf::DW_AT_high_pc) {
737 if (uint64_t HighPc = OutUnit.getAsCompileUnit()->getHighPc())
738 Addr = HighPc;
739 else
740 return 0;
741 } else {
742 if (AttrSpec.Attr == dwarf::DW_AT_high_pc)
743 Addr = constrainHighPC(HighPC: *Addr, /*IsLength=*/false);
744 if (VarAddressAdjustment)
745 *Addr += *VarAddressAdjustment;
746 else if (FuncAddressAdjustment)
747 *Addr += *FuncAddressAdjustment;
748 }
749
750 if (AttrSpec.Form == dwarf::DW_FORM_addr) {
751 return Generator.addScalarAttribute(Attr: AttrSpec.Attr, AttrForm: AttrSpec.Form, Value: *Addr)
752 .second;
753 }
754
755 return Generator
756 .addScalarAttribute(Attr: AttrSpec.Attr, AttrForm: dwarf::Form::DW_FORM_addrx,
757 Value: OutUnit.getAsCompileUnit()->getDebugAddrIndex(Addr: *Addr))
758 .second;
759}
760
761uint64_t DIEAttributeCloner::constrainHighPC(uint64_t HighPC, bool IsLength) {
762 if (!FuncAddressAdjustment)
763 return HighPC;
764 std::optional<uint64_t> LowPC =
765 dwarf::toAddress(V: InUnit.find(Die: InputDieEntry, Attrs: dwarf::DW_AT_low_pc));
766 if (!LowPC)
767 return HighPC;
768 uint64_t Constrained =
769 InUnit.getContainingFile().Addresses->constrainCodeRangeHighPC(
770 LowPC: *LowPC, HighPC: IsLength ? *LowPC + HighPC : HighPC, Adjustment: *FuncAddressAdjustment);
771 return IsLength ? Constrained - *LowPC : Constrained;
772}
773
774unsigned DIEAttributeCloner::finalizeAbbreviations(bool HasChildrenToClone) {
775 // Add the size of the abbreviation number to the output offset.
776 AttrOutOffset +=
777 Generator.finalizeAbbreviations(CHILDREN_yes: HasChildrenToClone, OffsetsList: &PatchesOffsets);
778
779 return AttrOutOffset;
780}
781