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