blob: 0c5a562cf30284b92374d5cd1564f23f630a7ecf [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//
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//===----------------------------------------------------------------------===//
Dean Michael Berrisd6c18652017-01-11 06:39:09 +000013#include "llvm/XRay/Trace.h"
14#include "llvm/ADT/STLExtras.h"
Dean Michael Berrisf8f909f2017-01-10 02:38:11 +000015#include "llvm/Support/DataExtractor.h"
Dean Michael Berrisd6c18652017-01-11 06:39:09 +000016#include "llvm/Support/Error.h"
Dean Michael Berrisf8f909f2017-01-10 02:38:11 +000017#include "llvm/Support/FileSystem.h"
Dean Michael Berrisd6c18652017-01-11 06:39:09 +000018#include "llvm/XRay/YAMLXRayRecord.h"
Dean Michael Berrisf8f909f2017-01-10 02:38:11 +000019
20using namespace llvm;
21using namespace llvm::xray;
22using llvm::yaml::Input;
23
Benjamin Kramer49a49fe2017-08-20 13:03:48 +000024namespace {
Dean Michael Berrisd6c18652017-01-11 06:39:09 +000025using XRayRecordStorage =
26 std::aligned_storage<sizeof(XRayRecord), alignof(XRayRecord)>::type;
Dean Michael Berrisf8f909f2017-01-10 02:38:11 +000027
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +000028// Populates the FileHeader reference by reading the first 32 bytes of the file.
29Error readBinaryFormatHeader(StringRef Data, XRayFileHeader &FileHeader) {
Dean Michael Berrisf8f909f2017-01-10 02:38:11 +000030 // 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
Dean Michael Berrisf8f909f2017-01-10 02:38:11 +000041
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);
Dean Michael Berris60c24872017-03-29 06:10:12 +000050 std::memcpy(&FileHeader.FreeFormData, Data.bytes_begin() + OffsetPtr, 16);
Dean Michael Berrisf8f909f2017-01-10 02:38:11 +000051 if (FileHeader.Version != 1)
52 return make_error<StringError>(
53 Twine("Unsupported XRay file version: ") + Twine(FileHeader.Version),
54 std::make_error_code(std::errc::invalid_argument));
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +000055 return Error::success();
56}
57
58Error loadNaiveFormatLog(StringRef Data, XRayFileHeader &FileHeader,
59 std::vector<XRayRecord> &Records) {
60 // Check that there is at least a header
61 if (Data.size() < 32)
62 return make_error<StringError>(
63 "Not enough bytes for an XRay log.",
64 std::make_error_code(std::errc::invalid_argument));
65
66 if (Data.size() - 32 == 0 || Data.size() % 32 != 0)
67 return make_error<StringError>(
68 "Invalid-sized XRay data.",
69 std::make_error_code(std::errc::invalid_argument));
70
71 if (auto E = readBinaryFormatHeader(Data, FileHeader))
72 return E;
Dean Michael Berrisf8f909f2017-01-10 02:38:11 +000073
74 // Each record after the header will be 32 bytes, in the following format:
75 //
76 // (2) uint16 : record type
77 // (1) uint8 : cpu id
78 // (1) uint8 : type
79 // (4) sint32 : function id
80 // (8) uint64 : tsc
81 // (4) uint32 : thread id
82 // (12) - : padding
83 for (auto S = Data.drop_front(32); !S.empty(); S = S.drop_front(32)) {
84 DataExtractor RecordExtractor(S, true, 8);
85 uint32_t OffsetPtr = 0;
86 Records.emplace_back();
87 auto &Record = Records.back();
88 Record.RecordType = RecordExtractor.getU16(&OffsetPtr);
89 Record.CPU = RecordExtractor.getU8(&OffsetPtr);
90 auto Type = RecordExtractor.getU8(&OffsetPtr);
91 switch (Type) {
92 case 0:
93 Record.Type = RecordTypes::ENTER;
94 break;
95 case 1:
96 Record.Type = RecordTypes::EXIT;
97 break;
98 default:
99 return make_error<StringError>(
100 Twine("Unknown record type '") + Twine(int{Type}) + "'",
NAKAMURA Takumib09bec22017-01-11 01:06:57 +0000101 std::make_error_code(std::errc::executable_format_error));
Dean Michael Berrisf8f909f2017-01-10 02:38:11 +0000102 }
103 Record.FuncId = RecordExtractor.getSigned(&OffsetPtr, sizeof(int32_t));
104 Record.TSC = RecordExtractor.getU64(&OffsetPtr);
105 Record.TId = RecordExtractor.getU32(&OffsetPtr);
106 }
107 return Error::success();
108}
109
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000110/// When reading from a Flight Data Recorder mode log, metadata records are
111/// sparse compared to packed function records, so we must maintain state as we
112/// read through the sequence of entries. This allows the reader to denormalize
113/// the CPUId and Thread Id onto each Function Record and transform delta
114/// encoded TSC values into absolute encodings on each record.
115struct FDRState {
116 uint16_t CPUId;
117 uint16_t ThreadId;
118 uint64_t BaseTSC;
Dean Michael Berrisa7bbe442017-05-12 01:06:41 +0000119
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000120 /// Encode some of the state transitions for the FDR log reader as explicit
121 /// checks. These are expectations for the next Record in the stream.
122 enum class Token {
123 NEW_BUFFER_RECORD_OR_EOF,
124 WALLCLOCK_RECORD,
125 NEW_CPU_ID_RECORD,
Dean Michael Berris60c24872017-03-29 06:10:12 +0000126 FUNCTION_SEQUENCE,
127 SCAN_TO_END_OF_THREAD_BUF,
Dean Michael Berrisa7bbe442017-05-12 01:06:41 +0000128 CUSTOM_EVENT_DATA,
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000129 };
130 Token Expects;
Dean Michael Berrisa7bbe442017-05-12 01:06:41 +0000131
Dean Michael Berris60c24872017-03-29 06:10:12 +0000132 // Each threads buffer may have trailing garbage to scan over, so we track our
133 // progress.
134 uint64_t CurrentBufferSize;
135 uint64_t CurrentBufferConsumed;
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000136};
Dean Michael Berrisf8f909f2017-01-10 02:38:11 +0000137
Benjamin Kramer49a49fe2017-08-20 13:03:48 +0000138const char *fdrStateToTwine(const FDRState::Token &state) {
Dean Michael Berris60c24872017-03-29 06:10:12 +0000139 switch (state) {
140 case FDRState::Token::NEW_BUFFER_RECORD_OR_EOF:
141 return "NEW_BUFFER_RECORD_OR_EOF";
142 case FDRState::Token::WALLCLOCK_RECORD:
143 return "WALLCLOCK_RECORD";
144 case FDRState::Token::NEW_CPU_ID_RECORD:
145 return "NEW_CPU_ID_RECORD";
146 case FDRState::Token::FUNCTION_SEQUENCE:
147 return "FUNCTION_SEQUENCE";
148 case FDRState::Token::SCAN_TO_END_OF_THREAD_BUF:
149 return "SCAN_TO_END_OF_THREAD_BUF";
Dean Michael Berrisa7bbe442017-05-12 01:06:41 +0000150 case FDRState::Token::CUSTOM_EVENT_DATA:
151 return "CUSTOM_EVENT_DATA";
Dean Michael Berris60c24872017-03-29 06:10:12 +0000152 }
153 return "UNKNOWN";
154}
155
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000156/// State transition when a NewBufferRecord is encountered.
157Error processFDRNewBufferRecord(FDRState &State, uint8_t RecordFirstByte,
158 DataExtractor &RecordExtractor) {
159
Dean Michael Berris60c24872017-03-29 06:10:12 +0000160 if (State.Expects != FDRState::Token::NEW_BUFFER_RECORD_OR_EOF)
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000161 return make_error<StringError>(
162 "Malformed log. Read New Buffer record kind out of sequence",
163 std::make_error_code(std::errc::executable_format_error));
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000164 uint32_t OffsetPtr = 1; // 1 byte into record.
165 State.ThreadId = RecordExtractor.getU16(&OffsetPtr);
166 State.Expects = FDRState::Token::WALLCLOCK_RECORD;
167 return Error::success();
168}
169
170/// State transition when an EndOfBufferRecord is encountered.
171Error processFDREndOfBufferRecord(FDRState &State, uint8_t RecordFirstByte,
172 DataExtractor &RecordExtractor) {
Dean Michael Berris60c24872017-03-29 06:10:12 +0000173 if (State.Expects == FDRState::Token::NEW_BUFFER_RECORD_OR_EOF)
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000174 return make_error<StringError>(
175 "Malformed log. Received EOB message without current buffer.",
176 std::make_error_code(std::errc::executable_format_error));
Dean Michael Berris60c24872017-03-29 06:10:12 +0000177 State.Expects = FDRState::Token::SCAN_TO_END_OF_THREAD_BUF;
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000178 return Error::success();
179}
180
181/// State transition when a NewCPUIdRecord is encountered.
182Error processFDRNewCPUIdRecord(FDRState &State, uint8_t RecordFirstByte,
183 DataExtractor &RecordExtractor) {
184 if (State.Expects != FDRState::Token::FUNCTION_SEQUENCE &&
Dean Michael Berris60c24872017-03-29 06:10:12 +0000185 State.Expects != FDRState::Token::NEW_CPU_ID_RECORD)
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000186 return make_error<StringError>(
187 "Malformed log. Read NewCPUId record kind out of sequence",
188 std::make_error_code(std::errc::executable_format_error));
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000189 uint32_t OffsetPtr = 1; // Read starting after the first byte.
190 State.CPUId = RecordExtractor.getU16(&OffsetPtr);
191 State.BaseTSC = RecordExtractor.getU64(&OffsetPtr);
192 State.Expects = FDRState::Token::FUNCTION_SEQUENCE;
193 return Error::success();
194}
195
196/// State transition when a TSCWrapRecord (overflow detection) is encountered.
197Error processFDRTSCWrapRecord(FDRState &State, uint8_t RecordFirstByte,
198 DataExtractor &RecordExtractor) {
Dean Michael Berris60c24872017-03-29 06:10:12 +0000199 if (State.Expects != FDRState::Token::FUNCTION_SEQUENCE)
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000200 return make_error<StringError>(
201 "Malformed log. Read TSCWrap record kind out of sequence",
202 std::make_error_code(std::errc::executable_format_error));
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000203 uint32_t OffsetPtr = 1; // Read starting after the first byte.
204 State.BaseTSC = RecordExtractor.getU64(&OffsetPtr);
205 return Error::success();
206}
207
208/// State transition when a WallTimeMarkerRecord is encountered.
209Error processFDRWallTimeRecord(FDRState &State, uint8_t RecordFirstByte,
210 DataExtractor &RecordExtractor) {
Dean Michael Berris60c24872017-03-29 06:10:12 +0000211 if (State.Expects != FDRState::Token::WALLCLOCK_RECORD)
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000212 return make_error<StringError>(
213 "Malformed log. Read Wallclock record kind out of sequence",
214 std::make_error_code(std::errc::executable_format_error));
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000215 // We don't encode the wall time into any of the records.
216 // XRayRecords are concerned with the TSC instead.
217 State.Expects = FDRState::Token::NEW_CPU_ID_RECORD;
218 return Error::success();
219}
220
Dean Michael Berrisa7bbe442017-05-12 01:06:41 +0000221/// State transition when a CustomEventMarker is encountered.
222Error processCustomEventMarker(FDRState &State, uint8_t RecordFirstByte,
223 DataExtractor &RecordExtractor,
224 size_t &RecordSize) {
225 // We can encounter a CustomEventMarker anywhere in the log, so we can handle
Keith Wyss3d0bc9e2017-08-02 21:47:27 +0000226 // it regardless of the expectation. However, we do set the expectation to
227 // read a set number of fixed bytes, as described in the metadata.
Dean Michael Berrisa7bbe442017-05-12 01:06:41 +0000228 uint32_t OffsetPtr = 1; // Read after the first byte.
229 uint32_t DataSize = RecordExtractor.getU32(&OffsetPtr);
230 uint64_t TSC = RecordExtractor.getU64(&OffsetPtr);
231
232 // FIXME: Actually represent the record through the API. For now we only skip
233 // through the data.
234 (void)TSC;
235 RecordSize = 16 + DataSize;
236 return Error::success();
237}
238
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000239/// Advances the state machine for reading the FDR record type by reading one
Keith Wysse96152a2017-04-06 03:32:01 +0000240/// Metadata Record and updating the State appropriately based on the kind of
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000241/// record encountered. The RecordKind is encoded in the first byte of the
242/// Record, which the caller should pass in because they have already read it
243/// to determine that this is a metadata record as opposed to a function record.
244Error processFDRMetadataRecord(FDRState &State, uint8_t RecordFirstByte,
Dean Michael Berrisa7bbe442017-05-12 01:06:41 +0000245 DataExtractor &RecordExtractor,
246 size_t &RecordSize) {
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000247 // The remaining 7 bits are the RecordKind enum.
248 uint8_t RecordKind = RecordFirstByte >> 1;
249 switch (RecordKind) {
250 case 0: // NewBuffer
251 if (auto E =
252 processFDRNewBufferRecord(State, RecordFirstByte, RecordExtractor))
253 return E;
254 break;
255 case 1: // EndOfBuffer
256 if (auto E = processFDREndOfBufferRecord(State, RecordFirstByte,
257 RecordExtractor))
258 return E;
259 break;
260 case 2: // NewCPUId
261 if (auto E =
262 processFDRNewCPUIdRecord(State, RecordFirstByte, RecordExtractor))
263 return E;
264 break;
265 case 3: // TSCWrap
266 if (auto E =
267 processFDRTSCWrapRecord(State, RecordFirstByte, RecordExtractor))
268 return E;
269 break;
270 case 4: // WallTimeMarker
271 if (auto E =
272 processFDRWallTimeRecord(State, RecordFirstByte, RecordExtractor))
273 return E;
274 break;
Dean Michael Berrisa7bbe442017-05-12 01:06:41 +0000275 case 5: // CustomEventMarker
276 if (auto E = processCustomEventMarker(State, RecordFirstByte,
277 RecordExtractor, RecordSize))
278 return E;
279 break;
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000280 default:
281 // Widen the record type to uint16_t to prevent conversion to char.
282 return make_error<StringError>(
283 Twine("Illegal metadata record type: ")
284 .concat(Twine(static_cast<unsigned>(RecordKind))),
285 std::make_error_code(std::errc::executable_format_error));
286 }
287 return Error::success();
288}
289
290/// Reads a function record from an FDR format log, appending a new XRayRecord
291/// to the vector being populated and updating the State with a new value
292/// reference value to interpret TSC deltas.
293///
294/// The XRayRecord constructed includes information from the function record
295/// processed here as well as Thread ID and CPU ID formerly extracted into
296/// State.
297Error processFDRFunctionRecord(FDRState &State, uint8_t RecordFirstByte,
298 DataExtractor &RecordExtractor,
299 std::vector<XRayRecord> &Records) {
300 switch (State.Expects) {
301 case FDRState::Token::NEW_BUFFER_RECORD_OR_EOF:
302 return make_error<StringError>(
303 "Malformed log. Received Function Record before new buffer setup.",
304 std::make_error_code(std::errc::executable_format_error));
305 case FDRState::Token::WALLCLOCK_RECORD:
306 return make_error<StringError>(
307 "Malformed log. Received Function Record when expecting wallclock.",
308 std::make_error_code(std::errc::executable_format_error));
309 case FDRState::Token::NEW_CPU_ID_RECORD:
310 return make_error<StringError>(
311 "Malformed log. Received Function Record before first CPU record.",
312 std::make_error_code(std::errc::executable_format_error));
313 default:
314 Records.emplace_back();
315 auto &Record = Records.back();
316 Record.RecordType = 0; // Record is type NORMAL.
317 // Strip off record type bit and use the next three bits.
318 uint8_t RecordType = (RecordFirstByte >> 1) & 0x07;
319 switch (RecordType) {
320 case static_cast<uint8_t>(RecordTypes::ENTER):
321 Record.Type = RecordTypes::ENTER;
322 break;
323 case static_cast<uint8_t>(RecordTypes::EXIT):
324 case 2: // TAIL_EXIT is not yet defined in RecordTypes.
325 Record.Type = RecordTypes::EXIT;
326 break;
327 default:
328 // When initializing the error, convert to uint16_t so that the record
329 // type isn't interpreted as a char.
330 return make_error<StringError>(
331 Twine("Illegal function record type: ")
332 .concat(Twine(static_cast<unsigned>(RecordType))),
333 std::make_error_code(std::errc::executable_format_error));
334 }
335 Record.CPU = State.CPUId;
336 Record.TId = State.ThreadId;
Keith Wyss3d0bc9e2017-08-02 21:47:27 +0000337 // Back up to read first 32 bits, including the 4 we pulled RecordType
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000338 // and RecordKind out of. The remaining 28 are FunctionId.
339 uint32_t OffsetPtr = 0;
340 // Despite function Id being a signed int on XRayRecord,
341 // when it is written to an FDR format, the top bits are truncated,
342 // so it is effectively an unsigned value. When we shift off the
343 // top four bits, we want the shift to be logical, so we read as
344 // uint32_t.
345 uint32_t FuncIdBitField = RecordExtractor.getU32(&OffsetPtr);
346 Record.FuncId = FuncIdBitField >> 4;
347 // FunctionRecords have a 32 bit delta from the previous absolute TSC
348 // or TSC delta. If this would overflow, we should read a TSCWrap record
349 // with an absolute TSC reading.
350 uint64_t new_tsc = State.BaseTSC + RecordExtractor.getU32(&OffsetPtr);
351 State.BaseTSC = new_tsc;
352 Record.TSC = new_tsc;
353 }
354 return Error::success();
355}
356
357/// Reads a log in FDR mode for version 1 of this binary format. FDR mode is
358/// defined as part of the compiler-rt project in xray_fdr_logging.h, and such
359/// a log consists of the familiar 32 bit XRayHeader, followed by sequences of
360/// of interspersed 16 byte Metadata Records and 8 byte Function Records.
361///
362/// The following is an attempt to document the grammar of the format, which is
363/// parsed by this function for little-endian machines. Since the format makes
364/// use of BitFields, when we support big-Endian architectures, we will need to
Simon Pilgrim68168d12017-03-30 12:59:53 +0000365/// adjust not only the endianness parameter to llvm's RecordExtractor, but also
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000366/// the bit twiddling logic, which is consistent with the little-endian
367/// convention that BitFields within a struct will first be packed into the
368/// least significant bits the address they belong to.
369///
370/// We expect a format complying with the grammar in the following pseudo-EBNF.
371///
372/// FDRLog: XRayFileHeader ThreadBuffer*
Keith Wyss3d0bc9e2017-08-02 21:47:27 +0000373/// XRayFileHeader: 32 bytes to identify the log as FDR with machine metadata.
374/// Includes BufferSize
375/// ThreadBuffer: NewBuffer WallClockTime NewCPUId FunctionSequence EOB
Dean Michael Berris60c24872017-03-29 06:10:12 +0000376/// BufSize: 8 byte unsigned integer indicating how large the buffer is.
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000377/// NewBuffer: 16 byte metadata record with Thread Id.
378/// WallClockTime: 16 byte metadata record with human readable time.
379/// NewCPUId: 16 byte metadata record with CPUId and a 64 bit TSC reading.
Dean Michael Berris60c24872017-03-29 06:10:12 +0000380/// EOB: 16 byte record in a thread buffer plus mem garbage to fill BufSize.
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000381/// FunctionSequence: NewCPUId | TSCWrap | FunctionRecord
382/// TSCWrap: 16 byte metadata record with a full 64 bit TSC reading.
383/// FunctionRecord: 8 byte record with FunctionId, entry/exit, and TSC delta.
384Error loadFDRLog(StringRef Data, XRayFileHeader &FileHeader,
385 std::vector<XRayRecord> &Records) {
386 if (Data.size() < 32)
387 return make_error<StringError>(
388 "Not enough bytes for an XRay log.",
389 std::make_error_code(std::errc::invalid_argument));
390
391 // For an FDR log, there are records sized 16 and 8 bytes.
Dean Michael Berris60c24872017-03-29 06:10:12 +0000392 // There actually may be no records if no non-trivial functions are
393 // instrumented.
394 if (Data.size() % 8 != 0)
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000395 return make_error<StringError>(
396 "Invalid-sized XRay data.",
397 std::make_error_code(std::errc::invalid_argument));
398
399 if (auto E = readBinaryFormatHeader(Data, FileHeader))
400 return E;
401
Dean Michael Berris60c24872017-03-29 06:10:12 +0000402 uint64_t BufferSize = 0;
403 {
404 StringRef ExtraDataRef(FileHeader.FreeFormData, 16);
405 DataExtractor ExtraDataExtractor(ExtraDataRef, true, 8);
406 uint32_t ExtraDataOffset = 0;
407 BufferSize = ExtraDataExtractor.getU64(&ExtraDataOffset);
408 }
409 FDRState State{0, 0, 0, FDRState::Token::NEW_BUFFER_RECORD_OR_EOF,
410 BufferSize, 0};
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000411 // RecordSize will tell the loop how far to seek ahead based on the record
412 // type that we have just read.
413 size_t RecordSize = 0;
414 for (auto S = Data.drop_front(32); !S.empty(); S = S.drop_front(RecordSize)) {
415 DataExtractor RecordExtractor(S, true, 8);
416 uint32_t OffsetPtr = 0;
Dean Michael Berris60c24872017-03-29 06:10:12 +0000417 if (State.Expects == FDRState::Token::SCAN_TO_END_OF_THREAD_BUF) {
418 RecordSize = State.CurrentBufferSize - State.CurrentBufferConsumed;
419 if (S.size() < State.CurrentBufferSize - State.CurrentBufferConsumed) {
420 return make_error<StringError>(
421 Twine("Incomplete thread buffer. Expected ") +
422 Twine(State.CurrentBufferSize - State.CurrentBufferConsumed) +
423 " remaining bytes but found " + Twine(S.size()),
424 make_error_code(std::errc::invalid_argument));
425 }
426 State.CurrentBufferConsumed = 0;
427 State.Expects = FDRState::Token::NEW_BUFFER_RECORD_OR_EOF;
428 continue;
429 }
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000430 uint8_t BitField = RecordExtractor.getU8(&OffsetPtr);
431 bool isMetadataRecord = BitField & 0x01uL;
432 if (isMetadataRecord) {
433 RecordSize = 16;
Dean Michael Berrisa7bbe442017-05-12 01:06:41 +0000434 if (auto E = processFDRMetadataRecord(State, BitField, RecordExtractor,
435 RecordSize))
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000436 return E;
Dean Michael Berris60c24872017-03-29 06:10:12 +0000437 State.CurrentBufferConsumed += RecordSize;
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000438 } else { // Process Function Record
439 RecordSize = 8;
440 if (auto E = processFDRFunctionRecord(State, BitField, RecordExtractor,
441 Records))
442 return E;
Dean Michael Berris60c24872017-03-29 06:10:12 +0000443 State.CurrentBufferConsumed += RecordSize;
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000444 }
445 }
Dean Michael Berris60c24872017-03-29 06:10:12 +0000446 // There are two conditions
447 if (State.Expects != FDRState::Token::NEW_BUFFER_RECORD_OR_EOF &&
448 !(State.Expects == FDRState::Token::SCAN_TO_END_OF_THREAD_BUF &&
449 State.CurrentBufferSize == State.CurrentBufferConsumed))
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000450 return make_error<StringError>(
Dean Michael Berris60c24872017-03-29 06:10:12 +0000451 Twine("Encountered EOF with unexpected state expectation ") +
452 fdrStateToTwine(State.Expects) +
453 ". Remaining expected bytes in thread buffer total " +
454 Twine(State.CurrentBufferSize - State.CurrentBufferConsumed),
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000455 std::make_error_code(std::errc::executable_format_error));
456
457 return Error::success();
458}
459
460Error loadYAMLLog(StringRef Data, XRayFileHeader &FileHeader,
461 std::vector<XRayRecord> &Records) {
Dean Michael Berrisf8f909f2017-01-10 02:38:11 +0000462 // Load the documents from the MappedFile.
463 YAMLXRayTrace Trace;
464 Input In(Data);
465 In >> Trace;
466 if (In.error())
467 return make_error<StringError>("Failed loading YAML Data.", In.error());
468
469 FileHeader.Version = Trace.Header.Version;
470 FileHeader.Type = Trace.Header.Type;
471 FileHeader.ConstantTSC = Trace.Header.ConstantTSC;
472 FileHeader.NonstopTSC = Trace.Header.NonstopTSC;
473 FileHeader.CycleFrequency = Trace.Header.CycleFrequency;
474
475 if (FileHeader.Version != 1)
476 return make_error<StringError>(
477 Twine("Unsupported XRay file version: ") + Twine(FileHeader.Version),
478 std::make_error_code(std::errc::invalid_argument));
479
480 Records.clear();
481 std::transform(Trace.Records.begin(), Trace.Records.end(),
482 std::back_inserter(Records), [&](const YAMLXRayRecord &R) {
483 return XRayRecord{R.RecordType, R.CPU, R.Type,
484 R.FuncId, R.TSC, R.TId};
485 });
486 return Error::success();
487}
Benjamin Kramer49a49fe2017-08-20 13:03:48 +0000488} // namespace
Dean Michael Berrisd6c18652017-01-11 06:39:09 +0000489
490Expected<Trace> llvm::xray::loadTraceFile(StringRef Filename, bool Sort) {
491 int Fd;
492 if (auto EC = sys::fs::openFileForRead(Filename, Fd)) {
493 return make_error<StringError>(
494 Twine("Cannot read log from '") + Filename + "'", EC);
495 }
496
497 // Attempt to get the filesize.
498 uint64_t FileSize;
499 if (auto EC = sys::fs::file_size(Filename, FileSize)) {
500 return make_error<StringError>(
501 Twine("Cannot read log from '") + Filename + "'", EC);
502 }
503 if (FileSize < 4) {
504 return make_error<StringError>(
505 Twine("File '") + Filename + "' too small for XRay.",
Hans Wennborg84da6612017-01-12 18:33:14 +0000506 std::make_error_code(std::errc::executable_format_error));
Dean Michael Berrisd6c18652017-01-11 06:39:09 +0000507 }
508
509 // Attempt to mmap the file.
510 std::error_code EC;
511 sys::fs::mapped_file_region MappedFile(
512 Fd, sys::fs::mapped_file_region::mapmode::readonly, FileSize, 0, EC);
513 if (EC) {
514 return make_error<StringError>(
515 Twine("Cannot read log from '") + Filename + "'", EC);
516 }
517
518 // Attempt to detect the file type using file magic. We have a slight bias
519 // towards the binary format, and we do this by making sure that the first 4
520 // bytes of the binary file is some combination of the following byte
521 // patterns:
522 //
523 // 0x0001 0x0000 - version 1, "naive" format
524 // 0x0001 0x0001 - version 1, "flight data recorder" format
525 //
526 // YAML files dont' typically have those first four bytes as valid text so we
527 // try loading assuming YAML if we don't find these bytes.
528 //
529 // Only if we can't load either the binary or the YAML format will we yield an
530 // error.
531 StringRef Magic(MappedFile.data(), 4);
532 DataExtractor HeaderExtractor(Magic, true, 8);
533 uint32_t OffsetPtr = 0;
534 uint16_t Version = HeaderExtractor.getU16(&OffsetPtr);
535 uint16_t Type = HeaderExtractor.getU16(&OffsetPtr);
536
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000537 enum BinaryFormatType { NAIVE_FORMAT = 0, FLIGHT_DATA_RECORDER_FORMAT = 1 };
538
Dean Michael Berrisd6c18652017-01-11 06:39:09 +0000539 Trace T;
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000540 if (Version == 1 && Type == NAIVE_FORMAT) {
541 if (auto E =
542 loadNaiveFormatLog(StringRef(MappedFile.data(), MappedFile.size()),
543 T.FileHeader, T.Records))
544 return std::move(E);
545 } else if (Version == 1 && Type == FLIGHT_DATA_RECORDER_FORMAT) {
546 if (auto E = loadFDRLog(StringRef(MappedFile.data(), MappedFile.size()),
547 T.FileHeader, T.Records))
Dean Michael Berrisd6c18652017-01-11 06:39:09 +0000548 return std::move(E);
549 } else {
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000550 if (auto E = loadYAMLLog(StringRef(MappedFile.data(), MappedFile.size()),
551 T.FileHeader, T.Records))
Dean Michael Berrisd6c18652017-01-11 06:39:09 +0000552 return std::move(E);
553 }
554
555 if (Sort)
556 std::sort(T.Records.begin(), T.Records.end(),
557 [&](const XRayRecord &L, const XRayRecord &R) {
558 return L.TSC < R.TSC;
559 });
560
561 return std::move(T);
562}