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 
246   int64_t previous_method_idx[2] = { -1, -1 };
247   MethodVerifier::FailureData failure_data;
248   ClassLinker* const linker = Runtime::Current()->GetClassLinker();
249 
250   for (const ClassAccessor::Method& method : accessor.GetMethods()) {
251     int64_t* previous_idx = &previous_method_idx[method.IsStaticOrDirect() ? 0u : 1u];
252     self->AllowThreadSuspension();
253     const uint32_t method_idx = method.GetIndex();
254     if (method_idx == *previous_idx) {
255       // smali can create dex files with two encoded_methods sharing the same method_idx
256       // http://code.google.com/p/smali/issues/detail?id=119
257       continue;
258     }
259     *previous_idx = method_idx;
260     const InvokeType type = method.GetInvokeType(class_def.access_flags_);
261     ArtMethod* resolved_method = linker->ResolveMethod<ClassLinker::ResolveMode::kNoChecks>(
262         method_idx, dex_cache, class_loader, /* referrer= */ nullptr, type);
263     if (resolved_method == nullptr) {
264       DCHECK(self->IsExceptionPending());
265       // We couldn't resolve the method, but continue regardless.
266       self->ClearException();
267     } else {
268       DCHECK(resolved_method->GetDeclaringClassUnchecked() != nullptr) << type;
269     }
270     std::string hard_failure_msg;
271     MethodVerifier::FailureData result =
272         MethodVerifier::VerifyMethod(self,
273                                      linker,
274                                      Runtime::Current()->GetArenaPool(),
275                                      method_idx,
276                                      dex_file,
277                                      dex_cache,
278                                      class_loader,
279                                      class_def,
280                                      method.GetCodeItem(),
281                                      resolved_method,
282                                      method.GetAccessFlags(),
283                                      callbacks,
284                                      verifier_callback,
285                                      allow_soft_failures,
286                                      log_level,
287                                      /*need_precise_constants=*/ false,
288                                      api_level,
289                                      Runtime::Current()->IsAotCompiler(),
290                                      &hard_failure_msg);
291     if (result.kind == FailureKind::kHardFailure) {
292       if (failure_data.kind == FailureKind::kHardFailure) {
293         // If we logged an error before, we need a newline.
294         *error += "\n";
295       } else {
296         // If we didn't log a hard failure before, print the header of the message.
297         *error += "Verifier rejected class ";
298         *error += PrettyDescriptor(dex_file->GetClassDescriptor(class_def));
299         *error += ":";
300       }
301       *error += " ";
302       *error += hard_failure_msg;
303     }
304     failure_data.Merge(result);
305   }
306 
307   if (failure_data.kind == FailureKind::kNoFailure) {
308     return FailureKind::kNoFailure;
309   } else {
310     if ((failure_data.types & VERIFY_ERROR_LOCKING) != 0) {
311       // Print a warning about expected slow-down. Use a string temporary to print one contiguous
312       // warning.
313       std::string tmp =
314           StringPrintf("Class %s failed lock verification and will run slower.",
315                        PrettyDescriptor(accessor.GetDescriptor()).c_str());
316       if (!gPrintedDxMonitorText) {
317         tmp = tmp + "\nCommon causes for lock verification issues are non-optimized dex code\n"
318                     "and incorrect proguard optimizations.";
319         gPrintedDxMonitorText = true;
320       }
321       LOG(WARNING) << tmp;
322     }
323     return failure_data.kind;
324   }
325 }
326 
Init(ClassLinker * class_linker)327 void ClassVerifier::Init(ClassLinker* class_linker) {
328   MethodVerifier::Init(class_linker);
329 }
330 
Shutdown()331 void ClassVerifier::Shutdown() {
332   MethodVerifier::Shutdown();
333 }
334 
VisitStaticRoots(RootVisitor * visitor)335 void ClassVerifier::VisitStaticRoots(RootVisitor* visitor) {
336   MethodVerifier::VisitStaticRoots(visitor);
337 }
338 
339 }  // namespace verifier
340 }  // namespace art
341