Merge "Make libdexfile tests independent of runtime"
diff --git a/compiler/optimizing/graph_visualizer.cc b/compiler/optimizing/graph_visualizer.cc
index 6144162..bbf8c26 100644
--- a/compiler/optimizing/graph_visualizer.cc
+++ b/compiler/optimizing/graph_visualizer.cc
@@ -445,6 +445,9 @@
         ? GetGraph()->GetDexFile().PrettyMethod(invoke->GetDexMethodIndex(), kWithSignature)
         : method->PrettyMethod(kWithSignature);
     StartAttributeStream("method_name") << method_name;
+    StartAttributeStream("always_throws") << std::boolalpha
+                                          << invoke->AlwaysThrows()
+                                          << std::noboolalpha;
   }
 
   void VisitInvokeUnresolved(HInvokeUnresolved* invoke) OVERRIDE {
diff --git a/compiler/optimizing/inliner.cc b/compiler/optimizing/inliner.cc
index 035e5ce..b9ae0ff 100644
--- a/compiler/optimizing/inliner.cc
+++ b/compiler/optimizing/inliner.cc
@@ -392,10 +392,33 @@
   return single_impl;
 }
 
-static bool AlwaysThrows(ArtMethod* method)
+static bool IsMethodUnverified(CompilerDriver* const compiler_driver, ArtMethod* method)
     REQUIRES_SHARED(Locks::mutator_lock_) {
-  CodeItemDataAccessor accessor(method->DexInstructionData());
+  if (!method->GetDeclaringClass()->IsVerified()) {
+    if (Runtime::Current()->UseJitCompilation()) {
+      // We're at runtime, we know this is cold code if the class
+      // is not verified, so don't bother analyzing.
+      return true;
+    }
+    uint16_t class_def_idx = method->GetDeclaringClass()->GetDexClassDefIndex();
+    if (!compiler_driver->IsMethodVerifiedWithoutFailures(
+        method->GetDexMethodIndex(), class_def_idx, *method->GetDexFile())) {
+      // Method has soft or hard failures, don't analyze.
+      return true;
+    }
+  }
+  return false;
+}
+
+static bool AlwaysThrows(CompilerDriver* const compiler_driver, ArtMethod* method)
+    REQUIRES_SHARED(Locks::mutator_lock_) {
+  DCHECK(method != nullptr);
+  // Skip non-compilable and unverified methods.
+  if (!method->IsCompilable() || IsMethodUnverified(compiler_driver, method)) {
+    return false;
+  }
   // Skip native methods, methods with try blocks, and methods that are too large.
+  CodeItemDataAccessor accessor(method->DexInstructionData());
   if (!accessor.HasCodeItem() ||
       accessor.TriesSize() != 0 ||
       accessor.InsnsSizeInCodeUnits() > kMaximumNumberOfTotalInstructions) {
@@ -478,7 +501,7 @@
           MaybeRecordStat(stats_, MethodCompilationStat::kInlinedInvokeVirtualOrInterface);
         }
       }
-    } else if (!cha_devirtualize && AlwaysThrows(actual_method)) {
+    } else if (!cha_devirtualize && AlwaysThrows(compiler_driver_, actual_method)) {
       // Set always throws property for non-inlined method call with single target
       // (unless it was obtained through CHA, because that would imply we have
       // to add the CHA dependency, which seems not worth it).
@@ -1450,16 +1473,11 @@
         << " has soft failures un-handled by the compiler, so it cannot be inlined";
   }
 
-  if (!method->GetDeclaringClass()->IsVerified()) {
-    uint16_t class_def_idx = method->GetDeclaringClass()->GetDexClassDefIndex();
-    if (Runtime::Current()->UseJitCompilation() ||
-        !compiler_driver_->IsMethodVerifiedWithoutFailures(
-            method->GetDexMethodIndex(), class_def_idx, *method->GetDexFile())) {
-      LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedNotVerified)
-          << "Method " << method->PrettyMethod()
-          << " couldn't be verified, so it cannot be inlined";
-      return false;
-    }
+  if (IsMethodUnverified(compiler_driver_, method)) {
+    LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedNotVerified)
+        << "Method " << method->PrettyMethod()
+        << " couldn't be verified, so it cannot be inlined";
+    return false;
   }
 
   if (invoke_instruction->IsInvokeStaticOrDirect() &&
diff --git a/runtime/base/array_ref.h b/runtime/base/array_ref.h
index ef86512..2753c81 100644
--- a/runtime/base/array_ref.h
+++ b/runtime/base/array_ref.h
@@ -106,6 +106,12 @@
     return *this = ArrayRef(other);
   }
 
