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