• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/enums.h"
26 #include "base/leb128.h"
27 #include "base/macros.h"
28 #include "base/malloc_arena_pool.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_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     uint32_t code_size = 12;
73     for (size_t i = 0 ; i < code_size; i++) {
74       fake_code_.push_back(0x70 | i);
75     }
76 
77     const uint32_t native_pc_offset = 4u;
78     CHECK_ALIGNED_PARAM(native_pc_offset, GetInstructionSetInstructionAlignment(kRuntimeISA));
79 
80     MallocArenaPool pool;
81     ArenaStack arena_stack(&pool);
82     ScopedArenaAllocator allocator(&arena_stack);
83     StackMapStream stack_maps(&allocator, kRuntimeISA);
84     stack_maps.BeginMethod(/* frame_size_in_bytes= */ 4 * sizeof(void*),
85                            /* core_spill_mask= */ 0u,
86                            /* fp_spill_mask= */ 0u,
87                            /* num_dex_registers= */ 0u,
88                            /* baseline= */ false,
89                            /* debuggable= */ false);
90     stack_maps.BeginStackMapEntry(kDexPc, native_pc_offset);
91     stack_maps.EndStackMapEntry();
92     stack_maps.EndMethod(code_size);
93     ScopedArenaVector<uint8_t> stack_map = stack_maps.Encode();
94 
95     const size_t stack_maps_size = stack_map.size();
96     const size_t header_size = sizeof(OatQuickMethodHeader);
97     const size_t code_alignment = GetInstructionSetCodeAlignment(kRuntimeISA);
98 
99     fake_header_code_and_maps_.resize(stack_maps_size + header_size + code_size + code_alignment);
100     // NB: The start of the vector might not have been allocated the desired alignment.
101     uint8_t* code_ptr =
102       AlignUp(&fake_header_code_and_maps_[stack_maps_size + header_size], code_alignment);
103 
104     memcpy(&fake_header_code_and_maps_[0], stack_map.data(), stack_maps_size);
105     OatQuickMethodHeader method_header(code_ptr - fake_header_code_and_maps_.data());
106     static_assert(std::is_trivially_copyable<OatQuickMethodHeader>::value, "Cannot use memcpy");
107     memcpy(code_ptr - header_size, &method_header, header_size);
108     memcpy(code_ptr, fake_code_.data(), fake_code_.size());
109 
110     if (kRuntimeISA == InstructionSet::kArm) {
111       // Check that the Thumb2 adjustment will be a NOP, see EntryPointToCodePointer().
112       CHECK_ALIGNED(code_ptr, 2);
113     }
114 
115     method_f_ = my_klass_->FindClassMethod("f", "()I", kRuntimePointerSize);
116     ASSERT_TRUE(method_f_ != nullptr);
117     ASSERT_FALSE(method_f_->IsDirect());
118     method_f_->SetEntryPointFromQuickCompiledCode(code_ptr);
119 
120     method_g_ = my_klass_->FindClassMethod("g", "(I)V", kRuntimePointerSize);
121     ASSERT_TRUE(method_g_ != nullptr);
122     ASSERT_FALSE(method_g_->IsDirect());
123     method_g_->SetEntryPointFromQuickCompiledCode(code_ptr);
124   }
125 
126   const DexFile* dex_;
127 
128   std::vector<uint8_t> fake_code_;
129   std::vector<uint8_t> fake_header_code_and_maps_;
130 
131   ArtMethod* method_f_;
132   ArtMethod* method_g_;
133 
134  private:
135   ObjPtr<mirror::Class> my_klass_;
136 };
137 
TEST_F(ExceptionTest,FindCatchHandler)138 TEST_F(ExceptionTest, FindCatchHandler) {
139   ScopedObjectAccess soa(Thread::Current());
140   CodeItemDataAccessor accessor(*dex_, method_f_->GetCodeItem());
141 
142   ASSERT_TRUE(accessor.HasCodeItem());
143 
144   ASSERT_EQ(2u, accessor.TriesSize());
145   ASSERT_NE(0u, accessor.InsnsSizeInCodeUnits());
146 
147   const dex::TryItem& t0 = accessor.TryItems().begin()[0];
148   const dex::TryItem& t1 = accessor.TryItems().begin()[1];
149   EXPECT_LE(t0.start_addr_, t1.start_addr_);
150   {
151     CatchHandlerIterator iter(accessor, 4 /* Dex PC in the first try block */);
152     EXPECT_STREQ("Ljava/io/IOException;", dex_->StringByTypeIdx(iter.GetHandlerTypeIndex()));
153     ASSERT_TRUE(iter.HasNext());
154     iter.Next();
155     EXPECT_STREQ("Ljava/lang/Exception;", dex_->StringByTypeIdx(iter.GetHandlerTypeIndex()));
156     ASSERT_TRUE(iter.HasNext());
157     iter.Next();
158     EXPECT_FALSE(iter.HasNext());
159   }
160   {
161     CatchHandlerIterator iter(accessor, 8 /* Dex PC in the second try block */);
162     EXPECT_STREQ("Ljava/io/IOException;", dex_->StringByTypeIdx(iter.GetHandlerTypeIndex()));
163     ASSERT_TRUE(iter.HasNext());
164     iter.Next();
165     EXPECT_FALSE(iter.HasNext());
166   }
167   {
168     CatchHandlerIterator iter(accessor, 11 /* Dex PC not in any try block */);
169     EXPECT_FALSE(iter.HasNext());
170   }
171 }
172 
TEST_F(ExceptionTest,StackTraceElement)173 TEST_F(ExceptionTest, StackTraceElement) {
174   Thread* thread = Thread::Current();
175   thread->TransitionFromSuspendedToRunnable();
176   bool started = runtime_->Start();
177   CHECK(started);
178   JNIEnv* env = thread->GetJniEnv();
179   ScopedObjectAccess soa(env);
180 
181   std::vector<uintptr_t> fake_stack;
182   Runtime* r = Runtime::Current();
183   r->SetInstructionSet(kRuntimeISA);
184   ArtMethod* save_method = r->CreateCalleeSaveMethod();
185   r->SetCalleeSaveMethod(save_method, CalleeSaveType::kSaveAllCalleeSaves);
186   QuickMethodFrameInfo frame_info = r->GetRuntimeMethodFrameInfo(save_method);
187 
188   ASSERT_EQ(kStackAlignment, 16U);
189   // ASSERT_EQ(sizeof(uintptr_t), sizeof(uint32_t));
190 
191   // Create the stack frame for the callee save method, expected by the runtime.
192   fake_stack.push_back(reinterpret_cast<uintptr_t>(save_method));
193   for (size_t i = 0; i < frame_info.FrameSizeInBytes() - 2 * sizeof(uintptr_t);
194        i += sizeof(uintptr_t)) {
195     fake_stack.push_back(0);
196   }
197 
198   OatQuickMethodHeader* header = OatQuickMethodHeader::FromEntryPoint(
199       method_g_->GetEntryPointFromQuickCompiledCode());
200   // Untag native pc when running with hwasan since the pcs on the stack aren't tagged and we use
201   // this to create a fake stack. See OatQuickMethodHeader::Contains where we untag code pointers
202   // before comparing it with the PC from the stack.
203   uintptr_t native_pc = header->ToNativeQuickPc(method_g_, kDexPc);
204   if (running_with_hwasan()) {
205     // TODO(228989263): Use HWASanUntag once we have a hwasan target for tests too. HWASanUntag
206     // uses static checks which won't work if we don't have a dedicated target.
207     native_pc = (native_pc & ((1ULL << 56) - 1));
208   }
209   fake_stack.push_back(native_pc);  // return pc
210 
211   // Create/push fake 16byte stack frame for method g
212   fake_stack.push_back(reinterpret_cast<uintptr_t>(method_g_));
213   fake_stack.push_back(0);
214   fake_stack.push_back(0);
215   fake_stack.push_back(native_pc);  // return pc.
216 
217   // Create/push fake 16byte stack frame for method f
218   fake_stack.push_back(reinterpret_cast<uintptr_t>(method_f_));
219   fake_stack.push_back(0);
220   fake_stack.push_back(0);
221   fake_stack.push_back(0xEBAD6070);  // return pc
222 
223   // Push Method* of null to terminate the trace
224   fake_stack.push_back(0);
225 
226   // Push null values which will become null incoming arguments.
227   fake_stack.push_back(0);
228   fake_stack.push_back(0);
229   fake_stack.push_back(0);
230 
231   // Set up thread to appear as if we called out of method_g_ at given pc dex.
232   thread->SetTopOfStack(reinterpret_cast<ArtMethod**>(&fake_stack[0]));
233 
234   jobject internal = thread->CreateInternalStackTrace(soa);
235   ASSERT_TRUE(internal != nullptr);
236   jobjectArray ste_array = Thread::InternalStackTraceToStackTraceElementArray(soa, internal);
237   ASSERT_TRUE(ste_array != nullptr);
238   auto trace_array = soa.Decode<mirror::ObjectArray<mirror::StackTraceElement>>(ste_array);
239 
240   ASSERT_TRUE(trace_array != nullptr);
241   ASSERT_TRUE(trace_array->Get(0) != nullptr);
242   EXPECT_STREQ("ExceptionHandle",
243                trace_array->Get(0)->GetDeclaringClass()->ToModifiedUtf8().c_str());
244   EXPECT_STREQ("ExceptionHandle.java",
245                trace_array->Get(0)->GetFileName()->ToModifiedUtf8().c_str());
246   EXPECT_STREQ("g", trace_array->Get(0)->GetMethodName()->ToModifiedUtf8().c_str());
247   EXPECT_EQ(36, trace_array->Get(0)->GetLineNumber());
248 
249   ASSERT_TRUE(trace_array->Get(1) != nullptr);
250   EXPECT_STREQ("ExceptionHandle",
251                trace_array->Get(1)->GetDeclaringClass()->ToModifiedUtf8().c_str());
252   EXPECT_STREQ("ExceptionHandle.java",
253                trace_array->Get(1)->GetFileName()->ToModifiedUtf8().c_str());
254   EXPECT_STREQ("f", trace_array->Get(1)->GetMethodName()->ToModifiedUtf8().c_str());
255   EXPECT_EQ(22, trace_array->Get(1)->GetLineNumber());
256 
257   thread->SetTopOfStack(nullptr);  // Disarm the assertion that no code is running when we detach.
258 }
259 
260 }  // namespace art
261