Prune methods in image DexCache based on referencing class.

This is a follow-up to
    https://android-review.googlesource.com/353911
where we did the same thing for fields.

Test: 163-app-image-methods
Test: testrunner.py --host
Test: testrunner.py --host --jit
Bug: 30627598
Change-Id: Ic24546f7e4a42f0f85e224a65ce1c8f7f1439340
diff --git a/compiler/image_writer.cc b/compiler/image_writer.cc
index e75f75b..4ff5dd2 100644
--- a/compiler/image_writer.cc
+++ b/compiler/image_writer.cc
@@ -951,11 +951,18 @@
     ArtMethod* method =
         mirror::DexCache::GetElementPtrSize(resolved_methods, i, target_ptr_size_);
     DCHECK(method != nullptr) << "Expected resolution method instead of null method";
-    mirror::Class* declaring_class = method->GetDeclaringClass();
+    // Check if the referenced class is in the image. Note that we want to check the referenced
+    // class rather than the declaring class to preserve the semantics, i.e. using a MethodId
+    // results in resolving the referenced class and that can for example throw OOME.
+    ObjPtr<mirror::Class> referencing_class = class_linker->LookupResolvedType(
+        dex_file,
+        dex_file.GetMethodId(i).class_idx_,
+        dex_cache,
+        class_loader);
     // Copied methods may be held live by a class which was not an image class but have a
     // declaring class which is an image class. Set it to the resolution method to be safe and
     // prevent dangling pointers.
-    if (method->IsCopied() || !KeepClass(declaring_class)) {
+    if (method->IsCopied() || !KeepClass(referencing_class)) {
       mirror::DexCache::SetElementPtrSize(resolved_methods,
                                           i,
                                           resolution_method,
@@ -963,8 +970,8 @@
     } else if (kIsDebugBuild) {
       // Check that the class is still in the classes table.
       ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
-      CHECK(class_linker->ClassInClassTable(declaring_class)) << "Class "
-          << Class::PrettyClass(declaring_class) << " not in class linker table";
+      CHECK(class_linker->ClassInClassTable(referencing_class)) << "Class "
+          << Class::PrettyClass(referencing_class) << " not in class linker table";
     }
   }
   // Prune fields and make the contents of the field array deterministic.
diff --git a/test/163-app-image-methods/expected.txt b/test/163-app-image-methods/expected.txt
new file mode 100644
index 0000000..f63e8e3
--- /dev/null
+++ b/test/163-app-image-methods/expected.txt
@@ -0,0 +1,3 @@
+Eating all memory.
+memoryWasAllocated = true
+match: true
diff --git a/test/163-app-image-methods/info.txt b/test/163-app-image-methods/info.txt
new file mode 100644
index 0000000..7b42ebc
--- /dev/null
+++ b/test/163-app-image-methods/info.txt
@@ -0,0 +1,3 @@
+Regression test for erroneously storing an ArtMethod* in the app image DexCache
+when the class from the corresponding MethodId is not in the app image, only the
+declaring class is.
diff --git a/test/163-app-image-methods/profile b/test/163-app-image-methods/profile
new file mode 100644
index 0000000..6585b94
--- /dev/null
+++ b/test/163-app-image-methods/profile
@@ -0,0 +1,2 @@
+LAAA/Base;
+LMain;
diff --git a/test/163-app-image-methods/run b/test/163-app-image-methods/run
new file mode 100644
index 0000000..7cc107a
--- /dev/null
+++ b/test/163-app-image-methods/run
@@ -0,0 +1,20 @@
+#!/bin/bash
+#
+# Copyright (C) 2017 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.
+
+# Use a profile to put specific classes in the app image.
+# Also run the compiler with -j1 to ensure specific class verification order.
+exec ${RUN} $@ --profile -Xcompiler-option --compiler-filter=speed-profile \
+    -Xcompiler-option -j1
diff --git a/test/163-app-image-methods/src/AAA/Base.java b/test/163-app-image-methods/src/AAA/Base.java
new file mode 100644
index 0000000..7ba71ad
--- /dev/null
+++ b/test/163-app-image-methods/src/AAA/Base.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package AAA;
+
+class Base {
+    // The method is public but the class is package-private.
+    public static int foo() { return 42; }
+}
diff --git a/test/163-app-image-methods/src/AAA/Derived.java b/test/163-app-image-methods/src/AAA/Derived.java
new file mode 100644
index 0000000..66e156f
--- /dev/null
+++ b/test/163-app-image-methods/src/AAA/Derived.java
@@ -0,0 +1,21 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package AAA;
+
+public class Derived extends Base {
+    // Allows public access to Base.foo() (Base is package-private) referenced as Derived.foo().
+}
diff --git a/test/163-app-image-methods/src/Main.java b/test/163-app-image-methods/src/Main.java
new file mode 100644
index 0000000..a995bb8
--- /dev/null
+++ b/test/163-app-image-methods/src/Main.java
@@ -0,0 +1,85 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+import AAA.Derived;
+
+public class Main {
+    public static void main(String[] args) {
+        try {
+            // Allocate memory for the "AAA.Derived" class name before eating memory.
+            String aaaDerivedName = "AAA.Derived";
+            System.out.println("Eating all memory.");
+            Object memory = eatAllMemory();
+
+            // This test assumes that Derived is not yet resolved. In some configurations
+            // (notably interp-ac), Derived is already resolved by verifying Main at run
+            // time. Therefore we cannot assume that we get a certain `value` and need to
+            // simply check for consistency, i.e. `value == another_value`.
+            int value = 0;
+            try {
+                // If the ArtMethod* is erroneously left in the DexCache, this
+                // shall succeed despite the class Derived being unresolved so
+                // far. Otherwise, we shall throw OOME trying to resolve it.
+                value = Derived.foo();
+            } catch (OutOfMemoryError e) {
+                value = -1;
+            }
+            int another_value = 0;
+            try {
+                // For comparison, try to resolve the class Derived directly.
+                Class.forName(aaaDerivedName, false, Main.class.getClassLoader());
+                another_value = 42;
+            } catch (OutOfMemoryError e) {
+                another_value = -1;
+            }
+            boolean memoryWasAllocated = (memory != null);
+            memory = null;
+            System.out.println("memoryWasAllocated = " + memoryWasAllocated);
+            System.out.println("match: " + (value == another_value));
+            if (value != another_value || (value != -1 && value != 42)) {
+                // Mismatch or unexpected value, print additional debugging information.
+                System.out.println("value: " + value);
+                System.out.println("another_value: " + another_value);
+            }
+        } catch (Throwable t) {
+            t.printStackTrace(System.out);
+        }
+    }
+
+    public static Object eatAllMemory() {
+      Object[] result = null;
+      int size = 1000000;
+      while (result == null && size != 0) {
+          try {
+              result = new Object[size];
+          } catch (OutOfMemoryError oome) {
+              size /= 2;
+          }
+      }
+      if (result != null) {
+          int index = 0;
+          while (index != result.length && size != 0) {
+              try {
+                  result[index] = new byte[size];
+                  ++index;
+              } catch (OutOfMemoryError oome) {
+                  size /= 2;
+              }
+          }
+      }
+      return result;
+  }
+}