1 /*
2  * Copyright (C) 2011 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "class_verifier.h"
18 
19 #include <android-base/logging.h>
20 #include <android-base/stringprintf.h>
21 
22 #include "art_method-inl.h"
23 #include "base/enums.h"
24 #include "base/locks.h"
25 #include "base/logging.h"
26 #include "base/systrace.h"
27 #include "base/utils.h"
28 #include "class_linker.h"
29 #include "compiler_callbacks.h"
30 #include "dex/class_accessor-inl.h"
31 #include "dex/class_reference.h"
32 #include "dex/descriptors_names.h"
33 #include "dex/dex_file-inl.h"
34 #include "handle.h"
35 #include "handle_scope-inl.h"
36 #include "method_verifier-inl.h"
37 #include "mirror/class-inl.h"
38 #include "mirror/dex_cache.h"
39 #include "runtime.h"
40 #include "thread.h"
41 #include "verifier/method_verifier.h"
42 #include "verifier/reg_type_cache.h"
43 
44 namespace art {
45 namespace verifier {
46 
47 using android::base::StringPrintf;
48 
49 // We print a warning blurb about "dx --no-optimize" when we find monitor-locking issues. Make
50 // sure we only print this once.
51 static bool gPrintedDxMonitorText = false;
52 
53 class StandardVerifyCallback : public VerifierCallback {
54  public:
SetDontCompile(ArtMethod * m,bool value)55   void SetDontCompile(ArtMethod* m, bool value) override REQUIRES_SHARED(Locks::mutator_lock_) {
56     if (value) {
57       m->SetDontCompile();
58     }
59   }
SetMustCountLocks(ArtMethod * m,bool value)60   void SetMustCountLocks(ArtMethod* m, bool value) override REQUIRES_SHARED(Locks::mutator_lock_) {
61     if (value) {
62       m->SetMustCountLocks();
63     }
64   }
65 };
66 
ReverifyClass(Thread * self,ObjPtr<mirror::Class> klass,HardFailLogMode log_level,uint32_t api_level,std::string * error)67 FailureKind ClassVerifier::ReverifyClass(Thread* self,
68                                          ObjPtr<mirror::Class> klass,
69                                          HardFailLogMode log_level,
70                                          uint32_t api_level,
71                                          std::string* error) {
72   DCHECK(!Runtime::Current()->IsAotCompiler());
73   StackHandleScope<1> hs(self);
74   Handle<mirror::Class> h_klass(hs.NewHandle(klass));
75   // We don't want to mess with these while other mutators are possibly looking at them. Instead we
76   // will wait until we can update them while everything is suspended.
77   class DelayedVerifyCallback : public VerifierCallback {
78    public:
79     void SetDontCompile(ArtMethod* m, bool value) override REQUIRES_SHARED(Locks::mutator_lock_) {
80       dont_compiles_.push_back({ m, value });
81     }
82     void SetMustCountLocks(ArtMethod* m, bool value) override
83         REQUIRES_SHARED(Locks::mutator_lock_) {
84       count_locks_.push_back({ m, value });
85     }
86     void UpdateFlags(bool skip_access_checks) REQUIRES(Locks::mutator_lock_) {
87       for (auto it : count_locks_) {
88         VLOG(verifier_debug) << "Setting " << it.first->PrettyMethod() << " count locks to "
89                              << it.second;
90         if (it.second) {
91           it.first->SetMustCountLocks();
92         } else {
93           it.first->ClearMustCountLocks();
94         }
95         if (skip_access_checks && it.first->IsInvokable() && !it.first->IsNative()) {
96           it.first->SetSkipAccessChecks();
97         }
98       }
99       for (auto it : dont_compiles_) {
100         VLOG(verifier_debug) << "Setting " << it.first->PrettyMethod() << " dont-compile to "
101                              << it.second;
102         if (it.second) {
103           it.first->SetDontCompile();
104         } else {
105           it.first->ClearDontCompile();
106         }
107       }
108     }
109 
110    private:
111     std::vector<std::pair<ArtMethod*, bool>> dont_compiles_;
112     std::vector<std::pair<ArtMethod*, bool>> count_locks_;
113   };
114   DelayedVerifyCallback dvc;
115   FailureKind res = CommonVerifyClass(self,
116                                       h_klass.Get(),
117                                       /*callbacks=*/nullptr,
118                                       &dvc,
119                                       /*allow_soft_failures=*/false,
120                                       log_level,
121                                       api_level,
122                                       error);
123   DCHECK_NE(res, FailureKind::kHardFailure);
124   ScopedThreadSuspension sts(Thread::Current(), ThreadState::kSuspended);
125   ScopedSuspendAll ssa("Update method flags for reverify");
126   dvc.UpdateFlags(res == FailureKind::kNoFailure);
127   return res;
128 }
129 
VerifyClass(Thread * self,ObjPtr<mirror::Class> klass,CompilerCallbacks * callbacks,bool allow_soft_failures,HardFailLogMode log_level,uint32_t api_level,std::string * error)130 FailureKind ClassVerifier::VerifyClass(Thread* self,
131                                        ObjPtr<mirror::Class> klass,
132                                        CompilerCallbacks* callbacks,
133                                        bool allow_soft_failures,
134                                        HardFailLogMode log_level,
135                                        uint32_t api_level,
136                                        std::string* error) {
137   if (klass->IsVerified()) {
138     return FailureKind::kNoFailure;
139   }
140   StandardVerifyCallback svc;
141   return CommonVerifyClass(self,
142                            klass,
143                            callbacks,
144                            &svc,
145                            allow_soft_failures,
146                            log_level,
147                            api_level,
148                            error);
149 }
150 
CommonVerifyClass(Thread * self,ObjPtr<mirror::Class> klass,CompilerCallbacks * callbacks,VerifierCallback * verifier_callback,bool allow_soft_failures,HardFailLogMode log_level,uint32_t api_level,std::string * error)151 FailureKind ClassVerifier::CommonVerifyClass(Thread* self,
152                                              ObjPtr<mirror::Class> klass,
153                                              CompilerCallbacks* callbacks,
154                                              VerifierCallback* verifier_callback,
155                                              bool allow_soft_failures,
156                                              HardFailLogMode log_level,
157                                              uint32_t api_level,
158                                              std::string* error) {
159   bool early_failure = false;
160   std::string failure_message;
161   const DexFile& dex_file = klass->GetDexFile();
162   const dex::ClassDef* class_def = klass->GetClassDef();
163   ObjPtr<mirror::Class> super = klass->GetSuperClass();
164   std::string temp;
165   if (super == nullptr && strcmp("Ljava/lang/Object;", klass->GetDescriptor(&temp)) != 0) {
166     early_failure = true;
167     failure_message = " that has no super class";
168   } else if (super != nullptr && super->IsFinal()) {
169     early_failure = true;
170     failure_message = " that attempts to sub-class final class " + super->PrettyDescriptor();
171   } else if (class_def == nullptr) {
172     early_failure = true;
173     failure_message = " that isn't present in dex file " + dex_file.GetLocation();
174   }
175   if (early_failure) {
176     *error = "Verifier rejected class " + klass->PrettyDescriptor() + failure_message;
177     if (callbacks != nullptr) {
178       ClassReference ref(&dex_file, klass->GetDexClassDefIndex());
179       callbacks->ClassRejected(ref);
180     }
181     return FailureKind::kHardFailure;
182   }
183   StackHandleScope<2> hs(self);
184   Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
185   Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
186   return VerifyClass(self,
187                      &dex_file,
188                      dex_cache,
189                      class_loader,
190                      *class_def,
191                      callbacks,
192                      verifier_callback,
193                      allow_soft_failures,
194                      log_level,
195                      api_level,
196                      error);
197 }
198 
199 
VerifyClass(Thread * self,const DexFile * dex_file,Handle<mirror::DexCache> dex_cache,Handle<mirror::ClassLoader> class_loader,const dex::ClassDef & class_def,CompilerCallbacks * callbacks,bool allow_soft_failures,HardFailLogMode log_level,uint32_t api_level,std::string * error)200 FailureKind ClassVerifier::VerifyClass(Thread* self,
201                                        const DexFile* dex_file,
202                                        Handle<mirror::DexCache> dex_cache,
203                                        Handle<mirror::ClassLoader> class_loader,
204                                        const dex::ClassDef& class_def,
205                                        CompilerCallbacks* callbacks,
206                                        bool allow_soft_failures,
207                                        HardFailLogMode log_level,
208                                        uint32_t api_level,
209                                        std::string* error) {
210   StandardVerifyCallback svc;
211   return VerifyClass(self,
212                      dex_file,
213                      dex_cache,
214                      class_loader,
215                      class_def,
216                      callbacks,
217                      &svc,
218                      allow_soft_failures,
219                      log_level,
220                      api_level,
221                      error);
222 }
223 
VerifyClass(Thread * self,const DexFile * dex_file,Handle<mirror::DexCache> dex_cache,Handle<mirror::ClassLoader> class_loader,const dex::ClassDef & class_def,CompilerCallbacks * callbacks,VerifierCallback * verifier_callback,bool allow_soft_failures,HardFailLogMode log_level,uint32_t api_level,std::string * error)224 FailureKind ClassVerifier::VerifyClass(Thread* self,
225                                        const DexFile* dex_file,
226                                        Handle<mirror::DexCache> dex_cache,
227                                        Handle<mirror::ClassLoader> class_loader,
228                                        const dex::ClassDef& class_def,
229                                        CompilerCallbacks* callbacks,
230                                        VerifierCallback* verifier_callback,
231                                        bool allow_soft_failures,
232                                        HardFailLogMode log_level,
233                                        uint32_t api_level,
234                                        std::string* error) {
235   // A class must not be abstract and final.
236   if ((class_def.access_flags_ & (kAccAbstract | kAccFinal)) == (kAccAbstract | kAccFinal)) {
237     *error = "Verifier rejected class ";
238     *error += PrettyDescriptor(dex_file->GetClassDescriptor(class_def));
239     *error += ": class is abstract and final.";
240     return FailureKind::kHardFailure;
241   }
242 
243   ClassAccessor accessor(*dex_file, class_def);
244   SCOPED_TRACE << "VerifyClass " << PrettyDescriptor(accessor.GetDescriptor());
245   uint64_t start_ns = 0u;
246   if (VLOG_IS_ON(verifier)) {
247     start_ns = NanoTime();
248   }
249 
250   int64_t previous_method_idx[2] = { -1, -1 };
251   MethodVerifier::FailureData failure_data;
252   ClassLinker* const linker = Runtime::Current()->GetClassLinker();
253 
254   for (const ClassAccessor::Method& method : accessor.GetMethods()) {
255     int64_t* previous_idx = &previous_method_idx[method.IsStaticOrDirect() ? 0u : 1u];
256     self->AllowThreadSuspension();
257     const uint32_t method_idx = method.GetIndex();
258     if (method_idx == *previous_idx) {
259       // smali can create dex files with two encoded_methods sharing the same method_idx
260       // http://code.google.com/p/smali/issues/detail?id=119
261       continue;
262     }
263     *previous_idx = method_idx;
264     const InvokeType type = method.GetInvokeType(class_def.access_flags_);
265     ArtMethod* resolved_method = linker->ResolveMethod<ClassLinker::ResolveMode::kNoChecks>(
266         method_idx, dex_cache, class_loader, /* referrer= */ nullptr, type);
267     if (resolved_method == nullptr) {
268       DCHECK(self->IsExceptionPending());
269       // We couldn't resolve the method, but continue regardless.
270       self->ClearException();
271     } else {
272       DCHECK(resolved_method->GetDeclaringClassUnchecked() != nullptr) << type;
273     }
274     std::string hard_failure_msg;
275     MethodVerifier::FailureData result =
276         MethodVerifier::VerifyMethod(self,
277                                      linker,
278                                      Runtime::Current()->GetArenaPool(),
279                                      method_idx,
280                                      dex_file,
281                                      dex_cache,
282                                      class_loader,
283                                      class_def,
284                                      method.GetCodeItem(),
285                                      resolved_method,
286                                      method.GetAccessFlags(),
287                                      callbacks,
288                                      verifier_callback,
289                                      allow_soft_failures,
290                                      log_level,
291                                      /*need_precise_constants=*/ false,
292                                      api_level,
293                                      Runtime::Current()->IsAotCompiler(),
294                                      &hard_failure_msg);
295     if (result.kind == FailureKind::kHardFailure) {
296       if (failure_data.kind == FailureKind::kHardFailure) {
297         // If we logged an error before, we need a newline.
298         *error += "\n";
299       } else {
300         // If we didn't log a hard failure before, print the header of the message.
301         *error += "Verifier rejected class ";
302         *error += PrettyDescriptor(dex_file->GetClassDescriptor(class_def));
303         *error += ":";
304       }
305       *error += " ";
306       *error += hard_failure_msg;
307     }
308     failure_data.Merge(result);
309   }
310   VLOG(verifier) << "VerifyClass took " << PrettyDuration(NanoTime() - start_ns)
311                  << ", class: " << PrettyDescriptor(dex_file->GetClassDescriptor(class_def));
312 
313   if (failure_data.kind == FailureKind::kNoFailure) {
314     return FailureKind::kNoFailure;
315   } else {
316     if ((failure_data.types & VERIFY_ERROR_LOCKING) != 0) {
317       // Print a warning about expected slow-down. Use a string temporary to print one contiguous
318       // warning.
319       std::string tmp =
320           StringPrintf("Class %s failed lock verification and will run slower.",
321                        PrettyDescriptor(accessor.GetDescriptor()).c_str());
322       if (!gPrintedDxMonitorText) {
323         tmp = tmp + "\nCommon causes for lock verification issues are non-optimized dex code\n"
324                     "and incorrect proguard optimizations.";
325         gPrintedDxMonitorText = true;
326       }
327       LOG(WARNING) << tmp;
328     }
329     return failure_data.kind;
330   }
331 }
332 
Init(ClassLinker * class_linker)333 void ClassVerifier::Init(ClassLinker* class_linker) {
334   MethodVerifier::Init(class_linker);
335 }
336 
Shutdown()337 void ClassVerifier::Shutdown() {
338   MethodVerifier::Shutdown();
339 }
340 
VisitStaticRoots(RootVisitor * visitor)341 void ClassVerifier::VisitStaticRoots(RootVisitor* visitor) {
342   MethodVerifier::VisitStaticRoots(visitor);
343 }
344 
345 }  // namespace verifier
346 }  // namespace art
347