1 //===--- HeaderMap.cpp - A file that acts like dir of symlinks ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the HeaderMap interface.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Lex/HeaderMap.h"
15 #include "clang/Lex/HeaderMapTypes.h"
16 #include "clang/Basic/CharInfo.h"
17 #include "clang/Basic/FileManager.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/Support/Compiler.h"
20 #include "llvm/Support/DataTypes.h"
21 #include "llvm/Support/MathExtras.h"
22 #include "llvm/Support/MemoryBuffer.h"
23 #include "llvm/Support/SwapByteOrder.h"
24 #include "llvm/Support/Debug.h"
27 using namespace clang;
29 /// HashHMapKey - This is the 'well known' hash function required by the file
30 /// format, used to look up keys in the hash table. The hash table uses simple
31 /// linear probing based on this function.
32 static inline unsigned HashHMapKey(StringRef Str) {
34 const char *S = Str.begin(), *End = Str.end();
37 Result += toLowercase(*S) * 13;
43 //===----------------------------------------------------------------------===//
44 // Verification and Construction
45 //===----------------------------------------------------------------------===//
47 /// HeaderMap::Create - This attempts to load the specified file as a header
48 /// map. If it doesn't look like a HeaderMap, it gives up and returns null.
49 /// If it looks like a HeaderMap but is obviously corrupted, it puts a reason
50 /// into the string error argument and returns null.
51 std::unique_ptr<HeaderMap> HeaderMap::Create(const FileEntry *FE,
53 // If the file is too small to be a header map, ignore it.
54 unsigned FileSize = FE->getSize();
55 if (FileSize <= sizeof(HMapHeader)) return nullptr;
57 auto FileBuffer = FM.getBufferForFile(FE);
58 if (!FileBuffer || !*FileBuffer)
61 if (!checkHeader(**FileBuffer, NeedsByteSwap))
63 return std::unique_ptr<HeaderMap>(new HeaderMap(std::move(*FileBuffer), NeedsByteSwap));
66 bool HeaderMapImpl::checkHeader(const llvm::MemoryBuffer &File,
67 bool &NeedsByteSwap) {
68 if (File.getBufferSize() <= sizeof(HMapHeader))
70 const char *FileStart = File.getBufferStart();
72 // We know the file is at least as big as the header, check it now.
73 const HMapHeader *Header = reinterpret_cast<const HMapHeader*>(FileStart);
75 // Sniff it to see if it's a headermap by checking the magic number and
77 if (Header->Magic == HMAP_HeaderMagicNumber &&
78 Header->Version == HMAP_HeaderVersion)
79 NeedsByteSwap = false;
80 else if (Header->Magic == llvm::ByteSwap_32(HMAP_HeaderMagicNumber) &&
81 Header->Version == llvm::ByteSwap_16(HMAP_HeaderVersion))
82 NeedsByteSwap = true; // Mixed endianness headermap.
84 return false; // Not a header map.
86 if (Header->Reserved != 0)
89 // Check the number of buckets. It should be a power of two, and there
90 // should be enough space in the file for all of them.
91 uint32_t NumBuckets = NeedsByteSwap
92 ? llvm::sys::getSwappedBytes(Header->NumBuckets)
94 if (!llvm::isPowerOf2_32(NumBuckets))
96 if (File.getBufferSize() <
97 sizeof(HMapHeader) + sizeof(HMapBucket) * NumBuckets)
100 // Okay, everything looks good.
104 //===----------------------------------------------------------------------===//
106 //===----------------------------------------------------------------------===//
109 /// getFileName - Return the filename of the headermap.
110 StringRef HeaderMapImpl::getFileName() const {
111 return FileBuffer->getBufferIdentifier();
114 unsigned HeaderMapImpl::getEndianAdjustedWord(unsigned X) const {
115 if (!NeedsBSwap) return X;
116 return llvm::ByteSwap_32(X);
119 /// getHeader - Return a reference to the file header, in unbyte-swapped form.
120 /// This method cannot fail.
121 const HMapHeader &HeaderMapImpl::getHeader() const {
122 // We know the file is at least as big as the header. Return it.
123 return *reinterpret_cast<const HMapHeader*>(FileBuffer->getBufferStart());
126 /// getBucket - Return the specified hash table bucket from the header map,
127 /// bswap'ing its fields as appropriate. If the bucket number is not valid,
128 /// this return a bucket with an empty key (0).
129 HMapBucket HeaderMapImpl::getBucket(unsigned BucketNo) const {
130 assert(FileBuffer->getBufferSize() >=
131 sizeof(HMapHeader) + sizeof(HMapBucket) * BucketNo &&
132 "Expected bucket to be in range");
135 Result.Key = HMAP_EmptyBucketKey;
137 const HMapBucket *BucketArray =
138 reinterpret_cast<const HMapBucket*>(FileBuffer->getBufferStart() +
140 const HMapBucket *BucketPtr = BucketArray+BucketNo;
142 // Load the values, bswapping as needed.
143 Result.Key = getEndianAdjustedWord(BucketPtr->Key);
144 Result.Prefix = getEndianAdjustedWord(BucketPtr->Prefix);
145 Result.Suffix = getEndianAdjustedWord(BucketPtr->Suffix);
149 Optional<StringRef> HeaderMapImpl::getString(unsigned StrTabIdx) const {
150 // Add the start of the string table to the idx.
151 StrTabIdx += getEndianAdjustedWord(getHeader().StringsOffset);
153 // Check for invalid index.
154 if (StrTabIdx >= FileBuffer->getBufferSize())
157 const char *Data = FileBuffer->getBufferStart() + StrTabIdx;
158 unsigned MaxLen = FileBuffer->getBufferSize() - StrTabIdx;
159 unsigned Len = strnlen(Data, MaxLen);
161 // Check whether the buffer is null-terminated.
162 if (Len == MaxLen && Data[Len - 1])
165 return StringRef(Data, Len);
168 //===----------------------------------------------------------------------===//
170 //===----------------------------------------------------------------------===//
172 /// dump - Print the contents of this headermap to stderr.
173 LLVM_DUMP_METHOD void HeaderMapImpl::dump() const {
174 const HMapHeader &Hdr = getHeader();
175 unsigned NumBuckets = getEndianAdjustedWord(Hdr.NumBuckets);
177 llvm::dbgs() << "Header Map " << getFileName() << ":\n " << NumBuckets
178 << ", " << getEndianAdjustedWord(Hdr.NumEntries) << "\n";
180 auto getStringOrInvalid = [this](unsigned Id) -> StringRef {
181 if (Optional<StringRef> S = getString(Id))
186 for (unsigned i = 0; i != NumBuckets; ++i) {
187 HMapBucket B = getBucket(i);
188 if (B.Key == HMAP_EmptyBucketKey) continue;
190 StringRef Key = getStringOrInvalid(B.Key);
191 StringRef Prefix = getStringOrInvalid(B.Prefix);
192 StringRef Suffix = getStringOrInvalid(B.Suffix);
193 llvm::dbgs() << " " << i << ". " << Key << " -> '" << Prefix << "' '"
198 /// LookupFile - Check to see if the specified relative filename is located in
199 /// this HeaderMap. If so, open it and return its FileEntry.
200 const FileEntry *HeaderMap::LookupFile(
201 StringRef Filename, FileManager &FM) const {
203 SmallString<1024> Path;
204 StringRef Dest = HeaderMapImpl::lookupFilename(Filename, Path);
208 return FM.getFile(Dest);
211 StringRef HeaderMapImpl::lookupFilename(StringRef Filename,
212 SmallVectorImpl<char> &DestPath) const {
213 const HMapHeader &Hdr = getHeader();
214 unsigned NumBuckets = getEndianAdjustedWord(Hdr.NumBuckets);
216 // Don't probe infinitely. This should be checked before constructing.
217 assert(llvm::isPowerOf2_32(NumBuckets) && "Expected power of 2");
219 // Linearly probe the hash table.
220 for (unsigned Bucket = HashHMapKey(Filename);; ++Bucket) {
221 HMapBucket B = getBucket(Bucket & (NumBuckets-1));
222 if (B.Key == HMAP_EmptyBucketKey) return StringRef(); // Hash miss.
224 // See if the key matches. If not, probe on.
225 Optional<StringRef> Key = getString(B.Key);
226 if (LLVM_UNLIKELY(!Key))
228 if (!Filename.equals_lower(*Key))
231 // If so, we have a match in the hash table. Construct the destination
233 Optional<StringRef> Prefix = getString(B.Prefix);
234 Optional<StringRef> Suffix = getString(B.Suffix);
237 if (LLVM_LIKELY(Prefix && Suffix)) {
238 DestPath.append(Prefix->begin(), Prefix->end());
239 DestPath.append(Suffix->begin(), Suffix->end());
241 return StringRef(DestPath.begin(), DestPath.size());