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