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