xref: /aosp_15_r20/frameworks/base/libs/androidfw/StringPool.cpp (revision d57664e9bc4670b3ecf6748a746a57c557b6bc9e)
1 /*
2  * Copyright (C) 2015 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <androidfw/BigBuffer.h>
18 #include <androidfw/StringPool.h>
19 
20 #include <algorithm>
21 #include <memory>
22 #include <string>
23 
24 #include "android-base/logging.h"
25 #include "androidfw/ResourceTypes.h"
26 #include "androidfw/StringPiece.h"
27 #include "androidfw/Util.h"
28 
29 using ::android::StringPiece;
30 
31 namespace android {
32 
Ref()33 StringPool::Ref::Ref() : entry_(nullptr) {
34 }
35 
Ref(const StringPool::Ref & rhs)36 StringPool::Ref::Ref(const StringPool::Ref& rhs) : entry_(rhs.entry_) {
37   if (entry_ != nullptr) {
38     entry_->ref_++;
39   }
40 }
41 
Ref(StringPool::Entry * entry)42 StringPool::Ref::Ref(StringPool::Entry* entry) : entry_(entry) {
43   if (entry_ != nullptr) {
44     entry_->ref_++;
45   }
46 }
47 
~Ref()48 StringPool::Ref::~Ref() {
49   if (entry_ != nullptr) {
50     entry_->ref_--;
51   }
52 }
53 
operator =(const StringPool::Ref & rhs)54 StringPool::Ref& StringPool::Ref::operator=(const StringPool::Ref& rhs) {
55   if (rhs.entry_ != nullptr) {
56     rhs.entry_->ref_++;
57   }
58 
59   if (entry_ != nullptr) {
60     entry_->ref_--;
61   }
62   entry_ = rhs.entry_;
63   return *this;
64 }
65 
operator ==(const Ref & rhs) const66 bool StringPool::Ref::operator==(const Ref& rhs) const {
67   return entry_->value == rhs.entry_->value;
68 }
69 
operator !=(const Ref & rhs) const70 bool StringPool::Ref::operator!=(const Ref& rhs) const {
71   return entry_->value != rhs.entry_->value;
72 }
73 
operator ->() const74 const std::string* StringPool::Ref::operator->() const {
75   return &entry_->value;
76 }
77 
operator *() const78 const std::string& StringPool::Ref::operator*() const {
79   return entry_->value;
80 }
81 
index() const82 size_t StringPool::Ref::index() const {
83   // Account for the styles, which *always* come first.
84   return entry_->pool_->styles_.size() + entry_->index_;
85 }
86 
GetContext() const87 const StringPool::Context& StringPool::Ref::GetContext() const {
88   return entry_->context;
89 }
90 
StyleRef()91 StringPool::StyleRef::StyleRef() : entry_(nullptr) {
92 }
93 
StyleRef(const StringPool::StyleRef & rhs)94 StringPool::StyleRef::StyleRef(const StringPool::StyleRef& rhs) : entry_(rhs.entry_) {
95   if (entry_ != nullptr) {
96     entry_->ref_++;
97   }
98 }
99 
StyleRef(StringPool::StyleEntry * entry)100 StringPool::StyleRef::StyleRef(StringPool::StyleEntry* entry) : entry_(entry) {
101   if (entry_ != nullptr) {
102     entry_->ref_++;
103   }
104 }
105 
~StyleRef()106 StringPool::StyleRef::~StyleRef() {
107   if (entry_ != nullptr) {
108     entry_->ref_--;
109   }
110 }
111 
operator =(const StringPool::StyleRef & rhs)112 StringPool::StyleRef& StringPool::StyleRef::operator=(const StringPool::StyleRef& rhs) {
113   if (rhs.entry_ != nullptr) {
114     rhs.entry_->ref_++;
115   }
116 
117   if (entry_ != nullptr) {
118     entry_->ref_--;
119   }
120   entry_ = rhs.entry_;
121   return *this;
122 }
123 
operator ==(const StyleRef & rhs) const124 bool StringPool::StyleRef::operator==(const StyleRef& rhs) const {
125   if (entry_->value != rhs.entry_->value) {
126     return false;
127   }
128 
129   if (entry_->spans.size() != rhs.entry_->spans.size()) {
130     return false;
131   }
132 
133   auto rhs_iter = rhs.entry_->spans.begin();
134   for (const Span& span : entry_->spans) {
135     const Span& rhs_span = *rhs_iter++;
136     if (span.first_char != rhs_span.first_char || span.last_char != rhs_span.last_char ||
137         span.name != rhs_span.name) {
138       return false;
139     }
140   }
141   return true;
142 }
143 
operator !=(const StyleRef & rhs) const144 bool StringPool::StyleRef::operator!=(const StyleRef& rhs) const {
145   return !operator==(rhs);
146 }
147 
operator ->() const148 const StringPool::StyleEntry* StringPool::StyleRef::operator->() const {
149   return entry_;
150 }
151 
operator *() const152 const StringPool::StyleEntry& StringPool::StyleRef::operator*() const {
153   return *entry_;
154 }
155 
index() const156 size_t StringPool::StyleRef::index() const {
157   return entry_->index_;
158 }
159 
GetContext() const160 const StringPool::Context& StringPool::StyleRef::GetContext() const {
161   return entry_->context;
162 }
163 
MakeRef(StringPiece str)164 StringPool::Ref StringPool::MakeRef(StringPiece str) {
165   return MakeRefImpl(str, Context{}, true);
166 }
167 
MakeRef(StringPiece str,const Context & context)168 StringPool::Ref StringPool::MakeRef(StringPiece str, const Context& context) {
169   return MakeRefImpl(str, context, true);
170 }
171 
MakeRefImpl(StringPiece str,const Context & context,bool unique)172 StringPool::Ref StringPool::MakeRefImpl(StringPiece str, const Context& context, bool unique) {
173   if (unique) {
174     auto range = indexed_strings_.equal_range(str);
175     for (auto iter = range.first; iter != range.second; ++iter) {
176       if (context.priority == iter->second->context.priority) {
177         return Ref(iter->second);
178       }
179     }
180   }
181 
182   std::unique_ptr<Entry> entry(new Entry());
183   entry->value = std::string(str);
184   entry->context = context;
185   entry->index_ = strings_.size();
186   entry->ref_ = 0;
187   entry->pool_ = this;
188 
189   Entry* borrow = entry.get();
190   strings_.emplace_back(std::move(entry));
191   indexed_strings_.insert(std::make_pair(StringPiece(borrow->value), borrow));
192   return Ref(borrow);
193 }
194 
MakeRef(const Ref & ref)195 StringPool::Ref StringPool::MakeRef(const Ref& ref) {
196   if (ref.entry_->pool_ == this) {
197     return ref;
198   }
199   return MakeRef(ref.entry_->value, ref.entry_->context);
200 }
201 
MakeRef(const StyleString & str)202 StringPool::StyleRef StringPool::MakeRef(const StyleString& str) {
203   return MakeRef(str, Context{});
204 }
205 
MakeRef(const StyleString & str,const Context & context)206 StringPool::StyleRef StringPool::MakeRef(const StyleString& str, const Context& context) {
207   std::unique_ptr<StyleEntry> entry(new StyleEntry());
208   entry->value = str.str;
209   entry->context = context;
210   entry->index_ = styles_.size();
211   entry->ref_ = 0;
212   for (const android::Span& span : str.spans) {
213     entry->spans.emplace_back(Span{MakeRef(span.name), span.first_char, span.last_char});
214   }
215 
216   StyleEntry* borrow = entry.get();
217   styles_.emplace_back(std::move(entry));
218   return StyleRef(borrow);
219 }
220 
MakeRef(const StyleRef & ref)221 StringPool::StyleRef StringPool::MakeRef(const StyleRef& ref) {
222   std::unique_ptr<StyleEntry> entry(new StyleEntry());
223   entry->value = ref.entry_->value;
224   entry->context = ref.entry_->context;
225   entry->index_ = styles_.size();
226   entry->ref_ = 0;
227   for (const Span& span : ref.entry_->spans) {
228     entry->spans.emplace_back(Span{MakeRef(*span.name), span.first_char, span.last_char});
229   }
230 
231   StyleEntry* borrow = entry.get();
232   styles_.emplace_back(std::move(entry));
233   return StyleRef(borrow);
234 }
235 
ReAssignIndices()236 void StringPool::ReAssignIndices() {
237   // Assign the style indices.
238   const size_t style_len = styles_.size();
239   for (size_t index = 0; index < style_len; index++) {
240     styles_[index]->index_ = index;
241   }
242 
243   // Assign the string indices.
244   const size_t string_len = strings_.size();
245   for (size_t index = 0; index < string_len; index++) {
246     strings_[index]->index_ = index;
247   }
248 }
249 
Merge(StringPool && pool)250 void StringPool::Merge(StringPool&& pool) {
251   // First, change the owning pool for the incoming strings.
252   for (std::unique_ptr<Entry>& entry : pool.strings_) {
253     entry->pool_ = this;
254   }
255 
256   // Now move the styles, strings, and indices over.
257   std::move(pool.styles_.begin(), pool.styles_.end(), std::back_inserter(styles_));
258   pool.styles_.clear();
259   std::move(pool.strings_.begin(), pool.strings_.end(), std::back_inserter(strings_));
260   pool.strings_.clear();
261   indexed_strings_.insert(pool.indexed_strings_.begin(), pool.indexed_strings_.end());
262   pool.indexed_strings_.clear();
263 
264   ReAssignIndices();
265 }
266 
HintWillAdd(size_t string_count,size_t style_count)267 void StringPool::HintWillAdd(size_t string_count, size_t style_count) {
268   strings_.reserve(strings_.size() + string_count);
269   styles_.reserve(styles_.size() + style_count);
270 }
271 
Prune()272 void StringPool::Prune() {
273   const auto iter_end = indexed_strings_.end();
274   auto index_iter = indexed_strings_.begin();
275   while (index_iter != iter_end) {
276     if (index_iter->second->ref_ <= 0) {
277       index_iter = indexed_strings_.erase(index_iter);
278     } else {
279       ++index_iter;
280     }
281   }
282 
283   auto end_iter2 =
284       std::remove_if(strings_.begin(), strings_.end(),
285                      [](const std::unique_ptr<Entry>& entry) -> bool { return entry->ref_ <= 0; });
286   auto end_iter3 = std::remove_if(
287       styles_.begin(), styles_.end(),
288       [](const std::unique_ptr<StyleEntry>& entry) -> bool { return entry->ref_ <= 0; });
289 
290   // Remove the entries at the end or else we'll be accessing a deleted string from the StyleEntry.
291   strings_.erase(end_iter2, strings_.end());
292   styles_.erase(end_iter3, styles_.end());
293 
294   ReAssignIndices();
295 }
296 
297 template <typename E>
SortEntries(std::vector<std::unique_ptr<E>> & entries,base::function_ref<int (const StringPool::Context &,const StringPool::Context &)> cmp)298 static void SortEntries(
299     std::vector<std::unique_ptr<E>>& entries,
300     base::function_ref<int(const StringPool::Context&, const StringPool::Context&)> cmp) {
301   using UEntry = std::unique_ptr<E>;
302   std::sort(entries.begin(), entries.end(), [cmp](const UEntry& a, const UEntry& b) -> bool {
303     int r = cmp(a->context, b->context);
304     if (r == 0) {
305       r = a->value.compare(b->value);
306     }
307     return r < 0;
308   });
309 }
310 
Sort()311 void StringPool::Sort() {
312   Sort([](auto&&, auto&&) { return 0; });
313 }
314 
Sort(base::function_ref<int (const Context &,const Context &)> cmp)315 void StringPool::Sort(base::function_ref<int(const Context&, const Context&)> cmp) {
316   SortEntries(styles_, cmp);
317   SortEntries(strings_, cmp);
318   ReAssignIndices();
319 }
320 
321 template <typename T>
EncodeLength(T * data,size_t length)322 static T* EncodeLength(T* data, size_t length) {
323   static_assert(std::is_integral<T>::value, "wat.");
324 
325   constexpr size_t kMask = 1 << ((sizeof(T) * 8) - 1);
326   constexpr size_t kMaxSize = kMask - 1;
327   if (length > kMaxSize) {
328     *data++ = kMask | (kMaxSize & (length >> (sizeof(T) * 8)));
329   }
330   *data++ = length;
331   return data;
332 }
333 
334 /**
335  * Returns the maximum possible string length that can be successfully encoded
336  * using 2 units of the specified T.
337  *    EncodeLengthMax<char> -> maximum unit length of 0x7FFF
338  *    EncodeLengthMax<char16_t> -> maximum unit length of 0x7FFFFFFF
339  **/
340 template <typename T>
EncodeLengthMax()341 static size_t EncodeLengthMax() {
342   static_assert(std::is_integral<T>::value, "wat.");
343 
344   constexpr size_t kMask = 1 << ((sizeof(T) * 8 * 2) - 1);
345   constexpr size_t max = kMask - 1;
346   return max;
347 }
348 
349 /**
350  * Returns the number of units (1 or 2) needed to encode the string length
351  * before writing the string.
352  */
353 template <typename T>
EncodedLengthUnits(size_t length)354 static size_t EncodedLengthUnits(size_t length) {
355   static_assert(std::is_integral<T>::value, "wat.");
356 
357   constexpr size_t kMask = 1 << ((sizeof(T) * 8) - 1);
358   constexpr size_t kMaxSize = kMask - 1;
359   return length > kMaxSize ? 2 : 1;
360 }
361 
362 const std::string kStringTooLarge = "STRING_TOO_LARGE";
363 
EncodeString(const std::string & str,const bool utf8,BigBuffer * out,IDiagnostics * diag)364 static bool EncodeString(const std::string& str, const bool utf8, BigBuffer* out,
365                          IDiagnostics* diag) {
366   if (utf8) {
367     const std::string& encoded = util::Utf8ToModifiedUtf8(str);
368     const ssize_t utf16_length =
369         utf8_to_utf16_length(reinterpret_cast<const uint8_t*>(encoded.data()), encoded.size());
370     CHECK(utf16_length >= 0);
371 
372     // Make sure the lengths to be encoded do not exceed the maximum length that
373     // can be encoded using chars
374     if ((((size_t)encoded.size()) > EncodeLengthMax<char>()) ||
375         (((size_t)utf16_length) > EncodeLengthMax<char>())) {
376       diag->Error(DiagMessage() << "string too large to encode using UTF-8 "
377                                 << "written instead as '" << kStringTooLarge << "'");
378 
379       EncodeString(kStringTooLarge, utf8, out, diag);
380       return false;
381     }
382 
383     const size_t total_size = EncodedLengthUnits<char>(utf16_length) +
384                               EncodedLengthUnits<char>(encoded.size()) + encoded.size() + 1;
385 
386     char* data = out->NextBlock<char>(total_size);
387 
388     // First encode the UTF16 string length.
389     data = EncodeLength(data, utf16_length);
390 
391     // Now encode the size of the real UTF8 string.
392     data = EncodeLength(data, encoded.size());
393     strncpy(data, encoded.data(), encoded.size());
394 
395   } else {
396     const std::u16string encoded = util::Utf8ToUtf16(str);
397     const ssize_t utf16_length = encoded.size();
398 
399     // Make sure the length to be encoded does not exceed the maximum possible
400     // length that can be encoded
401     if (((size_t)utf16_length) > EncodeLengthMax<char16_t>()) {
402       diag->Error(DiagMessage() << "string too large to encode using UTF-16 "
403                                 << "written instead as '" << kStringTooLarge << "'");
404 
405       EncodeString(kStringTooLarge, utf8, out, diag);
406       return false;
407     }
408 
409     // Total number of 16-bit words to write.
410     const size_t total_size = EncodedLengthUnits<char16_t>(utf16_length) + encoded.size() + 1;
411 
412     char16_t* data = out->NextBlock<char16_t>(total_size);
413 
414     // Encode the actual UTF16 string length.
415     data = EncodeLength(data, utf16_length);
416     const size_t byte_length = encoded.size() * sizeof(char16_t);
417 
418     // NOTE: For some reason, strncpy16(data, entry->value.data(),
419     // entry->value.size()) truncates the string.
420     memcpy(data, encoded.data(), byte_length);
421 
422     // The null-terminating character is already here due to the block of data
423     // being set to 0s on allocation.
424   }
425 
426   return true;
427 }
428 
Flatten(BigBuffer * out,const StringPool & pool,bool utf8,IDiagnostics * diag)429 bool StringPool::Flatten(BigBuffer* out, const StringPool& pool, bool utf8, IDiagnostics* diag) {
430   bool no_error = true;
431   const size_t start_index = out->size();
432   android::ResStringPool_header* header = out->NextBlock<android::ResStringPool_header>();
433   header->header.type = util::HostToDevice16(android::RES_STRING_POOL_TYPE);
434   header->header.headerSize = util::HostToDevice16(sizeof(*header));
435   header->stringCount = util::HostToDevice32(pool.size());
436   header->styleCount = util::HostToDevice32(pool.styles_.size());
437   if (utf8) {
438     header->flags |= android::ResStringPool_header::UTF8_FLAG;
439   }
440 
441   uint32_t* indices = pool.size() != 0 ? out->NextBlock<uint32_t>(pool.size()) : nullptr;
442   uint32_t* style_indices =
443       pool.styles_.size() != 0 ? out->NextBlock<uint32_t>(pool.styles_.size()) : nullptr;
444 
445   const size_t before_strings_index = out->size();
446   header->stringsStart = before_strings_index - start_index;
447 
448   // Styles always come first.
449   for (const std::unique_ptr<StyleEntry>& entry : pool.styles_) {
450     *indices++ = out->size() - before_strings_index;
451     no_error = EncodeString(entry->value, utf8, out, diag) && no_error;
452   }
453 
454   for (const std::unique_ptr<Entry>& entry : pool.strings_) {
455     *indices++ = out->size() - before_strings_index;
456     no_error = EncodeString(entry->value, utf8, out, diag) && no_error;
457   }
458 
459   out->Align4();
460 
461   if (style_indices != nullptr) {
462     const size_t before_styles_index = out->size();
463     header->stylesStart = util::HostToDevice32(before_styles_index - start_index);
464 
465     for (const std::unique_ptr<StyleEntry>& entry : pool.styles_) {
466       *style_indices++ = out->size() - before_styles_index;
467 
468       if (!entry->spans.empty()) {
469         android::ResStringPool_span* span =
470             out->NextBlock<android::ResStringPool_span>(entry->spans.size());
471         for (const Span& s : entry->spans) {
472           span->name.index = util::HostToDevice32(s.name.index());
473           span->firstChar = util::HostToDevice32(s.first_char);
474           span->lastChar = util::HostToDevice32(s.last_char);
475           span++;
476         }
477       }
478 
479       uint32_t* spanEnd = out->NextBlock<uint32_t>();
480       *spanEnd = android::ResStringPool_span::END;
481     }
482 
483     // The error checking code in the platform looks for an entire
484     // ResStringPool_span structure worth of 0xFFFFFFFF at the end
485     // of the style block, so fill in the remaining 2 32bit words
486     // with 0xFFFFFFFF.
487     const size_t padding_length =
488         sizeof(android::ResStringPool_span) - sizeof(android::ResStringPool_span::name);
489     uint8_t* padding = out->NextBlock<uint8_t>(padding_length);
490     memset(padding, 0xff, padding_length);
491     out->Align4();
492   }
493   header->header.size = util::HostToDevice32(out->size() - start_index);
494   return no_error;
495 }
496 
FlattenUtf8(BigBuffer * out,const StringPool & pool,IDiagnostics * diag)497 bool StringPool::FlattenUtf8(BigBuffer* out, const StringPool& pool, IDiagnostics* diag) {
498   return Flatten(out, pool, true, diag);
499 }
500 
FlattenUtf16(BigBuffer * out,const StringPool & pool,IDiagnostics * diag)501 bool StringPool::FlattenUtf16(BigBuffer* out, const StringPool& pool, IDiagnostics* diag) {
502   return Flatten(out, pool, false, diag);
503 }
504 
505 }  // namespace android
506