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