+  template <typename U>
+  static ArrayRef Cast(const ArrayRef<U>& src) {
+    return ArrayRef(reinterpret_cast<const T*>(src.data()),
+                    src.size() * sizeof(T) / sizeof(U));
+  }
+
   // Destructor.
   ~ArrayRef() = default;
 
diff --git a/runtime/gc/heap_test.cc b/runtime/gc/heap_test.cc
index 6d426c2..9d8e5d2 100644
--- a/runtime/gc/heap_test.cc
+++ b/runtime/gc/heap_test.cc
@@ -81,6 +81,7 @@
   void SetUpRuntimeOptions(RuntimeOptions* options) {
     CommonRuntimeTest::SetUpRuntimeOptions(options);
     options->push_back(std::make_pair("-Xzygote", nullptr));
+    options->push_back(std::make_pair("-Xno-hidden-api-checks", nullptr));
   }
 };
 
diff --git a/runtime/quicken_info.h b/runtime/quicken_info.h
index 52eca61..32f7005 100644
--- a/runtime/quicken_info.h
+++ b/runtime/quicken_info.h
@@ -50,16 +50,17 @@
     return index % kElementsPerIndex == 0;
   }
 
-  explicit QuickenInfoOffsetTableAccessor(const uint8_t* data, uint32_t max_index)
-      : table_(reinterpret_cast<const uint32_t*>(data)),
-        num_indices_(RoundUp(max_index, kElementsPerIndex) / kElementsPerIndex) {}
+  QuickenInfoOffsetTableAccessor(const ArrayRef<const uint8_t>& data, uint32_t max_index)
+      : table_(ArrayRef<const TableType>::Cast(data).SubArray(
+          0,
+          RoundUp(max_index, kElementsPerIndex) / kElementsPerIndex)) {}
 
   size_t SizeInBytes() const {
     return NumIndices() * sizeof(table_[0]);
   }
 
   uint32_t NumIndices() const {
-    return num_indices_;
+    return table_.size();
   }
 
   // Returns the offset for the index at or before the desired index. If the offset is for an index
@@ -69,17 +70,12 @@
     return table_[index / kElementsPerIndex];
   }
 
-  const uint8_t* DataEnd() const {
-    return reinterpret_cast<const uint8_t*>(table_ + NumIndices());
-  }
-
   static uint32_t Alignment() {
     return alignof(TableType);
   }
 
  private:
-  const TableType* table_;
-  uint32_t num_indices_;
+  const ArrayRef<const TableType> table_;
 };
 
 // QuickenInfoTable is a table of 16 bit dex indices. There is one slot for every instruction that
diff --git a/runtime/runtime.cc b/runtime/runtime.cc
index 25d83df..3afd320 100644
--- a/runtime/runtime.cc
+++ b/runtime/runtime.cc
@@ -1172,11 +1172,15 @@
 
   target_sdk_version_ = runtime_options.GetOrDefault(Opt::TargetSdkVersion);
 
-  // Check whether to enforce hidden API access checks. Zygote needs to be exempt
-  // but checks may be enabled for forked processes (see dalvik_system_ZygoteHooks).
-  if (is_zygote_ || runtime_options.Exists(Opt::NoHiddenApiChecks)) {
-    do_hidden_api_checks_ = false;
-  }
+  // Check whether to enforce hidden API access checks. The checks are disabled
+  // by default and we only enable them if:
+  // (a) runtime was started with a flag that enables the checks, or
+  // (b) Zygote forked a new process that is not exempt (see ZygoteHooks).
+  // TODO(dbrazdil): Turn the NoHiddenApiChecks negative flag into a positive one
+  // to clean up this logic.
+  do_hidden_api_checks_ = IsAotCompiler() && !runtime_options.Exists(Opt::NoHiddenApiChecks);
+  DCHECK(!is_zygote_ || !do_hidden_api_checks_)
+      << "Zygote should not be started with hidden API checks";
 
   no_sig_chain_ = runtime_options.Exists(Opt::NoSigChain);
   force_native_bridge_ = runtime_options.Exists(Opt::ForceNativeBridge);
