• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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_VIRTUAL_QUICK:
479     case Instruction::INVOKE_VIRTUAL_RANGE_QUICK: {
480       // Without inlining, we could just check that the offset is the class offset.
481       // However, when inlining, the compiler can (validly) merge the null check with a field access
482       // on the same object. Note that the stack map at the NPE will reflect the invoke's location,
483       // which is the caller.
484       return true;
485     }
486 
487     case Instruction::IGET_OBJECT:
488       if (kEmitCompilerReadBarrier && IsValidReadBarrierImplicitCheck(addr)) {
489         return true;
490       }
491       FALLTHROUGH_INTENDED;
492     case Instruction::IGET:
493     case Instruction::IGET_WIDE:
494     case Instruction::IGET_BOOLEAN:
495     case Instruction::IGET_BYTE:
496     case Instruction::IGET_CHAR:
497     case Instruction::IGET_SHORT:
498     case Instruction::IPUT:
499     case Instruction::IPUT_WIDE:
500     case Instruction::IPUT_OBJECT:
501     case Instruction::IPUT_BOOLEAN:
502     case Instruction::IPUT_BYTE:
503     case Instruction::IPUT_CHAR:
504     case Instruction::IPUT_SHORT: {
505       // We might be doing an implicit null check with an offset that doesn't correspond
506       // to the instruction, for example with two field accesses and the first one being
507       // eliminated or re-ordered.
508       return true;
509     }
510 
511     case Instruction::IGET_OBJECT_QUICK:
512       if (kEmitCompilerReadBarrier && IsValidReadBarrierImplicitCheck(addr)) {
513         return true;
514       }
515       FALLTHROUGH_INTENDED;
516     case Instruction::IGET_QUICK:
517     case Instruction::IGET_BOOLEAN_QUICK:
518     case Instruction::IGET_BYTE_QUICK:
519     case Instruction::IGET_CHAR_QUICK:
520     case Instruction::IGET_SHORT_QUICK:
521     case Instruction::IGET_WIDE_QUICK:
522     case Instruction::IPUT_QUICK:
523     case Instruction::IPUT_BOOLEAN_QUICK:
524     case Instruction::IPUT_BYTE_QUICK:
525     case Instruction::IPUT_CHAR_QUICK:
526     case Instruction::IPUT_SHORT_QUICK:
527     case Instruction::IPUT_WIDE_QUICK:
528     case Instruction::IPUT_OBJECT_QUICK: {
529       // We might be doing an implicit null check with an offset that doesn't correspond
530       // to the instruction, for example with two field accesses and the first one being
531       // eliminated or re-ordered.
532       return true;
533     }
534 
535     case Instruction::AGET_OBJECT:
536       if (kEmitCompilerReadBarrier && IsValidReadBarrierImplicitCheck(addr)) {
537         return true;
538       }
539       FALLTHROUGH_INTENDED;
540     case Instruction::AGET:
541     case Instruction::AGET_WIDE:
542     case Instruction::AGET_BOOLEAN:
543     case Instruction::AGET_BYTE:
544     case Instruction::AGET_CHAR:
545     case Instruction::AGET_SHORT:
546     case Instruction::APUT:
547     case Instruction::APUT_WIDE:
548     case Instruction::APUT_OBJECT:
549     case Instruction::APUT_BOOLEAN:
550     case Instruction::APUT_BYTE:
551     case Instruction::APUT_CHAR:
552     case Instruction::APUT_SHORT:
553     case Instruction::FILL_ARRAY_DATA:
554     case Instruction::ARRAY_LENGTH: {
555       // The length access should crash. We currently do not do implicit checks on
556       // the array access itself.
557       return (addr == 0u) || (addr == mirror::Array::LengthOffset().Uint32Value());
558     }
559 
560     default: {
561       // We have covered all the cases where an NPE could occur.
562       // Note that this must be kept in sync with the compiler, and adding
563       // any new way to do implicit checks in the compiler should also update
564       // this code.
565       return false;
566     }
567   }
568 }
569 
ThrowNullPointerExceptionFromDexPC(bool check_address,uintptr_t addr)570 void ThrowNullPointerExceptionFromDexPC(bool check_address, uintptr_t addr) {
571   uint32_t throw_dex_pc;
572   ArtMethod* method = Thread::Current()->GetCurrentMethod(&throw_dex_pc);
573   CodeItemInstructionAccessor accessor(method->DexInstructions());
574   CHECK_LT(throw_dex_pc, accessor.InsnsSizeInCodeUnits());
575   const Instruction& instr = accessor.InstructionAt(throw_dex_pc);
576   if (check_address && !IsValidImplicitCheck(addr, instr)) {
577     const DexFile* dex_file = method->GetDexFile();
578     LOG(FATAL) << "Invalid address for an implicit NullPointerException check: "
579                << "0x" << std::hex << addr << std::dec
580                << ", at "
581                << instr.DumpString(dex_file)
582                << " in "
583                << method->PrettyMethod();
584   }
585 
586   switch (instr.Opcode()) {
587     case Instruction::INVOKE_DIRECT:
588       ThrowNullPointerExceptionForMethodAccess(instr.VRegB_35c(), kDirect);
589       break;
590     case Instruction::INVOKE_DIRECT_RANGE:
591       ThrowNullPointerExceptionForMethodAccess(instr.VRegB_3rc(), kDirect);
592       break;
593     case Instruction::INVOKE_VIRTUAL:
594       ThrowNullPointerExceptionForMethodAccess(instr.VRegB_35c(), kVirtual);
595       break;
596     case Instruction::INVOKE_VIRTUAL_RANGE:
597       ThrowNullPointerExceptionForMethodAccess(instr.VRegB_3rc(), kVirtual);
598       break;
599     case Instruction::INVOKE_INTERFACE:
600       ThrowNullPointerExceptionForMethodAccess(instr.VRegB_35c(), kInterface);
601       break;
602     case Instruction::INVOKE_INTERFACE_RANGE:
603       ThrowNullPointerExceptionForMethodAccess(instr.VRegB_3rc(), kInterface);
604       break;
605     case Instruction::INVOKE_POLYMORPHIC:
606       ThrowNullPointerExceptionForMethodAccess(instr.VRegB_45cc(), kVirtual);
607       break;
608     case Instruction::INVOKE_POLYMORPHIC_RANGE:
609       ThrowNullPointerExceptionForMethodAccess(instr.VRegB_4rcc(), kVirtual);
610       break;
611     case Instruction::INVOKE_VIRTUAL_QUICK:
612     case Instruction::INVOKE_VIRTUAL_RANGE_QUICK: {
613       uint16_t method_idx = method->GetIndexFromQuickening(throw_dex_pc);
614       if (method_idx != DexFile::kDexNoIndex16) {
615         // NPE with precise message.
616         ThrowNullPointerExceptionForMethodAccess(method_idx, kVirtual);
617       } else {
618         // NPE with imprecise message.
619         ThrowNullPointerException("Attempt to invoke a virtual method on a null object reference");
620       }
621       break;
622     }
623     case Instruction::IGET:
624     case Instruction::IGET_WIDE:
625     case Instruction::IGET_OBJECT:
626     case Instruction::IGET_BOOLEAN:
627     case Instruction::IGET_BYTE:
628     case Instruction::IGET_CHAR:
629     case Instruction::IGET_SHORT: {
630       ArtField* field =
631           Runtime::Current()->GetClassLinker()->ResolveField(instr.VRegC_22c(), method, false);
632       Thread::Current()->ClearException();  // Resolution may fail, ignore.
633       ThrowNullPointerExceptionForFieldAccess(field, /* is_read= */ true);
634       break;
635     }
636     case Instruction::IGET_QUICK:
637     case Instruction::IGET_BOOLEAN_QUICK:
638     case Instruction::IGET_BYTE_QUICK:
639     case Instruction::IGET_CHAR_QUICK:
640     case Instruction::IGET_SHORT_QUICK:
641     case Instruction::IGET_WIDE_QUICK:
642     case Instruction::IGET_OBJECT_QUICK: {
643       uint16_t field_idx = method->GetIndexFromQuickening(throw_dex_pc);
644       ArtField* field = nullptr;
645       CHECK_NE(field_idx, DexFile::kDexNoIndex16);
646       field = Runtime::Current()->GetClassLinker()->ResolveField(
647           field_idx, method, /* is_static= */ false);
648       Thread::Current()->ClearException();  // Resolution may fail, ignore.
649       ThrowNullPointerExceptionForFieldAccess(field, /* is_read= */ true);
650       break;
651     }
652     case Instruction::IPUT:
653     case Instruction::IPUT_WIDE:
654     case Instruction::IPUT_OBJECT:
655     case Instruction::IPUT_BOOLEAN:
656     case Instruction::IPUT_BYTE:
657     case Instruction::IPUT_CHAR:
658     case Instruction::IPUT_SHORT: {
659       ArtField* field = Runtime::Current()->GetClassLinker()->ResolveField(
660           instr.VRegC_22c(), method, /* is_static= */ false);
661       Thread::Current()->ClearException();  // Resolution may fail, ignore.
662       ThrowNullPointerExceptionForFieldAccess(field, /* is_read= */ false);
663       break;
664     }
665     case Instruction::IPUT_QUICK:
666     case Instruction::IPUT_BOOLEAN_QUICK:
667     case Instruction::IPUT_BYTE_QUICK:
668     case Instruction::IPUT_CHAR_QUICK:
669     case Instruction::IPUT_SHORT_QUICK:
670     case Instruction::IPUT_WIDE_QUICK:
671     case Instruction::IPUT_OBJECT_QUICK: {
672       uint16_t field_idx = method->GetIndexFromQuickening(throw_dex_pc);
673       ArtField* field = nullptr;
674       CHECK_NE(field_idx, DexFile::kDexNoIndex16);
675       field = Runtime::Current()->GetClassLinker()->ResolveField(
676           field_idx, method, /* is_static= */ false);
677       Thread::Current()->ClearException();  // Resolution may fail, ignore.
678       ThrowNullPointerExceptionForFieldAccess(field, /* is_read= */ false);
679       break;
680     }
681     case Instruction::AGET:
682     case Instruction::AGET_WIDE:
683     case Instruction::AGET_OBJECT:
684     case Instruction::AGET_BOOLEAN:
685     case Instruction::AGET_BYTE:
686     case Instruction::AGET_CHAR:
687     case Instruction::AGET_SHORT:
688       ThrowException("Ljava/lang/NullPointerException;", nullptr,
689                      "Attempt to read from null array");
690       break;
691     case Instruction::APUT:
692     case Instruction::APUT_WIDE:
693     case Instruction::APUT_OBJECT:
694     case Instruction::APUT_BOOLEAN:
695     case Instruction::APUT_BYTE:
696     case Instruction::APUT_CHAR:
697     case Instruction::APUT_SHORT:
698       ThrowException("Ljava/lang/NullPointerException;", nullptr,
699                      "Attempt to write to null array");
700       break;
701     case Instruction::ARRAY_LENGTH:
702       ThrowException("Ljava/lang/NullPointerException;", nullptr,
703                      "Attempt to get length of null array");
704       break;
705     case Instruction::FILL_ARRAY_DATA: {
706       ThrowException("Ljava/lang/NullPointerException;", nullptr,
707                      "Attempt to write to null array");
708       break;
709     }
710     case Instruction::MONITOR_ENTER:
711     case Instruction::MONITOR_EXIT: {
712       ThrowException("Ljava/lang/NullPointerException;", nullptr,
713                      "Attempt to do a synchronize operation on a null object");
714       break;
715     }
716     default: {
717       const DexFile* dex_file = method->GetDexFile();
718       LOG(FATAL) << "NullPointerException at an unexpected instruction: "
719                  << instr.DumpString(dex_file)
720                  << " in "
721                  << method->PrettyMethod();
722       UNREACHABLE();
723     }
724   }
725 }
726 
ThrowNullPointerException(const char * msg)727 void ThrowNullPointerException(const char* msg) {
728   ThrowException("Ljava/lang/NullPointerException;", nullptr, msg);
729 }
730 
731 // ReadOnlyBufferException
732 
ThrowReadOnlyBufferException()733 void ThrowReadOnlyBufferException() {
734   Thread::Current()->ThrowNewException("Ljava/nio/ReadOnlyBufferException;", nullptr);
735 }
736 
737 // RuntimeException
738 
ThrowRuntimeException(const char * fmt,...)739 void ThrowRuntimeException(const char* fmt, ...) {
740   va_list args;
741   va_start(args, fmt);
742   ThrowException("Ljava/lang/RuntimeException;", nullptr, fmt, &args);
743   va_end(args);
744 }
745 
746 // SecurityException
747 
ThrowSecurityException(const char * fmt,...)748 void ThrowSecurityException(const char* fmt, ...) {
749   va_list args;
750   va_start(args, fmt);
751   ThrowException("Ljava/lang/SecurityException;", nullptr, fmt, &args);
752   va_end(args);
753 }
754 
755 // Stack overflow.
756 
ThrowStackOverflowError(Thread * self)757 void ThrowStackOverflowError(Thread* self) {
758   if (self->IsHandlingStackOverflow()) {
759     LOG(ERROR) << "Recursive stack overflow.";
760     // We don't fail here because SetStackEndForStackOverflow will print better diagnostics.
761   }
762 
763   self->SetStackEndForStackOverflow();  // Allow space on the stack for constructor to execute.
764   JNIEnvExt* env = self->GetJniEnv();
765   std::string msg("stack size ");
766   msg += PrettySize(self->GetStackSize());
767 
768   // Avoid running Java code for exception initialization.
769   // TODO: Checks to make this a bit less brittle.
770   //
771   // Note: this lambda ensures that the destruction of the ScopedLocalRefs will run in the extended
772   //       stack, which is important for modes with larger stack sizes (e.g., ASAN). Using a lambda
773   //       instead of a block simplifies the control flow.
774   auto create_and_throw = [&]() REQUIRES_SHARED(Locks::mutator_lock_) {
775     // Allocate an uninitialized object.
776     ScopedLocalRef<jobject> exc(env,
777                                 env->AllocObject(WellKnownClasses::java_lang_StackOverflowError));
778     if (exc == nullptr) {
779       LOG(WARNING) << "Could not allocate StackOverflowError object.";
780       return;
781     }
782 
783     // "Initialize".
784     // StackOverflowError -> VirtualMachineError -> Error -> Throwable -> Object.
785     // Only Throwable has "custom" fields:
786     //   String detailMessage.
787     //   Throwable cause (= this).
788     //   List<Throwable> suppressedExceptions (= Collections.emptyList()).
789     //   Object stackState;
790     //   StackTraceElement[] stackTrace;
791     // Only Throwable has a non-empty constructor:
792     //   this.stackTrace = EmptyArray.STACK_TRACE_ELEMENT;
793     //   fillInStackTrace();
794 
795     // detailMessage.
796     // TODO: Use String::FromModifiedUTF...?
797     ScopedLocalRef<jstring> s(env, env->NewStringUTF(msg.c_str()));
798     if (s == nullptr) {
799       LOG(WARNING) << "Could not throw new StackOverflowError because JNI NewStringUTF failed.";
800       return;
801     }
802 
803     env->SetObjectField(exc.get(), WellKnownClasses::java_lang_Throwable_detailMessage, s.get());
804 
805     // cause.
806     env->SetObjectField(exc.get(), WellKnownClasses::java_lang_Throwable_cause, exc.get());
807 
808     // suppressedExceptions.
809     ScopedLocalRef<jobject> emptylist(env, env->GetStaticObjectField(
810         WellKnownClasses::java_util_Collections,
811         WellKnownClasses::java_util_Collections_EMPTY_LIST));
812     CHECK(emptylist != nullptr);
813     env->SetObjectField(exc.get(),
814                         WellKnownClasses::java_lang_Throwable_suppressedExceptions,
815                         emptylist.get());
816 
817     // stackState is set as result of fillInStackTrace. fillInStackTrace calls
818     // nativeFillInStackTrace.
819     ScopedLocalRef<jobject> stack_state_val(env, nullptr);
820     {
821       ScopedObjectAccessUnchecked soa(env);  // TODO: Is this necessary?
822       stack_state_val.reset(soa.Self()->CreateInternalStackTrace<false>(soa));
823     }
824     if (stack_state_val != nullptr) {
825       env->SetObjectField(exc.get(),
826                           WellKnownClasses::java_lang_Throwable_stackState,
827                           stack_state_val.get());
828 
829       // stackTrace.
830       ScopedLocalRef<jobject> stack_trace_elem(env, env->GetStaticObjectField(
831           WellKnownClasses::libcore_util_EmptyArray,
832           WellKnownClasses::libcore_util_EmptyArray_STACK_TRACE_ELEMENT));
833       env->SetObjectField(exc.get(),
834                           WellKnownClasses::java_lang_Throwable_stackTrace,
835                           stack_trace_elem.get());
836     } else {
837       LOG(WARNING) << "Could not create stack trace.";
838       // Note: we'll create an exception without stack state, which is valid.
839     }
840 
841     // Throw the exception.
842     self->SetException(self->DecodeJObject(exc.get())->AsThrowable());
843   };
844   create_and_throw();
845   CHECK(self->IsExceptionPending());
846 
847   bool explicit_overflow_check = Runtime::Current()->ExplicitStackOverflowChecks();
848   self->ResetDefaultStackEnd();  // Return to default stack size.
849 
850   // And restore protection if implicit checks are on.
851   if (!explicit_overflow_check) {
852     self->ProtectStack();
853   }
854 }
855 
856 // StringIndexOutOfBoundsException
857 
ThrowStringIndexOutOfBoundsException(int index,int length)858 void ThrowStringIndexOutOfBoundsException(int index, int length) {
859   ThrowException("Ljava/lang/StringIndexOutOfBoundsException;", nullptr,
860                  StringPrintf("length=%d; index=%d", length, index).c_str());
861 }
862 
863 // UnsupportedOperationException
864 
ThrowUnsupportedOperationException()865 void ThrowUnsupportedOperationException() {
866   ThrowException("Ljava/lang/UnsupportedOperationException;");
867 }
868 
869 // VerifyError
870 
ThrowVerifyError(ObjPtr<mirror::Class> referrer,const char * fmt,...)871 void ThrowVerifyError(ObjPtr<mirror::Class> referrer, const char* fmt, ...) {
872   va_list args;
873   va_start(args, fmt);
874   ThrowException("Ljava/lang/VerifyError;", referrer, fmt, &args);
875   va_end(args);
876 }
877 
878 // WrongMethodTypeException
879 
ThrowWrongMethodTypeException(ObjPtr<mirror::MethodType> expected_type,ObjPtr<mirror::MethodType> actual_type)880 void ThrowWrongMethodTypeException(ObjPtr<mirror::MethodType> expected_type,
881                                    ObjPtr<mirror::MethodType> actual_type) {
882   ThrowWrongMethodTypeException(expected_type->PrettyDescriptor(), actual_type->PrettyDescriptor());
883 }
884 
ThrowWrongMethodTypeException(const std::string & expected_descriptor,const std::string & actual_descriptor)885 void ThrowWrongMethodTypeException(const std::string& expected_descriptor,
886                                    const std::string& actual_descriptor) {
887   std::ostringstream msg;
888   msg << "Expected " << expected_descriptor << " but was " << actual_descriptor;
889   ThrowException("Ljava/lang/invoke/WrongMethodTypeException;",  nullptr, msg.str().c_str());
890 }
891 
892 }  // namespace art
893