1 /*
2  * Copyright (C) 2016 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef ART_RUNTIME_OBJ_PTR_INL_H_
18 #define ART_RUNTIME_OBJ_PTR_INL_H_
19 
20 #include "obj_ptr.h"
21 #include "thread-inl.h"
22 
23 namespace art {
24 
25 template<class MirrorType>
IsValid()26 inline bool ObjPtr<MirrorType>::IsValid() const {
27   if (!kObjPtrPoisoning || IsNull()) {
28     return true;
29   }
30   return GetCookie() == TrimCookie(Thread::Current()->GetPoisonObjectCookie());
31 }
32 
33 template<class MirrorType>
AssertValid()34 inline void ObjPtr<MirrorType>::AssertValid() const {
35   if (kObjPtrPoisoning) {
36     CHECK(IsValid()) << "Stale object pointer " << PtrUnchecked() << " , expected cookie "
37         << TrimCookie(Thread::Current()->GetPoisonObjectCookie()) << " but got " << GetCookie();
38   }
39 }
40 
41 template<class MirrorType>
Encode(MirrorType * ptr)42 inline uintptr_t ObjPtr<MirrorType>::Encode(MirrorType* ptr) {
43   uintptr_t ref = reinterpret_cast<uintptr_t>(ptr);
44   DCHECK_ALIGNED(ref, kObjectAlignment);
45   if (kObjPtrPoisoning && ref != 0) {
46     DCHECK_LE(ref, 0xFFFFFFFFU);
47     ref >>= kObjectAlignmentShift;
48     // Put cookie in high bits.
49     Thread* self = Thread::Current();
50     DCHECK(self != nullptr);
51     ref |= self->GetPoisonObjectCookie() << kCookieShift;
52   }
53   return ref;
54 }
55 
56 template<class MirrorType>
57 inline std::ostream& operator<<(std::ostream& os, ObjPtr<MirrorType> ptr) {
58   // May be used for dumping bad pointers, do not use the checked version.
59   return os << ptr.PtrUnchecked();
60 }
61 
62 }  // namespace art
63 
64 #endif  // ART_RUNTIME_OBJ_PTR_INL_H_
65