3 * Copyright 2016 gRPC authors.
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
19 #include <grpc/support/port_platform.h>
21 #include "src/core/lib/slice/slice_internal.h"
22 #include "src/core/lib/slice/slice_utils.h"
27 #include <grpc/support/alloc.h>
28 #include <grpc/support/log.h>
30 #include "src/core/lib/gpr/murmur_hash.h"
31 #include "src/core/lib/gprpp/sync.h"
32 #include "src/core/lib/iomgr/iomgr_internal.h" /* for iomgr_abort_on_leaks() */
33 #include "src/core/lib/profiling/timers.h"
34 #include "src/core/lib/slice/slice_string_helpers.h"
35 #include "src/core/lib/transport/static_metadata.h"
37 #define LOG2_SHARD_COUNT 5
38 #define SHARD_COUNT (1 << LOG2_SHARD_COUNT)
39 #define INITIAL_SHARD_CAPACITY 8
41 #define TABLE_IDX(hash, capacity) (((hash) >> LOG2_SHARD_COUNT) % (capacity))
42 #define SHARD_IDX(hash) ((hash) & ((1 << LOG2_SHARD_COUNT) - 1))
44 using grpc_core::InternedSliceRefcount;
46 typedef struct slice_shard {
48 InternedSliceRefcount** strs;
53 static slice_shard g_shards[SHARD_COUNT];
55 struct static_metadata_hash_ent {
59 static static_metadata_hash_ent
60 static_metadata_hash[4 * GRPC_STATIC_MDSTR_COUNT];
61 static uint32_t max_static_metadata_hash_probe;
62 uint32_t grpc_static_metadata_hash_values[GRPC_STATIC_MDSTR_COUNT];
66 /* hash seed: decided at initialization time */
68 static bool g_forced_hash_seed = false;
70 InternedSliceRefcount::~InternedSliceRefcount() {
71 slice_shard* shard = &g_shards[SHARD_IDX(this->hash)];
72 MutexLock lock(&shard->mu);
73 InternedSliceRefcount** prev_next;
74 InternedSliceRefcount* cur;
75 for (prev_next = &shard->strs[TABLE_IDX(this->hash, shard->capacity)],
77 cur != this; prev_next = &cur->bucket_next, cur = cur->bucket_next) {
79 *prev_next = cur->bucket_next;
83 } // namespace grpc_core
85 static void grow_shard(slice_shard* shard) {
86 GPR_TIMER_SCOPE("grow_strtab", 0);
88 size_t capacity = shard->capacity * 2;
90 InternedSliceRefcount** strtab;
91 InternedSliceRefcount *s, *next;
93 strtab = static_cast<InternedSliceRefcount**>(
94 gpr_zalloc(sizeof(InternedSliceRefcount*) * capacity));
96 for (i = 0; i < shard->capacity; i++) {
97 for (s = shard->strs[i]; s; s = next) {
98 size_t idx = TABLE_IDX(s->hash, capacity);
99 next = s->bucket_next;
100 s->bucket_next = strtab[idx];
104 gpr_free(shard->strs);
105 shard->strs = strtab;
106 shard->capacity = capacity;
109 grpc_core::InternedSlice::InternedSlice(InternedSliceRefcount* s) {
111 data.refcounted.bytes = reinterpret_cast<uint8_t*>(s + 1);
112 data.refcounted.length = s->length;
115 uint32_t grpc_slice_default_hash_impl(grpc_slice s) {
116 return gpr_murmur_hash3(GRPC_SLICE_START_PTR(s), GRPC_SLICE_LENGTH(s),
117 grpc_core::g_hash_seed);
120 uint32_t grpc_static_slice_hash(grpc_slice s) {
121 return grpc_static_metadata_hash_values[GRPC_STATIC_METADATA_INDEX(s)];
124 int grpc_static_slice_eq(grpc_slice a, grpc_slice b) {
125 return GRPC_STATIC_METADATA_INDEX(a) == GRPC_STATIC_METADATA_INDEX(b);
128 uint32_t grpc_slice_hash(grpc_slice s) { return grpc_slice_hash_internal(s); }
130 grpc_slice grpc_slice_maybe_static_intern(grpc_slice slice,
131 bool* returned_slice_is_different) {
132 if (GRPC_IS_STATIC_METADATA_STRING(slice)) {
136 uint32_t hash = grpc_slice_hash_internal(slice);
137 for (uint32_t i = 0; i <= max_static_metadata_hash_probe; i++) {
138 static_metadata_hash_ent ent =
139 static_metadata_hash[(hash + i) % GPR_ARRAY_SIZE(static_metadata_hash)];
140 const grpc_core::StaticMetadataSlice* static_slice_table =
141 grpc_static_slice_table();
142 if (ent.hash == hash && ent.idx < GRPC_STATIC_MDSTR_COUNT &&
143 grpc_slice_eq_static_interned(slice, static_slice_table[ent.idx])) {
144 *returned_slice_is_different = true;
145 return static_slice_table[ent.idx];
152 grpc_slice grpc_slice_intern(grpc_slice slice) {
153 /* TODO(arjunroy): At present, this is capable of returning either a static or
154 an interned slice. This yields weirdness like the constructor for
155 ManagedMemorySlice instantiating itself as an instance of a derived type
156 (StaticMetadataSlice or InternedSlice). Should reexamine. */
157 return grpc_core::ManagedMemorySlice(&slice);
160 // Attempt to see if the provided slice or string matches a static slice.
161 // SliceArgs is either a const grpc_slice& or const pair<const char*, size_t>&.
162 // In either case, hash is the pre-computed hash value.
164 // Returns: a matching static slice, or null.
165 template <typename SliceArgs>
166 static const grpc_core::StaticMetadataSlice* MatchStaticSlice(
167 uint32_t hash, const SliceArgs& args) {
168 for (uint32_t i = 0; i <= max_static_metadata_hash_probe; i++) {
169 static_metadata_hash_ent ent =
170 static_metadata_hash[(hash + i) % GPR_ARRAY_SIZE(static_metadata_hash)];
171 const grpc_core::StaticMetadataSlice* static_slice_table =
172 grpc_static_slice_table();
173 if (ent.hash == hash && ent.idx < GRPC_STATIC_MDSTR_COUNT &&
174 static_slice_table[ent.idx] == args) {
175 return &static_slice_table[ent.idx];
181 // Helper methods to enable us to select appropriately overloaded slice methods
182 // whether we're dealing with a slice, or a buffer with length, when interning
183 // strings. Helpers for FindOrCreateInternedSlice().
184 static const char* GetBuffer(const std::pair<const char*, size_t>& buflen) {
187 static size_t GetLength(const std::pair<const char*, size_t>& buflen) {
188 return buflen.second;
190 static const void* GetBuffer(const grpc_slice& slice) {
191 return GRPC_SLICE_START_PTR(slice);
193 static size_t GetLength(const grpc_slice& slice) {
194 return GRPC_SLICE_LENGTH(slice);
197 // Creates an interned slice for a string that does not currently exist in the
198 // intern table. SliceArgs is either a const grpc_slice& or a const
199 // pair<const char*, size_t>&. Hash is the pre-computed hash value. We must
200 // already hold the shard lock. Helper for FindOrCreateInternedSlice().
202 // Returns: a newly interned slice.
203 template <typename SliceArgs>
204 static InternedSliceRefcount* InternNewStringLocked(slice_shard* shard,
207 const SliceArgs& args) {
208 /* string data goes after the internal_string header */
209 size_t len = GetLength(args);
210 const void* buffer = GetBuffer(args);
211 InternedSliceRefcount* s =
212 static_cast<InternedSliceRefcount*>(gpr_malloc(sizeof(*s) + len));
213 new (s) grpc_core::InternedSliceRefcount(len, hash, shard->strs[shard_idx]);
214 // TODO(arjunroy): Investigate why hpack tried to intern the nullptr string.
215 // https://github.com/grpc/grpc/pull/20110#issuecomment-526729282
217 memcpy(reinterpret_cast<char*>(s + 1), buffer, len);
219 shard->strs[shard_idx] = s;
221 if (shard->count > shard->capacity * 2) {
227 // Attempt to see if the provided slice or string matches an existing interned
228 // slice. SliceArgs... is either a const grpc_slice& or a string and length. In
229 // either case, hash is the pre-computed hash value. We must already hold the
230 // shard lock. Helper for FindOrCreateInternedSlice().
232 // Returns: a pre-existing matching static slice, or null.
233 template <typename SliceArgs>
234 static InternedSliceRefcount* MatchInternedSliceLocked(uint32_t hash,
236 const SliceArgs& args) {
237 InternedSliceRefcount* s;
238 slice_shard* shard = &g_shards[SHARD_IDX(hash)];
239 /* search for an existing string */
240 for (s = shard->strs[idx]; s; s = s->bucket_next) {
241 if (s->hash == hash && grpc_core::InternedSlice(s) == args) {
242 if (s->refcnt.RefIfNonZero()) {
250 // Attempt to see if the provided slice or string matches an existing interned
251 // slice, and failing that, create an interned slice with its contents. Returns
252 // either the existing matching interned slice or the newly created one.
253 // SliceArgs is either a const grpc_slice& or const pair<const char*, size_t>&.
254 // In either case, hash is the pre-computed hash value. We do not hold the
255 // shard lock here, but do take it.
257 // Returns: an interned slice, either pre-existing/matched or newly created.
258 template <typename SliceArgs>
259 static InternedSliceRefcount* FindOrCreateInternedSlice(uint32_t hash,
260 const SliceArgs& args) {
261 slice_shard* shard = &g_shards[SHARD_IDX(hash)];
262 gpr_mu_lock(&shard->mu);
263 const size_t idx = TABLE_IDX(hash, shard->capacity);
264 InternedSliceRefcount* s = MatchInternedSliceLocked(hash, idx, args);
266 s = InternNewStringLocked(shard, idx, hash, args);
268 gpr_mu_unlock(&shard->mu);
272 grpc_core::ManagedMemorySlice::ManagedMemorySlice(const char* string)
273 : grpc_core::ManagedMemorySlice::ManagedMemorySlice(string,
276 grpc_core::ManagedMemorySlice::ManagedMemorySlice(const char* string,
278 GPR_TIMER_SCOPE("grpc_slice_intern", 0);
279 const uint32_t hash = gpr_murmur_hash3(string, len, g_hash_seed);
280 const StaticMetadataSlice* static_slice =
281 MatchStaticSlice(hash, std::pair<const char*, size_t>(string, len));
283 *this = *static_slice;
285 *this = grpc_core::InternedSlice(FindOrCreateInternedSlice(
286 hash, std::pair<const char*, size_t>(string, len)));
290 grpc_core::ManagedMemorySlice::ManagedMemorySlice(const grpc_slice* slice_ptr) {
291 GPR_TIMER_SCOPE("grpc_slice_intern", 0);
292 const grpc_slice& slice = *slice_ptr;
293 if (GRPC_IS_STATIC_METADATA_STRING(slice)) {
294 *this = static_cast<const grpc_core::StaticMetadataSlice&>(slice);
297 const uint32_t hash = grpc_slice_hash_internal(slice);
298 const StaticMetadataSlice* static_slice = MatchStaticSlice(hash, slice);
300 *this = *static_slice;
302 *this = grpc_core::InternedSlice(FindOrCreateInternedSlice(hash, slice));
306 void grpc_test_only_set_slice_hash_seed(uint32_t seed) {
307 grpc_core::g_hash_seed = seed;
308 grpc_core::g_forced_hash_seed = true;
311 void grpc_slice_intern_init(void) {
312 if (!grpc_core::g_forced_hash_seed) {
313 grpc_core::g_hash_seed =
314 static_cast<uint32_t>(gpr_now(GPR_CLOCK_REALTIME).tv_nsec);
316 for (size_t i = 0; i < SHARD_COUNT; i++) {
317 slice_shard* shard = &g_shards[i];
318 gpr_mu_init(&shard->mu);
320 shard->capacity = INITIAL_SHARD_CAPACITY;
321 shard->strs = static_cast<InternedSliceRefcount**>(
322 gpr_zalloc(sizeof(*shard->strs) * shard->capacity));
324 for (size_t i = 0; i < GPR_ARRAY_SIZE(static_metadata_hash); i++) {
325 static_metadata_hash[i].hash = 0;
326 static_metadata_hash[i].idx = GRPC_STATIC_MDSTR_COUNT;
328 max_static_metadata_hash_probe = 0;
329 const grpc_core::StaticMetadataSlice* static_slice_table =
330 grpc_static_slice_table();
331 for (size_t i = 0; i < GRPC_STATIC_MDSTR_COUNT; i++) {
332 grpc_static_metadata_hash_values[i] =
333 grpc_slice_default_hash_internal(static_slice_table[i]);
334 for (size_t j = 0; j < GPR_ARRAY_SIZE(static_metadata_hash); j++) {
335 size_t slot = (grpc_static_metadata_hash_values[i] + j) %
336 GPR_ARRAY_SIZE(static_metadata_hash);
337 if (static_metadata_hash[slot].idx == GRPC_STATIC_MDSTR_COUNT) {
338 static_metadata_hash[slot].hash = grpc_static_metadata_hash_values[i];
339 static_metadata_hash[slot].idx = static_cast<uint32_t>(i);
340 if (j > max_static_metadata_hash_probe) {
341 max_static_metadata_hash_probe = static_cast<uint32_t>(j);
347 // Handle KV hash for all static mdelems.
348 for (size_t i = 0; i < GRPC_STATIC_MDELEM_COUNT; ++i) {
349 grpc_static_mdelem_table()[i].HashInit();
353 void grpc_slice_intern_shutdown(void) {
354 for (size_t i = 0; i < SHARD_COUNT; i++) {
355 slice_shard* shard = &g_shards[i];
356 gpr_mu_destroy(&shard->mu);
357 /* TODO(ctiller): GPR_ASSERT(shard->count == 0); */
358 if (shard->count != 0) {
359 gpr_log(GPR_DEBUG, "WARNING: %" PRIuPTR " metadata strings were leaked",
361 for (size_t j = 0; j < shard->capacity; j++) {
362 for (InternedSliceRefcount* s = shard->strs[j]; s; s = s->bucket_next) {
363 char* text = grpc_dump_slice(grpc_core::InternedSlice(s),
364 GPR_DUMP_HEX | GPR_DUMP_ASCII);
365 gpr_log(GPR_DEBUG, "LEAKED: %s", text);
369 if (grpc_iomgr_abort_on_leaks()) {
373 gpr_free(shard->strs);