xref: /llvm-project-15.0.7/llvm/lib/XRay/Trace.cpp (revision fbfaec70)
1 //===- Trace.cpp - XRay Trace Loading implementation. ---------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // XRay log reader implementation.
11 //
12 //===----------------------------------------------------------------------===//
13 #include "llvm/XRay/Trace.h"
14 #include "llvm/ADT/STLExtras.h"
15 #include "llvm/Support/DataExtractor.h"
16 #include "llvm/Support/Error.h"
17 #include "llvm/Support/FileSystem.h"
18 #include "llvm/XRay/YAMLXRayRecord.h"
19 
20 using namespace llvm;
21 using namespace llvm::xray;
22 using llvm::yaml::Input;
23 
24 namespace {
25 using XRayRecordStorage =
26     std::aligned_storage<sizeof(XRayRecord), alignof(XRayRecord)>::type;
27 
28 // Populates the FileHeader reference by reading the first 32 bytes of the file.
29 Error readBinaryFormatHeader(StringRef Data, XRayFileHeader &FileHeader) {
30   // FIXME: Maybe deduce whether the data is little or big-endian using some
31   // magic bytes in the beginning of the file?
32 
33   // First 32 bytes of the file will always be the header. We assume a certain
34   // format here:
35   //
36   //   (2)   uint16 : version
37   //   (2)   uint16 : type
38   //   (4)   uint32 : bitfield
39   //   (8)   uint64 : cycle frequency
40   //   (16)  -      : padding
41 
42   DataExtractor HeaderExtractor(Data, true, 8);
43   uint32_t OffsetPtr = 0;
44   FileHeader.Version = HeaderExtractor.getU16(&OffsetPtr);
45   FileHeader.Type = HeaderExtractor.getU16(&OffsetPtr);
46   uint32_t Bitfield = HeaderExtractor.getU32(&OffsetPtr);
47   FileHeader.ConstantTSC = Bitfield & 1uL;
48   FileHeader.NonstopTSC = Bitfield & 1uL << 1;
49   FileHeader.CycleFrequency = HeaderExtractor.getU64(&OffsetPtr);
50   std::memcpy(&FileHeader.FreeFormData, Data.bytes_begin() + OffsetPtr, 16);
51   if (FileHeader.Version != 1 && FileHeader.Version != 2)
52     return make_error<StringError>(
53         Twine("Unsupported XRay file version: ") + Twine(FileHeader.Version),
54         std::make_error_code(std::errc::invalid_argument));
55   return Error::success();
56 }
57 
58 Error loadNaiveFormatLog(StringRef Data, XRayFileHeader &FileHeader,
59                          std::vector<XRayRecord> &Records) {
60   if (Data.size() < 32)
61     return make_error<StringError>(
62         "Not enough bytes for an XRay log.",
63         std::make_error_code(std::errc::invalid_argument));
64 
65   if (Data.size() - 32 == 0 || Data.size() % 32 != 0)
66     return make_error<StringError>(
67         "Invalid-sized XRay data.",
68         std::make_error_code(std::errc::invalid_argument));
69 
70   if (auto E = readBinaryFormatHeader(Data, FileHeader))
71     return E;
72 
73   // Each record after the header will be 32 bytes, in the following format:
74   //
75   //   (2)   uint16 : record type
76   //   (1)   uint8  : cpu id
77   //   (1)   uint8  : type
78   //   (4)   sint32 : function id
79   //   (8)   uint64 : tsc
80   //   (4)   uint32 : thread id
81   //   (12)  -      : padding
82   for (auto S = Data.drop_front(32); !S.empty(); S = S.drop_front(32)) {
83     DataExtractor RecordExtractor(S, true, 8);
84     uint32_t OffsetPtr = 0;
85     Records.emplace_back();
86     auto &Record = Records.back();
87     Record.RecordType = RecordExtractor.getU16(&OffsetPtr);
88     Record.CPU = RecordExtractor.getU8(&OffsetPtr);
89     auto Type = RecordExtractor.getU8(&OffsetPtr);
90     switch (Type) {
91     case 0:
92       Record.Type = RecordTypes::ENTER;
93       break;
94     case 1:
95       Record.Type = RecordTypes::EXIT;
96       break;
97     case 2:
98       Record.Type = RecordTypes::TAIL_EXIT;
99       break;
100     default:
101       return make_error<StringError>(
102           Twine("Unknown record type '") + Twine(int{Type}) + "'",
103           std::make_error_code(std::errc::executable_format_error));
104     }
105     Record.FuncId = RecordExtractor.getSigned(&OffsetPtr, sizeof(int32_t));
106     Record.TSC = RecordExtractor.getU64(&OffsetPtr);
107     Record.TId = RecordExtractor.getU32(&OffsetPtr);
108   }
109   return Error::success();
110 }
111 
112 /// When reading from a Flight Data Recorder mode log, metadata records are
113 /// sparse compared to packed function records, so we must maintain state as we
114 /// read through the sequence of entries. This allows the reader to denormalize
115 /// the CPUId and Thread Id onto each Function Record and transform delta
116 /// encoded TSC values into absolute encodings on each record.
117 struct FDRState {
118   uint16_t CPUId;
119   uint16_t ThreadId;
120   uint64_t BaseTSC;
121 
122   /// Encode some of the state transitions for the FDR log reader as explicit
123   /// checks. These are expectations for the next Record in the stream.
124   enum class Token {
125     NEW_BUFFER_RECORD_OR_EOF,
126     WALLCLOCK_RECORD,
127     NEW_CPU_ID_RECORD,
128     FUNCTION_SEQUENCE,
129     SCAN_TO_END_OF_THREAD_BUF,
130     CUSTOM_EVENT_DATA,
131   };
132   Token Expects;
133 
134   // Each threads buffer may have trailing garbage to scan over, so we track our
135   // progress.
136   uint64_t CurrentBufferSize;
137   uint64_t CurrentBufferConsumed;
138 };
139 
140 const char *fdrStateToTwine(const FDRState::Token &state) {
141   switch (state) {
142   case FDRState::Token::NEW_BUFFER_RECORD_OR_EOF:
143     return "NEW_BUFFER_RECORD_OR_EOF";
144   case FDRState::Token::WALLCLOCK_RECORD:
145     return "WALLCLOCK_RECORD";
146   case FDRState::Token::NEW_CPU_ID_RECORD:
147     return "NEW_CPU_ID_RECORD";
148   case FDRState::Token::FUNCTION_SEQUENCE:
149     return "FUNCTION_SEQUENCE";
150   case FDRState::Token::SCAN_TO_END_OF_THREAD_BUF:
151     return "SCAN_TO_END_OF_THREAD_BUF";
152   case FDRState::Token::CUSTOM_EVENT_DATA:
153     return "CUSTOM_EVENT_DATA";
154   }
155   return "UNKNOWN";
156 }
157 
158 /// State transition when a NewBufferRecord is encountered.
159 Error processFDRNewBufferRecord(FDRState &State, uint8_t RecordFirstByte,
160                                 DataExtractor &RecordExtractor) {
161 
162   if (State.Expects != FDRState::Token::NEW_BUFFER_RECORD_OR_EOF)
163     return make_error<StringError>(
164         "Malformed log. Read New Buffer record kind out of sequence",
165         std::make_error_code(std::errc::executable_format_error));
166   uint32_t OffsetPtr = 1; // 1 byte into record.
167   State.ThreadId = RecordExtractor.getU16(&OffsetPtr);
168   State.Expects = FDRState::Token::WALLCLOCK_RECORD;
169   return Error::success();
170 }
171 
172 /// State transition when an EndOfBufferRecord is encountered.
173 Error processFDREndOfBufferRecord(FDRState &State, uint8_t RecordFirstByte,
174                                   DataExtractor &RecordExtractor) {
175   if (State.Expects == FDRState::Token::NEW_BUFFER_RECORD_OR_EOF)
176     return make_error<StringError>(
177         "Malformed log. Received EOB message without current buffer.",
178         std::make_error_code(std::errc::executable_format_error));
179   State.Expects = FDRState::Token::SCAN_TO_END_OF_THREAD_BUF;
180   return Error::success();
181 }
182 
183 /// State transition when a NewCPUIdRecord is encountered.
184 Error processFDRNewCPUIdRecord(FDRState &State, uint8_t RecordFirstByte,
185                                DataExtractor &RecordExtractor) {
186   if (State.Expects != FDRState::Token::FUNCTION_SEQUENCE &&
187       State.Expects != FDRState::Token::NEW_CPU_ID_RECORD)
188     return make_error<StringError>(
189         "Malformed log. Read NewCPUId record kind out of sequence",
190         std::make_error_code(std::errc::executable_format_error));
191   uint32_t OffsetPtr = 1; // Read starting after the first byte.
192   State.CPUId = RecordExtractor.getU16(&OffsetPtr);
193   State.BaseTSC = RecordExtractor.getU64(&OffsetPtr);
194   State.Expects = FDRState::Token::FUNCTION_SEQUENCE;
195   return Error::success();
196 }
197 
198 /// State transition when a TSCWrapRecord (overflow detection) is encountered.
199 Error processFDRTSCWrapRecord(FDRState &State, uint8_t RecordFirstByte,
200                               DataExtractor &RecordExtractor) {
201   if (State.Expects != FDRState::Token::FUNCTION_SEQUENCE)
202     return make_error<StringError>(
203         "Malformed log. Read TSCWrap record kind out of sequence",
204         std::make_error_code(std::errc::executable_format_error));
205   uint32_t OffsetPtr = 1; // Read starting after the first byte.
206   State.BaseTSC = RecordExtractor.getU64(&OffsetPtr);
207   return Error::success();
208 }
209 
210 /// State transition when a WallTimeMarkerRecord is encountered.
211 Error processFDRWallTimeRecord(FDRState &State, uint8_t RecordFirstByte,
212                                DataExtractor &RecordExtractor) {
213   if (State.Expects != FDRState::Token::WALLCLOCK_RECORD)
214     return make_error<StringError>(
215         "Malformed log. Read Wallclock record kind out of sequence",
216         std::make_error_code(std::errc::executable_format_error));
217   // We don't encode the wall time into any of the records.
218   // XRayRecords are concerned with the TSC instead.
219   State.Expects = FDRState::Token::NEW_CPU_ID_RECORD;
220   return Error::success();
221 }
222 
223 /// State transition when a CustomEventMarker is encountered.
224 Error processCustomEventMarker(FDRState &State, uint8_t RecordFirstByte,
225                                DataExtractor &RecordExtractor,
226                                size_t &RecordSize) {
227   // We can encounter a CustomEventMarker anywhere in the log, so we can handle
228   // it regardless of the expectation. However, we do set the expectation to
229   // read a set number of fixed bytes, as described in the metadata.
230   uint32_t OffsetPtr = 1; // Read after the first byte.
231   uint32_t DataSize = RecordExtractor.getU32(&OffsetPtr);
232   uint64_t TSC = RecordExtractor.getU64(&OffsetPtr);
233 
234   // FIXME: Actually represent the record through the API. For now we only skip
235   // through the data.
236   (void)TSC;
237   RecordSize = 16 + DataSize;
238   return Error::success();
239 }
240 
241 /// Advances the state machine for reading the FDR record type by reading one
242 /// Metadata Record and updating the State appropriately based on the kind of
243 /// record encountered. The RecordKind is encoded in the first byte of the
244 /// Record, which the caller should pass in because they have already read it
245 /// to determine that this is a metadata record as opposed to a function record.
246 Error processFDRMetadataRecord(FDRState &State, uint8_t RecordFirstByte,
247                                DataExtractor &RecordExtractor,
248                                size_t &RecordSize) {
249   // The remaining 7 bits are the RecordKind enum.
250   uint8_t RecordKind = RecordFirstByte >> 1;
251   switch (RecordKind) {
252   case 0: // NewBuffer
253     if (auto E =
254             processFDRNewBufferRecord(State, RecordFirstByte, RecordExtractor))
255       return E;
256     break;
257   case 1: // EndOfBuffer
258     if (auto E = processFDREndOfBufferRecord(State, RecordFirstByte,
259                                              RecordExtractor))
260       return E;
261     break;
262   case 2: // NewCPUId
263     if (auto E =
264             processFDRNewCPUIdRecord(State, RecordFirstByte, RecordExtractor))
265       return E;
266     break;
267   case 3: // TSCWrap
268     if (auto E =
269             processFDRTSCWrapRecord(State, RecordFirstByte, RecordExtractor))
270       return E;
271     break;
272   case 4: // WallTimeMarker
273     if (auto E =
274             processFDRWallTimeRecord(State, RecordFirstByte, RecordExtractor))
275       return E;
276     break;
277   case 5: // CustomEventMarker
278     if (auto E = processCustomEventMarker(State, RecordFirstByte,
279                                           RecordExtractor, RecordSize))
280       return E;
281     break;
282   default:
283     // Widen the record type to uint16_t to prevent conversion to char.
284     return make_error<StringError>(
285         Twine("Illegal metadata record type: ")
286             .concat(Twine(static_cast<unsigned>(RecordKind))),
287         std::make_error_code(std::errc::executable_format_error));
288   }
289   return Error::success();
290 }
291 
292 /// Reads a function record from an FDR format log, appending a new XRayRecord
293 /// to the vector being populated and updating the State with a new value
294 /// reference value to interpret TSC deltas.
295 ///
296 /// The XRayRecord constructed includes information from the function record
297 /// processed here as well as Thread ID and CPU ID formerly extracted into
298 /// State.
299 Error processFDRFunctionRecord(FDRState &State, uint8_t RecordFirstByte,
300                                DataExtractor &RecordExtractor,
301                                std::vector<XRayRecord> &Records) {
302   switch (State.Expects) {
303   case FDRState::Token::NEW_BUFFER_RECORD_OR_EOF:
304     return make_error<StringError>(
305         "Malformed log. Received Function Record before new buffer setup.",
306         std::make_error_code(std::errc::executable_format_error));
307   case FDRState::Token::WALLCLOCK_RECORD:
308     return make_error<StringError>(
309         "Malformed log. Received Function Record when expecting wallclock.",
310         std::make_error_code(std::errc::executable_format_error));
311   case FDRState::Token::NEW_CPU_ID_RECORD:
312     return make_error<StringError>(
313         "Malformed log. Received Function Record before first CPU record.",
314         std::make_error_code(std::errc::executable_format_error));
315   default:
316     Records.emplace_back();
317     auto &Record = Records.back();
318     Record.RecordType = 0; // Record is type NORMAL.
319     // Strip off record type bit and use the next three bits.
320     uint8_t RecordType = (RecordFirstByte >> 1) & 0x07;
321     switch (RecordType) {
322     case static_cast<uint8_t>(RecordTypes::ENTER):
323       Record.Type = RecordTypes::ENTER;
324       break;
325     case static_cast<uint8_t>(RecordTypes::EXIT):
326       Record.Type = RecordTypes::EXIT;
327       break;
328     case static_cast<uint8_t>(RecordTypes::TAIL_EXIT):
329       Record.Type = RecordTypes::TAIL_EXIT;
330       break;
331     default:
332       // Cast to an unsigned integer to not interpret the record type as a char.
333       return make_error<StringError>(
334           Twine("Illegal function record type: ")
335               .concat(Twine(static_cast<unsigned>(RecordType))),
336           std::make_error_code(std::errc::executable_format_error));
337     }
338     Record.CPU = State.CPUId;
339     Record.TId = State.ThreadId;
340     // Back up to read first 32 bits, including the 4 we pulled RecordType
341     // and RecordKind out of. The remaining 28 are FunctionId.
342     uint32_t OffsetPtr = 0;
343     // Despite function Id being a signed int on XRayRecord,
344     // when it is written to an FDR format, the top bits are truncated,
345     // so it is effectively an unsigned value. When we shift off the
346     // top four bits, we want the shift to be logical, so we read as
347     // uint32_t.
348     uint32_t FuncIdBitField = RecordExtractor.getU32(&OffsetPtr);
349     Record.FuncId = FuncIdBitField >> 4;
350     // FunctionRecords have a 32 bit delta from the previous absolute TSC
351     // or TSC delta. If this would overflow, we should read a TSCWrap record
352     // with an absolute TSC reading.
353     uint64_t NewTSC = State.BaseTSC + RecordExtractor.getU32(&OffsetPtr);
354     State.BaseTSC = NewTSC;
355     Record.TSC = NewTSC;
356   }
357   return Error::success();
358 }
359 
360 /// Reads a log in FDR mode for version 1 of this binary format. FDR mode is
361 /// defined as part of the compiler-rt project in xray_fdr_logging.h, and such
362 /// a log consists of the familiar 32 bit XRayHeader, followed by sequences of
363 /// of interspersed 16 byte Metadata Records and 8 byte Function Records.
364 ///
365 /// The following is an attempt to document the grammar of the format, which is
366 /// parsed by this function for little-endian machines. Since the format makes
367 /// use of BitFields, when we support big-endian architectures, we will need to
368 /// adjust not only the endianness parameter to llvm's RecordExtractor, but also
369 /// the bit twiddling logic, which is consistent with the little-endian
370 /// convention that BitFields within a struct will first be packed into the
371 /// least significant bits the address they belong to.
372 ///
373 /// We expect a format complying with the grammar in the following pseudo-EBNF.
374 ///
375 /// FDRLog: XRayFileHeader ThreadBuffer*
376 /// XRayFileHeader: 32 bytes to identify the log as FDR with machine metadata.
377 ///     Includes BufferSize
378 /// ThreadBuffer: NewBuffer WallClockTime NewCPUId FunctionSequence EOB
379 /// BufSize: 8 byte unsigned integer indicating how large the buffer is.
380 /// NewBuffer: 16 byte metadata record with Thread Id.
381 /// WallClockTime: 16 byte metadata record with human readable time.
382 /// NewCPUId: 16 byte metadata record with CPUId and a 64 bit TSC reading.
383 /// EOB: 16 byte record in a thread buffer plus mem garbage to fill BufSize.
384 /// FunctionSequence: NewCPUId | TSCWrap | FunctionRecord
385 /// TSCWrap: 16 byte metadata record with a full 64 bit TSC reading.
386 /// FunctionRecord: 8 byte record with FunctionId, entry/exit, and TSC delta.
387 Error loadFDRLog(StringRef Data, XRayFileHeader &FileHeader,
388                  std::vector<XRayRecord> &Records) {
389   if (Data.size() < 32)
390     return make_error<StringError>(
391         "Not enough bytes for an XRay log.",
392         std::make_error_code(std::errc::invalid_argument));
393 
394   // For an FDR log, there are records sized 16 and 8 bytes.
395   // There actually may be no records if no non-trivial functions are
396   // instrumented.
397   if (Data.size() % 8 != 0)
398     return make_error<StringError>(
399         "Invalid-sized XRay data.",
400         std::make_error_code(std::errc::invalid_argument));
401 
402   if (auto E = readBinaryFormatHeader(Data, FileHeader))
403     return E;
404 
405   uint64_t BufferSize = 0;
406   {
407     StringRef ExtraDataRef(FileHeader.FreeFormData, 16);
408     DataExtractor ExtraDataExtractor(ExtraDataRef, true, 8);
409     uint32_t ExtraDataOffset = 0;
410     BufferSize = ExtraDataExtractor.getU64(&ExtraDataOffset);
411   }
412   FDRState State{0,          0, 0, FDRState::Token::NEW_BUFFER_RECORD_OR_EOF,
413                  BufferSize, 0};
414   // RecordSize will tell the loop how far to seek ahead based on the record
415   // type that we have just read.
416   size_t RecordSize = 0;
417   for (auto S = Data.drop_front(32); !S.empty(); S = S.drop_front(RecordSize)) {
418     DataExtractor RecordExtractor(S, true, 8);
419     uint32_t OffsetPtr = 0;
420     if (State.Expects == FDRState::Token::SCAN_TO_END_OF_THREAD_BUF) {
421       RecordSize = State.CurrentBufferSize - State.CurrentBufferConsumed;
422       if (S.size() < RecordSize) {
423         return make_error<StringError>(
424             Twine("Incomplete thread buffer. Expected at least ") +
425                 Twine(RecordSize) + " bytes but found " + Twine(S.size()),
426             make_error_code(std::errc::invalid_argument));
427       }
428       State.CurrentBufferConsumed = 0;
429       State.Expects = FDRState::Token::NEW_BUFFER_RECORD_OR_EOF;
430       continue;
431     }
432     uint8_t BitField = RecordExtractor.getU8(&OffsetPtr);
433     bool isMetadataRecord = BitField & 0x01uL;
434     if (isMetadataRecord) {
435       RecordSize = 16;
436       if (auto E = processFDRMetadataRecord(State, BitField, RecordExtractor,
437                                             RecordSize))
438         return E;
439     } else { // Process Function Record
440       RecordSize = 8;
441       if (auto E = processFDRFunctionRecord(State, BitField, RecordExtractor,
442                                             Records))
443         return E;
444     }
445     State.CurrentBufferConsumed += RecordSize;
446   }
447 
448   // Having iterated over everything we've been given, we've either consumed
449   // everything and ended up in the end state, or were told to skip the rest.
450   bool Finished = State.Expects == FDRState::Token::SCAN_TO_END_OF_THREAD_BUF &&
451                   State.CurrentBufferSize == State.CurrentBufferConsumed;
452   if (State.Expects != FDRState::Token::NEW_BUFFER_RECORD_OR_EOF && !Finished)
453     return make_error<StringError>(
454         Twine("Encountered EOF with unexpected state expectation ") +
455             fdrStateToTwine(State.Expects) +
456             ". Remaining expected bytes in thread buffer total " +
457             Twine(State.CurrentBufferSize - State.CurrentBufferConsumed),
458         std::make_error_code(std::errc::executable_format_error));
459 
460   return Error::success();
461 }
462 
463 Error loadYAMLLog(StringRef Data, XRayFileHeader &FileHeader,
464                   std::vector<XRayRecord> &Records) {
465   YAMLXRayTrace Trace;
466   Input In(Data);
467   In >> Trace;
468   if (In.error())
469     return make_error<StringError>("Failed loading YAML Data.", In.error());
470 
471   FileHeader.Version = Trace.Header.Version;
472   FileHeader.Type = Trace.Header.Type;
473   FileHeader.ConstantTSC = Trace.Header.ConstantTSC;
474   FileHeader.NonstopTSC = Trace.Header.NonstopTSC;
475   FileHeader.CycleFrequency = Trace.Header.CycleFrequency;
476 
477   if (FileHeader.Version != 1)
478     return make_error<StringError>(
479         Twine("Unsupported XRay file version: ") + Twine(FileHeader.Version),
480         std::make_error_code(std::errc::invalid_argument));
481 
482   Records.clear();
483   std::transform(Trace.Records.begin(), Trace.Records.end(),
484                  std::back_inserter(Records), [&](const YAMLXRayRecord &R) {
485                    return XRayRecord{R.RecordType, R.CPU, R.Type,
486                                      R.FuncId,     R.TSC, R.TId};
487                  });
488   return Error::success();
489 }
490 } // namespace
491 
492 Expected<Trace> llvm::xray::loadTraceFile(StringRef Filename, bool Sort) {
493   int Fd;
494   if (auto EC = sys::fs::openFileForRead(Filename, Fd)) {
495     return make_error<StringError>(
496         Twine("Cannot read log from '") + Filename + "'", EC);
497   }
498 
499   uint64_t FileSize;
500   if (auto EC = sys::fs::file_size(Filename, FileSize)) {
501     return make_error<StringError>(
502         Twine("Cannot read log from '") + Filename + "'", EC);
503   }
504   if (FileSize < 4) {
505     return make_error<StringError>(
506         Twine("File '") + Filename + "' too small for XRay.",
507         std::make_error_code(std::errc::executable_format_error));
508   }
509 
510   // Map the opened file into memory and use a StringRef to access it later.
511   std::error_code EC;
512   sys::fs::mapped_file_region MappedFile(
513       Fd, sys::fs::mapped_file_region::mapmode::readonly, FileSize, 0, EC);
514   if (EC) {
515     return make_error<StringError>(
516         Twine("Cannot read log from '") + Filename + "'", EC);
517   }
518   auto Data = StringRef(MappedFile.data(), MappedFile.size());
519 
520   // Attempt to detect the file type using file magic. We have a slight bias
521   // towards the binary format, and we do this by making sure that the first 4
522   // bytes of the binary file is some combination of the following byte
523   // patterns: (observe the code loading them assumes they're little endian)
524   //
525   //   0x01 0x00 0x00 0x00 - version 1, "naive" format
526   //   0x01 0x00 0x01 0x00 - version 1, "flight data recorder" format
527   //
528   // YAML files don't typically have those first four bytes as valid text so we
529   // try loading assuming YAML if we don't find these bytes.
530   //
531   // Only if we can't load either the binary or the YAML format will we yield an
532   // error.
533   StringRef Magic(MappedFile.data(), 4);
534   DataExtractor HeaderExtractor(Magic, true, 8);
535   uint32_t OffsetPtr = 0;
536   uint16_t Version = HeaderExtractor.getU16(&OffsetPtr);
537   uint16_t Type = HeaderExtractor.getU16(&OffsetPtr);
538 
539   enum BinaryFormatType { NAIVE_FORMAT = 0, FLIGHT_DATA_RECORDER_FORMAT = 1 };
540 
541   Trace T;
542   if (Type == NAIVE_FORMAT && (Version == 1 || Version == 2)) {
543     if (auto E = loadNaiveFormatLog(Data, T.FileHeader, T.Records))
544       return std::move(E);
545   } else if (Version == 1 && Type == FLIGHT_DATA_RECORDER_FORMAT) {
546     if (auto E = loadFDRLog(Data, T.FileHeader, T.Records))
547       return std::move(E);
548   } else {
549     if (auto E = loadYAMLLog(Data, T.FileHeader, T.Records))
550       return std::move(E);
551   }
552 
553   if (Sort)
554     std::sort(T.Records.begin(), T.Records.end(),
555               [&](const XRayRecord &L, const XRayRecord &R) {
556                 return L.TSC < R.TSC;
557               });
558 
559   return std::move(T);
560 }
561