1 /*
2  * Copyright (C) 2014 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_MIRROR_OBJECT_REFERENCE_H_
18 #define ART_RUNTIME_MIRROR_OBJECT_REFERENCE_H_
19 
20 #include <array>
21 #include <string_view>
22 
23 #include "base/atomic.h"
24 #include "base/casts.h"
25 #include "base/locks.h"  // For Locks::mutator_lock_.
26 #include "base/macros.h"
27 #include "heap_poisoning.h"
28 #include "obj_ptr.h"
29 #include "runtime_globals.h"
30 
31 namespace art HIDDEN {
32 namespace mirror {
33 
34 class Object;
35 
36 // Classes shared with the managed side of the world need to be packed so that they don't have
37 // extra platform specific padding.
38 #define MANAGED PACKED(4)
39 #define MIRROR_CLASS(desc) \
40   static_assert(::art::mirror::IsMirroredDescriptor(desc), \
41                 desc " is not a known mirror class. Please update" \
42                 " IsMirroredDescriptor to include it!")
43 
IsMirroredDescriptor(std::string_view desc)44 constexpr bool IsMirroredDescriptor(std::string_view desc) {
45   if (desc[0] != 'L') {
46     // All primitives and arrays are mirrored
47     return true;
48   }
49 #define MIRROR_DESCRIPTORS(vis)                       \
50     vis("Ljava/lang/Class;")                          \
51     vis("Ljava/lang/ClassLoader;")                    \
52     vis("Ljava/lang/ClassNotFoundException;")         \
53     vis("Ljava/lang/DexCache;")                       \
54     vis("Ljava/lang/Object;")                         \
55     vis("Ljava/lang/StackFrameInfo;")                 \
56     vis("Ljava/lang/StackTraceElement;")              \
57     vis("Ljava/lang/String;")                         \
58     vis("Ljava/lang/Throwable;")                      \
59     vis("Ljava/lang/invoke/ArrayElementVarHandle;")   \
60     vis("Ljava/lang/invoke/ByteArrayViewVarHandle;")  \
61     vis("Ljava/lang/invoke/ByteBufferViewVarHandle;") \
62     vis("Ljava/lang/invoke/CallSite;")                \
63     vis("Ljava/lang/invoke/FieldVarHandle;")          \
64     vis("Ljava/lang/invoke/StaticFieldVarHandle;")    \
65     vis("Ljava/lang/invoke/MethodHandle;")            \
66     vis("Ljava/lang/invoke/MethodHandleImpl;")        \
67     vis("Ljava/lang/invoke/MethodHandles$Lookup;")    \
68     vis("Ljava/lang/invoke/MethodType;")              \
69     vis("Ljava/lang/invoke/VarHandle;")               \
70     vis("Ljava/lang/ref/FinalizerReference;")         \
71     vis("Ljava/lang/ref/Reference;")                  \
72     vis("Ljava/lang/reflect/AccessibleObject;")       \
73     vis("Ljava/lang/reflect/Constructor;")            \
74     vis("Ljava/lang/reflect/Executable;")             \
75     vis("Ljava/lang/reflect/Field;")                  \
76     vis("Ljava/lang/reflect/Method;")                 \
77     vis("Ljava/lang/reflect/Proxy;")                  \
78     vis("Ldalvik/system/ClassExt;")                   \
79     vis("Ldalvik/system/EmulatedStackFrame;")
80   // TODO: Once we are C++ 20 we can just have a constexpr array and std::find.
81   // constexpr std::array<std::string_view, 28> kMirrorTypes{
82   //    // Fill in
83   // };
84   // return std::find(kMirrorTypes.begin(), kMirrorTypes.end(), desc) != kMirrorTypes.end();
85 #define CHECK_DESCRIPTOR(descriptor)          \
86   if (std::string_view(descriptor) == desc) { \
87     return true;                              \
88   }
89   MIRROR_DESCRIPTORS(CHECK_DESCRIPTOR)
90 #undef CHECK_DESCRIPTOR
91   return false;
92 #undef MIRROR_DESCRIPTORS
93 }
94 
95 template<bool kPoisonReferences, class MirrorType>
96 class PtrCompression {
97  public:
98   // Compress reference to its bit representation.
Compress(MirrorType * mirror_ptr)99   static uint32_t Compress(MirrorType* mirror_ptr) {
100     uint32_t as_bits = reinterpret_cast32<uint32_t>(mirror_ptr);
101     return kPoisonReferences ? -as_bits : as_bits;
102   }
103 
104   // Uncompress an encoded reference from its bit representation.
Decompress(uint32_t ref)105   static MirrorType* Decompress(uint32_t ref) {
106     uint32_t as_bits = kPoisonReferences ? -ref : ref;
107     return reinterpret_cast32<MirrorType*>(as_bits);
108   }
109 
110   // Convert an ObjPtr to a compressed reference.
111   static uint32_t Compress(ObjPtr<MirrorType> ptr) REQUIRES_SHARED(Locks::mutator_lock_);
112 };
113 
114 // Value type representing a reference to a mirror::Object of type MirrorType.
115 template<bool kPoisonReferences, class MirrorType>
116 class MANAGED ObjectReference {
117  private:
118   using Compression = PtrCompression<kPoisonReferences, MirrorType>;
119 
120  public:
121   /*
122    * Returns a pointer to the mirror of the managed object this reference is for.
123    *
124    * This does NOT return the current object (which isn't derived from, and
125    * therefor cannot be a mirror::Object) as a mirror pointer.  Instead, this
126    * returns a pointer to the mirror of the managed object this refers to.
127    *
128    * TODO (chriswailes): Rename to GetPtr().
129    */
AsMirrorPtr()130   MirrorType* AsMirrorPtr() const {
131     return Compression::Decompress(reference_);
132   }
133 
Assign(MirrorType * other)134   void Assign(MirrorType* other) {
135     reference_ = Compression::Compress(other);
136   }
137 
138   void Assign(ObjPtr<MirrorType> ptr) REQUIRES_SHARED(Locks::mutator_lock_);
139 
Clear()140   void Clear() {
141     reference_ = 0;
142     DCHECK(IsNull());
143   }
144 
IsNull()145   bool IsNull() const {
146     return reference_ == 0;
147   }
148 
FromMirrorPtr(MirrorType * mirror_ptr)149   static ObjectReference<kPoisonReferences, MirrorType> FromMirrorPtr(MirrorType* mirror_ptr)
150       REQUIRES_SHARED(Locks::mutator_lock_) {
151     return ObjectReference<kPoisonReferences, MirrorType>(mirror_ptr);
152   }
153 
154  protected:
ObjectReference(MirrorType * mirror_ptr)155   explicit ObjectReference(MirrorType* mirror_ptr) REQUIRES_SHARED(Locks::mutator_lock_)
156       : reference_(Compression::Compress(mirror_ptr)) {
157   }
ObjectReference()158   ObjectReference() : reference_(0u) {
159     DCHECK(IsNull());
160   }
161 
162   // The encoded reference to a mirror::Object.
163   uint32_t reference_;
164 };
165 
166 // References between objects within the managed heap.
167 // Similar API to ObjectReference, but not a value type. Supports atomic access.
168 template<class MirrorType>
169 class MANAGED HeapReference {
170  private:
171   using Compression = PtrCompression<kPoisonHeapReferences, MirrorType>;
172 
173  public:
HeapReference()174   HeapReference() REQUIRES_SHARED(Locks::mutator_lock_) : HeapReference(nullptr) {}
175 
176   template <bool kIsVolatile = false>
AsMirrorPtr()177   MirrorType* AsMirrorPtr() const REQUIRES_SHARED(Locks::mutator_lock_) {
178     return Compression::Decompress(
179         kIsVolatile ? reference_.load(std::memory_order_seq_cst) : reference_.LoadJavaData());
180   }
181 
182   template <bool kIsVolatile = false>
Assign(MirrorType * other)183   void Assign(MirrorType* other) REQUIRES_SHARED(Locks::mutator_lock_) {
184     if (kIsVolatile) {
185       reference_.store(Compression::Compress(other), std::memory_order_seq_cst);
186     } else {
187       reference_.StoreJavaData(Compression::Compress(other));
188     }
189   }
190 
191   template <bool kIsVolatile = false>
192   void Assign(ObjPtr<MirrorType> ptr) REQUIRES_SHARED(Locks::mutator_lock_);
193 
Clear()194   void Clear() {
195     reference_.StoreJavaData(0);
196     DCHECK(IsNull());
197   }
198 
IsNull()199   bool IsNull() const {
200     return reference_.LoadJavaData() == 0;
201   }
202 
FromMirrorPtr(MirrorType * mirror_ptr)203   static HeapReference<MirrorType> FromMirrorPtr(MirrorType* mirror_ptr)
204       REQUIRES_SHARED(Locks::mutator_lock_) {
205     return HeapReference<MirrorType>(mirror_ptr);
206   }
207 
208   bool CasWeakRelaxed(MirrorType* old_ptr, MirrorType* new_ptr)
209       REQUIRES_SHARED(Locks::mutator_lock_);
210 
211  private:
HeapReference(MirrorType * mirror_ptr)212   explicit HeapReference(MirrorType* mirror_ptr) REQUIRES_SHARED(Locks::mutator_lock_)
213       : reference_(Compression::Compress(mirror_ptr)) {}
214 
215   // The encoded reference to a mirror::Object. Atomically updateable.
216   Atomic<uint32_t> reference_;
217 };
218 
219 static_assert(sizeof(mirror::HeapReference<mirror::Object>) == kHeapReferenceSize,
220               "heap reference size does not match");
221 
222 // Standard compressed reference used in the runtime. Used for StackReference and GC roots.
223 template<class MirrorType>
224 class MANAGED CompressedReference : public mirror::ObjectReference<false, MirrorType> {
225  public:
226   CompressedReference<MirrorType>()
227       : mirror::ObjectReference<false, MirrorType>() {}
228 
FromMirrorPtr(MirrorType * p)229   static CompressedReference<MirrorType> FromMirrorPtr(MirrorType* p)
230       REQUIRES_SHARED(Locks::mutator_lock_) {
231     return CompressedReference<MirrorType>(p);
232   }
233 
FromVRegValue(uint32_t vreg_value)234   static CompressedReference<MirrorType> FromVRegValue(uint32_t vreg_value) {
235     CompressedReference<MirrorType> result;
236     result.reference_ = vreg_value;
237     return result;
238   }
239 
AsVRegValue()240   uint32_t AsVRegValue() const {
241     return this->reference_;
242   }
243 
244  private:
CompressedReference(MirrorType * p)245   explicit CompressedReference(MirrorType* p) REQUIRES_SHARED(Locks::mutator_lock_)
246       : ObjectReference<false, MirrorType>(p) {}
247 };
248 
249 }  // namespace mirror
250 }  // namespace art
251 
252 #endif  // ART_RUNTIME_MIRROR_OBJECT_REFERENCE_H_
253