1 //===-- Serialization.cpp - Binary serialization of index data ------------===//
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 #include "Serialization.h"
10 #include "Index.h"
11 #include "RIFF.h"
12 #include "llvm/Support/Compression.h"
13 #include "llvm/Support/Endian.h"
14 #include "llvm/Support/Error.h"
15 
16 using namespace llvm;
17 namespace clang {
18 namespace clangd {
19 namespace {
20 Error makeError(const Twine &Msg) {
21   return make_error<StringError>(Msg, inconvertibleErrorCode());
22 }
23 
24 // IO PRIMITIVES
25 // We use little-endian 32 bit ints, sometimes with variable-length encoding.
26 
27 StringRef consume(StringRef &Data, int N) {
28   StringRef Ret = Data.take_front(N);
29   Data = Data.drop_front(N);
30   return Ret;
31 }
32 
33 uint8_t consume8(StringRef &Data) {
34   uint8_t Ret = Data.front();
35   Data = Data.drop_front();
36   return Ret;
37 }
38 
39 uint32_t consume32(StringRef &Data) {
40   auto Ret = support::endian::read32le(Data.bytes_begin());
41   Data = Data.drop_front(4);
42   return Ret;
43 }
44 
45 void write32(uint32_t I, raw_ostream &OS) {
46   char buf[4];
47   support::endian::write32le(buf, I);
48   OS.write(buf, sizeof(buf));
49 }
50 
51 // Variable-length int encoding (varint) uses the bottom 7 bits of each byte
52 // to encode the number, and the top bit to indicate whether more bytes follow.
53 // e.g. 9a 2f means [0x1a and keep reading, 0x2f and stop].
54 // This represents 0x1a | 0x2f<<7 = 6042.
55 // A 32-bit integer takes 1-5 bytes to encode; small numbers are more compact.
56 void writeVar(uint32_t I, raw_ostream &OS) {
57   constexpr static uint8_t More = 1 << 7;
58   if (LLVM_LIKELY(I < 1 << 7)) {
59     OS.write(I);
60     return;
61   }
62   for (;;) {
63     OS.write(I | More);
64     I >>= 7;
65     if (I < 1 << 7) {
66       OS.write(I);
67       return;
68     }
69   }
70 }
71 
72 uint32_t consumeVar(StringRef &Data) {
73   constexpr static uint8_t More = 1 << 7;
74   uint8_t B = consume8(Data);
75   if (LLVM_LIKELY(!(B & More)))
76     return B;
77   uint32_t Val = B & ~More;
78   for (int Shift = 7; B & More && Shift < 32; Shift += 7) {
79     B = consume8(Data);
80     Val |= (B & ~More) << Shift;
81   }
82   return Val;
83 }
84 
85 // STRING TABLE ENCODING
86 // Index data has many string fields, and many strings are identical.
87 // We store each string once, and refer to them by index.
88 //
89 // The string table's format is:
90 //   - UncompressedSize : uint32 (or 0 for no compression)
91 //   - CompressedData   : byte[CompressedSize]
92 //
93 // CompressedData is a zlib-compressed byte[UncompressedSize].
94 // It contains a sequence of null-terminated strings, e.g. "foo\0bar\0".
95 // These are sorted to improve compression.
96 
97 // Maps each string to a canonical representation.
98 // Strings remain owned externally (e.g. by SymbolSlab).
99 class StringTableOut {
100   DenseSet<StringRef> Unique;
101   std::vector<StringRef> Sorted;
102   // Since strings are interned, look up can be by pointer.
103   DenseMap<std::pair<const char *, size_t>, unsigned> Index;
104 
105 public:
106   StringTableOut() {
107     // Ensure there's at least one string in the table.
108     // Table size zero is reserved to indicate no compression.
109     Unique.insert("");
110   }
111   // Add a string to the table. Overwrites S if an identical string exists.
112   void intern(StringRef &S) { S = *Unique.insert(S).first; };
113   // Finalize the table and write it to OS. No more strings may be added.
114   void finalize(raw_ostream &OS) {
115     Sorted = {Unique.begin(), Unique.end()};
116     std::sort(Sorted.begin(), Sorted.end());
117     for (unsigned I = 0; I < Sorted.size(); ++I)
118       Index.try_emplace({Sorted[I].data(), Sorted[I].size()}, I);
119 
120     std::string RawTable;
121     for (StringRef S : Sorted) {
122       RawTable.append(S);
123       RawTable.push_back(0);
124     }
125     if (zlib::isAvailable()) {
126       SmallString<1> Compressed;
127       cantFail(zlib::compress(RawTable, Compressed));
128       write32(RawTable.size(), OS);
129       OS << Compressed;
130     } else {
131       write32(0, OS); // No compression.
132       OS << RawTable;
133     }
134   }
135   // Get the ID of an string, which must be interned. Table must be finalized.
136   unsigned index(StringRef S) const {
137     assert(!Sorted.empty() && "table not finalized");
138     assert(Index.count({S.data(), S.size()}) && "string not interned");
139     return Index.find({S.data(), S.size()})->second;
140   }
141 };
142 
143 struct StringTableIn {
144   BumpPtrAllocator Arena;
145   std::vector<StringRef> Strings;
146 };
147 
148 Expected<StringTableIn> readStringTable(StringRef Data) {
149   if (Data.size() < 4)
150     return makeError("Bad string table: not enough metadata");
151   size_t UncompressedSize = consume32(Data);
152 
153   StringRef Uncompressed;
154   SmallString<1> UncompressedStorage;
155   if (UncompressedSize == 0) // No compression
156     Uncompressed = Data;
157   else {
158     if (Error E =
159             llvm::zlib::uncompress(Data, UncompressedStorage, UncompressedSize))
160       return std::move(E);
161     Uncompressed = UncompressedStorage;
162   }
163 
164   StringTableIn Table;
165   StringSaver Saver(Table.Arena);
166   for (StringRef Rest = Uncompressed; !Rest.empty();) {
167     auto Len = Rest.find(0);
168     if (Len == StringRef::npos)
169       return makeError("Bad string table: not null terminated");
170     Table.Strings.push_back(Saver.save(consume(Rest, Len)));
171     Rest = Rest.drop_front();
172   }
173   return std::move(Table);
174 }
175 
176 // SYMBOL ENCODING
177 // Each field of clangd::Symbol is encoded in turn (see implementation).
178 //  - StringRef fields encode as varint (index into the string table)
179 //  - enums encode as the underlying type
180 //  - most numbers encode as varint
181 
182 // It's useful to the implementation to assume symbols have a bounded size.
183 constexpr size_t SymbolSizeBound = 512;
184 // To ensure the bounded size, restrict the number of include headers stored.
185 constexpr unsigned MaxIncludes = 50;
186 
187 void writeSymbol(const Symbol &Sym, const StringTableOut &Strings,
188                  raw_ostream &OS) {
189   auto StartOffset = OS.tell();
190   OS << Sym.ID.raw(); // TODO: once we start writing xrefs and posting lists,
191                       // symbol IDs should probably be in a string table.
192   OS.write(static_cast<uint8_t>(Sym.SymInfo.Kind));
193   OS.write(static_cast<uint8_t>(Sym.SymInfo.Lang));
194   writeVar(Strings.index(Sym.Name), OS);
195   writeVar(Strings.index(Sym.Scope), OS);
196   for (const auto &Loc : {Sym.Definition, Sym.CanonicalDeclaration}) {
197     writeVar(Strings.index(Loc.FileURI), OS);
198     for (const auto &Endpoint : {Loc.Start, Loc.End}) {
199       writeVar(Endpoint.Line, OS);
200       writeVar(Endpoint.Column, OS);
201     }
202   }
203   writeVar(Sym.References, OS);
204   OS.write(static_cast<uint8_t>(Sym.Flags));
205   OS.write(static_cast<uint8_t>(Sym.Origin));
206   writeVar(Strings.index(Sym.Signature), OS);
207   writeVar(Strings.index(Sym.CompletionSnippetSuffix), OS);
208   writeVar(Strings.index(Sym.Documentation), OS);
209   writeVar(Strings.index(Sym.ReturnType), OS);
210 
211   auto WriteInclude = [&](const Symbol::IncludeHeaderWithReferences &Include) {
212     writeVar(Strings.index(Include.IncludeHeader), OS);
213     writeVar(Include.References, OS);
214   };
215   // There are almost certainly few includes, so we can just write them.
216   if (LLVM_LIKELY(Sym.IncludeHeaders.size() <= MaxIncludes)) {
217     writeVar(Sym.IncludeHeaders.size(), OS);
218     for (const auto &Include : Sym.IncludeHeaders)
219       WriteInclude(Include);
220   } else {
221     // If there are too many, make sure we truncate the least important.
222     using Pointer = const Symbol::IncludeHeaderWithReferences *;
223     std::vector<Pointer> Pointers;
224     for (const auto &Include : Sym.IncludeHeaders)
225       Pointers.push_back(&Include);
226     std::sort(Pointers.begin(), Pointers.end(), [](Pointer L, Pointer R) {
227       return L->References > R->References;
228     });
229     Pointers.resize(MaxIncludes);
230 
231     writeVar(MaxIncludes, OS);
232     for (Pointer P : Pointers)
233       WriteInclude(*P);
234   }
235 
236   assert(OS.tell() - StartOffset < SymbolSizeBound && "Symbol length unsafe!");
237   (void)StartOffset; // Unused in NDEBUG;
238 }
239 
240 Expected<Symbol> readSymbol(StringRef &Data, const StringTableIn &Strings) {
241   // Usually we can skip bounds checks because the buffer is huge.
242   // Near the end of the buffer, this would be unsafe. In this rare case, copy
243   // the data into a bigger buffer so we can again skip the checks.
244   if (LLVM_UNLIKELY(Data.size() < SymbolSizeBound)) {
245     std::string Buf(Data);
246     Buf.resize(SymbolSizeBound);
247     StringRef ExtendedData = Buf;
248     auto Ret = readSymbol(ExtendedData, Strings);
249     unsigned BytesRead = Buf.size() - ExtendedData.size();
250     if (BytesRead > Data.size())
251       return makeError("read past end of data");
252     Data = Data.drop_front(BytesRead);
253     return Ret;
254   }
255 
256 #define READ_STRING(Field)                                                     \
257   do {                                                                         \
258     auto StringIndex = consumeVar(Data);                                       \
259     if (LLVM_UNLIKELY(StringIndex >= Strings.Strings.size()))                  \
260       return makeError("Bad string index");                                    \
261     Field = Strings.Strings[StringIndex];                                      \
262   } while (0)
263 
264   Symbol Sym;
265   Sym.ID = SymbolID::fromRaw(consume(Data, 20));
266   Sym.SymInfo.Kind = static_cast<index::SymbolKind>(consume8(Data));
267   Sym.SymInfo.Lang = static_cast<index::SymbolLanguage>(consume8(Data));
268   READ_STRING(Sym.Name);
269   READ_STRING(Sym.Scope);
270   for (SymbolLocation *Loc : {&Sym.Definition, &Sym.CanonicalDeclaration}) {
271     READ_STRING(Loc->FileURI);
272     for (auto &Endpoint : {&Loc->Start, &Loc->End}) {
273       Endpoint->Line = consumeVar(Data);
274       Endpoint->Column = consumeVar(Data);
275     }
276   }
277   Sym.References = consumeVar(Data);
278   Sym.Flags = static_cast<Symbol::SymbolFlag>(consume8(Data));
279   Sym.Origin = static_cast<SymbolOrigin>(consume8(Data));
280   READ_STRING(Sym.Signature);
281   READ_STRING(Sym.CompletionSnippetSuffix);
282   READ_STRING(Sym.Documentation);
283   READ_STRING(Sym.ReturnType);
284   unsigned IncludeHeaderN = consumeVar(Data);
285   if (IncludeHeaderN > MaxIncludes)
286     return makeError("too many IncludeHeaders");
287   Sym.IncludeHeaders.resize(IncludeHeaderN);
288   for (auto &I : Sym.IncludeHeaders) {
289     READ_STRING(I.IncludeHeader);
290     I.References = consumeVar(Data);
291   }
292 
293 #undef READ_STRING
294   return std::move(Sym);
295 }
296 
297 } // namespace
298 
299 // FILE ENCODING
300 // A file is a RIFF chunk with type 'CdIx'.
301 // It contains the sections:
302 //   - meta: version number
303 //   - stri: string table
304 //   - symb: symbols
305 
306 // The current versioning scheme is simple - non-current versions are rejected.
307 // If you make a breaking change, bump this version number to invalidate stored
308 // data. Later we may want to support some backward compatibility.
309 constexpr static uint32_t Version = 3;
310 
311 Expected<IndexFileIn> readIndexFile(StringRef Data) {
312   auto RIFF = riff::readFile(Data);
313   if (!RIFF)
314     return RIFF.takeError();
315   if (RIFF->Type != riff::fourCC("CdIx"))
316     return makeError("wrong RIFF type");
317   StringMap<StringRef> Chunks;
318   for (const auto &Chunk : RIFF->Chunks)
319     Chunks.try_emplace(StringRef(Chunk.ID.data(), Chunk.ID.size()), Chunk.Data);
320 
321   for (StringRef RequiredChunk : {"meta", "stri"})
322     if (!Chunks.count(RequiredChunk))
323       return makeError("missing required chunk " + RequiredChunk);
324 
325   StringRef Meta = Chunks.lookup("meta");
326   if (Meta.size() < 4 || consume32(Meta) != Version)
327     return makeError("wrong version");
328 
329   auto Strings = readStringTable(Chunks.lookup("stri"));
330   if (!Strings)
331     return Strings.takeError();
332 
333   IndexFileIn Result;
334   if (Chunks.count("symb")) {
335     StringRef SymbolData = Chunks.lookup("symb");
336     SymbolSlab::Builder Symbols;
337     while (!SymbolData.empty())
338       if (auto Sym = readSymbol(SymbolData, *Strings))
339         Symbols.insert(*Sym);
340       else
341         return Sym.takeError();
342     Result.Symbols = std::move(Symbols).build();
343   }
344   return std::move(Result);
345 }
346 
347 raw_ostream &operator<<(raw_ostream &OS, const IndexFileOut &Data) {
348   assert(Data.Symbols && "An index file without symbols makes no sense!");
349   riff::File RIFF;
350   RIFF.Type = riff::fourCC("CdIx");
351 
352   SmallString<4> Meta;
353   {
354     raw_svector_ostream MetaOS(Meta);
355     write32(Version, MetaOS);
356   }
357   RIFF.Chunks.push_back({riff::fourCC("meta"), Meta});
358 
359   StringTableOut Strings;
360   std::vector<Symbol> Symbols;
361   for (const auto &Sym : *Data.Symbols) {
362     Symbols.emplace_back(Sym);
363     visitStrings(Symbols.back(), [&](StringRef &S) { Strings.intern(S); });
364   }
365 
366   std::string StringSection;
367   {
368     raw_string_ostream StringOS(StringSection);
369     Strings.finalize(StringOS);
370   }
371   RIFF.Chunks.push_back({riff::fourCC("stri"), StringSection});
372 
373   std::string SymbolSection;
374   {
375     raw_string_ostream SymbolOS(SymbolSection);
376     for (const auto &Sym : Symbols)
377       writeSymbol(Sym, Strings, SymbolOS);
378   }
379   RIFF.Chunks.push_back({riff::fourCC("symb"), SymbolSection});
380 
381   return OS << RIFF;
382 }
383 
384 } // namespace clangd
385 } // namespace clang
386