1 // Copyright 2022 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // 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, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14
15 #include "pw_intrusive_ptr/internal/ref_counted_base.h"
16
17 #include <atomic>
18 #include <cstdint>
19
20 #include "pw_assert/check.h"
21
22 namespace pw::internal {
23
~RefCountedBase()24 RefCountedBase::~RefCountedBase() {
25 // Set the ref count to a poison value so that we have the best chance of
26 // catching a use-after-free situation.
27 //
28 // The value is chosen specifically to be negative when stored as an int32_t,
29 // and as far away from becoming positive (via either addition or subtraction)
30 // as possible.
31 ref_count_.store(static_cast<int32_t>(0xC0000000), std::memory_order_release);
32 }
33
AddRef() const34 void RefCountedBase::AddRef() const {
35 const auto refs = ref_count_.fetch_add(1, std::memory_order_relaxed);
36
37 // This assertion will fire if someone calls AddRef() on a ref-counted object
38 // that has reached ref_count_ == 0 but has not been destroyed yet. This could
39 // happen by manually calling AddRef(), or re-wrapping such a pointer with
40 // RefPtr<T>(T*) (which calls AddRef()).
41 PW_DCHECK(refs >= 0);
42 }
43
ReleaseRef() const44 bool RefCountedBase::ReleaseRef() const {
45 // We don't follow the boost::intrusive_ptr/fit::RefPtr approach here with a
46 // release fetch_sub and acquire fence afterwards due to TSAN not supporting
47 // fences (see https://gcc.gnu.org/bugzilla/show_bug.cgi?id=97868).
48 //
49 // This approach is a bit less performant - it does the acquiring on each
50 // release, not only for the last ref - but otherwise works the same.
51 const auto refs = ref_count_.fetch_sub(1, std::memory_order_acq_rel);
52
53 // This assertion will fire if someone manually calls ReleaseRef()
54 // on a ref-counted object too many times, or if ReleaseRef is called
55 // before an object has been wrapped with RefPtr.
56 PW_DCHECK(refs >= 1);
57
58 return refs == 1;
59 }
60
61 } // namespace pw::internal
62