diff --git a/runtime/vdex_file.cc b/runtime/vdex_file.cc
index 7428e98..0829c54 100644
--- a/runtime/vdex_file.cc
+++ b/runtime/vdex_file.cc
@@ -228,8 +228,7 @@
     const ArrayRef<const uint8_t>& quickening_info) const {
   // The offset a is in preheader right before the dex file.
   const uint32_t offset = GetQuickeningInfoTableOffset(source_dex_begin);
-  const uint8_t* data_ptr = quickening_info.data() + offset;
-  return QuickenInfoOffsetTableAccessor(data_ptr, num_method_ids);
+  return QuickenInfoOffsetTableAccessor(quickening_info.SubArray(offset), num_method_ids);
 }
 
 QuickenInfoOffsetTableAccessor VdexFile::GetQuickenInfoOffsetTable(
diff --git a/test/675-checker-unverified-method/expected.txt b/test/675-checker-unverified-method/expected.txt
new file mode 100644
index 0000000..b0aad4d
--- /dev/null
+++ b/test/675-checker-unverified-method/expected.txt
@@ -0,0 +1 @@
+passed
diff --git a/test/675-checker-unverified-method/info.txt b/test/675-checker-unverified-method/info.txt
new file mode 100644
index 0000000..667211a
--- /dev/null
+++ b/test/675-checker-unverified-method/info.txt
@@ -0,0 +1 @@
+Make sure analysis of unverified method is skipped.
diff --git a/test/675-checker-unverified-method/smali/TestCase.smali b/test/675-checker-unverified-method/smali/TestCase.smali
new file mode 100644
index 0000000..673b3f2
--- /dev/null
+++ b/test/675-checker-unverified-method/smali/TestCase.smali
@@ -0,0 +1,55 @@
+# Copyright (C) 2018 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+.class public LTestCase;
+
+.super Ljava/lang/Object;
+
+#
+# Ensure foo() does not analyze unverified bad() always-throws property.
+#
+## CHECK-START: void TestCase.foo(java.lang.Object) inliner (after)
+## CHECK-DAG: InvokeStaticOrDirect method_name:TestCase.bar always_throws:true
+## CHECK-DAG: InvokeStaticOrDirect method_name:TestCase.bad always_throws:false
+.method public static foo(Ljava/lang/Object;)V
+  .registers 1
+  if-nez v0, :Skip1
+  invoke-static {}, LTestCase;->bar()V
+:Skip1
+  if-nez v0, :Skip2
+  invoke-static {}, LTestCase;->bad()Lwont/be/Resolvable;
+:Skip2
+  return-void
+.end method
+
+#
+# Method bar() that verifies (but is never called).
+#
+.method public static bar()V
+  .registers 1
+  new-instance v0, Ljava/lang/RuntimeException;
+  invoke-direct {v0}, Ljava/lang/RuntimeException;-><init>()V
+  throw v0
+.end method
+
+#
+# Method bad() that fails to verify (but is never called).
+#
+.method public static bad()Lwont/be/Resolvable;
+  .registers 1
+  invoke-static {}, LTestCase;->bar()Lwont/be/Resolvable;
+  move-result-object v0
+  throw v0
+.end method
+
diff --git a/test/675-checker-unverified-method/src/Main.java b/test/675-checker-unverified-method/src/Main.java
new file mode 100644
index 0000000..0cdb2fe
--- /dev/null
+++ b/test/675-checker-unverified-method/src/Main.java
@@ -0,0 +1,28 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Ensure unverified method is not analyzed.
+ */
+public class Main {
+  public static void main(String[] args) throws Exception {
+    Object o = new Object();
+    Class<?> c = Class.forName("TestCase");
+    Object[] arguments = { o };
+    c.getMethod("foo", Object.class).invoke(null, arguments);
+    System.out.println("passed");
+  }
+}
diff --git a/test/956-methodhandles/src/Main.java b/test/956-methodhandles/src/Main.java
index cb06e42..1ddef03 100644
--- a/test/956-methodhandles/src/Main.java
+++ b/test/956-methodhandles/src/Main.java
@@ -22,6 +22,7 @@
 import java.lang.invoke.WrongMethodTypeException;
 import java.lang.reflect.Constructor;
 import java.lang.reflect.Field;
+import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Method;
 import java.nio.charset.Charset;
 import java.nio.charset.StandardCharsets;
@@ -79,6 +80,7 @@
     testVariableArity();
     testVariableArity_MethodHandles_bind();
     testRevealDirect();
+    testReflectiveCalls();
   }
 
   public static void testfindSpecial_invokeSuperBehaviour() throws Throwable {
@@ -1624,4 +1626,20 @@
     assertEquals(field, info.reflectAs(Field.class, MethodHandles.lookup()));
     assertEquals(MethodType.methodType(String.class), info.getMethodType());
   }
