HeaderMap.cpp 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. //===--- HeaderMap.cpp - A file that acts like dir of symlinks ------------===//
  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 HeaderMap interface.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Lex/HeaderMap.h"
  14. #include "clang/Basic/FileManager.h"
  15. #include "llvm/ADT/OwningPtr.h"
  16. #include "llvm/ADT/SmallString.h"
  17. #include "llvm/System/DataTypes.h"
  18. #include "llvm/Support/MathExtras.h"
  19. #include "llvm/Support/MemoryBuffer.h"
  20. #include <cstdio>
  21. using namespace clang;
  22. //===----------------------------------------------------------------------===//
  23. // Data Structures and Manifest Constants
  24. //===----------------------------------------------------------------------===//
  25. enum {
  26. HMAP_HeaderMagicNumber = ('h' << 24) | ('m' << 16) | ('a' << 8) | 'p',
  27. HMAP_HeaderVersion = 1,
  28. HMAP_EmptyBucketKey = 0
  29. };
  30. namespace clang {
  31. struct HMapBucket {
  32. uint32_t Key; // Offset (into strings) of key.
  33. uint32_t Prefix; // Offset (into strings) of value prefix.
  34. uint32_t Suffix; // Offset (into strings) of value suffix.
  35. };
  36. struct HMapHeader {
  37. uint32_t Magic; // Magic word, also indicates byte order.
  38. uint16_t Version; // Version number -- currently 1.
  39. uint16_t Reserved; // Reserved for future use - zero for now.
  40. uint32_t StringsOffset; // Offset to start of string pool.
  41. uint32_t NumEntries; // Number of entries in the string table.
  42. uint32_t NumBuckets; // Number of buckets (always a power of 2).
  43. uint32_t MaxValueLength; // Length of longest result path (excluding nul).
  44. // An array of 'NumBuckets' HMapBucket objects follows this header.
  45. // Strings follow the buckets, at StringsOffset.
  46. };
  47. } // end namespace clang.
  48. /// HashHMapKey - This is the 'well known' hash function required by the file
  49. /// format, used to look up keys in the hash table. The hash table uses simple
  50. /// linear probing based on this function.
  51. static inline unsigned HashHMapKey(llvm::StringRef Str) {
  52. unsigned Result = 0;
  53. const char *S = Str.begin(), *End = Str.end();
  54. for (; S != End; S++)
  55. Result += tolower(*S) * 13;
  56. return Result;
  57. }
  58. //===----------------------------------------------------------------------===//
  59. // Verification and Construction
  60. //===----------------------------------------------------------------------===//
  61. /// HeaderMap::Create - This attempts to load the specified file as a header
  62. /// map. If it doesn't look like a HeaderMap, it gives up and returns null.
  63. /// If it looks like a HeaderMap but is obviously corrupted, it puts a reason
  64. /// into the string error argument and returns null.
  65. const HeaderMap *HeaderMap::Create(const FileEntry *FE, FileManager &FM,
  66. const FileSystemOptions &FSOpts) {
  67. // If the file is too small to be a header map, ignore it.
  68. unsigned FileSize = FE->getSize();
  69. if (FileSize <= sizeof(HMapHeader)) return 0;
  70. llvm::OwningPtr<const llvm::MemoryBuffer> FileBuffer(
  71. FM.getBufferForFile(FE, FSOpts));
  72. if (FileBuffer == 0) return 0; // Unreadable file?
  73. const char *FileStart = FileBuffer->getBufferStart();
  74. // We know the file is at least as big as the header, check it now.
  75. const HMapHeader *Header = reinterpret_cast<const HMapHeader*>(FileStart);
  76. // Sniff it to see if it's a headermap by checking the magic number and
  77. // version.
  78. bool NeedsByteSwap;
  79. if (Header->Magic == HMAP_HeaderMagicNumber &&
  80. Header->Version == HMAP_HeaderVersion)
  81. NeedsByteSwap = false;
  82. else if (Header->Magic == llvm::ByteSwap_32(HMAP_HeaderMagicNumber) &&
  83. Header->Version == llvm::ByteSwap_16(HMAP_HeaderVersion))
  84. NeedsByteSwap = true; // Mixed endianness headermap.
  85. else
  86. return 0; // Not a header map.
  87. if (Header->Reserved != 0) return 0;
  88. // Okay, everything looks good, create the header map.
  89. return new HeaderMap(FileBuffer.take(), NeedsByteSwap);
  90. }
  91. HeaderMap::~HeaderMap() {
  92. delete FileBuffer;
  93. }
  94. //===----------------------------------------------------------------------===//
  95. // Utility Methods
  96. //===----------------------------------------------------------------------===//
  97. /// getFileName - Return the filename of the headermap.
  98. const char *HeaderMap::getFileName() const {
  99. return FileBuffer->getBufferIdentifier();
  100. }
  101. unsigned HeaderMap::getEndianAdjustedWord(unsigned X) const {
  102. if (!NeedsBSwap) return X;
  103. return llvm::ByteSwap_32(X);
  104. }
  105. /// getHeader - Return a reference to the file header, in unbyte-swapped form.
  106. /// This method cannot fail.
  107. const HMapHeader &HeaderMap::getHeader() const {
  108. // We know the file is at least as big as the header. Return it.
  109. return *reinterpret_cast<const HMapHeader*>(FileBuffer->getBufferStart());
  110. }
  111. /// getBucket - Return the specified hash table bucket from the header map,
  112. /// bswap'ing its fields as appropriate. If the bucket number is not valid,
  113. /// this return a bucket with an empty key (0).
  114. HMapBucket HeaderMap::getBucket(unsigned BucketNo) const {
  115. HMapBucket Result;
  116. Result.Key = HMAP_EmptyBucketKey;
  117. const HMapBucket *BucketArray =
  118. reinterpret_cast<const HMapBucket*>(FileBuffer->getBufferStart() +
  119. sizeof(HMapHeader));
  120. const HMapBucket *BucketPtr = BucketArray+BucketNo;
  121. if ((char*)(BucketPtr+1) > FileBuffer->getBufferEnd()) {
  122. Result.Prefix = 0;
  123. Result.Suffix = 0;
  124. return Result; // Invalid buffer, corrupt hmap.
  125. }
  126. // Otherwise, the bucket is valid. Load the values, bswapping as needed.
  127. Result.Key = getEndianAdjustedWord(BucketPtr->Key);
  128. Result.Prefix = getEndianAdjustedWord(BucketPtr->Prefix);
  129. Result.Suffix = getEndianAdjustedWord(BucketPtr->Suffix);
  130. return Result;
  131. }
  132. /// getString - Look up the specified string in the string table. If the string
  133. /// index is not valid, it returns an empty string.
  134. const char *HeaderMap::getString(unsigned StrTabIdx) const {
  135. // Add the start of the string table to the idx.
  136. StrTabIdx += getEndianAdjustedWord(getHeader().StringsOffset);
  137. // Check for invalid index.
  138. if (StrTabIdx >= FileBuffer->getBufferSize())
  139. return 0;
  140. // Otherwise, we have a valid pointer into the file. Just return it. We know
  141. // that the "string" can not overrun the end of the file, because the buffer
  142. // is nul terminated by virtue of being a MemoryBuffer.
  143. return FileBuffer->getBufferStart()+StrTabIdx;
  144. }
  145. //===----------------------------------------------------------------------===//
  146. // The Main Drivers
  147. //===----------------------------------------------------------------------===//
  148. /// dump - Print the contents of this headermap to stderr.
  149. void HeaderMap::dump() const {
  150. const HMapHeader &Hdr = getHeader();
  151. unsigned NumBuckets = getEndianAdjustedWord(Hdr.NumBuckets);
  152. fprintf(stderr, "Header Map %s:\n %d buckets, %d entries\n",
  153. getFileName(), NumBuckets,
  154. getEndianAdjustedWord(Hdr.NumEntries));
  155. for (unsigned i = 0; i != NumBuckets; ++i) {
  156. HMapBucket B = getBucket(i);
  157. if (B.Key == HMAP_EmptyBucketKey) continue;
  158. const char *Key = getString(B.Key);
  159. const char *Prefix = getString(B.Prefix);
  160. const char *Suffix = getString(B.Suffix);
  161. fprintf(stderr, " %d. %s -> '%s' '%s'\n", i, Key, Prefix, Suffix);
  162. }
  163. }
  164. /// LookupFile - Check to see if the specified relative filename is located in
  165. /// this HeaderMap. If so, open it and return its FileEntry.
  166. const FileEntry *HeaderMap::LookupFile(llvm::StringRef Filename,
  167. FileManager &FM,
  168. const FileSystemOptions &FileSystemOpts) const {
  169. const HMapHeader &Hdr = getHeader();
  170. unsigned NumBuckets = getEndianAdjustedWord(Hdr.NumBuckets);
  171. // If the number of buckets is not a power of two, the headermap is corrupt.
  172. // Don't probe infinitely.
  173. if (NumBuckets & (NumBuckets-1))
  174. return 0;
  175. // Linearly probe the hash table.
  176. for (unsigned Bucket = HashHMapKey(Filename);; ++Bucket) {
  177. HMapBucket B = getBucket(Bucket & (NumBuckets-1));
  178. if (B.Key == HMAP_EmptyBucketKey) return 0; // Hash miss.
  179. // See if the key matches. If not, probe on.
  180. if (!Filename.equals_lower(getString(B.Key)))
  181. continue;
  182. // If so, we have a match in the hash table. Construct the destination
  183. // path.
  184. llvm::SmallString<1024> DestPath;
  185. DestPath += getString(B.Prefix);
  186. DestPath += getString(B.Suffix);
  187. return FM.getFile(DestPath.begin(), DestPath.end(), FileSystemOpts);
  188. }
  189. }