-
Notifications
You must be signed in to change notification settings - Fork 404
/
rc.hpp
1440 lines (1276 loc) · 44.2 KB
/
rc.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// OpenVPN -- An application to securely tunnel IP networks
// over a single port, with support for SSL/TLS-based
// session authentication and key exchange,
// packet encryption, packet authentication, and
// packet compression.
//
// Copyright (C) 2012- OpenVPN Inc.
//
// SPDX-License-Identifier: MPL-2.0 OR AGPL-3.0-only WITH openvpn3-openssl-exception
//
// A basic reference-counting garbage collection scheme based
// on intrusive pointers, where the reference count is embedded in
// the object via inheritance. Simply inherit from RC to create an
// object that can be tracked with an RCPtr.
//
// We use tend to use RCPtr (or RCWeakPtr) rather than the other
// smart pointer classes (std or boost) for flexibility and
// performance.
//
// Smart pointers have two basic attributes that determine
// their performance. Either of these attributes, when required,
// will degrade the performance of the smart pointer:
//
// 1. whether the smart pointer is thread-safe, i.e. it uses an
// atomic reference counter
// 2. whether the smart pointer can be referrred to via a
// weak reference
//
// In keeping with the oft-stated C++ motto of only paying for
// what you use, both attributes can be independently controlled.
//
// * thread-unsafe/not-weak-referenceable -- class Foo : public RC<thread_unsafe_refcount>
// * thread-safe/not-weak-referenceable -- class Foo : public RC<thread_safe_refcount>
// * thread-unsafe/weak-referenceable -- class Foo : public RCWeak<thread_unsafe_refcount>
// * thread-safe/weak-referenceable -- class Foo : public RCWeak<thread_safe_refcount>
//
// Thread-safe reference counting can be significantly more expensive
// because an atomic object must be used for the reference count.
// Therefore, thread-safe reference counting should only be used for
// objects that have visibility across multiple threads.
//
// In addition, having an object be weak-referenceable also
// imposes a cost, so it should be avoided unless necessary.
//
// For clarity and as a general convention in the OpenVPN code,
// any object that inherits from RC should also declare a Ptr
// typedef that defines the smart pointer type that should be used to
// track the object, e.g.:
//
// class Foo : public RC<thread_unsafe_refcount> {
// public:
// typedef RCPtr<Foo> Ptr; // strong pointer
// typedef RCWeakPtr<Foo> WPtr; // weak pointer
// };
//
// This allows a smart-pointer to Foo to be referred to
// as Foo::Ptr or Foo::WPtr.
//
// Note that RC/RCWeak fully supports virtual inheritance. For
// example, consider the diamond inheritance pattern below, where
// both A and B objects contain their own reference count, but C
// inherits from both A and B. To prevent C objects from
// having two separate reference counts, it is necessary to
// virtually inherit from RC.
//
// class A : public virtual RC<thread_unsafe_refcount> {}
// class B : public virtual RC<thread_unsafe_refcount> {}
// class C : public A, public B {}
#ifndef OPENVPN_COMMON_RC_H
#define OPENVPN_COMMON_RC_H
#include <atomic>
#include <utility>
#include <openvpn/common/olong.hpp>
#ifdef OPENVPN_RC_DEBUG
#include <iostream>
#include <openvpn/common/demangle.hpp>
#endif
namespace openvpn {
/**
@brief The smart pointer class
@tparam T an RC enabled type
Defines a template class called RCPtr that implements a smart pointer for
reference counted objects.
RCPtr is a template class, meaning it can be instantiated for any type T that
supports reference counting. It keeps track of a pointer to an object of type T,
and handles incrementing and decrementing the reference count automatically.
The purpose of RCPtr is to automate reference counting for any reference-counted
object (any class that inherits from RC). It provides a safe way to have multiple
pointers to an object without worrying about memory leaks or double-frees.
RCPtr has a pointer member variable px that holds a pointer to the T object it
references. It overloads operators like * and -> to dereference the pointer and
access the referenced object.
The key methods are the constructors and destructor. The constructors increment
the reference count, and the destructor decrements it. This ensures the object
will stay allocated as long as any RCPtr points to it, and be freed when the
last RCPtr is destructed.
Copy and move constructors increment the refcount before assigning px, while
move assignment operators decrement the old refcount after reassigning px.
RCPtr is a smart pointer class that automates reference counting for any
reference-counted type T, allowing multiple pointer ownership without leaks or
double-frees.
*/
template <typename T>
class RCPtr
{
public:
typedef T element_type;
RCPtr() noexcept;
RCPtr(T *p, const bool add_ref = true) noexcept;
RCPtr(const RCPtr &rhs) noexcept;
RCPtr(RCPtr &&rhs) noexcept;
template <typename U>
RCPtr(const RCPtr<U> &rhs) noexcept;
~RCPtr();
RCPtr &operator=(const RCPtr &rhs) noexcept;
RCPtr &operator=(RCPtr &&rhs) noexcept;
void reset() noexcept;
void reset(T *rhs) noexcept;
void swap(RCPtr &rhs) noexcept;
T *get() const noexcept;
T &operator*() const noexcept;
T *operator->() const noexcept;
explicit operator bool() const noexcept;
bool operator==(const RCPtr &rhs) const;
bool operator!=(const RCPtr &rhs) const;
RCPtr<T> move_strong() noexcept;
template <typename U>
RCPtr<U> static_pointer_cast() const noexcept;
template <typename U>
RCPtr<U> dynamic_pointer_cast() const noexcept;
private:
T *px; ///< Pointer to the controlled object
};
/**
@brief Construct a new RCPtr<T>::RCPtr object
@tparam T an RC enabled type
The default constructor for the RCPtr class
This constructor initializes the RCPtr class with no referenced object. It sets the
internal px pointer to nullptr. The purpose of this default constructor is to allow
creating an RCPtr instance that doesn't yet reference anything. This is useful when
you need to declare an RCPtr variable but don't have an object to assign it to yet.
*/
template <typename T>
RCPtr<T>::RCPtr() noexcept
: px(nullptr){};
/**
@brief Construct a new RCPtr<T>::RCPtr object
@tparam T an RC enabled type
@param p pointer to an RC enabled object
@param add_ref bool that determines whether the RC of p is incremented
The RCPtr constructor taking a pointer and bool
This constructor initializes an RCPtr instance to point to a provided object pointer p.
It takes two inputs:
- p - a pointer to an object of type T that inherits from RC (reference counted).
- add_ref - a bool indicating if the reference count of p should be incremented.
It does not return anything directly. Its purpose is to construct an RCPtr instance.
The key logic is:
- The px member is assigned the provided pointer p.
- If add_ref is true, and px is non-null, the reference count of px is incremented
via openvpn::intrusive_ptr_add_ref().
This achieves the goal of constructing an RCPtr that points to the provided object pointer
p. If add_ref is true, it will also increment the ref count of p, indicating that RCPtr
now owns a count on that object.
*/
template <typename T>
RCPtr<T>::RCPtr(T *p, const bool add_ref) noexcept
: px(p)
{
if (px && add_ref)
intrusive_ptr_add_ref(px);
}
/**
@brief Copy constructor for RCPtr
@tparam T an RC enabled type
@param rhs the RCPtr to be copied
*/
template <typename T>
RCPtr<T>::RCPtr(const RCPtr &rhs) noexcept
: px(rhs.px)
{
if (px)
intrusive_ptr_add_ref(px);
}
/**
@brief Construct a new RCPtr object via move
@tparam T an RC enabled type
@param rhs object from which to move
*/
template <typename T>
RCPtr<T>::RCPtr(RCPtr &&rhs) noexcept
: px(rhs.px)
{
rhs.px = nullptr;
}
/**
@brief Construct a new RCPtr<T>::RCPtr object to type T and make it track an object of type U
@tparam T an RC enabled type
@tparam U an RC enabled type
@param rhs "RCPtr<U>" pointing to the object the new RCPtr<T> will reference as well
This achieves the goal of creating an RCPtr<T> that points to the same object as the "RCPtr<U>".
*/
template <typename T>
template <typename U>
RCPtr<T>::RCPtr(const RCPtr<U> &rhs) noexcept
: px(rhs.get())
{
if (px)
intrusive_ptr_add_ref(px);
}
/**
@brief Destroy the RCPtr<T>::RCPtr object
@tparam T an RC enabled type
This achieves the goal of reducing the refcount when the RCPtr is destructed, possibly deleting
the object if no other RCPtrs reference it anymore. The key data transformation is decrementing
the refcount via openvpn::intrusive_ptr_release().
*/
template <typename T>
RCPtr<T>::~RCPtr()
{
if (px)
intrusive_ptr_release(px);
}
/**
@brief Assigns an existing RCPtr<T> to point to a different T
@tparam T an RC enabled type
@param rhs other RCPtr<T>
@return reference to this
Assigns an existing RCPtr<T> to point to a different T, which is already controlled by another
RCPtr<T>. Reduces the refcount on the current T.
*/
template <typename T>
RCPtr<T> &RCPtr<T>::operator=(const RCPtr &rhs) noexcept
{
// notice that RCPtr(rhs) is a temp built from rhs, which will decrement old T when scope ends
RCPtr(rhs).swap(*this);
return *this;
}
/**
@brief Assigns an existing RCPtr<T> to point to a different T using move
@tparam T an RC enabled type
@param rhs other RCPtr<T>
@return reference to this
Assigns an existing RCPtr<T> to point to a different T using move, by stealing the guts of another
RCPtr.
*/
template <typename T>
RCPtr<T> &RCPtr<T>::operator=(RCPtr &&rhs) noexcept
{
RCPtr(std::move(rhs)).swap(*this);
return *this;
}
/**
@brief Points this RCPtr<T> to nullptr safely
@tparam T an RC enabled type
*/
template <typename T>
void RCPtr<T>::reset() noexcept
{
RCPtr().swap(*this);
}
/**
@brief Points this RCPtr to an RC enabled object T
@note It's critical that the object in question be allocated via new.
@tparam T an RC enabled type
@param rhs pointer to the object that will be managed by this pointer
*/
template <typename T>
void RCPtr<T>::reset(T *rhs) noexcept
{
RCPtr(rhs).swap(*this);
}
/**
@brief swaps the contents of two RCPtr<T>
@tparam T an RC enabled type
@param rhs the other RCPtr<T>
*/
template <typename T>
void RCPtr<T>::swap(RCPtr &rhs) noexcept
{
std::swap(px, rhs.px);
}
/**
@brief Returns the raw pointer to the object T, or nullptr.
@tparam T an RC enabled type
@return T* pointer we are tracking, or nullptr.
*/
template <typename T>
T *RCPtr<T>::get() const noexcept
{
return px;
}
/**
@brief Operator returns a ref to the pointed to T
@tparam T an RC enabled type
@return T& reference to the object this RCPtr points to
Operator returns a ref to the pointed to T, or if the RCPtr does not point
to a valid T, undefined behavior due to dereference of invalid pointer. This
is identical to the behavior of a C ptr or the STL smart pointers.
*/
template <typename T>
T &RCPtr<T>::operator*() const noexcept
{
return *px;
}
/**
@brief Returns the raw pointer to the object T, or nullptr.
@tparam T an RC enabled type
@return T* pointer we are tracking, or nullptr.
*/
template <typename T>
T *RCPtr<T>::operator->() const noexcept
{
return px;
}
/**
@brief Evaluates to true if the internal pointer is not equal to nullptr
@tparam T an RC enabled type
@return true if internal pointer is not equal to nullptr
@return false if internal pointer is equal to nullptr
*/
template <typename T>
RCPtr<T>::operator bool() const noexcept
{
return px != nullptr;
}
/**
@brief Evaluates to true if the two RCPtr<T> point to the same object.
@note Does not check equality of the pointed two object, rather checks for identity.
@tparam T an RC enabled type
@param rhs other RCPtr<T>
@return true if *this and rhs point to the same instance or both equal nullptr
@return false if *this and rhs point to different instances or do not both equal nullptr
*/
template <typename T>
bool RCPtr<T>::operator==(const RCPtr &rhs) const
{
return px == rhs.px;
}
/**
@brief Evaluates to true if the two RCPtr<T> point to different objects.
@tparam T an RC enabled type
@param rhs other RCPtr<T>
@return true if *this and rhs point to different instances or do not both equal nullptr
@return false if *this and rhs point to the same instance or both equal nullptr
*/
template <typename T>
bool RCPtr<T>::operator!=(const RCPtr &rhs) const
{
return px != rhs.px;
}
/**
@brief Moves ownership of the internal pointer to the returned RCPtr<T>
@tparam T an RC enabled type
@return The new owning RCPtr<T>
*/
template <typename T>
RCPtr<T> RCPtr<T>::move_strong() noexcept
{
T *p = px;
px = nullptr;
return RCPtr<T>(p, false);
}
/**
@brief Returns a "RCPtr<U>" that points to our T object
@tparam T an RC enabled type
@tparam U an RC enabled type
@return "RCPtr<U>" that points to the same object this points to
Performs a static_cast from T * to U * and then wraps the cast pointer in a new "RCPtr<U>"
*/
template <typename T>
template <typename U>
RCPtr<U> RCPtr<T>::static_pointer_cast() const noexcept
{
return RCPtr<U>(static_cast<U *>(px));
}
/**
@brief Returns a "RCPtr<U>" that points to our T object
@tparam T an RC enabled type
@tparam U an RC enabled type
@return "RCPtr<U>" that points to the same object this points to, or nullptr
Performs a dynamic_cast from T * to U * and then wraps the cast pointer in a new "RCPtr<U>",
or if the dynamic_cast fails the result will equal nullptr cast to U * in a new "RCPtr<U>".
*/
template <typename T>
template <typename U>
RCPtr<U> RCPtr<T>::dynamic_pointer_cast() const noexcept
{
return RCPtr<U>(dynamic_cast<U *>(px));
}
/**
@brief implements a weak pointer for reference counted objects.
@tparam T RCWeak enabled type
RCWeakPtr takes a template parameter T which is the type of the object it will hold a weak pointer
to. T must be a reference counted type. The purpose of RCWeakPtr is to hold a non-owning pointer to
a reference counted object that can be converted to a strong owning pointer if the object still
exists. It allows having a pointer to an object without affecting its reference count.
RCWeakPtr contains a member variable controller which holds a pointer to the reference count
controller object of the T object it points to. This allows it to query the reference count and
check if the object still exists.
The class provides methods to initialize the weak pointer from a strong pointer or raw pointer to a
T object. This sets the controller to point to the T object's reference count controller.
It also provides methods to reset the pointer, check if it has expired (if the object was deleted),
get a strong owning pointer via lock() if the object still exists, and get the reference count.
The key benefit of RCWeakPtr is being able to hold a non-owning pointer to a reference counted object
without affecting its lifetime. It allows referencing the object without incrementing the reference
count and can check if the object was deleted.
*/
template <typename T>
class RCWeakPtr
{
typedef RCPtr<T> Strong;
public:
typedef T element_type;
RCWeakPtr() noexcept;
RCWeakPtr(const Strong &p) noexcept;
RCWeakPtr(T *p) noexcept;
void reset(const Strong &p) noexcept;
void reset(T *p) noexcept;
void reset() noexcept;
void swap(RCWeakPtr &other) noexcept;
olong use_count() const noexcept;
bool expired() const noexcept;
Strong lock() const noexcept;
Strong move_strong() noexcept;
private:
typename T::Controller::Ptr controller; ///< Smart pointer to the T::ControllerF
};
/**
@brief Construct a new RCWeakPtr<T>::RCWeakPtr object
@tparam T RCWeak enabled type
*/
template <typename T>
RCWeakPtr<T>::RCWeakPtr() noexcept {};
/**
@brief Construct a new RCWeakPtr<T>::RCWeakPtr object
@tparam T RCWeak enabled type
@param p RCPtr that holds a reference to an RCWeak::Controller
*/
template <typename T>
RCWeakPtr<T>::RCWeakPtr(const Strong &p) noexcept
{
if (p)
controller = p->refcount_.controller;
}
/**
@brief Construct a new RCWeakPtr<T>::RCWeakPtr object
@tparam T RCWeak enabled type
@param p raw pointer to T
*/
template <typename T>
RCWeakPtr<T>::RCWeakPtr(T *p) noexcept
{
if (p)
controller = p->refcount_.controller;
}
/**
@brief Reassign this weak ptr to the object referenced by the given strong (RCPtr) pointer
@tparam T RCWeak enabled type
@param p Strong pointer to an RCWeak enabled object instance
*/
template <typename T>
void RCWeakPtr<T>::reset(const Strong &p) noexcept
{
if (p)
controller = p->refcount_.controller;
else
controller.reset();
}
/**
@brief Reassign this weak pointer to reference the controller within the specified object
@tparam T RCWeak enabled type
@param p an instance of an RCWeak enabled type
*/
template <typename T>
void RCWeakPtr<T>::reset(T *p) noexcept
{
if (p)
controller = p->refcount_.controller;
else
controller.reset();
}
/**
@brief remove any existing reference
@tparam T RCWeak enabled type
*/
template <typename T>
void RCWeakPtr<T>::reset() noexcept
{
controller.reset();
}
/**
@brief Swaps thing pointed to by *this withthing pointed to by other
@tparam T RCWeak enabled type
@param other the RCWeakPtr with which *this is to be swapped
*/
template <typename T>
void RCWeakPtr<T>::swap(RCWeakPtr &other) noexcept
{
controller.swap(other.controller);
}
/**
@brief Returns count of references to the object
@tparam T RCWeak enabled type
@return olong ref count
If we point to a controller, we return the object use count for the object the controller
refers to. Otherwise we return zero.
*/
template <typename T>
olong RCWeakPtr<T>::use_count() const noexcept
{
if (controller)
return controller->use_count();
else
return 0;
}
/**
@brief Returns true if the underlying object is already freed.
@tparam T RCWeak enabled type
@return true if the object has been freed.
@return false if the object still exists.
*/
template <typename T>
bool RCWeakPtr<T>::expired() const noexcept
{
return use_count() == 0;
}
/**
@brief Tries to upgrade the weak reference to a strong reference and returns that result
@tparam T RCWeak enabled type
@return RCWeakPtr<T>::Strong
If the underlying object has been freed, returns empty Strong ptr, otherwise returns a
Strong referring to the object.
*/
template <typename T>
typename RCWeakPtr<T>::Strong RCWeakPtr<T>::lock() const noexcept
{
if (controller)
return controller->template lock<Strong>();
else
return Strong();
}
/**
@brief Try to move the weak pointer into a strong pointer
@tparam T RCWeak enabled type
@return RCWeakPtr<T>::Strong to the weakly referred to T or nullptr if the T is no longer available
Releases the weak reference and either takes and returns a strong reference if possible
or nullptr if the lock cannot be accomplished.
*/
template <typename T>
typename RCWeakPtr<T>::Strong RCWeakPtr<T>::move_strong() noexcept
{
typename T::Controller::Ptr c;
c.swap(controller);
if (c)
return c->template lock<Strong>();
else
return Strong();
}
/* We're pretty sure these are false positives. They only occur with very
specific compiler versions and/or architectures.
For some reason some gcc versions think that the reference counter goes
away too soon when destructing certain MultiCompleteType objects. The
warnings/errors do not tell us why they think that.
So for now we display the warnings, but do not fail -Werror builds over
them. So that we can fail them for any other new warnings.
*/
#if !defined(__clang__) && defined(__GNUC__)
#pragma GCC diagnostic push
#if __GNUC__ == 12
#pragma GCC diagnostic warning "-Wuse-after-free"
#endif
#if __GNUC__ == 13 || __GNUC__ == 14
#pragma GCC diagnostic warning "-Wstringop-overflow"
#endif
#endif
/**
@brief implements a simple reference count for objects.
The purpose of thread_unsafe_refcount is to keep track of how many references exist to an
object and automatically delete the object when the reference count reaches zero. It
provides methods to increment, decrement, and read the current reference count.
thread_unsafe_refcount contains a member variable rc which holds the current reference count
number as a type olong. Overall, thread_unsafe_refcount provides simple reference counting
functionality to track object references in a single-threaded context. It could be used to
implement basic automatic memory management based on scope and references for objects.
*/
class thread_unsafe_refcount
{
public:
thread_unsafe_refcount() noexcept;
void operator++() noexcept;
olong operator--() noexcept;
bool inc_if_nonzero() noexcept;
olong use_count() const noexcept;
static constexpr bool is_thread_safe();
#ifdef OPENVPN_RC_NOTIFY
void notify_release() noexcept;
#endif
#ifdef OPENVPN_RC_NOTIFY
template <typename T>
class ListHead;
#endif
private:
thread_unsafe_refcount(const thread_unsafe_refcount &) = delete;
thread_unsafe_refcount &operator=(const thread_unsafe_refcount &) = delete;
olong rc; ///< The reference count, platform efficient integer type
};
/**
@brief Construct a new thread unsafe refcount::thread unsafe refcount object
initializes rc to 0 for a new object with no references.
*/
inline thread_unsafe_refcount::thread_unsafe_refcount() noexcept
: rc(olong(0)) {};
/**
@brief Increment ref count by 1
*/
inline void thread_unsafe_refcount::operator++() noexcept
{
++rc;
}
/**
@brief Decrement ref count by 1
@return olong
*/
inline olong thread_unsafe_refcount::operator--() noexcept
{
return --rc;
}
/**
@brief Increments refcount by 1 if refcount is not 0, returns true if it incremented refcount
@return true if the ref count was incremented
@return false if the ref count was not incremented
*/
inline bool thread_unsafe_refcount::inc_if_nonzero() noexcept
{
if (rc)
{
++rc;
return true;
}
else
return false;
}
/**
@brief Returns the internal use count
@return olong ref count
*/
inline olong thread_unsafe_refcount::use_count() const noexcept
{
return rc;
}
/**
@brief Returns false for this type
@return false
This allows a uniform way to check at compile time or runtime and determine if the
refcount type is thread safe or not. This one is not.
*/
inline constexpr bool thread_unsafe_refcount::is_thread_safe()
{
return false;
}
#ifdef OPENVPN_RC_NOTIFY
inline void thread_unsafe_refcount::notify_release() noexcept
{
}
#endif
#ifdef OPENVPN_RC_NOTIFY
template <typename T>
class thread_unsafe_refcount::ListHead
{
public:
ListHead() noexcept
: ptr(nullptr)
{
}
T *load() noexcept
{
return ptr;
}
void insert(T *item) noexcept
{
item->next = ptr;
ptr = item;
}
private:
ListHead(const ListHead &) = delete;
ListHead &operator=(const ListHead &) = delete;
T *ptr;
};
#endif
/**
@brief Implements a memory fenced ref count
*/
class thread_safe_refcount
{
public:
thread_safe_refcount() noexcept;
void operator++() noexcept;
olong operator--() noexcept;
bool inc_if_nonzero() noexcept;
olong use_count() const noexcept;
static constexpr bool is_thread_safe();
#ifdef OPENVPN_RC_NOTIFY
void notify_release() noexcept;
#endif
#ifdef OPENVPN_RC_NOTIFY
template <typename T>
class ListHead;
#endif
private:
thread_safe_refcount(const thread_safe_refcount &) = delete;
thread_safe_refcount &operator=(const thread_safe_refcount &) = delete;
std::atomic<olong> rc;
};
/**
@brief Construct a new thread safe refcount object
*/
inline thread_safe_refcount::thread_safe_refcount() noexcept
: rc(olong(0))
{
}
/**
@brief Atomically increment the refcount by 1
*/
inline void thread_safe_refcount::operator++() noexcept
{
rc.fetch_add(1, std::memory_order_relaxed);
}
/**
@brief Atomically decrement the internal counter by 1
@return olong decremented ref count
*/
inline olong thread_safe_refcount::operator--() noexcept
{
// http://www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html
const olong ret = rc.fetch_sub(1, std::memory_order_release) - 1;
if (ret == 0)
std::atomic_thread_fence(std::memory_order_acquire);
return ret;
}
/**
@brief Atomically increments refcount by 1 if refcount is not 0, returns true if it incremented refcount
@return true if refcount was incremented
@return false if refcount was not incremented
If refcount is 0, do nothing and return false. If refcount != 0, increment it and return true.
*/
inline bool thread_safe_refcount::inc_if_nonzero() noexcept
{
olong previous = rc.load(std::memory_order_relaxed);
while (true)
{
if (!previous)
break;
if (rc.compare_exchange_weak(previous, previous + 1, std::memory_order_relaxed))
break;
}
return previous > 0;
}
/**
@brief Returns the internal use count
@return olong ref count
*/
inline olong thread_safe_refcount::use_count() const noexcept
{
return rc.load(std::memory_order_relaxed);
}
/**
@brief Returns true for this class
@return true
This allows a uniform way to check at compile time or runtime and determine if the
refcount type is thread safe or not. This one is thread safe.
*/
inline constexpr bool thread_safe_refcount::is_thread_safe()
{
return true;
}
#ifdef OPENVPN_RC_NOTIFY
inline void thread_safe_refcount::notify_release() noexcept
{
}
#endif
#ifdef OPENVPN_RC_NOTIFY
template <typename T>
class thread_safe_refcount::ListHead
{
public:
ListHead() noexcept
: ptr(nullptr)
{
}
T *load() noexcept
{
return ptr;
}
void insert(T *item) noexcept
{
item->next = ptr;
ptr = item;
}
private:
ListHead(const ListHead &) = delete;
ListHead &operator=(const ListHead &) = delete;
T *ptr;
};
#endif
#if !defined(__clang__) && defined(__GNUC__)
#pragma GCC diagnostic pop
#endif
/**
@brief Reference count base class for objects tracked by RCPtr. Disallows copying and assignment.
Implements basic reference counting functionality for objects.
The purpose of RC is to provide a base class that other classes can inherit from to enable
reference counting and automatic memory management. It takes a template parameter RCImpl which
specifies the actual reference count implementation class that will be used, either
thread_safe_refcount or thread_unsafe_refcount.
RC provides a common base class for enabling reference counting on other classes via inheritance.
It delegates the actual reference count tracking to the RCImpl implementation specified as a
template parameter. It also prohibits copy or assignment of the inheriting object.
The member functions just delegate to the refcount_ object that's injected via template.
@tparam RCImpl The ref count implementation that will be used - thread_safe_refcount or thread_unsafe_refcount
*/
template <typename RCImpl>
class RC
{
public:
typedef RCPtr<RC> Ptr;
RC() noexcept = default;
virtual ~RC() = default;
RC(const RC &) = delete;
RC &operator=(const RC &) = delete;
olong use_count() const noexcept;
static constexpr bool is_thread_safe();
private:
template <typename R>
friend void intrusive_ptr_add_ref(R *rcptr) noexcept;
template <typename R>
friend void intrusive_ptr_release(R *rcptr) noexcept;
RCImpl refcount_;
};
/**
@brief Delegates call to RCImpl and returns the result
@tparam RCImpl a suitable ref count implementation
@return olong ref count
*/
template <typename RCImpl>
olong RC<RCImpl>::use_count() const noexcept
{
return refcount_.use_count();
}
/**
@brief Delegates call to RCImpl and returns the result
@tparam RCImpl a suitable ref count implementation
@return true if the underlying RCImpl is thread safe
@return false if the underlying RCImpl is not thread safe
*/
template <typename RCImpl>
constexpr bool RC<RCImpl>::is_thread_safe()
{
return RCImpl::is_thread_safe();
}
/**
@brief Reference count base class for objects tracked by RCPtr. Allows copying and assignment.
@tparam RCImpl The ref count implementation that will be used - thread_safe_refcount or thread_unsafe_refcount
Implements basic reference counting functionality for objects plus copy/assign.
The purpose of RCCopyable is to provide a base class that other classes can inherit from to
enable reference counting and automatic memory management. It takes a template parameter
RCImpl which specifies the actual reference count implementation class that will be used, either
thread_safe_refcount or thread_unsafe_refcount.
RCCopyable provides a common base class for enabling reference counting on other classes via
inheritance. It delegates the actual reference count tracking to the RCImpl implementation
specified as a template parameter.
Since copy and assignment are allowed and this is a reference counted type, some atypical logic
is implemented to make those operations work properly. This means that while the rest of the
inheriting object will be copied as per usual, for this object we will give the copy a fresh
reference count, since the count is bookkeeping metadata. The referencing pointers to the individual
objects will then take care of properly maintaining the RC of the new and the donor object as
per usual.
The member functions just delegate to the refcount_ object that's injected via template.
*/
template <typename RCImpl>
class RCCopyable
{
public:
virtual ~RCCopyable() = default;
RCCopyable() noexcept = default;
RCCopyable(const RCCopyable &) noexcept;
RCCopyable(RCCopyable &&) noexcept;
RCCopyable &operator=(const RCCopyable &) noexcept;
RCCopyable &operator=(RCCopyable &&) noexcept;
olong use_count() const noexcept;
private:
template <typename R>
friend void intrusive_ptr_add_ref(R *rcptr) noexcept;
template <typename R>
friend void intrusive_ptr_release(R *rcptr) noexcept;
RCImpl refcount_;
};
/**
@brief Construct a new RCCopyable object
@tparam RCImpl RC compatible type to use as ref count