1 //===-- llvm/CodeGen/DIEHash.cpp - Dwarf Hashing Framework ----------------===//
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 contains support for DWARF4 hashing of DIEs.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "DIEHash.h"
14 #include "ByteStreamer.h"
15 #include "DwarfCompileUnit.h"
16 #include "DwarfDebug.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/BinaryFormat/Dwarf.h"
20 #include "llvm/CodeGen/AsmPrinter.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/Endian.h"
23 #include "llvm/Support/raw_ostream.h"
24
25 using namespace llvm;
26
27 #define DEBUG_TYPE "dwarfdebug"
28
29 /// Grabs the string in whichever attribute is passed in and returns
30 /// a reference to it.
getDIEStringAttr(const DIE & Die,uint16_t Attr)31 static StringRef getDIEStringAttr(const DIE &Die, uint16_t Attr) {
32 // Iterate through all the attributes until we find the one we're
33 // looking for, if we can't find it return an empty string.
34 for (const auto &V : Die.values())
35 if (V.getAttribute() == Attr)
36 return V.getDIEString().getString();
37
38 return StringRef("");
39 }
40
41 /// Adds the string in \p Str to the hash. This also hashes
42 /// a trailing NULL with the string.
addString(StringRef Str)43 void DIEHash::addString(StringRef Str) {
44 LLVM_DEBUG(dbgs() << "Adding string " << Str << " to hash.\n");
45 Hash.update(Str);
46 Hash.update(makeArrayRef((uint8_t)'\0'));
47 }
48
49 // FIXME: The LEB128 routines are copied and only slightly modified out of
50 // LEB128.h.
51
52 /// Adds the unsigned in \p Value to the hash encoded as a ULEB128.
addULEB128(uint64_t Value)53 void DIEHash::addULEB128(uint64_t Value) {
54 LLVM_DEBUG(dbgs() << "Adding ULEB128 " << Value << " to hash.\n");
55 do {
56 uint8_t Byte = Value & 0x7f;
57 Value >>= 7;
58 if (Value != 0)
59 Byte |= 0x80; // Mark this byte to show that more bytes will follow.
60 Hash.update(Byte);
61 } while (Value != 0);
62 }
63
addSLEB128(int64_t Value)64 void DIEHash::addSLEB128(int64_t Value) {
65 LLVM_DEBUG(dbgs() << "Adding ULEB128 " << Value << " to hash.\n");
66 bool More;
67 do {
68 uint8_t Byte = Value & 0x7f;
69 Value >>= 7;
70 More = !((((Value == 0) && ((Byte & 0x40) == 0)) ||
71 ((Value == -1) && ((Byte & 0x40) != 0))));
72 if (More)
73 Byte |= 0x80; // Mark this byte to show that more bytes will follow.
74 Hash.update(Byte);
75 } while (More);
76 }
77
78 /// Including \p Parent adds the context of Parent to the hash..
addParentContext(const DIE & Parent)79 void DIEHash::addParentContext(const DIE &Parent) {
80
81 LLVM_DEBUG(dbgs() << "Adding parent context to hash...\n");
82
83 // [7.27.2] For each surrounding type or namespace beginning with the
84 // outermost such construct...
85 SmallVector<const DIE *, 1> Parents;
86 const DIE *Cur = &Parent;
87 while (Cur->getParent()) {
88 Parents.push_back(Cur);
89 Cur = Cur->getParent();
90 }
91 assert(Cur->getTag() == dwarf::DW_TAG_compile_unit ||
92 Cur->getTag() == dwarf::DW_TAG_type_unit);
93
94 // Reverse iterate over our list to go from the outermost construct to the
95 // innermost.
96 for (SmallVectorImpl<const DIE *>::reverse_iterator I = Parents.rbegin(),
97 E = Parents.rend();
98 I != E; ++I) {
99 const DIE &Die = **I;
100
101 // ... Append the letter "C" to the sequence...
102 addULEB128('C');
103
104 // ... Followed by the DWARF tag of the construct...
105 addULEB128(Die.getTag());
106
107 // ... Then the name, taken from the DW_AT_name attribute.
108 StringRef Name = getDIEStringAttr(Die, dwarf::DW_AT_name);
109 LLVM_DEBUG(dbgs() << "... adding context: " << Name << "\n");
110 if (!Name.empty())
111 addString(Name);
112 }
113 }
114
115 // Collect all of the attributes for a particular DIE in single structure.
collectAttributes(const DIE & Die,DIEAttrs & Attrs)116 void DIEHash::collectAttributes(const DIE &Die, DIEAttrs &Attrs) {
117
118 for (const auto &V : Die.values()) {
119 LLVM_DEBUG(dbgs() << "Attribute: "
120 << dwarf::AttributeString(V.getAttribute())
121 << " added.\n");
122 switch (V.getAttribute()) {
123 #define HANDLE_DIE_HASH_ATTR(NAME) \
124 case dwarf::NAME: \
125 Attrs.NAME = V; \
126 break;
127 #include "DIEHashAttributes.def"
128 default:
129 break;
130 }
131 }
132 }
133
hashShallowTypeReference(dwarf::Attribute Attribute,const DIE & Entry,StringRef Name)134 void DIEHash::hashShallowTypeReference(dwarf::Attribute Attribute,
135 const DIE &Entry, StringRef Name) {
136 // append the letter 'N'
137 addULEB128('N');
138
139 // the DWARF attribute code (DW_AT_type or DW_AT_friend),
140 addULEB128(Attribute);
141
142 // the context of the tag,
143 if (const DIE *Parent = Entry.getParent())
144 addParentContext(*Parent);
145
146 // the letter 'E',
147 addULEB128('E');
148
149 // and the name of the type.
150 addString(Name);
151
152 // Currently DW_TAG_friends are not used by Clang, but if they do become so,
153 // here's the relevant spec text to implement:
154 //
155 // For DW_TAG_friend, if the referenced entry is the DW_TAG_subprogram,
156 // the context is omitted and the name to be used is the ABI-specific name
157 // of the subprogram (e.g., the mangled linker name).
158 }
159
hashRepeatedTypeReference(dwarf::Attribute Attribute,unsigned DieNumber)160 void DIEHash::hashRepeatedTypeReference(dwarf::Attribute Attribute,
161 unsigned DieNumber) {
162 // a) If T is in the list of [previously hashed types], use the letter
163 // 'R' as the marker
164 addULEB128('R');
165
166 addULEB128(Attribute);
167
168 // and use the unsigned LEB128 encoding of [the index of T in the
169 // list] as the attribute value;
170 addULEB128(DieNumber);
171 }
172
hashDIEEntry(dwarf::Attribute Attribute,dwarf::Tag Tag,const DIE & Entry)173 void DIEHash::hashDIEEntry(dwarf::Attribute Attribute, dwarf::Tag Tag,
174 const DIE &Entry) {
175 assert(Tag != dwarf::DW_TAG_friend && "No current LLVM clients emit friend "
176 "tags. Add support here when there's "
177 "a use case");
178 // Step 5
179 // If the tag in Step 3 is one of [the below tags]
180 if ((Tag == dwarf::DW_TAG_pointer_type ||
181 Tag == dwarf::DW_TAG_reference_type ||
182 Tag == dwarf::DW_TAG_rvalue_reference_type ||
183 Tag == dwarf::DW_TAG_ptr_to_member_type) &&
184 // and the referenced type (via the [below attributes])
185 // FIXME: This seems overly restrictive, and causes hash mismatches
186 // there's a decl/def difference in the containing type of a
187 // ptr_to_member_type, but it's what DWARF says, for some reason.
188 Attribute == dwarf::DW_AT_type) {
189 // ... has a DW_AT_name attribute,
190 StringRef Name = getDIEStringAttr(Entry, dwarf::DW_AT_name);
191 if (!Name.empty()) {
192 hashShallowTypeReference(Attribute, Entry, Name);
193 return;
194 }
195 }
196
197 unsigned &DieNumber = Numbering[&Entry];
198 if (DieNumber) {
199 hashRepeatedTypeReference(Attribute, DieNumber);
200 return;
201 }
202
203 // otherwise, b) use the letter 'T' as the marker, ...
204 addULEB128('T');
205
206 addULEB128(Attribute);
207
208 // ... process the type T recursively by performing Steps 2 through 7, and
209 // use the result as the attribute value.
210 DieNumber = Numbering.size();
211 computeHash(Entry);
212 }
213
214 // Hash all of the values in a block like set of values. This assumes that
215 // all of the data is going to be added as integers.
hashBlockData(const DIE::const_value_range & Values)216 void DIEHash::hashBlockData(const DIE::const_value_range &Values) {
217 for (const auto &V : Values)
218 if (V.getType() == DIEValue::isBaseTypeRef) {
219 const DIE &C =
220 *CU->ExprRefedBaseTypes[V.getDIEBaseTypeRef().getIndex()].Die;
221 StringRef Name = getDIEStringAttr(C, dwarf::DW_AT_name);
222 assert(!Name.empty() &&
223 "Base types referenced from DW_OP_convert should have a name");
224 hashNestedType(C, Name);
225 } else
226 Hash.update((uint64_t)V.getDIEInteger().getValue());
227 }
228
229 // Hash the contents of a loclistptr class.
hashLocList(const DIELocList & LocList)230 void DIEHash::hashLocList(const DIELocList &LocList) {
231 HashingByteStreamer Streamer(*this);
232 DwarfDebug &DD = *AP->getDwarfDebug();
233 const DebugLocStream &Locs = DD.getDebugLocs();
234 const DebugLocStream::List &List = Locs.getList(LocList.getValue());
235 for (const DebugLocStream::Entry &Entry : Locs.getEntries(List))
236 DD.emitDebugLocEntry(Streamer, Entry, List.CU);
237 }
238
239 // Hash an individual attribute \param Attr based on the type of attribute and
240 // the form.
hashAttribute(const DIEValue & Value,dwarf::Tag Tag)241 void DIEHash::hashAttribute(const DIEValue &Value, dwarf::Tag Tag) {
242 dwarf::Attribute Attribute = Value.getAttribute();
243
244 // Other attribute values use the letter 'A' as the marker, and the value
245 // consists of the form code (encoded as an unsigned LEB128 value) followed by
246 // the encoding of the value according to the form code. To ensure
247 // reproducibility of the signature, the set of forms used in the signature
248 // computation is limited to the following: DW_FORM_sdata, DW_FORM_flag,
249 // DW_FORM_string, and DW_FORM_block.
250
251 switch (Value.getType()) {
252 case DIEValue::isNone:
253 llvm_unreachable("Expected valid DIEValue");
254
255 // 7.27 Step 3
256 // ... An attribute that refers to another type entry T is processed as
257 // follows:
258 case DIEValue::isEntry:
259 hashDIEEntry(Attribute, Tag, Value.getDIEEntry().getEntry());
260 break;
261 case DIEValue::isInteger: {
262 addULEB128('A');
263 addULEB128(Attribute);
264 switch (Value.getForm()) {
265 case dwarf::DW_FORM_data1:
266 case dwarf::DW_FORM_data2:
267 case dwarf::DW_FORM_data4:
268 case dwarf::DW_FORM_data8:
269 case dwarf::DW_FORM_udata:
270 case dwarf::DW_FORM_sdata:
271 addULEB128(dwarf::DW_FORM_sdata);
272 addSLEB128((int64_t)Value.getDIEInteger().getValue());
273 break;
274 // DW_FORM_flag_present is just flag with a value of one. We still give it a
275 // value so just use the value.
276 case dwarf::DW_FORM_flag_present:
277 case dwarf::DW_FORM_flag:
278 addULEB128(dwarf::DW_FORM_flag);
279 addULEB128((int64_t)Value.getDIEInteger().getValue());
280 break;
281 default:
282 llvm_unreachable("Unknown integer form!");
283 }
284 break;
285 }
286 case DIEValue::isString:
287 addULEB128('A');
288 addULEB128(Attribute);
289 addULEB128(dwarf::DW_FORM_string);
290 addString(Value.getDIEString().getString());
291 break;
292 case DIEValue::isInlineString:
293 addULEB128('A');
294 addULEB128(Attribute);
295 addULEB128(dwarf::DW_FORM_string);
296 addString(Value.getDIEInlineString().getString());
297 break;
298 case DIEValue::isBlock:
299 case DIEValue::isLoc:
300 case DIEValue::isLocList:
301 addULEB128('A');
302 addULEB128(Attribute);
303 addULEB128(dwarf::DW_FORM_block);
304 if (Value.getType() == DIEValue::isBlock) {
305 addULEB128(Value.getDIEBlock().ComputeSize(AP));
306 hashBlockData(Value.getDIEBlock().values());
307 } else if (Value.getType() == DIEValue::isLoc) {
308 addULEB128(Value.getDIELoc().ComputeSize(AP));
309 hashBlockData(Value.getDIELoc().values());
310 } else {
311 // We could add the block length, but that would take
312 // a bit of work and not add a lot of uniqueness
313 // to the hash in some way we could test.
314 hashLocList(Value.getDIELocList());
315 }
316 break;
317 // FIXME: It's uncertain whether or not we should handle this at the moment.
318 case DIEValue::isExpr:
319 case DIEValue::isLabel:
320 case DIEValue::isBaseTypeRef:
321 case DIEValue::isDelta:
322 llvm_unreachable("Add support for additional value types.");
323 }
324 }
325
326 // Go through the attributes from \param Attrs in the order specified in 7.27.4
327 // and hash them.
hashAttributes(const DIEAttrs & Attrs,dwarf::Tag Tag)328 void DIEHash::hashAttributes(const DIEAttrs &Attrs, dwarf::Tag Tag) {
329 #define HANDLE_DIE_HASH_ATTR(NAME) \
330 { \
331 if (Attrs.NAME) \
332 hashAttribute(Attrs.NAME, Tag); \
333 }
334 #include "DIEHashAttributes.def"
335 // FIXME: Add the extended attributes.
336 }
337
338 // Add all of the attributes for \param Die to the hash.
addAttributes(const DIE & Die)339 void DIEHash::addAttributes(const DIE &Die) {
340 DIEAttrs Attrs = {};
341 collectAttributes(Die, Attrs);
342 hashAttributes(Attrs, Die.getTag());
343 }
344
hashNestedType(const DIE & Die,StringRef Name)345 void DIEHash::hashNestedType(const DIE &Die, StringRef Name) {
346 // 7.27 Step 7
347 // ... append the letter 'S',
348 addULEB128('S');
349
350 // the tag of C,
351 addULEB128(Die.getTag());
352
353 // and the name.
354 addString(Name);
355 }
356
357 // Compute the hash of a DIE. This is based on the type signature computation
358 // given in section 7.27 of the DWARF4 standard. It is the md5 hash of a
359 // flattened description of the DIE.
computeHash(const DIE & Die)360 void DIEHash::computeHash(const DIE &Die) {
361 // Append the letter 'D', followed by the DWARF tag of the DIE.
362 addULEB128('D');
363 addULEB128(Die.getTag());
364
365 // Add each of the attributes of the DIE.
366 addAttributes(Die);
367
368 // Then hash each of the children of the DIE.
369 for (auto &C : Die.children()) {
370 // 7.27 Step 7
371 // If C is a nested type entry or a member function entry, ...
372 if (isType(C.getTag()) || (C.getTag() == dwarf::DW_TAG_subprogram && isType(C.getParent()->getTag()))) {
373 StringRef Name = getDIEStringAttr(C, dwarf::DW_AT_name);
374 // ... and has a DW_AT_name attribute
375 if (!Name.empty()) {
376 hashNestedType(C, Name);
377 continue;
378 }
379 }
380 computeHash(C);
381 }
382
383 // Following the last (or if there are no children), append a zero byte.
384 Hash.update(makeArrayRef((uint8_t)'\0'));
385 }
386
387 /// This is based on the type signature computation given in section 7.27 of the
388 /// DWARF4 standard. It is an md5 hash of the flattened description of the DIE
389 /// with the inclusion of the full CU and all top level CU entities.
390 // TODO: Initialize the type chain at 0 instead of 1 for CU signatures.
computeCUSignature(StringRef DWOName,const DIE & Die)391 uint64_t DIEHash::computeCUSignature(StringRef DWOName, const DIE &Die) {
392 Numbering.clear();
393 Numbering[&Die] = 1;
394
395 if (!DWOName.empty())
396 Hash.update(DWOName);
397 // Hash the DIE.
398 computeHash(Die);
399
400 // Now return the result.
401 MD5::MD5Result Result;
402 Hash.final(Result);
403
404 // ... take the least significant 8 bytes and return those. Our MD5
405 // implementation always returns its results in little endian, so we actually
406 // need the "high" word.
407 return Result.high();
408 }
409
410 /// This is based on the type signature computation given in section 7.27 of the
411 /// DWARF4 standard. It is an md5 hash of the flattened description of the DIE
412 /// with the inclusion of additional forms not specifically called out in the
413 /// standard.
computeTypeSignature(const DIE & Die)414 uint64_t DIEHash::computeTypeSignature(const DIE &Die) {
415 Numbering.clear();
416 Numbering[&Die] = 1;
417
418 if (const DIE *Parent = Die.getParent())
419 addParentContext(*Parent);
420
421 // Hash the DIE.
422 computeHash(Die);
423
424 // Now return the result.
425 MD5::MD5Result Result;
426 Hash.final(Result);
427
428 // ... take the least significant 8 bytes and return those. Our MD5
429 // implementation always returns its results in little endian, so we actually
430 // need the "high" word.
431 return Result.high();
432 }
433