blob: 89fd0b0748bfff0a28a83ea1965c986a51ad44ad [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
Dean Michael Berrisd6c18652017-01-11 06:39:09 +000024using XRayRecordStorage =
25 std::aligned_storage<sizeof(XRayRecord), alignof(XRayRecord)>::type;
Dean Michael Berrisf8f909f2017-01-10 02:38:11 +000026
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +000027// Populates the FileHeader reference by reading the first 32 bytes of the file.
28Error readBinaryFormatHeader(StringRef Data, XRayFileHeader &FileHeader) {
Dean Michael Berrisf8f909f2017-01-10 02:38:11 +000029 // FIXME: Maybe deduce whether the data is little or big-endian using some
30 // magic bytes in the beginning of the file?
31
32 // First 32 bytes of the file will always be the header. We assume a certain
33 // format here:
34 //
35 // (2) uint16 : version
36 // (2) uint16 : type
37 // (4) uint32 : bitfield
38 // (8) uint64 : cycle frequency
39 // (16) - : padding
Dean Michael Berrisf8f909f2017-01-10 02:38:11 +000040
41 DataExtractor HeaderExtractor(Data, true, 8);
42 uint32_t OffsetPtr = 0;
43 FileHeader.Version = HeaderExtractor.getU16(&OffsetPtr);
44 FileHeader.Type = HeaderExtractor.getU16(&OffsetPtr);
45 uint32_t Bitfield = HeaderExtractor.getU32(&OffsetPtr);
46 FileHeader.ConstantTSC = Bitfield & 1uL;
47 FileHeader.NonstopTSC = Bitfield & 1uL << 1;
48 FileHeader.CycleFrequency = HeaderExtractor.getU64(&OffsetPtr);
Dean Michael Berris60c24872017-03-29 06:10:12 +000049 std::memcpy(&FileHeader.FreeFormData, Data.bytes_begin() + OffsetPtr, 16);
Dean Michael Berrisf8f909f2017-01-10 02:38:11 +000050 if (FileHeader.Version != 1)
51 return make_error<StringError>(
52 Twine("Unsupported XRay file version: ") + Twine(FileHeader.Version),
53 std::make_error_code(std::errc::invalid_argument));
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +000054 return Error::success();
55}
56
57Error loadNaiveFormatLog(StringRef Data, XRayFileHeader &FileHeader,
58 std::vector<XRayRecord> &Records) {
59 // Check that there is at least a header
60 if (Data.size() < 32)
61 return make_error<StringError>(
62 "Not enough bytes for an XRay log.",
63 std::make_error_code(std::errc::invalid_argument));
64
65 if (Data.size() - 32 == 0 || Data.size() % 32 != 0)
66 return make_error<StringError>(
67 "Invalid-sized XRay data.",
68 std::make_error_code(std::errc::invalid_argument));
69
70 if (auto E = readBinaryFormatHeader(Data, FileHeader))
71 return E;
Dean Michael Berrisf8f909f2017-01-10 02:38:11 +000072
73 // Each record after the header will be 32 bytes, in the following format:
74 //
75 // (2) uint16 : record type
76 // (1) uint8 : cpu id
77 // (1) uint8 : type
78 // (4) sint32 : function id
79 // (8) uint64 : tsc
80 // (4) uint32 : thread id
81 // (12) - : padding
82 for (auto S = Data.drop_front(32); !S.empty(); S = S.drop_front(32)) {
83 DataExtractor RecordExtractor(S, true, 8);
84 uint32_t OffsetPtr = 0;
85 Records.emplace_back();
86 auto &Record = Records.back();
87 Record.RecordType = RecordExtractor.getU16(&OffsetPtr);
88 Record.CPU = RecordExtractor.getU8(&OffsetPtr);
89 auto Type = RecordExtractor.getU8(&OffsetPtr);
90 switch (Type) {
91 case 0:
92 Record.Type = RecordTypes::ENTER;
93 break;
94 case 1:
95 Record.Type = RecordTypes::EXIT;
96 break;
97 default:
98 return make_error<StringError>(
99 Twine("Unknown record type '") + Twine(int{Type}) + "'",
NAKAMURA Takumib09bec22017-01-11 01:06:57 +0000100 std::make_error_code(std::errc::executable_format_error));
Dean Michael Berrisf8f909f2017-01-10 02:38:11 +0000101 }
102 Record.FuncId = RecordExtractor.getSigned(&OffsetPtr, sizeof(int32_t));
103 Record.TSC = RecordExtractor.getU64(&OffsetPtr);
104 Record.TId = RecordExtractor.getU32(&OffsetPtr);
105 }
106 return Error::success();
107}
108
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000109/// When reading from a Flight Data Recorder mode log, metadata records are
110/// sparse compared to packed function records, so we must maintain state as we
111/// read through the sequence of entries. This allows the reader to denormalize
112/// the CPUId and Thread Id onto each Function Record and transform delta
113/// encoded TSC values into absolute encodings on each record.
114struct FDRState {
115 uint16_t CPUId;
116 uint16_t ThreadId;
117 uint64_t BaseTSC;
Dean Michael Berrisa7bbe442017-05-12 01:06:41 +0000118
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000119 /// Encode some of the state transitions for the FDR log reader as explicit
120 /// checks. These are expectations for the next Record in the stream.
121 enum class Token {
122 NEW_BUFFER_RECORD_OR_EOF,
123 WALLCLOCK_RECORD,
124 NEW_CPU_ID_RECORD,
Dean Michael Berris60c24872017-03-29 06:10:12 +0000125 FUNCTION_SEQUENCE,
126 SCAN_TO_END_OF_THREAD_BUF,
Dean Michael Berrisa7bbe442017-05-12 01:06:41 +0000127 CUSTOM_EVENT_DATA,
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000128 };
129 Token Expects;
Dean Michael Berrisa7bbe442017-05-12 01:06:41 +0000130
Dean Michael Berris60c24872017-03-29 06:10:12 +0000131 // Each threads buffer may have trailing garbage to scan over, so we track our
132 // progress.
133 uint64_t CurrentBufferSize;
134 uint64_t CurrentBufferConsumed;
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000135};
Dean Michael Berrisf8f909f2017-01-10 02:38:11 +0000136
Dean Michael Berris60c24872017-03-29 06:10:12 +0000137Twine fdrStateToTwine(const FDRState::Token &state) {
138 switch (state) {
139 case FDRState::Token::NEW_BUFFER_RECORD_OR_EOF:
140 return "NEW_BUFFER_RECORD_OR_EOF";
141 case FDRState::Token::WALLCLOCK_RECORD:
142 return "WALLCLOCK_RECORD";
143 case FDRState::Token::NEW_CPU_ID_RECORD:
144 return "NEW_CPU_ID_RECORD";
145 case FDRState::Token::FUNCTION_SEQUENCE:
146 return "FUNCTION_SEQUENCE";
147 case FDRState::Token::SCAN_TO_END_OF_THREAD_BUF:
148 return "SCAN_TO_END_OF_THREAD_BUF";
Dean Michael Berrisa7bbe442017-05-12 01:06:41 +0000149 case FDRState::Token::CUSTOM_EVENT_DATA:
150 return "CUSTOM_EVENT_DATA";
Dean Michael Berris60c24872017-03-29 06:10:12 +0000151 }
152 return "UNKNOWN";
153}
154
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000155/// State transition when a NewBufferRecord is encountered.
156Error processFDRNewBufferRecord(FDRState &State, uint8_t RecordFirstByte,
157 DataExtractor &RecordExtractor) {
158
Dean Michael Berris60c24872017-03-29 06:10:12 +0000159 if (State.Expects != FDRState::Token::NEW_BUFFER_RECORD_OR_EOF)
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000160 return make_error<StringError>(
161 "Malformed log. Read New Buffer record kind out of sequence",
162 std::make_error_code(std::errc::executable_format_error));
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000163 uint32_t OffsetPtr = 1; // 1 byte into record.
164 State.ThreadId = RecordExtractor.getU16(&OffsetPtr);
165 State.Expects = FDRState::Token::WALLCLOCK_RECORD;
166 return Error::success();
167}
168
169/// State transition when an EndOfBufferRecord is encountered.
170Error processFDREndOfBufferRecord(FDRState &State, uint8_t RecordFirstByte,
171 DataExtractor &RecordExtractor) {
Dean Michael Berris60c24872017-03-29 06:10:12 +0000172 if (State.Expects == FDRState::Token::NEW_BUFFER_RECORD_OR_EOF)
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000173 return make_error<StringError>(
174 "Malformed log. Received EOB message without current buffer.",
175 std::make_error_code(std::errc::executable_format_error));
Dean Michael Berris60c24872017-03-29 06:10:12 +0000176 State.Expects = FDRState::Token::SCAN_TO_END_OF_THREAD_BUF;
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000177 return Error::success();
178}
179
180/// State transition when a NewCPUIdRecord is encountered.
181Error processFDRNewCPUIdRecord(FDRState &State, uint8_t RecordFirstByte,
182 DataExtractor &RecordExtractor) {
183 if (State.Expects != FDRState::Token::FUNCTION_SEQUENCE &&
Dean Michael Berris60c24872017-03-29 06:10:12 +0000184 State.Expects != FDRState::Token::NEW_CPU_ID_RECORD)
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000185 return make_error<StringError>(
186 "Malformed log. Read NewCPUId record kind out of sequence",
187 std::make_error_code(std::errc::executable_format_error));
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000188 uint32_t OffsetPtr = 1; // Read starting after the first byte.
189 State.CPUId = RecordExtractor.getU16(&OffsetPtr);
190 State.BaseTSC = RecordExtractor.getU64(&OffsetPtr);
191 State.Expects = FDRState::Token::FUNCTION_SEQUENCE;
192 return Error::success();
193}
194
195/// State transition when a TSCWrapRecord (overflow detection) is encountered.
196Error processFDRTSCWrapRecord(FDRState &State, uint8_t RecordFirstByte,
197 DataExtractor &RecordExtractor) {
Dean Michael Berris60c24872017-03-29 06:10:12 +0000198 if (State.Expects != FDRState::Token::FUNCTION_SEQUENCE)
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000199 return make_error<StringError>(
200 "Malformed log. Read TSCWrap record kind out of sequence",
201 std::make_error_code(std::errc::executable_format_error));
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000202 uint32_t OffsetPtr = 1; // Read starting after the first byte.
203 State.BaseTSC = RecordExtractor.getU64(&OffsetPtr);
204 return Error::success();
205}
206
207/// State transition when a WallTimeMarkerRecord is encountered.
208Error processFDRWallTimeRecord(FDRState &State, uint8_t RecordFirstByte,
209 DataExtractor &RecordExtractor) {
Dean Michael Berris60c24872017-03-29 06:10:12 +0000210 if (State.Expects != FDRState::Token::WALLCLOCK_RECORD)
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000211 return make_error<StringError>(
212 "Malformed log. Read Wallclock record kind out of sequence",
213 std::make_error_code(std::errc::executable_format_error));
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000214 // We don't encode the wall time into any of the records.
215 // XRayRecords are concerned with the TSC instead.
216 State.Expects = FDRState::Token::NEW_CPU_ID_RECORD;
217 return Error::success();
218}
219
Dean Michael Berrisa7bbe442017-05-12 01:06:41 +0000220/// State transition when a CustomEventMarker is encountered.
221Error processCustomEventMarker(FDRState &State, uint8_t RecordFirstByte,
222 DataExtractor &RecordExtractor,
223 size_t &RecordSize) {
224 // We can encounter a CustomEventMarker anywhere in the log, so we can handle
Keith Wyss3d0bc9e2017-08-02 21:47:27 +0000225 // it regardless of the expectation. However, we do set the expectation to
226 // read a set number of fixed bytes, as described in the metadata.
Dean Michael Berrisa7bbe442017-05-12 01:06:41 +0000227 uint32_t OffsetPtr = 1; // Read after the first byte.
228 uint32_t DataSize = RecordExtractor.getU32(&OffsetPtr);
229 uint64_t TSC = RecordExtractor.getU64(&OffsetPtr);
230
231 // FIXME: Actually represent the record through the API. For now we only skip
232 // through the data.
233 (void)TSC;
234 RecordSize = 16 + DataSize;
235 return Error::success();
236}
237
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000238/// Advances the state machine for reading the FDR record type by reading one
Keith Wysse96152a2017-04-06 03:32:01 +0000239/// Metadata Record and updating the State appropriately based on the kind of
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000240/// record encountered. The RecordKind is encoded in the first byte of the
241/// Record, which the caller should pass in because they have already read it
242/// to determine that this is a metadata record as opposed to a function record.
243Error processFDRMetadataRecord(FDRState &State, uint8_t RecordFirstByte,
Dean Michael Berrisa7bbe442017-05-12 01:06:41 +0000244 DataExtractor &RecordExtractor,
245 size_t &RecordSize) {
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000246 // The remaining 7 bits are the RecordKind enum.
247 uint8_t RecordKind = RecordFirstByte >> 1;
248 switch (RecordKind) {
249 case 0: // NewBuffer
250 if (auto E =
251 processFDRNewBufferRecord(State, RecordFirstByte, RecordExtractor))
252 return E;
253 break;
254 case 1: // EndOfBuffer
255 if (auto E = processFDREndOfBufferRecord(State, RecordFirstByte,
256 RecordExtractor))
257 return E;
258 break;
259 case 2: // NewCPUId
260 if (auto E =
261 processFDRNewCPUIdRecord(State, RecordFirstByte, RecordExtractor))
262 return E;
263 break;
264 case 3: // TSCWrap
265 if (auto E =
266 processFDRTSCWrapRecord(State, RecordFirstByte, RecordExtractor))
267 return E;
268 break;
269 case 4: // WallTimeMarker
270 if (auto E =
271 processFDRWallTimeRecord(State, RecordFirstByte, RecordExtractor))
272 return E;
273 break;
Dean Michael Berrisa7bbe442017-05-12 01:06:41 +0000274 case 5: // CustomEventMarker
275 if (auto E = processCustomEventMarker(State, RecordFirstByte,
276 RecordExtractor, RecordSize))
277 return E;
278 break;
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000279 default:
280 // Widen the record type to uint16_t to prevent conversion to char.
281 return make_error<StringError>(
282 Twine("Illegal metadata record type: ")
283 .concat(Twine(static_cast<unsigned>(RecordKind))),
284 std::make_error_code(std::errc::executable_format_error));
285 }
286 return Error::success();
287}
288
289/// Reads a function record from an FDR format log, appending a new XRayRecord
290/// to the vector being populated and updating the State with a new value
291/// reference value to interpret TSC deltas.
292///
293/// The XRayRecord constructed includes information from the function record
294/// processed here as well as Thread ID and CPU ID formerly extracted into
295/// State.
296Error processFDRFunctionRecord(FDRState &State, uint8_t RecordFirstByte,
297 DataExtractor &RecordExtractor,
298 std::vector<XRayRecord> &Records) {
299 switch (State.Expects) {
300 case FDRState::Token::NEW_BUFFER_RECORD_OR_EOF:
301 return make_error<StringError>(
302 "Malformed log. Received Function Record before new buffer setup.",
303 std::make_error_code(std::errc::executable_format_error));
304 case FDRState::Token::WALLCLOCK_RECORD:
305 return make_error<StringError>(
306 "Malformed log. Received Function Record when expecting wallclock.",
307 std::make_error_code(std::errc::executable_format_error));
308 case FDRState::Token::NEW_CPU_ID_RECORD:
309 return make_error<StringError>(
310 "Malformed log. Received Function Record before first CPU record.",
311 std::make_error_code(std::errc::executable_format_error));
312 default:
313 Records.emplace_back();
314 auto &Record = Records.back();
315 Record.RecordType = 0; // Record is type NORMAL.
316 // Strip off record type bit and use the next three bits.
317 uint8_t RecordType = (RecordFirstByte >> 1) & 0x07;
318 switch (RecordType) {
319 case static_cast<uint8_t>(RecordTypes::ENTER):
320 Record.Type = RecordTypes::ENTER;
321 break;
322 case static_cast<uint8_t>(RecordTypes::EXIT):
323 case 2: // TAIL_EXIT is not yet defined in RecordTypes.
324 Record.Type = RecordTypes::EXIT;
325 break;
326 default:
327 // When initializing the error, convert to uint16_t so that the record
328 // type isn't interpreted as a char.
329 return make_error<StringError>(
330 Twine("Illegal function record type: ")
331 .concat(Twine(static_cast<unsigned>(RecordType))),
332 std::make_error_code(std::errc::executable_format_error));
333 }
334 Record.CPU = State.CPUId;
335 Record.TId = State.ThreadId;
Keith Wyss3d0bc9e2017-08-02 21:47:27 +0000336 // Back up to read first 32 bits, including the 4 we pulled RecordType
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000337 // and RecordKind out of. The remaining 28 are FunctionId.
338 uint32_t OffsetPtr = 0;
339 // Despite function Id being a signed int on XRayRecord,
340 // when it is written to an FDR format, the top bits are truncated,
341 // so it is effectively an unsigned value. When we shift off the
342 // top four bits, we want the shift to be logical, so we read as
343 // uint32_t.
344 uint32_t FuncIdBitField = RecordExtractor.getU32(&OffsetPtr);
345 Record.FuncId = FuncIdBitField >> 4;
346 // FunctionRecords have a 32 bit delta from the previous absolute TSC
347 // or TSC delta. If this would overflow, we should read a TSCWrap record
348 // with an absolute TSC reading.
349 uint64_t new_tsc = State.BaseTSC + RecordExtractor.getU32(&OffsetPtr);
350 State.BaseTSC = new_tsc;
351 Record.TSC = new_tsc;
352 }
353 return Error::success();
354}
355
356/// Reads a log in FDR mode for version 1 of this binary format. FDR mode is
357/// defined as part of the compiler-rt project in xray_fdr_logging.h, and such
358/// a log consists of the familiar 32 bit XRayHeader, followed by sequences of
359/// of interspersed 16 byte Metadata Records and 8 byte Function Records.
360///
361/// The following is an attempt to document the grammar of the format, which is
362/// parsed by this function for little-endian machines. Since the format makes
363/// use of BitFields, when we support big-Endian architectures, we will need to
Simon Pilgrim68168d12017-03-30 12:59:53 +0000364/// adjust not only the endianness parameter to llvm's RecordExtractor, but also
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000365/// the bit twiddling logic, which is consistent with the little-endian
366/// convention that BitFields within a struct will first be packed into the
367/// least significant bits the address they belong to.
368///
369/// We expect a format complying with the grammar in the following pseudo-EBNF.
370///
371/// FDRLog: XRayFileHeader ThreadBuffer*
Keith Wyss3d0bc9e2017-08-02 21:47:27 +0000372/// XRayFileHeader: 32 bytes to identify the log as FDR with machine metadata.
373/// Includes BufferSize
374/// ThreadBuffer: NewBuffer WallClockTime NewCPUId FunctionSequence EOB
Dean Michael Berris60c24872017-03-29 06:10:12 +0000375/// BufSize: 8 byte unsigned integer indicating how large the buffer is.
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000376/// NewBuffer: 16 byte metadata record with Thread Id.
377/// WallClockTime: 16 byte metadata record with human readable time.
378/// NewCPUId: 16 byte metadata record with CPUId and a 64 bit TSC reading.
Dean Michael Berris60c24872017-03-29 06:10:12 +0000379/// EOB: 16 byte record in a thread buffer plus mem garbage to fill BufSize.
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000380/// FunctionSequence: NewCPUId | TSCWrap | FunctionRecord
381/// TSCWrap: 16 byte metadata record with a full 64 bit TSC reading.
382/// FunctionRecord: 8 byte record with FunctionId, entry/exit, and TSC delta.
383Error loadFDRLog(StringRef Data, XRayFileHeader &FileHeader,
384 std::vector<XRayRecord> &Records) {
385 if (Data.size() < 32)
386 return make_error<StringError>(
387 "Not enough bytes for an XRay log.",
388 std::make_error_code(std::errc::invalid_argument));
389
390 // For an FDR log, there are records sized 16 and 8 bytes.
Dean Michael Berris60c24872017-03-29 06:10:12 +0000391 // There actually may be no records if no non-trivial functions are
392 // instrumented.
393 if (Data.size() % 8 != 0)
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000394 return make_error<StringError>(
395 "Invalid-sized XRay data.",
396 std::make_error_code(std::errc::invalid_argument));
397
398 if (auto E = readBinaryFormatHeader(Data, FileHeader))
399 return E;
400
Dean Michael Berris60c24872017-03-29 06:10:12 +0000401 uint64_t BufferSize = 0;
402 {
403 StringRef ExtraDataRef(FileHeader.FreeFormData, 16);
404 DataExtractor ExtraDataExtractor(ExtraDataRef, true, 8);
405 uint32_t ExtraDataOffset = 0;
406 BufferSize = ExtraDataExtractor.getU64(&ExtraDataOffset);
407 }
408 FDRState State{0, 0, 0, FDRState::Token::NEW_BUFFER_RECORD_OR_EOF,
409 BufferSize, 0};
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000410 // RecordSize will tell the loop how far to seek ahead based on the record
411 // type that we have just read.
412 size_t RecordSize = 0;
413 for (auto S = Data.drop_front(32); !S.empty(); S = S.drop_front(RecordSize)) {
414 DataExtractor RecordExtractor(S, true, 8);
415 uint32_t OffsetPtr = 0;
Dean Michael Berris60c24872017-03-29 06:10:12 +0000416 if (State.Expects == FDRState::Token::SCAN_TO_END_OF_THREAD_BUF) {
417 RecordSize = State.CurrentBufferSize - State.CurrentBufferConsumed;
418 if (S.size() < State.CurrentBufferSize - State.CurrentBufferConsumed) {
419 return make_error<StringError>(
420 Twine("Incomplete thread buffer. Expected ") +
421 Twine(State.CurrentBufferSize - State.CurrentBufferConsumed) +
422 " remaining bytes but found " + Twine(S.size()),
423 make_error_code(std::errc::invalid_argument));
424 }
425 State.CurrentBufferConsumed = 0;
426 State.Expects = FDRState::Token::NEW_BUFFER_RECORD_OR_EOF;
427 continue;
428 }
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000429 uint8_t BitField = RecordExtractor.getU8(&OffsetPtr);
430 bool isMetadataRecord = BitField & 0x01uL;
431 if (isMetadataRecord) {
432 RecordSize = 16;
Dean Michael Berrisa7bbe442017-05-12 01:06:41 +0000433 if (auto E = processFDRMetadataRecord(State, BitField, RecordExtractor,
434 RecordSize))
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000435 return E;
Dean Michael Berris60c24872017-03-29 06:10:12 +0000436 State.CurrentBufferConsumed += RecordSize;
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000437 } else { // Process Function Record
438 RecordSize = 8;
439 if (auto E = processFDRFunctionRecord(State, BitField, RecordExtractor,
440 Records))
441 return E;
Dean Michael Berris60c24872017-03-29 06:10:12 +0000442 State.CurrentBufferConsumed += RecordSize;
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000443 }
444 }
Dean Michael Berris60c24872017-03-29 06:10:12 +0000445 // There are two conditions
446 if (State.Expects != FDRState::Token::NEW_BUFFER_RECORD_OR_EOF &&
447 !(State.Expects == FDRState::Token::SCAN_TO_END_OF_THREAD_BUF &&
448 State.CurrentBufferSize == State.CurrentBufferConsumed))
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000449 return make_error<StringError>(
Dean Michael Berris60c24872017-03-29 06:10:12 +0000450 Twine("Encountered EOF with unexpected state expectation ") +
451 fdrStateToTwine(State.Expects) +
452 ". Remaining expected bytes in thread buffer total " +
453 Twine(State.CurrentBufferSize - State.CurrentBufferConsumed),
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000454 std::make_error_code(std::errc::executable_format_error));
455
456 return Error::success();
457}
458
459Error loadYAMLLog(StringRef Data, XRayFileHeader &FileHeader,
460 std::vector<XRayRecord> &Records) {
Dean Michael Berrisf8f909f2017-01-10 02:38:11 +0000461 // Load the documents from the MappedFile.
462 YAMLXRayTrace Trace;
463 Input In(Data);
464 In >> Trace;
465 if (In.error())
466 return make_error<StringError>("Failed loading YAML Data.", In.error());
467
468 FileHeader.Version = Trace.Header.Version;
469 FileHeader.Type = Trace.Header.Type;
470 FileHeader.ConstantTSC = Trace.Header.ConstantTSC;
471 FileHeader.NonstopTSC = Trace.Header.NonstopTSC;
472 FileHeader.CycleFrequency = Trace.Header.CycleFrequency;
473
474 if (FileHeader.Version != 1)
475 return make_error<StringError>(
476 Twine("Unsupported XRay file version: ") + Twine(FileHeader.Version),
477 std::make_error_code(std::errc::invalid_argument));
478
479 Records.clear();
480 std::transform(Trace.Records.begin(), Trace.Records.end(),
481 std::back_inserter(Records), [&](const YAMLXRayRecord &R) {
482 return XRayRecord{R.RecordType, R.CPU, R.Type,
483 R.FuncId, R.TSC, R.TId};
484 });
485 return Error::success();
486}
Dean Michael Berrisd6c18652017-01-11 06:39:09 +0000487
488Expected<Trace> llvm::xray::loadTraceFile(StringRef Filename, bool Sort) {
489 int Fd;
490 if (auto EC = sys::fs::openFileForRead(Filename, Fd)) {
491 return make_error<StringError>(
492 Twine("Cannot read log from '") + Filename + "'", EC);
493 }
494
495 // Attempt to get the filesize.
496 uint64_t FileSize;
497 if (auto EC = sys::fs::file_size(Filename, FileSize)) {
498 return make_error<StringError>(
499 Twine("Cannot read log from '") + Filename + "'", EC);
500 }
501 if (FileSize < 4) {
502 return make_error<StringError>(
503 Twine("File '") + Filename + "' too small for XRay.",
Hans Wennborg84da6612017-01-12 18:33:14 +0000504 std::make_error_code(std::errc::executable_format_error));
Dean Michael Berrisd6c18652017-01-11 06:39:09 +0000505 }
506
507 // Attempt to mmap the file.
508 std::error_code EC;
509 sys::fs::mapped_file_region MappedFile(
510 Fd, sys::fs::mapped_file_region::mapmode::readonly, FileSize, 0, EC);
511 if (EC) {
512 return make_error<StringError>(
513 Twine("Cannot read log from '") + Filename + "'", EC);
514 }
515
516 // Attempt to detect the file type using file magic. We have a slight bias
517 // towards the binary format, and we do this by making sure that the first 4
518 // bytes of the binary file is some combination of the following byte
519 // patterns:
520 //
521 // 0x0001 0x0000 - version 1, "naive" format
522 // 0x0001 0x0001 - version 1, "flight data recorder" format
523 //
524 // YAML files dont' typically have those first four bytes as valid text so we
525 // try loading assuming YAML if we don't find these bytes.
526 //
527 // Only if we can't load either the binary or the YAML format will we yield an
528 // error.
529 StringRef Magic(MappedFile.data(), 4);
530 DataExtractor HeaderExtractor(Magic, true, 8);
531 uint32_t OffsetPtr = 0;
532 uint16_t Version = HeaderExtractor.getU16(&OffsetPtr);
533 uint16_t Type = HeaderExtractor.getU16(&OffsetPtr);
534
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000535 enum BinaryFormatType { NAIVE_FORMAT = 0, FLIGHT_DATA_RECORDER_FORMAT = 1 };
536
Dean Michael Berrisd6c18652017-01-11 06:39:09 +0000537 Trace T;
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000538 if (Version == 1 && Type == NAIVE_FORMAT) {
539 if (auto E =
540 loadNaiveFormatLog(StringRef(MappedFile.data(), MappedFile.size()),
541 T.FileHeader, T.Records))
542 return std::move(E);
543 } else if (Version == 1 && Type == FLIGHT_DATA_RECORDER_FORMAT) {
544 if (auto E = loadFDRLog(StringRef(MappedFile.data(), MappedFile.size()),
545 T.FileHeader, T.Records))
Dean Michael Berrisd6c18652017-01-11 06:39:09 +0000546 return std::move(E);
547 } else {
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000548 if (auto E = loadYAMLLog(StringRef(MappedFile.data(), MappedFile.size()),
549 T.FileHeader, T.Records))
Dean Michael Berrisd6c18652017-01-11 06:39:09 +0000550 return std::move(E);
551 }
552
553 if (Sort)
554 std::sort(T.Records.begin(), T.Records.end(),
555 [&](const XRayRecord &L, const XRayRecord &R) {
556 return L.TSC < R.TSC;
557 });
558
559 return std::move(T);
560}