PTHLexer.cpp revision e013d685c6689ac7ae103ee88acf573422d1ed6a
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  unsigned DiagID = Diags->getCustomDiagID(level, Msg);
415  Diags->Report(FullSourceLoc(), DiagID);
416}
417
418PTHManager* PTHManager::Create(const std::string& file, Diagnostic* Diags,
419                               Diagnostic::Level level) {
420  // Memory map the PTH file.
421  llvm::OwningPtr<llvm::MemoryBuffer>
422  File(llvm::MemoryBuffer::getFile(file.c_str()));
423
424  if (!File) {
425    if (Diags) {
426      unsigned DiagID = Diags->getCustomDiagID(level,
427                                               "PTH file %0 could not be read");
428      Diags->Report(FullSourceLoc(), DiagID) << file;
429    }
430
431    return 0;
432  }
433
434  // Get the buffer ranges and check if there are at least three 32-bit
435  // words at the end of the file.
436  const unsigned char* BufBeg = (unsigned char*)File->getBufferStart();
437  const unsigned char* BufEnd = (unsigned char*)File->getBufferEnd();
438
439  // Check the prologue of the file.
440  if ((BufEnd - BufBeg) < (signed) (sizeof("cfe-pth") + 3 + 4) ||
441      memcmp(BufBeg, "cfe-pth", sizeof("cfe-pth") - 1) != 0) {
442    InvalidPTH(Diags, level);
443    return 0;
444  }
445
446  // Read the PTH version.
447  const unsigned char *p = BufBeg + (sizeof("cfe-pth") - 1);
448  unsigned Version = ReadLE32(p);
449
450  if (Version != PTHManager::Version) {
451    InvalidPTH(Diags, level,
452        Version < PTHManager::Version
453        ? "PTH file uses an older PTH format that is no longer supported"
454        : "PTH file uses a newer PTH format that cannot be read");
455    return 0;
456  }
457
458  // Compute the address of the index table at the end of the PTH file.
459  const unsigned char *PrologueOffset = p;
460
461  if (PrologueOffset >= BufEnd) {
462    InvalidPTH(Diags, level);
463    return 0;
464  }
465
466  // Construct the file lookup table.  This will be used for mapping from
467  // FileEntry*'s to cached tokens.
468  const unsigned char* FileTableOffset = PrologueOffset + sizeof(uint32_t)*2;
469  const unsigned char* FileTable = BufBeg + ReadLE32(FileTableOffset);
470
471  if (!(FileTable > BufBeg && FileTable < BufEnd)) {
472    InvalidPTH(Diags, level);
473    return 0; // FIXME: Proper error diagnostic?
474  }
475
476  llvm::OwningPtr<PTHFileLookup> FL(PTHFileLookup::Create(FileTable, BufBeg));
477
478  // Warn if the PTH file is empty.  We still want to create a PTHManager
479  // as the PTH could be used with -include-pth.
480  if (FL->isEmpty())
481    InvalidPTH(Diags, level, "PTH file contains no cached source data");
482
483  // Get the location of the table mapping from persistent ids to the
484  // data needed to reconstruct identifiers.
485  const unsigned char* IDTableOffset = PrologueOffset + sizeof(uint32_t)*0;
486  const unsigned char* IData = BufBeg + ReadLE32(IDTableOffset);
487
488  if (!(IData >= BufBeg && IData < BufEnd)) {
489    InvalidPTH(Diags, level);
490    return 0;
491  }
492
493  // Get the location of the hashtable mapping between strings and
494  // persistent IDs.
495  const unsigned char* StringIdTableOffset = PrologueOffset + sizeof(uint32_t)*1;
496  const unsigned char* StringIdTable = BufBeg + ReadLE32(StringIdTableOffset);
497  if (!(StringIdTable >= BufBeg && StringIdTable < BufEnd)) {
498    InvalidPTH(Diags, level);
499    return 0;
500  }
501
502  llvm::OwningPtr<PTHStringIdLookup> SL(PTHStringIdLookup::Create(StringIdTable,
503                                                                  BufBeg));
504
505  // Get the location of the spelling cache.
506  const unsigned char* spellingBaseOffset = PrologueOffset + sizeof(uint32_t)*3;
507  const unsigned char* spellingBase = BufBeg + ReadLE32(spellingBaseOffset);
508  if (!(spellingBase >= BufBeg && spellingBase < BufEnd)) {
509    InvalidPTH(Diags, level);
510    return 0;
511  }
512
513  // Get the number of IdentifierInfos and pre-allocate the identifier cache.
514  uint32_t NumIds = ReadLE32(IData);
515
516  // Pre-allocate the peristent ID -> IdentifierInfo* cache.  We use calloc()
517  // so that we in the best case only zero out memory once when the OS returns
518  // us new pages.
519  IdentifierInfo** PerIDCache = 0;
520
521  if (NumIds) {
522    PerIDCache = (IdentifierInfo**)calloc(NumIds, sizeof(*PerIDCache));
523    if (!PerIDCache) {
524      InvalidPTH(Diags, level,
525                 "Could not allocate memory for processing PTH file");
526      return 0;
527    }
528  }
529
530  // Compute the address of the original source file.
531  const unsigned char* originalSourceBase = PrologueOffset + sizeof(uint32_t)*4;
532  unsigned len = ReadUnalignedLE16(originalSourceBase);
533  if (!len) originalSourceBase = 0;
534
535  // Create the new PTHManager.
536  return new PTHManager(File.take(), FL.take(), IData, PerIDCache,
537                        SL.take(), NumIds, spellingBase,
538                        (const char*) originalSourceBase);
539}
540
541IdentifierInfo* PTHManager::LazilyCreateIdentifierInfo(unsigned PersistentID) {
542  // Look in the PTH file for the string data for the IdentifierInfo object.
543  const unsigned char* TableEntry = IdDataTable + sizeof(uint32_t)*PersistentID;
544  const unsigned char* IDData =
545    (const unsigned char*)Buf->getBufferStart() + ReadLE32(TableEntry);
546  assert(IDData < (const unsigned char*)Buf->getBufferEnd());
547
548  // Allocate the object.
549  std::pair<IdentifierInfo,const unsigned char*> *Mem =
550    Alloc.Allocate<std::pair<IdentifierInfo,const unsigned char*> >();
551
552  Mem->second = IDData;
553  assert(IDData[0] != '\0');
554  IdentifierInfo *II = new ((void*) Mem) IdentifierInfo();
555
556  // Store the new IdentifierInfo in the cache.
557  PerIDCache[PersistentID] = II;
558  assert(II->getNameStart() && II->getNameStart()[0] != '\0');
559  return II;
560}
561
562IdentifierInfo* PTHManager::get(const char *NameStart, const char *NameEnd) {
563  PTHStringIdLookup& SL = *((PTHStringIdLookup*)StringIdLookup);
564  // Double check our assumption that the last character isn't '\0'.
565  assert(NameEnd==NameStart || NameStart[NameEnd-NameStart-1] != '\0');
566  PTHStringIdLookup::iterator I = SL.find(std::make_pair(NameStart,
567                                                         NameEnd - NameStart));
568  if (I == SL.end()) // No identifier found?
569    return 0;
570
571  // Match found.  Return the identifier!
572  assert(*I > 0);
573  return GetIdentifierInfo(*I-1);
574}
575
576PTHLexer *PTHManager::CreateLexer(FileID FID) {
577  const FileEntry *FE = PP->getSourceManager().getFileEntryForID(FID);
578  if (!FE)
579    return 0;
580
581  // Lookup the FileEntry object in our file lookup data structure.  It will
582  // return a variant that indicates whether or not there is an offset within
583  // the PTH file that contains cached tokens.
584  PTHFileLookup& PFL = *((PTHFileLookup*)FileLookup);
585  PTHFileLookup::iterator I = PFL.find(FE);
586
587  if (I == PFL.end()) // No tokens available?
588    return 0;
589
590  const PTHFileData& FileData = *I;
591
592  const unsigned char *BufStart = (const unsigned char *)Buf->getBufferStart();
593  // Compute the offset of the token data within the buffer.
594  const unsigned char* data = BufStart + FileData.getTokenOffset();
595
596  // Get the location of pp-conditional table.
597  const unsigned char* ppcond = BufStart + FileData.getPPCondOffset();
598  uint32_t Len = ReadLE32(ppcond);
599  if (Len == 0) ppcond = 0;
600
601  assert(PP && "No preprocessor set yet!");
602  return new PTHLexer(*PP, FID, data, ppcond, *this);
603}
604
605//===----------------------------------------------------------------------===//
606// 'stat' caching.
607//===----------------------------------------------------------------------===//
608
609namespace {
610class VISIBILITY_HIDDEN PTHStatData {
611public:
612  const bool hasStat;
613  const ino_t ino;
614  const dev_t dev;
615  const mode_t mode;
616  const time_t mtime;
617  const off_t size;
618
619  PTHStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
620  : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {}
621
622  PTHStatData()
623    : hasStat(false), ino(0), dev(0), mode(0), mtime(0), size(0) {}
624};
625
626class VISIBILITY_HIDDEN PTHStatLookupTrait : public PTHFileLookupCommonTrait {
627public:
628  typedef const char* external_key_type;  // const char*
629  typedef PTHStatData data_type;
630
631  static internal_key_type GetInternalKey(const char *path) {
632    // The key 'kind' doesn't matter here because it is ignored in EqualKey.
633    return std::make_pair((unsigned char) 0x0, path);
634  }
635
636  static bool EqualKey(internal_key_type a, internal_key_type b) {
637    // When doing 'stat' lookups we don't care about the kind of 'a' and 'b',
638    // just the paths.
639    return strcmp(a.second, b.second) == 0;
640  }
641
642  static data_type ReadData(const internal_key_type& k, const unsigned char* d,
643                            unsigned) {
644
645    if (k.first /* File or Directory */) {
646      if (k.first == 0x1 /* File */) d += 4 * 2; // Skip the first 2 words.
647      ino_t ino = (ino_t) ReadUnalignedLE32(d);
648      dev_t dev = (dev_t) ReadUnalignedLE32(d);
649      mode_t mode = (mode_t) ReadUnalignedLE16(d);
650      time_t mtime = (time_t) ReadUnalignedLE64(d);
651      return data_type(ino, dev, mode, mtime, (off_t) ReadUnalignedLE64(d));
652    }
653
654    // Negative stat.  Don't read anything.
655    return data_type();
656  }
657};
658
659class VISIBILITY_HIDDEN PTHStatCache : public StatSysCallCache {
660  typedef OnDiskChainedHashTable<PTHStatLookupTrait> CacheTy;
661  CacheTy Cache;
662
663public:
664  PTHStatCache(PTHFileLookup &FL) :
665    Cache(FL.getNumBuckets(), FL.getNumEntries(), FL.getBuckets(),
666          FL.getBase()) {}
667
668  ~PTHStatCache() {}
669
670  int stat(const char *path, struct stat *buf) {
671    // Do the lookup for the file's data in the PTH file.
672    CacheTy::iterator I = Cache.find(path);
673
674    // If we don't get a hit in the PTH file just forward to 'stat'.
675    if (I == Cache.end())
676      return StatSysCallCache::stat(path, buf);
677
678    const PTHStatData& Data = *I;
679
680    if (!Data.hasStat)
681      return 1;
682
683    buf->st_ino = Data.ino;
684    buf->st_dev = Data.dev;
685    buf->st_mtime = Data.mtime;
686    buf->st_mode = Data.mode;
687    buf->st_size = Data.size;
688    return 0;
689  }
690};
691} // end anonymous namespace
692
693StatSysCallCache *PTHManager::createStatCache() {
694  return new PTHStatCache(*((PTHFileLookup*) FileLookup));
695}
696