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 "base/bit_utils.h"
21#include "obj_ptr.h"
22#include "thread-current-inl.h"
23
24namespace art {
25
26template<class MirrorType>
27inline bool ObjPtr<MirrorType>::IsValid() const {
28  if (!kObjPtrPoisoning || IsNull()) {
29    return true;
30  }
31  return GetCookie() == TrimCookie(Thread::Current()->GetPoisonObjectCookie());
32}
33
34template<class MirrorType>
35inline void ObjPtr<MirrorType>::AssertValid() const {
36  if (kObjPtrPoisoning) {
37    CHECK(IsValid()) << "Stale object pointer " << PtrUnchecked() << " , expected cookie "
38        << TrimCookie(Thread::Current()->GetPoisonObjectCookie()) << " but got " << GetCookie();
39  }
40}
41
42template<class MirrorType>
43inline uintptr_t ObjPtr<MirrorType>::Encode(MirrorType* ptr) {
44  uintptr_t ref = reinterpret_cast<uintptr_t>(ptr);
45  DCHECK_ALIGNED(ref, kObjectAlignment);
46  if (kObjPtrPoisoning && ref != 0) {
47    DCHECK_LE(ref, 0xFFFFFFFFU);
48    ref >>= kObjectAlignmentShift;
49    // Put cookie in high bits.
50    Thread* self = Thread::Current();
51    DCHECK(self != nullptr);
52    ref |= self->GetPoisonObjectCookie() << kCookieShift;
53  }
54  return ref;
55}
56
57template<class MirrorType>
58inline std::ostream& operator<<(std::ostream& os, ObjPtr<MirrorType> ptr) {
59  // May be used for dumping bad pointers, do not use the checked version.
60  return os << ptr.PtrUnchecked();
61}
62
63}  // namespace art
64
65#endif  // ART_RUNTIME_OBJ_PTR_INL_H_
66