blob: 131c7807b1b5cb87a6ec50dc429afcf15c77c56b [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 Berris0f84a7d2017-09-18 06:08:46 +000051 if (FileHeader.Version != 1 && FileHeader.Version != 2)
Dean Michael Berrisf8f909f2017-01-10 02:38:11 +000052 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) {
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +000060 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;
Dean Michael Berris0f84a7d2017-09-18 06:08:46 +000097 case 2:
98 Record.Type = RecordTypes::TAIL_EXIT;
99 break;
Dean Michael Berrisf8f909f2017-01-10 02:38:11 +0000100 default:
101 return make_error<StringError>(
102 Twine("Unknown record type '") + Twine(int{Type}) + "'",
NAKAMURA Takumib09bec22017-01-11 01:06:57 +0000103 std::make_error_code(std::errc::executable_format_error));
Dean Michael Berrisf8f909f2017-01-10 02:38:11 +0000104 }
105 Record.FuncId = RecordExtractor.getSigned(&OffsetPtr, sizeof(int32_t));
106 Record.TSC = RecordExtractor.getU64(&OffsetPtr);
107 Record.TId = RecordExtractor.getU32(&OffsetPtr);
108 }
109 return Error::success();
110}
111
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000112/// When reading from a Flight Data Recorder mode log, metadata records are
113/// sparse compared to packed function records, so we must maintain state as we
114/// read through the sequence of entries. This allows the reader to denormalize
115/// the CPUId and Thread Id onto each Function Record and transform delta
116/// encoded TSC values into absolute encodings on each record.
117struct FDRState {
118 uint16_t CPUId;
119 uint16_t ThreadId;
120 uint64_t BaseTSC;
Dean Michael Berrisa7bbe442017-05-12 01:06:41 +0000121
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000122 /// Encode some of the state transitions for the FDR log reader as explicit
123 /// checks. These are expectations for the next Record in the stream.
124 enum class Token {
125 NEW_BUFFER_RECORD_OR_EOF,
126 WALLCLOCK_RECORD,
127 NEW_CPU_ID_RECORD,
Dean Michael Berris60c24872017-03-29 06:10:12 +0000128 FUNCTION_SEQUENCE,
129 SCAN_TO_END_OF_THREAD_BUF,
Dean Michael Berrisa7bbe442017-05-12 01:06:41 +0000130 CUSTOM_EVENT_DATA,
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000131 };
132 Token Expects;
Dean Michael Berrisa7bbe442017-05-12 01:06:41 +0000133
Dean Michael Berris60c24872017-03-29 06:10:12 +0000134 // Each threads buffer may have trailing garbage to scan over, so we track our
135 // progress.
136 uint64_t CurrentBufferSize;
137 uint64_t CurrentBufferConsumed;
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000138};
Dean Michael Berrisf8f909f2017-01-10 02:38:11 +0000139
Benjamin Kramer49a49fe2017-08-20 13:03:48 +0000140const char *fdrStateToTwine(const FDRState::Token &state) {
Dean Michael Berris60c24872017-03-29 06:10:12 +0000141 switch (state) {
142 case FDRState::Token::NEW_BUFFER_RECORD_OR_EOF:
143 return "NEW_BUFFER_RECORD_OR_EOF";
144 case FDRState::Token::WALLCLOCK_RECORD:
145 return "WALLCLOCK_RECORD";
146 case FDRState::Token::NEW_CPU_ID_RECORD:
147 return "NEW_CPU_ID_RECORD";
148 case FDRState::Token::FUNCTION_SEQUENCE:
149 return "FUNCTION_SEQUENCE";
150 case FDRState::Token::SCAN_TO_END_OF_THREAD_BUF:
151 return "SCAN_TO_END_OF_THREAD_BUF";
Dean Michael Berrisa7bbe442017-05-12 01:06:41 +0000152 case FDRState::Token::CUSTOM_EVENT_DATA:
153 return "CUSTOM_EVENT_DATA";
Dean Michael Berris60c24872017-03-29 06:10:12 +0000154 }
155 return "UNKNOWN";
156}
157
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000158/// State transition when a NewBufferRecord is encountered.
159Error processFDRNewBufferRecord(FDRState &State, uint8_t RecordFirstByte,
160 DataExtractor &RecordExtractor) {
161
Dean Michael Berris60c24872017-03-29 06:10:12 +0000162 if (State.Expects != FDRState::Token::NEW_BUFFER_RECORD_OR_EOF)
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000163 return make_error<StringError>(
164 "Malformed log. Read New Buffer record kind out of sequence",
165 std::make_error_code(std::errc::executable_format_error));
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000166 uint32_t OffsetPtr = 1; // 1 byte into record.
167 State.ThreadId = RecordExtractor.getU16(&OffsetPtr);
168 State.Expects = FDRState::Token::WALLCLOCK_RECORD;
169 return Error::success();
170}
171
172/// State transition when an EndOfBufferRecord is encountered.
173Error processFDREndOfBufferRecord(FDRState &State, uint8_t RecordFirstByte,
174 DataExtractor &RecordExtractor) {
Dean Michael Berris60c24872017-03-29 06:10:12 +0000175 if (State.Expects == FDRState::Token::NEW_BUFFER_RECORD_OR_EOF)
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000176 return make_error<StringError>(
177 "Malformed log. Received EOB message without current buffer.",
178 std::make_error_code(std::errc::executable_format_error));
Dean Michael Berris60c24872017-03-29 06:10:12 +0000179 State.Expects = FDRState::Token::SCAN_TO_END_OF_THREAD_BUF;
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000180 return Error::success();
181}
182
183/// State transition when a NewCPUIdRecord is encountered.
184Error processFDRNewCPUIdRecord(FDRState &State, uint8_t RecordFirstByte,
185 DataExtractor &RecordExtractor) {
186 if (State.Expects != FDRState::Token::FUNCTION_SEQUENCE &&
Dean Michael Berris60c24872017-03-29 06:10:12 +0000187 State.Expects != FDRState::Token::NEW_CPU_ID_RECORD)
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000188 return make_error<StringError>(
189 "Malformed log. Read NewCPUId record kind out of sequence",
190 std::make_error_code(std::errc::executable_format_error));
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000191 uint32_t OffsetPtr = 1; // Read starting after the first byte.
192 State.CPUId = RecordExtractor.getU16(&OffsetPtr);
193 State.BaseTSC = RecordExtractor.getU64(&OffsetPtr);
194 State.Expects = FDRState::Token::FUNCTION_SEQUENCE;
195 return Error::success();
196}
197
198/// State transition when a TSCWrapRecord (overflow detection) is encountered.
199Error processFDRTSCWrapRecord(FDRState &State, uint8_t RecordFirstByte,
200 DataExtractor &RecordExtractor) {
Dean Michael Berris60c24872017-03-29 06:10:12 +0000201 if (State.Expects != FDRState::Token::FUNCTION_SEQUENCE)
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000202 return make_error<StringError>(
203 "Malformed log. Read TSCWrap record kind out of sequence",
204 std::make_error_code(std::errc::executable_format_error));
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000205 uint32_t OffsetPtr = 1; // Read starting after the first byte.
206 State.BaseTSC = RecordExtractor.getU64(&OffsetPtr);
207 return Error::success();
208}
209
210/// State transition when a WallTimeMarkerRecord is encountered.
211Error processFDRWallTimeRecord(FDRState &State, uint8_t RecordFirstByte,
212 DataExtractor &RecordExtractor) {
Dean Michael Berris60c24872017-03-29 06:10:12 +0000213 if (State.Expects != FDRState::Token::WALLCLOCK_RECORD)
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000214 return make_error<StringError>(
215 "Malformed log. Read Wallclock record kind out of sequence",
216 std::make_error_code(std::errc::executable_format_error));
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000217 // We don't encode the wall time into any of the records.
218 // XRayRecords are concerned with the TSC instead.
219 State.Expects = FDRState::Token::NEW_CPU_ID_RECORD;
220 return Error::success();
221}
222
Dean Michael Berrisa7bbe442017-05-12 01:06:41 +0000223/// State transition when a CustomEventMarker is encountered.
224Error processCustomEventMarker(FDRState &State, uint8_t RecordFirstByte,
225 DataExtractor &RecordExtractor,
226 size_t &RecordSize) {
227 // We can encounter a CustomEventMarker anywhere in the log, so we can handle
Keith Wyss3d0bc9e2017-08-02 21:47:27 +0000228 // it regardless of the expectation. However, we do set the expectation to
229 // read a set number of fixed bytes, as described in the metadata.
Dean Michael Berrisa7bbe442017-05-12 01:06:41 +0000230 uint32_t OffsetPtr = 1; // Read after the first byte.
231 uint32_t DataSize = RecordExtractor.getU32(&OffsetPtr);
232 uint64_t TSC = RecordExtractor.getU64(&OffsetPtr);
233
234 // FIXME: Actually represent the record through the API. For now we only skip
235 // through the data.
236 (void)TSC;
237 RecordSize = 16 + DataSize;
238 return Error::success();
239}
240
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000241/// Advances the state machine for reading the FDR record type by reading one
Keith Wysse96152a2017-04-06 03:32:01 +0000242/// Metadata Record and updating the State appropriately based on the kind of
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000243/// record encountered. The RecordKind is encoded in the first byte of the
244/// Record, which the caller should pass in because they have already read it
245/// to determine that this is a metadata record as opposed to a function record.
246Error processFDRMetadataRecord(FDRState &State, uint8_t RecordFirstByte,
Dean Michael Berrisa7bbe442017-05-12 01:06:41 +0000247 DataExtractor &RecordExtractor,
248 size_t &RecordSize) {
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000249 // The remaining 7 bits are the RecordKind enum.
250 uint8_t RecordKind = RecordFirstByte >> 1;
251 switch (RecordKind) {
252 case 0: // NewBuffer
253 if (auto E =
254 processFDRNewBufferRecord(State, RecordFirstByte, RecordExtractor))
255 return E;
256 break;
257 case 1: // EndOfBuffer
258 if (auto E = processFDREndOfBufferRecord(State, RecordFirstByte,
259 RecordExtractor))
260 return E;
261 break;
262 case 2: // NewCPUId
263 if (auto E =
264 processFDRNewCPUIdRecord(State, RecordFirstByte, RecordExtractor))
265 return E;
266 break;
267 case 3: // TSCWrap
268 if (auto E =
269 processFDRTSCWrapRecord(State, RecordFirstByte, RecordExtractor))
270 return E;
271 break;
272 case 4: // WallTimeMarker
273 if (auto E =
274 processFDRWallTimeRecord(State, RecordFirstByte, RecordExtractor))
275 return E;
276 break;
Dean Michael Berrisa7bbe442017-05-12 01:06:41 +0000277 case 5: // CustomEventMarker
278 if (auto E = processCustomEventMarker(State, RecordFirstByte,
279 RecordExtractor, RecordSize))
280 return E;
281 break;
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000282 default:
283 // Widen the record type to uint16_t to prevent conversion to char.
284 return make_error<StringError>(
285 Twine("Illegal metadata record type: ")
286 .concat(Twine(static_cast<unsigned>(RecordKind))),
287 std::make_error_code(std::errc::executable_format_error));
288 }
289 return Error::success();
290}
291
292/// Reads a function record from an FDR format log, appending a new XRayRecord
293/// to the vector being populated and updating the State with a new value
294/// reference value to interpret TSC deltas.
295///
296/// The XRayRecord constructed includes information from the function record
297/// processed here as well as Thread ID and CPU ID formerly extracted into
298/// State.
299Error processFDRFunctionRecord(FDRState &State, uint8_t RecordFirstByte,
300 DataExtractor &RecordExtractor,
301 std::vector<XRayRecord> &Records) {
302 switch (State.Expects) {
303 case FDRState::Token::NEW_BUFFER_RECORD_OR_EOF:
304 return make_error<StringError>(
305 "Malformed log. Received Function Record before new buffer setup.",
306 std::make_error_code(std::errc::executable_format_error));
307 case FDRState::Token::WALLCLOCK_RECORD:
308 return make_error<StringError>(
309 "Malformed log. Received Function Record when expecting wallclock.",
310 std::make_error_code(std::errc::executable_format_error));
311 case FDRState::Token::NEW_CPU_ID_RECORD:
312 return make_error<StringError>(
313 "Malformed log. Received Function Record before first CPU record.",
314 std::make_error_code(std::errc::executable_format_error));
315 default:
316 Records.emplace_back();
317 auto &Record = Records.back();
318 Record.RecordType = 0; // Record is type NORMAL.
319 // Strip off record type bit and use the next three bits.
320 uint8_t RecordType = (RecordFirstByte >> 1) & 0x07;
321 switch (RecordType) {
322 case static_cast<uint8_t>(RecordTypes::ENTER):
323 Record.Type = RecordTypes::ENTER;
324 break;
325 case static_cast<uint8_t>(RecordTypes::EXIT):
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000326 Record.Type = RecordTypes::EXIT;
327 break;
Dean Michael Berris0f84a7d2017-09-18 06:08:46 +0000328 case static_cast<uint8_t>(RecordTypes::TAIL_EXIT):
329 Record.Type = RecordTypes::TAIL_EXIT;
330 break;
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000331 default:
Martin Pelikand78db152017-09-15 04:22:16 +0000332 // Cast to an unsigned integer to not interpret the record type as a char.
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000333 return make_error<StringError>(
334 Twine("Illegal function record type: ")
335 .concat(Twine(static_cast<unsigned>(RecordType))),
336 std::make_error_code(std::errc::executable_format_error));
337 }
338 Record.CPU = State.CPUId;
339 Record.TId = State.ThreadId;
Keith Wyss3d0bc9e2017-08-02 21:47:27 +0000340 // Back up to read first 32 bits, including the 4 we pulled RecordType
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000341 // and RecordKind out of. The remaining 28 are FunctionId.
342 uint32_t OffsetPtr = 0;
343 // Despite function Id being a signed int on XRayRecord,
344 // when it is written to an FDR format, the top bits are truncated,
345 // so it is effectively an unsigned value. When we shift off the
346 // top four bits, we want the shift to be logical, so we read as
347 // uint32_t.
348 uint32_t FuncIdBitField = RecordExtractor.getU32(&OffsetPtr);
349 Record.FuncId = FuncIdBitField >> 4;
350 // FunctionRecords have a 32 bit delta from the previous absolute TSC
351 // or TSC delta. If this would overflow, we should read a TSCWrap record
352 // with an absolute TSC reading.
Martin Pelikand78db152017-09-15 04:22:16 +0000353 uint64_t NewTSC = State.BaseTSC + RecordExtractor.getU32(&OffsetPtr);
354 State.BaseTSC = NewTSC;
355 Record.TSC = NewTSC;
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000356 }
357 return Error::success();
358}
359
360/// Reads a log in FDR mode for version 1 of this binary format. FDR mode is
361/// defined as part of the compiler-rt project in xray_fdr_logging.h, and such
362/// a log consists of the familiar 32 bit XRayHeader, followed by sequences of
363/// of interspersed 16 byte Metadata Records and 8 byte Function Records.
364///
365/// The following is an attempt to document the grammar of the format, which is
366/// parsed by this function for little-endian machines. Since the format makes
Martin Pelikand78db152017-09-15 04:22:16 +0000367/// use of BitFields, when we support big-endian architectures, we will need to
Simon Pilgrim68168d12017-03-30 12:59:53 +0000368/// adjust not only the endianness parameter to llvm's RecordExtractor, but also
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000369/// the bit twiddling logic, which is consistent with the little-endian
370/// convention that BitFields within a struct will first be packed into the
371/// least significant bits the address they belong to.
372///
373/// We expect a format complying with the grammar in the following pseudo-EBNF.
374///
375/// FDRLog: XRayFileHeader ThreadBuffer*
Keith Wyss3d0bc9e2017-08-02 21:47:27 +0000376/// XRayFileHeader: 32 bytes to identify the log as FDR with machine metadata.
377/// Includes BufferSize
378/// ThreadBuffer: NewBuffer WallClockTime NewCPUId FunctionSequence EOB
Dean Michael Berris60c24872017-03-29 06:10:12 +0000379/// BufSize: 8 byte unsigned integer indicating how large the buffer is.
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000380/// NewBuffer: 16 byte metadata record with Thread Id.
381/// WallClockTime: 16 byte metadata record with human readable time.
382/// NewCPUId: 16 byte metadata record with CPUId and a 64 bit TSC reading.
Dean Michael Berris60c24872017-03-29 06:10:12 +0000383/// EOB: 16 byte record in a thread buffer plus mem garbage to fill BufSize.
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000384/// FunctionSequence: NewCPUId | TSCWrap | FunctionRecord
385/// TSCWrap: 16 byte metadata record with a full 64 bit TSC reading.
386/// FunctionRecord: 8 byte record with FunctionId, entry/exit, and TSC delta.
387Error loadFDRLog(StringRef Data, XRayFileHeader &FileHeader,
388 std::vector<XRayRecord> &Records) {
389 if (Data.size() < 32)
390 return make_error<StringError>(
391 "Not enough bytes for an XRay log.",
392 std::make_error_code(std::errc::invalid_argument));
393
394 // For an FDR log, there are records sized 16 and 8 bytes.
Dean Michael Berris60c24872017-03-29 06:10:12 +0000395 // There actually may be no records if no non-trivial functions are
396 // instrumented.
397 if (Data.size() % 8 != 0)
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000398 return make_error<StringError>(
399 "Invalid-sized XRay data.",
400 std::make_error_code(std::errc::invalid_argument));
401
402 if (auto E = readBinaryFormatHeader(Data, FileHeader))
403 return E;
404
Dean Michael Berris60c24872017-03-29 06:10:12 +0000405 uint64_t BufferSize = 0;
406 {
407 StringRef ExtraDataRef(FileHeader.FreeFormData, 16);
408 DataExtractor ExtraDataExtractor(ExtraDataRef, true, 8);
409 uint32_t ExtraDataOffset = 0;
410 BufferSize = ExtraDataExtractor.getU64(&ExtraDataOffset);
411 }
412 FDRState State{0, 0, 0, FDRState::Token::NEW_BUFFER_RECORD_OR_EOF,
413 BufferSize, 0};
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000414 // RecordSize will tell the loop how far to seek ahead based on the record
415 // type that we have just read.
416 size_t RecordSize = 0;
417 for (auto S = Data.drop_front(32); !S.empty(); S = S.drop_front(RecordSize)) {
418 DataExtractor RecordExtractor(S, true, 8);
419 uint32_t OffsetPtr = 0;
Dean Michael Berris60c24872017-03-29 06:10:12 +0000420 if (State.Expects == FDRState::Token::SCAN_TO_END_OF_THREAD_BUF) {
421 RecordSize = State.CurrentBufferSize - State.CurrentBufferConsumed;
Martin Pelikand78db152017-09-15 04:22:16 +0000422 if (S.size() < RecordSize) {
Dean Michael Berris60c24872017-03-29 06:10:12 +0000423 return make_error<StringError>(
Martin Pelikand78db152017-09-15 04:22:16 +0000424 Twine("Incomplete thread buffer. Expected at least ") +
425 Twine(RecordSize) + " bytes but found " + Twine(S.size()),
Dean Michael Berris60c24872017-03-29 06:10:12 +0000426 make_error_code(std::errc::invalid_argument));
427 }
428 State.CurrentBufferConsumed = 0;
429 State.Expects = FDRState::Token::NEW_BUFFER_RECORD_OR_EOF;
430 continue;
431 }
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000432 uint8_t BitField = RecordExtractor.getU8(&OffsetPtr);
433 bool isMetadataRecord = BitField & 0x01uL;
434 if (isMetadataRecord) {
435 RecordSize = 16;
Dean Michael Berrisa7bbe442017-05-12 01:06:41 +0000436 if (auto E = processFDRMetadataRecord(State, BitField, RecordExtractor,
437 RecordSize))
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000438 return E;
439 } else { // Process Function Record
440 RecordSize = 8;
441 if (auto E = processFDRFunctionRecord(State, BitField, RecordExtractor,
442 Records))
443 return E;
444 }
Martin Pelikand78db152017-09-15 04:22:16 +0000445 State.CurrentBufferConsumed += RecordSize;
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000446 }
Martin Pelikand78db152017-09-15 04:22:16 +0000447
448 // Having iterated over everything we've been given, we've either consumed
449 // everything and ended up in the end state, or were told to skip the rest.
450 bool Finished = State.Expects == FDRState::Token::SCAN_TO_END_OF_THREAD_BUF &&
Dean Michael Berris0f84a7d2017-09-18 06:08:46 +0000451 State.CurrentBufferSize == State.CurrentBufferConsumed;
Martin Pelikand78db152017-09-15 04:22:16 +0000452 if (State.Expects != FDRState::Token::NEW_BUFFER_RECORD_OR_EOF && !Finished)
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000453 return make_error<StringError>(
Dean Michael Berris60c24872017-03-29 06:10:12 +0000454 Twine("Encountered EOF with unexpected state expectation ") +
455 fdrStateToTwine(State.Expects) +
456 ". Remaining expected bytes in thread buffer total " +
457 Twine(State.CurrentBufferSize - State.CurrentBufferConsumed),
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000458 std::make_error_code(std::errc::executable_format_error));
459
460 return Error::success();
461}
462
463Error loadYAMLLog(StringRef Data, XRayFileHeader &FileHeader,
464 std::vector<XRayRecord> &Records) {
Dean Michael Berrisf8f909f2017-01-10 02:38:11 +0000465 YAMLXRayTrace Trace;
466 Input In(Data);
467 In >> Trace;
468 if (In.error())
469 return make_error<StringError>("Failed loading YAML Data.", In.error());
470
471 FileHeader.Version = Trace.Header.Version;
472 FileHeader.Type = Trace.Header.Type;
473 FileHeader.ConstantTSC = Trace.Header.ConstantTSC;
474 FileHeader.NonstopTSC = Trace.Header.NonstopTSC;
475 FileHeader.CycleFrequency = Trace.Header.CycleFrequency;
476
477 if (FileHeader.Version != 1)
478 return make_error<StringError>(
479 Twine("Unsupported XRay file version: ") + Twine(FileHeader.Version),
480 std::make_error_code(std::errc::invalid_argument));
481
482 Records.clear();
483 std::transform(Trace.Records.begin(), Trace.Records.end(),
484 std::back_inserter(Records), [&](const YAMLXRayRecord &R) {
485 return XRayRecord{R.RecordType, R.CPU, R.Type,
486 R.FuncId, R.TSC, R.TId};
487 });
488 return Error::success();
489}
Benjamin Kramer49a49fe2017-08-20 13:03:48 +0000490} // namespace
Dean Michael Berrisd6c18652017-01-11 06:39:09 +0000491
492Expected<Trace> llvm::xray::loadTraceFile(StringRef Filename, bool Sort) {
493 int Fd;
494 if (auto EC = sys::fs::openFileForRead(Filename, Fd)) {
495 return make_error<StringError>(
496 Twine("Cannot read log from '") + Filename + "'", EC);
497 }
498
Dean Michael Berrisd6c18652017-01-11 06:39:09 +0000499 uint64_t FileSize;
500 if (auto EC = sys::fs::file_size(Filename, FileSize)) {
501 return make_error<StringError>(
502 Twine("Cannot read log from '") + Filename + "'", EC);
503 }
504 if (FileSize < 4) {
505 return make_error<StringError>(
506 Twine("File '") + Filename + "' too small for XRay.",
Hans Wennborg84da6612017-01-12 18:33:14 +0000507 std::make_error_code(std::errc::executable_format_error));
Dean Michael Berrisd6c18652017-01-11 06:39:09 +0000508 }
509
Martin Pelikand78db152017-09-15 04:22:16 +0000510 // Map the opened file into memory and use a StringRef to access it later.
Dean Michael Berrisd6c18652017-01-11 06:39:09 +0000511 std::error_code EC;
512 sys::fs::mapped_file_region MappedFile(
513 Fd, sys::fs::mapped_file_region::mapmode::readonly, FileSize, 0, EC);
514 if (EC) {
515 return make_error<StringError>(
516 Twine("Cannot read log from '") + Filename + "'", EC);
517 }
Martin Pelikand78db152017-09-15 04:22:16 +0000518 auto Data = StringRef(MappedFile.data(), MappedFile.size());
Dean Michael Berrisd6c18652017-01-11 06:39:09 +0000519
520 // Attempt to detect the file type using file magic. We have a slight bias
521 // towards the binary format, and we do this by making sure that the first 4
522 // bytes of the binary file is some combination of the following byte
Martin Pelikand78db152017-09-15 04:22:16 +0000523 // patterns: (observe the code loading them assumes they're little endian)
Dean Michael Berrisd6c18652017-01-11 06:39:09 +0000524 //
Martin Pelikand78db152017-09-15 04:22:16 +0000525 // 0x01 0x00 0x00 0x00 - version 1, "naive" format
526 // 0x01 0x00 0x01 0x00 - version 1, "flight data recorder" format
Dean Michael Berrisd6c18652017-01-11 06:39:09 +0000527 //
Martin Pelikand78db152017-09-15 04:22:16 +0000528 // YAML files don't typically have those first four bytes as valid text so we
Dean Michael Berrisd6c18652017-01-11 06:39:09 +0000529 // try loading assuming YAML if we don't find these bytes.
530 //
531 // Only if we can't load either the binary or the YAML format will we yield an
532 // error.
533 StringRef Magic(MappedFile.data(), 4);
534 DataExtractor HeaderExtractor(Magic, true, 8);
535 uint32_t OffsetPtr = 0;
536 uint16_t Version = HeaderExtractor.getU16(&OffsetPtr);
537 uint16_t Type = HeaderExtractor.getU16(&OffsetPtr);
538
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000539 enum BinaryFormatType { NAIVE_FORMAT = 0, FLIGHT_DATA_RECORDER_FORMAT = 1 };
540
Dean Michael Berrisd6c18652017-01-11 06:39:09 +0000541 Trace T;
Dean Michael Berris0f84a7d2017-09-18 06:08:46 +0000542 if (Type == NAIVE_FORMAT && (Version == 1 || Version == 2)) {
543 if (auto E = loadNaiveFormatLog(Data, T.FileHeader, T.Records))
Dean Michael Berris4f83c4d2017-02-17 01:47:16 +0000544 return std::move(E);
545 } else if (Version == 1 && Type == FLIGHT_DATA_RECORDER_FORMAT) {
Martin Pelikand78db152017-09-15 04:22:16 +0000546 if (auto E = loadFDRLog(Data, T.FileHeader, T.Records))
Dean Michael Berrisd6c18652017-01-11 06:39:09 +0000547 return std::move(E);
548 } else {
Martin Pelikand78db152017-09-15 04:22:16 +0000549 if (auto E = loadYAMLLog(Data, 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}