1 //===- Trace.cpp - XRay Trace Loading implementation. ---------------------===// 2 // 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 //===----------------------------------------------------------------------===// 13 #include "llvm/XRay/Trace.h" 14 #include "llvm/ADT/STLExtras.h" 15 #include "llvm/Support/DataExtractor.h" 16 #include "llvm/Support/Error.h" 17 #include "llvm/Support/FileSystem.h" 18 #include "llvm/XRay/YAMLXRayRecord.h" 19 20 using namespace llvm; 21 using namespace llvm::xray; 22 using llvm::yaml::Input; 23 24 using XRayRecordStorage = 25 std::aligned_storage<sizeof(XRayRecord), alignof(XRayRecord)>::type; 26 27 // Populates the FileHeader reference by reading the first 32 bytes of the file. 28 Error readBinaryFormatHeader(StringRef Data, XRayFileHeader &FileHeader) { 29 // 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 40 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); 49 50 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)); 54 return Error::success(); 55 } 56 57 Error 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; 72 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}) + "'", 100 std::make_error_code(std::errc::executable_format_error)); 101 } 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 109 /// 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. 114 struct FDRState { 115 uint16_t CPUId; 116 uint16_t ThreadId; 117 uint64_t BaseTSC; 118 /// Encode some of the state transitions for the FDR log reader as explicit 119 /// checks. These are expectations for the next Record in the stream. 120 enum class Token { 121 NEW_BUFFER_RECORD_OR_EOF, 122 WALLCLOCK_RECORD, 123 NEW_CPU_ID_RECORD, 124 FUNCTION_SEQUENCE 125 }; 126 Token Expects; 127 }; 128 129 /// State transition when a NewBufferRecord is encountered. 130 Error processFDRNewBufferRecord(FDRState &State, uint8_t RecordFirstByte, 131 DataExtractor &RecordExtractor) { 132 133 if (State.Expects != FDRState::Token::NEW_BUFFER_RECORD_OR_EOF) { 134 return make_error<StringError>( 135 "Malformed log. Read New Buffer record kind out of sequence", 136 std::make_error_code(std::errc::executable_format_error)); 137 } 138 uint32_t OffsetPtr = 1; // 1 byte into record. 139 State.ThreadId = RecordExtractor.getU16(&OffsetPtr); 140 State.Expects = FDRState::Token::WALLCLOCK_RECORD; 141 return Error::success(); 142 } 143 144 /// State transition when an EndOfBufferRecord is encountered. 145 Error processFDREndOfBufferRecord(FDRState &State, uint8_t RecordFirstByte, 146 DataExtractor &RecordExtractor) { 147 if (State.Expects == FDRState::Token::NEW_BUFFER_RECORD_OR_EOF) { 148 return make_error<StringError>( 149 "Malformed log. Received EOB message without current buffer.", 150 std::make_error_code(std::errc::executable_format_error)); 151 } 152 State.Expects = FDRState::Token::NEW_BUFFER_RECORD_OR_EOF; 153 return Error::success(); 154 } 155 156 /// State transition when a NewCPUIdRecord is encountered. 157 Error processFDRNewCPUIdRecord(FDRState &State, uint8_t RecordFirstByte, 158 DataExtractor &RecordExtractor) { 159 if (State.Expects != FDRState::Token::FUNCTION_SEQUENCE && 160 State.Expects != FDRState::Token::NEW_CPU_ID_RECORD) { 161 return make_error<StringError>( 162 "Malformed log. Read NewCPUId record kind out of sequence", 163 std::make_error_code(std::errc::executable_format_error)); 164 } 165 uint32_t OffsetPtr = 1; // Read starting after the first byte. 166 State.CPUId = RecordExtractor.getU16(&OffsetPtr); 167 State.BaseTSC = RecordExtractor.getU64(&OffsetPtr); 168 State.Expects = FDRState::Token::FUNCTION_SEQUENCE; 169 return Error::success(); 170 } 171 172 /// State transition when a TSCWrapRecord (overflow detection) is encountered. 173 Error processFDRTSCWrapRecord(FDRState &State, uint8_t RecordFirstByte, 174 DataExtractor &RecordExtractor) { 175 if (State.Expects != FDRState::Token::FUNCTION_SEQUENCE) { 176 return make_error<StringError>( 177 "Malformed log. Read TSCWrap record kind out of sequence", 178 std::make_error_code(std::errc::executable_format_error)); 179 } 180 uint32_t OffsetPtr = 1; // Read starting after the first byte. 181 State.BaseTSC = RecordExtractor.getU64(&OffsetPtr); 182 return Error::success(); 183 } 184 185 /// State transition when a WallTimeMarkerRecord is encountered. 186 Error processFDRWallTimeRecord(FDRState &State, uint8_t RecordFirstByte, 187 DataExtractor &RecordExtractor) { 188 if (State.Expects != FDRState::Token::WALLCLOCK_RECORD) { 189 return make_error<StringError>( 190 "Malformed log. Read Wallclock record kind out of sequence", 191 std::make_error_code(std::errc::executable_format_error)); 192 } 193 // We don't encode the wall time into any of the records. 194 // XRayRecords are concerned with the TSC instead. 195 State.Expects = FDRState::Token::NEW_CPU_ID_RECORD; 196 return Error::success(); 197 } 198 199 /// Advances the state machine for reading the FDR record type by reading one 200 /// Metadata Record and updating the State approriately based on the kind of 201 /// record encountered. The RecordKind is encoded in the first byte of the 202 /// Record, which the caller should pass in because they have already read it 203 /// to determine that this is a metadata record as opposed to a function record. 204 Error processFDRMetadataRecord(FDRState &State, uint8_t RecordFirstByte, 205 DataExtractor &RecordExtractor) { 206 // The remaining 7 bits are the RecordKind enum. 207 uint8_t RecordKind = RecordFirstByte >> 1; 208 switch (RecordKind) { 209 case 0: // NewBuffer 210 if (auto E = 211 processFDRNewBufferRecord(State, RecordFirstByte, RecordExtractor)) 212 return E; 213 break; 214 case 1: // EndOfBuffer 215 if (auto E = processFDREndOfBufferRecord(State, RecordFirstByte, 216 RecordExtractor)) 217 return E; 218 break; 219 case 2: // NewCPUId 220 if (auto E = 221 processFDRNewCPUIdRecord(State, RecordFirstByte, RecordExtractor)) 222 return E; 223 break; 224 case 3: // TSCWrap 225 if (auto E = 226 processFDRTSCWrapRecord(State, RecordFirstByte, RecordExtractor)) 227 return E; 228 break; 229 case 4: // WallTimeMarker 230 if (auto E = 231 processFDRWallTimeRecord(State, RecordFirstByte, RecordExtractor)) 232 return E; 233 break; 234 default: 235 // Widen the record type to uint16_t to prevent conversion to char. 236 return make_error<StringError>( 237 Twine("Illegal metadata record type: ") 238 .concat(Twine(static_cast<unsigned>(RecordKind))), 239 std::make_error_code(std::errc::executable_format_error)); 240 } 241 return Error::success(); 242 } 243 244 /// Reads a function record from an FDR format log, appending a new XRayRecord 245 /// to the vector being populated and updating the State with a new value 246 /// reference value to interpret TSC deltas. 247 /// 248 /// The XRayRecord constructed includes information from the function record 249 /// processed here as well as Thread ID and CPU ID formerly extracted into 250 /// State. 251 Error processFDRFunctionRecord(FDRState &State, uint8_t RecordFirstByte, 252 DataExtractor &RecordExtractor, 253 std::vector<XRayRecord> &Records) { 254 switch (State.Expects) { 255 case FDRState::Token::NEW_BUFFER_RECORD_OR_EOF: 256 return make_error<StringError>( 257 "Malformed log. Received Function Record before new buffer setup.", 258 std::make_error_code(std::errc::executable_format_error)); 259 case FDRState::Token::WALLCLOCK_RECORD: 260 return make_error<StringError>( 261 "Malformed log. Received Function Record when expecting wallclock.", 262 std::make_error_code(std::errc::executable_format_error)); 263 case FDRState::Token::NEW_CPU_ID_RECORD: 264 return make_error<StringError>( 265 "Malformed log. Received Function Record before first CPU record.", 266 std::make_error_code(std::errc::executable_format_error)); 267 default: 268 Records.emplace_back(); 269 auto &Record = Records.back(); 270 Record.RecordType = 0; // Record is type NORMAL. 271 // Strip off record type bit and use the next three bits. 272 uint8_t RecordType = (RecordFirstByte >> 1) & 0x07; 273 switch (RecordType) { 274 case static_cast<uint8_t>(RecordTypes::ENTER): 275 Record.Type = RecordTypes::ENTER; 276 break; 277 case static_cast<uint8_t>(RecordTypes::EXIT): 278 case 2: // TAIL_EXIT is not yet defined in RecordTypes. 279 Record.Type = RecordTypes::EXIT; 280 break; 281 default: 282 // When initializing the error, convert to uint16_t so that the record 283 // type isn't interpreted as a char. 284 return make_error<StringError>( 285 Twine("Illegal function record type: ") 286 .concat(Twine(static_cast<unsigned>(RecordType))), 287 std::make_error_code(std::errc::executable_format_error)); 288 } 289 Record.CPU = State.CPUId; 290 Record.TId = State.ThreadId; 291 // Back up to read first 32 bits, including the 8 we pulled RecordType 292 // and RecordKind out of. The remaining 28 are FunctionId. 293 uint32_t OffsetPtr = 0; 294 // Despite function Id being a signed int on XRayRecord, 295 // when it is written to an FDR format, the top bits are truncated, 296 // so it is effectively an unsigned value. When we shift off the 297 // top four bits, we want the shift to be logical, so we read as 298 // uint32_t. 299 uint32_t FuncIdBitField = RecordExtractor.getU32(&OffsetPtr); 300 Record.FuncId = FuncIdBitField >> 4; 301 // FunctionRecords have a 32 bit delta from the previous absolute TSC 302 // or TSC delta. If this would overflow, we should read a TSCWrap record 303 // with an absolute TSC reading. 304 uint64_t new_tsc = State.BaseTSC + RecordExtractor.getU32(&OffsetPtr); 305 State.BaseTSC = new_tsc; 306 Record.TSC = new_tsc; 307 } 308 return Error::success(); 309 } 310 311 /// Reads a log in FDR mode for version 1 of this binary format. FDR mode is 312 /// defined as part of the compiler-rt project in xray_fdr_logging.h, and such 313 /// a log consists of the familiar 32 bit XRayHeader, followed by sequences of 314 /// of interspersed 16 byte Metadata Records and 8 byte Function Records. 315 /// 316 /// The following is an attempt to document the grammar of the format, which is 317 /// parsed by this function for little-endian machines. Since the format makes 318 /// use of BitFields, when we support big-Endian architectures, we will need to 319 /// adjust not only the endianess parameter to llvm's RecordExtractor, but also 320 /// the bit twiddling logic, which is consistent with the little-endian 321 /// convention that BitFields within a struct will first be packed into the 322 /// least significant bits the address they belong to. 323 /// 324 /// We expect a format complying with the grammar in the following pseudo-EBNF. 325 /// 326 /// FDRLog: XRayFileHeader ThreadBuffer* 327 /// XRayFileHeader: 32 bits to identify the log as FDR with machine metadata. 328 /// ThreadBuffer: NewBuffer WallClockTime NewCPUId FunctionSequence EOB 329 /// NewBuffer: 16 byte metadata record with Thread Id. 330 /// WallClockTime: 16 byte metadata record with human readable time. 331 /// NewCPUId: 16 byte metadata record with CPUId and a 64 bit TSC reading. 332 /// EOB: 16 byte metadata record marking the end of a thread's sequence. 333 /// FunctionSequence: NewCPUId | TSCWrap | FunctionRecord 334 /// TSCWrap: 16 byte metadata record with a full 64 bit TSC reading. 335 /// FunctionRecord: 8 byte record with FunctionId, entry/exit, and TSC delta. 336 Error loadFDRLog(StringRef Data, XRayFileHeader &FileHeader, 337 std::vector<XRayRecord> &Records) { 338 if (Data.size() < 32) 339 return make_error<StringError>( 340 "Not enough bytes for an XRay log.", 341 std::make_error_code(std::errc::invalid_argument)); 342 343 // For an FDR log, there are records sized 16 and 8 bytes. 344 if (Data.size() - 32 == 0 || Data.size() % 8 != 0) 345 return make_error<StringError>( 346 "Invalid-sized XRay data.", 347 std::make_error_code(std::errc::invalid_argument)); 348 349 if (auto E = readBinaryFormatHeader(Data, FileHeader)) 350 return E; 351 352 FDRState State{0, 0, 0, FDRState::Token::NEW_BUFFER_RECORD_OR_EOF}; 353 // RecordSize will tell the loop how far to seek ahead based on the record 354 // type that we have just read. 355 size_t RecordSize = 0; 356 for (auto S = Data.drop_front(32); !S.empty(); S = S.drop_front(RecordSize)) { 357 DataExtractor RecordExtractor(S, true, 8); 358 uint32_t OffsetPtr = 0; 359 uint8_t BitField = RecordExtractor.getU8(&OffsetPtr); 360 bool isMetadataRecord = BitField & 0x01uL; 361 if (isMetadataRecord) { 362 RecordSize = 16; 363 if (auto E = processFDRMetadataRecord(State, BitField, RecordExtractor)) 364 return E; 365 } else { // Process Function Record 366 RecordSize = 8; 367 if (auto E = processFDRFunctionRecord(State, BitField, RecordExtractor, 368 Records)) 369 return E; 370 } 371 } 372 if (State.Expects != FDRState::Token::NEW_BUFFER_RECORD_OR_EOF) 373 return make_error<StringError>( 374 "Encountered EOF without preceding End of Buffer record.", 375 std::make_error_code(std::errc::executable_format_error)); 376 377 return Error::success(); 378 } 379 380 Error loadYAMLLog(StringRef Data, XRayFileHeader &FileHeader, 381 std::vector<XRayRecord> &Records) { 382 // Load the documents from the MappedFile. 383 YAMLXRayTrace Trace; 384 Input In(Data); 385 In >> Trace; 386 if (In.error()) 387 return make_error<StringError>("Failed loading YAML Data.", In.error()); 388 389 FileHeader.Version = Trace.Header.Version; 390 FileHeader.Type = Trace.Header.Type; 391 FileHeader.ConstantTSC = Trace.Header.ConstantTSC; 392 FileHeader.NonstopTSC = Trace.Header.NonstopTSC; 393 FileHeader.CycleFrequency = Trace.Header.CycleFrequency; 394 395 if (FileHeader.Version != 1) 396 return make_error<StringError>( 397 Twine("Unsupported XRay file version: ") + Twine(FileHeader.Version), 398 std::make_error_code(std::errc::invalid_argument)); 399 400 Records.clear(); 401 std::transform(Trace.Records.begin(), Trace.Records.end(), 402 std::back_inserter(Records), [&](const YAMLXRayRecord &R) { 403 return XRayRecord{R.RecordType, R.CPU, R.Type, 404 R.FuncId, R.TSC, R.TId}; 405 }); 406 return Error::success(); 407 } 408 409 Expected<Trace> llvm::xray::loadTraceFile(StringRef Filename, bool Sort) { 410 int Fd; 411 if (auto EC = sys::fs::openFileForRead(Filename, Fd)) { 412 return make_error<StringError>( 413 Twine("Cannot read log from '") + Filename + "'", EC); 414 } 415 416 // Attempt to get the filesize. 417 uint64_t FileSize; 418 if (auto EC = sys::fs::file_size(Filename, FileSize)) { 419 return make_error<StringError>( 420 Twine("Cannot read log from '") + Filename + "'", EC); 421 } 422 if (FileSize < 4) { 423 return make_error<StringError>( 424 Twine("File '") + Filename + "' too small for XRay.", 425 std::make_error_code(std::errc::executable_format_error)); 426 } 427 428 // Attempt to mmap the file. 429 std::error_code EC; 430 sys::fs::mapped_file_region MappedFile( 431 Fd, sys::fs::mapped_file_region::mapmode::readonly, FileSize, 0, EC); 432 if (EC) { 433 return make_error<StringError>( 434 Twine("Cannot read log from '") + Filename + "'", EC); 435 } 436 437 // Attempt to detect the file type using file magic. We have a slight bias 438 // towards the binary format, and we do this by making sure that the first 4 439 // bytes of the binary file is some combination of the following byte 440 // patterns: 441 // 442 // 0x0001 0x0000 - version 1, "naive" format 443 // 0x0001 0x0001 - version 1, "flight data recorder" format 444 // 445 // YAML files dont' typically have those first four bytes as valid text so we 446 // try loading assuming YAML if we don't find these bytes. 447 // 448 // Only if we can't load either the binary or the YAML format will we yield an 449 // error. 450 StringRef Magic(MappedFile.data(), 4); 451 DataExtractor HeaderExtractor(Magic, true, 8); 452 uint32_t OffsetPtr = 0; 453 uint16_t Version = HeaderExtractor.getU16(&OffsetPtr); 454 uint16_t Type = HeaderExtractor.getU16(&OffsetPtr); 455 456 enum BinaryFormatType { NAIVE_FORMAT = 0, FLIGHT_DATA_RECORDER_FORMAT = 1 }; 457 458 Trace T; 459 if (Version == 1 && Type == NAIVE_FORMAT) { 460 if (auto E = 461 loadNaiveFormatLog(StringRef(MappedFile.data(), MappedFile.size()), 462 T.FileHeader, T.Records)) 463 return std::move(E); 464 } else if (Version == 1 && Type == FLIGHT_DATA_RECORDER_FORMAT) { 465 if (auto E = loadFDRLog(StringRef(MappedFile.data(), MappedFile.size()), 466 T.FileHeader, T.Records)) 467 return std::move(E); 468 } else { 469 if (auto E = loadYAMLLog(StringRef(MappedFile.data(), MappedFile.size()), 470 T.FileHeader, T.Records)) 471 return std::move(E); 472 } 473 474 if (Sort) 475 std::sort(T.Records.begin(), T.Records.end(), 476 [&](const XRayRecord &L, const XRayRecord &R) { 477 return L.TSC < R.TSC; 478 }); 479 480 return std::move(T); 481 } 482