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