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