xref: /llvm-project-15.0.7/llvm/lib/XRay/Trace.cpp (revision 59439dd0)
1d6c18657SDean Michael Berris //===- Trace.cpp - XRay Trace Loading implementation. ---------------------===//
2d6c18657SDean Michael Berris //
3d6c18657SDean Michael Berris //                     The LLVM Compiler Infrastructure
4d6c18657SDean Michael Berris //
5d6c18657SDean Michael Berris // This file is distributed under the University of Illinois Open Source
6d6c18657SDean Michael Berris // License. See LICENSE.TXT for details.
7d6c18657SDean Michael Berris //
8d6c18657SDean Michael Berris //===----------------------------------------------------------------------===//
9d6c18657SDean Michael Berris //
10d6c18657SDean Michael Berris // XRay log reader implementation.
11d6c18657SDean Michael Berris //
12d6c18657SDean Michael Berris //===----------------------------------------------------------------------===//
13d6c18657SDean Michael Berris #include "llvm/XRay/Trace.h"
14d6c18657SDean Michael Berris #include "llvm/ADT/STLExtras.h"
15d6c18657SDean Michael Berris #include "llvm/Support/DataExtractor.h"
16d6c18657SDean Michael Berris #include "llvm/Support/Error.h"
17d6c18657SDean Michael Berris #include "llvm/Support/FileSystem.h"
18985c2b92SDean Michael Berris #include "llvm/XRay/BlockIndexer.h"
19985c2b92SDean Michael Berris #include "llvm/XRay/BlockVerifier.h"
20985c2b92SDean Michael Berris #include "llvm/XRay/FDRRecordConsumer.h"
21985c2b92SDean Michael Berris #include "llvm/XRay/FDRRecordProducer.h"
22985c2b92SDean Michael Berris #include "llvm/XRay/FDRRecords.h"
23985c2b92SDean Michael Berris #include "llvm/XRay/FDRTraceExpander.h"
24d764c1b6SDean Michael Berris #include "llvm/XRay/FileHeaderReader.h"
25d6c18657SDean Michael Berris #include "llvm/XRay/YAMLXRayRecord.h"
26985c2b92SDean Michael Berris #include <memory>
27985c2b92SDean Michael Berris #include <vector>
28d6c18657SDean Michael Berris 
29d6c18657SDean Michael Berris using namespace llvm;
30d6c18657SDean Michael Berris using namespace llvm::xray;
31d6c18657SDean Michael Berris using llvm::yaml::Input;
32d6c18657SDean Michael Berris 
3349a49fe8SBenjamin Kramer namespace {
34d6c18657SDean Michael Berris using XRayRecordStorage =
35d6c18657SDean Michael Berris     std::aligned_storage<sizeof(XRayRecord), alignof(XRayRecord)>::type;
36d6c18657SDean Michael Berris 
375b7548c6SDean Michael Berris Error loadNaiveFormatLog(StringRef Data, bool IsLittleEndian,
385b7548c6SDean Michael Berris                          XRayFileHeader &FileHeader,
394f83c4d1SDean Michael Berris                          std::vector<XRayRecord> &Records) {
404f83c4d1SDean Michael Berris   if (Data.size() < 32)
414f83c4d1SDean Michael Berris     return make_error<StringError>(
424f83c4d1SDean Michael Berris         "Not enough bytes for an XRay log.",
434f83c4d1SDean Michael Berris         std::make_error_code(std::errc::invalid_argument));
444f83c4d1SDean Michael Berris 
454f83c4d1SDean Michael Berris   if (Data.size() - 32 == 0 || Data.size() % 32 != 0)
464f83c4d1SDean Michael Berris     return make_error<StringError>(
474f83c4d1SDean Michael Berris         "Invalid-sized XRay data.",
484f83c4d1SDean Michael Berris         std::make_error_code(std::errc::invalid_argument));
494f83c4d1SDean Michael Berris 
505b7548c6SDean Michael Berris   DataExtractor Reader(Data, IsLittleEndian, 8);
51a9d477a6SDean Michael Berris   uint32_t OffsetPtr = 0;
52d764c1b6SDean Michael Berris   auto FileHeaderOrError = readBinaryFormatHeader(Reader, OffsetPtr);
53d764c1b6SDean Michael Berris   if (!FileHeaderOrError)
54d764c1b6SDean Michael Berris     return FileHeaderOrError.takeError();
55d764c1b6SDean Michael Berris   FileHeader = std::move(FileHeaderOrError.get());
56d6c18657SDean Michael Berris 
57d6c18657SDean Michael Berris   // Each record after the header will be 32 bytes, in the following format:
58d6c18657SDean Michael Berris   //
59d6c18657SDean Michael Berris   //   (2)   uint16 : record type
60d6c18657SDean Michael Berris   //   (1)   uint8  : cpu id
61d6c18657SDean Michael Berris   //   (1)   uint8  : type
62d6c18657SDean Michael Berris   //   (4)   sint32 : function id
63d6c18657SDean Michael Berris   //   (8)   uint64 : tsc
64d6c18657SDean Michael Berris   //   (4)   uint32 : thread id
6510141261SDean Michael Berris   //   (4)   uint32 : process id
6610141261SDean Michael Berris   //   (8)   -      : padding
67a9d477a6SDean Michael Berris   while (Reader.isValidOffset(OffsetPtr)) {
68a9d477a6SDean Michael Berris     if (!Reader.isValidOffsetForDataOfSize(OffsetPtr, 32))
69a9d477a6SDean Michael Berris       return createStringError(
70a9d477a6SDean Michael Berris           std::make_error_code(std::errc::executable_format_error),
71a9d477a6SDean Michael Berris           "Not enough bytes to read a full record at offset %d.", OffsetPtr);
72a9d477a6SDean Michael Berris     auto PreReadOffset = OffsetPtr;
73a9d477a6SDean Michael Berris     auto RecordType = Reader.getU16(&OffsetPtr);
74a9d477a6SDean Michael Berris     if (OffsetPtr == PreReadOffset)
75a9d477a6SDean Michael Berris       return createStringError(
76a9d477a6SDean Michael Berris           std::make_error_code(std::errc::executable_format_error),
77a9d477a6SDean Michael Berris           "Failed reading record type at offset %d.", OffsetPtr);
78a9d477a6SDean Michael Berris 
79a9d477a6SDean Michael Berris     switch (RecordType) {
800a465d7aSDean Michael Berris     case 0: { // Normal records.
81d6c18657SDean Michael Berris       Records.emplace_back();
82d6c18657SDean Michael Berris       auto &Record = Records.back();
830a465d7aSDean Michael Berris       Record.RecordType = RecordType;
84a9d477a6SDean Michael Berris 
85a9d477a6SDean Michael Berris       PreReadOffset = OffsetPtr;
86a9d477a6SDean Michael Berris       Record.CPU = Reader.getU8(&OffsetPtr);
87a9d477a6SDean Michael Berris       if (OffsetPtr == PreReadOffset)
88a9d477a6SDean Michael Berris         return createStringError(
89a9d477a6SDean Michael Berris             std::make_error_code(std::errc::executable_format_error),
90a9d477a6SDean Michael Berris             "Failed reading CPU field at offset %d.", OffsetPtr);
91a9d477a6SDean Michael Berris 
92a9d477a6SDean Michael Berris       PreReadOffset = OffsetPtr;
93a9d477a6SDean Michael Berris       auto Type = Reader.getU8(&OffsetPtr);
94a9d477a6SDean Michael Berris       if (OffsetPtr == PreReadOffset)
95a9d477a6SDean Michael Berris         return createStringError(
96a9d477a6SDean Michael Berris             std::make_error_code(std::errc::executable_format_error),
97a9d477a6SDean Michael Berris             "Failed reading record type field at offset %d.", OffsetPtr);
98a9d477a6SDean Michael Berris 
99d6c18657SDean Michael Berris       switch (Type) {
100d6c18657SDean Michael Berris       case 0:
101d6c18657SDean Michael Berris         Record.Type = RecordTypes::ENTER;
102d6c18657SDean Michael Berris         break;
103d6c18657SDean Michael Berris       case 1:
104d6c18657SDean Michael Berris         Record.Type = RecordTypes::EXIT;
105d6c18657SDean Michael Berris         break;
1060f84a7d3SDean Michael Berris       case 2:
1070f84a7d3SDean Michael Berris         Record.Type = RecordTypes::TAIL_EXIT;
1080f84a7d3SDean Michael Berris         break;
1090a465d7aSDean Michael Berris       case 3:
1100a465d7aSDean Michael Berris         Record.Type = RecordTypes::ENTER_ARG;
1110a465d7aSDean Michael Berris         break;
112d6c18657SDean Michael Berris       default:
113a9d477a6SDean Michael Berris         return createStringError(
114a9d477a6SDean Michael Berris             std::make_error_code(std::errc::executable_format_error),
115a9d477a6SDean Michael Berris             "Unknown record type '%d' at offset %d.", Type, OffsetPtr);
116d6c18657SDean Michael Berris       }
117a9d477a6SDean Michael Berris 
118a9d477a6SDean Michael Berris       PreReadOffset = OffsetPtr;
119a9d477a6SDean Michael Berris       Record.FuncId = Reader.getSigned(&OffsetPtr, sizeof(int32_t));
120a9d477a6SDean Michael Berris       if (OffsetPtr == PreReadOffset)
121a9d477a6SDean Michael Berris         return createStringError(
122a9d477a6SDean Michael Berris             std::make_error_code(std::errc::executable_format_error),
123a9d477a6SDean Michael Berris             "Failed reading function id field at offset %d.", OffsetPtr);
124a9d477a6SDean Michael Berris 
125a9d477a6SDean Michael Berris       PreReadOffset = OffsetPtr;
126a9d477a6SDean Michael Berris       Record.TSC = Reader.getU64(&OffsetPtr);
127a9d477a6SDean Michael Berris       if (OffsetPtr == PreReadOffset)
128a9d477a6SDean Michael Berris         return createStringError(
129a9d477a6SDean Michael Berris             std::make_error_code(std::errc::executable_format_error),
130a9d477a6SDean Michael Berris             "Failed reading TSC field at offset %d.", OffsetPtr);
131a9d477a6SDean Michael Berris 
132a9d477a6SDean Michael Berris       PreReadOffset = OffsetPtr;
133a9d477a6SDean Michael Berris       Record.TId = Reader.getU32(&OffsetPtr);
134a9d477a6SDean Michael Berris       if (OffsetPtr == PreReadOffset)
135a9d477a6SDean Michael Berris         return createStringError(
136a9d477a6SDean Michael Berris             std::make_error_code(std::errc::executable_format_error),
137a9d477a6SDean Michael Berris             "Failed reading thread id field at offset %d.", OffsetPtr);
138a9d477a6SDean Michael Berris 
139a9d477a6SDean Michael Berris       PreReadOffset = OffsetPtr;
140a9d477a6SDean Michael Berris       Record.PId = Reader.getU32(&OffsetPtr);
141a9d477a6SDean Michael Berris       if (OffsetPtr == PreReadOffset)
142a9d477a6SDean Michael Berris         return createStringError(
143a9d477a6SDean Michael Berris             std::make_error_code(std::errc::executable_format_error),
144a9d477a6SDean Michael Berris             "Failed reading process id at offset %d.", OffsetPtr);
145a9d477a6SDean Michael Berris 
1460a465d7aSDean Michael Berris       break;
1470a465d7aSDean Michael Berris     }
1480a465d7aSDean Michael Berris     case 1: { // Arg payload record.
1490a465d7aSDean Michael Berris       auto &Record = Records.back();
150a9d477a6SDean Michael Berris 
151a9d477a6SDean Michael Berris       // We skip the next two bytes of the record, because we don't need the
152a9d477a6SDean Michael Berris       // type and the CPU record for arg payloads.
1530a465d7aSDean Michael Berris       OffsetPtr += 2;
154a9d477a6SDean Michael Berris       PreReadOffset = OffsetPtr;
155a9d477a6SDean Michael Berris       int32_t FuncId = Reader.getSigned(&OffsetPtr, sizeof(int32_t));
156a9d477a6SDean Michael Berris       if (OffsetPtr == PreReadOffset)
157a9d477a6SDean Michael Berris         return createStringError(
158a9d477a6SDean Michael Berris             std::make_error_code(std::errc::executable_format_error),
159a9d477a6SDean Michael Berris             "Failed reading function id field at offset %d.", OffsetPtr);
160a9d477a6SDean Michael Berris 
161a9d477a6SDean Michael Berris       PreReadOffset = OffsetPtr;
162a9d477a6SDean Michael Berris       auto TId = Reader.getU32(&OffsetPtr);
163a9d477a6SDean Michael Berris       if (OffsetPtr == PreReadOffset)
164a9d477a6SDean Michael Berris         return createStringError(
165a9d477a6SDean Michael Berris             std::make_error_code(std::errc::executable_format_error),
166a9d477a6SDean Michael Berris             "Failed reading thread id field at offset %d.", OffsetPtr);
167a9d477a6SDean Michael Berris 
168a9d477a6SDean Michael Berris       PreReadOffset = OffsetPtr;
169a9d477a6SDean Michael Berris       auto PId = Reader.getU32(&OffsetPtr);
170a9d477a6SDean Michael Berris       if (OffsetPtr == PreReadOffset)
171a9d477a6SDean Michael Berris         return createStringError(
172a9d477a6SDean Michael Berris             std::make_error_code(std::errc::executable_format_error),
173a9d477a6SDean Michael Berris             "Failed reading process id field at offset %d.", OffsetPtr);
17410141261SDean Michael Berris 
17510141261SDean Michael Berris       // Make a check for versions above 3 for the Pid field
17610141261SDean Michael Berris       if (Record.FuncId != FuncId || Record.TId != TId ||
17710141261SDean Michael Berris           (FileHeader.Version >= 3 ? Record.PId != PId : false))
178a9d477a6SDean Michael Berris         return createStringError(
179a9d477a6SDean Michael Berris             std::make_error_code(std::errc::executable_format_error),
180a9d477a6SDean Michael Berris             "Corrupted log, found arg payload following non-matching "
181a9d477a6SDean Michael Berris             "function+thread record. Record for function %d != %d at offset "
182a9d477a6SDean Michael Berris             "%d",
183a9d477a6SDean Michael Berris             Record.FuncId, FuncId, OffsetPtr);
18410141261SDean Michael Berris 
185a9d477a6SDean Michael Berris       PreReadOffset = OffsetPtr;
186a9d477a6SDean Michael Berris       auto Arg = Reader.getU64(&OffsetPtr);
187a9d477a6SDean Michael Berris       if (OffsetPtr == PreReadOffset)
188a9d477a6SDean Michael Berris         return createStringError(
189a9d477a6SDean Michael Berris             std::make_error_code(std::errc::executable_format_error),
190a9d477a6SDean Michael Berris             "Failed reading argument payload at offset %d.", OffsetPtr);
191a9d477a6SDean Michael Berris 
1920a465d7aSDean Michael Berris       Record.CallArgs.push_back(Arg);
1930a465d7aSDean Michael Berris       break;
1940a465d7aSDean Michael Berris     }
1950a465d7aSDean Michael Berris     default:
196a9d477a6SDean Michael Berris       return createStringError(
197a9d477a6SDean Michael Berris           std::make_error_code(std::errc::executable_format_error),
198a9d477a6SDean Michael Berris           "Unknown record type '%d' at offset %d.", RecordType, OffsetPtr);
1990a465d7aSDean Michael Berris     }
200a9d477a6SDean Michael Berris     // Advance the offset pointer enough bytes to align to 32-byte records for
201a9d477a6SDean Michael Berris     // basic mode logs.
202a9d477a6SDean Michael Berris     OffsetPtr += 8;
203d6c18657SDean Michael Berris   }
204d6c18657SDean Michael Berris   return Error::success();
205d6c18657SDean Michael Berris }
206d6c18657SDean Michael Berris 
2074f83c4d1SDean Michael Berris /// Reads a log in FDR mode for version 1 of this binary format. FDR mode is
2084f83c4d1SDean Michael Berris /// defined as part of the compiler-rt project in xray_fdr_logging.h, and such
2094f83c4d1SDean Michael Berris /// a log consists of the familiar 32 bit XRayHeader, followed by sequences of
2104f83c4d1SDean Michael Berris /// of interspersed 16 byte Metadata Records and 8 byte Function Records.
2114f83c4d1SDean Michael Berris ///
2124f83c4d1SDean Michael Berris /// The following is an attempt to document the grammar of the format, which is
2134f83c4d1SDean Michael Berris /// parsed by this function for little-endian machines. Since the format makes
214d78db156SMartin Pelikan /// use of BitFields, when we support big-endian architectures, we will need to
21568168d17SSimon Pilgrim /// adjust not only the endianness parameter to llvm's RecordExtractor, but also
2164f83c4d1SDean Michael Berris /// the bit twiddling logic, which is consistent with the little-endian
2174f83c4d1SDean Michael Berris /// convention that BitFields within a struct will first be packed into the
2184f83c4d1SDean Michael Berris /// least significant bits the address they belong to.
2194f83c4d1SDean Michael Berris ///
2206ec72625SDean Michael Berris /// We expect a format complying with the grammar in the following pseudo-EBNF
2216ec72625SDean Michael Berris /// in Version 1 of the FDR log.
2224f83c4d1SDean Michael Berris ///
2234f83c4d1SDean Michael Berris /// FDRLog: XRayFileHeader ThreadBuffer*
2243d0bc9efSKeith Wyss /// XRayFileHeader: 32 bytes to identify the log as FDR with machine metadata.
2253d0bc9efSKeith Wyss ///     Includes BufferSize
2263d0bc9efSKeith Wyss /// ThreadBuffer: NewBuffer WallClockTime NewCPUId FunctionSequence EOB
22760c24878SDean Michael Berris /// BufSize: 8 byte unsigned integer indicating how large the buffer is.
2284f83c4d1SDean Michael Berris /// NewBuffer: 16 byte metadata record with Thread Id.
2294f83c4d1SDean Michael Berris /// WallClockTime: 16 byte metadata record with human readable time.
23010141261SDean Michael Berris /// Pid: 16 byte metadata record with Pid
2314f83c4d1SDean Michael Berris /// NewCPUId: 16 byte metadata record with CPUId and a 64 bit TSC reading.
23260c24878SDean Michael Berris /// EOB: 16 byte record in a thread buffer plus mem garbage to fill BufSize.
2334f83c4d1SDean Michael Berris /// FunctionSequence: NewCPUId | TSCWrap | FunctionRecord
2344f83c4d1SDean Michael Berris /// TSCWrap: 16 byte metadata record with a full 64 bit TSC reading.
2354f83c4d1SDean Michael Berris /// FunctionRecord: 8 byte record with FunctionId, entry/exit, and TSC delta.
2366ec72625SDean Michael Berris ///
2376ec72625SDean Michael Berris /// In Version 2, we make the following changes:
2386ec72625SDean Michael Berris ///
2396ec72625SDean Michael Berris /// ThreadBuffer: BufferExtents NewBuffer WallClockTime NewCPUId
2406ec72625SDean Michael Berris ///               FunctionSequence
2416ec72625SDean Michael Berris /// BufferExtents: 16 byte metdata record describing how many usable bytes are
2426ec72625SDean Michael Berris ///                in the buffer. This is measured from the start of the buffer
2436ec72625SDean Michael Berris ///                and must always be at least 48 (bytes).
24410141261SDean Michael Berris ///
24510141261SDean Michael Berris /// In Version 3, we make the following changes:
24610141261SDean Michael Berris ///
24710141261SDean Michael Berris /// ThreadBuffer: BufferExtents NewBuffer WallClockTime Pid NewCPUId
24810141261SDean Michael Berris ///               FunctionSequence
2496ec72625SDean Michael Berris /// EOB: *deprecated*
250*59439dd0SDean Michael Berris ///
251*59439dd0SDean Michael Berris /// In Version 4, we make the following changes:
252*59439dd0SDean Michael Berris ///
253*59439dd0SDean Michael Berris /// CustomEventRecord now includes the CPU data.
254*59439dd0SDean Michael Berris ///
255*59439dd0SDean Michael Berris /// In Version 5, we make the following changes:
256*59439dd0SDean Michael Berris ///
257*59439dd0SDean Michael Berris /// CustomEventRecord and TypedEventRecord now use TSC delta encoding similar to
258*59439dd0SDean Michael Berris /// what FunctionRecord instances use, and we no longer need to include the CPU
259*59439dd0SDean Michael Berris /// id in the CustomEventRecord.
260*59439dd0SDean Michael Berris ///
2615b7548c6SDean Michael Berris Error loadFDRLog(StringRef Data, bool IsLittleEndian,
2625b7548c6SDean Michael Berris                  XRayFileHeader &FileHeader, std::vector<XRayRecord> &Records) {
263d764c1b6SDean Michael Berris 
2644f83c4d1SDean Michael Berris   if (Data.size() < 32)
265985c2b92SDean Michael Berris     return createStringError(std::make_error_code(std::errc::invalid_argument),
266985c2b92SDean Michael Berris                              "Not enough bytes for an XRay FDR log.");
267985c2b92SDean Michael Berris   DataExtractor DE(Data, IsLittleEndian, 8);
2684f83c4d1SDean Michael Berris 
269a9d477a6SDean Michael Berris   uint32_t OffsetPtr = 0;
270985c2b92SDean Michael Berris   auto FileHeaderOrError = readBinaryFormatHeader(DE, OffsetPtr);
271d764c1b6SDean Michael Berris   if (!FileHeaderOrError)
272d764c1b6SDean Michael Berris     return FileHeaderOrError.takeError();
273d764c1b6SDean Michael Berris   FileHeader = std::move(FileHeaderOrError.get());
2744f83c4d1SDean Michael Berris 
275985c2b92SDean Michael Berris   // First we load the records into memory.
276985c2b92SDean Michael Berris   std::vector<std::unique_ptr<Record>> FDRRecords;
277985c2b92SDean Michael Berris 
27860c24878SDean Michael Berris   {
279985c2b92SDean Michael Berris     FileBasedRecordProducer P(FileHeader, DE, OffsetPtr);
280985c2b92SDean Michael Berris     LogBuilderConsumer C(FDRRecords);
281985c2b92SDean Michael Berris     while (DE.isValidOffsetForDataOfSize(OffsetPtr, 1)) {
282985c2b92SDean Michael Berris       auto R = P.produce();
283985c2b92SDean Michael Berris       if (!R)
284985c2b92SDean Michael Berris         return R.takeError();
285985c2b92SDean Michael Berris       if (auto E = C.consume(std::move(R.get())))
2864f83c4d1SDean Michael Berris         return E;
287985c2b92SDean Michael Berris     }
288985c2b92SDean Michael Berris   }
289985c2b92SDean Michael Berris 
290985c2b92SDean Michael Berris   // Next we index the records into blocks.
291985c2b92SDean Michael Berris   BlockIndexer::Index Index;
292985c2b92SDean Michael Berris   {
293985c2b92SDean Michael Berris     BlockIndexer Indexer(Index);
294985c2b92SDean Michael Berris     for (auto &R : FDRRecords)
295985c2b92SDean Michael Berris       if (auto E = R->apply(Indexer))
296985c2b92SDean Michael Berris         return E;
297985c2b92SDean Michael Berris     if (auto E = Indexer.flush())
2984f83c4d1SDean Michael Berris       return E;
299d78db156SMartin Pelikan   }
3006ec72625SDean Michael Berris 
301985c2b92SDean Michael Berris   // Then we verify the consistency of the blocks.
302985c2b92SDean Michael Berris   {
303985c2b92SDean Michael Berris     for (auto &PTB : Index) {
304985c2b92SDean Michael Berris       auto &Blocks = PTB.second;
305985c2b92SDean Michael Berris       for (auto &B : Blocks) {
30690a46bdeSDean Michael Berris         BlockVerifier Verifier;
307985c2b92SDean Michael Berris         for (auto *R : B.Records)
308985c2b92SDean Michael Berris           if (auto E = R->apply(Verifier))
309985c2b92SDean Michael Berris             return E;
310985c2b92SDean Michael Berris         if (auto E = Verifier.verify())
311985c2b92SDean Michael Berris           return E;
312985c2b92SDean Michael Berris       }
3136ec72625SDean Michael Berris     }
3144f83c4d1SDean Michael Berris   }
315d78db156SMartin Pelikan 
316985c2b92SDean Michael Berris   // This is now the meat of the algorithm. Here we sort the blocks according to
317985c2b92SDean Michael Berris   // the Walltime record in each of the blocks for the same thread. This allows
318985c2b92SDean Michael Berris   // us to more consistently recreate the execution trace in temporal order.
319985c2b92SDean Michael Berris   // After the sort, we then reconstitute `Trace` records using a stateful
320985c2b92SDean Michael Berris   // visitor associated with a single process+thread pair.
321985c2b92SDean Michael Berris   {
322985c2b92SDean Michael Berris     for (auto &PTB : Index) {
323985c2b92SDean Michael Berris       auto &Blocks = PTB.second;
3246b67ff03SDean Michael Berris       llvm::sort(Blocks, [](const BlockIndexer::Block &L,
3256b67ff03SDean Michael Berris                             const BlockIndexer::Block &R) {
326985c2b92SDean Michael Berris         return (L.WallclockTime->seconds() < R.WallclockTime->seconds() &&
327985c2b92SDean Michael Berris                 L.WallclockTime->nanos() < R.WallclockTime->nanos());
328985c2b92SDean Michael Berris       });
329174d2cf7SDean Michael Berris       auto Adder = [&](const XRayRecord &R) { Records.push_back(R); };
330174d2cf7SDean Michael Berris       TraceExpander Expander(Adder, FileHeader.Version);
331985c2b92SDean Michael Berris       for (auto &B : Blocks) {
332985c2b92SDean Michael Berris         for (auto *R : B.Records)
333985c2b92SDean Michael Berris           if (auto E = R->apply(Expander))
334985c2b92SDean Michael Berris             return E;
335985c2b92SDean Michael Berris       }
336985c2b92SDean Michael Berris       if (auto E = Expander.flush())
337985c2b92SDean Michael Berris         return E;
338985c2b92SDean Michael Berris     }
339985c2b92SDean Michael Berris   }
3404f83c4d1SDean Michael Berris 
3414f83c4d1SDean Michael Berris   return Error::success();
3424f83c4d1SDean Michael Berris }
3434f83c4d1SDean Michael Berris 
3444f83c4d1SDean Michael Berris Error loadYAMLLog(StringRef Data, XRayFileHeader &FileHeader,
3454f83c4d1SDean Michael Berris                   std::vector<XRayRecord> &Records) {
346d6c18657SDean Michael Berris   YAMLXRayTrace Trace;
347d6c18657SDean Michael Berris   Input In(Data);
348d6c18657SDean Michael Berris   In >> Trace;
349d6c18657SDean Michael Berris   if (In.error())
350d6c18657SDean Michael Berris     return make_error<StringError>("Failed loading YAML Data.", In.error());
351d6c18657SDean Michael Berris 
352d6c18657SDean Michael Berris   FileHeader.Version = Trace.Header.Version;
353d6c18657SDean Michael Berris   FileHeader.Type = Trace.Header.Type;
354d6c18657SDean Michael Berris   FileHeader.ConstantTSC = Trace.Header.ConstantTSC;
355d6c18657SDean Michael Berris   FileHeader.NonstopTSC = Trace.Header.NonstopTSC;
356d6c18657SDean Michael Berris   FileHeader.CycleFrequency = Trace.Header.CycleFrequency;
357d6c18657SDean Michael Berris 
358d6c18657SDean Michael Berris   if (FileHeader.Version != 1)
359d6c18657SDean Michael Berris     return make_error<StringError>(
360d6c18657SDean Michael Berris         Twine("Unsupported XRay file version: ") + Twine(FileHeader.Version),
361d6c18657SDean Michael Berris         std::make_error_code(std::errc::invalid_argument));
362d6c18657SDean Michael Berris 
363d6c18657SDean Michael Berris   Records.clear();
364d6c18657SDean Michael Berris   std::transform(Trace.Records.begin(), Trace.Records.end(),
365d6c18657SDean Michael Berris                  std::back_inserter(Records), [&](const YAMLXRayRecord &R) {
36625f8d204SDean Michael Berris                    return XRayRecord{R.RecordType, R.CPU,      R.Type,
36725f8d204SDean Michael Berris                                      R.FuncId,     R.TSC,      R.TId,
36825f8d204SDean Michael Berris                                      R.PId,        R.CallArgs, R.Data};
369d6c18657SDean Michael Berris                  });
370d6c18657SDean Michael Berris   return Error::success();
371d6c18657SDean Michael Berris }
37249a49fe8SBenjamin Kramer } // namespace
373d6c18657SDean Michael Berris 
374d6c18657SDean Michael Berris Expected<Trace> llvm::xray::loadTraceFile(StringRef Filename, bool Sort) {
375d6c18657SDean Michael Berris   int Fd;
376d6c18657SDean Michael Berris   if (auto EC = sys::fs::openFileForRead(Filename, Fd)) {
377d6c18657SDean Michael Berris     return make_error<StringError>(
378d6c18657SDean Michael Berris         Twine("Cannot read log from '") + Filename + "'", EC);
379d6c18657SDean Michael Berris   }
380d6c18657SDean Michael Berris 
381d6c18657SDean Michael Berris   uint64_t FileSize;
382d6c18657SDean Michael Berris   if (auto EC = sys::fs::file_size(Filename, FileSize)) {
383d6c18657SDean Michael Berris     return make_error<StringError>(
384d6c18657SDean Michael Berris         Twine("Cannot read log from '") + Filename + "'", EC);
385d6c18657SDean Michael Berris   }
386d6c18657SDean Michael Berris   if (FileSize < 4) {
387d6c18657SDean Michael Berris     return make_error<StringError>(
388d6c18657SDean Michael Berris         Twine("File '") + Filename + "' too small for XRay.",
38984da6615SHans Wennborg         std::make_error_code(std::errc::executable_format_error));
390d6c18657SDean Michael Berris   }
391d6c18657SDean Michael Berris 
392d78db156SMartin Pelikan   // Map the opened file into memory and use a StringRef to access it later.
393d6c18657SDean Michael Berris   std::error_code EC;
394d6c18657SDean Michael Berris   sys::fs::mapped_file_region MappedFile(
395d6c18657SDean Michael Berris       Fd, sys::fs::mapped_file_region::mapmode::readonly, FileSize, 0, EC);
396d6c18657SDean Michael Berris   if (EC) {
397d6c18657SDean Michael Berris     return make_error<StringError>(
398d6c18657SDean Michael Berris         Twine("Cannot read log from '") + Filename + "'", EC);
399d6c18657SDean Michael Berris   }
400d78db156SMartin Pelikan   auto Data = StringRef(MappedFile.data(), MappedFile.size());
4015b7548c6SDean Michael Berris 
4025b7548c6SDean Michael Berris   // TODO: Lift the endianness and implementation selection here.
4035b7548c6SDean Michael Berris   DataExtractor LittleEndianDE(Data, true, 8);
4045b7548c6SDean Michael Berris   auto TraceOrError = loadTrace(LittleEndianDE, Sort);
4055b7548c6SDean Michael Berris   if (!TraceOrError) {
4065b7548c6SDean Michael Berris     DataExtractor BigEndianDE(Data, false, 8);
4075b7548c6SDean Michael Berris     TraceOrError = loadTrace(BigEndianDE, Sort);
4085b7548c6SDean Michael Berris   }
4095b7548c6SDean Michael Berris   return TraceOrError;
410f81b0800SDean Michael Berris }
411d6c18657SDean Michael Berris 
412f81b0800SDean Michael Berris Expected<Trace> llvm::xray::loadTrace(const DataExtractor &DE, bool Sort) {
413d6c18657SDean Michael Berris   // Attempt to detect the file type using file magic. We have a slight bias
414d6c18657SDean Michael Berris   // towards the binary format, and we do this by making sure that the first 4
415d6c18657SDean Michael Berris   // bytes of the binary file is some combination of the following byte
416d78db156SMartin Pelikan   // patterns: (observe the code loading them assumes they're little endian)
417d6c18657SDean Michael Berris   //
418d78db156SMartin Pelikan   //   0x01 0x00 0x00 0x00 - version 1, "naive" format
419d78db156SMartin Pelikan   //   0x01 0x00 0x01 0x00 - version 1, "flight data recorder" format
4206ec72625SDean Michael Berris   //   0x02 0x00 0x01 0x00 - version 2, "flight data recorder" format
421d6c18657SDean Michael Berris   //
422d78db156SMartin Pelikan   // YAML files don't typically have those first four bytes as valid text so we
423d6c18657SDean Michael Berris   // try loading assuming YAML if we don't find these bytes.
424d6c18657SDean Michael Berris   //
425d6c18657SDean Michael Berris   // Only if we can't load either the binary or the YAML format will we yield an
426d6c18657SDean Michael Berris   // error.
4275b7548c6SDean Michael Berris   DataExtractor HeaderExtractor(DE.getData(), DE.isLittleEndian(), 8);
428d6c18657SDean Michael Berris   uint32_t OffsetPtr = 0;
429d6c18657SDean Michael Berris   uint16_t Version = HeaderExtractor.getU16(&OffsetPtr);
430d6c18657SDean Michael Berris   uint16_t Type = HeaderExtractor.getU16(&OffsetPtr);
431d6c18657SDean Michael Berris 
4324f83c4d1SDean Michael Berris   enum BinaryFormatType { NAIVE_FORMAT = 0, FLIGHT_DATA_RECORDER_FORMAT = 1 };
4334f83c4d1SDean Michael Berris 
434d6c18657SDean Michael Berris   Trace T;
4356ec72625SDean Michael Berris   switch (Type) {
4366ec72625SDean Michael Berris   case NAIVE_FORMAT:
43710141261SDean Michael Berris     if (Version == 1 || Version == 2 || Version == 3) {
4385b7548c6SDean Michael Berris       if (auto E = loadNaiveFormatLog(DE.getData(), DE.isLittleEndian(),
4395b7548c6SDean Michael Berris                                       T.FileHeader, T.Records))
4404f83c4d1SDean Michael Berris         return std::move(E);
4416ec72625SDean Michael Berris     } else {
4426ec72625SDean Michael Berris       return make_error<StringError>(
4436ec72625SDean Michael Berris           Twine("Unsupported version for Basic/Naive Mode logging: ") +
4446ec72625SDean Michael Berris               Twine(Version),
4456ec72625SDean Michael Berris           std::make_error_code(std::errc::executable_format_error));
4466ec72625SDean Michael Berris     }
4476ec72625SDean Michael Berris     break;
4486ec72625SDean Michael Berris   case FLIGHT_DATA_RECORDER_FORMAT:
449*59439dd0SDean Michael Berris     if (Version >= 1 && Version <= 5) {
4505b7548c6SDean Michael Berris       if (auto E = loadFDRLog(DE.getData(), DE.isLittleEndian(), T.FileHeader,
4515b7548c6SDean Michael Berris                               T.Records))
452d6c18657SDean Michael Berris         return std::move(E);
453d6c18657SDean Michael Berris     } else {
4546ec72625SDean Michael Berris       return make_error<StringError>(
4556ec72625SDean Michael Berris           Twine("Unsupported version for FDR Mode logging: ") + Twine(Version),
4566ec72625SDean Michael Berris           std::make_error_code(std::errc::executable_format_error));
4576ec72625SDean Michael Berris     }
4586ec72625SDean Michael Berris     break;
4596ec72625SDean Michael Berris   default:
460f81b0800SDean Michael Berris     if (auto E = loadYAMLLog(DE.getData(), T.FileHeader, T.Records))
461d6c18657SDean Michael Berris       return std::move(E);
462d6c18657SDean Michael Berris   }
463d6c18657SDean Michael Berris 
464d6c18657SDean Michael Berris   if (Sort)
46528f3d5cbSMandeep Singh Grang     std::stable_sort(T.Records.begin(), T.Records.end(),
466d6c18657SDean Michael Berris                      [&](const XRayRecord &L, const XRayRecord &R) {
467d6c18657SDean Michael Berris                        return L.TSC < R.TSC;
468d6c18657SDean Michael Berris                      });
469d6c18657SDean Michael Berris 
470d6c18657SDean Michael Berris   return std::move(T);
471d6c18657SDean Michael Berris }
472