1 /*
2  * Copyright (C) 2016 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 // Test is in compiler, as it uses compiler related code.
18 #include "verifier/verifier_deps.h"
19 
20 #include "art_method-inl.h"
21 #include "base/indenter.h"
22 #include "class_linker.h"
23 #include "common_compiler_driver_test.h"
24 #include "compiler_callbacks.h"
25 #include "dex/class_accessor-inl.h"
26 #include "dex/class_iterator.h"
27 #include "dex/dex_file-inl.h"
28 #include "dex/dex_file_types.h"
29 #include "dex/verification_results.h"
30 #include "dex/verified_method.h"
31 #include "driver/compiler_driver-inl.h"
32 #include "driver/compiler_options.h"
33 #include "handle_scope-inl.h"
34 #include "mirror/class_loader.h"
35 #include "runtime.h"
36 #include "scoped_thread_state_change-inl.h"
37 #include "thread.h"
38 #include "utils/atomic_dex_ref_map-inl.h"
39 #include "verifier/method_verifier-inl.h"
40 
41 namespace art {
42 namespace verifier {
43 
44 class VerifierDepsCompilerCallbacks : public CompilerCallbacks {
45  public:
VerifierDepsCompilerCallbacks()46   VerifierDepsCompilerCallbacks()
47       : CompilerCallbacks(CompilerCallbacks::CallbackMode::kCompileApp),
48         deps_(nullptr) {}
49 
MethodVerified(verifier::MethodVerifier * verifier ATTRIBUTE_UNUSED)50   void MethodVerified(verifier::MethodVerifier* verifier ATTRIBUTE_UNUSED) override {}
ClassRejected(ClassReference ref ATTRIBUTE_UNUSED)51   void ClassRejected(ClassReference ref ATTRIBUTE_UNUSED) override {}
52 
GetVerifierDeps() const53   verifier::VerifierDeps* GetVerifierDeps() const override { return deps_; }
SetVerifierDeps(verifier::VerifierDeps * deps)54   void SetVerifierDeps(verifier::VerifierDeps* deps) override { deps_ = deps; }
55 
56  private:
57   verifier::VerifierDeps* deps_;
58 };
59 
60 class VerifierDepsTest : public CommonCompilerDriverTest {
61  public:
SetUpRuntimeOptions(RuntimeOptions * options)62   void SetUpRuntimeOptions(RuntimeOptions* options) override {
63     CommonCompilerTest::SetUpRuntimeOptions(options);
64     callbacks_.reset(new VerifierDepsCompilerCallbacks());
65   }
66 
FindClassByName(ScopedObjectAccess & soa,const std::string & name)67   ObjPtr<mirror::Class> FindClassByName(ScopedObjectAccess& soa, const std::string& name)
68       REQUIRES_SHARED(Locks::mutator_lock_) {
69     StackHandleScope<1> hs(soa.Self());
70     Handle<mirror::ClassLoader> class_loader_handle(
71         hs.NewHandle(soa.Decode<mirror::ClassLoader>(class_loader_)));
72     ObjPtr<mirror::Class> klass =
73         class_linker_->FindClass(soa.Self(), name.c_str(), class_loader_handle);
74     if (klass == nullptr) {
75       DCHECK(soa.Self()->IsExceptionPending());
76       soa.Self()->ClearException();
77     }
78     return klass;
79   }
80 
SetupCompilerDriver()81   void SetupCompilerDriver() {
82     compiler_options_->image_type_ = CompilerOptions::ImageType::kNone;
83     compiler_driver_->InitializeThreadPools();
84   }
85 
VerifyWithCompilerDriver(verifier::VerifierDeps * verifier_deps)86   void VerifyWithCompilerDriver(verifier::VerifierDeps* verifier_deps) {
87     TimingLogger timings("Verify", false, false);
88     // The compiler driver handles the verifier deps in the callbacks, so
89     // remove what this class did for unit testing.
90     if (verifier_deps == nullptr) {
91       // Create some verifier deps by default if they are not already specified.
92       verifier_deps = new verifier::VerifierDeps(dex_files_);
93       verifier_deps_.reset(verifier_deps);
94     }
95     callbacks_->SetVerifierDeps(verifier_deps);
96     compiler_driver_->Verify(class_loader_, dex_files_, &timings, verification_results_.get());
97     callbacks_->SetVerifierDeps(nullptr);
98     // Clear entries in the verification results to avoid hitting a DCHECK that
99     // we always succeed inserting a new entry after verifying.
100     AtomicDexRefMap<MethodReference, const VerifiedMethod*>* map =
101         &verification_results_->atomic_verified_methods_;
102     map->Visit([](const DexFileReference& ref ATTRIBUTE_UNUSED, const VerifiedMethod* method) {
103       delete method;
104     });
105     map->ClearEntries();
106   }
107 
SetVerifierDeps(const std::vector<const DexFile * > & dex_files)108   void SetVerifierDeps(const std::vector<const DexFile*>& dex_files) {
109     verifier_deps_.reset(new verifier::VerifierDeps(dex_files));
110     VerifierDepsCompilerCallbacks* callbacks =
111         reinterpret_cast<VerifierDepsCompilerCallbacks*>(callbacks_.get());
112     callbacks->SetVerifierDeps(verifier_deps_.get());
113   }
114 
LoadDexFile(ScopedObjectAccess & soa,const char * name1,const char * name2=nullptr)115   void LoadDexFile(ScopedObjectAccess& soa, const char* name1, const char* name2 = nullptr)
116       REQUIRES_SHARED(Locks::mutator_lock_) {
117     class_loader_ = (name2 == nullptr) ? LoadDex(name1) : LoadMultiDex(name1, name2);
118     dex_files_ = GetDexFiles(class_loader_);
119     primary_dex_file_ = dex_files_.front();
120 
121     SetVerifierDeps(dex_files_);
122     StackHandleScope<1> hs(soa.Self());
123     Handle<mirror::ClassLoader> loader =
124         hs.NewHandle(soa.Decode<mirror::ClassLoader>(class_loader_));
125     for (const DexFile* dex_file : dex_files_) {
126       class_linker_->RegisterDexFile(*dex_file, loader.Get());
127     }
128     for (const DexFile* dex_file : dex_files_) {
129       verification_results_->AddDexFile(dex_file);
130     }
131     SetDexFilesForOatFile(dex_files_);
132   }
133 
LoadDexFile(ScopedObjectAccess & soa)134   void LoadDexFile(ScopedObjectAccess& soa) REQUIRES_SHARED(Locks::mutator_lock_) {
135     LoadDexFile(soa, "VerifierDeps");
136     CHECK_EQ(dex_files_.size(), 1u);
137     klass_Main_ = FindClassByName(soa, "LMain;");
138     CHECK(klass_Main_ != nullptr);
139   }
140 
VerifyMethod(const std::string & method_name)141   bool VerifyMethod(const std::string& method_name) {
142     ScopedObjectAccess soa(Thread::Current());
143     LoadDexFile(soa);
144 
145     StackHandleScope<2> hs(soa.Self());
146     Handle<mirror::ClassLoader> class_loader_handle(
147         hs.NewHandle(soa.Decode<mirror::ClassLoader>(class_loader_)));
148     Handle<mirror::DexCache> dex_cache_handle(hs.NewHandle(klass_Main_->GetDexCache()));
149 
150     const dex::ClassDef* class_def = klass_Main_->GetClassDef();
151     ClassAccessor accessor(*primary_dex_file_, *class_def);
152 
153     bool has_failures = true;
154     bool found_method = false;
155 
156     for (const ClassAccessor::Method& method : accessor.GetMethods()) {
157       ArtMethod* resolved_method =
158           class_linker_->ResolveMethod<ClassLinker::ResolveMode::kNoChecks>(
159               method.GetIndex(),
160               dex_cache_handle,
161               class_loader_handle,
162               /* referrer= */ nullptr,
163               method.GetInvokeType(class_def->access_flags_));
164       CHECK(resolved_method != nullptr);
165       if (method_name == resolved_method->GetName()) {
166         soa.Self()->SetVerifierDeps(callbacks_->GetVerifierDeps());
167         std::unique_ptr<MethodVerifier> verifier(
168             MethodVerifier::CreateVerifier(soa.Self(),
169                                            primary_dex_file_,
170                                            dex_cache_handle,
171                                            class_loader_handle,
172                                            *class_def,
173                                            method.GetCodeItem(),
174                                            method.GetIndex(),
175                                            resolved_method,
176                                            method.GetAccessFlags(),
177                                            /* can_load_classes= */ true,
178                                            /* allow_soft_failures= */ true,
179                                            /* need_precise_constants= */ true,
180                                            /* verify to dump */ false,
181                                            /* allow_thread_suspension= */ true,
182                                            /* api_level= */ 0));
183         verifier->Verify();
184         soa.Self()->SetVerifierDeps(nullptr);
185         has_failures = verifier->HasFailures();
186         found_method = true;
187       }
188     }
189     CHECK(found_method) << "Expected to find method " << method_name;
190     return !has_failures;
191   }
192 
VerifyDexFile(const char * multidex=nullptr)193   void VerifyDexFile(const char* multidex = nullptr) {
194     {
195       ScopedObjectAccess soa(Thread::Current());
196       LoadDexFile(soa, "VerifierDeps", multidex);
197     }
198     SetupCompilerDriver();
199     VerifyWithCompilerDriver(/* verifier_deps= */ nullptr);
200   }
201 
TestAssignabilityRecording(const std::string & dst,const std::string & src,bool is_strict,bool is_assignable)202   bool TestAssignabilityRecording(const std::string& dst,
203                                   const std::string& src,
204                                   bool is_strict,
205                                   bool is_assignable) {
206     ScopedObjectAccess soa(Thread::Current());
207     LoadDexFile(soa);
208     StackHandleScope<1> hs(soa.Self());
209     Handle<mirror::Class> klass_dst = hs.NewHandle(FindClassByName(soa, dst));
210     DCHECK(klass_dst != nullptr) << dst;
211     ObjPtr<mirror::Class> klass_src = FindClassByName(soa, src);
212     DCHECK(klass_src != nullptr) << src;
213     verifier_deps_->AddAssignability(*primary_dex_file_,
214                                      klass_dst.Get(),
215                                      klass_src,
216                                      is_strict,
217                                      is_assignable);
218     return true;
219   }
220 
221   // Check that the status of classes in `class_loader_` match the
222   // expected status in `deps`.
VerifyClassStatus(const verifier::VerifierDeps & deps)223   void VerifyClassStatus(const verifier::VerifierDeps& deps) {
224     ScopedObjectAccess soa(Thread::Current());
225     StackHandleScope<2> hs(soa.Self());
226     Handle<mirror::ClassLoader> class_loader_handle(
227         hs.NewHandle(soa.Decode<mirror::ClassLoader>(class_loader_)));
228     MutableHandle<mirror::Class> cls(hs.NewHandle<mirror::Class>(nullptr));
229     for (const DexFile* dex_file : dex_files_) {
230       const std::vector<bool>& verified_classes = deps.GetVerifiedClasses(*dex_file);
231       ASSERT_EQ(verified_classes.size(), dex_file->NumClassDefs());
232       for (uint32_t i = 0; i < dex_file->NumClassDefs(); ++i) {
233         const dex::ClassDef& class_def = dex_file->GetClassDef(i);
234         const char* descriptor = dex_file->GetClassDescriptor(class_def);
235         cls.Assign(class_linker_->FindClass(soa.Self(), descriptor, class_loader_handle));
236         if (cls == nullptr) {
237           CHECK(soa.Self()->IsExceptionPending());
238           soa.Self()->ClearException();
239         } else if (&cls->GetDexFile() != dex_file) {
240           // Ignore classes from different dex files.
241         } else if (verified_classes[i]) {
242           ASSERT_EQ(cls->GetStatus(), ClassStatus::kVerified);
243         } else {
244           ASSERT_LT(cls->GetStatus(), ClassStatus::kVerified);
245         }
246       }
247     }
248   }
249 
GetClassDefIndex(const std::string & cls,const DexFile & dex_file)250   uint16_t GetClassDefIndex(const std::string& cls, const DexFile& dex_file) {
251     const dex::TypeId* type_id = dex_file.FindTypeId(cls.c_str());
252     DCHECK(type_id != nullptr);
253     dex::TypeIndex type_idx = dex_file.GetIndexForTypeId(*type_id);
254     const dex::ClassDef* class_def = dex_file.FindClassDef(type_idx);
255     DCHECK(class_def != nullptr);
256     return dex_file.GetIndexForClassDef(*class_def);
257   }
258 
HasUnverifiedClass(const std::string & cls)259   bool HasUnverifiedClass(const std::string& cls) {
260     return HasUnverifiedClass(cls, *primary_dex_file_);
261   }
262 
HasUnverifiedClass(const std::string & cls,const DexFile & dex_file)263   bool HasUnverifiedClass(const std::string& cls, const DexFile& dex_file) {
264     uint16_t class_def_idx = GetClassDefIndex(cls, dex_file);
265     return !verifier_deps_->GetVerifiedClasses(dex_file)[class_def_idx];
266   }
267 
HasRedefinedClass(const std::string & cls)268   bool HasRedefinedClass(const std::string& cls) {
269     uint16_t class_def_idx = GetClassDefIndex(cls, *primary_dex_file_);
270     return verifier_deps_->GetRedefinedClasses(*primary_dex_file_)[class_def_idx];
271   }
272 
273   // Iterates over all assignability records and tries to find an entry which
274   // matches the expected destination/source pair.
HasAssignable(const std::string & expected_destination,const std::string & expected_source,bool expected_is_assignable)275   bool HasAssignable(const std::string& expected_destination,
276                      const std::string& expected_source,
277                      bool expected_is_assignable) {
278     for (auto& dex_dep : verifier_deps_->dex_deps_) {
279       const DexFile& dex_file = *dex_dep.first;
280       auto& storage = expected_is_assignable ? dex_dep.second->assignable_types_
281                                              : dex_dep.second->unassignable_types_;
282       for (auto& entry : storage) {
283         std::string actual_destination =
284             verifier_deps_->GetStringFromId(dex_file, entry.GetDestination());
285         std::string actual_source = verifier_deps_->GetStringFromId(dex_file, entry.GetSource());
286         if ((expected_destination == actual_destination) && (expected_source == actual_source)) {
287           return true;
288         }
289       }
290     }
291     return false;
292   }
293 
294   // Iterates over all class resolution records, finds an entry which matches
295   // the given class descriptor and tests its properties.
HasClass(const std::string & expected_klass,bool expected_resolved,const std::string & expected_access_flags="")296   bool HasClass(const std::string& expected_klass,
297                 bool expected_resolved,
298                 const std::string& expected_access_flags = "") {
299     for (auto& dex_dep : verifier_deps_->dex_deps_) {
300       for (auto& entry : dex_dep.second->classes_) {
301         if (expected_resolved != entry.IsResolved()) {
302           continue;
303         }
304 
305         std::string actual_klass = dex_dep.first->StringByTypeIdx(entry.GetDexTypeIndex());
306         if (expected_klass != actual_klass) {
307           continue;
308         }
309 
310         if (expected_resolved) {
311           // Test access flags. Note that PrettyJavaAccessFlags always appends
312           // a space after the modifiers. Add it to the expected access flags.
313           std::string actual_access_flags = PrettyJavaAccessFlags(entry.GetAccessFlags());
314           if (expected_access_flags + " " != actual_access_flags) {
315             continue;
316           }
317         }
318 
319         return true;
320       }
321     }
322     return false;
323   }
324 
325   // Iterates over all field resolution records, finds an entry which matches
326   // the given field class+name+type and tests its properties.
HasField(const std::string & expected_klass,const std::string & expected_name,const std::string & expected_type,bool expected_resolved,const std::string & expected_access_flags="",const std::string & expected_decl_klass="")327   bool HasField(const std::string& expected_klass,
328                 const std::string& expected_name,
329                 const std::string& expected_type,
330                 bool expected_resolved,
331                 const std::string& expected_access_flags = "",
332                 const std::string& expected_decl_klass = "") {
333     for (auto& dex_dep : verifier_deps_->dex_deps_) {
334       for (auto& entry : dex_dep.second->fields_) {
335         if (expected_resolved != entry.IsResolved()) {
336           continue;
337         }
338 
339         const dex::FieldId& field_id = dex_dep.first->GetFieldId(entry.GetDexFieldIndex());
340 
341         std::string actual_klass = dex_dep.first->StringByTypeIdx(field_id.class_idx_);
342         if (expected_klass != actual_klass) {
343           continue;
344         }
345 
346         std::string actual_name = dex_dep.first->StringDataByIdx(field_id.name_idx_);
347         if (expected_name != actual_name) {
348           continue;
349         }
350 
351         std::string actual_type = dex_dep.first->StringByTypeIdx(field_id.type_idx_);
352         if (expected_type != actual_type) {
353           continue;
354         }
355 
356         if (expected_resolved) {
357           // Test access flags. Note that PrettyJavaAccessFlags always appends
358           // a space after the modifiers. Add it to the expected access flags.
359           std::string actual_access_flags = PrettyJavaAccessFlags(entry.GetAccessFlags());
360           if (expected_access_flags + " " != actual_access_flags) {
361             continue;
362           }
363 
364           std::string actual_decl_klass = verifier_deps_->GetStringFromId(
365               *dex_dep.first, entry.GetDeclaringClassIndex());
366           if (expected_decl_klass != actual_decl_klass) {
367             continue;
368           }
369         }
370 
371         return true;
372       }
373     }
374     return false;
375   }
376 
377   // Iterates over all method resolution records, finds an entry which matches
378   // the given field kind+class+name+signature and tests its properties.
HasMethod(const std::string & expected_klass,const std::string & expected_name,const std::string & expected_signature,bool expect_resolved,const std::string & expected_access_flags="",const std::string & expected_decl_klass="")379   bool HasMethod(const std::string& expected_klass,
380                  const std::string& expected_name,
381                  const std::string& expected_signature,
382                  bool expect_resolved,
383                  const std::string& expected_access_flags = "",
384                  const std::string& expected_decl_klass = "") {
385     for (auto& dex_dep : verifier_deps_->dex_deps_) {
386       for (const VerifierDeps::MethodResolution& entry : dex_dep.second->methods_) {
387         if (expect_resolved != entry.IsResolved()) {
388           continue;
389         }
390 
391         const dex::MethodId& method_id = dex_dep.first->GetMethodId(entry.GetDexMethodIndex());
392 
393         std::string actual_klass = dex_dep.first->StringByTypeIdx(method_id.class_idx_);
394         if (expected_klass != actual_klass) {
395           continue;
396         }
397 
398         std::string actual_name = dex_dep.first->StringDataByIdx(method_id.name_idx_);
399         if (expected_name != actual_name) {
400           continue;
401         }
402 
403         std::string actual_signature = dex_dep.first->GetMethodSignature(method_id).ToString();
404         if (expected_signature != actual_signature) {
405           continue;
406         }
407 
408         if (expect_resolved) {
409           // Test access flags. Note that PrettyJavaAccessFlags always appends
410           // a space after the modifiers. Add it to the expected access flags.
411           std::string actual_access_flags = PrettyJavaAccessFlags(entry.GetAccessFlags());
412           if (expected_access_flags + " " != actual_access_flags) {
413             continue;
414           }
415 
416           std::string actual_decl_klass = verifier_deps_->GetStringFromId(
417               *dex_dep.first, entry.GetDeclaringClassIndex());
418           if (expected_decl_klass != actual_decl_klass) {
419             continue;
420           }
421         }
422 
423         return true;
424       }
425     }
426     return false;
427   }
428 
NumberOfCompiledDexFiles()429   size_t NumberOfCompiledDexFiles() {
430     return verifier_deps_->dex_deps_.size();
431   }
432 
HasBoolValue(const std::vector<bool> & vec,bool value)433   bool HasBoolValue(const std::vector<bool>& vec, bool value) {
434     return std::count(vec.begin(), vec.end(), value) > 0;
435   }
436 
HasEachKindOfRecord()437   bool HasEachKindOfRecord() {
438     bool has_strings = false;
439     bool has_assignability = false;
440     bool has_classes = false;
441     bool has_fields = false;
442     bool has_methods = false;
443     bool has_verified_classes = false;
444     bool has_unverified_classes = false;
445     bool has_redefined_classes = false;
446     bool has_not_redefined_classes = false;
447 
448     for (auto& entry : verifier_deps_->dex_deps_) {
449       has_strings |= !entry.second->strings_.empty();
450       has_assignability |= !entry.second->assignable_types_.empty();
451       has_assignability |= !entry.second->unassignable_types_.empty();
452       has_classes |= !entry.second->classes_.empty();
453       has_fields |= !entry.second->fields_.empty();
454       has_methods |= !entry.second->methods_.empty();
455       has_verified_classes |= HasBoolValue(entry.second->verified_classes_, true);
456       has_unverified_classes |= HasBoolValue(entry.second->verified_classes_, false);
457       has_redefined_classes |= HasBoolValue(entry.second->redefined_classes_, true);
458       has_not_redefined_classes |= HasBoolValue(entry.second->redefined_classes_, false);
459     }
460 
461     return has_strings &&
462            has_assignability &&
463            has_classes &&
464            has_fields &&
465            has_methods &&
466            has_verified_classes &&
467            has_unverified_classes &&
468            has_redefined_classes &&
469            has_not_redefined_classes;
470   }
471 
472   // Load the dex file again with a new class loader, decode the VerifierDeps
473   // in `buffer`, allow the caller to modify the deps and then run validation.
474   template<typename Fn>
RunValidation(Fn fn,const std::vector<uint8_t> & buffer,std::string * error_msg)475   bool RunValidation(Fn fn, const std::vector<uint8_t>& buffer, std::string* error_msg) {
476     ScopedObjectAccess soa(Thread::Current());
477 
478     jobject second_loader = LoadDex("VerifierDeps");
479     const auto& second_dex_files = GetDexFiles(second_loader);
480 
481     VerifierDeps decoded_deps(second_dex_files, /*output_only=*/ false);
482     bool parsed = decoded_deps.ParseStoredData(second_dex_files, ArrayRef<const uint8_t>(buffer));
483     CHECK(parsed);
484     VerifierDeps::DexFileDeps* decoded_dex_deps =
485         decoded_deps.GetDexFileDeps(*second_dex_files.front());
486 
487     // Let the test modify the dependencies.
488     fn(*decoded_dex_deps);
489 
490     StackHandleScope<1> hs(soa.Self());
491     Handle<mirror::ClassLoader> new_class_loader =
492         hs.NewHandle<mirror::ClassLoader>(soa.Decode<mirror::ClassLoader>(second_loader));
493 
494     return decoded_deps.ValidateDependencies(soa.Self(),
495                                              new_class_loader,
496                                              std::vector<const DexFile*>(),
497                                              error_msg);
498   }
499 
500   std::unique_ptr<verifier::VerifierDeps> verifier_deps_;
501   std::vector<const DexFile*> dex_files_;
502   const DexFile* primary_dex_file_;
503   jobject class_loader_;
504   ObjPtr<mirror::Class> klass_Main_;
505 };
506 
TEST_F(VerifierDepsTest,StringToId)507 TEST_F(VerifierDepsTest, StringToId) {
508   ScopedObjectAccess soa(Thread::Current());
509   LoadDexFile(soa);
510 
511   dex::StringIndex id_Main1 = verifier_deps_->GetIdFromString(*primary_dex_file_, "LMain;");
512   ASSERT_LT(id_Main1.index_, primary_dex_file_->NumStringIds());
513   ASSERT_EQ("LMain;", verifier_deps_->GetStringFromId(*primary_dex_file_, id_Main1));
514 
515   dex::StringIndex id_Main2 = verifier_deps_->GetIdFromString(*primary_dex_file_, "LMain;");
516   ASSERT_LT(id_Main2.index_, primary_dex_file_->NumStringIds());
517   ASSERT_EQ("LMain;", verifier_deps_->GetStringFromId(*primary_dex_file_, id_Main2));
518 
519   dex::StringIndex id_Lorem1 = verifier_deps_->GetIdFromString(*primary_dex_file_, "Lorem ipsum");
520   ASSERT_GE(id_Lorem1.index_, primary_dex_file_->NumStringIds());
521   ASSERT_EQ("Lorem ipsum", verifier_deps_->GetStringFromId(*primary_dex_file_, id_Lorem1));
522 
523   dex::StringIndex id_Lorem2 = verifier_deps_->GetIdFromString(*primary_dex_file_, "Lorem ipsum");
524   ASSERT_GE(id_Lorem2.index_, primary_dex_file_->NumStringIds());
525   ASSERT_EQ("Lorem ipsum", verifier_deps_->GetStringFromId(*primary_dex_file_, id_Lorem2));
526 
527   ASSERT_EQ(id_Main1, id_Main2);
528   ASSERT_EQ(id_Lorem1, id_Lorem2);
529   ASSERT_NE(id_Main1, id_Lorem1);
530 }
531 
TEST_F(VerifierDepsTest,Assignable_BothInBoot)532 TEST_F(VerifierDepsTest, Assignable_BothInBoot) {
533   ASSERT_TRUE(TestAssignabilityRecording(/* dst= */ "Ljava/util/TimeZone;",
534                                          /* src= */ "Ljava/util/SimpleTimeZone;",
535                                          /* is_strict= */ true,
536                                          /* is_assignable= */ true));
537   ASSERT_TRUE(HasAssignable("Ljava/util/TimeZone;", "Ljava/util/SimpleTimeZone;", true));
538 }
539 
TEST_F(VerifierDepsTest,Assignable_DestinationInBoot1)540 TEST_F(VerifierDepsTest, Assignable_DestinationInBoot1) {
541   ASSERT_TRUE(TestAssignabilityRecording(/* dst= */ "Ljava/net/Socket;",
542                                          /* src= */ "LMySSLSocket;",
543                                          /* is_strict= */ true,
544                                          /* is_assignable= */ true));
545   ASSERT_TRUE(HasAssignable("Ljava/net/Socket;", "Ljavax/net/ssl/SSLSocket;", true));
546 }
547 
TEST_F(VerifierDepsTest,Assignable_DestinationInBoot2)548 TEST_F(VerifierDepsTest, Assignable_DestinationInBoot2) {
549   ASSERT_TRUE(TestAssignabilityRecording(/* dst= */ "Ljava/util/TimeZone;",
550                                          /* src= */ "LMySimpleTimeZone;",
551                                          /* is_strict= */ true,
552                                          /* is_assignable= */ true));
553   ASSERT_TRUE(HasAssignable("Ljava/util/TimeZone;", "Ljava/util/SimpleTimeZone;", true));
554 }
555 
TEST_F(VerifierDepsTest,Assignable_DestinationInBoot3)556 TEST_F(VerifierDepsTest, Assignable_DestinationInBoot3) {
557   ASSERT_TRUE(TestAssignabilityRecording(/* dst= */ "Ljava/util/Collection;",
558                                          /* src= */ "LMyThreadSet;",
559                                          /* is_strict= */ true,
560                                          /* is_assignable= */ true));
561   ASSERT_TRUE(HasAssignable("Ljava/util/Collection;", "Ljava/util/Set;", true));
562 }
563 
TEST_F(VerifierDepsTest,Assignable_BothArrays_Resolved)564 TEST_F(VerifierDepsTest, Assignable_BothArrays_Resolved) {
565   ASSERT_TRUE(TestAssignabilityRecording(/* dst= */ "[[Ljava/util/TimeZone;",
566                                          /* src= */ "[[Ljava/util/SimpleTimeZone;",
567                                          /* is_strict= */ true,
568                                          /* is_assignable= */ true));
569   // If the component types of both arrays are resolved, we optimize the list of
570   // dependencies by recording a dependency on the component types.
571   ASSERT_FALSE(HasAssignable("[[Ljava/util/TimeZone;", "[[Ljava/util/SimpleTimeZone;", true));
572   ASSERT_FALSE(HasAssignable("[Ljava/util/TimeZone;", "[Ljava/util/SimpleTimeZone;", true));
573   ASSERT_TRUE(HasAssignable("Ljava/util/TimeZone;", "Ljava/util/SimpleTimeZone;", true));
574 }
575 
TEST_F(VerifierDepsTest,NotAssignable_BothInBoot)576 TEST_F(VerifierDepsTest, NotAssignable_BothInBoot) {
577   ASSERT_TRUE(TestAssignabilityRecording(/* dst= */ "Ljava/lang/Exception;",
578                                          /* src= */ "Ljava/util/SimpleTimeZone;",
579                                          /* is_strict= */ true,
580                                          /* is_assignable= */ false));
581   ASSERT_TRUE(HasAssignable("Ljava/lang/Exception;", "Ljava/util/SimpleTimeZone;", false));
582 }
583 
TEST_F(VerifierDepsTest,NotAssignable_DestinationInBoot1)584 TEST_F(VerifierDepsTest, NotAssignable_DestinationInBoot1) {
585   ASSERT_TRUE(TestAssignabilityRecording(/* dst= */ "Ljava/lang/Exception;",
586                                          /* src= */ "LMySSLSocket;",
587                                          /* is_strict= */ true,
588                                          /* is_assignable= */ false));
589   ASSERT_TRUE(HasAssignable("Ljava/lang/Exception;", "Ljavax/net/ssl/SSLSocket;", false));
590 }
591 
TEST_F(VerifierDepsTest,NotAssignable_DestinationInBoot2)592 TEST_F(VerifierDepsTest, NotAssignable_DestinationInBoot2) {
593   ASSERT_TRUE(TestAssignabilityRecording(/* dst= */ "Ljava/lang/Exception;",
594                                          /* src= */ "LMySimpleTimeZone;",
595                                          /* is_strict= */ true,
596                                          /* is_assignable= */ false));
597   ASSERT_TRUE(HasAssignable("Ljava/lang/Exception;", "Ljava/util/SimpleTimeZone;", false));
598 }
599 
TEST_F(VerifierDepsTest,NotAssignable_BothArrays)600 TEST_F(VerifierDepsTest, NotAssignable_BothArrays) {
601   ASSERT_TRUE(TestAssignabilityRecording(/* dst= */ "[Ljava/lang/Exception;",
602                                          /* src= */ "[Ljava/util/SimpleTimeZone;",
603                                          /* is_strict= */ true,
604                                          /* is_assignable= */ false));
605   ASSERT_TRUE(HasAssignable("Ljava/lang/Exception;", "Ljava/util/SimpleTimeZone;", false));
606 }
607 
TEST_F(VerifierDepsTest,ArgumentType_ResolvedClass)608 TEST_F(VerifierDepsTest, ArgumentType_ResolvedClass) {
609   ASSERT_TRUE(VerifyMethod("ArgumentType_ResolvedClass"));
610   ASSERT_TRUE(HasClass("Ljava/lang/Thread;", true, "public"));
611 }
612 
TEST_F(VerifierDepsTest,ArgumentType_UnresolvedClass)613 TEST_F(VerifierDepsTest, ArgumentType_UnresolvedClass) {
614   ASSERT_TRUE(VerifyMethod("ArgumentType_UnresolvedClass"));
615   ASSERT_TRUE(HasClass("LUnresolvedClass;", false));
616 }
617 
TEST_F(VerifierDepsTest,ArgumentType_UnresolvedSuper)618 TEST_F(VerifierDepsTest, ArgumentType_UnresolvedSuper) {
619   ASSERT_TRUE(VerifyMethod("ArgumentType_UnresolvedSuper"));
620   ASSERT_TRUE(HasClass("LMySetWithUnresolvedSuper;", false));
621 }
622 
TEST_F(VerifierDepsTest,ReturnType_Reference)623 TEST_F(VerifierDepsTest, ReturnType_Reference) {
624   ASSERT_TRUE(VerifyMethod("ReturnType_Reference"));
625   ASSERT_TRUE(HasAssignable("Ljava/lang/Throwable;", "Ljava/lang/IllegalStateException;", true));
626 }
627 
TEST_F(VerifierDepsTest,ReturnType_Array)628 TEST_F(VerifierDepsTest, ReturnType_Array) {
629   ASSERT_FALSE(VerifyMethod("ReturnType_Array"));
630   ASSERT_TRUE(HasAssignable("Ljava/lang/Integer;", "Ljava/lang/IllegalStateException;", false));
631 }
632 
TEST_F(VerifierDepsTest,InvokeArgumentType)633 TEST_F(VerifierDepsTest, InvokeArgumentType) {
634   ASSERT_TRUE(VerifyMethod("InvokeArgumentType"));
635   ASSERT_TRUE(HasClass("Ljava/text/SimpleDateFormat;", true, "public"));
636   ASSERT_TRUE(HasClass("Ljava/util/SimpleTimeZone;", true, "public"));
637   ASSERT_TRUE(HasMethod("Ljava/text/SimpleDateFormat;",
638                         "setTimeZone",
639                         "(Ljava/util/TimeZone;)V",
640                         /* expect_resolved= */ true,
641                         "public",
642                         "Ljava/text/DateFormat;"));
643   ASSERT_TRUE(HasAssignable("Ljava/util/TimeZone;", "Ljava/util/SimpleTimeZone;", true));
644 }
645 
TEST_F(VerifierDepsTest,MergeTypes_RegisterLines)646 TEST_F(VerifierDepsTest, MergeTypes_RegisterLines) {
647   ASSERT_TRUE(VerifyMethod("MergeTypes_RegisterLines"));
648   ASSERT_TRUE(HasAssignable("Ljava/lang/Exception;", "Ljava/net/SocketTimeoutException;", true));
649   ASSERT_TRUE(HasAssignable(
650       "Ljava/lang/Exception;", "Ljava/util/concurrent/TimeoutException;", true));
651 }
652 
TEST_F(VerifierDepsTest,MergeTypes_IfInstanceOf)653 TEST_F(VerifierDepsTest, MergeTypes_IfInstanceOf) {
654   ASSERT_TRUE(VerifyMethod("MergeTypes_IfInstanceOf"));
655   ASSERT_TRUE(HasAssignable("Ljava/lang/Exception;", "Ljava/net/SocketTimeoutException;", true));
656   ASSERT_TRUE(HasAssignable(
657       "Ljava/lang/Exception;", "Ljava/util/concurrent/TimeoutException;", true));
658   ASSERT_TRUE(HasAssignable("Ljava/net/SocketTimeoutException;", "Ljava/lang/Exception;", false));
659 }
660 
TEST_F(VerifierDepsTest,MergeTypes_Unresolved)661 TEST_F(VerifierDepsTest, MergeTypes_Unresolved) {
662   ASSERT_TRUE(VerifyMethod("MergeTypes_Unresolved"));
663   ASSERT_TRUE(HasAssignable("Ljava/lang/Exception;", "Ljava/net/SocketTimeoutException;", true));
664   ASSERT_TRUE(HasAssignable(
665       "Ljava/lang/Exception;", "Ljava/util/concurrent/TimeoutException;", true));
666 }
667 
TEST_F(VerifierDepsTest,ConstClass_Resolved)668 TEST_F(VerifierDepsTest, ConstClass_Resolved) {
669   ASSERT_TRUE(VerifyMethod("ConstClass_Resolved"));
670   ASSERT_TRUE(HasClass("Ljava/lang/IllegalStateException;", true, "public"));
671 }
672 
TEST_F(VerifierDepsTest,ConstClass_Unresolved)673 TEST_F(VerifierDepsTest, ConstClass_Unresolved) {
674   ASSERT_FALSE(VerifyMethod("ConstClass_Unresolved"));
675   ASSERT_TRUE(HasClass("LUnresolvedClass;", false));
676 }
677 
TEST_F(VerifierDepsTest,CheckCast_Resolved)678 TEST_F(VerifierDepsTest, CheckCast_Resolved) {
679   ASSERT_TRUE(VerifyMethod("CheckCast_Resolved"));
680   ASSERT_TRUE(HasClass("Ljava/lang/IllegalStateException;", true, "public"));
681 }
682 
TEST_F(VerifierDepsTest,CheckCast_Unresolved)683 TEST_F(VerifierDepsTest, CheckCast_Unresolved) {
684   ASSERT_FALSE(VerifyMethod("CheckCast_Unresolved"));
685   ASSERT_TRUE(HasClass("LUnresolvedClass;", false));
686 }
687 
TEST_F(VerifierDepsTest,InstanceOf_Resolved)688 TEST_F(VerifierDepsTest, InstanceOf_Resolved) {
689   ASSERT_TRUE(VerifyMethod("InstanceOf_Resolved"));
690   ASSERT_TRUE(HasClass("Ljava/lang/IllegalStateException;", true, "public"));
691 }
692 
TEST_F(VerifierDepsTest,InstanceOf_Unresolved)693 TEST_F(VerifierDepsTest, InstanceOf_Unresolved) {
694   ASSERT_FALSE(VerifyMethod("InstanceOf_Unresolved"));
695   ASSERT_TRUE(HasClass("LUnresolvedClass;", false));
696 }
697 
TEST_F(VerifierDepsTest,NewInstance_Resolved)698 TEST_F(VerifierDepsTest, NewInstance_Resolved) {
699   ASSERT_TRUE(VerifyMethod("NewInstance_Resolved"));
700   ASSERT_TRUE(HasClass("Ljava/lang/IllegalStateException;", true, "public"));
701 }
702 
TEST_F(VerifierDepsTest,NewInstance_Unresolved)703 TEST_F(VerifierDepsTest, NewInstance_Unresolved) {
704   ASSERT_FALSE(VerifyMethod("NewInstance_Unresolved"));
705   ASSERT_TRUE(HasClass("LUnresolvedClass;", false));
706 }
707 
TEST_F(VerifierDepsTest,NewArray_Unresolved)708 TEST_F(VerifierDepsTest, NewArray_Unresolved) {
709   ASSERT_FALSE(VerifyMethod("NewArray_Unresolved"));
710   ASSERT_TRUE(HasClass("[LUnresolvedClass;", false));
711 }
712 
TEST_F(VerifierDepsTest,Throw)713 TEST_F(VerifierDepsTest, Throw) {
714   ASSERT_TRUE(VerifyMethod("Throw"));
715   ASSERT_TRUE(HasAssignable("Ljava/lang/Throwable;", "Ljava/lang/IllegalStateException;", true));
716 }
717 
TEST_F(VerifierDepsTest,MoveException_Resolved)718 TEST_F(VerifierDepsTest, MoveException_Resolved) {
719   ASSERT_TRUE(VerifyMethod("MoveException_Resolved"));
720   ASSERT_TRUE(HasClass("Ljava/io/InterruptedIOException;", true, "public"));
721   ASSERT_TRUE(HasClass("Ljava/net/SocketTimeoutException;", true, "public"));
722   ASSERT_TRUE(HasClass("Ljava/util/zip/ZipException;", true, "public"));
723 
724   // Testing that all exception types are assignable to Throwable.
725   ASSERT_TRUE(HasAssignable("Ljava/lang/Throwable;", "Ljava/io/InterruptedIOException;", true));
726   ASSERT_TRUE(HasAssignable("Ljava/lang/Throwable;", "Ljava/net/SocketTimeoutException;", true));
727   ASSERT_TRUE(HasAssignable("Ljava/lang/Throwable;", "Ljava/util/zip/ZipException;", true));
728 
729   // Testing that the merge type is assignable to Throwable.
730   ASSERT_TRUE(HasAssignable("Ljava/lang/Throwable;", "Ljava/io/IOException;", true));
731 
732   // Merging of exception types.
733   ASSERT_TRUE(HasAssignable("Ljava/io/IOException;", "Ljava/io/InterruptedIOException;", true));
734   ASSERT_TRUE(HasAssignable("Ljava/io/IOException;", "Ljava/util/zip/ZipException;", true));
735   ASSERT_TRUE(HasAssignable(
736       "Ljava/io/InterruptedIOException;", "Ljava/net/SocketTimeoutException;", true));
737 }
738 
TEST_F(VerifierDepsTest,MoveException_Unresolved)739 TEST_F(VerifierDepsTest, MoveException_Unresolved) {
740   ASSERT_FALSE(VerifyMethod("MoveException_Unresolved"));
741   ASSERT_TRUE(HasClass("LUnresolvedException;", false));
742 }
743 
TEST_F(VerifierDepsTest,StaticField_Resolved_DeclaredInReferenced)744 TEST_F(VerifierDepsTest, StaticField_Resolved_DeclaredInReferenced) {
745   ASSERT_TRUE(VerifyMethod("StaticField_Resolved_DeclaredInReferenced"));
746   ASSERT_TRUE(HasClass("Ljava/lang/System;", true, "public"));
747   ASSERT_TRUE(HasField("Ljava/lang/System;",
748                        "out",
749                        "Ljava/io/PrintStream;",
750                        true,
751                        "public static",
752                        "Ljava/lang/System;"));
753 }
754 
TEST_F(VerifierDepsTest,StaticField_Resolved_DeclaredInSuperclass1)755 TEST_F(VerifierDepsTest, StaticField_Resolved_DeclaredInSuperclass1) {
756   ASSERT_TRUE(VerifyMethod("StaticField_Resolved_DeclaredInSuperclass1"));
757   ASSERT_TRUE(HasClass("Ljava/util/SimpleTimeZone;", true, "public"));
758   ASSERT_TRUE(HasField(
759       "Ljava/util/SimpleTimeZone;", "LONG", "I", true, "public static", "Ljava/util/TimeZone;"));
760 }
761 
TEST_F(VerifierDepsTest,StaticField_Resolved_DeclaredInSuperclass2)762 TEST_F(VerifierDepsTest, StaticField_Resolved_DeclaredInSuperclass2) {
763   ASSERT_TRUE(VerifyMethod("StaticField_Resolved_DeclaredInSuperclass2"));
764   ASSERT_TRUE(HasField(
765       "LMySimpleTimeZone;", "SHORT", "I", true, "public static", "Ljava/util/TimeZone;"));
766 }
767 
TEST_F(VerifierDepsTest,StaticField_Resolved_DeclaredInInterface1)768 TEST_F(VerifierDepsTest, StaticField_Resolved_DeclaredInInterface1) {
769   ASSERT_TRUE(VerifyMethod("StaticField_Resolved_DeclaredInInterface1"));
770   ASSERT_TRUE(HasClass("Ljavax/xml/transform/dom/DOMResult;", true, "public"));
771   ASSERT_TRUE(HasField("Ljavax/xml/transform/dom/DOMResult;",
772                        "PI_ENABLE_OUTPUT_ESCAPING",
773                        "Ljava/lang/String;",
774                        true,
775                        "public static",
776                        "Ljavax/xml/transform/Result;"));
777 }
778 
TEST_F(VerifierDepsTest,StaticField_Resolved_DeclaredInInterface2)779 TEST_F(VerifierDepsTest, StaticField_Resolved_DeclaredInInterface2) {
780   ASSERT_TRUE(VerifyMethod("StaticField_Resolved_DeclaredInInterface2"));
781   ASSERT_TRUE(HasField("LMyDOMResult;",
782                        "PI_ENABLE_OUTPUT_ESCAPING",
783                        "Ljava/lang/String;",
784                        true,
785                        "public static",
786                        "Ljavax/xml/transform/Result;"));
787 }
788 
TEST_F(VerifierDepsTest,StaticField_Resolved_DeclaredInInterface3)789 TEST_F(VerifierDepsTest, StaticField_Resolved_DeclaredInInterface3) {
790   ASSERT_TRUE(VerifyMethod("StaticField_Resolved_DeclaredInInterface3"));
791   ASSERT_TRUE(HasField("LMyResult;",
792                        "PI_ENABLE_OUTPUT_ESCAPING",
793                        "Ljava/lang/String;",
794                        true,
795                        "public static",
796                        "Ljavax/xml/transform/Result;"));
797 }
798 
TEST_F(VerifierDepsTest,StaticField_Resolved_DeclaredInInterface4)799 TEST_F(VerifierDepsTest, StaticField_Resolved_DeclaredInInterface4) {
800   ASSERT_TRUE(VerifyMethod("StaticField_Resolved_DeclaredInInterface4"));
801   ASSERT_TRUE(HasField("LMyDocument;",
802                        "ELEMENT_NODE",
803                        "S",
804                        true,
805                        "public static",
806                        "Lorg/w3c/dom/Node;"));
807 }
808 
TEST_F(VerifierDepsTest,StaticField_Unresolved_ReferrerInBoot)809 TEST_F(VerifierDepsTest, StaticField_Unresolved_ReferrerInBoot) {
810   ASSERT_TRUE(VerifyMethod("StaticField_Unresolved_ReferrerInBoot"));
811   ASSERT_TRUE(HasClass("Ljava/util/TimeZone;", true, "public"));
812   ASSERT_TRUE(HasField("Ljava/util/TimeZone;", "x", "I", false));
813 }
814 
TEST_F(VerifierDepsTest,StaticField_Unresolved_ReferrerInDex)815 TEST_F(VerifierDepsTest, StaticField_Unresolved_ReferrerInDex) {
816   ASSERT_TRUE(VerifyMethod("StaticField_Unresolved_ReferrerInDex"));
817   ASSERT_TRUE(HasField("LMyThreadSet;", "x", "I", false));
818 }
819 
TEST_F(VerifierDepsTest,InstanceField_Resolved_DeclaredInReferenced)820 TEST_F(VerifierDepsTest, InstanceField_Resolved_DeclaredInReferenced) {
821   ASSERT_TRUE(VerifyMethod("InstanceField_Resolved_DeclaredInReferenced"));
822   ASSERT_TRUE(HasClass("Ljava/io/InterruptedIOException;", true, "public"));
823   ASSERT_TRUE(HasField("Ljava/io/InterruptedIOException;",
824                        "bytesTransferred",
825                        "I",
826                        true,
827                        "public",
828                        "Ljava/io/InterruptedIOException;"));
829   ASSERT_TRUE(HasAssignable(
830       "Ljava/io/InterruptedIOException;", "Ljava/net/SocketTimeoutException;", true));
831 }
832 
TEST_F(VerifierDepsTest,InstanceField_Resolved_DeclaredInSuperclass1)833 TEST_F(VerifierDepsTest, InstanceField_Resolved_DeclaredInSuperclass1) {
834   ASSERT_TRUE(VerifyMethod("InstanceField_Resolved_DeclaredInSuperclass1"));
835   ASSERT_TRUE(HasClass("Ljava/net/SocketTimeoutException;", true, "public"));
836   ASSERT_TRUE(HasField("Ljava/net/SocketTimeoutException;",
837                        "bytesTransferred",
838                        "I",
839                        true,
840                        "public",
841                        "Ljava/io/InterruptedIOException;"));
842   ASSERT_TRUE(HasAssignable(
843       "Ljava/io/InterruptedIOException;", "Ljava/net/SocketTimeoutException;", true));
844 }
845 
TEST_F(VerifierDepsTest,InstanceField_Resolved_DeclaredInSuperclass2)846 TEST_F(VerifierDepsTest, InstanceField_Resolved_DeclaredInSuperclass2) {
847   ASSERT_TRUE(VerifyMethod("InstanceField_Resolved_DeclaredInSuperclass2"));
848   ASSERT_TRUE(HasField("LMySocketTimeoutException;",
849                        "bytesTransferred",
850                        "I",
851                        true,
852                        "public",
853                        "Ljava/io/InterruptedIOException;"));
854   ASSERT_TRUE(HasAssignable(
855       "Ljava/io/InterruptedIOException;", "Ljava/net/SocketTimeoutException;", true));
856 }
857 
TEST_F(VerifierDepsTest,InstanceField_Unresolved_ReferrerInBoot)858 TEST_F(VerifierDepsTest, InstanceField_Unresolved_ReferrerInBoot) {
859   ASSERT_TRUE(VerifyMethod("InstanceField_Unresolved_ReferrerInBoot"));
860   ASSERT_TRUE(HasClass("Ljava/io/InterruptedIOException;", true, "public"));
861   ASSERT_TRUE(HasField("Ljava/io/InterruptedIOException;", "x", "I", false));
862 }
863 
TEST_F(VerifierDepsTest,InstanceField_Unresolved_ReferrerInDex)864 TEST_F(VerifierDepsTest, InstanceField_Unresolved_ReferrerInDex) {
865   ASSERT_TRUE(VerifyMethod("InstanceField_Unresolved_ReferrerInDex"));
866   ASSERT_TRUE(HasField("LMyThreadSet;", "x", "I", false));
867 }
868 
TEST_F(VerifierDepsTest,InvokeStatic_Resolved_DeclaredInReferenced)869 TEST_F(VerifierDepsTest, InvokeStatic_Resolved_DeclaredInReferenced) {
870   ASSERT_TRUE(VerifyMethod("InvokeStatic_Resolved_DeclaredInReferenced"));
871   ASSERT_TRUE(HasClass("Ljava/net/Socket;", true, "public"));
872   ASSERT_TRUE(HasMethod("Ljava/net/Socket;",
873                         "setSocketImplFactory",
874                         "(Ljava/net/SocketImplFactory;)V",
875                         /* expect_resolved= */ true,
876                         "public static",
877                         "Ljava/net/Socket;"));
878 }
879 
TEST_F(VerifierDepsTest,InvokeStatic_Resolved_DeclaredInSuperclass1)880 TEST_F(VerifierDepsTest, InvokeStatic_Resolved_DeclaredInSuperclass1) {
881   ASSERT_TRUE(VerifyMethod("InvokeStatic_Resolved_DeclaredInSuperclass1"));
882   ASSERT_TRUE(HasClass("Ljavax/net/ssl/SSLSocket;", true, "public"));
883   ASSERT_TRUE(HasMethod("Ljavax/net/ssl/SSLSocket;",
884                         "setSocketImplFactory",
885                         "(Ljava/net/SocketImplFactory;)V",
886                         /* expect_resolved= */ true,
887                         "public static",
888                         "Ljava/net/Socket;"));
889 }
890 
TEST_F(VerifierDepsTest,InvokeStatic_Resolved_DeclaredInSuperclass2)891 TEST_F(VerifierDepsTest, InvokeStatic_Resolved_DeclaredInSuperclass2) {
892   ASSERT_TRUE(VerifyMethod("InvokeStatic_Resolved_DeclaredInSuperclass2"));
893   ASSERT_TRUE(HasMethod("LMySSLSocket;",
894                         "setSocketImplFactory",
895                         "(Ljava/net/SocketImplFactory;)V",
896                         /* expect_resolved= */ true,
897                         "public static",
898                         "Ljava/net/Socket;"));
899 }
900 
TEST_F(VerifierDepsTest,InvokeStatic_DeclaredInInterface1)901 TEST_F(VerifierDepsTest, InvokeStatic_DeclaredInInterface1) {
902   ASSERT_TRUE(VerifyMethod("InvokeStatic_DeclaredInInterface1"));
903   ASSERT_TRUE(HasClass("Ljava/util/Map$Entry;", true, "public interface"));
904   ASSERT_TRUE(HasMethod("Ljava/util/Map$Entry;",
905                         "comparingByKey",
906                         "()Ljava/util/Comparator;",
907                         /* expect_resolved= */ true,
908                         "public static",
909                         "Ljava/util/Map$Entry;"));
910 }
911 
TEST_F(VerifierDepsTest,InvokeStatic_DeclaredInInterface2)912 TEST_F(VerifierDepsTest, InvokeStatic_DeclaredInInterface2) {
913   ASSERT_FALSE(VerifyMethod("InvokeStatic_DeclaredInInterface2"));
914   ASSERT_TRUE(HasClass("Ljava/util/AbstractMap$SimpleEntry;", true, "public"));
915   ASSERT_TRUE(HasMethod("Ljava/util/AbstractMap$SimpleEntry;",
916                         "comparingByKey",
917                         "()Ljava/util/Comparator;",
918                         /* expect_resolved= */ false));
919 }
920 
TEST_F(VerifierDepsTest,InvokeStatic_Unresolved1)921 TEST_F(VerifierDepsTest, InvokeStatic_Unresolved1) {
922   ASSERT_FALSE(VerifyMethod("InvokeStatic_Unresolved1"));
923   ASSERT_TRUE(HasClass("Ljavax/net/ssl/SSLSocket;", true, "public"));
924   ASSERT_TRUE(HasMethod("Ljavax/net/ssl/SSLSocket;",
925                         "x",
926                         "()V",
927                         /* expect_resolved= */ false));
928 }
929 
TEST_F(VerifierDepsTest,InvokeStatic_Unresolved2)930 TEST_F(VerifierDepsTest, InvokeStatic_Unresolved2) {
931   ASSERT_FALSE(VerifyMethod("InvokeStatic_Unresolved2"));
932   ASSERT_TRUE(HasMethod("LMySSLSocket;",
933                         "x",
934                         "()V",
935                         /* expect_resolved= */ false));
936 }
937 
TEST_F(VerifierDepsTest,InvokeDirect_Resolved_DeclaredInReferenced)938 TEST_F(VerifierDepsTest, InvokeDirect_Resolved_DeclaredInReferenced) {
939   ASSERT_TRUE(VerifyMethod("InvokeDirect_Resolved_DeclaredInReferenced"));
940   ASSERT_TRUE(HasClass("Ljava/net/Socket;", true, "public"));
941   ASSERT_TRUE(HasMethod("Ljava/net/Socket;",
942                         "<init>",
943                         "()V",
944                         /* expect_resolved= */ true,
945                         "public",
946                         "Ljava/net/Socket;"));
947 }
948 
TEST_F(VerifierDepsTest,InvokeDirect_Resolved_DeclaredInSuperclass1)949 TEST_F(VerifierDepsTest, InvokeDirect_Resolved_DeclaredInSuperclass1) {
950   ASSERT_FALSE(VerifyMethod("InvokeDirect_Resolved_DeclaredInSuperclass1"));
951   ASSERT_TRUE(HasClass("Ljavax/net/ssl/SSLSocket;", true, "public"));
952   ASSERT_TRUE(HasMethod("Ljavax/net/ssl/SSLSocket;",
953                         "checkOldImpl",
954                         "()V",
955                         /* expect_resolved= */ true,
956                         "private",
957                         "Ljava/net/Socket;"));
958 }
959 
TEST_F(VerifierDepsTest,InvokeDirect_Resolved_DeclaredInSuperclass2)960 TEST_F(VerifierDepsTest, InvokeDirect_Resolved_DeclaredInSuperclass2) {
961   ASSERT_FALSE(VerifyMethod("InvokeDirect_Resolved_DeclaredInSuperclass2"));
962   ASSERT_TRUE(HasMethod("LMySSLSocket;",
963                         "checkOldImpl",
964                         "()V",
965                         /* expect_resolved= */ true,
966                         "private",
967                         "Ljava/net/Socket;"));
968 }
969 
TEST_F(VerifierDepsTest,InvokeDirect_Unresolved1)970 TEST_F(VerifierDepsTest, InvokeDirect_Unresolved1) {
971   ASSERT_FALSE(VerifyMethod("InvokeDirect_Unresolved1"));
972   ASSERT_TRUE(HasClass("Ljavax/net/ssl/SSLSocket;", true, "public"));
973   ASSERT_TRUE(HasMethod("Ljavax/net/ssl/SSLSocket;",
974                         "x",
975                         "()V",
976                         /* expect_resolved= */ false));
977 }
978 
TEST_F(VerifierDepsTest,InvokeDirect_Unresolved2)979 TEST_F(VerifierDepsTest, InvokeDirect_Unresolved2) {
980   ASSERT_FALSE(VerifyMethod("InvokeDirect_Unresolved2"));
981   ASSERT_TRUE(HasMethod("LMySSLSocket;",
982                         "x",
983                         "()V",
984                         /* expect_resolved= */ false));
985 }
986 
TEST_F(VerifierDepsTest,InvokeVirtual_Resolved_DeclaredInReferenced)987 TEST_F(VerifierDepsTest, InvokeVirtual_Resolved_DeclaredInReferenced) {
988   ASSERT_TRUE(VerifyMethod("InvokeVirtual_Resolved_DeclaredInReferenced"));
989   ASSERT_TRUE(HasClass("Ljava/lang/Throwable;", true, "public"));
990   ASSERT_TRUE(HasMethod("Ljava/lang/Throwable;",
991                         "getMessage",
992                         "()Ljava/lang/String;",
993                         /* expect_resolved= */ true,
994                         "public",
995                         "Ljava/lang/Throwable;"));
996   // Type dependency on `this` argument.
997   ASSERT_TRUE(HasAssignable("Ljava/lang/Throwable;", "Ljava/net/SocketTimeoutException;", true));
998 }
999 
TEST_F(VerifierDepsTest,InvokeVirtual_Resolved_DeclaredInSuperclass1)1000 TEST_F(VerifierDepsTest, InvokeVirtual_Resolved_DeclaredInSuperclass1) {
1001   ASSERT_TRUE(VerifyMethod("InvokeVirtual_Resolved_DeclaredInSuperclass1"));
1002   ASSERT_TRUE(HasClass("Ljava/io/InterruptedIOException;", true, "public"));
1003   ASSERT_TRUE(HasMethod("Ljava/io/InterruptedIOException;",
1004                         "getMessage",
1005                         "()Ljava/lang/String;",
1006                         /* expect_resolved= */ true,
1007                         "public",
1008                         "Ljava/lang/Throwable;"));
1009   // Type dependency on `this` argument.
1010   ASSERT_TRUE(HasAssignable("Ljava/lang/Throwable;", "Ljava/net/SocketTimeoutException;", true));
1011 }
1012 
TEST_F(VerifierDepsTest,InvokeVirtual_Resolved_DeclaredInSuperclass2)1013 TEST_F(VerifierDepsTest, InvokeVirtual_Resolved_DeclaredInSuperclass2) {
1014   ASSERT_TRUE(VerifyMethod("InvokeVirtual_Resolved_DeclaredInSuperclass2"));
1015   ASSERT_TRUE(HasMethod("LMySocketTimeoutException;",
1016                         "getMessage",
1017                         "()Ljava/lang/String;",
1018                         /* expect_resolved= */ true,
1019                         "public",
1020                         "Ljava/lang/Throwable;"));
1021 }
1022 
TEST_F(VerifierDepsTest,InvokeVirtual_Resolved_DeclaredInSuperinterface)1023 TEST_F(VerifierDepsTest, InvokeVirtual_Resolved_DeclaredInSuperinterface) {
1024   ASSERT_TRUE(VerifyMethod("InvokeVirtual_Resolved_DeclaredInSuperinterface"));
1025   ASSERT_TRUE(HasMethod("LMyThreadSet;",
1026                         "size",
1027                         "()I",
1028                         /* expect_resolved= */ true,
1029                         "public",
1030                         "Ljava/util/Set;"));
1031 }
1032 
TEST_F(VerifierDepsTest,InvokeVirtual_Unresolved1)1033 TEST_F(VerifierDepsTest, InvokeVirtual_Unresolved1) {
1034   ASSERT_FALSE(VerifyMethod("InvokeVirtual_Unresolved1"));
1035   ASSERT_TRUE(HasClass("Ljava/io/InterruptedIOException;", true, "public"));
1036   ASSERT_TRUE(HasMethod("Ljava/io/InterruptedIOException;",
1037                         "x",
1038                         "()V",
1039                         /* expect_resolved= */ false));
1040 }
1041 
TEST_F(VerifierDepsTest,InvokeVirtual_Unresolved2)1042 TEST_F(VerifierDepsTest, InvokeVirtual_Unresolved2) {
1043   ASSERT_FALSE(VerifyMethod("InvokeVirtual_Unresolved2"));
1044   ASSERT_TRUE(HasMethod("LMySocketTimeoutException;",
1045                         "x",
1046                         "()V",
1047                         /* expect_resolved= */ false));
1048 }
1049 
TEST_F(VerifierDepsTest,InvokeInterface_Resolved_DeclaredInReferenced)1050 TEST_F(VerifierDepsTest, InvokeInterface_Resolved_DeclaredInReferenced) {
1051   ASSERT_TRUE(VerifyMethod("InvokeInterface_Resolved_DeclaredInReferenced"));
1052   ASSERT_TRUE(HasClass("Ljava/lang/Runnable;", true, "public interface"));
1053   ASSERT_TRUE(HasMethod("Ljava/lang/Runnable;",
1054                         "run",
1055                         "()V",
1056                         /* expect_resolved= */ true,
1057                         "public",
1058                         "Ljava/lang/Runnable;"));
1059 }
1060 
TEST_F(VerifierDepsTest,InvokeInterface_Resolved_DeclaredInSuperclass)1061 TEST_F(VerifierDepsTest, InvokeInterface_Resolved_DeclaredInSuperclass) {
1062   ASSERT_FALSE(VerifyMethod("InvokeInterface_Resolved_DeclaredInSuperclass"));
1063   // TODO: Maybe we should not record dependency if the invoke type does not match the lookup type.
1064   ASSERT_TRUE(HasMethod("LMyThread;",
1065                         "join",
1066                         "()V",
1067                         /* expect_resolved= */ true,
1068                         "public",
1069                         "Ljava/lang/Thread;"));
1070 }
1071 
TEST_F(VerifierDepsTest,InvokeInterface_Resolved_DeclaredInSuperinterface1)1072 TEST_F(VerifierDepsTest, InvokeInterface_Resolved_DeclaredInSuperinterface1) {
1073   ASSERT_FALSE(VerifyMethod("InvokeInterface_Resolved_DeclaredInSuperinterface1"));
1074   // TODO: Maybe we should not record dependency if the invoke type does not match the lookup type.
1075   ASSERT_TRUE(HasMethod("LMyThreadSet;",
1076                         "run",
1077                         "()V",
1078                         /* expect_resolved= */ true,
1079                         "public",
1080                         "Ljava/lang/Thread;"));
1081 }
1082 
TEST_F(VerifierDepsTest,InvokeInterface_Resolved_DeclaredInSuperinterface2)1083 TEST_F(VerifierDepsTest, InvokeInterface_Resolved_DeclaredInSuperinterface2) {
1084   ASSERT_FALSE(VerifyMethod("InvokeInterface_Resolved_DeclaredInSuperinterface2"));
1085   ASSERT_TRUE(HasMethod("LMyThreadSet;",
1086                         "isEmpty",
1087                         "()Z",
1088                         /* expect_resolved= */ true,
1089                         "public",
1090                         "Ljava/util/Set;"));
1091 }
1092 
TEST_F(VerifierDepsTest,InvokeInterface_Unresolved1)1093 TEST_F(VerifierDepsTest, InvokeInterface_Unresolved1) {
1094   ASSERT_FALSE(VerifyMethod("InvokeInterface_Unresolved1"));
1095   ASSERT_TRUE(HasClass("Ljava/lang/Runnable;", true, "public interface"));
1096   ASSERT_TRUE(HasMethod("Ljava/lang/Runnable;",
1097                         "x",
1098                         "()V",
1099                         /* expect_resolved= */ false));
1100 }
1101 
TEST_F(VerifierDepsTest,InvokeInterface_Unresolved2)1102 TEST_F(VerifierDepsTest, InvokeInterface_Unresolved2) {
1103   ASSERT_FALSE(VerifyMethod("InvokeInterface_Unresolved2"));
1104   ASSERT_TRUE(HasMethod("LMyThreadSet;", "x", "()V", /* expect_resolved= */ false));
1105 }
1106 
TEST_F(VerifierDepsTest,InvokeSuper_ThisAssignable)1107 TEST_F(VerifierDepsTest, InvokeSuper_ThisAssignable) {
1108   ASSERT_TRUE(VerifyMethod("InvokeSuper_ThisAssignable"));
1109   ASSERT_TRUE(HasClass("Ljava/lang/Runnable;", true, "public interface"));
1110   ASSERT_TRUE(HasAssignable("Ljava/lang/Runnable;", "Ljava/lang/Thread;", true));
1111   ASSERT_TRUE(HasMethod("Ljava/lang/Runnable;",
1112                         "run",
1113                         "()V",
1114                         /* expect_resolved= */ true,
1115                         "public",
1116                         "Ljava/lang/Runnable;"));
1117 }
1118 
TEST_F(VerifierDepsTest,InvokeSuper_ThisNotAssignable)1119 TEST_F(VerifierDepsTest, InvokeSuper_ThisNotAssignable) {
1120   ASSERT_FALSE(VerifyMethod("InvokeSuper_ThisNotAssignable"));
1121   ASSERT_TRUE(HasClass("Ljava/lang/Integer;", true, "public"));
1122   ASSERT_TRUE(HasAssignable("Ljava/lang/Integer;", "Ljava/lang/Thread;", false));
1123   ASSERT_TRUE(HasMethod("Ljava/lang/Integer;",
1124                         "intValue", "()I",
1125                         /* expect_resolved= */ true,
1126                         "public", "Ljava/lang/Integer;"));
1127 }
1128 
TEST_F(VerifierDepsTest,ArgumentType_ResolvedReferenceArray)1129 TEST_F(VerifierDepsTest, ArgumentType_ResolvedReferenceArray) {
1130   ASSERT_TRUE(VerifyMethod("ArgumentType_ResolvedReferenceArray"));
1131   ASSERT_TRUE(HasClass("[Ljava/lang/Thread;", true, "public"));
1132 }
1133 
TEST_F(VerifierDepsTest,NewArray_Resolved)1134 TEST_F(VerifierDepsTest, NewArray_Resolved) {
1135   ASSERT_TRUE(VerifyMethod("NewArray_Resolved"));
1136   ASSERT_TRUE(HasClass("[Ljava/lang/IllegalStateException;", true, "public"));
1137 }
1138 
TEST_F(VerifierDepsTest,EncodeDecode)1139 TEST_F(VerifierDepsTest, EncodeDecode) {
1140   VerifyDexFile();
1141 
1142   ASSERT_EQ(1u, NumberOfCompiledDexFiles());
1143   ASSERT_TRUE(HasEachKindOfRecord());
1144 
1145   std::vector<uint8_t> buffer;
1146   verifier_deps_->Encode(dex_files_, &buffer);
1147   ASSERT_FALSE(buffer.empty());
1148 
1149   VerifierDeps decoded_deps(dex_files_, /*output_only=*/ false);
1150   bool parsed = decoded_deps.ParseStoredData(dex_files_, ArrayRef<const uint8_t>(buffer));
1151   ASSERT_TRUE(parsed);
1152   ASSERT_TRUE(verifier_deps_->Equals(decoded_deps));
1153 }
1154 
TEST_F(VerifierDepsTest,EncodeDecodeMulti)1155 TEST_F(VerifierDepsTest, EncodeDecodeMulti) {
1156   VerifyDexFile("MultiDex");
1157 
1158   ASSERT_GT(NumberOfCompiledDexFiles(), 1u);
1159   std::vector<uint8_t> buffer;
1160   verifier_deps_->Encode(dex_files_, &buffer);
1161   ASSERT_FALSE(buffer.empty());
1162 
1163   // Create new DexFile, to mess with std::map order: the verifier deps used
1164   // to iterate over the map, which doesn't guarantee insertion order. We fixed
1165   // this by passing the expected order when encoding/decoding.
1166   std::vector<std::unique_ptr<const DexFile>> first_dex_files = OpenTestDexFiles("VerifierDeps");
1167   std::vector<std::unique_ptr<const DexFile>> second_dex_files = OpenTestDexFiles("MultiDex");
1168   std::vector<const DexFile*> dex_files;
1169   for (auto& dex_file : first_dex_files) {
1170     dex_files.push_back(dex_file.get());
1171   }
1172   for (auto& dex_file : second_dex_files) {
1173     dex_files.push_back(dex_file.get());
1174   }
1175 
1176   // Dump the new verifier deps to ensure it can properly read the data.
1177   VerifierDeps decoded_deps(dex_files, /*output_only=*/ false);
1178   bool parsed = decoded_deps.ParseStoredData(dex_files, ArrayRef<const uint8_t>(buffer));
1179   ASSERT_TRUE(parsed);
1180   std::ostringstream stream;
1181   VariableIndentationOutputStream os(&stream);
1182   decoded_deps.Dump(&os);
1183 }
1184 
TEST_F(VerifierDepsTest,UnverifiedClasses)1185 TEST_F(VerifierDepsTest, UnverifiedClasses) {
1186   VerifyDexFile();
1187   ASSERT_FALSE(HasUnverifiedClass("LMyThread;"));
1188   // Test that a class with a soft failure is recorded.
1189   ASSERT_TRUE(HasUnverifiedClass("LMain;"));
1190   // Test that a class with hard failure is recorded.
1191   ASSERT_TRUE(HasUnverifiedClass("LMyVerificationFailure;"));
1192   // Test that a class with unresolved super is recorded.
1193   ASSERT_TRUE(HasUnverifiedClass("LMyClassWithNoSuper;"));
1194   // Test that a class with unresolved super and hard failure is recorded.
1195   ASSERT_TRUE(HasUnverifiedClass("LMyClassWithNoSuperButFailures;"));
1196 }
1197 
TEST_F(VerifierDepsTest,RedefinedClass)1198 TEST_F(VerifierDepsTest, RedefinedClass) {
1199   VerifyDexFile();
1200   // Test that a class which redefines a boot classpath class has dependencies recorded.
1201   ASSERT_TRUE(HasRedefinedClass("Ljava/net/SocketTimeoutException;"));
1202   // These come from test case InstanceField_Resolved_DeclaredInSuperclass1.
1203   ASSERT_TRUE(HasClass("Ljava/net/SocketTimeoutException;", true, "public"));
1204   ASSERT_TRUE(HasField("Ljava/net/SocketTimeoutException;",
1205                        "bytesTransferred",
1206                        "I",
1207                        true,
1208                        "public",
1209                        "Ljava/io/InterruptedIOException;"));
1210 }
1211 
TEST_F(VerifierDepsTest,UnverifiedOrder)1212 TEST_F(VerifierDepsTest, UnverifiedOrder) {
1213   ScopedObjectAccess soa(Thread::Current());
1214   jobject loader = LoadDex("VerifierDeps");
1215   std::vector<const DexFile*> dex_files = GetDexFiles(loader);
1216   ASSERT_GT(dex_files.size(), 0u);
1217   const DexFile* dex_file = dex_files[0];
1218   VerifierDeps deps1(dex_files);
1219   Thread* const self = Thread::Current();
1220   ASSERT_TRUE(self->GetVerifierDeps() == nullptr);
1221   self->SetVerifierDeps(&deps1);
1222   deps1.MaybeRecordVerificationStatus(*dex_file,
1223                                       dex_file->GetClassDef(0u),
1224                                       verifier::FailureKind::kHardFailure);
1225   deps1.MaybeRecordVerificationStatus(*dex_file,
1226                                       dex_file->GetClassDef(1u),
1227                                       verifier::FailureKind::kHardFailure);
1228   VerifierDeps deps2(dex_files);
1229   self->SetVerifierDeps(nullptr);
1230   self->SetVerifierDeps(&deps2);
1231   deps2.MaybeRecordVerificationStatus(*dex_file,
1232                                       dex_file->GetClassDef(1u),
1233                                       verifier::FailureKind::kHardFailure);
1234   deps2.MaybeRecordVerificationStatus(*dex_file,
1235                                       dex_file->GetClassDef(0u),
1236                                       verifier::FailureKind::kHardFailure);
1237   self->SetVerifierDeps(nullptr);
1238   std::vector<uint8_t> buffer1;
1239   deps1.Encode(dex_files, &buffer1);
1240   std::vector<uint8_t> buffer2;
1241   deps2.Encode(dex_files, &buffer2);
1242   EXPECT_EQ(buffer1, buffer2);
1243 }
1244 
TEST_F(VerifierDepsTest,VerifyDeps)1245 TEST_F(VerifierDepsTest, VerifyDeps) {
1246   std::string error_msg;
1247 
1248   VerifyDexFile();
1249   ASSERT_EQ(1u, NumberOfCompiledDexFiles());
1250   ASSERT_TRUE(HasEachKindOfRecord());
1251 
1252   // When validating, we create a new class loader, as
1253   // the existing `class_loader_` may contain erroneous classes,
1254   // that ClassLinker::FindClass won't return.
1255 
1256   std::vector<uint8_t> buffer;
1257   verifier_deps_->Encode(dex_files_, &buffer);
1258   ASSERT_FALSE(buffer.empty());
1259 
1260   // Check that dependencies are satisfied after decoding `buffer`.
1261   ASSERT_TRUE(RunValidation([](VerifierDeps::DexFileDeps&) {}, buffer, &error_msg))
1262       << error_msg;
1263 
1264   // Mess with the dependencies to make sure we catch any change and fail to verify.
1265   ASSERT_FALSE(RunValidation([](VerifierDeps::DexFileDeps& deps) {
1266         deps.assignable_types_.insert(*deps.unassignable_types_.begin());
1267       }, buffer, &error_msg));
1268 
1269   // Mess with the unassignable_types.
1270   ASSERT_FALSE(RunValidation([](VerifierDeps::DexFileDeps& deps) {
1271         deps.unassignable_types_.insert(*deps.assignable_types_.begin());
1272       }, buffer, &error_msg));
1273 
1274   // Mess with classes.
1275   ASSERT_FALSE(RunValidation([](VerifierDeps::DexFileDeps& deps) {
1276         for (const auto& entry : deps.classes_) {
1277           if (entry.IsResolved()) {
1278             deps.classes_.insert(VerifierDeps::ClassResolution(
1279                 entry.GetDexTypeIndex(), VerifierDeps::kUnresolvedMarker));
1280             return;
1281           }
1282         }
1283         LOG(FATAL) << "Could not find any resolved classes";
1284         UNREACHABLE();
1285       }, buffer, &error_msg));
1286   ASSERT_FALSE(RunValidation([](VerifierDeps::DexFileDeps& deps) {
1287         for (const auto& entry : deps.classes_) {
1288           if (!entry.IsResolved()) {
1289             deps.classes_.insert(VerifierDeps::ClassResolution(
1290                 entry.GetDexTypeIndex(), VerifierDeps::kUnresolvedMarker - 1));
1291             return;
1292           }
1293         }
1294         LOG(FATAL) << "Could not find any unresolved classes";
1295         UNREACHABLE();
1296       }, buffer, &error_msg));
1297   ASSERT_FALSE(RunValidation([](VerifierDeps::DexFileDeps& deps) {
1298         for (const auto& entry : deps.classes_) {
1299           if (entry.IsResolved()) {
1300             deps.classes_.insert(VerifierDeps::ClassResolution(
1301                 entry.GetDexTypeIndex(), entry.GetAccessFlags() - 1));
1302             return;
1303           }
1304         }
1305         LOG(FATAL) << "Could not find any resolved classes";
1306         UNREACHABLE();
1307       }, buffer, &error_msg));
1308 
1309   // Mess with fields.
1310   ASSERT_FALSE(RunValidation([](VerifierDeps::DexFileDeps& deps) {
1311         for (const auto& entry : deps.fields_) {
1312           if (entry.IsResolved()) {
1313             deps.fields_.insert(VerifierDeps::FieldResolution(entry.GetDexFieldIndex(),
1314                                                               VerifierDeps::kUnresolvedMarker,
1315                                                               entry.GetDeclaringClassIndex()));
1316             return;
1317           }
1318         }
1319         LOG(FATAL) << "Could not find any resolved fields";
1320         UNREACHABLE();
1321       }, buffer, &error_msg));
1322   ASSERT_FALSE(RunValidation([](VerifierDeps::DexFileDeps& deps) {
1323         for (const auto& entry : deps.fields_) {
1324           if (!entry.IsResolved()) {
1325             constexpr dex::StringIndex kStringIndexZero(0);  // We know there is a class there.
1326             deps.fields_.insert(VerifierDeps::FieldResolution(0 /* we know there is a field there */,
1327                                                               VerifierDeps::kUnresolvedMarker - 1,
1328                                                               kStringIndexZero));
1329             return;
1330           }
1331         }
1332         LOG(FATAL) << "Could not find any unresolved fields";
1333         UNREACHABLE();
1334       }, buffer, &error_msg));
1335   ASSERT_FALSE(RunValidation([](VerifierDeps::DexFileDeps& deps) {
1336         for (const auto& entry : deps.fields_) {
1337           if (entry.IsResolved()) {
1338             deps.fields_.insert(VerifierDeps::FieldResolution(entry.GetDexFieldIndex(),
1339                                                               entry.GetAccessFlags() - 1,
1340                                                               entry.GetDeclaringClassIndex()));
1341             return;
1342           }
1343         }
1344         LOG(FATAL) << "Could not find any resolved fields";
1345         UNREACHABLE();
1346       }, buffer, &error_msg));
1347   ASSERT_FALSE(RunValidation([](VerifierDeps::DexFileDeps& deps) {
1348         for (const auto& entry : deps.fields_) {
1349           constexpr dex::StringIndex kNewTypeIndex(0);
1350           if (entry.GetDeclaringClassIndex() != kNewTypeIndex) {
1351             deps.fields_.insert(VerifierDeps::FieldResolution(entry.GetDexFieldIndex(),
1352                                                               entry.GetAccessFlags(),
1353                                                               kNewTypeIndex));
1354             return;
1355           }
1356         }
1357         LOG(FATAL) << "Could not find any suitable fields";
1358         UNREACHABLE();
1359       }, buffer, &error_msg));
1360 
1361   // Mess with methods.
1362   ASSERT_FALSE(RunValidation([](VerifierDeps::DexFileDeps& deps) {
1363         std::set<VerifierDeps::MethodResolution>* methods = &deps.methods_;
1364         for (const auto& entry : *methods) {
1365           if (entry.IsResolved()) {
1366             methods->insert(VerifierDeps::MethodResolution(entry.GetDexMethodIndex(),
1367                                                           VerifierDeps::kUnresolvedMarker,
1368                                                           entry.GetDeclaringClassIndex()));
1369             return;
1370           }
1371         }
1372         LOG(FATAL) << "Could not find any resolved methods";
1373         UNREACHABLE();
1374       }, buffer, &error_msg));
1375   ASSERT_FALSE(RunValidation([](VerifierDeps::DexFileDeps& deps) {
1376         std::set<VerifierDeps::MethodResolution>* methods = &deps.methods_;
1377         for (const auto& entry : *methods) {
1378           if (!entry.IsResolved()) {
1379             constexpr dex::StringIndex kStringIndexZero(0);  // We know there is a class there.
1380             methods->insert(VerifierDeps::MethodResolution(0 /* we know there is a method there */,
1381                                                           VerifierDeps::kUnresolvedMarker - 1,
1382                                                           kStringIndexZero));
1383             return;
1384           }
1385         }
1386         LOG(FATAL) << "Could not find any unresolved methods";
1387         UNREACHABLE();
1388       }, buffer, &error_msg));
1389   ASSERT_FALSE(RunValidation([](VerifierDeps::DexFileDeps& deps) {
1390         std::set<VerifierDeps::MethodResolution>* methods = &deps.methods_;
1391         for (const auto& entry : *methods) {
1392           if (entry.IsResolved()) {
1393             methods->insert(VerifierDeps::MethodResolution(entry.GetDexMethodIndex(),
1394                                                           entry.GetAccessFlags() - 1,
1395                                                           entry.GetDeclaringClassIndex()));
1396             return;
1397           }
1398         }
1399         LOG(FATAL) << "Could not find any resolved methods";
1400         UNREACHABLE();
1401       }, buffer, &error_msg));
1402   ASSERT_FALSE(RunValidation([](VerifierDeps::DexFileDeps& deps) {
1403         std::set<VerifierDeps::MethodResolution>* methods = &deps.methods_;
1404         for (const auto& entry : *methods) {
1405           constexpr dex::StringIndex kNewTypeIndex(0);
1406           if (entry.IsResolved() && entry.GetDeclaringClassIndex() != kNewTypeIndex) {
1407             methods->insert(VerifierDeps::MethodResolution(entry.GetDexMethodIndex(),
1408                                                           entry.GetAccessFlags(),
1409                                                           kNewTypeIndex));
1410             return;
1411           }
1412         }
1413         LOG(FATAL) << "Could not find any suitable methods";
1414         UNREACHABLE();
1415       }, buffer, &error_msg));
1416 }
1417 
TEST_F(VerifierDepsTest,CompilerDriver)1418 TEST_F(VerifierDepsTest, CompilerDriver) {
1419   SetupCompilerDriver();
1420 
1421   // Test both multi-dex and single-dex configuration.
1422   for (const char* multi : { "MultiDex", static_cast<const char*>(nullptr) }) {
1423     // Test that the compiler driver behaves as expected when the dependencies
1424     // verify and when they don't verify.
1425     for (bool verify_failure : { false, true }) {
1426       {
1427         ScopedObjectAccess soa(Thread::Current());
1428         LoadDexFile(soa, "VerifierDeps", multi);
1429       }
1430       VerifyWithCompilerDriver(/* verifier_deps= */ nullptr);
1431 
1432       std::vector<uint8_t> buffer;
1433       verifier_deps_->Encode(dex_files_, &buffer);
1434 
1435       {
1436         ScopedObjectAccess soa(Thread::Current());
1437         LoadDexFile(soa, "VerifierDeps", multi);
1438       }
1439       VerifierDeps decoded_deps(dex_files_, /*output_only=*/ false);
1440       bool parsed = decoded_deps.ParseStoredData(dex_files_, ArrayRef<const uint8_t>(buffer));
1441       ASSERT_TRUE(parsed);
1442       if (verify_failure) {
1443         // Just taint the decoded VerifierDeps with one invalid entry.
1444         VerifierDeps::DexFileDeps* deps = decoded_deps.GetDexFileDeps(*primary_dex_file_);
1445         bool found = false;
1446         for (const auto& entry : deps->classes_) {
1447           if (entry.IsResolved()) {
1448             deps->classes_.insert(VerifierDeps::ClassResolution(
1449                 entry.GetDexTypeIndex(), VerifierDeps::kUnresolvedMarker));
1450             found = true;
1451             break;
1452           }
1453         }
1454         ASSERT_TRUE(found);
1455       }
1456       VerifyWithCompilerDriver(&decoded_deps);
1457 
1458       if (verify_failure) {
1459         ASSERT_FALSE(verifier_deps_ == nullptr);
1460         ASSERT_FALSE(verifier_deps_->Equals(decoded_deps));
1461       } else {
1462         VerifyClassStatus(decoded_deps);
1463       }
1464     }
1465   }
1466 }
1467 
TEST_F(VerifierDepsTest,MultiDexVerification)1468 TEST_F(VerifierDepsTest, MultiDexVerification) {
1469   VerifyDexFile("VerifierDepsMulti");
1470   ASSERT_EQ(NumberOfCompiledDexFiles(), 2u);
1471 
1472   ASSERT_TRUE(HasUnverifiedClass("LMySoftVerificationFailure;", *dex_files_[1]));
1473   ASSERT_TRUE(HasUnverifiedClass("LMySub1SoftVerificationFailure;", *dex_files_[0]));
1474   ASSERT_TRUE(HasUnverifiedClass("LMySub2SoftVerificationFailure;", *dex_files_[0]));
1475 
1476   std::vector<uint8_t> buffer;
1477   verifier_deps_->Encode(dex_files_, &buffer);
1478   ASSERT_FALSE(buffer.empty());
1479 }
1480 
TEST_F(VerifierDepsTest,NotAssignable_InterfaceWithClassInBoot)1481 TEST_F(VerifierDepsTest, NotAssignable_InterfaceWithClassInBoot) {
1482   ASSERT_TRUE(TestAssignabilityRecording(/* dst= */ "Ljava/lang/Exception;",
1483                                          /* src= */ "LIface;",
1484                                          /* is_strict= */ true,
1485                                          /* is_assignable= */ false));
1486   ASSERT_TRUE(HasAssignable("Ljava/lang/Exception;", "LIface;", false));
1487 }
1488 
TEST_F(VerifierDepsTest,Assignable_Arrays)1489 TEST_F(VerifierDepsTest, Assignable_Arrays) {
1490   ASSERT_TRUE(TestAssignabilityRecording(/* dst= */ "[LIface;",
1491                                          /* src= */ "[LMyClassExtendingInterface;",
1492                                          /* is_strict= */ false,
1493                                          /* is_assignable= */ true));
1494   ASSERT_FALSE(HasAssignable(
1495       "LIface;", "LMyClassExtendingInterface;", /* expected_is_assignable= */ true));
1496   ASSERT_FALSE(HasAssignable(
1497       "LIface;", "LMyClassExtendingInterface;", /* expected_is_assignable= */ false));
1498 }
1499 
1500 }  // namespace verifier
1501 }  // namespace art
1502