1 //===- DebugStringTableSubsection.cpp - CodeView String Table ---*- C++ -*-===//
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 #include "llvm/DebugInfo/CodeView/DebugStringTableSubsection.h"
11 
12 #include "llvm/Support/BinaryStream.h"
13 #include "llvm/Support/BinaryStreamReader.h"
14 #include "llvm/Support/BinaryStreamWriter.h"
15 
16 using namespace llvm;
17 using namespace llvm::codeview;
18 
19 DebugStringTableSubsectionRef::DebugStringTableSubsectionRef()
20     : DebugSubsectionRef(DebugSubsectionKind::StringTable) {}
21 
22 Error DebugStringTableSubsectionRef::initialize(BinaryStreamRef Contents) {
23   Stream = Contents;
24   return Error::success();
25 }
26 Error DebugStringTableSubsectionRef::initialize(BinaryStreamReader &Reader) {
27   return Reader.readStreamRef(Stream);
28 }
29 
30 Expected<StringRef>
31 DebugStringTableSubsectionRef::getString(uint32_t Offset) const {
32   BinaryStreamReader Reader(Stream);
33   Reader.setOffset(Offset);
34   StringRef Result;
35   if (auto EC = Reader.readCString(Result))
36     return std::move(EC);
37   return Result;
38 }
39 
40 DebugStringTableSubsection::DebugStringTableSubsection()
41     : DebugSubsection(DebugSubsectionKind::StringTable) {}
42 
43 uint32_t DebugStringTableSubsection::insert(StringRef S) {
44   auto P = Strings.insert({S, StringSize});
45 
46   // If a given string didn't exist in the string table, we want to increment
47   // the string table size.
48   if (P.second)
49     StringSize += S.size() + 1; // +1 for '\0'
50   return P.first->second;
51 }
52 
53 uint32_t DebugStringTableSubsection::calculateSerializedSize() const {
54   return StringSize;
55 }
56 
57 Error DebugStringTableSubsection::commit(BinaryStreamWriter &Writer) const {
58   uint32_t Begin = Writer.getOffset();
59   uint32_t End = Begin + StringSize;
60 
61   // Write a null string at the beginning.
62   if (auto EC = Writer.writeCString(StringRef()))
63     return EC;
64 
65   for (auto &Pair : Strings) {
66     StringRef S = Pair.getKey();
67     uint32_t Offset = Begin + Pair.getValue();
68     Writer.setOffset(Offset);
69     if (auto EC = Writer.writeCString(S))
70       return EC;
71     assert(Writer.getOffset() <= End);
72   }
73 
74   Writer.setOffset(End);
75   assert((End - Begin) == StringSize);
76   return Error::success();
77 }
78 
79 uint32_t DebugStringTableSubsection::size() const { return Strings.size(); }
80 
81 uint32_t DebugStringTableSubsection::getStringId(StringRef S) const {
82   auto Iter = Strings.find(S);
83   assert(Iter != Strings.end());
84   return Iter->second;
85 }
86