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