1 /*
2  * Copyright (C) 2011 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 #include "reference_table.h"
18 
19 #include <regex>
20 
21 #include "android-base/stringprintf.h"
22 
23 #include "art_method-inl.h"
24 #include "class_linker.h"
25 #include "class_root-inl.h"
26 #include "common_runtime_test.h"
27 #include "dex/primitive.h"
28 #include "handle_scope-inl.h"
29 #include "mirror/array-inl.h"
30 #include "mirror/array-alloc-inl.h"
31 #include "mirror/class-alloc-inl.h"
32 #include "mirror/class-inl.h"
33 #include "mirror/class_loader.h"
34 #include "mirror/string.h"
35 #include "runtime.h"
36 #include "scoped_thread_state_change-inl.h"
37 #include "thread-current-inl.h"
38 
39 namespace art HIDDEN {
40 
41 using android::base::StringPrintf;
42 
43 class ReferenceTableTest : public CommonRuntimeTest {
44  protected:
ReferenceTableTest()45   ReferenceTableTest() {
46     use_boot_image_ = true;  // Make the Runtime creation cheaper.
47   }
48 };
49 
CreateWeakReference(ObjPtr<mirror::Object> referent)50 static ObjPtr<mirror::Object> CreateWeakReference(ObjPtr<mirror::Object> referent)
51     REQUIRES_SHARED(Locks::mutator_lock_) {
52   Thread* self = Thread::Current();
53   ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
54 
55   StackHandleScope<3> scope(self);
56   Handle<mirror::Object> h_referent(scope.NewHandle<mirror::Object>(referent));
57 
58   Handle<mirror::Class> h_ref_class(scope.NewHandle<mirror::Class>(
59       class_linker->FindClass(self,
60                               "Ljava/lang/ref/WeakReference;",
61                               ScopedNullHandle<mirror::ClassLoader>())));
62   CHECK(h_ref_class != nullptr);
63   CHECK(class_linker->EnsureInitialized(self, h_ref_class, true, true));
64 
65   Handle<mirror::Object> h_ref_instance(scope.NewHandle<mirror::Object>(
66       h_ref_class->AllocObject(self)));
67   CHECK(h_ref_instance != nullptr);
68 
69   ArtMethod* constructor = h_ref_class->FindConstructor(
70       "(Ljava/lang/Object;)V", class_linker->GetImagePointerSize());
71   CHECK(constructor != nullptr);
72 
73   uint32_t args[2];
74   args[0] = PointerToLowMemUInt32(h_ref_instance.Get());
75   args[1] = PointerToLowMemUInt32(h_referent.Get());
76   JValue result;
77   constructor->Invoke(self, args, sizeof(uint32_t), &result, constructor->GetShorty());
78   CHECK(!self->IsExceptionPending());
79 
80   return h_ref_instance.Get();
81 }
82 
TEST_F(ReferenceTableTest,Basics)83 TEST_F(ReferenceTableTest, Basics) {
84   ScopedObjectAccess soa(Thread::Current());
85   StackHandleScope<5u> hs(soa.Self());
86   Handle<mirror::String> o1 =
87       hs.NewHandle(mirror::String::AllocFromModifiedUtf8(soa.Self(), "hello"));
88 
89   ReferenceTable rt("test", 0, 11);
90 
91   // Check dumping the empty table.
92   {
93     std::ostringstream oss;
94     rt.Dump(oss);
95     EXPECT_NE(oss.str().find("(empty)"), std::string::npos) << oss.str();
96     EXPECT_EQ(0U, rt.Size());
97   }
98 
99   // Check removal of all nulls in a empty table is a no-op.
100   rt.Remove(nullptr);
101   EXPECT_EQ(0U, rt.Size());
102 
103   // Check removal of all o1 in a empty table is a no-op.
104   rt.Remove(o1.Get());
105   EXPECT_EQ(0U, rt.Size());
106 
107   // Add o1 and check we have 1 element and can dump.
108   {
109     rt.Add(o1.Get());
110     EXPECT_EQ(1U, rt.Size());
111     std::ostringstream oss;
112     rt.Dump(oss);
113     EXPECT_NE(oss.str().find("1 of java.lang.String"), std::string::npos) << oss.str();
114     EXPECT_EQ(oss.str().find("short[]"), std::string::npos) << oss.str();
115   }
116 
117   // Add a second object 10 times so we can then check dumping works as expected.
118   Handle<mirror::ShortArray> o2 = hs.NewHandle(mirror::ShortArray::Alloc(soa.Self(), 0));
119   for (size_t i = 0; i < 10; ++i) {
120     rt.Add(o2.Get());
121     EXPECT_EQ(i + 2, rt.Size());
122     std::ostringstream oss;
123     rt.Dump(oss);
124     EXPECT_NE(oss.str().find(StringPrintf("Last %zd entries (of %zd):",
125                                           i + 2 > 10 ? 10 : i + 2,
126                                           i + 2)),
127               std::string::npos) << oss.str();
128     EXPECT_NE(oss.str().find("1 of java.lang.String"), std::string::npos) << oss.str();
129     if (i == 0) {
130       EXPECT_NE(oss.str().find("1 of short[]"), std::string::npos) << oss.str();
131     } else {
132       EXPECT_NE(oss.str().find(StringPrintf("%zd of short[] (1 unique instances)", i + 1)),
133                 std::string::npos) << oss.str();
134     }
135   }
136 
137   // Remove o1 (first element).
138   {
139     rt.Remove(o1.Get());
140     EXPECT_EQ(10U, rt.Size());
141     std::ostringstream oss;
142     rt.Dump(oss);
143     EXPECT_EQ(oss.str().find("java.lang.String"), std::string::npos) << oss.str();
144   }
145 
146   // Remove o2 ten times.
147   for (size_t i = 0; i < 10; ++i) {
148     rt.Remove(o2.Get());
149     EXPECT_EQ(9 - i, rt.Size());
150     std::ostringstream oss;
151     rt.Dump(oss);
152     if (i == 9) {
153       EXPECT_EQ(oss.str().find("short[]"), std::string::npos) << oss.str();
154     } else if (i == 8) {
155       EXPECT_NE(oss.str().find("1 of short[]"), std::string::npos) << oss.str();
156     } else {
157       EXPECT_NE(oss.str().find(StringPrintf("%zd of short[] (1 unique instances)", 10 - i - 1)),
158                 std::string::npos) << oss.str();
159     }
160   }
161 
162   // Add a reference and check that the type of the referent is dumped.
163   {
164     ObjPtr<mirror::Object> empty_reference = CreateWeakReference(nullptr);
165     ASSERT_TRUE(empty_reference->IsReferenceInstance());
166     rt.Add(empty_reference);
167     std::ostringstream oss;
168     rt.Dump(oss);
169     EXPECT_NE(oss.str().find("java.lang.ref.WeakReference (referent is null)"), std::string::npos)
170         << oss.str();
171     rt.Remove(empty_reference);
172   }
173 
174   {
175     ObjPtr<mirror::Object> string_referent =
176         mirror::String::AllocFromModifiedUtf8(Thread::Current(), "A");
177     ObjPtr<mirror::Object> non_empty_reference = CreateWeakReference(string_referent);
178     ASSERT_TRUE(non_empty_reference->IsReferenceInstance());
179     rt.Add(non_empty_reference);
180     std::ostringstream oss;
181     rt.Dump(oss);
182     EXPECT_NE(oss.str().find("java.lang.ref.WeakReference (referent is a java.lang.String)"),
183               std::string::npos)
184         << oss.str();
185     rt.Remove(non_empty_reference);
186   }
187 
188   // Add two objects. Enable allocation tracking for the latter.
189   {
190     Handle<mirror::String> h_without_trace(hs.NewHandle(
191         mirror::String::AllocFromModifiedUtf8(soa.Self(), "Without")));
192 
193     {
194       ScopedThreadSuspension sts(soa.Self(), ThreadState::kSuspended);
195       gc::AllocRecordObjectMap::SetAllocTrackingEnabled(true);
196     }
197 
198     // To get a stack, actually make a call. Use substring, that's simple. Calling through JNI
199     // avoids having to create the low-level args array ourselves.
200     Handle<mirror::Object> h_with_trace;
201     {
202       ArtMethod* substr = GetClassRoot<mirror::String>()->FindClassMethod(
203           "substring", "(II)Ljava/lang/String;", kRuntimePointerSize);
204       ASSERT_TRUE(substr != nullptr);
205       h_with_trace = hs.NewHandle(
206           substr->InvokeFinal<'L', 'I', 'I'>(soa.Self(), h_without_trace.Get(), 0, 4));
207       ASSERT_TRUE(h_with_trace != nullptr);
208     }
209 
210     Handle<mirror::Object> h_ref;
211     {
212       jclass weak_ref_class = soa.Env()->FindClass("java/lang/ref/WeakReference");
213       ASSERT_TRUE(weak_ref_class != nullptr);
214       jmethodID init = soa.Env()->GetMethodID(weak_ref_class,
215                                               "<init>",
216                                               "(Ljava/lang/Object;)V");
217       ASSERT_TRUE(init != nullptr);
218       jobject referent = soa.Env()->AddLocalReference<jobject>(h_with_trace.Get());
219       jobject result = soa.Env()->NewObject(weak_ref_class, init, referent);
220       ASSERT_TRUE(result != nullptr);
221       h_ref = hs.NewHandle(soa.Self()->DecodeJObject(result));
222     }
223 
224     rt.Add(h_without_trace.Get());
225     rt.Add(h_with_trace.Get());
226     rt.Add(h_ref.Get());
227 
228     std::ostringstream oss;
229     rt.Dump(oss);
230 
231     constexpr const char* kStackTracePattern =
232         R"(test reference table dump:\n)"
233         R"(  Last 3 entries \(of 3\):\n)"  // NOLINT
234         R"(        2: 0x[0-9a-f]* java.lang.ref.WeakReference \(referent is a java.lang.String\)\n)"  // NOLINT
235         R"(          Allocated at:\n)"
236         R"(            \(No managed frames\)\n)"  // NOLINT
237         R"(          Referent allocated at:\n)"
238         R"(            java.lang.String java.lang.String.fastSubstring\(int, int\):-2\n)"  // NOLINT
239         R"(            java.lang.String java.lang.String.substring\(int, int\):[0-9]*\n)"  // NOLINT
240         R"(        1: 0x[0-9a-f]* java.lang.String "With"\n)"
241         R"(          Allocated at:\n)"
242         R"(            java.lang.String java.lang.String.fastSubstring\(int, int\):-2\n)"  // NOLINT
243         R"(            java.lang.String java.lang.String.substring\(int, int\):[0-9]*\n)"  // NOLINT
244         R"(        0: 0x[0-9a-f]* java.lang.String "Without"\n)"
245         R"(  Summary:\n)"
246         R"(        2 of java.lang.String \(2 unique instances\)\n)"  // NOLINT
247         R"(        1 of java.lang.ref.WeakReference\n)";
248     std::regex stack_trace_regex(kStackTracePattern);
249     std::smatch stack_trace_match;
250     std::string str = oss.str();
251     bool found = std::regex_search(str, stack_trace_match, stack_trace_regex);
252     EXPECT_TRUE(found) << str;
253 
254     {
255       ScopedThreadSuspension sts(soa.Self(), ThreadState::kSuspended);
256       gc::AllocRecordObjectMap::SetAllocTrackingEnabled(false);
257     }
258   }
259 }
260 
FindAll(const std::string & haystack,const char * needle)261 static std::vector<size_t> FindAll(const std::string& haystack, const char* needle) {
262   std::vector<size_t> res;
263   size_t start = 0;
264   do {
265     size_t pos = haystack.find(needle, start);
266     if (pos == std::string::npos) {
267       break;
268     }
269     res.push_back(pos);
270     start = pos + 1;
271   } while (start < haystack.size());
272   return res;
273 }
274 
TEST_F(ReferenceTableTest,SummaryOrder)275 TEST_F(ReferenceTableTest, SummaryOrder) {
276   // Check that the summary statistics are sorted.
277   ScopedObjectAccess soa(Thread::Current());
278 
279   ReferenceTable rt("test", 0, 20);
280 
281   {
282     StackHandleScope<1> hs(soa.Self());
283     Handle<mirror::String> s1 =
284         hs.NewHandle(mirror::String::AllocFromModifiedUtf8(soa.Self(), "hello"));
285     ObjPtr<mirror::String> s2 = mirror::String::AllocFromModifiedUtf8(soa.Self(), "world");
286 
287     // 3 copies of s1, 2 copies of s2, interleaved.
288     for (size_t i = 0; i != 2; ++i) {
289       rt.Add(s1.Get());
290       rt.Add(s2);
291     }
292     rt.Add(s1.Get());
293   }
294 
295   {
296     // Differently sized byte arrays. Should be sorted by identical (non-unique count).
297     StackHandleScope<1> hs(soa.Self());
298     Handle<mirror::ByteArray> b1_1 = hs.NewHandle(mirror::ByteArray::Alloc(soa.Self(), 1));
299     rt.Add(b1_1.Get());
300     rt.Add(mirror::ByteArray::Alloc(soa.Self(), 2));
301     rt.Add(b1_1.Get());
302     rt.Add(mirror::ByteArray::Alloc(soa.Self(), 2));
303     rt.Add(mirror::ByteArray::Alloc(soa.Self(), 1));
304     rt.Add(mirror::ByteArray::Alloc(soa.Self(), 2));
305   }
306 
307   rt.Add(mirror::CharArray::Alloc(soa.Self(), 0));
308 
309   // Now dump, and ensure order.
310   std::ostringstream oss;
311   rt.Dump(oss);
312 
313   // Only do this on the part after Summary.
314   std::string base = oss.str();
315   size_t summary_pos = base.find("Summary:");
316   ASSERT_NE(summary_pos, std::string::npos);
317 
318   std::string haystack = base.substr(summary_pos);
319 
320   std::vector<size_t> strCounts = FindAll(haystack, "java.lang.String");
321   std::vector<size_t> b1Counts = FindAll(haystack, "byte[] (1 elements)");
322   std::vector<size_t> b2Counts = FindAll(haystack, "byte[] (2 elements)");
323   std::vector<size_t> cCounts = FindAll(haystack, "char[]");
324 
325   // Only one each.
326   EXPECT_EQ(1u, strCounts.size());
327   EXPECT_EQ(1u, b1Counts.size());
328   EXPECT_EQ(1u, b2Counts.size());
329   EXPECT_EQ(1u, cCounts.size());
330 
331   // Expect them to be in order.
332   EXPECT_LT(strCounts[0], b1Counts[0]);
333   EXPECT_LT(b1Counts[0], b2Counts[0]);
334   EXPECT_LT(b2Counts[0], cCounts[0]);
335 }
336 
337 }  // namespace art
338