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 <android-base/test_utils.h>
18
19 #include <memory>
20 #include <type_traits>
21
22 #include "art_method-inl.h"
23 #include "base/arena_allocator.h"
24 #include "base/callee_save_type.h"
25 #include "base/leb128.h"
26 #include "base/macros.h"
27 #include "base/malloc_arena_pool.h"
28 #include "base/pointer_size.h"
29 #include "class_linker.h"
30 #include "common_runtime_test.h"
31 #include "dex/code_item_accessors-inl.h"
32 #include "dex/dex_file-inl.h"
33 #include "dex/dex_file.h"
34 #include "dex/dex_file_exception_helpers.h"
35 #include "gtest/gtest.h"
36 #include "handle_scope-inl.h"
37 #include "mirror/class-inl.h"
38 #include "mirror/object-inl.h"
39 #include "mirror/object_array-inl.h"
40 #include "mirror/stack_trace_element-inl.h"
41 #include "oat/oat_quick_method_header.h"
42 #include "obj_ptr-inl.h"
43 #include "optimizing/stack_map_stream.h"
44 #include "runtime-inl.h"
45 #include "scoped_thread_state_change-inl.h"
46 #include "thread.h"
47
48 namespace art HIDDEN {
49
50 class ExceptionTest : public CommonRuntimeTest {
51 protected:
52 // Since various dexers may differ in bytecode layout, we play
53 // it safe and simply set the dex pc to the start of the method,
54 // which always points to the first source statement.
55 static constexpr const uint32_t kDexPc = 0;
56
SetUp()57 void SetUp() override {
58 CommonRuntimeTest::SetUp();
59
60 ScopedObjectAccess soa(Thread::Current());
61 StackHandleScope<2> hs(soa.Self());
62 Handle<mirror::ClassLoader> class_loader(
63 hs.NewHandle(soa.Decode<mirror::ClassLoader>(LoadDex("ExceptionHandle"))));
64 my_klass_ = class_linker_->FindClass(soa.Self(), "LExceptionHandle;", class_loader);
65 ASSERT_TRUE(my_klass_ != nullptr);
66 Handle<mirror::Class> klass(hs.NewHandle(my_klass_));
67 class_linker_->EnsureInitialized(soa.Self(), klass, true, true);
68 my_klass_ = klass.Get();
69
70 dex_ = my_klass_->GetDexCache()->GetDexFile();
71
72 std::vector<uint8_t> fake_code;
73 uint32_t code_size = 12;
74 for (size_t i = 0 ; i < code_size; i++) {
75 fake_code.push_back(0x70 | i);
76 }
77
78 const uint32_t native_pc_offset = 4u;
79 CHECK_ALIGNED_PARAM(native_pc_offset, GetInstructionSetInstructionAlignment(kRuntimeISA));
80
81 MallocArenaPool pool;
82 ArenaStack arena_stack(&pool);
83 ScopedArenaAllocator allocator(&arena_stack);
84 StackMapStream stack_maps(&allocator, kRuntimeISA);
85 stack_maps.BeginMethod(/* frame_size_in_bytes= */ 4 * sizeof(void*),
86 /* core_spill_mask= */ 0u,
87 /* fp_spill_mask= */ 0u,
88 /* num_dex_registers= */ 0u,
89 /* baseline= */ false,
90 /* debuggable= */ false);
91 stack_maps.BeginStackMapEntry(kDexPc, native_pc_offset);
92 stack_maps.EndStackMapEntry();
93 stack_maps.EndMethod(code_size);
94 ScopedArenaVector<uint8_t> stack_map = stack_maps.Encode();
95
96 const size_t stack_maps_size = stack_map.size();
97 const size_t header_size = sizeof(OatQuickMethodHeader);
98 const size_t code_alignment = GetInstructionSetCodeAlignment(kRuntimeISA);
99
100 fake_header_code_and_maps_size_ = stack_maps_size + header_size + code_size + code_alignment;
101 // Use mmap to make sure we get untagged memory here. Real code gets allocated using
102 // mspace_memalign which is never tagged.
103 fake_header_code_and_maps_ = static_cast<uint8_t*>(mmap(nullptr,
104 fake_header_code_and_maps_size_,
105 PROT_READ | PROT_WRITE,
106 MAP_PRIVATE | MAP_ANONYMOUS,
107 -1,
108 0));
109 uint8_t* code_ptr =
110 AlignUp(&fake_header_code_and_maps_[stack_maps_size + header_size], code_alignment);
111
112 memcpy(&fake_header_code_and_maps_[0], stack_map.data(), stack_maps_size);
113 OatQuickMethodHeader method_header(code_ptr - fake_header_code_and_maps_);
114 static_assert(std::is_trivially_copyable<OatQuickMethodHeader>::value, "Cannot use memcpy");
115 memcpy(code_ptr - header_size, &method_header, header_size);
116 memcpy(code_ptr, fake_code.data(), fake_code.size());
117
118 if (kRuntimeISA == InstructionSet::kArm) {
119 // Check that the Thumb2 adjustment will be a NOP, see EntryPointToCodePointer().
120 CHECK_ALIGNED(code_ptr, 2);
121 }
122
123 method_f_ = my_klass_->FindClassMethod("f", "()I", kRuntimePointerSize);
124 ASSERT_TRUE(method_f_ != nullptr);
125 ASSERT_FALSE(method_f_->IsDirect());
126 method_f_->SetEntryPointFromQuickCompiledCode(code_ptr);
127
128 method_g_ = my_klass_->FindClassMethod("g", "(I)V", kRuntimePointerSize);
129 ASSERT_TRUE(method_g_ != nullptr);
130 ASSERT_FALSE(method_g_->IsDirect());
131 method_g_->SetEntryPointFromQuickCompiledCode(code_ptr);
132 }
133
TearDown()134 void TearDown() override { munmap(fake_header_code_and_maps_, fake_header_code_and_maps_size_); }
135
136 const DexFile* dex_;
137
138 size_t fake_header_code_and_maps_size_;
139 uint8_t* fake_header_code_and_maps_;
140
141 ArtMethod* method_f_;
142 ArtMethod* method_g_;
143
144 private:
145 ObjPtr<mirror::Class> my_klass_;
146 };
147
TEST_F(ExceptionTest,FindCatchHandler)148 TEST_F(ExceptionTest, FindCatchHandler) {
149 ScopedObjectAccess soa(Thread::Current());
150 CodeItemDataAccessor accessor(*dex_, method_f_->GetCodeItem());
151
152 ASSERT_TRUE(accessor.HasCodeItem());
153
154 ASSERT_EQ(2u, accessor.TriesSize());
155 ASSERT_NE(0u, accessor.InsnsSizeInCodeUnits());
156
157 const dex::TryItem& t0 = accessor.TryItems().begin()[0];
158 const dex::TryItem& t1 = accessor.TryItems().begin()[1];
159 EXPECT_LE(t0.start_addr_, t1.start_addr_);
160 {
161 CatchHandlerIterator iter(accessor, 4 /* Dex PC in the first try block */);
162 EXPECT_STREQ("Ljava/io/IOException;", dex_->GetTypeDescriptor(iter.GetHandlerTypeIndex()));
163 ASSERT_TRUE(iter.HasNext());
164 iter.Next();
165 EXPECT_STREQ("Ljava/lang/Exception;", dex_->GetTypeDescriptor(iter.GetHandlerTypeIndex()));
166 ASSERT_TRUE(iter.HasNext());
167 iter.Next();
168 EXPECT_FALSE(iter.HasNext());
169 }
170 {
171 CatchHandlerIterator iter(accessor, 8 /* Dex PC in the second try block */);
172 EXPECT_STREQ("Ljava/io/IOException;", dex_->GetTypeDescriptor(iter.GetHandlerTypeIndex()));
173 ASSERT_TRUE(iter.HasNext());
174 iter.Next();
175 EXPECT_FALSE(iter.HasNext());
176 }
177 {
178 CatchHandlerIterator iter(accessor, 11 /* Dex PC not in any try block */);
179 EXPECT_FALSE(iter.HasNext());
180 }
181 }
182
TEST_F(ExceptionTest,StackTraceElement)183 TEST_F(ExceptionTest, StackTraceElement) {
184 Thread* thread = Thread::Current();
185 thread->TransitionFromSuspendedToRunnable();
186 bool started = runtime_->Start();
187 CHECK(started);
188 JNIEnv* env = thread->GetJniEnv();
189 ScopedObjectAccess soa(env);
190
191 std::vector<uintptr_t> fake_stack;
192 Runtime* r = Runtime::Current();
193 r->SetInstructionSet(kRuntimeISA);
194 ArtMethod* save_method = r->CreateCalleeSaveMethod();
195 r->SetCalleeSaveMethod(save_method, CalleeSaveType::kSaveAllCalleeSaves);
196 QuickMethodFrameInfo frame_info = r->GetRuntimeMethodFrameInfo(save_method);
197
198 ASSERT_EQ(kStackAlignment, 16U);
199 // ASSERT_EQ(sizeof(uintptr_t), sizeof(uint32_t));
200
201 // Create the stack frame for the callee save method, expected by the runtime.
202 fake_stack.push_back(reinterpret_cast<uintptr_t>(save_method));
203 for (size_t i = 0; i < frame_info.FrameSizeInBytes() - 2 * sizeof(uintptr_t);
204 i += sizeof(uintptr_t)) {
205 fake_stack.push_back(0);
206 }
207
208 OatQuickMethodHeader* header = OatQuickMethodHeader::FromEntryPoint(
209 method_g_->GetEntryPointFromQuickCompiledCode());
210 // Untag native pc when running with hwasan since the pcs on the stack aren't tagged and we use
211 // this to create a fake stack. See OatQuickMethodHeader::Contains where we untag code pointers
212 // before comparing it with the PC from the stack.
213 uintptr_t native_pc = header->ToNativeQuickPc(method_g_, kDexPc);
214 if (running_with_hwasan()) {
215 // TODO(228989263): Use HWASanUntag once we have a hwasan target for tests too. HWASanUntag
216 // uses static checks which won't work if we don't have a dedicated target.
217 native_pc = (native_pc & ((1ULL << 56) - 1));
218 }
219 fake_stack.push_back(native_pc); // return pc
220
221 // Create/push fake 16byte stack frame for method g
222 fake_stack.push_back(reinterpret_cast<uintptr_t>(method_g_));
223 fake_stack.push_back(0);
224 fake_stack.push_back(0);
225 fake_stack.push_back(native_pc); // return pc.
226
227 // Create/push fake 16byte stack frame for method f
228 fake_stack.push_back(reinterpret_cast<uintptr_t>(method_f_));
229 fake_stack.push_back(0);
230 fake_stack.push_back(0);
231 fake_stack.push_back(0xEBAD6070); // return pc
232
233 // Push Method* of null to terminate the trace
234 fake_stack.push_back(0);
235
236 // Push null values which will become null incoming arguments.
237 fake_stack.push_back(0);
238 fake_stack.push_back(0);
239 fake_stack.push_back(0);
240
241 // Set up thread to appear as if we called out of method_g_ at given pc dex.
242 thread->SetTopOfStack(reinterpret_cast<ArtMethod**>(&fake_stack[0]));
243
244 jobject internal = thread->CreateInternalStackTrace(soa);
245 ASSERT_TRUE(internal != nullptr);
246 jobjectArray ste_array = Thread::InternalStackTraceToStackTraceElementArray(soa, internal);
247 ASSERT_TRUE(ste_array != nullptr);
248 auto trace_array = soa.Decode<mirror::ObjectArray<mirror::StackTraceElement>>(ste_array);
249
250 ASSERT_TRUE(trace_array != nullptr);
251 ASSERT_TRUE(trace_array->Get(0) != nullptr);
252 EXPECT_STREQ("ExceptionHandle",
253 trace_array->Get(0)->GetDeclaringClass()->ToModifiedUtf8().c_str());
254 EXPECT_STREQ("ExceptionHandle.java",
255 trace_array->Get(0)->GetFileName()->ToModifiedUtf8().c_str());
256 EXPECT_STREQ("g", trace_array->Get(0)->GetMethodName()->ToModifiedUtf8().c_str());
257 EXPECT_EQ(36, trace_array->Get(0)->GetLineNumber());
258
259 ASSERT_TRUE(trace_array->Get(1) != nullptr);
260 EXPECT_STREQ("ExceptionHandle",
261 trace_array->Get(1)->GetDeclaringClass()->ToModifiedUtf8().c_str());
262 EXPECT_STREQ("ExceptionHandle.java",
263 trace_array->Get(1)->GetFileName()->ToModifiedUtf8().c_str());
264 EXPECT_STREQ("f", trace_array->Get(1)->GetMethodName()->ToModifiedUtf8().c_str());
265 EXPECT_EQ(22, trace_array->Get(1)->GetLineNumber());
266
267 thread->SetTopOfStack(nullptr); // Disarm the assertion that no code is running when we detach.
268 }
269
270 } // namespace art
271