xref: /llvm-project-15.0.7/llvm/lib/XRay/Trace.cpp (revision 2946cd70)
1d6c18657SDean Michael Berris //===- Trace.cpp - XRay Trace Loading implementation. ---------------------===//
2d6c18657SDean Michael Berris //
3*2946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*2946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
5*2946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6d6c18657SDean Michael Berris //
7d6c18657SDean Michael Berris //===----------------------------------------------------------------------===//
8d6c18657SDean Michael Berris //
9d6c18657SDean Michael Berris // XRay log reader implementation.
10d6c18657SDean Michael Berris //
11d6c18657SDean Michael Berris //===----------------------------------------------------------------------===//
12d6c18657SDean Michael Berris #include "llvm/XRay/Trace.h"
13d6c18657SDean Michael Berris #include "llvm/ADT/STLExtras.h"
14d6c18657SDean Michael Berris #include "llvm/Support/DataExtractor.h"
15d6c18657SDean Michael Berris #include "llvm/Support/Error.h"
16d6c18657SDean Michael Berris #include "llvm/Support/FileSystem.h"
17985c2b92SDean Michael Berris #include "llvm/XRay/BlockIndexer.h"
18985c2b92SDean Michael Berris #include "llvm/XRay/BlockVerifier.h"
19985c2b92SDean Michael Berris #include "llvm/XRay/FDRRecordConsumer.h"
20985c2b92SDean Michael Berris #include "llvm/XRay/FDRRecordProducer.h"
21985c2b92SDean Michael Berris #include "llvm/XRay/FDRRecords.h"
22985c2b92SDean Michael Berris #include "llvm/XRay/FDRTraceExpander.h"
23d764c1b6SDean Michael Berris #include "llvm/XRay/FileHeaderReader.h"
24d6c18657SDean Michael Berris #include "llvm/XRay/YAMLXRayRecord.h"
25985c2b92SDean Michael Berris #include <memory>
26985c2b92SDean Michael Berris #include <vector>
27d6c18657SDean Michael Berris 
28d6c18657SDean Michael Berris using namespace llvm;
29d6c18657SDean Michael Berris using namespace llvm::xray;
30d6c18657SDean Michael Berris using llvm::yaml::Input;
31d6c18657SDean Michael Berris 
3249a49fe8SBenjamin Kramer namespace {
33d6c18657SDean Michael Berris using XRayRecordStorage =
34d6c18657SDean Michael Berris     std::aligned_storage<sizeof(XRayRecord), alignof(XRayRecord)>::type;
35d6c18657SDean Michael Berris 
365b7548c6SDean Michael Berris Error loadNaiveFormatLog(StringRef Data, bool IsLittleEndian,
375b7548c6SDean Michael Berris                          XRayFileHeader &FileHeader,
384f83c4d1SDean Michael Berris                          std::vector<XRayRecord> &Records) {
394f83c4d1SDean Michael Berris   if (Data.size() < 32)
404f83c4d1SDean Michael Berris     return make_error<StringError>(
414f83c4d1SDean Michael Berris         "Not enough bytes for an XRay log.",
424f83c4d1SDean Michael Berris         std::make_error_code(std::errc::invalid_argument));
434f83c4d1SDean Michael Berris 
444f83c4d1SDean Michael Berris   if (Data.size() - 32 == 0 || Data.size() % 32 != 0)
454f83c4d1SDean Michael Berris     return make_error<StringError>(
464f83c4d1SDean Michael Berris         "Invalid-sized XRay data.",
474f83c4d1SDean Michael Berris         std::make_error_code(std::errc::invalid_argument));
484f83c4d1SDean Michael Berris 
495b7548c6SDean Michael Berris   DataExtractor Reader(Data, IsLittleEndian, 8);
50a9d477a6SDean Michael Berris   uint32_t OffsetPtr = 0;
51d764c1b6SDean Michael Berris   auto FileHeaderOrError = readBinaryFormatHeader(Reader, OffsetPtr);
52d764c1b6SDean Michael Berris   if (!FileHeaderOrError)
53d764c1b6SDean Michael Berris     return FileHeaderOrError.takeError();
54d764c1b6SDean Michael Berris   FileHeader = std::move(FileHeaderOrError.get());
55d6c18657SDean Michael Berris 
56d6c18657SDean Michael Berris   // Each record after the header will be 32 bytes, in the following format:
57d6c18657SDean Michael Berris   //
58d6c18657SDean Michael Berris   //   (2)   uint16 : record type
59d6c18657SDean Michael Berris   //   (1)   uint8  : cpu id
60d6c18657SDean Michael Berris   //   (1)   uint8  : type
61d6c18657SDean Michael Berris   //   (4)   sint32 : function id
62d6c18657SDean Michael Berris   //   (8)   uint64 : tsc
63d6c18657SDean Michael Berris   //   (4)   uint32 : thread id
6410141261SDean Michael Berris   //   (4)   uint32 : process id
6510141261SDean Michael Berris   //   (8)   -      : padding
66a9d477a6SDean Michael Berris   while (Reader.isValidOffset(OffsetPtr)) {
67a9d477a6SDean Michael Berris     if (!Reader.isValidOffsetForDataOfSize(OffsetPtr, 32))
68a9d477a6SDean Michael Berris       return createStringError(
69a9d477a6SDean Michael Berris           std::make_error_code(std::errc::executable_format_error),
70a9d477a6SDean Michael Berris           "Not enough bytes to read a full record at offset %d.", OffsetPtr);
71a9d477a6SDean Michael Berris     auto PreReadOffset = OffsetPtr;
72a9d477a6SDean Michael Berris     auto RecordType = Reader.getU16(&OffsetPtr);
73a9d477a6SDean Michael Berris     if (OffsetPtr == PreReadOffset)
74a9d477a6SDean Michael Berris       return createStringError(
75a9d477a6SDean Michael Berris           std::make_error_code(std::errc::executable_format_error),
76a9d477a6SDean Michael Berris           "Failed reading record type at offset %d.", OffsetPtr);
77a9d477a6SDean Michael Berris 
78a9d477a6SDean Michael Berris     switch (RecordType) {
790a465d7aSDean Michael Berris     case 0: { // Normal records.
80d6c18657SDean Michael Berris       Records.emplace_back();
81d6c18657SDean Michael Berris       auto &Record = Records.back();
820a465d7aSDean Michael Berris       Record.RecordType = RecordType;
83a9d477a6SDean Michael Berris 
84a9d477a6SDean Michael Berris       PreReadOffset = OffsetPtr;
85a9d477a6SDean Michael Berris       Record.CPU = Reader.getU8(&OffsetPtr);
86a9d477a6SDean Michael Berris       if (OffsetPtr == PreReadOffset)
87a9d477a6SDean Michael Berris         return createStringError(
88a9d477a6SDean Michael Berris             std::make_error_code(std::errc::executable_format_error),
89a9d477a6SDean Michael Berris             "Failed reading CPU field at offset %d.", OffsetPtr);
90a9d477a6SDean Michael Berris 
91a9d477a6SDean Michael Berris       PreReadOffset = OffsetPtr;
92a9d477a6SDean Michael Berris       auto Type = Reader.getU8(&OffsetPtr);
93a9d477a6SDean Michael Berris       if (OffsetPtr == PreReadOffset)
94a9d477a6SDean Michael Berris         return createStringError(
95a9d477a6SDean Michael Berris             std::make_error_code(std::errc::executable_format_error),
96a9d477a6SDean Michael Berris             "Failed reading record type field at offset %d.", OffsetPtr);
97a9d477a6SDean Michael Berris 
98d6c18657SDean Michael Berris       switch (Type) {
99d6c18657SDean Michael Berris       case 0:
100d6c18657SDean Michael Berris         Record.Type = RecordTypes::ENTER;
101d6c18657SDean Michael Berris         break;
102d6c18657SDean Michael Berris       case 1:
103d6c18657SDean Michael Berris         Record.Type = RecordTypes::EXIT;
104d6c18657SDean Michael Berris         break;
1050f84a7d3SDean Michael Berris       case 2:
1060f84a7d3SDean Michael Berris         Record.Type = RecordTypes::TAIL_EXIT;
1070f84a7d3SDean Michael Berris         break;
1080a465d7aSDean Michael Berris       case 3:
1090a465d7aSDean Michael Berris         Record.Type = RecordTypes::ENTER_ARG;
1100a465d7aSDean Michael Berris         break;
111d6c18657SDean Michael Berris       default:
112a9d477a6SDean Michael Berris         return createStringError(
113a9d477a6SDean Michael Berris             std::make_error_code(std::errc::executable_format_error),
114a9d477a6SDean Michael Berris             "Unknown record type '%d' at offset %d.", Type, OffsetPtr);
115d6c18657SDean Michael Berris       }
116a9d477a6SDean Michael Berris 
117a9d477a6SDean Michael Berris       PreReadOffset = OffsetPtr;
118a9d477a6SDean Michael Berris       Record.FuncId = Reader.getSigned(&OffsetPtr, sizeof(int32_t));
119a9d477a6SDean Michael Berris       if (OffsetPtr == PreReadOffset)
120a9d477a6SDean Michael Berris         return createStringError(
121a9d477a6SDean Michael Berris             std::make_error_code(std::errc::executable_format_error),
122a9d477a6SDean Michael Berris             "Failed reading function id field at offset %d.", OffsetPtr);
123a9d477a6SDean Michael Berris 
124a9d477a6SDean Michael Berris       PreReadOffset = OffsetPtr;
125a9d477a6SDean Michael Berris       Record.TSC = Reader.getU64(&OffsetPtr);
126a9d477a6SDean Michael Berris       if (OffsetPtr == PreReadOffset)
127a9d477a6SDean Michael Berris         return createStringError(
128a9d477a6SDean Michael Berris             std::make_error_code(std::errc::executable_format_error),
129a9d477a6SDean Michael Berris             "Failed reading TSC field at offset %d.", OffsetPtr);
130a9d477a6SDean Michael Berris 
131a9d477a6SDean Michael Berris       PreReadOffset = OffsetPtr;
132a9d477a6SDean Michael Berris       Record.TId = Reader.getU32(&OffsetPtr);
133a9d477a6SDean Michael Berris       if (OffsetPtr == PreReadOffset)
134a9d477a6SDean Michael Berris         return createStringError(
135a9d477a6SDean Michael Berris             std::make_error_code(std::errc::executable_format_error),
136a9d477a6SDean Michael Berris             "Failed reading thread id field at offset %d.", OffsetPtr);
137a9d477a6SDean Michael Berris 
138a9d477a6SDean Michael Berris       PreReadOffset = OffsetPtr;
139a9d477a6SDean Michael Berris       Record.PId = Reader.getU32(&OffsetPtr);
140a9d477a6SDean Michael Berris       if (OffsetPtr == PreReadOffset)
141a9d477a6SDean Michael Berris         return createStringError(
142a9d477a6SDean Michael Berris             std::make_error_code(std::errc::executable_format_error),
143a9d477a6SDean Michael Berris             "Failed reading process id at offset %d.", OffsetPtr);
144a9d477a6SDean Michael Berris 
1450a465d7aSDean Michael Berris       break;
1460a465d7aSDean Michael Berris     }
1470a465d7aSDean Michael Berris     case 1: { // Arg payload record.
1480a465d7aSDean Michael Berris       auto &Record = Records.back();
149a9d477a6SDean Michael Berris 
150a9d477a6SDean Michael Berris       // We skip the next two bytes of the record, because we don't need the
151a9d477a6SDean Michael Berris       // type and the CPU record for arg payloads.
1520a465d7aSDean Michael Berris       OffsetPtr += 2;
153a9d477a6SDean Michael Berris       PreReadOffset = OffsetPtr;
154a9d477a6SDean Michael Berris       int32_t FuncId = Reader.getSigned(&OffsetPtr, sizeof(int32_t));
155a9d477a6SDean Michael Berris       if (OffsetPtr == PreReadOffset)
156a9d477a6SDean Michael Berris         return createStringError(
157a9d477a6SDean Michael Berris             std::make_error_code(std::errc::executable_format_error),
158a9d477a6SDean Michael Berris             "Failed reading function id field at offset %d.", OffsetPtr);
159a9d477a6SDean Michael Berris 
160a9d477a6SDean Michael Berris       PreReadOffset = OffsetPtr;
161a9d477a6SDean Michael Berris       auto TId = Reader.getU32(&OffsetPtr);
162a9d477a6SDean Michael Berris       if (OffsetPtr == PreReadOffset)
163a9d477a6SDean Michael Berris         return createStringError(
164a9d477a6SDean Michael Berris             std::make_error_code(std::errc::executable_format_error),
165a9d477a6SDean Michael Berris             "Failed reading thread id field at offset %d.", OffsetPtr);
166a9d477a6SDean Michael Berris 
167a9d477a6SDean Michael Berris       PreReadOffset = OffsetPtr;
168a9d477a6SDean Michael Berris       auto PId = Reader.getU32(&OffsetPtr);
169a9d477a6SDean Michael Berris       if (OffsetPtr == PreReadOffset)
170a9d477a6SDean Michael Berris         return createStringError(
171a9d477a6SDean Michael Berris             std::make_error_code(std::errc::executable_format_error),
172a9d477a6SDean Michael Berris             "Failed reading process id field at offset %d.", OffsetPtr);
17310141261SDean Michael Berris 
17410141261SDean Michael Berris       // Make a check for versions above 3 for the Pid field
17510141261SDean Michael Berris       if (Record.FuncId != FuncId || Record.TId != TId ||
17610141261SDean Michael Berris           (FileHeader.Version >= 3 ? Record.PId != PId : false))
177a9d477a6SDean Michael Berris         return createStringError(
178a9d477a6SDean Michael Berris             std::make_error_code(std::errc::executable_format_error),
179a9d477a6SDean Michael Berris             "Corrupted log, found arg payload following non-matching "
180a9d477a6SDean Michael Berris             "function+thread record. Record for function %d != %d at offset "
181a9d477a6SDean Michael Berris             "%d",
182a9d477a6SDean Michael Berris             Record.FuncId, FuncId, OffsetPtr);
18310141261SDean Michael Berris 
184a9d477a6SDean Michael Berris       PreReadOffset = OffsetPtr;
185a9d477a6SDean Michael Berris       auto Arg = Reader.getU64(&OffsetPtr);
186a9d477a6SDean Michael Berris       if (OffsetPtr == PreReadOffset)
187a9d477a6SDean Michael Berris         return createStringError(
188a9d477a6SDean Michael Berris             std::make_error_code(std::errc::executable_format_error),
189a9d477a6SDean Michael Berris             "Failed reading argument payload at offset %d.", OffsetPtr);
190a9d477a6SDean Michael Berris 
1910a465d7aSDean Michael Berris       Record.CallArgs.push_back(Arg);
1920a465d7aSDean Michael Berris       break;
1930a465d7aSDean Michael Berris     }
1940a465d7aSDean Michael Berris     default:
195a9d477a6SDean Michael Berris       return createStringError(
196a9d477a6SDean Michael Berris           std::make_error_code(std::errc::executable_format_error),
197a9d477a6SDean Michael Berris           "Unknown record type '%d' at offset %d.", RecordType, OffsetPtr);
1980a465d7aSDean Michael Berris     }
199a9d477a6SDean Michael Berris     // Advance the offset pointer enough bytes to align to 32-byte records for
200a9d477a6SDean Michael Berris     // basic mode logs.
201a9d477a6SDean Michael Berris     OffsetPtr += 8;
202d6c18657SDean Michael Berris   }
203d6c18657SDean Michael Berris   return Error::success();
204d6c18657SDean Michael Berris }
205d6c18657SDean Michael Berris 
2064f83c4d1SDean Michael Berris /// Reads a log in FDR mode for version 1 of this binary format. FDR mode is
2074f83c4d1SDean Michael Berris /// defined as part of the compiler-rt project in xray_fdr_logging.h, and such
2084f83c4d1SDean Michael Berris /// a log consists of the familiar 32 bit XRayHeader, followed by sequences of
2094f83c4d1SDean Michael Berris /// of interspersed 16 byte Metadata Records and 8 byte Function Records.
2104f83c4d1SDean Michael Berris ///
2114f83c4d1SDean Michael Berris /// The following is an attempt to document the grammar of the format, which is
2124f83c4d1SDean Michael Berris /// parsed by this function for little-endian machines. Since the format makes
213d78db156SMartin Pelikan /// use of BitFields, when we support big-endian architectures, we will need to
21468168d17SSimon Pilgrim /// adjust not only the endianness parameter to llvm's RecordExtractor, but also
2154f83c4d1SDean Michael Berris /// the bit twiddling logic, which is consistent with the little-endian
2164f83c4d1SDean Michael Berris /// convention that BitFields within a struct will first be packed into the
2174f83c4d1SDean Michael Berris /// least significant bits the address they belong to.
2184f83c4d1SDean Michael Berris ///
2196ec72625SDean Michael Berris /// We expect a format complying with the grammar in the following pseudo-EBNF
2206ec72625SDean Michael Berris /// in Version 1 of the FDR log.
2214f83c4d1SDean Michael Berris ///
2224f83c4d1SDean Michael Berris /// FDRLog: XRayFileHeader ThreadBuffer*
2233d0bc9efSKeith Wyss /// XRayFileHeader: 32 bytes to identify the log as FDR with machine metadata.
2243d0bc9efSKeith Wyss ///     Includes BufferSize
2253d0bc9efSKeith Wyss /// ThreadBuffer: NewBuffer WallClockTime NewCPUId FunctionSequence EOB
22660c24878SDean Michael Berris /// BufSize: 8 byte unsigned integer indicating how large the buffer is.
2274f83c4d1SDean Michael Berris /// NewBuffer: 16 byte metadata record with Thread Id.
2284f83c4d1SDean Michael Berris /// WallClockTime: 16 byte metadata record with human readable time.
22910141261SDean Michael Berris /// Pid: 16 byte metadata record with Pid
2304f83c4d1SDean Michael Berris /// NewCPUId: 16 byte metadata record with CPUId and a 64 bit TSC reading.
23160c24878SDean Michael Berris /// EOB: 16 byte record in a thread buffer plus mem garbage to fill BufSize.
2324f83c4d1SDean Michael Berris /// FunctionSequence: NewCPUId | TSCWrap | FunctionRecord
2334f83c4d1SDean Michael Berris /// TSCWrap: 16 byte metadata record with a full 64 bit TSC reading.
2344f83c4d1SDean Michael Berris /// FunctionRecord: 8 byte record with FunctionId, entry/exit, and TSC delta.
2356ec72625SDean Michael Berris ///
2366ec72625SDean Michael Berris /// In Version 2, we make the following changes:
2376ec72625SDean Michael Berris ///
2386ec72625SDean Michael Berris /// ThreadBuffer: BufferExtents NewBuffer WallClockTime NewCPUId
2396ec72625SDean Michael Berris ///               FunctionSequence
2406ec72625SDean Michael Berris /// BufferExtents: 16 byte metdata record describing how many usable bytes are
2416ec72625SDean Michael Berris ///                in the buffer. This is measured from the start of the buffer
2426ec72625SDean Michael Berris ///                and must always be at least 48 (bytes).
24310141261SDean Michael Berris ///
24410141261SDean Michael Berris /// In Version 3, we make the following changes:
24510141261SDean Michael Berris ///
24610141261SDean Michael Berris /// ThreadBuffer: BufferExtents NewBuffer WallClockTime Pid NewCPUId
24710141261SDean Michael Berris ///               FunctionSequence
2486ec72625SDean Michael Berris /// EOB: *deprecated*
24959439dd0SDean Michael Berris ///
25059439dd0SDean Michael Berris /// In Version 4, we make the following changes:
25159439dd0SDean Michael Berris ///
25259439dd0SDean Michael Berris /// CustomEventRecord now includes the CPU data.
25359439dd0SDean Michael Berris ///
25459439dd0SDean Michael Berris /// In Version 5, we make the following changes:
25559439dd0SDean Michael Berris ///
25659439dd0SDean Michael Berris /// CustomEventRecord and TypedEventRecord now use TSC delta encoding similar to
25759439dd0SDean Michael Berris /// what FunctionRecord instances use, and we no longer need to include the CPU
25859439dd0SDean Michael Berris /// id in the CustomEventRecord.
25959439dd0SDean Michael Berris ///
2605b7548c6SDean Michael Berris Error loadFDRLog(StringRef Data, bool IsLittleEndian,
2615b7548c6SDean Michael Berris                  XRayFileHeader &FileHeader, std::vector<XRayRecord> &Records) {
262d764c1b6SDean Michael Berris 
2634f83c4d1SDean Michael Berris   if (Data.size() < 32)
264985c2b92SDean Michael Berris     return createStringError(std::make_error_code(std::errc::invalid_argument),
265985c2b92SDean Michael Berris                              "Not enough bytes for an XRay FDR log.");
266985c2b92SDean Michael Berris   DataExtractor DE(Data, IsLittleEndian, 8);
2674f83c4d1SDean Michael Berris 
268a9d477a6SDean Michael Berris   uint32_t OffsetPtr = 0;
269985c2b92SDean Michael Berris   auto FileHeaderOrError = readBinaryFormatHeader(DE, OffsetPtr);
270d764c1b6SDean Michael Berris   if (!FileHeaderOrError)
271d764c1b6SDean Michael Berris     return FileHeaderOrError.takeError();
272d764c1b6SDean Michael Berris   FileHeader = std::move(FileHeaderOrError.get());
2734f83c4d1SDean Michael Berris 
274985c2b92SDean Michael Berris   // First we load the records into memory.
275985c2b92SDean Michael Berris   std::vector<std::unique_ptr<Record>> FDRRecords;
276985c2b92SDean Michael Berris 
27760c24878SDean Michael Berris   {
278985c2b92SDean Michael Berris     FileBasedRecordProducer P(FileHeader, DE, OffsetPtr);
279985c2b92SDean Michael Berris     LogBuilderConsumer C(FDRRecords);
280985c2b92SDean Michael Berris     while (DE.isValidOffsetForDataOfSize(OffsetPtr, 1)) {
281985c2b92SDean Michael Berris       auto R = P.produce();
282985c2b92SDean Michael Berris       if (!R)
283985c2b92SDean Michael Berris         return R.takeError();
284985c2b92SDean Michael Berris       if (auto E = C.consume(std::move(R.get())))
2854f83c4d1SDean Michael Berris         return E;
286985c2b92SDean Michael Berris     }
287985c2b92SDean Michael Berris   }
288985c2b92SDean Michael Berris 
289985c2b92SDean Michael Berris   // Next we index the records into blocks.
290985c2b92SDean Michael Berris   BlockIndexer::Index Index;
291985c2b92SDean Michael Berris   {
292985c2b92SDean Michael Berris     BlockIndexer Indexer(Index);
293985c2b92SDean Michael Berris     for (auto &R : FDRRecords)
294985c2b92SDean Michael Berris       if (auto E = R->apply(Indexer))
295985c2b92SDean Michael Berris         return E;
296985c2b92SDean Michael Berris     if (auto E = Indexer.flush())
2974f83c4d1SDean Michael Berris       return E;
298d78db156SMartin Pelikan   }
2996ec72625SDean Michael Berris 
300985c2b92SDean Michael Berris   // Then we verify the consistency of the blocks.
301985c2b92SDean Michael Berris   {
302985c2b92SDean Michael Berris     for (auto &PTB : Index) {
303985c2b92SDean Michael Berris       auto &Blocks = PTB.second;
304985c2b92SDean Michael Berris       for (auto &B : Blocks) {
30590a46bdeSDean Michael Berris         BlockVerifier Verifier;
306985c2b92SDean Michael Berris         for (auto *R : B.Records)
307985c2b92SDean Michael Berris           if (auto E = R->apply(Verifier))
308985c2b92SDean Michael Berris             return E;
309985c2b92SDean Michael Berris         if (auto E = Verifier.verify())
310985c2b92SDean Michael Berris           return E;
311985c2b92SDean Michael Berris       }
3126ec72625SDean Michael Berris     }
3134f83c4d1SDean Michael Berris   }
314d78db156SMartin Pelikan 
315985c2b92SDean Michael Berris   // This is now the meat of the algorithm. Here we sort the blocks according to
316985c2b92SDean Michael Berris   // the Walltime record in each of the blocks for the same thread. This allows
317985c2b92SDean Michael Berris   // us to more consistently recreate the execution trace in temporal order.
318985c2b92SDean Michael Berris   // After the sort, we then reconstitute `Trace` records using a stateful
319985c2b92SDean Michael Berris   // visitor associated with a single process+thread pair.
320985c2b92SDean Michael Berris   {
321985c2b92SDean Michael Berris     for (auto &PTB : Index) {
322985c2b92SDean Michael Berris       auto &Blocks = PTB.second;
3236b67ff03SDean Michael Berris       llvm::sort(Blocks, [](const BlockIndexer::Block &L,
3246b67ff03SDean Michael Berris                             const BlockIndexer::Block &R) {
325985c2b92SDean Michael Berris         return (L.WallclockTime->seconds() < R.WallclockTime->seconds() &&
326985c2b92SDean Michael Berris                 L.WallclockTime->nanos() < R.WallclockTime->nanos());
327985c2b92SDean Michael Berris       });
328174d2cf7SDean Michael Berris       auto Adder = [&](const XRayRecord &R) { Records.push_back(R); };
329174d2cf7SDean Michael Berris       TraceExpander Expander(Adder, FileHeader.Version);
330985c2b92SDean Michael Berris       for (auto &B : Blocks) {
331985c2b92SDean Michael Berris         for (auto *R : B.Records)
332985c2b92SDean Michael Berris           if (auto E = R->apply(Expander))
333985c2b92SDean Michael Berris             return E;
334985c2b92SDean Michael Berris       }
335985c2b92SDean Michael Berris       if (auto E = Expander.flush())
336985c2b92SDean Michael Berris         return E;
337985c2b92SDean Michael Berris     }
338985c2b92SDean Michael Berris   }
3394f83c4d1SDean Michael Berris 
3404f83c4d1SDean Michael Berris   return Error::success();
3414f83c4d1SDean Michael Berris }
3424f83c4d1SDean Michael Berris 
3434f83c4d1SDean Michael Berris Error loadYAMLLog(StringRef Data, XRayFileHeader &FileHeader,
3444f83c4d1SDean Michael Berris                   std::vector<XRayRecord> &Records) {
345d6c18657SDean Michael Berris   YAMLXRayTrace Trace;
346d6c18657SDean Michael Berris   Input In(Data);
347d6c18657SDean Michael Berris   In >> Trace;
348d6c18657SDean Michael Berris   if (In.error())
349d6c18657SDean Michael Berris     return make_error<StringError>("Failed loading YAML Data.", In.error());
350d6c18657SDean Michael Berris 
351d6c18657SDean Michael Berris   FileHeader.Version = Trace.Header.Version;
352d6c18657SDean Michael Berris   FileHeader.Type = Trace.Header.Type;
353d6c18657SDean Michael Berris   FileHeader.ConstantTSC = Trace.Header.ConstantTSC;
354d6c18657SDean Michael Berris   FileHeader.NonstopTSC = Trace.Header.NonstopTSC;
355d6c18657SDean Michael Berris   FileHeader.CycleFrequency = Trace.Header.CycleFrequency;
356d6c18657SDean Michael Berris 
357d6c18657SDean Michael Berris   if (FileHeader.Version != 1)
358d6c18657SDean Michael Berris     return make_error<StringError>(
359d6c18657SDean Michael Berris         Twine("Unsupported XRay file version: ") + Twine(FileHeader.Version),
360d6c18657SDean Michael Berris         std::make_error_code(std::errc::invalid_argument));
361d6c18657SDean Michael Berris 
362d6c18657SDean Michael Berris   Records.clear();
363d6c18657SDean Michael Berris   std::transform(Trace.Records.begin(), Trace.Records.end(),
364d6c18657SDean Michael Berris                  std::back_inserter(Records), [&](const YAMLXRayRecord &R) {
36525f8d204SDean Michael Berris                    return XRayRecord{R.RecordType, R.CPU,      R.Type,
36625f8d204SDean Michael Berris                                      R.FuncId,     R.TSC,      R.TId,
36725f8d204SDean Michael Berris                                      R.PId,        R.CallArgs, R.Data};
368d6c18657SDean Michael Berris                  });
369d6c18657SDean Michael Berris   return Error::success();
370d6c18657SDean Michael Berris }
37149a49fe8SBenjamin Kramer } // namespace
372d6c18657SDean Michael Berris 
373d6c18657SDean Michael Berris Expected<Trace> llvm::xray::loadTraceFile(StringRef Filename, bool Sort) {
374d6c18657SDean Michael Berris   int Fd;
375d6c18657SDean Michael Berris   if (auto EC = sys::fs::openFileForRead(Filename, Fd)) {
376d6c18657SDean Michael Berris     return make_error<StringError>(
377d6c18657SDean Michael Berris         Twine("Cannot read log from '") + Filename + "'", EC);
378d6c18657SDean Michael Berris   }
379d6c18657SDean Michael Berris 
380d6c18657SDean Michael Berris   uint64_t FileSize;
381d6c18657SDean Michael Berris   if (auto EC = sys::fs::file_size(Filename, FileSize)) {
382d6c18657SDean Michael Berris     return make_error<StringError>(
383d6c18657SDean Michael Berris         Twine("Cannot read log from '") + Filename + "'", EC);
384d6c18657SDean Michael Berris   }
385d6c18657SDean Michael Berris   if (FileSize < 4) {
386d6c18657SDean Michael Berris     return make_error<StringError>(
387d6c18657SDean Michael Berris         Twine("File '") + Filename + "' too small for XRay.",
38884da6615SHans Wennborg         std::make_error_code(std::errc::executable_format_error));
389d6c18657SDean Michael Berris   }
390d6c18657SDean Michael Berris 
391d78db156SMartin Pelikan   // Map the opened file into memory and use a StringRef to access it later.
392d6c18657SDean Michael Berris   std::error_code EC;
393d6c18657SDean Michael Berris   sys::fs::mapped_file_region MappedFile(
394d6c18657SDean Michael Berris       Fd, sys::fs::mapped_file_region::mapmode::readonly, FileSize, 0, EC);
395d6c18657SDean Michael Berris   if (EC) {
396d6c18657SDean Michael Berris     return make_error<StringError>(
397d6c18657SDean Michael Berris         Twine("Cannot read log from '") + Filename + "'", EC);
398d6c18657SDean Michael Berris   }
399d78db156SMartin Pelikan   auto Data = StringRef(MappedFile.data(), MappedFile.size());
4005b7548c6SDean Michael Berris 
4015b7548c6SDean Michael Berris   // TODO: Lift the endianness and implementation selection here.
4025b7548c6SDean Michael Berris   DataExtractor LittleEndianDE(Data, true, 8);
4035b7548c6SDean Michael Berris   auto TraceOrError = loadTrace(LittleEndianDE, Sort);
4045b7548c6SDean Michael Berris   if (!TraceOrError) {
4055b7548c6SDean Michael Berris     DataExtractor BigEndianDE(Data, false, 8);
4065b7548c6SDean Michael Berris     TraceOrError = loadTrace(BigEndianDE, Sort);
4075b7548c6SDean Michael Berris   }
4085b7548c6SDean Michael Berris   return TraceOrError;
409f81b0800SDean Michael Berris }
410d6c18657SDean Michael Berris 
411f81b0800SDean Michael Berris Expected<Trace> llvm::xray::loadTrace(const DataExtractor &DE, bool Sort) {
412d6c18657SDean Michael Berris   // Attempt to detect the file type using file magic. We have a slight bias
413d6c18657SDean Michael Berris   // towards the binary format, and we do this by making sure that the first 4
414d6c18657SDean Michael Berris   // bytes of the binary file is some combination of the following byte
415d78db156SMartin Pelikan   // patterns: (observe the code loading them assumes they're little endian)
416d6c18657SDean Michael Berris   //
417d78db156SMartin Pelikan   //   0x01 0x00 0x00 0x00 - version 1, "naive" format
418d78db156SMartin Pelikan   //   0x01 0x00 0x01 0x00 - version 1, "flight data recorder" format
4196ec72625SDean Michael Berris   //   0x02 0x00 0x01 0x00 - version 2, "flight data recorder" format
420d6c18657SDean Michael Berris   //
421d78db156SMartin Pelikan   // YAML files don't typically have those first four bytes as valid text so we
422d6c18657SDean Michael Berris   // try loading assuming YAML if we don't find these bytes.
423d6c18657SDean Michael Berris   //
424d6c18657SDean Michael Berris   // Only if we can't load either the binary or the YAML format will we yield an
425d6c18657SDean Michael Berris   // error.
4265b7548c6SDean Michael Berris   DataExtractor HeaderExtractor(DE.getData(), DE.isLittleEndian(), 8);
427d6c18657SDean Michael Berris   uint32_t OffsetPtr = 0;
428d6c18657SDean Michael Berris   uint16_t Version = HeaderExtractor.getU16(&OffsetPtr);
429d6c18657SDean Michael Berris   uint16_t Type = HeaderExtractor.getU16(&OffsetPtr);
430d6c18657SDean Michael Berris 
4314f83c4d1SDean Michael Berris   enum BinaryFormatType { NAIVE_FORMAT = 0, FLIGHT_DATA_RECORDER_FORMAT = 1 };
4324f83c4d1SDean Michael Berris 
433d6c18657SDean Michael Berris   Trace T;
4346ec72625SDean Michael Berris   switch (Type) {
4356ec72625SDean Michael Berris   case NAIVE_FORMAT:
43610141261SDean Michael Berris     if (Version == 1 || Version == 2 || Version == 3) {
4375b7548c6SDean Michael Berris       if (auto E = loadNaiveFormatLog(DE.getData(), DE.isLittleEndian(),
4385b7548c6SDean Michael Berris                                       T.FileHeader, T.Records))
4394f83c4d1SDean Michael Berris         return std::move(E);
4406ec72625SDean Michael Berris     } else {
4416ec72625SDean Michael Berris       return make_error<StringError>(
4426ec72625SDean Michael Berris           Twine("Unsupported version for Basic/Naive Mode logging: ") +
4436ec72625SDean Michael Berris               Twine(Version),
4446ec72625SDean Michael Berris           std::make_error_code(std::errc::executable_format_error));
4456ec72625SDean Michael Berris     }
4466ec72625SDean Michael Berris     break;
4476ec72625SDean Michael Berris   case FLIGHT_DATA_RECORDER_FORMAT:
44859439dd0SDean Michael Berris     if (Version >= 1 && Version <= 5) {
4495b7548c6SDean Michael Berris       if (auto E = loadFDRLog(DE.getData(), DE.isLittleEndian(), T.FileHeader,
4505b7548c6SDean Michael Berris                               T.Records))
451d6c18657SDean Michael Berris         return std::move(E);
452d6c18657SDean Michael Berris     } else {
4536ec72625SDean Michael Berris       return make_error<StringError>(
4546ec72625SDean Michael Berris           Twine("Unsupported version for FDR Mode logging: ") + Twine(Version),
4556ec72625SDean Michael Berris           std::make_error_code(std::errc::executable_format_error));
4566ec72625SDean Michael Berris     }
4576ec72625SDean Michael Berris     break;
4586ec72625SDean Michael Berris   default:
459f81b0800SDean Michael Berris     if (auto E = loadYAMLLog(DE.getData(), T.FileHeader, T.Records))
460d6c18657SDean Michael Berris       return std::move(E);
461d6c18657SDean Michael Berris   }
462d6c18657SDean Michael Berris 
463d6c18657SDean Michael Berris   if (Sort)
46428f3d5cbSMandeep Singh Grang     std::stable_sort(T.Records.begin(), T.Records.end(),
465d6c18657SDean Michael Berris                      [&](const XRayRecord &L, const XRayRecord &R) {
466d6c18657SDean Michael Berris                        return L.TSC < R.TSC;
467d6c18657SDean Michael Berris                      });
468d6c18657SDean Michael Berris 
469d6c18657SDean Michael Berris   return std::move(T);
470d6c18657SDean Michael Berris }
471