1 // Copyright 2016 Google Inc. All rights reserved.
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
7 // http://www.apache.org/licenses/LICENSE-2.0
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.
18 #include "zcpointer.h"
27 #define EXPECT(expr) do { if (!(expr)) { throw std::logic_error(#expr); } } while(0)
29 #if defined(ZCPOINTER_TRACK_REFS) && ZCPOINTER_TRACK_REFS
31 #define EXPECT_UAF(expr) do { \
34 throw std::logic_error("Expected use-after-free: " #expr); \
35 } catch (zc::UseAfterFreeError) {} \
40 #define EXPECT_UAF(expr) do { \
41 std::cout << ">>> ZCPOINTER_TRACK_REFS not enabled, cannot catch UAF" << std::endl; \
48 zc
::owned
<C
> c(new C());
49 zc
::ref
<C
> owned
= c
.get();
50 zc
::ref
<C
> owned2
= owned
;
52 EXPECT_UAF(owned2
->DoThing());
57 zc
::owned
<T
> t(new T());
58 //T* unwrap = t.get();
60 zc
::ref
<T
> ref
= t
.get();
65 zc
::owned
<C
> c(new C());
66 zc
::ref
<C
> owned
= c
.get();
68 zc
::owned
<C
> c2(std
::move(c
));
72 EXPECT_UAF(owned
->DoThing());
75 void PtrHelper(zc
::ref
<C
>* out
) {
76 zc
::owned
<C
> c(new C());
83 EXPECT_UAF(ref
->DoThing());
87 zc
::owned
<C
> a(new C());
88 zc
::owned
<C
> b(new C());
94 zc
::ref
<C
> ra
= a
.get();
95 zc
::ref
<C
> rb
= b
.get();
98 EXPECT(ra
== a
.get());
100 EXPECT(rb
== b
.get());
104 zc
::ref
<C
> r
= a
.get();
106 EXPECT(r
== a
.get());
110 zc
::ref
<C
> rc
= nullptr;
112 EXPECT(rc
== c
.get());
113 EXPECT(c
== nullptr);
114 EXPECT(rc
== nullptr);
123 zc
::ref
<C
> rl
= l
.get();
124 zc
::ref
<C
> rr
= r
.get();
129 EXPECT(l
== nullptr);
130 EXPECT(r
== nullptr);
131 EXPECT(rl
== nullptr);
132 EXPECT(rr
== nullptr);
137 std
::vector
<zc
::ref
<C
>> vec
{
143 for (const auto& r
: vec
) {
144 EXPECT(r
== c
.get());
149 std
::vector
<zc
::owned
<C
>> vec
;
150 vec
.push_back(std
::move(zc
::owned
<C
>(new C())));
151 vec
.push_back(std
::move(zc
::owned
<C
>(new C())));
152 vec
.push_back(std
::move(zc
::owned
<C
>(new C())));
155 EXPECT_UAF(ref
->DoThing());
158 #define TEST_FUNC(fn) { #fn , Test##fn }
174 for (const auto& test
: kTests
) {
175 std
::cout
<< "=== BEGIN " << test
.name
<< " ===" << std
::endl
;
178 std
::cout
<< "+++ PASS " << test
.name
<< " +++" << std
::endl
;
179 } catch (const std
::logic_error
& e
) {
181 std
::cout
<< "!!! FAIL " << test
.name
182 << ": Assertion failure: " << e
.what() << " ===" << std
::endl
;
186 return passed ?
0 : 1;