+
+  public static void testReflectiveCalls() throws Throwable {
+    String[] methodNames = { "invoke", "invokeExact" };
+    for (String methodName : methodNames) {
+      Method invokeMethod = MethodHandle.class.getMethod(methodName, Object[].class);
+      MethodHandle instance =
+          MethodHandles.lookup().findVirtual(java.io.PrintStream.class, "println",
+                                             MethodType.methodType(void.class, String.class));
+      try {
+        invokeMethod.invoke(instance, new Object[] { new Object[] { Integer.valueOf(1) } } );
+        fail();
+      } catch (InvocationTargetException ite) {
+        assertEquals(ite.getCause().getClass(), UnsupportedOperationException.class);
+      }
+    }
+  }
 }
diff --git a/tools/external_oj_libjdwp_art_failures.txt b/tools/external_oj_libjdwp_art_failures.txt
index 88ffa6e..828c0aa 100644
--- a/tools/external_oj_libjdwp_art_failures.txt
+++ b/tools/external_oj_libjdwp_art_failures.txt
@@ -53,6 +53,19 @@
            "org.apache.harmony.jpda.tests.jdwp.VirtualMachine.CapabilitiesNewTest#testCapabilitiesNew001" ]
 },
 {
+  description: "Test is flaky",
+  result: EXEC_FAILED,
+  bug: 69121056,
+  name: "org.apache.harmony.jpda.tests.jdwp.ObjectReference.IsCollectedTest#testIsCollected001"
+},
+{
+  description: "Test is flaky",
+  result: EXEC_FAILED,
+  bug: 70958370,
+  names: [ "org.apache.harmony.jpda.tests.jdwp.ObjectReference.EnableCollectionTest#testEnableCollection001",
+           "org.apache.harmony.jpda.tests.jdwp.MultiSession.EnableCollectionTest#testEnableCollection001" ]
+},
+{
   description: "Test crashes",
   result: EXEC_FAILED,
   bug: 69591477,
diff --git a/tools/prebuilt_libjdwp_art_failures.txt b/tools/prebuilt_libjdwp_art_failures.txt
index b0475bb..a9d268d 100644
--- a/tools/prebuilt_libjdwp_art_failures.txt
+++ b/tools/prebuilt_libjdwp_art_failures.txt
@@ -102,12 +102,25 @@
            "org.apache.harmony.jpda.tests.jdwp.VirtualMachine.CapabilitiesNewTest#testCapabilitiesNew001" ]
 },
 {
+  description: "Test is flaky",
+  result: EXEC_FAILED,
+  bug: 69121056,
+  name: "org.apache.harmony.jpda.tests.jdwp.ObjectReference.IsCollectedTest#testIsCollected001"
+},
+{
   description: "Test for ddms extensions that are not implemented for prebuilt-libjdwp",
   result: EXEC_FAILED,
   bug: 69169846,
   name: "org.apache.harmony.jpda.tests.jdwp.DDM.DDMTest#testChunk001"
 },
 {
+  description: "Test is flakey",
+  result: EXEC_FAILED,
+  bug: 70958370,
+  names: [ "org.apache.harmony.jpda.tests.jdwp.ObjectReference.EnableCollectionTest#testEnableCollection001",
+           "org.apache.harmony.jpda.tests.jdwp.MultiSession.EnableCollectionTest#testEnableCollection001" ]
+},
+{
   description: "Test crashes",
   result: EXEC_FAILED,
   bug: 69591477,