blob: 4f107e1059ccbf33eea037b4d50a44f8464b3d7d [file] [log] [blame]
Dean Michael Berrisd6c18652017-01-11 06:39:09 +00001//===- Trace.cpp - XRay Trace Loading implementation. ---------------------===//
Dean Michael Berrisf8f909f2017-01-10 02:38:11 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Dean Michael Berrisf8f909f2017-01-10 02:38:11 +00006//
7//===----------------------------------------------------------------------===//
8//
9// XRay log reader implementation.
10//
11//===----------------------------------------------------------------------===//
Dean Michael Berrisd6c18652017-01-11 06:39:09 +000012#include "llvm/XRay/Trace.h"
13#include "llvm/ADT/STLExtras.h"
Dean Michael Berrisf8f909f2017-01-10 02:38:11 +000014#include "llvm/Support/DataExtractor.h"
Dean Michael Berrisd6c18652017-01-11 06:39:09 +000015#include "llvm/Support/Error.h"
Dean Michael Berrisf8f909f2017-01-10 02:38:11 +000016#include "llvm/Support/FileSystem.h"
Dean Michael Berris985c2b92018-09-11 06:45:59 +000017#include "llvm/XRay/BlockIndexer.h"
18#include "llvm/XRay/BlockVerifier.h"
19#include "llvm/XRay/FDRRecordConsumer.h"
20#include "llvm/XRay/FDRRecordProducer.h"
21#include "llvm/XRay/FDRRecords.h"
22#include "llvm/XRay/FDRTraceExpander.h"
Dean Michael Berrisd764c1b2018-08-22 07:37:55 +000023#include "llvm/XRay/FileHeaderReader.h"
Dean Michael Berrisd6c18652017-01-11 06:39:09 +000024#include "llvm/XRay/YAMLXRayRecord.h"
Dean Michael Berris985c2b92018-09-11 06:45:59 +000025#include <memory>
26#include <vector>
Dean Michael Berrisf8f909f2017-01-10 02:38:11 +000027
28using namespace llvm;
29using namespace llvm::xray;
30using llvm::yaml::Input;
31
Benjamin Kramer49a49fe2017-08-20 13:03:48 +000032namespace {
Dean Michael Berrisd6c18652017-01-11 06:39:09 +000033using XRayRecordStorage =
34 std::aligned_storage<sizeof(XRayRecord), alignof(XRayRecord)>::type;
Dean Michael Berrisf8f909f2017-01-10 02:38:11 +000035
Dean Michael Berris5b7548c2018-08-31 17:06:28 +000036Error loadNaiveFormatLog(StringRef Data, bool IsLittleEndian,
37 XRayFileHeader &FileHeader,
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +000038 std::vector<XRayRecord> &Records) {
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +000039 if (Data.size() < 32)
40 return make_error<StringError>(
41 "Not enough bytes for an XRay log.",
42 std::make_error_code(std::errc::invalid_argument));
43
44 if (Data.size() - 32 == 0 || Data.size() % 32 != 0)
45 return make_error<StringError>(
46 "Invalid-sized XRay data.",
47 std::make_error_code(std::errc::invalid_argument));
48
Dean Michael Berris5b7548c2018-08-31 17:06:28 +000049 DataExtractor Reader(Data, IsLittleEndian, 8);
Igor Kudrinf26a70a2019-08-06 10:49:40 +000050 uint64_t OffsetPtr = 0;
Dean Michael Berrisd764c1b2018-08-22 07:37:55 +000051 auto FileHeaderOrError = readBinaryFormatHeader(Reader, OffsetPtr);
52 if (!FileHeaderOrError)
53 return FileHeaderOrError.takeError();
54 FileHeader = std::move(FileHeaderOrError.get());
Dean Michael Berrisf8f909f2017-01-10 02:38:11 +000055
56 // Each record after the header will be 32 bytes, in the following format:
57 //
58 // (2) uint16 : record type
59 // (1) uint8 : cpu id
60 // (1) uint8 : type
61 // (4) sint32 : function id
62 // (8) uint64 : tsc
63 // (4) uint32 : thread id
Dean Michael Berris10141262018-07-13 05:38:22 +000064 // (4) uint32 : process id
65 // (8) - : padding
Dean Michael Berrisa9d477a2018-08-07 04:42:39 +000066 while (Reader.isValidOffset(OffsetPtr)) {
67 if (!Reader.isValidOffsetForDataOfSize(OffsetPtr, 32))
68 return createStringError(
69 std::make_error_code(std::errc::executable_format_error),
Igor Kudrinf26a70a2019-08-06 10:49:40 +000070 "Not enough bytes to read a full record at offset %" PRId64 ".",
71 OffsetPtr);
Dean Michael Berrisa9d477a2018-08-07 04:42:39 +000072 auto PreReadOffset = OffsetPtr;
73 auto RecordType = Reader.getU16(&OffsetPtr);
74 if (OffsetPtr == PreReadOffset)
75 return createStringError(
76 std::make_error_code(std::errc::executable_format_error),
Igor Kudrinf26a70a2019-08-06 10:49:40 +000077 "Failed reading record type at offset %" PRId64 ".", OffsetPtr);
Dean Michael Berrisa9d477a2018-08-07 04:42:39 +000078
79 switch (RecordType) {
Dean Michael Berris0a465d72017-10-05 05:18:17 +000080 case 0: { // Normal records.
81 Records.emplace_back();
82 auto &Record = Records.back();
83 Record.RecordType = RecordType;
Dean Michael Berrisa9d477a2018-08-07 04:42:39 +000084
85 PreReadOffset = OffsetPtr;
86 Record.CPU = Reader.getU8(&OffsetPtr);
87 if (OffsetPtr == PreReadOffset)
88 return createStringError(
89 std::make_error_code(std::errc::executable_format_error),
Igor Kudrinf26a70a2019-08-06 10:49:40 +000090 "Failed reading CPU field at offset %" PRId64 ".", OffsetPtr);
Dean Michael Berrisa9d477a2018-08-07 04:42:39 +000091
92 PreReadOffset = OffsetPtr;
93 auto Type = Reader.getU8(&OffsetPtr);
94 if (OffsetPtr == PreReadOffset)
95 return createStringError(
96 std::make_error_code(std::errc::executable_format_error),
Igor Kudrinf26a70a2019-08-06 10:49:40 +000097 "Failed reading record type field at offset %" PRId64 ".",
98 OffsetPtr);
Dean Michael Berrisa9d477a2018-08-07 04:42:39 +000099
Dean Michael Berris0a465d72017-10-05 05:18:17 +0000100 switch (Type) {
101 case 0:
102 Record.Type = RecordTypes::ENTER;
103 break;
104 case 1:
105 Record.Type = RecordTypes::EXIT;
106 break;
107 case 2:
108 Record.Type = RecordTypes::TAIL_EXIT;
109 break;
110 case 3:
111 Record.Type = RecordTypes::ENTER_ARG;
112 break;
113 default:
Dean Michael Berrisa9d477a2018-08-07 04:42:39 +0000114 return createStringError(
115 std::make_error_code(std::errc::executable_format_error),
Igor Kudrinf26a70a2019-08-06 10:49:40 +0000116 "Unknown record type '%d' at offset %" PRId64 ".", Type, OffsetPtr);
Dean Michael Berris0a465d72017-10-05 05:18:17 +0000117 }
Dean Michael Berrisa9d477a2018-08-07 04:42:39 +0000118
119 PreReadOffset = OffsetPtr;
120 Record.FuncId = Reader.getSigned(&OffsetPtr, sizeof(int32_t));
121 if (OffsetPtr == PreReadOffset)
122 return createStringError(
123 std::make_error_code(std::errc::executable_format_error),
Igor Kudrinf26a70a2019-08-06 10:49:40 +0000124 "Failed reading function id field at offset %" PRId64 ".",
125 OffsetPtr);
Dean Michael Berrisa9d477a2018-08-07 04:42:39 +0000126
127 PreReadOffset = OffsetPtr;
128 Record.TSC = Reader.getU64(&OffsetPtr);
129 if (OffsetPtr == PreReadOffset)
130 return createStringError(
131 std::make_error_code(std::errc::executable_format_error),
Igor Kudrinf26a70a2019-08-06 10:49:40 +0000132 "Failed reading TSC field at offset %" PRId64 ".", OffsetPtr);
Dean Michael Berrisa9d477a2018-08-07 04:42:39 +0000133
134 PreReadOffset = OffsetPtr;
135 Record.TId = Reader.getU32(&OffsetPtr);
136 if (OffsetPtr == PreReadOffset)
137 return createStringError(
138 std::make_error_code(std::errc::executable_format_error),
Igor Kudrinf26a70a2019-08-06 10:49:40 +0000139 "Failed reading thread id field at offset %" PRId64 ".", OffsetPtr);
Dean Michael Berrisa9d477a2018-08-07 04:42:39 +0000140
141 PreReadOffset = OffsetPtr;
142 Record.PId = Reader.getU32(&OffsetPtr);
143 if (OffsetPtr == PreReadOffset)
144 return createStringError(
145 std::make_error_code(std::errc::executable_format_error),
Igor Kudrinf26a70a2019-08-06 10:49:40 +0000146 "Failed reading process id at offset %" PRId64 ".", OffsetPtr);
Dean Michael Berrisa9d477a2018-08-07 04:42:39 +0000147
Dean Michael Berrisf8f909f2017-01-10 02:38:11 +0000148 break;
Dean Michael Berris0a465d72017-10-05 05:18:17 +0000149 }
150 case 1: { // Arg payload record.
151 auto &Record = Records.back();
Dean Michael Berrisa9d477a2018-08-07 04:42:39 +0000152
153 // We skip the next two bytes of the record, because we don't need the
154 // type and the CPU record for arg payloads.
Dean Michael Berris0a465d72017-10-05 05:18:17 +0000155 OffsetPtr += 2;
Dean Michael Berrisa9d477a2018-08-07 04:42:39 +0000156 PreReadOffset = OffsetPtr;
157 int32_t FuncId = Reader.getSigned(&OffsetPtr, sizeof(int32_t));
158 if (OffsetPtr == PreReadOffset)
159 return createStringError(
160 std::make_error_code(std::errc::executable_format_error),
Igor Kudrinf26a70a2019-08-06 10:49:40 +0000161 "Failed reading function id field at offset %" PRId64 ".",
162 OffsetPtr);
Dean Michael Berrisa9d477a2018-08-07 04:42:39 +0000163
164 PreReadOffset = OffsetPtr;
165 auto TId = Reader.getU32(&OffsetPtr);
166 if (OffsetPtr == PreReadOffset)
167 return createStringError(
168 std::make_error_code(std::errc::executable_format_error),
Igor Kudrinf26a70a2019-08-06 10:49:40 +0000169 "Failed reading thread id field at offset %" PRId64 ".", OffsetPtr);
Dean Michael Berrisa9d477a2018-08-07 04:42:39 +0000170
171 PreReadOffset = OffsetPtr;
172 auto PId = Reader.getU32(&OffsetPtr);
173 if (OffsetPtr == PreReadOffset)
174 return createStringError(
175 std::make_error_code(std::errc::executable_format_error),
Igor Kudrinf26a70a2019-08-06 10:49:40 +0000176 "Failed reading process id field at offset %" PRId64 ".",
177 OffsetPtr);
Dean Michael Berris10141262018-07-13 05:38:22 +0000178
179 // Make a check for versions above 3 for the Pid field
180 if (Record.FuncId != FuncId || Record.TId != TId ||
181 (FileHeader.Version >= 3 ? Record.PId != PId : false))
Dean Michael Berrisa9d477a2018-08-07 04:42:39 +0000182 return createStringError(
183 std::make_error_code(std::errc::executable_format_error),
184 "Corrupted log, found arg payload following non-matching "
185 "function+thread record. Record for function %d != %d at offset "
Igor Kudrinf26a70a2019-08-06 10:49:40 +0000186 "%" PRId64 ".",
Dean Michael Berrisa9d477a2018-08-07 04:42:39 +0000187 Record.FuncId, FuncId, OffsetPtr);
Dean Michael Berris10141262018-07-13 05:38:22 +0000188
Dean Michael Berrisa9d477a2018-08-07 04:42:39 +0000189 PreReadOffset = OffsetPtr;
190 auto Arg = Reader.getU64(&OffsetPtr);
191 if (OffsetPtr == PreReadOffset)
192 return createStringError(
193 std::make_error_code(std::errc::executable_format_error),
Igor Kudrinf26a70a2019-08-06 10:49:40 +0000194 "Failed reading argument payload at offset %" PRId64 ".",
195 OffsetPtr);
Dean Michael Berrisa9d477a2018-08-07 04:42:39 +0000196
Dean Michael Berris0a465d72017-10-05 05:18:17 +0000197 Record.CallArgs.push_back(Arg);
Dean Michael Berrisf8f909f2017-01-10 02:38:11 +0000198 break;
Dean Michael Berris0a465d72017-10-05 05:18:17 +0000199 }
Dean Michael Berrisf8f909f2017-01-10 02:38:11 +0000200 default:
Dean Michael Berrisa9d477a2018-08-07 04:42:39 +0000201 return createStringError(
202 std::make_error_code(std::errc::executable_format_error),
Igor Kudrinf26a70a2019-08-06 10:49:40 +0000203 "Unknown record type '%d' at offset %" PRId64 ".", RecordType,
204 OffsetPtr);
Dean Michael Berrisf8f909f2017-01-10 02:38:11 +0000205 }
Dean Michael Berrisa9d477a2018-08-07 04:42:39 +0000206 // Advance the offset pointer enough bytes to align to 32-byte records for
207 // basic mode logs.
208 OffsetPtr += 8;
Dean Michael Berrisf8f909f2017-01-10 02:38:11 +0000209 }
210 return Error::success();
211}
212
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000213/// Reads a log in FDR mode for version 1 of this binary format. FDR mode is
214/// defined as part of the compiler-rt project in xray_fdr_logging.h, and such
215/// a log consists of the familiar 32 bit XRayHeader, followed by sequences of
216/// of interspersed 16 byte Metadata Records and 8 byte Function Records.
217///
218/// The following is an attempt to document the grammar of the format, which is
219/// parsed by this function for little-endian machines. Since the format makes
Martin Pelikand78db152017-09-15 04:22:16 +0000220/// use of BitFields, when we support big-endian architectures, we will need to
Simon Pilgrim68168d12017-03-30 12:59:53 +0000221/// adjust not only the endianness parameter to llvm's RecordExtractor, but also
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000222/// the bit twiddling logic, which is consistent with the little-endian
223/// convention that BitFields within a struct will first be packed into the
224/// least significant bits the address they belong to.
225///
Dean Michael Berris6ec72622017-11-21 07:16:57 +0000226/// We expect a format complying with the grammar in the following pseudo-EBNF
227/// in Version 1 of the FDR log.
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000228///
229/// FDRLog: XRayFileHeader ThreadBuffer*
Keith Wyss3d0bc9e2017-08-02 21:47:27 +0000230/// XRayFileHeader: 32 bytes to identify the log as FDR with machine metadata.
231/// Includes BufferSize
232/// ThreadBuffer: NewBuffer WallClockTime NewCPUId FunctionSequence EOB
Dean Michael Berris60c24872017-03-29 06:10:12 +0000233/// BufSize: 8 byte unsigned integer indicating how large the buffer is.
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000234/// NewBuffer: 16 byte metadata record with Thread Id.
235/// WallClockTime: 16 byte metadata record with human readable time.
Dean Michael Berris10141262018-07-13 05:38:22 +0000236/// Pid: 16 byte metadata record with Pid
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000237/// NewCPUId: 16 byte metadata record with CPUId and a 64 bit TSC reading.
Dean Michael Berris60c24872017-03-29 06:10:12 +0000238/// EOB: 16 byte record in a thread buffer plus mem garbage to fill BufSize.
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000239/// FunctionSequence: NewCPUId | TSCWrap | FunctionRecord
240/// TSCWrap: 16 byte metadata record with a full 64 bit TSC reading.
241/// FunctionRecord: 8 byte record with FunctionId, entry/exit, and TSC delta.
Dean Michael Berris6ec72622017-11-21 07:16:57 +0000242///
243/// In Version 2, we make the following changes:
244///
245/// ThreadBuffer: BufferExtents NewBuffer WallClockTime NewCPUId
246/// FunctionSequence
247/// BufferExtents: 16 byte metdata record describing how many usable bytes are
248/// in the buffer. This is measured from the start of the buffer
249/// and must always be at least 48 (bytes).
Dean Michael Berris10141262018-07-13 05:38:22 +0000250///
251/// In Version 3, we make the following changes:
252///
253/// ThreadBuffer: BufferExtents NewBuffer WallClockTime Pid NewCPUId
254/// FunctionSequence
Dean Michael Berris6ec72622017-11-21 07:16:57 +0000255/// EOB: *deprecated*
Dean Michael Berris59439dd2018-11-07 04:37:42 +0000256///
257/// In Version 4, we make the following changes:
258///
259/// CustomEventRecord now includes the CPU data.
260///
261/// In Version 5, we make the following changes:
262///
263/// CustomEventRecord and TypedEventRecord now use TSC delta encoding similar to
264/// what FunctionRecord instances use, and we no longer need to include the CPU
265/// id in the CustomEventRecord.
266///
Dean Michael Berris5b7548c2018-08-31 17:06:28 +0000267Error loadFDRLog(StringRef Data, bool IsLittleEndian,
268 XRayFileHeader &FileHeader, std::vector<XRayRecord> &Records) {
Dean Michael Berrisd764c1b2018-08-22 07:37:55 +0000269
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000270 if (Data.size() < 32)
Dean Michael Berris985c2b92018-09-11 06:45:59 +0000271 return createStringError(std::make_error_code(std::errc::invalid_argument),
272 "Not enough bytes for an XRay FDR log.");
273 DataExtractor DE(Data, IsLittleEndian, 8);
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000274
Igor Kudrinf26a70a2019-08-06 10:49:40 +0000275 uint64_t OffsetPtr = 0;
Dean Michael Berris985c2b92018-09-11 06:45:59 +0000276 auto FileHeaderOrError = readBinaryFormatHeader(DE, OffsetPtr);
Dean Michael Berrisd764c1b2018-08-22 07:37:55 +0000277 if (!FileHeaderOrError)
278 return FileHeaderOrError.takeError();
279 FileHeader = std::move(FileHeaderOrError.get());
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000280
Dean Michael Berris985c2b92018-09-11 06:45:59 +0000281 // First we load the records into memory.
282 std::vector<std::unique_ptr<Record>> FDRRecords;
283
Dean Michael Berris60c24872017-03-29 06:10:12 +0000284 {
Dean Michael Berris985c2b92018-09-11 06:45:59 +0000285 FileBasedRecordProducer P(FileHeader, DE, OffsetPtr);
286 LogBuilderConsumer C(FDRRecords);
287 while (DE.isValidOffsetForDataOfSize(OffsetPtr, 1)) {
288 auto R = P.produce();
289 if (!R)
290 return R.takeError();
291 if (auto E = C.consume(std::move(R.get())))
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000292 return E;
293 }
Dean Michael Berris985c2b92018-09-11 06:45:59 +0000294 }
Dean Michael Berris6ec72622017-11-21 07:16:57 +0000295
Dean Michael Berris985c2b92018-09-11 06:45:59 +0000296 // Next we index the records into blocks.
297 BlockIndexer::Index Index;
298 {
299 BlockIndexer Indexer(Index);
300 for (auto &R : FDRRecords)
301 if (auto E = R->apply(Indexer))
302 return E;
303 if (auto E = Indexer.flush())
304 return E;
305 }
Dean Michael Berrisa9d477a2018-08-07 04:42:39 +0000306
Dean Michael Berris985c2b92018-09-11 06:45:59 +0000307 // Then we verify the consistency of the blocks.
308 {
Dean Michael Berris985c2b92018-09-11 06:45:59 +0000309 for (auto &PTB : Index) {
310 auto &Blocks = PTB.second;
311 for (auto &B : Blocks) {
Dean Michael Berris90a46bd2018-09-13 09:25:42 +0000312 BlockVerifier Verifier;
Dean Michael Berris985c2b92018-09-11 06:45:59 +0000313 for (auto *R : B.Records)
314 if (auto E = R->apply(Verifier))
315 return E;
316 if (auto E = Verifier.verify())
317 return E;
Dean Michael Berris985c2b92018-09-11 06:45:59 +0000318 }
Dean Michael Berris6ec72622017-11-21 07:16:57 +0000319 }
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000320 }
Martin Pelikand78db152017-09-15 04:22:16 +0000321
Dean Michael Berris985c2b92018-09-11 06:45:59 +0000322 // This is now the meat of the algorithm. Here we sort the blocks according to
323 // the Walltime record in each of the blocks for the same thread. This allows
324 // us to more consistently recreate the execution trace in temporal order.
325 // After the sort, we then reconstitute `Trace` records using a stateful
326 // visitor associated with a single process+thread pair.
327 {
328 for (auto &PTB : Index) {
329 auto &Blocks = PTB.second;
Dean Michael Berris6b67ff02018-11-01 00:18:52 +0000330 llvm::sort(Blocks, [](const BlockIndexer::Block &L,
331 const BlockIndexer::Block &R) {
332 return (L.WallclockTime->seconds() < R.WallclockTime->seconds() &&
333 L.WallclockTime->nanos() < R.WallclockTime->nanos());
334 });
Dean Michael Berris174d2cf2018-09-11 08:03:30 +0000335 auto Adder = [&](const XRayRecord &R) { Records.push_back(R); };
336 TraceExpander Expander(Adder, FileHeader.Version);
Dean Michael Berris985c2b92018-09-11 06:45:59 +0000337 for (auto &B : Blocks) {
338 for (auto *R : B.Records)
339 if (auto E = R->apply(Expander))
340 return E;
341 }
342 if (auto E = Expander.flush())
343 return E;
344 }
345 }
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000346
347 return Error::success();
348}
349
350Error loadYAMLLog(StringRef Data, XRayFileHeader &FileHeader,
351 std::vector<XRayRecord> &Records) {
Dean Michael Berrisf8f909f2017-01-10 02:38:11 +0000352 YAMLXRayTrace Trace;
353 Input In(Data);
354 In >> Trace;
355 if (In.error())
356 return make_error<StringError>("Failed loading YAML Data.", In.error());
357
358 FileHeader.Version = Trace.Header.Version;
359 FileHeader.Type = Trace.Header.Type;
360 FileHeader.ConstantTSC = Trace.Header.ConstantTSC;
361 FileHeader.NonstopTSC = Trace.Header.NonstopTSC;
362 FileHeader.CycleFrequency = Trace.Header.CycleFrequency;
363
364 if (FileHeader.Version != 1)
365 return make_error<StringError>(
366 Twine("Unsupported XRay file version: ") + Twine(FileHeader.Version),
367 std::make_error_code(std::errc::invalid_argument));
368
369 Records.clear();
370 std::transform(Trace.Records.begin(), Trace.Records.end(),
371 std::back_inserter(Records), [&](const YAMLXRayRecord &R) {
Dean Michael Berris25f8d202018-11-06 08:51:37 +0000372 return XRayRecord{R.RecordType, R.CPU, R.Type,
373 R.FuncId, R.TSC, R.TId,
374 R.PId, R.CallArgs, R.Data};
Dean Michael Berrisf8f909f2017-01-10 02:38:11 +0000375 });
376 return Error::success();
377}
Benjamin Kramer49a49fe2017-08-20 13:03:48 +0000378} // namespace
Dean Michael Berrisd6c18652017-01-11 06:39:09 +0000379
380Expected<Trace> llvm::xray::loadTraceFile(StringRef Filename, bool Sort) {
Reid Klecknerf002fcb2019-07-11 20:29:32 +0000381 Expected<sys::fs::file_t> FdOrErr = sys::fs::openNativeFileForRead(Filename);
382 if (!FdOrErr)
383 return FdOrErr.takeError();
Dean Michael Berrisd6c18652017-01-11 06:39:09 +0000384
Dean Michael Berrisd6c18652017-01-11 06:39:09 +0000385 uint64_t FileSize;
386 if (auto EC = sys::fs::file_size(Filename, FileSize)) {
387 return make_error<StringError>(
388 Twine("Cannot read log from '") + Filename + "'", EC);
389 }
390 if (FileSize < 4) {
391 return make_error<StringError>(
392 Twine("File '") + Filename + "' too small for XRay.",
Hans Wennborg84da6612017-01-12 18:33:14 +0000393 std::make_error_code(std::errc::executable_format_error));
Dean Michael Berrisd6c18652017-01-11 06:39:09 +0000394 }
395
Martin Pelikand78db152017-09-15 04:22:16 +0000396 // Map the opened file into memory and use a StringRef to access it later.
Dean Michael Berrisd6c18652017-01-11 06:39:09 +0000397 std::error_code EC;
398 sys::fs::mapped_file_region MappedFile(
Reid Klecknerf002fcb2019-07-11 20:29:32 +0000399 *FdOrErr, sys::fs::mapped_file_region::mapmode::readonly, FileSize, 0,
400 EC);
401 sys::fs::closeFile(*FdOrErr);
Dean Michael Berrisd6c18652017-01-11 06:39:09 +0000402 if (EC) {
403 return make_error<StringError>(
404 Twine("Cannot read log from '") + Filename + "'", EC);
405 }
Martin Pelikand78db152017-09-15 04:22:16 +0000406 auto Data = StringRef(MappedFile.data(), MappedFile.size());
Dean Michael Berris5b7548c2018-08-31 17:06:28 +0000407
408 // TODO: Lift the endianness and implementation selection here.
409 DataExtractor LittleEndianDE(Data, true, 8);
410 auto TraceOrError = loadTrace(LittleEndianDE, Sort);
411 if (!TraceOrError) {
412 DataExtractor BigEndianDE(Data, false, 8);
413 TraceOrError = loadTrace(BigEndianDE, Sort);
414 }
415 return TraceOrError;
Dean Michael Berrisf81b0802018-08-24 10:30:37 +0000416}
Dean Michael Berrisd6c18652017-01-11 06:39:09 +0000417
Dean Michael Berrisf81b0802018-08-24 10:30:37 +0000418Expected<Trace> llvm::xray::loadTrace(const DataExtractor &DE, bool Sort) {
Dean Michael Berrisd6c18652017-01-11 06:39:09 +0000419 // Attempt to detect the file type using file magic. We have a slight bias
420 // towards the binary format, and we do this by making sure that the first 4
421 // bytes of the binary file is some combination of the following byte
Martin Pelikand78db152017-09-15 04:22:16 +0000422 // patterns: (observe the code loading them assumes they're little endian)
Dean Michael Berrisd6c18652017-01-11 06:39:09 +0000423 //
Martin Pelikand78db152017-09-15 04:22:16 +0000424 // 0x01 0x00 0x00 0x00 - version 1, "naive" format
425 // 0x01 0x00 0x01 0x00 - version 1, "flight data recorder" format
Dean Michael Berris6ec72622017-11-21 07:16:57 +0000426 // 0x02 0x00 0x01 0x00 - version 2, "flight data recorder" format
Dean Michael Berrisd6c18652017-01-11 06:39:09 +0000427 //
Martin Pelikand78db152017-09-15 04:22:16 +0000428 // YAML files don't typically have those first four bytes as valid text so we
Dean Michael Berrisd6c18652017-01-11 06:39:09 +0000429 // try loading assuming YAML if we don't find these bytes.
430 //
431 // Only if we can't load either the binary or the YAML format will we yield an
432 // error.
Dean Michael Berris5b7548c2018-08-31 17:06:28 +0000433 DataExtractor HeaderExtractor(DE.getData(), DE.isLittleEndian(), 8);
Igor Kudrinf26a70a2019-08-06 10:49:40 +0000434 uint64_t OffsetPtr = 0;
Dean Michael Berrisd6c18652017-01-11 06:39:09 +0000435 uint16_t Version = HeaderExtractor.getU16(&OffsetPtr);
436 uint16_t Type = HeaderExtractor.getU16(&OffsetPtr);
437
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000438 enum BinaryFormatType { NAIVE_FORMAT = 0, FLIGHT_DATA_RECORDER_FORMAT = 1 };
439
Dean Michael Berrisd6c18652017-01-11 06:39:09 +0000440 Trace T;
Dean Michael Berris6ec72622017-11-21 07:16:57 +0000441 switch (Type) {
442 case NAIVE_FORMAT:
Dean Michael Berris10141262018-07-13 05:38:22 +0000443 if (Version == 1 || Version == 2 || Version == 3) {
Dean Michael Berris5b7548c2018-08-31 17:06:28 +0000444 if (auto E = loadNaiveFormatLog(DE.getData(), DE.isLittleEndian(),
445 T.FileHeader, T.Records))
Dean Michael Berris6ec72622017-11-21 07:16:57 +0000446 return std::move(E);
447 } else {
448 return make_error<StringError>(
449 Twine("Unsupported version for Basic/Naive Mode logging: ") +
450 Twine(Version),
451 std::make_error_code(std::errc::executable_format_error));
452 }
453 break;
454 case FLIGHT_DATA_RECORDER_FORMAT:
Dean Michael Berris59439dd2018-11-07 04:37:42 +0000455 if (Version >= 1 && Version <= 5) {
Dean Michael Berris5b7548c2018-08-31 17:06:28 +0000456 if (auto E = loadFDRLog(DE.getData(), DE.isLittleEndian(), T.FileHeader,
457 T.Records))
Dean Michael Berris6ec72622017-11-21 07:16:57 +0000458 return std::move(E);
459 } else {
460 return make_error<StringError>(
461 Twine("Unsupported version for FDR Mode logging: ") + Twine(Version),
462 std::make_error_code(std::errc::executable_format_error));
463 }
464 break;
465 default:
Dean Michael Berrisf81b0802018-08-24 10:30:37 +0000466 if (auto E = loadYAMLLog(DE.getData(), T.FileHeader, T.Records))
Dean Michael Berrisd6c18652017-01-11 06:39:09 +0000467 return std::move(E);
468 }
469
470 if (Sort)
Fangrui Songefd94c52019-04-23 14:51:27 +0000471 llvm::stable_sort(T.Records, [&](const XRayRecord &L, const XRayRecord &R) {
472 return L.TSC < R.TSC;
473 });
Dean Michael Berrisd6c18652017-01-11 06:39:09 +0000474
475 return std::move(T);
476}