PTHLexer.cpp revision 94e3d1f0349634235606be77c08b3a48a6d563d6
1//===--- PTHLexer.cpp - Lex from a token stream ---------------------------===// 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// This file implements the PTHLexer interface. 11// 12//===----------------------------------------------------------------------===// 13 14#include "clang/Basic/TokenKinds.h" 15#include "clang/Basic/FileManager.h" 16#include "clang/Basic/IdentifierTable.h" 17#include "clang/Basic/OnDiskHashTable.h" 18#include "clang/Lex/LexDiagnostic.h" 19#include "clang/Lex/PTHLexer.h" 20#include "clang/Lex/Preprocessor.h" 21#include "clang/Lex/PTHManager.h" 22#include "clang/Lex/Token.h" 23#include "clang/Lex/Preprocessor.h" 24#include "llvm/ADT/OwningPtr.h" 25#include "llvm/ADT/StringExtras.h" 26#include "llvm/ADT/StringMap.h" 27#include "llvm/Support/MemoryBuffer.h" 28#include <sys/stat.h> 29using namespace clang; 30using namespace clang::io; 31 32#define DISK_TOKEN_SIZE (1+1+2+4+4) 33 34//===----------------------------------------------------------------------===// 35// PTHLexer methods. 36//===----------------------------------------------------------------------===// 37 38PTHLexer::PTHLexer(Preprocessor &PP, FileID FID, const unsigned char *D, 39 const unsigned char *ppcond, PTHManager &PM) 40 : PreprocessorLexer(&PP, FID), TokBuf(D), CurPtr(D), LastHashTokPtr(0), 41 PPCond(ppcond), CurPPCondPtr(ppcond), PTHMgr(PM) { 42 43 FileStartLoc = PP.getSourceManager().getLocForStartOfFile(FID); 44} 45 46void PTHLexer::Lex(Token& Tok) { 47LexNextToken: 48 49 //===--------------------------------------==// 50 // Read the raw token data. 51 //===--------------------------------------==// 52 53 // Shadow CurPtr into an automatic variable. 54 const unsigned char *CurPtrShadow = CurPtr; 55 56 // Read in the data for the token. 57 unsigned Word0 = ReadLE32(CurPtrShadow); 58 uint32_t IdentifierID = ReadLE32(CurPtrShadow); 59 uint32_t FileOffset = ReadLE32(CurPtrShadow); 60 61 tok::TokenKind TKind = (tok::TokenKind) (Word0 & 0xFF); 62 Token::TokenFlags TFlags = (Token::TokenFlags) ((Word0 >> 8) & 0xFF); 63 uint32_t Len = Word0 >> 16; 64 65 CurPtr = CurPtrShadow; 66 67 //===--------------------------------------==// 68 // Construct the token itself. 69 //===--------------------------------------==// 70 71 Tok.startToken(); 72 Tok.setKind(TKind); 73 Tok.setFlag(TFlags); 74 assert(!LexingRawMode); 75 Tok.setLocation(FileStartLoc.getFileLocWithOffset(FileOffset)); 76 Tok.setLength(Len); 77 78 // Handle identifiers. 79 if (Tok.isLiteral()) { 80 Tok.setLiteralData((const char*) (PTHMgr.SpellingBase + IdentifierID)); 81 } 82 else if (IdentifierID) { 83 MIOpt.ReadToken(); 84 IdentifierInfo *II = PTHMgr.GetIdentifierInfo(IdentifierID-1); 85 86 Tok.setIdentifierInfo(II); 87 88 // Change the kind of this identifier to the appropriate token kind, e.g. 89 // turning "for" into a keyword. 90 Tok.setKind(II->getTokenID()); 91 92 if (II->isHandleIdentifierCase()) 93 PP->HandleIdentifier(Tok); 94 return; 95 } 96 97 //===--------------------------------------==// 98 // Process the token. 99 //===--------------------------------------==// 100 if (TKind == tok::eof) { 101 // Save the end-of-file token. 102 EofToken = Tok; 103 104 // Save 'PP' to 'PPCache' as LexEndOfFile can delete 'this'. 105 Preprocessor *PPCache = PP; 106 107 assert(!ParsingPreprocessorDirective); 108 assert(!LexingRawMode); 109 110 if (LexEndOfFile(Tok)) 111 return; 112 113 return PPCache->Lex(Tok); 114 } 115 116 if (TKind == tok::hash && Tok.isAtStartOfLine()) { 117 LastHashTokPtr = CurPtr - DISK_TOKEN_SIZE; 118 assert(!LexingRawMode); 119 PP->HandleDirective(Tok); 120 121 if (PP->isCurrentLexer(this)) 122 goto LexNextToken; 123 124 return PP->Lex(Tok); 125 } 126 127 if (TKind == tok::eom) { 128 assert(ParsingPreprocessorDirective); 129 ParsingPreprocessorDirective = false; 130 return; 131 } 132 133 MIOpt.ReadToken(); 134} 135 136bool PTHLexer::LexEndOfFile(Token &Result) { 137 // If we hit the end of the file while parsing a preprocessor directive, 138 // end the preprocessor directive first. The next token returned will 139 // then be the end of file. 140 if (ParsingPreprocessorDirective) { 141 ParsingPreprocessorDirective = false; // Done parsing the "line". 142 return true; // Have a token. 143 } 144 145 assert(!LexingRawMode); 146 147 // If we are in a #if directive, emit an error. 148 while (!ConditionalStack.empty()) { 149 PP->Diag(ConditionalStack.back().IfLoc, 150 diag::err_pp_unterminated_conditional); 151 ConditionalStack.pop_back(); 152 } 153 154 // Finally, let the preprocessor handle this. 155 return PP->HandleEndOfFile(Result); 156} 157 158// FIXME: We can just grab the last token instead of storing a copy 159// into EofToken. 160void PTHLexer::getEOF(Token& Tok) { 161 assert(EofToken.is(tok::eof)); 162 Tok = EofToken; 163} 164 165void PTHLexer::DiscardToEndOfLine() { 166 assert(ParsingPreprocessorDirective && ParsingFilename == false && 167 "Must be in a preprocessing directive!"); 168 169 // We assume that if the preprocessor wishes to discard to the end of 170 // the line that it also means to end the current preprocessor directive. 171 ParsingPreprocessorDirective = false; 172 173 // Skip tokens by only peeking at their token kind and the flags. 174 // We don't need to actually reconstruct full tokens from the token buffer. 175 // This saves some copies and it also reduces IdentifierInfo* lookup. 176 const unsigned char* p = CurPtr; 177 while (1) { 178 // Read the token kind. Are we at the end of the file? 179 tok::TokenKind x = (tok::TokenKind) (uint8_t) *p; 180 if (x == tok::eof) break; 181 182 // Read the token flags. Are we at the start of the next line? 183 Token::TokenFlags y = (Token::TokenFlags) (uint8_t) p[1]; 184 if (y & Token::StartOfLine) break; 185 186 // Skip to the next token. 187 p += DISK_TOKEN_SIZE; 188 } 189 190 CurPtr = p; 191} 192 193/// SkipBlock - Used by Preprocessor to skip the current conditional block. 194bool PTHLexer::SkipBlock() { 195 assert(CurPPCondPtr && "No cached PP conditional information."); 196 assert(LastHashTokPtr && "No known '#' token."); 197 198 const unsigned char* HashEntryI = 0; 199 uint32_t Offset; 200 uint32_t TableIdx; 201 202 do { 203 // Read the token offset from the side-table. 204 Offset = ReadLE32(CurPPCondPtr); 205 206 // Read the target table index from the side-table. 207 TableIdx = ReadLE32(CurPPCondPtr); 208 209 // Compute the actual memory address of the '#' token data for this entry. 210 HashEntryI = TokBuf + Offset; 211 212 // Optmization: "Sibling jumping". #if...#else...#endif blocks can 213 // contain nested blocks. In the side-table we can jump over these 214 // nested blocks instead of doing a linear search if the next "sibling" 215 // entry is not at a location greater than LastHashTokPtr. 216 if (HashEntryI < LastHashTokPtr && TableIdx) { 217 // In the side-table we are still at an entry for a '#' token that 218 // is earlier than the last one we saw. Check if the location we would 219 // stride gets us closer. 220 const unsigned char* NextPPCondPtr = 221 PPCond + TableIdx*(sizeof(uint32_t)*2); 222 assert(NextPPCondPtr >= CurPPCondPtr); 223 // Read where we should jump to. 224 uint32_t TmpOffset = ReadLE32(NextPPCondPtr); 225 const unsigned char* HashEntryJ = TokBuf + TmpOffset; 226 227 if (HashEntryJ <= LastHashTokPtr) { 228 // Jump directly to the next entry in the side table. 229 HashEntryI = HashEntryJ; 230 Offset = TmpOffset; 231 TableIdx = ReadLE32(NextPPCondPtr); 232 CurPPCondPtr = NextPPCondPtr; 233 } 234 } 235 } 236 while (HashEntryI < LastHashTokPtr); 237 assert(HashEntryI == LastHashTokPtr && "No PP-cond entry found for '#'"); 238 assert(TableIdx && "No jumping from #endifs."); 239 240 // Update our side-table iterator. 241 const unsigned char* NextPPCondPtr = PPCond + TableIdx*(sizeof(uint32_t)*2); 242 assert(NextPPCondPtr >= CurPPCondPtr); 243 CurPPCondPtr = NextPPCondPtr; 244 245 // Read where we should jump to. 246 HashEntryI = TokBuf + ReadLE32(NextPPCondPtr); 247 uint32_t NextIdx = ReadLE32(NextPPCondPtr); 248 249 // By construction NextIdx will be zero if this is a #endif. This is useful 250 // to know to obviate lexing another token. 251 bool isEndif = NextIdx == 0; 252 253 // This case can occur when we see something like this: 254 // 255 // #if ... 256 // /* a comment or nothing */ 257 // #elif 258 // 259 // If we are skipping the first #if block it will be the case that CurPtr 260 // already points 'elif'. Just return. 261 262 if (CurPtr > HashEntryI) { 263 assert(CurPtr == HashEntryI + DISK_TOKEN_SIZE); 264 // Did we reach a #endif? If so, go ahead and consume that token as well. 265 if (isEndif) 266 CurPtr += DISK_TOKEN_SIZE*2; 267 else 268 LastHashTokPtr = HashEntryI; 269 270 return isEndif; 271 } 272 273 // Otherwise, we need to advance. Update CurPtr to point to the '#' token. 274 CurPtr = HashEntryI; 275 276 // Update the location of the last observed '#'. This is useful if we 277 // are skipping multiple blocks. 278 LastHashTokPtr = CurPtr; 279 280 // Skip the '#' token. 281 assert(((tok::TokenKind)*CurPtr) == tok::hash); 282 CurPtr += DISK_TOKEN_SIZE; 283 284 // Did we reach a #endif? If so, go ahead and consume that token as well. 285 if (isEndif) { CurPtr += DISK_TOKEN_SIZE*2; } 286 287 return isEndif; 288} 289 290SourceLocation PTHLexer::getSourceLocation() { 291 // getSourceLocation is not on the hot path. It is used to get the location 292 // of the next token when transitioning back to this lexer when done 293 // handling a #included file. Just read the necessary data from the token 294 // data buffer to construct the SourceLocation object. 295 // NOTE: This is a virtual function; hence it is defined out-of-line. 296 const unsigned char *OffsetPtr = CurPtr + (DISK_TOKEN_SIZE - 4); 297 uint32_t Offset = ReadLE32(OffsetPtr); 298 return FileStartLoc.getFileLocWithOffset(Offset); 299} 300 301//===----------------------------------------------------------------------===// 302// PTH file lookup: map from strings to file data. 303//===----------------------------------------------------------------------===// 304 305/// PTHFileLookup - This internal data structure is used by the PTHManager 306/// to map from FileEntry objects managed by FileManager to offsets within 307/// the PTH file. 308namespace { 309class PTHFileData { 310 const uint32_t TokenOff; 311 const uint32_t PPCondOff; 312public: 313 PTHFileData(uint32_t tokenOff, uint32_t ppCondOff) 314 : TokenOff(tokenOff), PPCondOff(ppCondOff) {} 315 316 uint32_t getTokenOffset() const { return TokenOff; } 317 uint32_t getPPCondOffset() const { return PPCondOff; } 318}; 319 320 321class PTHFileLookupCommonTrait { 322public: 323 typedef std::pair<unsigned char, const char*> internal_key_type; 324 325 static unsigned ComputeHash(internal_key_type x) { 326 return llvm::HashString(x.second); 327 } 328 329 static std::pair<unsigned, unsigned> 330 ReadKeyDataLength(const unsigned char*& d) { 331 unsigned keyLen = (unsigned) ReadUnalignedLE16(d); 332 unsigned dataLen = (unsigned) *(d++); 333 return std::make_pair(keyLen, dataLen); 334 } 335 336 static internal_key_type ReadKey(const unsigned char* d, unsigned) { 337 unsigned char k = *(d++); // Read the entry kind. 338 return std::make_pair(k, (const char*) d); 339 } 340}; 341 342class PTHFileLookupTrait : public PTHFileLookupCommonTrait { 343public: 344 typedef const FileEntry* external_key_type; 345 typedef PTHFileData data_type; 346 347 static internal_key_type GetInternalKey(const FileEntry* FE) { 348 return std::make_pair((unsigned char) 0x1, FE->getName()); 349 } 350 351 static bool EqualKey(internal_key_type a, internal_key_type b) { 352 return a.first == b.first && strcmp(a.second, b.second) == 0; 353 } 354 355 static PTHFileData ReadData(const internal_key_type& k, 356 const unsigned char* d, unsigned) { 357 assert(k.first == 0x1 && "Only file lookups can match!"); 358 uint32_t x = ::ReadUnalignedLE32(d); 359 uint32_t y = ::ReadUnalignedLE32(d); 360 return PTHFileData(x, y); 361 } 362}; 363 364class PTHStringLookupTrait { 365public: 366 typedef uint32_t 367 data_type; 368 369 typedef const std::pair<const char*, unsigned> 370 external_key_type; 371 372 typedef external_key_type internal_key_type; 373 374 static bool EqualKey(const internal_key_type& a, 375 const internal_key_type& b) { 376 return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0 377 : false; 378 } 379 380 static unsigned ComputeHash(const internal_key_type& a) { 381 return llvm::HashString(llvm::StringRef(a.first, a.second)); 382 } 383 384 // This hopefully will just get inlined and removed by the optimizer. 385 static const internal_key_type& 386 GetInternalKey(const external_key_type& x) { return x; } 387 388 static std::pair<unsigned, unsigned> 389 ReadKeyDataLength(const unsigned char*& d) { 390 return std::make_pair((unsigned) ReadUnalignedLE16(d), sizeof(uint32_t)); 391 } 392 393 static std::pair<const char*, unsigned> 394 ReadKey(const unsigned char* d, unsigned n) { 395 assert(n >= 2 && d[n-1] == '\0'); 396 return std::make_pair((const char*) d, n-1); 397 } 398 399 static uint32_t ReadData(const internal_key_type& k, const unsigned char* d, 400 unsigned) { 401 return ::ReadUnalignedLE32(d); 402 } 403}; 404 405} // end anonymous namespace 406 407typedef OnDiskChainedHashTable<PTHFileLookupTrait> PTHFileLookup; 408typedef OnDiskChainedHashTable<PTHStringLookupTrait> PTHStringIdLookup; 409 410//===----------------------------------------------------------------------===// 411// PTHManager methods. 412//===----------------------------------------------------------------------===// 413 414PTHManager::PTHManager(const llvm::MemoryBuffer* buf, void* fileLookup, 415 const unsigned char* idDataTable, 416 IdentifierInfo** perIDCache, 417 void* stringIdLookup, unsigned numIds, 418 const unsigned char* spellingBase, 419 const char* originalSourceFile) 420: Buf(buf), PerIDCache(perIDCache), FileLookup(fileLookup), 421 IdDataTable(idDataTable), StringIdLookup(stringIdLookup), 422 NumIds(numIds), PP(0), SpellingBase(spellingBase), 423 OriginalSourceFile(originalSourceFile) {} 424 425PTHManager::~PTHManager() { 426 delete Buf; 427 delete (PTHFileLookup*) FileLookup; 428 delete (PTHStringIdLookup*) StringIdLookup; 429 free(PerIDCache); 430} 431 432static void InvalidPTH(Diagnostic &Diags, const char *Msg) { 433 Diags.Report(Diags.getCustomDiagID(Diagnostic::Error, Msg)); 434} 435 436PTHManager* PTHManager::Create(const std::string& file, Diagnostic &Diags) { 437 // Memory map the PTH file. 438 llvm::OwningPtr<llvm::MemoryBuffer> 439 File(llvm::MemoryBuffer::getFile(file.c_str())); 440 441 if (!File) { 442 Diags.Report(diag::err_invalid_pth_file) << file; 443 return 0; 444 } 445 446 // Get the buffer ranges and check if there are at least three 32-bit 447 // words at the end of the file. 448 const unsigned char* BufBeg = (unsigned char*)File->getBufferStart(); 449 const unsigned char* BufEnd = (unsigned char*)File->getBufferEnd(); 450 451 // Check the prologue of the file. 452 if ((BufEnd - BufBeg) < (signed) (sizeof("cfe-pth") + 3 + 4) || 453 memcmp(BufBeg, "cfe-pth", sizeof("cfe-pth") - 1) != 0) { 454 Diags.Report(diag::err_invalid_pth_file) << file; 455 return 0; 456 } 457 458 // Read the PTH version. 459 const unsigned char *p = BufBeg + (sizeof("cfe-pth") - 1); 460 unsigned Version = ReadLE32(p); 461 462 if (Version < PTHManager::Version) { 463 InvalidPTH(Diags, 464 Version < PTHManager::Version 465 ? "PTH file uses an older PTH format that is no longer supported" 466 : "PTH file uses a newer PTH format that cannot be read"); 467 return 0; 468 } 469 470 // Compute the address of the index table at the end of the PTH file. 471 const unsigned char *PrologueOffset = p; 472 473 if (PrologueOffset >= BufEnd) { 474 Diags.Report(diag::err_invalid_pth_file) << file; 475 return 0; 476 } 477 478 // Construct the file lookup table. This will be used for mapping from 479 // FileEntry*'s to cached tokens. 480 const unsigned char* FileTableOffset = PrologueOffset + sizeof(uint32_t)*2; 481 const unsigned char* FileTable = BufBeg + ReadLE32(FileTableOffset); 482 483 if (!(FileTable > BufBeg && FileTable < BufEnd)) { 484 Diags.Report(diag::err_invalid_pth_file) << file; 485 return 0; // FIXME: Proper error diagnostic? 486 } 487 488 llvm::OwningPtr<PTHFileLookup> FL(PTHFileLookup::Create(FileTable, BufBeg)); 489 490 // Warn if the PTH file is empty. We still want to create a PTHManager 491 // as the PTH could be used with -include-pth. 492 if (FL->isEmpty()) 493 InvalidPTH(Diags, "PTH file contains no cached source data"); 494 495 // Get the location of the table mapping from persistent ids to the 496 // data needed to reconstruct identifiers. 497 const unsigned char* IDTableOffset = PrologueOffset + sizeof(uint32_t)*0; 498 const unsigned char* IData = BufBeg + ReadLE32(IDTableOffset); 499 500 if (!(IData >= BufBeg && IData < BufEnd)) { 501 Diags.Report(diag::err_invalid_pth_file) << file; 502 return 0; 503 } 504 505 // Get the location of the hashtable mapping between strings and 506 // persistent IDs. 507 const unsigned char* StringIdTableOffset = PrologueOffset + sizeof(uint32_t)*1; 508 const unsigned char* StringIdTable = BufBeg + ReadLE32(StringIdTableOffset); 509 if (!(StringIdTable >= BufBeg && StringIdTable < BufEnd)) { 510 Diags.Report(diag::err_invalid_pth_file) << file; 511 return 0; 512 } 513 514 llvm::OwningPtr<PTHStringIdLookup> SL(PTHStringIdLookup::Create(StringIdTable, 515 BufBeg)); 516 517 // Get the location of the spelling cache. 518 const unsigned char* spellingBaseOffset = PrologueOffset + sizeof(uint32_t)*3; 519 const unsigned char* spellingBase = BufBeg + ReadLE32(spellingBaseOffset); 520 if (!(spellingBase >= BufBeg && spellingBase < BufEnd)) { 521 Diags.Report(diag::err_invalid_pth_file) << file; 522 return 0; 523 } 524 525 // Get the number of IdentifierInfos and pre-allocate the identifier cache. 526 uint32_t NumIds = ReadLE32(IData); 527 528 // Pre-allocate the peristent ID -> IdentifierInfo* cache. We use calloc() 529 // so that we in the best case only zero out memory once when the OS returns 530 // us new pages. 531 IdentifierInfo** PerIDCache = 0; 532 533 if (NumIds) { 534 PerIDCache = (IdentifierInfo**)calloc(NumIds, sizeof(*PerIDCache)); 535 if (!PerIDCache) { 536 InvalidPTH(Diags, "Could not allocate memory for processing PTH file"); 537 return 0; 538 } 539 } 540 541 // Compute the address of the original source file. 542 const unsigned char* originalSourceBase = PrologueOffset + sizeof(uint32_t)*4; 543 unsigned len = ReadUnalignedLE16(originalSourceBase); 544 if (!len) originalSourceBase = 0; 545 546 // Create the new PTHManager. 547 return new PTHManager(File.take(), FL.take(), IData, PerIDCache, 548 SL.take(), NumIds, spellingBase, 549 (const char*) originalSourceBase); 550} 551 552IdentifierInfo* PTHManager::LazilyCreateIdentifierInfo(unsigned PersistentID) { 553 // Look in the PTH file for the string data for the IdentifierInfo object. 554 const unsigned char* TableEntry = IdDataTable + sizeof(uint32_t)*PersistentID; 555 const unsigned char* IDData = 556 (const unsigned char*)Buf->getBufferStart() + ReadLE32(TableEntry); 557 assert(IDData < (const unsigned char*)Buf->getBufferEnd()); 558 559 // Allocate the object. 560 std::pair<IdentifierInfo,const unsigned char*> *Mem = 561 Alloc.Allocate<std::pair<IdentifierInfo,const unsigned char*> >(); 562 563 Mem->second = IDData; 564 assert(IDData[0] != '\0'); 565 IdentifierInfo *II = new ((void*) Mem) IdentifierInfo(); 566 567 // Store the new IdentifierInfo in the cache. 568 PerIDCache[PersistentID] = II; 569 assert(II->getNameStart() && II->getNameStart()[0] != '\0'); 570 return II; 571} 572 573IdentifierInfo* PTHManager::get(llvm::StringRef Name) { 574 PTHStringIdLookup& SL = *((PTHStringIdLookup*)StringIdLookup); 575 // Double check our assumption that the last character isn't '\0'. 576 assert(Name.empty() || Name.data()[Name.size()-1] != '\0'); 577 PTHStringIdLookup::iterator I = SL.find(std::make_pair(Name.data(), 578 Name.size())); 579 if (I == SL.end()) // No identifier found? 580 return 0; 581 582 // Match found. Return the identifier! 583 assert(*I > 0); 584 return GetIdentifierInfo(*I-1); 585} 586 587PTHLexer *PTHManager::CreateLexer(FileID FID) { 588 const FileEntry *FE = PP->getSourceManager().getFileEntryForID(FID); 589 if (!FE) 590 return 0; 591 592 // Lookup the FileEntry object in our file lookup data structure. It will 593 // return a variant that indicates whether or not there is an offset within 594 // the PTH file that contains cached tokens. 595 PTHFileLookup& PFL = *((PTHFileLookup*)FileLookup); 596 PTHFileLookup::iterator I = PFL.find(FE); 597 598 if (I == PFL.end()) // No tokens available? 599 return 0; 600 601 const PTHFileData& FileData = *I; 602 603 const unsigned char *BufStart = (const unsigned char *)Buf->getBufferStart(); 604 // Compute the offset of the token data within the buffer. 605 const unsigned char* data = BufStart + FileData.getTokenOffset(); 606 607 // Get the location of pp-conditional table. 608 const unsigned char* ppcond = BufStart + FileData.getPPCondOffset(); 609 uint32_t Len = ReadLE32(ppcond); 610 if (Len == 0) ppcond = 0; 611 612 assert(PP && "No preprocessor set yet!"); 613 return new PTHLexer(*PP, FID, data, ppcond, *this); 614} 615 616//===----------------------------------------------------------------------===// 617// 'stat' caching. 618//===----------------------------------------------------------------------===// 619 620namespace { 621class PTHStatData { 622public: 623 const bool hasStat; 624 const ino_t ino; 625 const dev_t dev; 626 const mode_t mode; 627 const time_t mtime; 628 const off_t size; 629 630 PTHStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s) 631 : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {} 632 633 PTHStatData() 634 : hasStat(false), ino(0), dev(0), mode(0), mtime(0), size(0) {} 635}; 636 637class PTHStatLookupTrait : public PTHFileLookupCommonTrait { 638public: 639 typedef const char* external_key_type; // const char* 640 typedef PTHStatData data_type; 641 642 static internal_key_type GetInternalKey(const char *path) { 643 // The key 'kind' doesn't matter here because it is ignored in EqualKey. 644 return std::make_pair((unsigned char) 0x0, path); 645 } 646 647 static bool EqualKey(internal_key_type a, internal_key_type b) { 648 // When doing 'stat' lookups we don't care about the kind of 'a' and 'b', 649 // just the paths. 650 return strcmp(a.second, b.second) == 0; 651 } 652 653 static data_type ReadData(const internal_key_type& k, const unsigned char* d, 654 unsigned) { 655 656 if (k.first /* File or Directory */) { 657 if (k.first == 0x1 /* File */) d += 4 * 2; // Skip the first 2 words. 658 ino_t ino = (ino_t) ReadUnalignedLE32(d); 659 dev_t dev = (dev_t) ReadUnalignedLE32(d); 660 mode_t mode = (mode_t) ReadUnalignedLE16(d); 661 time_t mtime = (time_t) ReadUnalignedLE64(d); 662 return data_type(ino, dev, mode, mtime, (off_t) ReadUnalignedLE64(d)); 663 } 664 665 // Negative stat. Don't read anything. 666 return data_type(); 667 } 668}; 669 670class PTHStatCache : public StatSysCallCache { 671 typedef OnDiskChainedHashTable<PTHStatLookupTrait> CacheTy; 672 CacheTy Cache; 673 674public: 675 PTHStatCache(PTHFileLookup &FL) : 676 Cache(FL.getNumBuckets(), FL.getNumEntries(), FL.getBuckets(), 677 FL.getBase()) {} 678 679 ~PTHStatCache() {} 680 681 int stat(const char *path, struct stat *buf) { 682 // Do the lookup for the file's data in the PTH file. 683 CacheTy::iterator I = Cache.find(path); 684 685 // If we don't get a hit in the PTH file just forward to 'stat'. 686 if (I == Cache.end()) 687 return StatSysCallCache::stat(path, buf); 688 689 const PTHStatData& Data = *I; 690 691 if (!Data.hasStat) 692 return 1; 693 694 buf->st_ino = Data.ino; 695 buf->st_dev = Data.dev; 696 buf->st_mtime = Data.mtime; 697 buf->st_mode = Data.mode; 698 buf->st_size = Data.size; 699 return 0; 700 } 701}; 702} // end anonymous namespace 703 704StatSysCallCache *PTHManager::createStatCache() { 705 return new PTHStatCache(*((PTHFileLookup*) FileLookup)); 706} 707