Coverage Report

Created: 2024-09-23 06:29

/src/abseil-cpp/absl/base/call_once.h
Line
Count
Source (jump to first uncovered line)
1
// Copyright 2017 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
// -----------------------------------------------------------------------------
16
// File: call_once.h
17
// -----------------------------------------------------------------------------
18
//
19
// This header file provides an Abseil version of `std::call_once` for invoking
20
// a given function at most once, across all threads. This Abseil version is
21
// faster than the C++11 version and incorporates the C++17 argument-passing
22
// fix, so that (for example) non-const references may be passed to the invoked
23
// function.
24
25
#ifndef ABSL_BASE_CALL_ONCE_H_
26
#define ABSL_BASE_CALL_ONCE_H_
27
28
#include <algorithm>
29
#include <atomic>
30
#include <cstdint>
31
#include <type_traits>
32
#include <utility>
33
34
#include "absl/base/internal/invoke.h"
35
#include "absl/base/internal/low_level_scheduling.h"
36
#include "absl/base/internal/raw_logging.h"
37
#include "absl/base/internal/scheduling_mode.h"
38
#include "absl/base/internal/spinlock_wait.h"
39
#include "absl/base/macros.h"
40
#include "absl/base/nullability.h"
41
#include "absl/base/optimization.h"
42
#include "absl/base/port.h"
43
44
namespace absl {
45
ABSL_NAMESPACE_BEGIN
46
47
class once_flag;
48
49
namespace base_internal {
50
absl::Nonnull<std::atomic<uint32_t>*> ControlWord(
51
    absl::Nonnull<absl::once_flag*> flag);
52
}  // namespace base_internal
53
54
// call_once()
55
//
56
// For all invocations using a given `once_flag`, invokes a given `fn` exactly
57
// once across all threads. The first call to `call_once()` with a particular
58
// `once_flag` argument (that does not throw an exception) will run the
59
// specified function with the provided `args`; other calls with the same
60
// `once_flag` argument will not run the function, but will wait
61
// for the provided function to finish running (if it is still running).
62
//
63
// This mechanism provides a safe, simple, and fast mechanism for one-time
64
// initialization in a multi-threaded process.
65
//
66
// Example:
67
//
68
// class MyInitClass {
69
//  public:
70
//  ...
71
//  mutable absl::once_flag once_;
72
//
73
//  MyInitClass* init() const {
74
//    absl::call_once(once_, &MyInitClass::Init, this);
75
//    return ptr_;
76
//  }
77
//
78
template <typename Callable, typename... Args>
79
void call_once(absl::once_flag& flag, Callable&& fn, Args&&... args);
80
81
// once_flag
82
//
83
// Objects of this type are used to distinguish calls to `call_once()` and
84
// ensure the provided function is only invoked once across all threads. This
85
// type is not copyable or movable. However, it has a `constexpr`
86
// constructor, and is safe to use as a namespace-scoped global variable.
87
class once_flag {
88
 public:
89
0
  constexpr once_flag() : control_(0) {}
90
  once_flag(const once_flag&) = delete;
91
  once_flag& operator=(const once_flag&) = delete;
92
93
 private:
94
  friend absl::Nonnull<std::atomic<uint32_t>*> base_internal::ControlWord(
95
      absl::Nonnull<once_flag*> flag);
96
  std::atomic<uint32_t> control_;
97
};
98
99
//------------------------------------------------------------------------------
100
// End of public interfaces.
101
// Implementation details follow.
102
//------------------------------------------------------------------------------
103
104
namespace base_internal {
105
106
// Like call_once, but uses KERNEL_ONLY scheduling. Intended to be used to
107
// initialize entities used by the scheduler implementation.
108
template <typename Callable, typename... Args>
109
void LowLevelCallOnce(absl::Nonnull<absl::once_flag*> flag, Callable&& fn,
110
                      Args&&... args);
111
112
// Disables scheduling while on stack when scheduling mode is non-cooperative.
113
// No effect for cooperative scheduling modes.
114
class SchedulingHelper {
115
 public:
116
6
  explicit SchedulingHelper(base_internal::SchedulingMode mode) : mode_(mode) {
117
6
    if (mode_ == base_internal::SCHEDULE_KERNEL_ONLY) {
118
2
      guard_result_ = base_internal::SchedulingGuard::DisableRescheduling();
119
2
    }
120
6
  }
121
122
6
  ~SchedulingHelper() {
123
6
    if (mode_ == base_internal::SCHEDULE_KERNEL_ONLY) {
124
2
      base_internal::SchedulingGuard::EnableRescheduling(guard_result_);
125
2
    }
126
6
  }
127
128
 private:
129
  base_internal::SchedulingMode mode_;
130
  bool guard_result_ = false;
131
};
132
133
// Bit patterns for call_once state machine values.  Internal implementation
134
// detail, not for use by clients.
135
//
136
// The bit patterns are arbitrarily chosen from unlikely values, to aid in
137
// debugging.  However, kOnceInit must be 0, so that a zero-initialized
138
// once_flag will be valid for immediate use.
139
enum {
140
  kOnceInit = 0,
141
  kOnceRunning = 0x65C2937B,
142
  kOnceWaiter = 0x05A308D2,
143
  // A very small constant is chosen for kOnceDone so that it fit in a single
144
  // compare with immediate instruction for most common ISAs.  This is verified
145
  // for x86, POWER and ARM.
146
  kOnceDone = 221,    // Random Number
147
};
148
149
template <typename Callable, typename... Args>
150
ABSL_ATTRIBUTE_NOINLINE void CallOnceImpl(
151
    absl::Nonnull<std::atomic<uint32_t>*> control,
152
    base_internal::SchedulingMode scheduling_mode, Callable&& fn,
153
6
    Args&&... args) {
154
6
#ifndef NDEBUG
155
6
  {
156
6
    uint32_t old_control = control->load(std::memory_order_relaxed);
157
6
    if (old_control != kOnceInit &&
158
6
        old_control != kOnceRunning &&
159
6
        old_control != kOnceWaiter &&
160
6
        old_control != kOnceDone) {
161
0
      ABSL_RAW_LOG(FATAL, "Unexpected value for control word: 0x%lx",
162
0
                   static_cast<unsigned long>(old_control));  // NOLINT
163
0
    }
164
6
  }
165
6
#endif  // NDEBUG
166
6
  static const base_internal::SpinLockWaitTransition trans[] = {
167
6
      {kOnceInit, kOnceRunning, true},
168
6
      {kOnceRunning, kOnceWaiter, false},
169
6
      {kOnceDone, kOnceDone, true}};
170
171
  // Must do this before potentially modifying control word's state.
172
6
  base_internal::SchedulingHelper maybe_disable_scheduling(scheduling_mode);
173
  // Short circuit the simplest case to avoid procedure call overhead.
174
  // The base_internal::SpinLockWait() call returns either kOnceInit or
175
  // kOnceDone. If it returns kOnceDone, it must have loaded the control word
176
  // with std::memory_order_acquire and seen a value of kOnceDone.
177
6
  uint32_t old_control = kOnceInit;
178
6
  if (control->compare_exchange_strong(old_control, kOnceRunning,
179
6
                                       std::memory_order_relaxed) ||
180
6
      base_internal::SpinLockWait(control, ABSL_ARRAYSIZE(trans), trans,
181
6
                                  scheduling_mode) == kOnceInit) {
182
6
    base_internal::invoke(std::forward<Callable>(fn),
183
6
                          std::forward<Args>(args)...);
184
6
    old_control =
185
6
        control->exchange(base_internal::kOnceDone, std::memory_order_release);
186
6
    if (old_control == base_internal::kOnceWaiter) {
187
0
      base_internal::SpinLockWake(control, true);
188
0
    }
189
6
  }  // else *control is already kOnceDone
190
6
}
void absl::base_internal::CallOnceImpl<void (absl::flags_internal::FlagImpl::*)(), absl::flags_internal::FlagImpl*>(std::__1::atomic<unsigned int>*, absl::base_internal::SchedulingMode, void (absl::flags_internal::FlagImpl::*&&)(), absl::flags_internal::FlagImpl*&&)
Line
Count
Source
153
1
    Args&&... args) {
154
1
#ifndef NDEBUG
155
1
  {
156
1
    uint32_t old_control = control->load(std::memory_order_relaxed);
157
1
    if (old_control != kOnceInit &&
158
1
        old_control != kOnceRunning &&
159
1
        old_control != kOnceWaiter &&
160
1
        old_control != kOnceDone) {
161
0
      ABSL_RAW_LOG(FATAL, "Unexpected value for control word: 0x%lx",
162
0
                   static_cast<unsigned long>(old_control));  // NOLINT
163
0
    }
164
1
  }
165
1
#endif  // NDEBUG
166
1
  static const base_internal::SpinLockWaitTransition trans[] = {
167
1
      {kOnceInit, kOnceRunning, true},
168
1
      {kOnceRunning, kOnceWaiter, false},
169
1
      {kOnceDone, kOnceDone, true}};
170
171
  // Must do this before potentially modifying control word's state.
172
1
  base_internal::SchedulingHelper maybe_disable_scheduling(scheduling_mode);
173
  // Short circuit the simplest case to avoid procedure call overhead.
174
  // The base_internal::SpinLockWait() call returns either kOnceInit or
175
  // kOnceDone. If it returns kOnceDone, it must have loaded the control word
176
  // with std::memory_order_acquire and seen a value of kOnceDone.
177
1
  uint32_t old_control = kOnceInit;
178
1
  if (control->compare_exchange_strong(old_control, kOnceRunning,
179
1
                                       std::memory_order_relaxed) ||
180
1
      base_internal::SpinLockWait(control, ABSL_ARRAYSIZE(trans), trans,
181
1
                                  scheduling_mode) == kOnceInit) {
182
1
    base_internal::invoke(std::forward<Callable>(fn),
183
1
                          std::forward<Args>(args)...);
184
1
    old_control =
185
1
        control->exchange(base_internal::kOnceDone, std::memory_order_release);
186
1
    if (old_control == base_internal::kOnceWaiter) {
187
0
      base_internal::SpinLockWake(control, true);
188
0
    }
189
1
  }  // else *control is already kOnceDone
190
1
}
log_sink_set.cc:void absl::base_internal::CallOnceImpl<absl::log_internal::(anonymous namespace)::StderrLogSink::Send(absl::LogEntry const&)::{lambda()#1}>(std::__1::atomic<unsigned int>*, absl::base_internal::SchedulingMode, absl::log_internal::(anonymous namespace)::StderrLogSink::Send(absl::LogEntry const&)::{lambda()#1}&&)
Line
Count
Source
153
1
    Args&&... args) {
154
1
#ifndef NDEBUG
155
1
  {
156
1
    uint32_t old_control = control->load(std::memory_order_relaxed);
157
1
    if (old_control != kOnceInit &&
158
1
        old_control != kOnceRunning &&
159
1
        old_control != kOnceWaiter &&
160
1
        old_control != kOnceDone) {
161
0
      ABSL_RAW_LOG(FATAL, "Unexpected value for control word: 0x%lx",
162
0
                   static_cast<unsigned long>(old_control));  // NOLINT
163
0
    }
164
1
  }
165
1
#endif  // NDEBUG
166
1
  static const base_internal::SpinLockWaitTransition trans[] = {
167
1
      {kOnceInit, kOnceRunning, true},
168
1
      {kOnceRunning, kOnceWaiter, false},
169
1
      {kOnceDone, kOnceDone, true}};
170
171
  // Must do this before potentially modifying control word's state.
172
1
  base_internal::SchedulingHelper maybe_disable_scheduling(scheduling_mode);
173
  // Short circuit the simplest case to avoid procedure call overhead.
174
  // The base_internal::SpinLockWait() call returns either kOnceInit or
175
  // kOnceDone. If it returns kOnceDone, it must have loaded the control word
176
  // with std::memory_order_acquire and seen a value of kOnceDone.
177
1
  uint32_t old_control = kOnceInit;
178
1
  if (control->compare_exchange_strong(old_control, kOnceRunning,
179
1
                                       std::memory_order_relaxed) ||
180
1
      base_internal::SpinLockWait(control, ABSL_ARRAYSIZE(trans), trans,
181
1
                                  scheduling_mode) == kOnceInit) {
182
1
    base_internal::invoke(std::forward<Callable>(fn),
183
1
                          std::forward<Args>(args)...);
184
1
    old_control =
185
1
        control->exchange(base_internal::kOnceDone, std::memory_order_release);
186
1
    if (old_control == base_internal::kOnceWaiter) {
187
0
      base_internal::SpinLockWake(control, true);
188
0
    }
189
1
  }  // else *control is already kOnceDone
190
1
}
Unexecuted instantiation: mutex.cc:void absl::base_internal::CallOnceImpl<absl::(anonymous namespace)::GetMutexGlobals()::$_0>(std::__1::atomic<unsigned int>*, absl::base_internal::SchedulingMode, absl::(anonymous namespace)::GetMutexGlobals()::$_0&&)
void absl::base_internal::CallOnceImpl<void (&)()>(std::__1::atomic<unsigned int>*, absl::base_internal::SchedulingMode, void (&)())
Line
Count
Source
153
2
    Args&&... args) {
154
2
#ifndef NDEBUG
155
2
  {
156
2
    uint32_t old_control = control->load(std::memory_order_relaxed);
157
2
    if (old_control != kOnceInit &&
158
2
        old_control != kOnceRunning &&
159
2
        old_control != kOnceWaiter &&
160
2
        old_control != kOnceDone) {
161
0
      ABSL_RAW_LOG(FATAL, "Unexpected value for control word: 0x%lx",
162
0
                   static_cast<unsigned long>(old_control));  // NOLINT
163
0
    }
164
2
  }
165
2
#endif  // NDEBUG
166
2
  static const base_internal::SpinLockWaitTransition trans[] = {
167
2
      {kOnceInit, kOnceRunning, true},
168
2
      {kOnceRunning, kOnceWaiter, false},
169
2
      {kOnceDone, kOnceDone, true}};
170
171
  // Must do this before potentially modifying control word's state.
172
2
  base_internal::SchedulingHelper maybe_disable_scheduling(scheduling_mode);
173
  // Short circuit the simplest case to avoid procedure call overhead.
174
  // The base_internal::SpinLockWait() call returns either kOnceInit or
175
  // kOnceDone. If it returns kOnceDone, it must have loaded the control word
176
  // with std::memory_order_acquire and seen a value of kOnceDone.
177
2
  uint32_t old_control = kOnceInit;
178
2
  if (control->compare_exchange_strong(old_control, kOnceRunning,
179
2
                                       std::memory_order_relaxed) ||
180
2
      base_internal::SpinLockWait(control, ABSL_ARRAYSIZE(trans), trans,
181
2
                                  scheduling_mode) == kOnceInit) {
182
2
    base_internal::invoke(std::forward<Callable>(fn),
183
2
                          std::forward<Args>(args)...);
184
2
    old_control =
185
2
        control->exchange(base_internal::kOnceDone, std::memory_order_release);
186
2
    if (old_control == base_internal::kOnceWaiter) {
187
0
      base_internal::SpinLockWake(control, true);
188
0
    }
189
2
  }  // else *control is already kOnceDone
190
2
}
Unexecuted instantiation: spinlock.cc:void absl::base_internal::CallOnceImpl<absl::base_internal::SpinLock::SpinLoop()::$_0>(std::__1::atomic<unsigned int>*, absl::base_internal::SchedulingMode, absl::base_internal::SpinLock::SpinLoop()::$_0&&)
Unexecuted instantiation: sysinfo.cc:void absl::base_internal::CallOnceImpl<absl::base_internal::NumCPUs()::$_0>(std::__1::atomic<unsigned int>*, absl::base_internal::SchedulingMode, absl::base_internal::NumCPUs()::$_0&&)
Unexecuted instantiation: sysinfo.cc:void absl::base_internal::CallOnceImpl<absl::base_internal::NominalCPUFrequency()::$_0>(std::__1::atomic<unsigned int>*, absl::base_internal::SchedulingMode, absl::base_internal::NominalCPUFrequency()::$_0&&)
void absl::base_internal::CallOnceImpl<void (&)(void (*)(void*)), void (*&)(void*)>(std::__1::atomic<unsigned int>*, absl::base_internal::SchedulingMode, void (&)(void (*)(void*)), void (*&)(void*))
Line
Count
Source
153
2
    Args&&... args) {
154
2
#ifndef NDEBUG
155
2
  {
156
2
    uint32_t old_control = control->load(std::memory_order_relaxed);
157
2
    if (old_control != kOnceInit &&
158
2
        old_control != kOnceRunning &&
159
2
        old_control != kOnceWaiter &&
160
2
        old_control != kOnceDone) {
161
0
      ABSL_RAW_LOG(FATAL, "Unexpected value for control word: 0x%lx",
162
0
                   static_cast<unsigned long>(old_control));  // NOLINT
163
0
    }
164
2
  }
165
2
#endif  // NDEBUG
166
2
  static const base_internal::SpinLockWaitTransition trans[] = {
167
2
      {kOnceInit, kOnceRunning, true},
168
2
      {kOnceRunning, kOnceWaiter, false},
169
2
      {kOnceDone, kOnceDone, true}};
170
171
  // Must do this before potentially modifying control word's state.
172
2
  base_internal::SchedulingHelper maybe_disable_scheduling(scheduling_mode);
173
  // Short circuit the simplest case to avoid procedure call overhead.
174
  // The base_internal::SpinLockWait() call returns either kOnceInit or
175
  // kOnceDone. If it returns kOnceDone, it must have loaded the control word
176
  // with std::memory_order_acquire and seen a value of kOnceDone.
177
2
  uint32_t old_control = kOnceInit;
178
2
  if (control->compare_exchange_strong(old_control, kOnceRunning,
179
2
                                       std::memory_order_relaxed) ||
180
2
      base_internal::SpinLockWait(control, ABSL_ARRAYSIZE(trans), trans,
181
2
                                  scheduling_mode) == kOnceInit) {
182
2
    base_internal::invoke(std::forward<Callable>(fn),
183
2
                          std::forward<Args>(args)...);
184
2
    old_control =
185
2
        control->exchange(base_internal::kOnceDone, std::memory_order_release);
186
2
    if (old_control == base_internal::kOnceWaiter) {
187
0
      base_internal::SpinLockWake(control, true);
188
0
    }
189
2
  }  // else *control is already kOnceDone
190
2
}
191
192
inline absl::Nonnull<std::atomic<uint32_t>*> ControlWord(
193
3.79M
    absl::Nonnull<once_flag*> flag) {
194
3.79M
  return &flag->control_;
195
3.79M
}
196
197
template <typename Callable, typename... Args>
198
void LowLevelCallOnce(absl::Nonnull<absl::once_flag*> flag, Callable&& fn,
199
10
                      Args&&... args) {
200
10
  std::atomic<uint32_t>* once = base_internal::ControlWord(flag);
201
10
  uint32_t s = once->load(std::memory_order_acquire);
202
10
  if (ABSL_PREDICT_FALSE(s != base_internal::kOnceDone)) {
203
2
    base_internal::CallOnceImpl(once, base_internal::SCHEDULE_KERNEL_ONLY,
204
2
                                std::forward<Callable>(fn),
205
2
                                std::forward<Args>(args)...);
206
2
  }
207
10
}
Unexecuted instantiation: mutex.cc:void absl::base_internal::LowLevelCallOnce<absl::(anonymous namespace)::GetMutexGlobals()::$_0>(absl::once_flag*, absl::(anonymous namespace)::GetMutexGlobals()::$_0&&)
void absl::base_internal::LowLevelCallOnce<void (&)()>(absl::once_flag*, void (&)())
Line
Count
Source
199
10
                      Args&&... args) {
200
10
  std::atomic<uint32_t>* once = base_internal::ControlWord(flag);
201
10
  uint32_t s = once->load(std::memory_order_acquire);
202
10
  if (ABSL_PREDICT_FALSE(s != base_internal::kOnceDone)) {
203
2
    base_internal::CallOnceImpl(once, base_internal::SCHEDULE_KERNEL_ONLY,
204
2
                                std::forward<Callable>(fn),
205
2
                                std::forward<Args>(args)...);
206
2
  }
207
10
}
Unexecuted instantiation: spinlock.cc:void absl::base_internal::LowLevelCallOnce<absl::base_internal::SpinLock::SpinLoop()::$_0>(absl::once_flag*, absl::base_internal::SpinLock::SpinLoop()::$_0&&)
Unexecuted instantiation: sysinfo.cc:void absl::base_internal::LowLevelCallOnce<absl::base_internal::NumCPUs()::$_0>(absl::once_flag*, absl::base_internal::NumCPUs()::$_0&&)
Unexecuted instantiation: sysinfo.cc:void absl::base_internal::LowLevelCallOnce<absl::base_internal::NominalCPUFrequency()::$_0>(absl::once_flag*, absl::base_internal::NominalCPUFrequency()::$_0&&)
208
209
}  // namespace base_internal
210
211
template <typename Callable, typename... Args>
212
3.79M
void call_once(absl::once_flag& flag, Callable&& fn, Args&&... args) {
213
3.79M
  std::atomic<uint32_t>* once = base_internal::ControlWord(&flag);
214
3.79M
  uint32_t s = once->load(std::memory_order_acquire);
215
3.79M
  if (ABSL_PREDICT_FALSE(s != base_internal::kOnceDone)) {
216
4
    base_internal::CallOnceImpl(
217
4
        once, base_internal::SCHEDULE_COOPERATIVE_AND_KERNEL,
218
4
        std::forward<Callable>(fn), std::forward<Args>(args)...);
219
4
  }
220
3.79M
}
void absl::call_once<void (absl::flags_internal::FlagImpl::*)(), absl::flags_internal::FlagImpl*>(absl::once_flag&, void (absl::flags_internal::FlagImpl::*&&)(), absl::flags_internal::FlagImpl*&&)
Line
Count
Source
212
1
void call_once(absl::once_flag& flag, Callable&& fn, Args&&... args) {
213
1
  std::atomic<uint32_t>* once = base_internal::ControlWord(&flag);
214
1
  uint32_t s = once->load(std::memory_order_acquire);
215
1
  if (ABSL_PREDICT_FALSE(s != base_internal::kOnceDone)) {
216
1
    base_internal::CallOnceImpl(
217
1
        once, base_internal::SCHEDULE_COOPERATIVE_AND_KERNEL,
218
1
        std::forward<Callable>(fn), std::forward<Args>(args)...);
219
1
  }
220
1
}
log_sink_set.cc:void absl::call_once<absl::log_internal::(anonymous namespace)::StderrLogSink::Send(absl::LogEntry const&)::{lambda()#1}>(absl::once_flag&, absl::log_internal::(anonymous namespace)::StderrLogSink::Send(absl::LogEntry const&)::{lambda()#1}&&)
Line
Count
Source
212
3.79M
void call_once(absl::once_flag& flag, Callable&& fn, Args&&... args) {
213
3.79M
  std::atomic<uint32_t>* once = base_internal::ControlWord(&flag);
214
3.79M
  uint32_t s = once->load(std::memory_order_acquire);
215
3.79M
  if (ABSL_PREDICT_FALSE(s != base_internal::kOnceDone)) {
216
1
    base_internal::CallOnceImpl(
217
1
        once, base_internal::SCHEDULE_COOPERATIVE_AND_KERNEL,
218
1
        std::forward<Callable>(fn), std::forward<Args>(args)...);
219
1
  }
220
3.79M
}
void absl::call_once<void (&)(void (*)(void*)), void (*&)(void*)>(absl::once_flag&, void (&)(void (*)(void*)), void (*&)(void*))
Line
Count
Source
212
2
void call_once(absl::once_flag& flag, Callable&& fn, Args&&... args) {
213
2
  std::atomic<uint32_t>* once = base_internal::ControlWord(&flag);
214
2
  uint32_t s = once->load(std::memory_order_acquire);
215
2
  if (ABSL_PREDICT_FALSE(s != base_internal::kOnceDone)) {
216
2
    base_internal::CallOnceImpl(
217
2
        once, base_internal::SCHEDULE_COOPERATIVE_AND_KERNEL,
218
2
        std::forward<Callable>(fn), std::forward<Args>(args)...);
219
2
  }
220
2
}
221
222
ABSL_NAMESPACE_END
223
}  // namespace absl
224
225
#endif  // ABSL_BASE_CALL_ONCE_H_