1 /*
2 * Copyright (C) 2012 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 "common_throws.h"
18
19 #include <sstream>
20
21 #include <android-base/logging.h>
22 #include <android-base/stringprintf.h>
23
24 #include "art_field-inl.h"
25 #include "art_method-inl.h"
26 #include "class_linker-inl.h"
27 #include "debug_print.h"
28 #include "dex/dex_file-inl.h"
29 #include "dex/dex_instruction-inl.h"
30 #include "dex/invoke_type.h"
31 #include "mirror/class-inl.h"
32 #include "mirror/method_type.h"
33 #include "mirror/object-inl.h"
34 #include "mirror/object_array-inl.h"
35 #include "nativehelper/scoped_local_ref.h"
36 #include "obj_ptr-inl.h"
37 #include "thread.h"
38 #include "well_known_classes.h"
39
40 namespace art {
41
42 using android::base::StringAppendV;
43 using android::base::StringPrintf;
44
AddReferrerLocation(std::ostream & os,ObjPtr<mirror::Class> referrer)45 static void AddReferrerLocation(std::ostream& os, ObjPtr<mirror::Class> referrer)
46 REQUIRES_SHARED(Locks::mutator_lock_) {
47 if (referrer != nullptr) {
48 std::string location(referrer->GetLocation());
49 if (!location.empty()) {
50 os << " (declaration of '" << referrer->PrettyDescriptor()
51 << "' appears in " << location << ")";
52 }
53 }
54 }
55
ThrowException(const char * exception_descriptor)56 static void ThrowException(const char* exception_descriptor) REQUIRES_SHARED(Locks::mutator_lock_) {
57 Thread* self = Thread::Current();
58 self->ThrowNewException(exception_descriptor, nullptr);
59 }
60
ThrowException(const char * exception_descriptor,ObjPtr<mirror::Class> referrer,const char * fmt,va_list * args=nullptr)61 static void ThrowException(const char* exception_descriptor,
62 ObjPtr<mirror::Class> referrer,
63 const char* fmt,
64 va_list* args = nullptr)
65 REQUIRES_SHARED(Locks::mutator_lock_) {
66 std::ostringstream msg;
67 if (args != nullptr) {
68 std::string vmsg;
69 StringAppendV(&vmsg, fmt, *args);
70 msg << vmsg;
71 } else {
72 msg << fmt;
73 }
74 AddReferrerLocation(msg, referrer);
75 Thread* self = Thread::Current();
76 self->ThrowNewException(exception_descriptor, msg.str().c_str());
77 }
78
ThrowWrappedException(const char * exception_descriptor,ObjPtr<mirror::Class> referrer,const char * fmt,va_list * args=nullptr)79 static void ThrowWrappedException(const char* exception_descriptor,
80 ObjPtr<mirror::Class> referrer,
81 const char* fmt,
82 va_list* args = nullptr)
83 REQUIRES_SHARED(Locks::mutator_lock_) {
84 std::ostringstream msg;
85 if (args != nullptr) {
86 std::string vmsg;
87 StringAppendV(&vmsg, fmt, *args);
88 msg << vmsg;
89 } else {
90 msg << fmt;
91 }
92 AddReferrerLocation(msg, referrer);
93 Thread* self = Thread::Current();
94 self->ThrowNewWrappedException(exception_descriptor, msg.str().c_str());
95 }
96
97 // AbstractMethodError
98
ThrowAbstractMethodError(ArtMethod * method)99 void ThrowAbstractMethodError(ArtMethod* method) {
100 ThrowException("Ljava/lang/AbstractMethodError;", nullptr,
101 StringPrintf("abstract method \"%s\"",
102 ArtMethod::PrettyMethod(method).c_str()).c_str());
103 }
104
ThrowAbstractMethodError(uint32_t method_idx,const DexFile & dex_file)105 void ThrowAbstractMethodError(uint32_t method_idx, const DexFile& dex_file) {
106 ThrowException("Ljava/lang/AbstractMethodError;", /* referrer= */ nullptr,
107 StringPrintf("abstract method \"%s\"",
108 dex_file.PrettyMethod(method_idx,
109 /* with_signature= */ true).c_str()).c_str());
110 }
111
112 // ArithmeticException
113
ThrowArithmeticExceptionDivideByZero()114 void ThrowArithmeticExceptionDivideByZero() {
115 ThrowException("Ljava/lang/ArithmeticException;", nullptr, "divide by zero");
116 }
117
118 // ArrayIndexOutOfBoundsException
119
ThrowArrayIndexOutOfBoundsException(int index,int length)120 void ThrowArrayIndexOutOfBoundsException(int index, int length) {
121 ThrowException("Ljava/lang/ArrayIndexOutOfBoundsException;", nullptr,
122 StringPrintf("length=%d; index=%d", length, index).c_str());
123 }
124
125 // ArrayStoreException
126
ThrowArrayStoreException(ObjPtr<mirror::Class> element_class,ObjPtr<mirror::Class> array_class)127 void ThrowArrayStoreException(ObjPtr<mirror::Class> element_class,
128 ObjPtr<mirror::Class> array_class) {
129 ThrowException("Ljava/lang/ArrayStoreException;", nullptr,
130 StringPrintf("%s cannot be stored in an array of type %s",
131 mirror::Class::PrettyDescriptor(element_class).c_str(),
132 mirror::Class::PrettyDescriptor(array_class).c_str()).c_str());
133 }
134
135 // BootstrapMethodError
136
ThrowBootstrapMethodError(const char * fmt,...)137 void ThrowBootstrapMethodError(const char* fmt, ...) {
138 va_list args;
139 va_start(args, fmt);
140 ThrowException("Ljava/lang/BootstrapMethodError;", nullptr, fmt, &args);
141 va_end(args);
142 }
143
ThrowWrappedBootstrapMethodError(const char * fmt,...)144 void ThrowWrappedBootstrapMethodError(const char* fmt, ...) {
145 va_list args;
146 va_start(args, fmt);
147 ThrowWrappedException("Ljava/lang/BootstrapMethodError;", nullptr, fmt, &args);
148 va_end(args);
149 }
150
151 // ClassCastException
152
ThrowClassCastException(ObjPtr<mirror::Class> dest_type,ObjPtr<mirror::Class> src_type)153 void ThrowClassCastException(ObjPtr<mirror::Class> dest_type, ObjPtr<mirror::Class> src_type) {
154 DumpB77342775DebugData(dest_type, src_type);
155 ThrowException("Ljava/lang/ClassCastException;", nullptr,
156 StringPrintf("%s cannot be cast to %s",
157 mirror::Class::PrettyDescriptor(src_type).c_str(),
158 mirror::Class::PrettyDescriptor(dest_type).c_str()).c_str());
159 }
160
ThrowClassCastException(const char * msg)161 void ThrowClassCastException(const char* msg) {
162 ThrowException("Ljava/lang/ClassCastException;", nullptr, msg);
163 }
164
165 // ClassCircularityError
166
ThrowClassCircularityError(ObjPtr<mirror::Class> c)167 void ThrowClassCircularityError(ObjPtr<mirror::Class> c) {
168 std::ostringstream msg;
169 msg << mirror::Class::PrettyDescriptor(c);
170 ThrowException("Ljava/lang/ClassCircularityError;", c, msg.str().c_str());
171 }
172
ThrowClassCircularityError(ObjPtr<mirror::Class> c,const char * fmt,...)173 void ThrowClassCircularityError(ObjPtr<mirror::Class> c, const char* fmt, ...) {
174 va_list args;
175 va_start(args, fmt);
176 ThrowException("Ljava/lang/ClassCircularityError;", c, fmt, &args);
177 va_end(args);
178 }
179
180 // ClassFormatError
181
ThrowClassFormatError(ObjPtr<mirror::Class> referrer,const char * fmt,...)182 void ThrowClassFormatError(ObjPtr<mirror::Class> referrer, const char* fmt, ...) {
183 va_list args;
184 va_start(args, fmt);
185 ThrowException("Ljava/lang/ClassFormatError;", referrer, fmt, &args);
186 va_end(args);
187 }
188
189 // IllegalAccessError
190
ThrowIllegalAccessErrorClass(ObjPtr<mirror::Class> referrer,ObjPtr<mirror::Class> accessed)191 void ThrowIllegalAccessErrorClass(ObjPtr<mirror::Class> referrer, ObjPtr<mirror::Class> accessed) {
192 std::ostringstream msg;
193 msg << "Illegal class access: '" << mirror::Class::PrettyDescriptor(referrer)
194 << "' attempting to access '" << mirror::Class::PrettyDescriptor(accessed) << "'";
195 ThrowException("Ljava/lang/IllegalAccessError;", referrer, msg.str().c_str());
196 }
197
ThrowIllegalAccessErrorClassForMethodDispatch(ObjPtr<mirror::Class> referrer,ObjPtr<mirror::Class> accessed,ArtMethod * called,InvokeType type)198 void ThrowIllegalAccessErrorClassForMethodDispatch(ObjPtr<mirror::Class> referrer,
199 ObjPtr<mirror::Class> accessed,
200 ArtMethod* called,
201 InvokeType type) {
202 std::ostringstream msg;
203 msg << "Illegal class access ('" << mirror::Class::PrettyDescriptor(referrer)
204 << "' attempting to access '"
205 << mirror::Class::PrettyDescriptor(accessed) << "') in attempt to invoke " << type
206 << " method " << ArtMethod::PrettyMethod(called).c_str();
207 ThrowException("Ljava/lang/IllegalAccessError;", referrer, msg.str().c_str());
208 }
209
ThrowIllegalAccessErrorMethod(ObjPtr<mirror::Class> referrer,ArtMethod * accessed)210 void ThrowIllegalAccessErrorMethod(ObjPtr<mirror::Class> referrer, ArtMethod* accessed) {
211 std::ostringstream msg;
212 msg << "Method '" << ArtMethod::PrettyMethod(accessed) << "' is inaccessible to class '"
213 << mirror::Class::PrettyDescriptor(referrer) << "'";
214 ThrowException("Ljava/lang/IllegalAccessError;", referrer, msg.str().c_str());
215 }
216
ThrowIllegalAccessErrorField(ObjPtr<mirror::Class> referrer,ArtField * accessed)217 void ThrowIllegalAccessErrorField(ObjPtr<mirror::Class> referrer, ArtField* accessed) {
218 std::ostringstream msg;
219 msg << "Field '" << ArtField::PrettyField(accessed, false) << "' is inaccessible to class '"
220 << mirror::Class::PrettyDescriptor(referrer) << "'";
221 ThrowException("Ljava/lang/IllegalAccessError;", referrer, msg.str().c_str());
222 }
223
ThrowIllegalAccessErrorFinalField(ArtMethod * referrer,ArtField * accessed)224 void ThrowIllegalAccessErrorFinalField(ArtMethod* referrer, ArtField* accessed) {
225 std::ostringstream msg;
226 msg << "Final field '" << ArtField::PrettyField(accessed, false)
227 << "' cannot be written to by method '" << ArtMethod::PrettyMethod(referrer) << "'";
228 ThrowException("Ljava/lang/IllegalAccessError;",
229 referrer != nullptr ? referrer->GetDeclaringClass() : nullptr,
230 msg.str().c_str());
231 }
232
ThrowIllegalAccessError(ObjPtr<mirror::Class> referrer,const char * fmt,...)233 void ThrowIllegalAccessError(ObjPtr<mirror::Class> referrer, const char* fmt, ...) {
234 va_list args;
235 va_start(args, fmt);
236 ThrowException("Ljava/lang/IllegalAccessError;", referrer, fmt, &args);
237 va_end(args);
238 }
239
240 // IllegalAccessException
241
ThrowIllegalAccessException(const char * msg)242 void ThrowIllegalAccessException(const char* msg) {
243 ThrowException("Ljava/lang/IllegalAccessException;", nullptr, msg);
244 }
245
246 // IllegalArgumentException
247
ThrowIllegalArgumentException(const char * msg)248 void ThrowIllegalArgumentException(const char* msg) {
249 ThrowException("Ljava/lang/IllegalArgumentException;", nullptr, msg);
250 }
251
252 // IllegalStateException
253
ThrowIllegalStateException(const char * msg)254 void ThrowIllegalStateException(const char* msg) {
255 ThrowException("Ljava/lang/IllegalStateException;", nullptr, msg);
256 }
257
258 // IncompatibleClassChangeError
259
ThrowIncompatibleClassChangeError(InvokeType expected_type,InvokeType found_type,ArtMethod * method,ArtMethod * referrer)260 void ThrowIncompatibleClassChangeError(InvokeType expected_type, InvokeType found_type,
261 ArtMethod* method, ArtMethod* referrer) {
262 std::ostringstream msg;
263 msg << "The method '" << ArtMethod::PrettyMethod(method) << "' was expected to be of type "
264 << expected_type << " but instead was found to be of type " << found_type;
265 ThrowException("Ljava/lang/IncompatibleClassChangeError;",
266 referrer != nullptr ? referrer->GetDeclaringClass() : nullptr,
267 msg.str().c_str());
268 }
269
ThrowIncompatibleClassChangeErrorClassForInterfaceSuper(ArtMethod * method,ObjPtr<mirror::Class> target_class,ObjPtr<mirror::Object> this_object,ArtMethod * referrer)270 void ThrowIncompatibleClassChangeErrorClassForInterfaceSuper(ArtMethod* method,
271 ObjPtr<mirror::Class> target_class,
272 ObjPtr<mirror::Object> this_object,
273 ArtMethod* referrer) {
274 // Referrer is calling interface_method on this_object, however, the interface_method isn't
275 // implemented by this_object.
276 CHECK(this_object != nullptr);
277 std::ostringstream msg;
278 msg << "Class '" << mirror::Class::PrettyDescriptor(this_object->GetClass())
279 << "' does not implement interface '" << mirror::Class::PrettyDescriptor(target_class)
280 << "' in call to '"
281 << ArtMethod::PrettyMethod(method) << "'";
282 DumpB77342775DebugData(target_class, this_object->GetClass());
283 ThrowException("Ljava/lang/IncompatibleClassChangeError;",
284 referrer != nullptr ? referrer->GetDeclaringClass() : nullptr,
285 msg.str().c_str());
286 }
287
ThrowIncompatibleClassChangeErrorClassForInterfaceDispatch(ArtMethod * interface_method,ObjPtr<mirror::Object> this_object,ArtMethod * referrer)288 void ThrowIncompatibleClassChangeErrorClassForInterfaceDispatch(ArtMethod* interface_method,
289 ObjPtr<mirror::Object> this_object,
290 ArtMethod* referrer) {
291 // Referrer is calling interface_method on this_object, however, the interface_method isn't
292 // implemented by this_object.
293 CHECK(this_object != nullptr);
294 std::ostringstream msg;
295 msg << "Class '" << mirror::Class::PrettyDescriptor(this_object->GetClass())
296 << "' does not implement interface '"
297 << mirror::Class::PrettyDescriptor(interface_method->GetDeclaringClass())
298 << "' in call to '" << ArtMethod::PrettyMethod(interface_method) << "'";
299 DumpB77342775DebugData(interface_method->GetDeclaringClass(), this_object->GetClass());
300 ThrowException("Ljava/lang/IncompatibleClassChangeError;",
301 referrer != nullptr ? referrer->GetDeclaringClass() : nullptr,
302 msg.str().c_str());
303 }
304
ThrowIncompatibleClassChangeErrorField(ArtField * resolved_field,bool is_static,ArtMethod * referrer)305 void ThrowIncompatibleClassChangeErrorField(ArtField* resolved_field, bool is_static,
306 ArtMethod* referrer) {
307 std::ostringstream msg;
308 msg << "Expected '" << ArtField::PrettyField(resolved_field) << "' to be a "
309 << (is_static ? "static" : "instance") << " field" << " rather than a "
310 << (is_static ? "instance" : "static") << " field";
311 ThrowException("Ljava/lang/IncompatibleClassChangeError;", referrer->GetDeclaringClass(),
312 msg.str().c_str());
313 }
314
ThrowIncompatibleClassChangeError(ObjPtr<mirror::Class> referrer,const char * fmt,...)315 void ThrowIncompatibleClassChangeError(ObjPtr<mirror::Class> referrer, const char* fmt, ...) {
316 va_list args;
317 va_start(args, fmt);
318 ThrowException("Ljava/lang/IncompatibleClassChangeError;", referrer, fmt, &args);
319 va_end(args);
320 }
321
ThrowIncompatibleClassChangeErrorForMethodConflict(ArtMethod * method)322 void ThrowIncompatibleClassChangeErrorForMethodConflict(ArtMethod* method) {
323 DCHECK(method != nullptr);
324 ThrowException("Ljava/lang/IncompatibleClassChangeError;",
325 /*referrer=*/nullptr,
326 StringPrintf("Conflicting default method implementations %s",
327 ArtMethod::PrettyMethod(method).c_str()).c_str());
328 }
329
330 // IndexOutOfBoundsException
331
ThrowIndexOutOfBoundsException(int index,int length)332 void ThrowIndexOutOfBoundsException(int index, int length) {
333 ThrowException("Ljava/lang/IndexOutOfBoundsException;", nullptr,
334 StringPrintf("length=%d; index=%d", length, index).c_str());
335 }
336
337 // InternalError
338
ThrowInternalError(const char * fmt,...)339 void ThrowInternalError(const char* fmt, ...) {
340 va_list args;
341 va_start(args, fmt);
342 ThrowException("Ljava/lang/InternalError;", nullptr, fmt, &args);
343 va_end(args);
344 }
345
346 // IOException
347
ThrowIOException(const char * fmt,...)348 void ThrowIOException(const char* fmt, ...) {
349 va_list args;
350 va_start(args, fmt);
351 ThrowException("Ljava/io/IOException;", nullptr, fmt, &args);
352 va_end(args);
353 }
354
ThrowWrappedIOException(const char * fmt,...)355 void ThrowWrappedIOException(const char* fmt, ...) {
356 va_list args;
357 va_start(args, fmt);
358 ThrowWrappedException("Ljava/io/IOException;", nullptr, fmt, &args);
359 va_end(args);
360 }
361
362 // LinkageError
363
ThrowLinkageError(ObjPtr<mirror::Class> referrer,const char * fmt,...)364 void ThrowLinkageError(ObjPtr<mirror::Class> referrer, const char* fmt, ...) {
365 va_list args;
366 va_start(args, fmt);
367 ThrowException("Ljava/lang/LinkageError;", referrer, fmt, &args);
368 va_end(args);
369 }
370
ThrowWrappedLinkageError(ObjPtr<mirror::Class> referrer,const char * fmt,...)371 void ThrowWrappedLinkageError(ObjPtr<mirror::Class> referrer, const char* fmt, ...) {
372 va_list args;
373 va_start(args, fmt);
374 ThrowWrappedException("Ljava/lang/LinkageError;", referrer, fmt, &args);
375 va_end(args);
376 }
377
378 // NegativeArraySizeException
379
ThrowNegativeArraySizeException(int size)380 void ThrowNegativeArraySizeException(int size) {
381 ThrowException("Ljava/lang/NegativeArraySizeException;", nullptr,
382 StringPrintf("%d", size).c_str());
383 }
384
ThrowNegativeArraySizeException(const char * msg)385 void ThrowNegativeArraySizeException(const char* msg) {
386 ThrowException("Ljava/lang/NegativeArraySizeException;", nullptr, msg);
387 }
388
389 // NoSuchFieldError
390
ThrowNoSuchFieldError(std::string_view scope,ObjPtr<mirror::Class> c,std::string_view type,std::string_view name)391 void ThrowNoSuchFieldError(std::string_view scope,
392 ObjPtr<mirror::Class> c,
393 std::string_view type,
394 std::string_view name) {
395 std::ostringstream msg;
396 std::string temp;
397 msg << "No " << scope << "field " << name << " of type " << type
398 << " in class " << c->GetDescriptor(&temp) << " or its superclasses";
399 ThrowException("Ljava/lang/NoSuchFieldError;", c, msg.str().c_str());
400 }
401
ThrowNoSuchFieldException(ObjPtr<mirror::Class> c,std::string_view name)402 void ThrowNoSuchFieldException(ObjPtr<mirror::Class> c, std::string_view name) {
403 std::ostringstream msg;
404 std::string temp;
405 msg << "No field " << name << " in class " << c->GetDescriptor(&temp);
406 ThrowException("Ljava/lang/NoSuchFieldException;", c, msg.str().c_str());
407 }
408
409 // NoSuchMethodError
410
ThrowNoSuchMethodError(InvokeType type,ObjPtr<mirror::Class> c,std::string_view name,const Signature & signature)411 void ThrowNoSuchMethodError(InvokeType type,
412 ObjPtr<mirror::Class> c,
413 std::string_view name,
414 const Signature& signature) {
415 std::ostringstream msg;
416 std::string temp;
417 msg << "No " << type << " method " << name << signature
418 << " in class " << c->GetDescriptor(&temp) << " or its super classes";
419 ThrowException("Ljava/lang/NoSuchMethodError;", c, msg.str().c_str());
420 }
421
422 // NullPointerException
423
ThrowNullPointerExceptionForFieldAccess(ArtField * field,bool is_read)424 void ThrowNullPointerExceptionForFieldAccess(ArtField* field, bool is_read) {
425 std::ostringstream msg;
426 msg << "Attempt to " << (is_read ? "read from" : "write to")
427 << " field '" << ArtField::PrettyField(field, true) << "' on a null object reference";
428 ThrowException("Ljava/lang/NullPointerException;", nullptr, msg.str().c_str());
429 }
430
ThrowNullPointerExceptionForMethodAccessImpl(uint32_t method_idx,const DexFile & dex_file,InvokeType type)431 static void ThrowNullPointerExceptionForMethodAccessImpl(uint32_t method_idx,
432 const DexFile& dex_file,
433 InvokeType type)
434 REQUIRES_SHARED(Locks::mutator_lock_) {
435 std::ostringstream msg;
436 msg << "Attempt to invoke " << type << " method '"
437 << dex_file.PrettyMethod(method_idx, true) << "' on a null object reference";
438 ThrowException("Ljava/lang/NullPointerException;", nullptr, msg.str().c_str());
439 }
440
ThrowNullPointerExceptionForMethodAccess(uint32_t method_idx,InvokeType type)441 void ThrowNullPointerExceptionForMethodAccess(uint32_t method_idx, InvokeType type) {
442 const DexFile& dex_file = *Thread::Current()->GetCurrentMethod(nullptr)->GetDexFile();
443 ThrowNullPointerExceptionForMethodAccessImpl(method_idx, dex_file, type);
444 }
445
ThrowNullPointerExceptionForMethodAccess(ArtMethod * method,InvokeType type)446 void ThrowNullPointerExceptionForMethodAccess(ArtMethod* method, InvokeType type) {
447 ThrowNullPointerExceptionForMethodAccessImpl(method->GetDexMethodIndex(),
448 *method->GetDexFile(),
449 type);
450 }
451
IsValidReadBarrierImplicitCheck(uintptr_t addr)452 static bool IsValidReadBarrierImplicitCheck(uintptr_t addr) {
453 DCHECK(kEmitCompilerReadBarrier);
454 uint32_t monitor_offset = mirror::Object::MonitorOffset().Uint32Value();
455 if (kUseBakerReadBarrier &&
456 (kRuntimeISA == InstructionSet::kX86 || kRuntimeISA == InstructionSet::kX86_64)) {
457 constexpr uint32_t gray_byte_position = LockWord::kReadBarrierStateShift / kBitsPerByte;
458 monitor_offset += gray_byte_position;
459 }
460 return addr == monitor_offset;
461 }
462
IsValidImplicitCheck(uintptr_t addr,const Instruction & instr)463 static bool IsValidImplicitCheck(uintptr_t addr, const Instruction& instr)
464 REQUIRES_SHARED(Locks::mutator_lock_) {
465 if (!CanDoImplicitNullCheckOn(addr)) {
466 return false;
467 }
468
469 switch (instr.Opcode()) {
470 case Instruction::INVOKE_DIRECT:
471 case Instruction::INVOKE_DIRECT_RANGE:
472 case Instruction::INVOKE_VIRTUAL:
473 case Instruction::INVOKE_VIRTUAL_RANGE:
474 case Instruction::INVOKE_INTERFACE:
475 case Instruction::INVOKE_INTERFACE_RANGE:
476 case Instruction::INVOKE_POLYMORPHIC:
477 case Instruction::INVOKE_POLYMORPHIC_RANGE:
478 case Instruction::INVOKE_SUPER:
479 case Instruction::INVOKE_SUPER_RANGE:
480 case Instruction::INVOKE_VIRTUAL_QUICK:
481 case Instruction::INVOKE_VIRTUAL_RANGE_QUICK: {
482 // Without inlining, we could just check that the offset is the class offset.
483 // However, when inlining, the compiler can (validly) merge the null check with a field access
484 // on the same object. Note that the stack map at the NPE will reflect the invoke's location,
485 // which is the caller.
486 return true;
487 }
488
489 case Instruction::IGET_OBJECT:
490 if (kEmitCompilerReadBarrier && IsValidReadBarrierImplicitCheck(addr)) {
491 return true;
492 }
493 FALLTHROUGH_INTENDED;
494 case Instruction::IGET:
495 case Instruction::IGET_WIDE:
496 case Instruction::IGET_BOOLEAN:
497 case Instruction::IGET_BYTE:
498 case Instruction::IGET_CHAR:
499 case Instruction::IGET_SHORT:
500 case Instruction::IPUT:
501 case Instruction::IPUT_WIDE:
502 case Instruction::IPUT_OBJECT:
503 case Instruction::IPUT_BOOLEAN:
504 case Instruction::IPUT_BYTE:
505 case Instruction::IPUT_CHAR:
506 case Instruction::IPUT_SHORT: {
507 // We might be doing an implicit null check with an offset that doesn't correspond
508 // to the instruction, for example with two field accesses and the first one being
509 // eliminated or re-ordered.
510 return true;
511 }
512
513 case Instruction::IGET_OBJECT_QUICK:
514 if (kEmitCompilerReadBarrier && IsValidReadBarrierImplicitCheck(addr)) {
515 return true;
516 }
517 FALLTHROUGH_INTENDED;
518 case Instruction::IGET_QUICK:
519 case Instruction::IGET_BOOLEAN_QUICK:
520 case Instruction::IGET_BYTE_QUICK:
521 case Instruction::IGET_CHAR_QUICK:
522 case Instruction::IGET_SHORT_QUICK:
523 case Instruction::IGET_WIDE_QUICK:
524 case Instruction::IPUT_QUICK:
525 case Instruction::IPUT_BOOLEAN_QUICK:
526 case Instruction::IPUT_BYTE_QUICK:
527 case Instruction::IPUT_CHAR_QUICK:
528 case Instruction::IPUT_SHORT_QUICK:
529 case Instruction::IPUT_WIDE_QUICK:
530 case Instruction::IPUT_OBJECT_QUICK: {
531 // We might be doing an implicit null check with an offset that doesn't correspond
532 // to the instruction, for example with two field accesses and the first one being
533 // eliminated or re-ordered.
534 return true;
535 }
536
537 case Instruction::AGET_OBJECT:
538 if (kEmitCompilerReadBarrier && IsValidReadBarrierImplicitCheck(addr)) {
539 return true;
540 }
541 FALLTHROUGH_INTENDED;
542 case Instruction::AGET:
543 case Instruction::AGET_WIDE:
544 case Instruction::AGET_BOOLEAN:
545 case Instruction::AGET_BYTE:
546 case Instruction::AGET_CHAR:
547 case Instruction::AGET_SHORT:
548 case Instruction::APUT:
549 case Instruction::APUT_WIDE:
550 case Instruction::APUT_OBJECT:
551 case Instruction::APUT_BOOLEAN:
552 case Instruction::APUT_BYTE:
553 case Instruction::APUT_CHAR:
554 case Instruction::APUT_SHORT:
555 case Instruction::FILL_ARRAY_DATA:
556 case Instruction::ARRAY_LENGTH: {
557 // The length access should crash. We currently do not do implicit checks on
558 // the array access itself.
559 return (addr == 0u) || (addr == mirror::Array::LengthOffset().Uint32Value());
560 }
561
562 default: {
563 // We have covered all the cases where an NPE could occur.
564 // Note that this must be kept in sync with the compiler, and adding
565 // any new way to do implicit checks in the compiler should also update
566 // this code.
567 return false;
568 }
569 }
570 }
571
ThrowNullPointerExceptionFromDexPC(bool check_address,uintptr_t addr)572 void ThrowNullPointerExceptionFromDexPC(bool check_address, uintptr_t addr) {
573 uint32_t throw_dex_pc;
574 ArtMethod* method = Thread::Current()->GetCurrentMethod(&throw_dex_pc);
575 CodeItemInstructionAccessor accessor(method->DexInstructions());
576 CHECK_LT(throw_dex_pc, accessor.InsnsSizeInCodeUnits());
577 const Instruction& instr = accessor.InstructionAt(throw_dex_pc);
578 if (check_address && !IsValidImplicitCheck(addr, instr)) {
579 const DexFile* dex_file = method->GetDexFile();
580 LOG(FATAL) << "Invalid address for an implicit NullPointerException check: "
581 << "0x" << std::hex << addr << std::dec
582 << ", at "
583 << instr.DumpString(dex_file)
584 << " in "
585 << method->PrettyMethod();
586 }
587
588 switch (instr.Opcode()) {
589 case Instruction::INVOKE_DIRECT:
590 ThrowNullPointerExceptionForMethodAccess(instr.VRegB_35c(), kDirect);
591 break;
592 case Instruction::INVOKE_DIRECT_RANGE:
593 ThrowNullPointerExceptionForMethodAccess(instr.VRegB_3rc(), kDirect);
594 break;
595 case Instruction::INVOKE_VIRTUAL:
596 ThrowNullPointerExceptionForMethodAccess(instr.VRegB_35c(), kVirtual);
597 break;
598 case Instruction::INVOKE_VIRTUAL_RANGE:
599 ThrowNullPointerExceptionForMethodAccess(instr.VRegB_3rc(), kVirtual);
600 break;
601 case Instruction::INVOKE_SUPER:
602 ThrowNullPointerExceptionForMethodAccess(instr.VRegB_35c(), kSuper);
603 break;
604 case Instruction::INVOKE_SUPER_RANGE:
605 ThrowNullPointerExceptionForMethodAccess(instr.VRegB_3rc(), kSuper);
606 break;
607 case Instruction::INVOKE_INTERFACE:
608 ThrowNullPointerExceptionForMethodAccess(instr.VRegB_35c(), kInterface);
609 break;
610 case Instruction::INVOKE_INTERFACE_RANGE:
611 ThrowNullPointerExceptionForMethodAccess(instr.VRegB_3rc(), kInterface);
612 break;
613 case Instruction::INVOKE_POLYMORPHIC:
614 ThrowNullPointerExceptionForMethodAccess(instr.VRegB_45cc(), kVirtual);
615 break;
616 case Instruction::INVOKE_POLYMORPHIC_RANGE:
617 ThrowNullPointerExceptionForMethodAccess(instr.VRegB_4rcc(), kVirtual);
618 break;
619 case Instruction::INVOKE_VIRTUAL_QUICK:
620 case Instruction::INVOKE_VIRTUAL_RANGE_QUICK: {
621 uint16_t method_idx = method->GetIndexFromQuickening(throw_dex_pc);
622 if (method_idx != DexFile::kDexNoIndex16) {
623 // NPE with precise message.
624 ThrowNullPointerExceptionForMethodAccess(method_idx, kVirtual);
625 } else {
626 // NPE with imprecise message.
627 ThrowNullPointerException("Attempt to invoke a virtual method on a null object reference");
628 }
629 break;
630 }
631 case Instruction::IGET:
632 case Instruction::IGET_WIDE:
633 case Instruction::IGET_OBJECT:
634 case Instruction::IGET_BOOLEAN:
635 case Instruction::IGET_BYTE:
636 case Instruction::IGET_CHAR:
637 case Instruction::IGET_SHORT: {
638 ArtField* field =
639 Runtime::Current()->GetClassLinker()->ResolveField(instr.VRegC_22c(), method, false);
640 Thread::Current()->ClearException(); // Resolution may fail, ignore.
641 ThrowNullPointerExceptionForFieldAccess(field, /* is_read= */ true);
642 break;
643 }
644 case Instruction::IGET_QUICK:
645 case Instruction::IGET_BOOLEAN_QUICK:
646 case Instruction::IGET_BYTE_QUICK:
647 case Instruction::IGET_CHAR_QUICK:
648 case Instruction::IGET_SHORT_QUICK:
649 case Instruction::IGET_WIDE_QUICK:
650 case Instruction::IGET_OBJECT_QUICK: {
651 uint16_t field_idx = method->GetIndexFromQuickening(throw_dex_pc);
652 ArtField* field = nullptr;
653 CHECK_NE(field_idx, DexFile::kDexNoIndex16);
654 field = Runtime::Current()->GetClassLinker()->ResolveField(
655 field_idx, method, /* is_static= */ false);
656 Thread::Current()->ClearException(); // Resolution may fail, ignore.
657 ThrowNullPointerExceptionForFieldAccess(field, /* is_read= */ true);
658 break;
659 }
660 case Instruction::IPUT:
661 case Instruction::IPUT_WIDE:
662 case Instruction::IPUT_OBJECT:
663 case Instruction::IPUT_BOOLEAN:
664 case Instruction::IPUT_BYTE:
665 case Instruction::IPUT_CHAR:
666 case Instruction::IPUT_SHORT: {
667 ArtField* field = Runtime::Current()->GetClassLinker()->ResolveField(
668 instr.VRegC_22c(), method, /* is_static= */ false);
669 Thread::Current()->ClearException(); // Resolution may fail, ignore.
670 ThrowNullPointerExceptionForFieldAccess(field, /* is_read= */ false);
671 break;
672 }
673 case Instruction::IPUT_QUICK:
674 case Instruction::IPUT_BOOLEAN_QUICK:
675 case Instruction::IPUT_BYTE_QUICK:
676 case Instruction::IPUT_CHAR_QUICK:
677 case Instruction::IPUT_SHORT_QUICK:
678 case Instruction::IPUT_WIDE_QUICK:
679 case Instruction::IPUT_OBJECT_QUICK: {
680 uint16_t field_idx = method->GetIndexFromQuickening(throw_dex_pc);
681 ArtField* field = nullptr;
682 CHECK_NE(field_idx, DexFile::kDexNoIndex16);
683 field = Runtime::Current()->GetClassLinker()->ResolveField(
684 field_idx, method, /* is_static= */ false);
685 Thread::Current()->ClearException(); // Resolution may fail, ignore.
686 ThrowNullPointerExceptionForFieldAccess(field, /* is_read= */ false);
687 break;
688 }
689 case Instruction::AGET:
690 case Instruction::AGET_WIDE:
691 case Instruction::AGET_OBJECT:
692 case Instruction::AGET_BOOLEAN:
693 case Instruction::AGET_BYTE:
694 case Instruction::AGET_CHAR:
695 case Instruction::AGET_SHORT:
696 ThrowException("Ljava/lang/NullPointerException;", nullptr,
697 "Attempt to read from null array");
698 break;
699 case Instruction::APUT:
700 case Instruction::APUT_WIDE:
701 case Instruction::APUT_OBJECT:
702 case Instruction::APUT_BOOLEAN:
703 case Instruction::APUT_BYTE:
704 case Instruction::APUT_CHAR:
705 case Instruction::APUT_SHORT:
706 ThrowException("Ljava/lang/NullPointerException;", nullptr,
707 "Attempt to write to null array");
708 break;
709 case Instruction::ARRAY_LENGTH:
710 ThrowException("Ljava/lang/NullPointerException;", nullptr,
711 "Attempt to get length of null array");
712 break;
713 case Instruction::FILL_ARRAY_DATA: {
714 ThrowException("Ljava/lang/NullPointerException;", nullptr,
715 "Attempt to write to null array");
716 break;
717 }
718 case Instruction::MONITOR_ENTER:
719 case Instruction::MONITOR_EXIT: {
720 ThrowException("Ljava/lang/NullPointerException;", nullptr,
721 "Attempt to do a synchronize operation on a null object");
722 break;
723 }
724 default: {
725 const DexFile* dex_file = method->GetDexFile();
726 LOG(FATAL) << "NullPointerException at an unexpected instruction: "
727 << instr.DumpString(dex_file)
728 << " in "
729 << method->PrettyMethod();
730 UNREACHABLE();
731 }
732 }
733 }
734
ThrowNullPointerException(const char * msg)735 void ThrowNullPointerException(const char* msg) {
736 ThrowException("Ljava/lang/NullPointerException;", nullptr, msg);
737 }
738
ThrowNullPointerException()739 void ThrowNullPointerException() {
740 ThrowException("Ljava/lang/NullPointerException;");
741 }
742
743 // ReadOnlyBufferException
744
ThrowReadOnlyBufferException()745 void ThrowReadOnlyBufferException() {
746 Thread::Current()->ThrowNewException("Ljava/nio/ReadOnlyBufferException;", nullptr);
747 }
748
749 // RuntimeException
750
ThrowRuntimeException(const char * fmt,...)751 void ThrowRuntimeException(const char* fmt, ...) {
752 va_list args;
753 va_start(args, fmt);
754 ThrowException("Ljava/lang/RuntimeException;", nullptr, fmt, &args);
755 va_end(args);
756 }
757
758 // SecurityException
759
ThrowSecurityException(const char * fmt,...)760 void ThrowSecurityException(const char* fmt, ...) {
761 va_list args;
762 va_start(args, fmt);
763 ThrowException("Ljava/lang/SecurityException;", nullptr, fmt, &args);
764 va_end(args);
765 }
766
767 // Stack overflow.
768
ThrowStackOverflowError(Thread * self)769 void ThrowStackOverflowError(Thread* self) {
770 if (self->IsHandlingStackOverflow()) {
771 LOG(ERROR) << "Recursive stack overflow.";
772 // We don't fail here because SetStackEndForStackOverflow will print better diagnostics.
773 }
774
775 self->SetStackEndForStackOverflow(); // Allow space on the stack for constructor to execute.
776 JNIEnvExt* env = self->GetJniEnv();
777 std::string msg("stack size ");
778 msg += PrettySize(self->GetStackSize());
779
780 // Avoid running Java code for exception initialization.
781 // TODO: Checks to make this a bit less brittle.
782 //
783 // Note: this lambda ensures that the destruction of the ScopedLocalRefs will run in the extended
784 // stack, which is important for modes with larger stack sizes (e.g., ASAN). Using a lambda
785 // instead of a block simplifies the control flow.
786 auto create_and_throw = [&]() REQUIRES_SHARED(Locks::mutator_lock_) {
787 // Allocate an uninitialized object.
788 ScopedLocalRef<jobject> exc(env,
789 env->AllocObject(WellKnownClasses::java_lang_StackOverflowError));
790 if (exc == nullptr) {
791 LOG(WARNING) << "Could not allocate StackOverflowError object.";
792 return;
793 }
794
795 // "Initialize".
796 // StackOverflowError -> VirtualMachineError -> Error -> Throwable -> Object.
797 // Only Throwable has "custom" fields:
798 // String detailMessage.
799 // Throwable cause (= this).
800 // List<Throwable> suppressedExceptions (= Collections.emptyList()).
801 // Object stackState;
802 // StackTraceElement[] stackTrace;
803 // Only Throwable has a non-empty constructor:
804 // this.stackTrace = EmptyArray.STACK_TRACE_ELEMENT;
805 // fillInStackTrace();
806
807 // detailMessage.
808 // TODO: Use String::FromModifiedUTF...?
809 ScopedLocalRef<jstring> s(env, env->NewStringUTF(msg.c_str()));
810 if (s == nullptr) {
811 LOG(WARNING) << "Could not throw new StackOverflowError because JNI NewStringUTF failed.";
812 return;
813 }
814
815 env->SetObjectField(exc.get(), WellKnownClasses::java_lang_Throwable_detailMessage, s.get());
816
817 // cause.
818 env->SetObjectField(exc.get(), WellKnownClasses::java_lang_Throwable_cause, exc.get());
819
820 // suppressedExceptions.
821 ScopedLocalRef<jobject> emptylist(env, env->GetStaticObjectField(
822 WellKnownClasses::java_util_Collections,
823 WellKnownClasses::java_util_Collections_EMPTY_LIST));
824 CHECK(emptylist != nullptr);
825 env->SetObjectField(exc.get(),
826 WellKnownClasses::java_lang_Throwable_suppressedExceptions,
827 emptylist.get());
828
829 // stackState is set as result of fillInStackTrace. fillInStackTrace calls
830 // nativeFillInStackTrace.
831 ScopedLocalRef<jobject> stack_state_val(env, nullptr);
832 {
833 ScopedObjectAccessUnchecked soa(env); // TODO: Is this necessary?
834 stack_state_val.reset(soa.Self()->CreateInternalStackTrace<false>(soa));
835 }
836 if (stack_state_val != nullptr) {
837 env->SetObjectField(exc.get(),
838 WellKnownClasses::java_lang_Throwable_stackState,
839 stack_state_val.get());
840
841 // stackTrace.
842 ScopedLocalRef<jobject> stack_trace_elem(env, env->GetStaticObjectField(
843 WellKnownClasses::libcore_util_EmptyArray,
844 WellKnownClasses::libcore_util_EmptyArray_STACK_TRACE_ELEMENT));
845 env->SetObjectField(exc.get(),
846 WellKnownClasses::java_lang_Throwable_stackTrace,
847 stack_trace_elem.get());
848 } else {
849 LOG(WARNING) << "Could not create stack trace.";
850 // Note: we'll create an exception without stack state, which is valid.
851 }
852
853 // Throw the exception.
854 self->SetException(self->DecodeJObject(exc.get())->AsThrowable());
855 };
856 create_and_throw();
857 CHECK(self->IsExceptionPending());
858
859 bool explicit_overflow_check = Runtime::Current()->ExplicitStackOverflowChecks();
860 self->ResetDefaultStackEnd(); // Return to default stack size.
861
862 // And restore protection if implicit checks are on.
863 if (!explicit_overflow_check) {
864 self->ProtectStack();
865 }
866 }
867
868 // StringIndexOutOfBoundsException
869
ThrowStringIndexOutOfBoundsException(int index,int length)870 void ThrowStringIndexOutOfBoundsException(int index, int length) {
871 ThrowException("Ljava/lang/StringIndexOutOfBoundsException;", nullptr,
872 StringPrintf("length=%d; index=%d", length, index).c_str());
873 }
874
875 // UnsupportedOperationException
876
ThrowUnsupportedOperationException()877 void ThrowUnsupportedOperationException() {
878 ThrowException("Ljava/lang/UnsupportedOperationException;");
879 }
880
881 // VerifyError
882
ThrowVerifyError(ObjPtr<mirror::Class> referrer,const char * fmt,...)883 void ThrowVerifyError(ObjPtr<mirror::Class> referrer, const char* fmt, ...) {
884 va_list args;
885 va_start(args, fmt);
886 ThrowException("Ljava/lang/VerifyError;", referrer, fmt, &args);
887 va_end(args);
888 }
889
890 // WrongMethodTypeException
891
ThrowWrongMethodTypeException(ObjPtr<mirror::MethodType> expected_type,ObjPtr<mirror::MethodType> actual_type)892 void ThrowWrongMethodTypeException(ObjPtr<mirror::MethodType> expected_type,
893 ObjPtr<mirror::MethodType> actual_type) {
894 ThrowWrongMethodTypeException(expected_type->PrettyDescriptor(), actual_type->PrettyDescriptor());
895 }
896
ThrowWrongMethodTypeException(const std::string & expected_descriptor,const std::string & actual_descriptor)897 void ThrowWrongMethodTypeException(const std::string& expected_descriptor,
898 const std::string& actual_descriptor) {
899 std::ostringstream msg;
900 msg << "Expected " << expected_descriptor << " but was " << actual_descriptor;
901 ThrowException("Ljava/lang/invoke/WrongMethodTypeException;", nullptr, msg.str().c_str());
902 }
903
904 } // namespace art
905