1 //===-- BreakpadRecords.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 "Plugins/ObjectFile/Breakpad/BreakpadRecords.h"
10 #include "llvm/ADT/StringExtras.h"
11 #include "llvm/ADT/StringSwitch.h"
12 #include "llvm/Support/Endian.h"
13 #include "llvm/Support/FormatVariadic.h"
14 #include <optional>
15 
16 using namespace lldb_private;
17 using namespace lldb_private::breakpad;
18 
19 namespace {
20 enum class Token {
21   Unknown,
22   Module,
23   Info,
24   CodeID,
25   File,
26   Func,
27   Inline,
28   InlineOrigin,
29   Public,
30   Stack,
31   CFI,
32   Init,
33   Win,
34 };
35 }
36 
37 template<typename T>
38 static T stringTo(llvm::StringRef Str);
39 
40 template <> Token stringTo<Token>(llvm::StringRef Str) {
41   return llvm::StringSwitch<Token>(Str)
42       .Case("MODULE", Token::Module)
43       .Case("INFO", Token::Info)
44       .Case("CODE_ID", Token::CodeID)
45       .Case("FILE", Token::File)
46       .Case("FUNC", Token::Func)
47       .Case("INLINE", Token::Inline)
48       .Case("INLINE_ORIGIN", Token::InlineOrigin)
49       .Case("PUBLIC", Token::Public)
50       .Case("STACK", Token::Stack)
51       .Case("CFI", Token::CFI)
52       .Case("INIT", Token::Init)
53       .Case("WIN", Token::Win)
54       .Default(Token::Unknown);
55 }
56 
57 template <>
58 llvm::Triple::OSType stringTo<llvm::Triple::OSType>(llvm::StringRef Str) {
59   using llvm::Triple;
60   return llvm::StringSwitch<Triple::OSType>(Str)
61       .Case("Linux", Triple::Linux)
62       .Case("mac", Triple::MacOSX)
63       .Case("windows", Triple::Win32)
64       .Default(Triple::UnknownOS);
65 }
66 
67 template <>
68 llvm::Triple::ArchType stringTo<llvm::Triple::ArchType>(llvm::StringRef Str) {
69   using llvm::Triple;
70   return llvm::StringSwitch<Triple::ArchType>(Str)
71       .Case("arm", Triple::arm)
72       .Cases("arm64", "arm64e", Triple::aarch64)
73       .Case("mips", Triple::mips)
74       .Case("ppc", Triple::ppc)
75       .Case("ppc64", Triple::ppc64)
76       .Case("s390", Triple::systemz)
77       .Case("sparc", Triple::sparc)
78       .Case("sparcv9", Triple::sparcv9)
79       .Case("x86", Triple::x86)
80       .Cases("x86_64", "x86_64h", Triple::x86_64)
81       .Default(Triple::UnknownArch);
82 }
83 
84 template<typename T>
85 static T consume(llvm::StringRef &Str) {
86   llvm::StringRef Token;
87   std::tie(Token, Str) = getToken(Str);
88   return stringTo<T>(Token);
89 }
90 
91 /// Return the number of hex digits needed to encode an (POD) object of a given
92 /// type.
93 template <typename T> static constexpr size_t hex_digits() {
94   return 2 * sizeof(T);
95 }
96 
97 static UUID parseModuleId(llvm::Triple::OSType os, llvm::StringRef str) {
98   struct data_t {
99     using uuid_t = uint8_t[16];
100     uuid_t uuid;
101     llvm::support::ubig32_t age;
102   } data;
103   static_assert(sizeof(data) == 20);
104   // The textual module id encoding should be between 33 and 40 bytes long,
105   // depending on the size of the age field, which is of variable length.
106   // The first three chunks of the id are encoded in big endian, so we need to
107   // byte-swap those.
108   if (str.size() <= hex_digits<data_t::uuid_t>() ||
109       str.size() > hex_digits<data_t>())
110     return UUID();
111   if (!all_of(str, llvm::isHexDigit))
112     return UUID();
113 
114   llvm::StringRef uuid_str = str.take_front(hex_digits<data_t::uuid_t>());
115   llvm::StringRef age_str = str.drop_front(hex_digits<data_t::uuid_t>());
116 
117   llvm::copy(fromHex(uuid_str), data.uuid);
118   uint32_t age;
119   bool success = to_integer(age_str, age, 16);
120   assert(success);
121   (void)success;
122   data.age = age;
123 
124   // On non-windows, the age field should always be zero, so we don't include to
125   // match the native uuid format of these platforms.
126   return UUID(&data, os == llvm::Triple::Win32 ? sizeof(data)
127                                                : sizeof(data.uuid));
128 }
129 
130 std::optional<Record::Kind> Record::classify(llvm::StringRef Line) {
131   Token Tok = consume<Token>(Line);
132   switch (Tok) {
133   case Token::Module:
134     return Record::Module;
135   case Token::Info:
136     return Record::Info;
137   case Token::File:
138     return Record::File;
139   case Token::Func:
140     return Record::Func;
141   case Token::Public:
142     return Record::Public;
143   case Token::Stack:
144     Tok = consume<Token>(Line);
145     switch (Tok) {
146     case Token::CFI:
147       return Record::StackCFI;
148     case Token::Win:
149       return Record::StackWin;
150     default:
151       return std::nullopt;
152     }
153   case Token::Inline:
154     return Record::Inline;
155   case Token::InlineOrigin:
156     return Record::InlineOrigin;
157   case Token::Unknown:
158     // Optimistically assume that any unrecognised token means this is a line
159     // record, those don't have a special keyword and start directly with a
160     // hex number.
161     return Record::Line;
162 
163   case Token::CodeID:
164   case Token::CFI:
165   case Token::Init:
166   case Token::Win:
167     // These should never appear at the start of a valid record.
168     return std::nullopt;
169   }
170   llvm_unreachable("Fully covered switch above!");
171 }
172 
173 std::optional<ModuleRecord> ModuleRecord::parse(llvm::StringRef Line) {
174   // MODULE Linux x86_64 E5894855C35DCCCCCCCCCCCCCCCCCCCC0 a.out
175   if (consume<Token>(Line) != Token::Module)
176     return std::nullopt;
177 
178   llvm::Triple::OSType OS = consume<llvm::Triple::OSType>(Line);
179   if (OS == llvm::Triple::UnknownOS)
180     return std::nullopt;
181 
182   llvm::Triple::ArchType Arch = consume<llvm::Triple::ArchType>(Line);
183   if (Arch == llvm::Triple::UnknownArch)
184     return std::nullopt;
185 
186   llvm::StringRef Str;
187   std::tie(Str, Line) = getToken(Line);
188   UUID ID = parseModuleId(OS, Str);
189   if (!ID)
190     return std::nullopt;
191 
192   return ModuleRecord(OS, Arch, std::move(ID));
193 }
194 
195 llvm::raw_ostream &breakpad::operator<<(llvm::raw_ostream &OS,
196                                         const ModuleRecord &R) {
197   return OS << "MODULE " << llvm::Triple::getOSTypeName(R.OS) << " "
198             << llvm::Triple::getArchTypeName(R.Arch) << " "
199             << R.ID.GetAsString();
200 }
201 
202 std::optional<InfoRecord> InfoRecord::parse(llvm::StringRef Line) {
203   // INFO CODE_ID 554889E55DC3CCCCCCCCCCCCCCCCCCCC [a.exe]
204   if (consume<Token>(Line) != Token::Info)
205     return std::nullopt;
206 
207   if (consume<Token>(Line) != Token::CodeID)
208     return std::nullopt;
209 
210   llvm::StringRef Str;
211   std::tie(Str, Line) = getToken(Line);
212   // If we don't have any text following the code ID (e.g. on linux), we should
213   // use this as the UUID. Otherwise, we should revert back to the module ID.
214   UUID ID;
215   if (Line.trim().empty()) {
216     if (Str.empty() || !ID.SetFromStringRef(Str))
217       return std::nullopt;
218   }
219   return InfoRecord(std::move(ID));
220 }
221 
222 llvm::raw_ostream &breakpad::operator<<(llvm::raw_ostream &OS,
223                                         const InfoRecord &R) {
224   return OS << "INFO CODE_ID " << R.ID.GetAsString();
225 }
226 
227 template <typename T>
228 static std::optional<T> parseNumberName(llvm::StringRef Line, Token TokenType) {
229   // TOKEN number name
230   if (consume<Token>(Line) != TokenType)
231     return std::nullopt;
232 
233   llvm::StringRef Str;
234   size_t Number;
235   std::tie(Str, Line) = getToken(Line);
236   if (!to_integer(Str, Number))
237     return std::nullopt;
238 
239   llvm::StringRef Name = Line.trim();
240   if (Name.empty())
241     return std::nullopt;
242 
243   return T(Number, Name);
244 }
245 
246 std::optional<FileRecord> FileRecord::parse(llvm::StringRef Line) {
247   // FILE number name
248   return parseNumberName<FileRecord>(Line, Token::File);
249 }
250 
251 llvm::raw_ostream &breakpad::operator<<(llvm::raw_ostream &OS,
252                                         const FileRecord &R) {
253   return OS << "FILE " << R.Number << " " << R.Name;
254 }
255 
256 std::optional<InlineOriginRecord>
257 InlineOriginRecord::parse(llvm::StringRef Line) {
258   // INLINE_ORIGIN number name
259   return parseNumberName<InlineOriginRecord>(Line, Token::InlineOrigin);
260 }
261 
262 llvm::raw_ostream &breakpad::operator<<(llvm::raw_ostream &OS,
263                                         const InlineOriginRecord &R) {
264   return OS << "INLINE_ORIGIN " << R.Number << " " << R.Name;
265 }
266 
267 static bool parsePublicOrFunc(llvm::StringRef Line, bool &Multiple,
268                               lldb::addr_t &Address, lldb::addr_t *Size,
269                               lldb::addr_t &ParamSize, llvm::StringRef &Name) {
270   // PUBLIC [m] address param_size name
271   // or
272   // FUNC [m] address size param_size name
273 
274   Token Tok = Size ? Token::Func : Token::Public;
275 
276   if (consume<Token>(Line) != Tok)
277     return false;
278 
279   llvm::StringRef Str;
280   std::tie(Str, Line) = getToken(Line);
281   Multiple = Str == "m";
282 
283   if (Multiple)
284     std::tie(Str, Line) = getToken(Line);
285   if (!to_integer(Str, Address, 16))
286     return false;
287 
288   if (Tok == Token::Func) {
289     std::tie(Str, Line) = getToken(Line);
290     if (!to_integer(Str, *Size, 16))
291       return false;
292   }
293 
294   std::tie(Str, Line) = getToken(Line);
295   if (!to_integer(Str, ParamSize, 16))
296     return false;
297 
298   Name = Line.trim();
299   if (Name.empty())
300     return false;
301 
302   return true;
303 }
304 
305 std::optional<FuncRecord> FuncRecord::parse(llvm::StringRef Line) {
306   bool Multiple;
307   lldb::addr_t Address, Size, ParamSize;
308   llvm::StringRef Name;
309 
310   if (parsePublicOrFunc(Line, Multiple, Address, &Size, ParamSize, Name))
311     return FuncRecord(Multiple, Address, Size, ParamSize, Name);
312 
313   return std::nullopt;
314 }
315 
316 bool breakpad::operator==(const FuncRecord &L, const FuncRecord &R) {
317   return L.Multiple == R.Multiple && L.Address == R.Address &&
318          L.Size == R.Size && L.ParamSize == R.ParamSize && L.Name == R.Name;
319 }
320 llvm::raw_ostream &breakpad::operator<<(llvm::raw_ostream &OS,
321                                         const FuncRecord &R) {
322   return OS << llvm::formatv("FUNC {0}{1:x-} {2:x-} {3:x-} {4}",
323                              R.Multiple ? "m " : "", R.Address, R.Size,
324                              R.ParamSize, R.Name);
325 }
326 
327 std::optional<InlineRecord> InlineRecord::parse(llvm::StringRef Line) {
328   // INLINE inline_nest_level call_site_line call_site_file_num origin_num
329   // [address size]+
330   if (consume<Token>(Line) != Token::Inline)
331     return std::nullopt;
332 
333   llvm::SmallVector<llvm::StringRef> Tokens;
334   SplitString(Line, Tokens, " ");
335   if (Tokens.size() < 6 || Tokens.size() % 2 == 1)
336     return std::nullopt;
337 
338   size_t InlineNestLevel;
339   uint32_t CallSiteLineNum;
340   size_t CallSiteFileNum;
341   size_t OriginNum;
342   if (!(to_integer(Tokens[0], InlineNestLevel) &&
343         to_integer(Tokens[1], CallSiteLineNum) &&
344         to_integer(Tokens[2], CallSiteFileNum) &&
345         to_integer(Tokens[3], OriginNum)))
346     return std::nullopt;
347 
348   InlineRecord Record = InlineRecord(InlineNestLevel, CallSiteLineNum,
349                                      CallSiteFileNum, OriginNum);
350   for (size_t i = 4; i < Tokens.size(); i += 2) {
351     lldb::addr_t Address;
352     if (!to_integer(Tokens[i], Address, 16))
353       return std::nullopt;
354     lldb::addr_t Size;
355     if (!to_integer(Tokens[i + 1].trim(), Size, 16))
356       return std::nullopt;
357     Record.Ranges.emplace_back(Address, Size);
358   }
359   return Record;
360 }
361 
362 bool breakpad::operator==(const InlineRecord &L, const InlineRecord &R) {
363   return L.InlineNestLevel == R.InlineNestLevel &&
364          L.CallSiteLineNum == R.CallSiteLineNum &&
365          L.CallSiteFileNum == R.CallSiteFileNum && L.OriginNum == R.OriginNum &&
366          L.Ranges == R.Ranges;
367 }
368 
369 llvm::raw_ostream &breakpad::operator<<(llvm::raw_ostream &OS,
370                                         const InlineRecord &R) {
371   OS << llvm::formatv("INLINE {0} {1} {2} {3}", R.InlineNestLevel,
372                       R.CallSiteLineNum, R.CallSiteFileNum, R.OriginNum);
373   for (const auto &range : R.Ranges) {
374     OS << llvm::formatv(" {0:x-} {1:x-}", range.first, range.second);
375   }
376   return OS;
377 }
378 
379 std::optional<LineRecord> LineRecord::parse(llvm::StringRef Line) {
380   lldb::addr_t Address;
381   llvm::StringRef Str;
382   std::tie(Str, Line) = getToken(Line);
383   if (!to_integer(Str, Address, 16))
384     return std::nullopt;
385 
386   lldb::addr_t Size;
387   std::tie(Str, Line) = getToken(Line);
388   if (!to_integer(Str, Size, 16))
389     return std::nullopt;
390 
391   uint32_t LineNum;
392   std::tie(Str, Line) = getToken(Line);
393   if (!to_integer(Str, LineNum))
394     return std::nullopt;
395 
396   size_t FileNum;
397   std::tie(Str, Line) = getToken(Line);
398   if (!to_integer(Str, FileNum))
399     return std::nullopt;
400 
401   return LineRecord(Address, Size, LineNum, FileNum);
402 }
403 
404 bool breakpad::operator==(const LineRecord &L, const LineRecord &R) {
405   return L.Address == R.Address && L.Size == R.Size && L.LineNum == R.LineNum &&
406          L.FileNum == R.FileNum;
407 }
408 llvm::raw_ostream &breakpad::operator<<(llvm::raw_ostream &OS,
409                                         const LineRecord &R) {
410   return OS << llvm::formatv("{0:x-} {1:x-} {2} {3}", R.Address, R.Size,
411                              R.LineNum, R.FileNum);
412 }
413 
414 std::optional<PublicRecord> PublicRecord::parse(llvm::StringRef Line) {
415   bool Multiple;
416   lldb::addr_t Address, ParamSize;
417   llvm::StringRef Name;
418 
419   if (parsePublicOrFunc(Line, Multiple, Address, nullptr, ParamSize, Name))
420     return PublicRecord(Multiple, Address, ParamSize, Name);
421 
422   return std::nullopt;
423 }
424 
425 bool breakpad::operator==(const PublicRecord &L, const PublicRecord &R) {
426   return L.Multiple == R.Multiple && L.Address == R.Address &&
427          L.ParamSize == R.ParamSize && L.Name == R.Name;
428 }
429 llvm::raw_ostream &breakpad::operator<<(llvm::raw_ostream &OS,
430                                         const PublicRecord &R) {
431   return OS << llvm::formatv("PUBLIC {0}{1:x-} {2:x-} {3}",
432                              R.Multiple ? "m " : "", R.Address, R.ParamSize,
433                              R.Name);
434 }
435 
436 std::optional<StackCFIRecord> StackCFIRecord::parse(llvm::StringRef Line) {
437   // STACK CFI INIT address size reg1: expr1 reg2: expr2 ...
438   // or
439   // STACK CFI address reg1: expr1 reg2: expr2 ...
440   // No token in exprN ends with a colon.
441 
442   if (consume<Token>(Line) != Token::Stack)
443     return std::nullopt;
444   if (consume<Token>(Line) != Token::CFI)
445     return std::nullopt;
446 
447   llvm::StringRef Str;
448   std::tie(Str, Line) = getToken(Line);
449 
450   bool IsInitRecord = stringTo<Token>(Str) == Token::Init;
451   if (IsInitRecord)
452     std::tie(Str, Line) = getToken(Line);
453 
454   lldb::addr_t Address;
455   if (!to_integer(Str, Address, 16))
456     return std::nullopt;
457 
458   std::optional<lldb::addr_t> Size;
459   if (IsInitRecord) {
460     Size.emplace();
461     std::tie(Str, Line) = getToken(Line);
462     if (!to_integer(Str, *Size, 16))
463       return std::nullopt;
464   }
465 
466   return StackCFIRecord(Address, Size, Line.trim());
467 }
468 
469 bool breakpad::operator==(const StackCFIRecord &L, const StackCFIRecord &R) {
470   return L.Address == R.Address && L.Size == R.Size &&
471          L.UnwindRules == R.UnwindRules;
472 }
473 
474 llvm::raw_ostream &breakpad::operator<<(llvm::raw_ostream &OS,
475                                         const StackCFIRecord &R) {
476   OS << "STACK CFI ";
477   if (R.Size)
478     OS << "INIT ";
479   OS << llvm::formatv("{0:x-} ", R.Address);
480   if (R.Size)
481     OS << llvm::formatv("{0:x-} ", *R.Size);
482   return OS << " " << R.UnwindRules;
483 }
484 
485 std::optional<StackWinRecord> StackWinRecord::parse(llvm::StringRef Line) {
486   // STACK WIN type rva code_size prologue_size epilogue_size parameter_size
487   //     saved_register_size local_size max_stack_size has_program_string
488   //     program_string_OR_allocates_base_pointer
489 
490   if (consume<Token>(Line) != Token::Stack)
491     return std::nullopt;
492   if (consume<Token>(Line) != Token::Win)
493     return std::nullopt;
494 
495   llvm::StringRef Str;
496   uint8_t Type;
497   std::tie(Str, Line) = getToken(Line);
498   // Right now we only support the "FrameData" frame type.
499   if (!to_integer(Str, Type) || FrameType(Type) != FrameType::FrameData)
500     return std::nullopt;
501 
502   lldb::addr_t RVA;
503   std::tie(Str, Line) = getToken(Line);
504   if (!to_integer(Str, RVA, 16))
505     return std::nullopt;
506 
507   lldb::addr_t CodeSize;
508   std::tie(Str, Line) = getToken(Line);
509   if (!to_integer(Str, CodeSize, 16))
510     return std::nullopt;
511 
512   // Skip fields which we aren't using right now.
513   std::tie(Str, Line) = getToken(Line); // prologue_size
514   std::tie(Str, Line) = getToken(Line); // epilogue_size
515 
516   lldb::addr_t ParameterSize;
517   std::tie(Str, Line) = getToken(Line);
518   if (!to_integer(Str, ParameterSize, 16))
519     return std::nullopt;
520 
521   lldb::addr_t SavedRegisterSize;
522   std::tie(Str, Line) = getToken(Line);
523   if (!to_integer(Str, SavedRegisterSize, 16))
524     return std::nullopt;
525 
526   lldb::addr_t LocalSize;
527   std::tie(Str, Line) = getToken(Line);
528   if (!to_integer(Str, LocalSize, 16))
529     return std::nullopt;
530 
531   std::tie(Str, Line) = getToken(Line); // max_stack_size
532 
533   uint8_t HasProgramString;
534   std::tie(Str, Line) = getToken(Line);
535   if (!to_integer(Str, HasProgramString))
536     return std::nullopt;
537   // FrameData records should always have a program string.
538   if (!HasProgramString)
539     return std::nullopt;
540 
541   return StackWinRecord(RVA, CodeSize, ParameterSize, SavedRegisterSize,
542                         LocalSize, Line.trim());
543 }
544 
545 bool breakpad::operator==(const StackWinRecord &L, const StackWinRecord &R) {
546   return L.RVA == R.RVA && L.CodeSize == R.CodeSize &&
547          L.ParameterSize == R.ParameterSize &&
548          L.SavedRegisterSize == R.SavedRegisterSize &&
549          L.LocalSize == R.LocalSize && L.ProgramString == R.ProgramString;
550 }
551 
552 llvm::raw_ostream &breakpad::operator<<(llvm::raw_ostream &OS,
553                                         const StackWinRecord &R) {
554   return OS << llvm::formatv(
555              "STACK WIN 4 {0:x-} {1:x-} ? ? {2} {3} {4} ? 1 {5}", R.RVA,
556              R.CodeSize, R.ParameterSize, R.SavedRegisterSize, R.LocalSize,
557              R.ProgramString);
558 }
559 
560 llvm::StringRef breakpad::toString(Record::Kind K) {
561   switch (K) {
562   case Record::Module:
563     return "MODULE";
564   case Record::Info:
565     return "INFO";
566   case Record::File:
567     return "FILE";
568   case Record::Func:
569     return "FUNC";
570   case Record::Inline:
571     return "INLINE";
572   case Record::InlineOrigin:
573     return "INLINE_ORIGIN";
574   case Record::Line:
575     return "LINE";
576   case Record::Public:
577     return "PUBLIC";
578   case Record::StackCFI:
579     return "STACK CFI";
580   case Record::StackWin:
581     return "STACK WIN";
582   }
583   llvm_unreachable("Unknown record kind!");
584 }
585