1 //===-- ConstString.cpp -----------------------------------------*- 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 "lldb/Utility/ConstString.h"
11 
12 #include "lldb/Utility/Stream.h"
13 
14 #include "llvm/ADT/StringMap.h"
15 #include "llvm/ADT/iterator.h"            // for iterator_facade_base
16 #include "llvm/Support/Allocator.h"       // for BumpPtrAllocator
17 #include "llvm/Support/DJB.h"             // for djbHash
18 #include "llvm/Support/FormatProviders.h" // for format_provider
19 #include "llvm/Support/RWMutex.h"
20 #include "llvm/Support/Threading.h"
21 
22 #include <algorithm> // for min
23 #include <array>
24 #include <utility> // for make_pair, pair
25 
26 #include <inttypes.h> // for PRIu64
27 #include <stdint.h>   // for uint8_t, uint32_t, uint64_t
28 #include <string.h>   // for size_t, strlen
29 
30 using namespace lldb_private;
31 
32 class Pool {
33 public:
34   typedef const char *StringPoolValueType;
35   typedef llvm::StringMap<StringPoolValueType, llvm::BumpPtrAllocator>
36       StringPool;
37   typedef llvm::StringMapEntry<StringPoolValueType> StringPoolEntryType;
38 
39   static StringPoolEntryType &
40   GetStringMapEntryFromKeyData(const char *keyData) {
41     return StringPoolEntryType::GetStringMapEntryFromKeyData(keyData);
42   }
43 
44   static size_t GetConstCStringLength(const char *ccstr) {
45     if (ccstr != nullptr) {
46       // Since the entry is read only, and we derive the entry entirely from
47       // the pointer, we don't need the lock.
48       const StringPoolEntryType &entry = GetStringMapEntryFromKeyData(ccstr);
49       return entry.getKey().size();
50     }
51     return 0;
52   }
53 
54   StringPoolValueType GetMangledCounterpart(const char *ccstr) const {
55     if (ccstr != nullptr) {
56       const uint8_t h = hash(llvm::StringRef(ccstr));
57       llvm::sys::SmartScopedReader<false> rlock(m_string_pools[h].m_mutex);
58       return GetStringMapEntryFromKeyData(ccstr).getValue();
59     }
60     return nullptr;
61   }
62 
63   bool SetMangledCounterparts(const char *key_ccstr, const char *value_ccstr) {
64     if (key_ccstr != nullptr && value_ccstr != nullptr) {
65       {
66         const uint8_t h = hash(llvm::StringRef(key_ccstr));
67         llvm::sys::SmartScopedWriter<false> wlock(m_string_pools[h].m_mutex);
68         GetStringMapEntryFromKeyData(key_ccstr).setValue(value_ccstr);
69       }
70       {
71         const uint8_t h = hash(llvm::StringRef(value_ccstr));
72         llvm::sys::SmartScopedWriter<false> wlock(m_string_pools[h].m_mutex);
73         GetStringMapEntryFromKeyData(value_ccstr).setValue(key_ccstr);
74       }
75       return true;
76     }
77     return false;
78   }
79 
80   const char *GetConstCString(const char *cstr) {
81     if (cstr != nullptr)
82       return GetConstCStringWithLength(cstr, strlen(cstr));
83     return nullptr;
84   }
85 
86   const char *GetConstCStringWithLength(const char *cstr, size_t cstr_len) {
87     if (cstr != nullptr)
88       return GetConstCStringWithStringRef(llvm::StringRef(cstr, cstr_len));
89     return nullptr;
90   }
91 
92   const char *GetConstCStringWithStringRef(const llvm::StringRef &string_ref) {
93     if (string_ref.data()) {
94       const uint8_t h = hash(string_ref);
95 
96       {
97         llvm::sys::SmartScopedReader<false> rlock(m_string_pools[h].m_mutex);
98         auto it = m_string_pools[h].m_string_map.find(string_ref);
99         if (it != m_string_pools[h].m_string_map.end())
100           return it->getKeyData();
101       }
102 
103       llvm::sys::SmartScopedWriter<false> wlock(m_string_pools[h].m_mutex);
104       StringPoolEntryType &entry =
105           *m_string_pools[h]
106                .m_string_map.insert(std::make_pair(string_ref, nullptr))
107                .first;
108       return entry.getKeyData();
109     }
110     return nullptr;
111   }
112 
113   const char *
114   GetConstCStringAndSetMangledCounterPart(const char *demangled_cstr,
115                                           const char *mangled_ccstr) {
116     if (demangled_cstr != nullptr) {
117       const char *demangled_ccstr = nullptr;
118 
119       {
120         llvm::StringRef string_ref(demangled_cstr);
121         const uint8_t h = hash(string_ref);
122         llvm::sys::SmartScopedWriter<false> wlock(m_string_pools[h].m_mutex);
123 
124         // Make string pool entry with the mangled counterpart already set
125         StringPoolEntryType &entry =
126             *m_string_pools[h]
127                  .m_string_map.insert(std::make_pair(string_ref, mangled_ccstr))
128                  .first;
129 
130         // Extract the const version of the demangled_cstr
131         demangled_ccstr = entry.getKeyData();
132       }
133 
134       {
135         // Now assign the demangled const string as the counterpart of the
136         // mangled const string...
137         const uint8_t h = hash(llvm::StringRef(mangled_ccstr));
138         llvm::sys::SmartScopedWriter<false> wlock(m_string_pools[h].m_mutex);
139         GetStringMapEntryFromKeyData(mangled_ccstr).setValue(demangled_ccstr);
140       }
141 
142       // Return the constant demangled C string
143       return demangled_ccstr;
144     }
145     return nullptr;
146   }
147 
148   const char *GetConstTrimmedCStringWithLength(const char *cstr,
149                                                size_t cstr_len) {
150     if (cstr != nullptr) {
151       const size_t trimmed_len = std::min<size_t>(strlen(cstr), cstr_len);
152       return GetConstCStringWithLength(cstr, trimmed_len);
153     }
154     return nullptr;
155   }
156 
157   //------------------------------------------------------------------
158   // Return the size in bytes that this object and any items in its collection
159   // of uniqued strings + data count values takes in memory.
160   //------------------------------------------------------------------
161   size_t MemorySize() const {
162     size_t mem_size = sizeof(Pool);
163     for (const auto &pool : m_string_pools) {
164       llvm::sys::SmartScopedReader<false> rlock(pool.m_mutex);
165       for (const auto &entry : pool.m_string_map)
166         mem_size += sizeof(StringPoolEntryType) + entry.getKey().size();
167     }
168     return mem_size;
169   }
170 
171 protected:
172   uint8_t hash(const llvm::StringRef &s) const {
173     uint32_t h = llvm::djbHash(s);
174     return ((h >> 24) ^ (h >> 16) ^ (h >> 8) ^ h) & 0xff;
175   }
176 
177   struct PoolEntry {
178     mutable llvm::sys::SmartRWMutex<false> m_mutex;
179     StringPool m_string_map;
180   };
181 
182   std::array<PoolEntry, 256> m_string_pools;
183 };
184 
185 //----------------------------------------------------------------------
186 // Frameworks and dylibs aren't supposed to have global C++ initializers so we
187 // hide the string pool in a static function so that it will get initialized on
188 // the first call to this static function.
189 //
190 // Note, for now we make the string pool a pointer to the pool, because we
191 // can't guarantee that some objects won't get destroyed after the global
192 // destructor chain is run, and trying to make sure no destructors touch
193 // ConstStrings is difficult.  So we leak the pool instead.
194 //----------------------------------------------------------------------
195 static Pool &StringPool() {
196   static llvm::once_flag g_pool_initialization_flag;
197   static Pool *g_string_pool = nullptr;
198 
199   llvm::call_once(g_pool_initialization_flag,
200                  []() { g_string_pool = new Pool(); });
201 
202   return *g_string_pool;
203 }
204 
205 ConstString::ConstString(const char *cstr)
206     : m_string(StringPool().GetConstCString(cstr)) {}
207 
208 ConstString::ConstString(const char *cstr, size_t cstr_len)
209     : m_string(StringPool().GetConstCStringWithLength(cstr, cstr_len)) {}
210 
211 ConstString::ConstString(const llvm::StringRef &s)
212     : m_string(StringPool().GetConstCStringWithLength(s.data(), s.size())) {}
213 
214 bool ConstString::operator<(const ConstString &rhs) const {
215   if (m_string == rhs.m_string)
216     return false;
217 
218   llvm::StringRef lhs_string_ref(GetStringRef());
219   llvm::StringRef rhs_string_ref(rhs.GetStringRef());
220 
221   // If both have valid C strings, then return the comparison
222   if (lhs_string_ref.data() && rhs_string_ref.data())
223     return lhs_string_ref < rhs_string_ref;
224 
225   // Else one of them was nullptr, so if LHS is nullptr then it is less than
226   return lhs_string_ref.data() == nullptr;
227 }
228 
229 Stream &lldb_private::operator<<(Stream &s, const ConstString &str) {
230   const char *cstr = str.GetCString();
231   if (cstr != nullptr)
232     s << cstr;
233 
234   return s;
235 }
236 
237 size_t ConstString::GetLength() const {
238   return Pool::GetConstCStringLength(m_string);
239 }
240 
241 bool ConstString::Equals(const ConstString &lhs, const ConstString &rhs,
242                          const bool case_sensitive) {
243   if (lhs.m_string == rhs.m_string)
244     return true;
245 
246   // Since the pointers weren't equal, and identical ConstStrings always have
247   // identical pointers, the result must be false for case sensitive equality
248   // test.
249   if (case_sensitive)
250     return false;
251 
252   // perform case insensitive equality test
253   llvm::StringRef lhs_string_ref(lhs.GetStringRef());
254   llvm::StringRef rhs_string_ref(rhs.GetStringRef());
255   return lhs_string_ref.equals_lower(rhs_string_ref);
256 }
257 
258 int ConstString::Compare(const ConstString &lhs, const ConstString &rhs,
259                          const bool case_sensitive) {
260   // If the iterators are the same, this is the same string
261   const char *lhs_cstr = lhs.m_string;
262   const char *rhs_cstr = rhs.m_string;
263   if (lhs_cstr == rhs_cstr)
264     return 0;
265   if (lhs_cstr && rhs_cstr) {
266     llvm::StringRef lhs_string_ref(lhs.GetStringRef());
267     llvm::StringRef rhs_string_ref(rhs.GetStringRef());
268 
269     if (case_sensitive) {
270       return lhs_string_ref.compare(rhs_string_ref);
271     } else {
272       return lhs_string_ref.compare_lower(rhs_string_ref);
273     }
274   }
275 
276   if (lhs_cstr)
277     return +1; // LHS isn't nullptr but RHS is
278   else
279     return -1; // LHS is nullptr but RHS isn't
280 }
281 
282 void ConstString::Dump(Stream *s, const char *fail_value) const {
283   if (s != nullptr) {
284     const char *cstr = AsCString(fail_value);
285     if (cstr != nullptr)
286       s->PutCString(cstr);
287   }
288 }
289 
290 void ConstString::DumpDebug(Stream *s) const {
291   const char *cstr = GetCString();
292   size_t cstr_len = GetLength();
293   // Only print the parens if we have a non-nullptr string
294   const char *parens = cstr ? "\"" : "";
295   s->Printf("%*p: ConstString, string = %s%s%s, length = %" PRIu64,
296             static_cast<int>(sizeof(void *) * 2),
297             static_cast<const void *>(this), parens, cstr, parens,
298             static_cast<uint64_t>(cstr_len));
299 }
300 
301 void ConstString::SetCString(const char *cstr) {
302   m_string = StringPool().GetConstCString(cstr);
303 }
304 
305 void ConstString::SetString(const llvm::StringRef &s) {
306   m_string = StringPool().GetConstCStringWithLength(s.data(), s.size());
307 }
308 
309 void ConstString::SetCStringWithMangledCounterpart(const char *demangled,
310                                                    const ConstString &mangled) {
311   m_string = StringPool().GetConstCStringAndSetMangledCounterPart(
312       demangled, mangled.m_string);
313 }
314 
315 bool ConstString::GetMangledCounterpart(ConstString &counterpart) const {
316   counterpart.m_string = StringPool().GetMangledCounterpart(m_string);
317   return (bool)counterpart;
318 }
319 
320 void ConstString::SetCStringWithLength(const char *cstr, size_t cstr_len) {
321   m_string = StringPool().GetConstCStringWithLength(cstr, cstr_len);
322 }
323 
324 void ConstString::SetTrimmedCStringWithLength(const char *cstr,
325                                               size_t cstr_len) {
326   m_string = StringPool().GetConstTrimmedCStringWithLength(cstr, cstr_len);
327 }
328 
329 size_t ConstString::StaticMemorySize() {
330   // Get the size of the static string pool
331   return StringPool().MemorySize();
332 }
333 
334 void llvm::format_provider<ConstString>::format(const ConstString &CS,
335                                                 llvm::raw_ostream &OS,
336                                                 llvm::StringRef Options) {
337   format_provider<StringRef>::format(CS.AsCString(), OS, Options);
338 }
339