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