Coverage Report

Created: 2025-07-11 06:37

/src/abseil-cpp/absl/container/internal/container_memory.h
Line
Count
Source (jump to first uncovered line)
1
// Copyright 2018 The Abseil Authors.
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
//      https://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14
15
#ifndef ABSL_CONTAINER_INTERNAL_CONTAINER_MEMORY_H_
16
#define ABSL_CONTAINER_INTERNAL_CONTAINER_MEMORY_H_
17
18
#include <cassert>
19
#include <cstddef>
20
#include <cstdint>
21
#include <cstring>
22
#include <memory>
23
#include <new>
24
#include <tuple>
25
#include <type_traits>
26
#include <utility>
27
28
#include "absl/base/config.h"
29
#include "absl/hash/hash.h"
30
#include "absl/memory/memory.h"
31
#include "absl/meta/type_traits.h"
32
#include "absl/utility/utility.h"
33
34
#ifdef ABSL_HAVE_ADDRESS_SANITIZER
35
#include <sanitizer/asan_interface.h>
36
#endif
37
38
#ifdef ABSL_HAVE_MEMORY_SANITIZER
39
#include <sanitizer/msan_interface.h>
40
#endif
41
42
namespace absl {
43
ABSL_NAMESPACE_BEGIN
44
namespace container_internal {
45
46
template <size_t Alignment>
47
struct alignas(Alignment) AlignedType {};
48
49
// Allocates at least n bytes aligned to the specified alignment.
50
// Alignment must be a power of 2. It must be positive.
51
//
52
// Note that many allocators don't honor alignment requirements above certain
53
// threshold (usually either alignof(std::max_align_t) or alignof(void*)).
54
// Allocate() doesn't apply alignment corrections. If the underlying allocator
55
// returns insufficiently alignment pointer, that's what you are going to get.
56
template <size_t Alignment, class Alloc>
57
void* Allocate(Alloc* alloc, size_t n) {
58
  static_assert(Alignment > 0, "");
59
  assert(n && "n must be positive");
60
  using M = AlignedType<Alignment>;
61
  using A = typename absl::allocator_traits<Alloc>::template rebind_alloc<M>;
62
  using AT = typename absl::allocator_traits<Alloc>::template rebind_traits<M>;
63
  // On macOS, "mem_alloc" is a #define with one argument defined in
64
  // rpc/types.h, so we can't name the variable "mem_alloc" and initialize it
65
  // with the "foo(bar)" syntax.
66
  A my_mem_alloc(*alloc);
67
  void* p = AT::allocate(my_mem_alloc, (n + sizeof(M) - 1) / sizeof(M));
68
  assert(reinterpret_cast<uintptr_t>(p) % Alignment == 0 &&
69
         "allocator does not respect alignment");
70
  return p;
71
}
72
73
// Returns true if the destruction of the value with given Allocator will be
74
// trivial.
75
template <class Allocator, class ValueType>
76
constexpr auto IsDestructionTrivial() {
77
  constexpr bool result =
78
      std::is_trivially_destructible<ValueType>::value &&
79
      std::is_same<typename absl::allocator_traits<
80
                       Allocator>::template rebind_alloc<char>,
81
                   std::allocator<char>>::value;
82
  return std::integral_constant<bool, result>();
83
}
84
85
// The pointer must have been previously obtained by calling
86
// Allocate<Alignment>(alloc, n).
87
template <size_t Alignment, class Alloc>
88
void Deallocate(Alloc* alloc, void* p, size_t n) {
89
  static_assert(Alignment > 0, "");
90
  assert(n && "n must be positive");
91
  using M = AlignedType<Alignment>;
92
  using A = typename absl::allocator_traits<Alloc>::template rebind_alloc<M>;
93
  using AT = typename absl::allocator_traits<Alloc>::template rebind_traits<M>;
94
  // On macOS, "mem_alloc" is a #define with one argument defined in
95
  // rpc/types.h, so we can't name the variable "mem_alloc" and initialize it
96
  // with the "foo(bar)" syntax.
97
  A my_mem_alloc(*alloc);
98
  AT::deallocate(my_mem_alloc, static_cast<M*>(p),
99
                 (n + sizeof(M) - 1) / sizeof(M));
100
}
101
102
namespace memory_internal {
103
104
// Constructs T into uninitialized storage pointed by `ptr` using the args
105
// specified in the tuple.
106
template <class Alloc, class T, class Tuple, size_t... I>
107
void ConstructFromTupleImpl(Alloc* alloc, T* ptr, Tuple&& t,
108
                            absl::index_sequence<I...>) {
109
  absl::allocator_traits<Alloc>::construct(
110
      *alloc, ptr, std::get<I>(std::forward<Tuple>(t))...);
111
}
112
113
template <class T, class F>
114
struct WithConstructedImplF {
115
  template <class... Args>
116
  decltype(std::declval<F>()(std::declval<T>())) operator()(
117
      Args&&... args) const {
118
    return std::forward<F>(f)(T(std::forward<Args>(args)...));
119
  }
120
  F&& f;
121
};
122
123
template <class T, class Tuple, size_t... Is, class F>
124
decltype(std::declval<F>()(std::declval<T>())) WithConstructedImpl(
125
    Tuple&& t, absl::index_sequence<Is...>, F&& f) {
126
  return WithConstructedImplF<T, F>{std::forward<F>(f)}(
127
      std::get<Is>(std::forward<Tuple>(t))...);
128
}
129
130
template <class T, size_t... Is>
131
auto TupleRefImpl(T&& t, absl::index_sequence<Is...>)
132
    -> decltype(std::forward_as_tuple(std::get<Is>(std::forward<T>(t))...)) {
133
  return std::forward_as_tuple(std::get<Is>(std::forward<T>(t))...);
134
}
135
136
// Returns a tuple of references to the elements of the input tuple. T must be a
137
// tuple.
138
template <class T>
139
auto TupleRef(T&& t) -> decltype(TupleRefImpl(
140
    std::forward<T>(t),
141
    absl::make_index_sequence<
142
        std::tuple_size<typename std::decay<T>::type>::value>())) {
143
  return TupleRefImpl(
144
      std::forward<T>(t),
145
      absl::make_index_sequence<
146
          std::tuple_size<typename std::decay<T>::type>::value>());
147
}
148
149
template <class F, class K, class V>
150
decltype(std::declval<F>()(std::declval<const K&>(), std::piecewise_construct,
151
                           std::declval<std::tuple<K>>(), std::declval<V>()))
152
DecomposePairImpl(F&& f, std::pair<std::tuple<K>, V> p) {
153
  const auto& key = std::get<0>(p.first);
154
  return std::forward<F>(f)(key, std::piecewise_construct, std::move(p.first),
155
                            std::move(p.second));
156
}
157
158
}  // namespace memory_internal
159
160
// Constructs T into uninitialized storage pointed by `ptr` using the args
161
// specified in the tuple.
162
template <class Alloc, class T, class Tuple>
163
void ConstructFromTuple(Alloc* alloc, T* ptr, Tuple&& t) {
164
  memory_internal::ConstructFromTupleImpl(
165
      alloc, ptr, std::forward<Tuple>(t),
166
      absl::make_index_sequence<
167
          std::tuple_size<typename std::decay<Tuple>::type>::value>());
168
}
169
170
// Constructs T using the args specified in the tuple and calls F with the
171
// constructed value.
172
template <class T, class Tuple, class F>
173
decltype(std::declval<F>()(std::declval<T>())) WithConstructed(Tuple&& t,
174
                                                               F&& f) {
175
  return memory_internal::WithConstructedImpl<T>(
176
      std::forward<Tuple>(t),
177
      absl::make_index_sequence<
178
          std::tuple_size<typename std::decay<Tuple>::type>::value>(),
179
      std::forward<F>(f));
180
}
181
182
// Given arguments of an std::pair's constructor, PairArgs() returns a pair of
183
// tuples with references to the passed arguments. The tuples contain
184
// constructor arguments for the first and the second elements of the pair.
185
//
186
// The following two snippets are equivalent.
187
//
188
// 1. std::pair<F, S> p(args...);
189
//
190
// 2. auto a = PairArgs(args...);
191
//    std::pair<F, S> p(std::piecewise_construct,
192
//                      std::move(a.first), std::move(a.second));
193
0
inline std::pair<std::tuple<>, std::tuple<>> PairArgs() { return {}; }
194
template <class F, class S>
195
std::pair<std::tuple<F&&>, std::tuple<S&&>> PairArgs(F&& f, S&& s) {
196
  return {std::piecewise_construct, std::forward_as_tuple(std::forward<F>(f)),
197
          std::forward_as_tuple(std::forward<S>(s))};
198
}
199
template <class F, class S>
200
std::pair<std::tuple<const F&>, std::tuple<const S&>> PairArgs(
201
    const std::pair<F, S>& p) {
202
  return PairArgs(p.first, p.second);
203
}
204
template <class F, class S>
205
std::pair<std::tuple<F&&>, std::tuple<S&&>> PairArgs(std::pair<F, S>&& p) {
206
  return PairArgs(std::forward<F>(p.first), std::forward<S>(p.second));
207
}
208
template <class F, class S>
209
auto PairArgs(std::piecewise_construct_t, F&& f, S&& s)
210
    -> decltype(std::make_pair(memory_internal::TupleRef(std::forward<F>(f)),
211
                               memory_internal::TupleRef(std::forward<S>(s)))) {
212
  return std::make_pair(memory_internal::TupleRef(std::forward<F>(f)),
213
                        memory_internal::TupleRef(std::forward<S>(s)));
214
}
215
216
// A helper function for implementing apply() in map policies.
217
template <class F, class... Args>
218
auto DecomposePair(F&& f, Args&&... args)
219
    -> decltype(memory_internal::DecomposePairImpl(
220
        std::forward<F>(f), PairArgs(std::forward<Args>(args)...))) {
221
  return memory_internal::DecomposePairImpl(
222
      std::forward<F>(f), PairArgs(std::forward<Args>(args)...));
223
}
224
225
// A helper function for implementing apply() in set policies.
226
template <class F, class Arg>
227
decltype(std::declval<F>()(std::declval<const Arg&>(), std::declval<Arg>()))
228
DecomposeValue(F&& f, Arg&& arg) {
229
  const auto& key = arg;
230
  return std::forward<F>(f)(key, std::forward<Arg>(arg));
231
}
232
233
// Helper functions for asan and msan.
234
8.02M
inline void SanitizerPoisonMemoryRegion(const void* m, size_t s) {
235
#ifdef ABSL_HAVE_ADDRESS_SANITIZER
236
  ASAN_POISON_MEMORY_REGION(m, s);
237
#endif
238
#ifdef ABSL_HAVE_MEMORY_SANITIZER
239
  __msan_poison(m, s);
240
#endif
241
8.02M
  (void)m;
242
8.02M
  (void)s;
243
8.02M
}
244
245
16.5M
inline void SanitizerUnpoisonMemoryRegion(const void* m, size_t s) {
246
#ifdef ABSL_HAVE_ADDRESS_SANITIZER
247
  ASAN_UNPOISON_MEMORY_REGION(m, s);
248
#endif
249
#ifdef ABSL_HAVE_MEMORY_SANITIZER
250
  __msan_unpoison(m, s);
251
#endif
252
16.5M
  (void)m;
253
16.5M
  (void)s;
254
16.5M
}
255
256
template <typename T>
257
inline void SanitizerPoisonObject(const T* object) {
258
  SanitizerPoisonMemoryRegion(object, sizeof(T));
259
}
260
261
template <typename T>
262
inline void SanitizerUnpoisonObject(const T* object) {
263
  SanitizerUnpoisonMemoryRegion(object, sizeof(T));
264
}
265
266
namespace memory_internal {
267
268
// If Pair is a standard-layout type, OffsetOf<Pair>::kFirst and
269
// OffsetOf<Pair>::kSecond are equivalent to offsetof(Pair, first) and
270
// offsetof(Pair, second) respectively. Otherwise they are -1.
271
//
272
// The purpose of OffsetOf is to avoid calling offsetof() on non-standard-layout
273
// type, which is non-portable.
274
template <class Pair, class = std::true_type>
275
struct OffsetOf {
276
  static constexpr size_t kFirst = static_cast<size_t>(-1);
277
  static constexpr size_t kSecond = static_cast<size_t>(-1);
278
};
279
280
template <class Pair>
281
struct OffsetOf<Pair, typename std::is_standard_layout<Pair>::type> {
282
  static constexpr size_t kFirst = offsetof(Pair, first);
283
  static constexpr size_t kSecond = offsetof(Pair, second);
284
};
285
286
template <class K, class V>
287
struct IsLayoutCompatible {
288
 private:
289
  struct Pair {
290
    K first;
291
    V second;
292
  };
293
294
  // Is P layout-compatible with Pair?
295
  template <class P>
296
  static constexpr bool LayoutCompatible() {
297
    return std::is_standard_layout<P>() && sizeof(P) == sizeof(Pair) &&
298
           alignof(P) == alignof(Pair) &&
299
           memory_internal::OffsetOf<P>::kFirst ==
300
               memory_internal::OffsetOf<Pair>::kFirst &&
301
           memory_internal::OffsetOf<P>::kSecond ==
302
               memory_internal::OffsetOf<Pair>::kSecond;
303
  }
304
305
 public:
306
  // Whether pair<const K, V> and pair<K, V> are layout-compatible. If they are,
307
  // then it is safe to store them in a union and read from either.
308
  static constexpr bool value = std::is_standard_layout<K>() &&
309
                                std::is_standard_layout<Pair>() &&
310
                                memory_internal::OffsetOf<Pair>::kFirst == 0 &&
311
                                LayoutCompatible<std::pair<K, V>>() &&
312
                                LayoutCompatible<std::pair<const K, V>>();
313
};
314
315
}  // namespace memory_internal
316
317
// The internal storage type for key-value containers like flat_hash_map.
318
//
319
// It is convenient for the value_type of a flat_hash_map<K, V> to be
320
// pair<const K, V>; the "const K" prevents accidental modification of the key
321
// when dealing with the reference returned from find() and similar methods.
322
// However, this creates other problems; we want to be able to emplace(K, V)
323
// efficiently with move operations, and similarly be able to move a
324
// pair<K, V> in insert().
325
//
326
// The solution is this union, which aliases the const and non-const versions
327
// of the pair. This also allows flat_hash_map<const K, V> to work, even though
328
// that has the same efficiency issues with move in emplace() and insert() -
329
// but people do it anyway.
330
//
331
// If kMutableKeys is false, only the value member can be accessed.
332
//
333
// If kMutableKeys is true, key can be accessed through all slots while value
334
// and mutable_value must be accessed only via INITIALIZED slots. Slots are
335
// created and destroyed via mutable_value so that the key can be moved later.
336
//
337
// Accessing one of the union fields while the other is active is safe as
338
// long as they are layout-compatible, which is guaranteed by the definition of
339
// kMutableKeys. For C++11, the relevant section of the standard is
340
// https://timsong-cpp.github.io/cppwp/n3337/class.mem#19 (9.2.19)
341
template <class K, class V>
342
union map_slot_type {
343
  map_slot_type() {}
344
  ~map_slot_type() = delete;
345
  using value_type = std::pair<const K, V>;
346
  using mutable_value_type =
347
      std::pair<absl::remove_const_t<K>, absl::remove_const_t<V>>;
348
349
  value_type value;
350
  mutable_value_type mutable_value;
351
  absl::remove_const_t<K> key;
352
};
353
354
template <class K, class V>
355
struct map_slot_policy {
356
  using slot_type = map_slot_type<K, V>;
357
  using value_type = std::pair<const K, V>;
358
  using mutable_value_type =
359
      std::pair<absl::remove_const_t<K>, absl::remove_const_t<V>>;
360
361
 private:
362
  static void emplace(slot_type* slot) {
363
    // The construction of union doesn't do anything at runtime but it allows us
364
    // to access its members without violating aliasing rules.
365
    new (slot) slot_type;
366
  }
367
  // If pair<const K, V> and pair<K, V> are layout-compatible, we can accept one
368
  // or the other via slot_type. We are also free to access the key via
369
  // slot_type::key in this case.
370
  using kMutableKeys = memory_internal::IsLayoutCompatible<K, V>;
371
372
 public:
373
  static value_type& element(slot_type* slot) { return slot->value; }
374
  static const value_type& element(const slot_type* slot) {
375
    return slot->value;
376
  }
377
378
  static K& mutable_key(slot_type* slot) {
379
    // Still check for kMutableKeys so that we can avoid calling std::launder
380
    // unless necessary because it can interfere with optimizations.
381
    return kMutableKeys::value ? slot->key
382
                               : *std::launder(const_cast<K*>(
383
                                     std::addressof(slot->value.first)));
384
  }
385
386
  static const K& key(const slot_type* slot) {
387
    return kMutableKeys::value ? slot->key : slot->value.first;
388
  }
389
390
  template <class Allocator, class... Args>
391
  static void construct(Allocator* alloc, slot_type* slot, Args&&... args) {
392
    emplace(slot);
393
    if (kMutableKeys::value) {
394
      absl::allocator_traits<Allocator>::construct(*alloc, &slot->mutable_value,
395
                                                   std::forward<Args>(args)...);
396
    } else {
397
      absl::allocator_traits<Allocator>::construct(*alloc, &slot->value,
398
                                                   std::forward<Args>(args)...);
399
    }
400
  }
401
402
  // Construct this slot by moving from another slot.
403
  template <class Allocator>
404
  static void construct(Allocator* alloc, slot_type* slot, slot_type* other) {
405
    emplace(slot);
406
    if (kMutableKeys::value) {
407
      absl::allocator_traits<Allocator>::construct(
408
          *alloc, &slot->mutable_value, std::move(other->mutable_value));
409
    } else {
410
      absl::allocator_traits<Allocator>::construct(*alloc, &slot->value,
411
                                                   std::move(other->value));
412
    }
413
  }
414
415
  // Construct this slot by copying from another slot.
416
  template <class Allocator>
417
  static void construct(Allocator* alloc, slot_type* slot,
418
                        const slot_type* other) {
419
    emplace(slot);
420
    absl::allocator_traits<Allocator>::construct(*alloc, &slot->value,
421
                                                 other->value);
422
  }
423
424
  template <class Allocator>
425
  static auto destroy(Allocator* alloc, slot_type* slot) {
426
    if (kMutableKeys::value) {
427
      absl::allocator_traits<Allocator>::destroy(*alloc, &slot->mutable_value);
428
    } else {
429
      absl::allocator_traits<Allocator>::destroy(*alloc, &slot->value);
430
    }
431
    return IsDestructionTrivial<Allocator, value_type>();
432
  }
433
434
  template <class Allocator>
435
  static auto transfer(Allocator* alloc, slot_type* new_slot,
436
                       slot_type* old_slot) {
437
    // This should really just be
438
    // typename absl::is_trivially_relocatable<value_type>::type()
439
    // but std::pair is not trivially copyable in C++23 in some standard
440
    // library versions.
441
    // See https://github.com/llvm/llvm-project/pull/95444 for instance.
442
    auto is_relocatable = typename std::conjunction<
443
        absl::is_trivially_relocatable<typename value_type::first_type>,
444
        absl::is_trivially_relocatable<typename value_type::second_type>>::
445
        type();
446
447
    emplace(new_slot);
448
    if (is_relocatable) {
449
      // TODO(b/247130232,b/251814870): remove casts after fixing warnings.
450
      std::memcpy(static_cast<void*>(std::launder(&new_slot->value)),
451
                  static_cast<const void*>(&old_slot->value),
452
                  sizeof(value_type));
453
      return is_relocatable;
454
    }
455
456
    if (kMutableKeys::value) {
457
      absl::allocator_traits<Allocator>::construct(
458
          *alloc, &new_slot->mutable_value, std::move(old_slot->mutable_value));
459
    } else {
460
      absl::allocator_traits<Allocator>::construct(*alloc, &new_slot->value,
461
                                                   std::move(old_slot->value));
462
    }
463
    destroy(alloc, old_slot);
464
    return is_relocatable;
465
  }
466
};
467
468
// Suppress erroneous uninitialized memory errors on GCC. For example, GCC
469
// thinks that the call to slot_array() in find_or_prepare_insert() is reading
470
// uninitialized memory, but slot_array is only called there when the table is
471
// non-empty and this memory is initialized when the table is non-empty.
472
#if !defined(__clang__) && defined(__GNUC__)
473
#define ABSL_SWISSTABLE_IGNORE_UNINITIALIZED(x)                    \
474
  _Pragma("GCC diagnostic push")                                   \
475
      _Pragma("GCC diagnostic ignored \"-Wmaybe-uninitialized\"")  \
476
          _Pragma("GCC diagnostic ignored \"-Wuninitialized\"") x; \
477
  _Pragma("GCC diagnostic pop")
478
#define ABSL_SWISSTABLE_IGNORE_UNINITIALIZED_RETURN(x) \
479
  ABSL_SWISSTABLE_IGNORE_UNINITIALIZED(return x)
480
#else
481
#define ABSL_SWISSTABLE_IGNORE_UNINITIALIZED(x) x
482
609M
#define ABSL_SWISSTABLE_IGNORE_UNINITIALIZED_RETURN(x) return x
483
#endif
484
485
// Variadic arguments hash function that ignore the rest of the arguments.
486
// Useful for usage with policy traits.
487
template <class Hash, bool kIsDefault>
488
struct HashElement {
489
  HashElement(const Hash& h, size_t s) : hash(h), seed(s) {}
490
491
  template <class K, class... Args>
492
  size_t operator()(const K& key, Args&&...) const {
493
    if constexpr (kIsDefault) {
494
      // TODO(b/384509507): resolve `no header providing
495
      // "absl::hash_internal::SupportsHashWithSeed" is directly included`.
496
      // Maybe we should make "internal/hash.h" be a separate library.
497
      return absl::hash_internal::HashWithSeed().hash(hash, key, seed);
498
    }
499
    // NOLINTNEXTLINE(clang-diagnostic-sign-conversion)
500
    return hash(key) ^ seed;
501
  }
502
  const Hash& hash;
503
  size_t seed;
504
};
505
506
// No arguments function hash function for a specific key.
507
template <class Hash, class Key, bool kIsDefault>
508
struct HashKey {
509
  HashKey(const Hash& h, const Key& k) : hash(h), key(k) {}
510
511
  size_t operator()(size_t seed) const {
512
    return HashElement<Hash, kIsDefault>{hash, seed}(key);
513
  }
514
  const Hash& hash;
515
  const Key& key;
516
};
517
518
// Variadic arguments equality function that ignore the rest of the arguments.
519
// Useful for usage with policy traits.
520
template <class K1, class KeyEqual>
521
struct EqualElement {
522
  template <class K2, class... Args>
523
  bool operator()(const K2& lhs, Args&&...) const {
524
    ABSL_SWISSTABLE_IGNORE_UNINITIALIZED_RETURN(eq(lhs, rhs));
525
  }
526
  const K1& rhs;
527
  const KeyEqual& eq;
528
};
529
530
// Type erased function for computing hash of the slot.
531
using HashSlotFn = size_t (*)(const void* hash_fn, void* slot, size_t seed);
532
533
// Type erased function to apply `Fn` to data inside of the `slot`.
534
// The data is expected to have type `T`.
535
template <class Fn, class T, bool kIsDefault>
536
size_t TypeErasedApplyToSlotFn(const void* fn, void* slot, size_t seed) {
537
  const auto* f = static_cast<const Fn*>(fn);
538
  return HashElement<Fn, kIsDefault>{*f, seed}(*static_cast<const T*>(slot));
539
}
540
541
// Type erased function to apply `Fn` to data inside of the `*slot_ptr`.
542
// The data is expected to have type `T`.
543
template <class Fn, class T, bool kIsDefault>
544
size_t TypeErasedDerefAndApplyToSlotFn(const void* fn, void* slot_ptr,
545
                                       size_t seed) {
546
  const auto* f = static_cast<const Fn*>(fn);
547
  const T* slot = *static_cast<const T**>(slot_ptr);
548
  return HashElement<Fn, kIsDefault>{*f, seed}(*slot);
549
}
550
551
}  // namespace container_internal
552
ABSL_NAMESPACE_END
553
}  // namespace absl
554
555
#endif  // ABSL_CONTAINER_INTERNAL_CONTAINER_MEMORY_H_