1 /*
2  * Copyright (C) 2019 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 "src/trace_processor/containers/string_pool.h"
18 
19 #include <limits>
20 
21 #include "perfetto/base/logging.h"
22 #include "perfetto/ext/base/utils.h"
23 
24 namespace perfetto {
25 namespace trace_processor {
26 
27 // static
28 constexpr size_t StringPool::kNumBlockIndexBits;
29 // static
30 constexpr size_t StringPool::kNumBlockOffsetBits;
31 // static
32 constexpr size_t StringPool::kLargeStringFlagBitMask;
33 // static
34 constexpr size_t StringPool::kBlockOffsetBitMask;
35 // static
36 constexpr size_t StringPool::kBlockIndexBitMask;
37 // static
38 constexpr size_t StringPool::kBlockSizeBytes;
39 // static
40 constexpr size_t StringPool::kMinLargeStringSizeBytes;
41 
StringPool()42 StringPool::StringPool() {
43   static_assert(
44       StringPool::kMinLargeStringSizeBytes <= StringPool::kBlockSizeBytes + 1,
45       "minimum size of large strings must be small enough to support any "
46       "string that doesn't fit in a Block.");
47 
48   blocks_.emplace_back(kBlockSizeBytes);
49 
50   // Reserve a slot for the null string.
51   PERFETTO_CHECK(blocks_.back().TryInsert(NullTermStringView()).first);
52 }
53 
54 StringPool::~StringPool() = default;
55 
56 StringPool::StringPool(StringPool&&) = default;
57 StringPool& StringPool::operator=(StringPool&&) = default;
58 
InsertString(base::StringView str,uint64_t hash)59 StringPool::Id StringPool::InsertString(base::StringView str, uint64_t hash) {
60   // Try and find enough space in the current block for the string and the
61   // metadata (varint-encoded size + the string data + the null terminator).
62   bool success;
63   uint32_t offset;
64   std::tie(success, offset) = blocks_.back().TryInsert(str);
65   if (PERFETTO_UNLIKELY(!success)) {
66     // The block did not have enough space for the string. If the string is
67     // large, add it into the |large_strings_| vector, to avoid discarding a
68     // large portion of the current block's memory. This also enables us to
69     // support strings that wouldn't fit into a single block. Otherwise, add a
70     // new block to store the string.
71     if (str.size() + kMaxMetadataSize >= kMinLargeStringSizeBytes) {
72       return InsertLargeString(str, hash);
73     } else {
74       blocks_.emplace_back(kBlockSizeBytes);
75     }
76 
77     // Try and reserve space again - this time we should definitely succeed.
78     std::tie(success, offset) = blocks_.back().TryInsert(str);
79     PERFETTO_CHECK(success);
80   }
81 
82   // Compute the id from the block index and offset and add a mapping from the
83   // hash to the id.
84   Id string_id = Id::BlockString(blocks_.size() - 1, offset);
85   string_index_.emplace(hash, string_id);
86   return string_id;
87 }
88 
InsertLargeString(base::StringView str,uint64_t hash)89 StringPool::Id StringPool::InsertLargeString(base::StringView str,
90                                              uint64_t hash) {
91   large_strings_.emplace_back(new std::string(str.begin(), str.size()));
92   // Compute id from the index and add a mapping from the hash to the id.
93   Id string_id = Id::LargeString(large_strings_.size() - 1);
94   string_index_.emplace(hash, string_id);
95   return string_id;
96 }
97 
TryInsert(base::StringView str)98 std::pair<bool /*success*/, uint32_t /*offset*/> StringPool::Block::TryInsert(
99     base::StringView str) {
100   auto str_size = str.size();
101   size_t max_pos = static_cast<size_t>(pos_) + str_size + kMaxMetadataSize;
102   if (max_pos > size_)
103     return std::make_pair(false, 0u);
104 
105   // Ensure that we commit up until the end of the string to memory.
106   mem_.EnsureCommitted(max_pos);
107 
108   // Get where we should start writing this string.
109   uint32_t offset = pos_;
110   uint8_t* begin = Get(offset);
111 
112   // First write the size of the string using varint encoding.
113   uint8_t* end = protozero::proto_utils::WriteVarInt(str_size, begin);
114 
115   // Next the string itself.
116   if (PERFETTO_LIKELY(str_size > 0)) {
117     memcpy(end, str.data(), str_size);
118     end += str_size;
119   }
120 
121   // Finally add a null terminator.
122   *(end++) = '\0';
123 
124   // Update the end of the block and return the pointer to the string.
125   pos_ = OffsetOf(end);
126 
127   return std::make_pair(true, offset);
128 }
129 
Iterator(const StringPool * pool)130 StringPool::Iterator::Iterator(const StringPool* pool) : pool_(pool) {}
131 
operator ++()132 StringPool::Iterator& StringPool::Iterator::operator++() {
133   if (block_index_ < pool_->blocks_.size()) {
134     // Try and go to the next string in the current block.
135     const auto& block = pool_->blocks_[block_index_];
136 
137     // Find the size of the string at the current offset in the block
138     // and increment the offset by that size.
139     uint32_t str_size = 0;
140     const uint8_t* ptr = block.Get(block_offset_);
141     ptr = ReadSize(ptr, &str_size);
142     ptr += str_size + 1;
143     block_offset_ = block.OffsetOf(ptr);
144 
145     // If we're out of bounds for this block, go to the start of the next block.
146     if (block.pos() <= block_offset_) {
147       block_index_++;
148       block_offset_ = 0;
149     }
150 
151     return *this;
152   }
153 
154   // Advance to the next string from |large_strings_|.
155   PERFETTO_DCHECK(large_strings_index_ < pool_->large_strings_.size());
156   large_strings_index_++;
157   return *this;
158 }
159 
operator bool() const160 StringPool::Iterator::operator bool() const {
161   return block_index_ < pool_->blocks_.size() ||
162          large_strings_index_ < pool_->large_strings_.size();
163 }
164 
StringView()165 NullTermStringView StringPool::Iterator::StringView() {
166   return pool_->Get(StringId());
167 }
168 
StringId()169 StringPool::Id StringPool::Iterator::StringId() {
170   if (block_index_ < pool_->blocks_.size()) {
171     PERFETTO_DCHECK(block_offset_ < pool_->blocks_[block_index_].pos());
172 
173     // If we're at (0, 0), we have the null string which has id 0.
174     if (block_index_ == 0 && block_offset_ == 0)
175       return Id::Null();
176     return Id::BlockString(block_index_, block_offset_);
177   }
178   PERFETTO_DCHECK(large_strings_index_ < pool_->large_strings_.size());
179   return Id::LargeString(large_strings_index_);
180 }
181 
182 }  // namespace trace_processor
183 }  // namespace perfetto
184