HeaderMap.cpp 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  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/Lex/HeaderMapTypes.h"
  15. #include "clang/Basic/CharInfo.h"
  16. #include "clang/Basic/FileManager.h"
  17. #include "llvm/ADT/SmallString.h"
  18. #include "llvm/Support/DataTypes.h"
  19. #include "llvm/Support/MathExtras.h"
  20. #include "llvm/Support/MemoryBuffer.h"
  21. #include "llvm/Support/SwapByteOrder.h"
  22. #include "llvm/Support/Debug.h"
  23. #include <cstring>
  24. #include <memory>
  25. using namespace clang;
  26. /// HashHMapKey - This is the 'well known' hash function required by the file
  27. /// format, used to look up keys in the hash table. The hash table uses simple
  28. /// linear probing based on this function.
  29. static inline unsigned HashHMapKey(StringRef Str) {
  30. unsigned Result = 0;
  31. const char *S = Str.begin(), *End = Str.end();
  32. for (; S != End; S++)
  33. Result += toLowercase(*S) * 13;
  34. return Result;
  35. }
  36. //===----------------------------------------------------------------------===//
  37. // Verification and Construction
  38. //===----------------------------------------------------------------------===//
  39. /// HeaderMap::Create - This attempts to load the specified file as a header
  40. /// map. If it doesn't look like a HeaderMap, it gives up and returns null.
  41. /// If it looks like a HeaderMap but is obviously corrupted, it puts a reason
  42. /// into the string error argument and returns null.
  43. const HeaderMap *HeaderMap::Create(const FileEntry *FE, FileManager &FM) {
  44. // If the file is too small to be a header map, ignore it.
  45. unsigned FileSize = FE->getSize();
  46. if (FileSize <= sizeof(HMapHeader)) return nullptr;
  47. auto FileBuffer = FM.getBufferForFile(FE);
  48. if (!FileBuffer || !*FileBuffer)
  49. return nullptr;
  50. bool NeedsByteSwap;
  51. if (!checkHeader(**FileBuffer, NeedsByteSwap))
  52. return nullptr;
  53. return new HeaderMap(std::move(*FileBuffer), NeedsByteSwap);
  54. }
  55. bool HeaderMapImpl::checkHeader(const llvm::MemoryBuffer &File,
  56. bool &NeedsByteSwap) {
  57. if (File.getBufferSize() <= sizeof(HMapHeader))
  58. return false;
  59. const char *FileStart = File.getBufferStart();
  60. // We know the file is at least as big as the header, check it now.
  61. const HMapHeader *Header = reinterpret_cast<const HMapHeader*>(FileStart);
  62. // Sniff it to see if it's a headermap by checking the magic number and
  63. // version.
  64. if (Header->Magic == HMAP_HeaderMagicNumber &&
  65. Header->Version == HMAP_HeaderVersion)
  66. NeedsByteSwap = false;
  67. else if (Header->Magic == llvm::ByteSwap_32(HMAP_HeaderMagicNumber) &&
  68. Header->Version == llvm::ByteSwap_16(HMAP_HeaderVersion))
  69. NeedsByteSwap = true; // Mixed endianness headermap.
  70. else
  71. return false; // Not a header map.
  72. if (Header->Reserved != 0)
  73. return false;
  74. // Check the number of buckets. It should be a power of two, and there
  75. // should be enough space in the file for all of them.
  76. auto NumBuckets = NeedsByteSwap
  77. ? llvm::sys::getSwappedBytes(Header->NumBuckets)
  78. : Header->NumBuckets;
  79. if (NumBuckets & (NumBuckets - 1))
  80. return false;
  81. if (File.getBufferSize() <
  82. sizeof(HMapHeader) + sizeof(HMapBucket) * NumBuckets)
  83. return false;
  84. // Okay, everything looks good.
  85. return true;
  86. }
  87. //===----------------------------------------------------------------------===//
  88. // Utility Methods
  89. //===----------------------------------------------------------------------===//
  90. /// getFileName - Return the filename of the headermap.
  91. const char *HeaderMapImpl::getFileName() const {
  92. return FileBuffer->getBufferIdentifier();
  93. }
  94. unsigned HeaderMapImpl::getEndianAdjustedWord(unsigned X) const {
  95. if (!NeedsBSwap) return X;
  96. return llvm::ByteSwap_32(X);
  97. }
  98. /// getHeader - Return a reference to the file header, in unbyte-swapped form.
  99. /// This method cannot fail.
  100. const HMapHeader &HeaderMapImpl::getHeader() const {
  101. // We know the file is at least as big as the header. Return it.
  102. return *reinterpret_cast<const HMapHeader*>(FileBuffer->getBufferStart());
  103. }
  104. /// getBucket - Return the specified hash table bucket from the header map,
  105. /// bswap'ing its fields as appropriate. If the bucket number is not valid,
  106. /// this return a bucket with an empty key (0).
  107. HMapBucket HeaderMapImpl::getBucket(unsigned BucketNo) const {
  108. assert(FileBuffer->getBufferSize() >=
  109. sizeof(HMapHeader) + sizeof(HMapBucket) * BucketNo &&
  110. "Expected bucket to be in range");
  111. HMapBucket Result;
  112. Result.Key = HMAP_EmptyBucketKey;
  113. const HMapBucket *BucketArray =
  114. reinterpret_cast<const HMapBucket*>(FileBuffer->getBufferStart() +
  115. sizeof(HMapHeader));
  116. const HMapBucket *BucketPtr = BucketArray+BucketNo;
  117. // Load the values, bswapping as needed.
  118. Result.Key = getEndianAdjustedWord(BucketPtr->Key);
  119. Result.Prefix = getEndianAdjustedWord(BucketPtr->Prefix);
  120. Result.Suffix = getEndianAdjustedWord(BucketPtr->Suffix);
  121. return Result;
  122. }
  123. /// getString - Look up the specified string in the string table. If the string
  124. /// index is not valid, it returns an empty string.
  125. StringRef HeaderMapImpl::getString(unsigned StrTabIdx) const {
  126. // Add the start of the string table to the idx.
  127. StrTabIdx += getEndianAdjustedWord(getHeader().StringsOffset);
  128. // Check for invalid index.
  129. if (StrTabIdx >= FileBuffer->getBufferSize())
  130. return "";
  131. const char *Data = FileBuffer->getBufferStart() + StrTabIdx;
  132. unsigned MaxLen = FileBuffer->getBufferSize() - StrTabIdx;
  133. unsigned Len = strnlen(Data, MaxLen);
  134. // Check whether the buffer is null-terminated.
  135. if (Len == MaxLen && Data[Len - 1])
  136. return "";
  137. return StringRef(Data, Len);
  138. }
  139. //===----------------------------------------------------------------------===//
  140. // The Main Drivers
  141. //===----------------------------------------------------------------------===//
  142. /// dump - Print the contents of this headermap to stderr.
  143. LLVM_DUMP_METHOD void HeaderMapImpl::dump() const {
  144. const HMapHeader &Hdr = getHeader();
  145. unsigned NumBuckets = getEndianAdjustedWord(Hdr.NumBuckets);
  146. llvm::dbgs() << "Header Map " << getFileName() << ":\n " << NumBuckets
  147. << ", " << getEndianAdjustedWord(Hdr.NumEntries) << "\n";
  148. for (unsigned i = 0; i != NumBuckets; ++i) {
  149. HMapBucket B = getBucket(i);
  150. if (B.Key == HMAP_EmptyBucketKey) continue;
  151. StringRef Key = getString(B.Key);
  152. StringRef Prefix = getString(B.Prefix);
  153. StringRef Suffix = getString(B.Suffix);
  154. llvm::dbgs() << " " << i << ". " << Key << " -> '" << Prefix << "' '"
  155. << Suffix << "'\n";
  156. }
  157. }
  158. /// LookupFile - Check to see if the specified relative filename is located in
  159. /// this HeaderMap. If so, open it and return its FileEntry.
  160. const FileEntry *HeaderMap::LookupFile(
  161. StringRef Filename, FileManager &FM) const {
  162. SmallString<1024> Path;
  163. StringRef Dest = HeaderMapImpl::lookupFilename(Filename, Path);
  164. if (Dest.empty())
  165. return nullptr;
  166. return FM.getFile(Dest);
  167. }
  168. StringRef HeaderMapImpl::lookupFilename(StringRef Filename,
  169. SmallVectorImpl<char> &DestPath) const {
  170. const HMapHeader &Hdr = getHeader();
  171. unsigned NumBuckets = getEndianAdjustedWord(Hdr.NumBuckets);
  172. // Don't probe infinitely. This should be checked before constructing.
  173. assert(!(NumBuckets & (NumBuckets - 1)) && "Expected power of 2");
  174. // Linearly probe the hash table.
  175. for (unsigned Bucket = HashHMapKey(Filename);; ++Bucket) {
  176. HMapBucket B = getBucket(Bucket & (NumBuckets-1));
  177. if (B.Key == HMAP_EmptyBucketKey) return StringRef(); // Hash miss.
  178. // See if the key matches. If not, probe on.
  179. if (!Filename.equals_lower(getString(B.Key)))
  180. continue;
  181. // If so, we have a match in the hash table. Construct the destination
  182. // path.
  183. StringRef Prefix = getString(B.Prefix);
  184. StringRef Suffix = getString(B.Suffix);
  185. DestPath.clear();
  186. DestPath.append(Prefix.begin(), Prefix.end());
  187. DestPath.append(Suffix.begin(), Suffix.end());
  188. return StringRef(DestPath.begin(), DestPath.size());
  189. }
  190. }