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 #define EXPECT_UAF(expr) do { \
32 throw std::logic_error("Expected use-after-free: " #expr); \
33 } catch (zc::UseAfterFreeError) {} \
37 zc
::owned
<C
> c(new C());
38 zc
::ref
<C
> owned
= c
.get();
39 zc
::ref
<C
> owned2
= owned
;
41 EXPECT_UAF(owned2
->DoThing());
46 zc
::owned
<T
> t(new T());
47 //T* unwrap = t.get();
49 zc
::ref
<T
> ref
= t
.get();
54 zc
::owned
<C
> c(new C());
55 zc
::ref
<C
> owned
= c
.get();
57 zc
::owned
<C
> c2(std
::move(c
));
61 EXPECT_UAF(owned
->DoThing());
64 void PtrHelper(zc
::ref
<C
>* out
) {
65 zc
::owned
<C
> c(new C());
72 EXPECT_UAF(ref
->DoThing());
76 zc
::owned
<C
> a(new C());
77 zc
::owned
<C
> b(new C());
83 zc
::ref
<C
> ra
= a
.get();
84 zc
::ref
<C
> rb
= b
.get();
87 EXPECT(ra
== a
.get());
89 EXPECT(rb
== b
.get());
93 zc
::ref
<C
> r
= a
.get();
99 zc
::ref
<C
> rc
= nullptr;
101 EXPECT(rc
== c
.get());
102 EXPECT(c
== nullptr);
103 EXPECT(rc
== nullptr);
112 zc
::ref
<C
> rl
= l
.get();
113 zc
::ref
<C
> rr
= r
.get();
118 EXPECT(l
== nullptr);
119 EXPECT(r
== nullptr);
120 EXPECT(rl
== nullptr);
121 EXPECT(rr
== nullptr);
126 std
::vector
<zc
::ref
<C
>> vec
{
132 for (const auto& r
: vec
) {
133 EXPECT(r
== c
.get());
138 std
::vector
<zc
::owned
<C
>> vec
;
139 vec
.push_back(std
::move(zc
::owned
<C
>(new C())));
140 vec
.push_back(std
::move(zc
::owned
<C
>(new C())));
141 vec
.push_back(std
::move(zc
::owned
<C
>(new C())));
144 EXPECT_UAF(ref
->DoThing());
147 #define TEST_FUNC(fn) { #fn , Test##fn }
163 for (const auto& test
: kTests
) {
164 std
::cout
<< "=== BEGIN " << test
.name
<< " ===" << std
::endl
;
167 std
::cout
<< "=== PASS " << test
.name
<< " ===" << std
::endl
;
168 } catch (const std
::logic_error
& e
) {
170 std
::cout
<< "=== FAIL " << test
.name
171 << ": Assertion failure: " << e
.what() << " ===" << std
::endl
;
175 return passed ?
0 : 1;