Merge "[veridex] Detect reflection uses." into pi-dev
diff --git a/build/Android.gtest.mk b/build/Android.gtest.mk
index 8681642..b342abe 100644
--- a/build/Android.gtest.mk
+++ b/build/Android.gtest.mk
@@ -37,6 +37,7 @@
   ExceptionHandle \
   GetMethodSignature \
   HiddenApi \
+  HiddenApiSignatures \
   ImageLayoutA \
   ImageLayoutB \
   IMTA \
@@ -160,6 +161,7 @@
 ART_GTEST_dex2oat_image_test_DEX_DEPS := $(ART_GTEST_dex2oat_environment_tests_DEX_DEPS) Statics VerifierDeps
 ART_GTEST_exception_test_DEX_DEPS := ExceptionHandle
 ART_GTEST_hiddenapi_test_DEX_DEPS := HiddenApi
+ART_GTEST_hidden_api_test_DEX_DEPS := HiddenApiSignatures
 ART_GTEST_image_test_DEX_DEPS := ImageLayoutA ImageLayoutB DefaultMethods
 ART_GTEST_imtable_test_DEX_DEPS := IMTA IMTB
 ART_GTEST_instrumentation_test_DEX_DEPS := Instrumentation
diff --git a/openjdkjvmti/ti_stack.cc b/openjdkjvmti/ti_stack.cc
index 41a649b..4526be4 100644
--- a/openjdkjvmti/ti_stack.cc
+++ b/openjdkjvmti/ti_stack.cc
@@ -925,7 +925,9 @@
     if (target != self) {
       called_method = true;
       // RequestSynchronousCheckpoint releases the thread_list_lock_ as a part of its execution.
-      if (!target->RequestSynchronousCheckpoint(&closure)) {
+      // Since this deals with object references we need to avoid going to sleep.
+      art::ScopedAssertNoThreadSuspension sants("Getting owned monitor usage");
+      if (!target->RequestSynchronousCheckpoint(&closure, art::ThreadState::kRunnable)) {
         return ERR(THREAD_NOT_ALIVE);
       }
     } else {
diff --git a/runtime/Android.bp b/runtime/Android.bp
index 51fbb2e..c0f1c36 100644
--- a/runtime/Android.bp
+++ b/runtime/Android.bp
@@ -87,6 +87,7 @@
         "gc/space/zygote_space.cc",
         "gc/task_processor.cc",
         "gc/verification.cc",
+        "hidden_api.cc",
         "hprof/hprof.cc",
         "image.cc",
         "index_bss_mapping.cc",
@@ -572,6 +573,7 @@
         "gc/task_processor_test.cc",
         "gtest_test.cc",
         "handle_scope_test.cc",
+        "hidden_api_test.cc",
         "imtable_test.cc",
         "indenter_test.cc",
         "indirect_reference_table_test.cc",
diff --git a/runtime/class_linker.cc b/runtime/class_linker.cc
index 6229822..879301c 100644
--- a/runtime/class_linker.cc
+++ b/runtime/class_linker.cc
@@ -72,6 +72,7 @@
 #include "gc/space/space-inl.h"
 #include "gc_root-inl.h"
 #include "handle_scope-inl.h"
+#include "hidden_api.h"
 #include "image-inl.h"
 #include "imt_conflict_table.h"
 #include "imtable-inl.h"
diff --git a/runtime/hidden_api.cc b/runtime/hidden_api.cc
new file mode 100644
index 0000000..f0b36a0
--- /dev/null
+++ b/runtime/hidden_api.cc
@@ -0,0 +1,172 @@
+/*
+ * 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.
+ */
+
+#include "hidden_api.h"
+
+#include "base/dumpable.h"
+
+namespace art {
+namespace hiddenapi {
+
+static inline std::ostream& operator<<(std::ostream& os, AccessMethod value) {
+  switch (value) {
+    case kReflection:
+      os << "reflection";
+      break;
+    case kJNI:
+      os << "JNI";
+      break;
+    case kLinking:
+      os << "linking";
+      break;
+  }
+  return os;
+}
+
+static constexpr bool EnumsEqual(EnforcementPolicy policy, HiddenApiAccessFlags::ApiList apiList) {
+  return static_cast<int>(policy) == static_cast<int>(apiList);
+}
+
+// GetMemberAction-related static_asserts.
+static_assert(
+    EnumsEqual(EnforcementPolicy::kAllLists, HiddenApiAccessFlags::kLightGreylist) &&
+    EnumsEqual(EnforcementPolicy::kDarkGreyAndBlackList, HiddenApiAccessFlags::kDarkGreylist) &&
+    EnumsEqual(EnforcementPolicy::kBlacklistOnly, HiddenApiAccessFlags::kBlacklist),
+    "Mismatch between EnforcementPolicy and ApiList enums");
+static_assert(
+    EnforcementPolicy::kAllLists < EnforcementPolicy::kDarkGreyAndBlackList &&
+    EnforcementPolicy::kDarkGreyAndBlackList < EnforcementPolicy::kBlacklistOnly,
+    "EnforcementPolicy values ordering not correct");
+
+namespace detail {
+
+MemberSignature::MemberSignature(ArtField* field) {
+  member_type_ = "field";
+  signature_parts_ = {
+    field->GetDeclaringClass()->GetDescriptor(&tmp_),
+    "->",
+    field->GetName(),
+    ":",
+    field->GetTypeDescriptor()
+  };
+}
+
+MemberSignature::MemberSignature(ArtMethod* method) {
+  member_type_ = "method";
+  signature_parts_ = {
+    method->GetDeclaringClass()->GetDescriptor(&tmp_),
+    "->",
+    method->GetName(),
+    method->GetSignature().ToString()
+  };
+}
+
+bool MemberSignature::DoesPrefixMatch(const std::string& prefix) const {
+  size_t pos = 0;
+  for (const std::string& part : signature_parts_) {
+    size_t count = std::min(prefix.length() - pos, part.length());
+    if (prefix.compare(pos, count, part, 0, count) == 0) {
+      pos += count;
+    } else {
+      return false;
+    }
+  }
+  // We have a complete match if all parts match (we exit the loop without
+  // returning) AND we've matched the whole prefix.
+  return pos == prefix.length();
+}
+
+bool MemberSignature::IsExempted(const std::vector<std::string>& exemptions) {
+  for (const std::string& exemption : exemptions) {
+    if (DoesPrefixMatch(exemption)) {
+      return true;
+    }
+  }
+  return false;
+}
+
+void MemberSignature::Dump(std::ostream& os) const {
+  for (std::string part : signature_parts_) {
+    os << part;
+  }
+}
+
+void MemberSignature::WarnAboutAccess(AccessMethod access_method,
+                                      HiddenApiAccessFlags::ApiList list) {
+  LOG(WARNING) << "Accessing hidden " << member_type_ << " " << Dumpable<MemberSignature>(*this)
+               << " (" << list << ", " << access_method << ")";
+}
+
+template<typename T>
+bool ShouldBlockAccessToMemberImpl(T* member, Action action, AccessMethod access_method) {
+  // Get the signature, we need it later.
+  MemberSignature member_signature(member);
+
+  Runtime* runtime = Runtime::Current();
+
+  if (action == kDeny) {
+    // If we were about to deny, check for an exemption first.
+    // Exempted APIs are treated as light grey list.
+    if (member_signature.IsExempted(runtime->GetHiddenApiExemptions())) {
+      action = kAllowButWarn;
+      // Avoid re-examining the exemption list next time.
+      // Note this results in the warning below showing "light greylist", which
+      // seems like what one would expect. Exemptions effectively add new members to
+      // the light greylist.
+      member->SetAccessFlags(HiddenApiAccessFlags::EncodeForRuntime(
+              member->GetAccessFlags(), HiddenApiAccessFlags::kLightGreylist));
+    }
+  }
+
+  // Print a log message with information about this class member access.
+  // We do this regardless of whether we block the access or not.
+  member_signature.WarnAboutAccess(access_method,
+      HiddenApiAccessFlags::DecodeFromRuntime(member->GetAccessFlags()));
+
+  if (action == kDeny) {
+    // Block access
+    return true;
+  }
+
+  // Allow access to this member but print a warning.
+  DCHECK(action == kAllowButWarn || action == kAllowButWarnAndToast);
+
+  // Depending on a runtime flag, we might move the member into whitelist and
+  // skip the warning the next time the member is accessed.
+  if (runtime->ShouldDedupeHiddenApiWarnings()) {
+    member->SetAccessFlags(HiddenApiAccessFlags::EncodeForRuntime(
+        member->GetAccessFlags(), HiddenApiAccessFlags::kWhitelist));
+  }
+
+  // If this action requires a UI warning, set the appropriate flag.
+  if (action == kAllowButWarnAndToast || runtime->ShouldAlwaysSetHiddenApiWarningFlag()) {
+    runtime->SetPendingHiddenApiWarning(true);
+  }
+
+  return false;
+}
+
+// Need to instantiate this.
+template bool ShouldBlockAccessToMemberImpl<ArtField>(ArtField* member,
+                                                      Action action,
+                                                      AccessMethod access_method);
+template bool ShouldBlockAccessToMemberImpl<ArtMethod>(ArtMethod* member,
+                                                       Action action,
+                                                       AccessMethod access_method);
+
+}  // namespace detail
+}  // namespace hiddenapi
+}  // namespace art
diff --git a/runtime/hidden_api.h b/runtime/hidden_api.h
index dbe776e..cc6c146 100644
--- a/runtime/hidden_api.h
+++ b/runtime/hidden_api.h
@@ -19,6 +19,7 @@
 
 #include "art_field-inl.h"
 #include "art_method-inl.h"
+#include "base/mutex.h"
 #include "dex/hidden_api_access_flags.h"
 #include "mirror/class-inl.h"
 #include "reflection.h"
@@ -57,25 +58,6 @@
   kLinking,
 };
 
-inline std::ostream& operator<<(std::ostream& os, AccessMethod value) {
-  switch (value) {
-    case kReflection:
-      os << "reflection";
-      break;
-    case kJNI:
-      os << "JNI";
-      break;
-    case kLinking:
-      os << "linking";
-      break;
-  }
-  return os;
-}
-
-static constexpr bool EnumsEqual(EnforcementPolicy policy, HiddenApiAccessFlags::ApiList apiList) {
-  return static_cast<int>(policy) == static_cast<int>(apiList);
-}
-
 inline Action GetMemberAction(uint32_t access_flags) {
   EnforcementPolicy policy = Runtime::Current()->GetHiddenApiEnforcementPolicy();
   if (policy == EnforcementPolicy::kNoChecks) {
@@ -88,16 +70,7 @@
     return kAllow;
   }
   // The logic below relies on equality of values in the enums EnforcementPolicy and
-  // HiddenApiAccessFlags::ApiList, and their ordering. Assert that this is as expected.
-  static_assert(
-      EnumsEqual(EnforcementPolicy::kAllLists, HiddenApiAccessFlags::kLightGreylist) &&
-      EnumsEqual(EnforcementPolicy::kDarkGreyAndBlackList, HiddenApiAccessFlags::kDarkGreylist) &&
-      EnumsEqual(EnforcementPolicy::kBlacklistOnly, HiddenApiAccessFlags::kBlacklist),
-      "Mismatch between EnforcementPolicy and ApiList enums");
-  static_assert(
-      EnforcementPolicy::kAllLists < EnforcementPolicy::kDarkGreyAndBlackList &&
-      EnforcementPolicy::kDarkGreyAndBlackList < EnforcementPolicy::kBlacklistOnly,
-      "EnforcementPolicy values ordering not correct");
+  // HiddenApiAccessFlags::ApiList, and their ordering. Assertions are in hidden_api.cc.
   if (static_cast<int>(policy) > static_cast<int>(api_list)) {
     return api_list == HiddenApiAccessFlags::kDarkGreylist
         ? kAllowButWarnAndToast
@@ -107,27 +80,56 @@
   }
 }
 
-// Issue a warning about field access.
-inline void WarnAboutMemberAccess(ArtField* field, AccessMethod access_method)
+// Implementation details. DO NOT ACCESS DIRECTLY.
+namespace detail {
+
+// Class to encapsulate the signature of a member (ArtField or ArtMethod). This
+// is used as a helper when matching prefixes, and when logging the signature.
+class MemberSignature {
+ private:
+  std::string member_type_;
+  std::vector<std::string> signature_parts_;
+  std::string tmp_;
+
+ public:
+  explicit MemberSignature(ArtField* field) REQUIRES_SHARED(Locks::mutator_lock_);
+  explicit MemberSignature(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_);
+
+  void Dump(std::ostream& os) const;
+
+  // Performs prefix match on this member. Since the full member signature is
+  // composed of several parts, we match each part in turn (rather than
+  // building the entire thing in memory and performing a simple prefix match)
+  bool DoesPrefixMatch(const std::string& prefix) const;
+
+  bool IsExempted(const std::vector<std::string>& exemptions);
+
+  void WarnAboutAccess(AccessMethod access_method, HiddenApiAccessFlags::ApiList list);
+};
+
+template<typename T>
+bool ShouldBlockAccessToMemberImpl(T* member,
+                                   Action action,
+                                   AccessMethod access_method)
+    REQUIRES_SHARED(Locks::mutator_lock_);
+
+// Returns true if the caller is either loaded by the boot strap class loader or comes from
+// a dex file located in ${ANDROID_ROOT}/framework/.
+ALWAYS_INLINE
+inline bool IsCallerInPlatformDex(ObjPtr<mirror::ClassLoader> caller_class_loader,
+                                  ObjPtr<mirror::DexCache> caller_dex_cache)
     REQUIRES_SHARED(Locks::mutator_lock_) {
-  std::string tmp;
-  LOG(WARNING) << "Accessing hidden field "
-               << field->GetDeclaringClass()->GetDescriptor(&tmp) << "->"
-               << field->GetName() << ":" << field->GetTypeDescriptor()
-               << " (" << HiddenApiAccessFlags::DecodeFromRuntime(field->GetAccessFlags())
-               << ", " << access_method << ")";
+  if (caller_class_loader.IsNull()) {
+    return true;
+  } else if (caller_dex_cache.IsNull()) {
+    return false;
+  } else {
+    const DexFile* caller_dex_file = caller_dex_cache->GetDexFile();
+    return caller_dex_file != nullptr && caller_dex_file->IsPlatformDexFile();
+  }
 }
 
-// Issue a warning about method access.
-inline void WarnAboutMemberAccess(ArtMethod* method, AccessMethod access_method)
-    REQUIRES_SHARED(Locks::mutator_lock_) {
-  std::string tmp;
-  LOG(WARNING) << "Accessing hidden method "
-               << method->GetDeclaringClass()->GetDescriptor(&tmp) << "->"
-               << method->GetName() << method->GetSignature().ToString()
-               << " (" << HiddenApiAccessFlags::DecodeFromRuntime(method->GetAccessFlags())
-               << ", " << access_method << ")";
-}
+}  // namespace detail
 
 // Returns true if access to `member` should be denied to the caller of the
 // reflective query. The decision is based on whether the caller is in the
@@ -157,54 +159,13 @@
   }
 
   // Member is hidden and caller is not in the platform.
-
-  // Print a log message with information about this class member access.
-  // We do this regardless of whether we block the access or not.
-  WarnAboutMemberAccess(member, access_method);
-
-  if (action == kDeny) {
-    // Block access
-    return true;
-  }
-
-  // Allow access to this member but print a warning.
-  DCHECK(action == kAllowButWarn || action == kAllowButWarnAndToast);
-
-  Runtime* runtime = Runtime::Current();
-
-  // Depending on a runtime flag, we might move the member into whitelist and
-  // skip the warning the next time the member is accessed.
-  if (runtime->ShouldDedupeHiddenApiWarnings()) {
-    member->SetAccessFlags(HiddenApiAccessFlags::EncodeForRuntime(
-        member->GetAccessFlags(), HiddenApiAccessFlags::kWhitelist));
-  }
-
-  // If this action requires a UI warning, set the appropriate flag.
-  if (action == kAllowButWarnAndToast || runtime->ShouldAlwaysSetHiddenApiWarningFlag()) {
-    runtime->SetPendingHiddenApiWarning(true);
-  }
-
-  return false;
-}
-
-// Returns true if the caller is either loaded by the boot strap class loader or comes from
-// a dex file located in ${ANDROID_ROOT}/framework/.
-inline bool IsCallerInPlatformDex(ObjPtr<mirror::ClassLoader> caller_class_loader,
-                                  ObjPtr<mirror::DexCache> caller_dex_cache)
-    REQUIRES_SHARED(Locks::mutator_lock_) {
-  if (caller_class_loader.IsNull()) {
-    return true;
-  } else if (caller_dex_cache.IsNull()) {
-    return false;
-  } else {
-    const DexFile* caller_dex_file = caller_dex_cache->GetDexFile();
-    return caller_dex_file != nullptr && caller_dex_file->IsPlatformDexFile();
-  }
+  return detail::ShouldBlockAccessToMemberImpl(member, action, access_method);
 }
 
 inline bool IsCallerInPlatformDex(ObjPtr<mirror::Class> caller)
     REQUIRES_SHARED(Locks::mutator_lock_) {
-  return !caller.IsNull() && IsCallerInPlatformDex(caller->GetClassLoader(), caller->GetDexCache());
+  return !caller.IsNull() &&
+      detail::IsCallerInPlatformDex(caller->GetClassLoader(), caller->GetDexCache());
 }
 
 // Returns true if access to `member` should be denied to a caller loaded with
@@ -216,7 +177,7 @@
                                       ObjPtr<mirror::DexCache> caller_dex_cache,
                                       AccessMethod access_method)
     REQUIRES_SHARED(Locks::mutator_lock_) {
-  bool caller_in_platform = IsCallerInPlatformDex(caller_class_loader, caller_dex_cache);
+  bool caller_in_platform = detail::IsCallerInPlatformDex(caller_class_loader, caller_dex_cache);
   return ShouldBlockAccessToMember(member,
                                    /* thread */ nullptr,
                                    [caller_in_platform] (Thread*) { return caller_in_platform; },
diff --git a/runtime/hidden_api_test.cc b/runtime/hidden_api_test.cc
new file mode 100644
index 0000000..5a31dd4
--- /dev/null
+++ b/runtime/hidden_api_test.cc
@@ -0,0 +1,275 @@
+/*
+ * 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.
+ */
+
+#include "hidden_api.h"
+
+#include "common_runtime_test.h"
+#include "jni_internal.h"
+
+namespace art {
+
+using hiddenapi::detail::MemberSignature;
+
+class HiddenApiTest : public CommonRuntimeTest {
+ protected:
+  void SetUp() OVERRIDE {
+    // Do the normal setup.
+    CommonRuntimeTest::SetUp();
+    self_ = Thread::Current();
+    self_->TransitionFromSuspendedToRunnable();
+    LoadDex("HiddenApiSignatures");
+    bool started = runtime_->Start();
+    CHECK(started);
+
+    class1_field1_ = getArtField("mypackage/packagea/Class1", "field1", "I");
+    class1_field12_ = getArtField("mypackage/packagea/Class1", "field12", "I");
+    class1_init_ = getArtMethod("mypackage/packagea/Class1", "<init>", "()V");
+    class1_method1_ = getArtMethod("mypackage/packagea/Class1", "method1", "()V");
+    class1_method1_i_ = getArtMethod("mypackage/packagea/Class1", "method1", "(I)V");
+    class1_method12_ = getArtMethod("mypackage/packagea/Class1", "method12", "()V");
+    class12_field1_ = getArtField("mypackage/packagea/Class12", "field1", "I");
+    class12_method1_ = getArtMethod("mypackage/packagea/Class12", "method1", "()V");
+    class2_field1_ = getArtField("mypackage/packagea/Class2", "field1", "I");
+    class2_method1_ = getArtMethod("mypackage/packagea/Class2", "method1", "()V");
+    class2_method1_i_ = getArtMethod("mypackage/packagea/Class2", "method1", "(I)V");
+    class3_field1_ = getArtField("mypackage/packageb/Class3", "field1", "I");
+    class3_method1_ = getArtMethod("mypackage/packageb/Class3", "method1", "()V");
+    class3_method1_i_ = getArtMethod("mypackage/packageb/Class3", "method1", "(I)V");
+  }
+
+  ArtMethod* getArtMethod(const char* class_name, const char* name, const char* signature) {
+    JNIEnv* env = Thread::Current()->GetJniEnv();
+    jclass klass = env->FindClass(class_name);
+    jmethodID method_id = env->GetMethodID(klass, name, signature);
+    ArtMethod* art_method = jni::DecodeArtMethod(method_id);
+    return art_method;
+  }
+
+  ArtField* getArtField(const char* class_name, const char* name, const char* signature) {
+    JNIEnv* env = Thread::Current()->GetJniEnv();
+    jclass klass = env->FindClass(class_name);
+    jfieldID field_id = env->GetFieldID(klass, name, signature);
+    ArtField* art_field = jni::DecodeArtField(field_id);
+    return art_field;
+  }
+
+ protected:
+  Thread* self_;
+  ArtField* class1_field1_;
+  ArtField* class1_field12_;
+  ArtMethod* class1_init_;
+  ArtMethod* class1_method1_;
+  ArtMethod* class1_method1_i_;
+  ArtMethod* class1_method12_;
+  ArtField* class12_field1_;
+  ArtMethod* class12_method1_;
+  ArtField* class2_field1_;
+  ArtMethod* class2_method1_;
+  ArtMethod* class2_method1_i_;
+  ArtField* class3_field1_;
+  ArtMethod* class3_method1_;
+  ArtMethod* class3_method1_i_;
+};
+
+TEST_F(HiddenApiTest, CheckMembersRead) {
+  ASSERT_NE(nullptr, class1_field1_);
+  ASSERT_NE(nullptr, class1_field12_);
+  ASSERT_NE(nullptr, class1_init_);
+  ASSERT_NE(nullptr, class1_method1_);
+  ASSERT_NE(nullptr, class1_method1_i_);
+  ASSERT_NE(nullptr, class1_method12_);
+  ASSERT_NE(nullptr, class12_field1_);
+  ASSERT_NE(nullptr, class12_method1_);
+  ASSERT_NE(nullptr, class2_field1_);
+  ASSERT_NE(nullptr, class2_method1_);
+  ASSERT_NE(nullptr, class2_method1_i_);
+  ASSERT_NE(nullptr, class3_field1_);
+  ASSERT_NE(nullptr, class3_method1_);
+  ASSERT_NE(nullptr, class3_method1_i_);
+}
+
+TEST_F(HiddenApiTest, CheckEverythingMatchesL) {
+  ScopedObjectAccess soa(self_);
+  std::string prefix("L");
+  ASSERT_TRUE(MemberSignature(class1_field1_).DoesPrefixMatch(prefix));
+  ASSERT_TRUE(MemberSignature(class1_field12_).DoesPrefixMatch(prefix));
+  ASSERT_TRUE(MemberSignature(class1_init_).DoesPrefixMatch(prefix));
+  ASSERT_TRUE(MemberSignature(class1_method1_).DoesPrefixMatch(prefix));
+  ASSERT_TRUE(MemberSignature(class1_method1_i_).DoesPrefixMatch(prefix));
+  ASSERT_TRUE(MemberSignature(class12_field1_).DoesPrefixMatch(prefix));
+  ASSERT_TRUE(MemberSignature(class12_method1_).DoesPrefixMatch(prefix));
+  ASSERT_TRUE(MemberSignature(class1_method12_).DoesPrefixMatch(prefix));
+  ASSERT_TRUE(MemberSignature(class2_field1_).DoesPrefixMatch(prefix));
+  ASSERT_TRUE(MemberSignature(class2_method1_).DoesPrefixMatch(prefix));
+  ASSERT_TRUE(MemberSignature(class2_method1_i_).DoesPrefixMatch(prefix));
+  ASSERT_TRUE(MemberSignature(class3_field1_).DoesPrefixMatch(prefix));
+  ASSERT_TRUE(MemberSignature(class3_method1_).DoesPrefixMatch(prefix));
+  ASSERT_TRUE(MemberSignature(class3_method1_i_).DoesPrefixMatch(prefix));
+}
+
+TEST_F(HiddenApiTest, CheckPackageMatch) {
+  ScopedObjectAccess soa(self_);
+  std::string prefix("Lmypackage/packagea/");
+  ASSERT_TRUE(MemberSignature(class1_field1_).DoesPrefixMatch(prefix));
+  ASSERT_TRUE(MemberSignature(class1_field12_).DoesPrefixMatch(prefix));
+  ASSERT_TRUE(MemberSignature(class1_init_).DoesPrefixMatch(prefix));
+  ASSERT_TRUE(MemberSignature(class1_method1_).DoesPrefixMatch(prefix));
+  ASSERT_TRUE(MemberSignature(class1_method1_i_).DoesPrefixMatch(prefix));
+  ASSERT_TRUE(MemberSignature(class1_method12_).DoesPrefixMatch(prefix));
+  ASSERT_TRUE(MemberSignature(class12_field1_).DoesPrefixMatch(prefix));
+  ASSERT_TRUE(MemberSignature(class12_method1_).DoesPrefixMatch(prefix));
+  ASSERT_TRUE(MemberSignature(class2_field1_).DoesPrefixMatch(prefix));
+  ASSERT_TRUE(MemberSignature(class2_method1_).DoesPrefixMatch(prefix));
+  ASSERT_TRUE(MemberSignature(class2_method1_i_).DoesPrefixMatch(prefix));
+  ASSERT_FALSE(MemberSignature(class3_field1_).DoesPrefixMatch(prefix));
+  ASSERT_FALSE(MemberSignature(class3_method1_).DoesPrefixMatch(prefix));
+  ASSERT_FALSE(MemberSignature(class3_method1_i_).DoesPrefixMatch(prefix));
+}
+
+TEST_F(HiddenApiTest, CheckClassMatch) {
+  ScopedObjectAccess soa(self_);
+  std::string prefix("Lmypackage/packagea/Class1");
+  ASSERT_TRUE(MemberSignature(class1_field1_).DoesPrefixMatch(prefix));
+  ASSERT_TRUE(MemberSignature(class1_field12_).DoesPrefixMatch(prefix));
+  ASSERT_TRUE(MemberSignature(class1_init_).DoesPrefixMatch(prefix));
+  ASSERT_TRUE(MemberSignature(class1_method1_).DoesPrefixMatch(prefix));
+  ASSERT_TRUE(MemberSignature(class1_method1_i_).DoesPrefixMatch(prefix));
+  ASSERT_TRUE(MemberSignature(class1_method12_).DoesPrefixMatch(prefix));
+  ASSERT_TRUE(MemberSignature(class12_field1_).DoesPrefixMatch(prefix));
+  ASSERT_TRUE(MemberSignature(class12_method1_).DoesPrefixMatch(prefix));
+  ASSERT_FALSE(MemberSignature(class2_field1_).DoesPrefixMatch(prefix));
+  ASSERT_FALSE(MemberSignature(class2_method1_).DoesPrefixMatch(prefix));
+  ASSERT_FALSE(MemberSignature(class2_method1_i_).DoesPrefixMatch(prefix));
+}
+
+TEST_F(HiddenApiTest, CheckClassExactMatch) {
+  ScopedObjectAccess soa(self_);
+  std::string prefix("Lmypackage/packagea/Class1;");
+  ASSERT_TRUE(MemberSignature(class1_field1_).DoesPrefixMatch(prefix));
+  ASSERT_TRUE(MemberSignature(class1_field12_).DoesPrefixMatch(prefix));
+  ASSERT_TRUE(MemberSignature(class1_init_).DoesPrefixMatch(prefix));
+  ASSERT_TRUE(MemberSignature(class1_method1_).DoesPrefixMatch(prefix));
+  ASSERT_TRUE(MemberSignature(class1_method1_i_).DoesPrefixMatch(prefix));
+  ASSERT_FALSE(MemberSignature(class12_field1_).DoesPrefixMatch(prefix));
+  ASSERT_FALSE(MemberSignature(class12_method1_).DoesPrefixMatch(prefix));
+  ASSERT_FALSE(MemberSignature(class2_field1_).DoesPrefixMatch(prefix));
+  ASSERT_FALSE(MemberSignature(class2_method1_).DoesPrefixMatch(prefix));
+  ASSERT_FALSE(MemberSignature(class2_method1_i_).DoesPrefixMatch(prefix));
+}
+
+TEST_F(HiddenApiTest, CheckMethodMatch) {
+  ScopedObjectAccess soa(self_);
+  std::string prefix("Lmypackage/packagea/Class1;->method1");
+  ASSERT_FALSE(MemberSignature(class1_field1_).DoesPrefixMatch(prefix));
+  ASSERT_FALSE(MemberSignature(class1_field12_).DoesPrefixMatch(prefix));
+  ASSERT_FALSE(MemberSignature(class1_init_).DoesPrefixMatch(prefix));
+  ASSERT_TRUE(MemberSignature(class1_method1_).DoesPrefixMatch(prefix));
+  ASSERT_TRUE(MemberSignature(class1_method1_i_).DoesPrefixMatch(prefix));
+  ASSERT_TRUE(MemberSignature(class1_method12_).DoesPrefixMatch(prefix));
+  ASSERT_FALSE(MemberSignature(class12_field1_).DoesPrefixMatch(prefix));
+  ASSERT_FALSE(MemberSignature(class12_method1_).DoesPrefixMatch(prefix));
+}
+
+TEST_F(HiddenApiTest, CheckMethodExactMatch) {
+  ScopedObjectAccess soa(self_);
+  std::string prefix("Lmypackage/packagea/Class1;->method1(");
+  ASSERT_FALSE(MemberSignature(class1_field1_).DoesPrefixMatch(prefix));
+  ASSERT_FALSE(MemberSignature(class1_field12_).DoesPrefixMatch(prefix));
+  ASSERT_FALSE(MemberSignature(class1_init_).DoesPrefixMatch(prefix));
+  ASSERT_TRUE(MemberSignature(class1_method1_).DoesPrefixMatch(prefix));
+  ASSERT_TRUE(MemberSignature(class1_method1_i_).DoesPrefixMatch(prefix));
+  ASSERT_FALSE(MemberSignature(class1_method12_).DoesPrefixMatch(prefix));
+}
+
+TEST_F(HiddenApiTest, CheckMethodSignatureMatch) {
+  ScopedObjectAccess soa(self_);
+  std::string prefix("Lmypackage/packagea/Class1;->method1(I)");
+  ASSERT_FALSE(MemberSignature(class1_field1_).DoesPrefixMatch(prefix));
+  ASSERT_FALSE(MemberSignature(class1_field12_).DoesPrefixMatch(prefix));
+  ASSERT_FALSE(MemberSignature(class1_method1_).DoesPrefixMatch(prefix));
+  ASSERT_TRUE(MemberSignature(class1_method1_i_).DoesPrefixMatch(prefix));
+  ASSERT_FALSE(MemberSignature(class1_method12_).DoesPrefixMatch(prefix));
+}
+
+TEST_F(HiddenApiTest, CheckMethodSignatureAndReturnMatch) {
+  ScopedObjectAccess soa(self_);
+  std::string prefix("Lmypackage/packagea/Class1;->method1()V");
+  ASSERT_FALSE(MemberSignature(class1_field1_).DoesPrefixMatch(prefix));
+  ASSERT_FALSE(MemberSignature(class1_field12_).DoesPrefixMatch(prefix));
+  ASSERT_TRUE(MemberSignature(class1_method1_).DoesPrefixMatch(prefix));
+  ASSERT_FALSE(MemberSignature(class1_method1_i_).DoesPrefixMatch(prefix));
+  ASSERT_FALSE(MemberSignature(class1_method12_).DoesPrefixMatch(prefix));
+}
+
+TEST_F(HiddenApiTest, CheckFieldMatch) {
+  ScopedObjectAccess soa(self_);
+  std::string prefix("Lmypackage/packagea/Class1;->field1");
+  ASSERT_TRUE(MemberSignature(class1_field1_).DoesPrefixMatch(prefix));
+  ASSERT_TRUE(MemberSignature(class1_field12_).DoesPrefixMatch(prefix));
+  ASSERT_FALSE(MemberSignature(class1_method1_).DoesPrefixMatch(prefix));
+  ASSERT_FALSE(MemberSignature(class1_method1_i_).DoesPrefixMatch(prefix));
+  ASSERT_FALSE(MemberSignature(class1_method12_).DoesPrefixMatch(prefix));
+}
+
+TEST_F(HiddenApiTest, CheckFieldExactMatch) {
+  ScopedObjectAccess soa(self_);
+  std::string prefix("Lmypackage/packagea/Class1;->field1:");
+  ASSERT_TRUE(MemberSignature(class1_field1_).DoesPrefixMatch(prefix));
+  ASSERT_FALSE(MemberSignature(class1_field12_).DoesPrefixMatch(prefix));
+  ASSERT_FALSE(MemberSignature(class1_method1_).DoesPrefixMatch(prefix));
+}
+
+TEST_F(HiddenApiTest, CheckFieldTypeMatch) {
+  ScopedObjectAccess soa(self_);
+  std::string prefix("Lmypackage/packagea/Class1;->field1:I");
+  ASSERT_TRUE(MemberSignature(class1_field1_).DoesPrefixMatch(prefix));
+  ASSERT_FALSE(MemberSignature(class1_field12_).DoesPrefixMatch(prefix));
+  ASSERT_FALSE(MemberSignature(class1_method1_).DoesPrefixMatch(prefix));
+}
+
+TEST_F(HiddenApiTest, CheckConstructorMatch) {
+  ScopedObjectAccess soa(self_);
+  std::string prefix("Lmypackage/packagea/Class1;-><init>");
+  ASSERT_TRUE(MemberSignature(class1_init_).DoesPrefixMatch(prefix));
+  ASSERT_FALSE(MemberSignature(class1_method1_).DoesPrefixMatch(prefix));
+}
+
+TEST_F(HiddenApiTest, CheckConstructorExactMatch) {
+  ScopedObjectAccess soa(self_);
+  std::string prefix("Lmypackage/packagea/Class1;-><init>()V");
+  ASSERT_TRUE(MemberSignature(class1_init_).DoesPrefixMatch(prefix));
+  ASSERT_FALSE(MemberSignature(class1_method1_).DoesPrefixMatch(prefix));
+}
+
+TEST_F(HiddenApiTest, CheckMethodSignatureTrailingCharsNoMatch) {
+  ScopedObjectAccess soa(self_);
+  std::string prefix("Lmypackage/packagea/Class1;->method1()Vfoo");
+  ASSERT_FALSE(MemberSignature(class1_method1_).DoesPrefixMatch(prefix));
+}
+
+TEST_F(HiddenApiTest, CheckConstructorTrailingCharsNoMatch) {
+  ScopedObjectAccess soa(self_);
+  std::string prefix("Lmypackage/packagea/Class1;-><init>()Vfoo");
+  ASSERT_FALSE(MemberSignature(class1_init_).DoesPrefixMatch(prefix));
+}
+
+TEST_F(HiddenApiTest, CheckFieldTrailingCharsNoMatch) {
+  ScopedObjectAccess soa(self_);
+  std::string prefix("Lmypackage/packagea/Class1;->field1:Ifoo");
+  ASSERT_FALSE(MemberSignature(class1_field1_).DoesPrefixMatch(prefix));
+}
+
+}  // namespace art
diff --git a/runtime/mirror/class-inl.h b/runtime/mirror/class-inl.h
index f0898f4..72b3179 100644
--- a/runtime/mirror/class-inl.h
+++ b/runtime/mirror/class-inl.h
@@ -31,7 +31,6 @@
 #include "dex/invoke_type.h"
 #include "dex_cache.h"
 #include "gc/heap-inl.h"
-#include "hidden_api.h"
 #include "iftable.h"
 #include "subtype_check.h"
 #include "object-inl.h"
diff --git a/runtime/native/dalvik_system_VMRuntime.cc b/runtime/native/dalvik_system_VMRuntime.cc
index 505b745..a5ade6f 100644
--- a/runtime/native/dalvik_system_VMRuntime.cc
+++ b/runtime/native/dalvik_system_VMRuntime.cc
@@ -78,6 +78,21 @@
   return Runtime::Current()->HasPendingHiddenApiWarning() ? JNI_TRUE : JNI_FALSE;
 }
 
+static void VMRuntime_setHiddenApiExemptions(JNIEnv* env,
+                                            jclass,
+                                            jobjectArray exemptions) {
+  std::vector<std::string> exemptions_vec;
+  int exemptions_length = env->GetArrayLength(exemptions);
+  for (int i = 0; i < exemptions_length; i++) {
+    jstring exemption = reinterpret_cast<jstring>(env->GetObjectArrayElement(exemptions, i));
+    const char* raw_exemption = env->GetStringUTFChars(exemption, nullptr);
+    exemptions_vec.push_back(raw_exemption);
+    env->ReleaseStringUTFChars(exemption, raw_exemption);
+  }
+
+  Runtime::Current()->SetHiddenApiExemptions(exemptions_vec);
+}
+
 static jobject VMRuntime_newNonMovableArray(JNIEnv* env, jobject, jclass javaElementClass,
                                             jint length) {
   ScopedFastNativeObjectAccess soa(env);
@@ -672,6 +687,7 @@
   NATIVE_METHOD(VMRuntime, concurrentGC, "()V"),
   NATIVE_METHOD(VMRuntime, disableJitCompilation, "()V"),
   NATIVE_METHOD(VMRuntime, hasUsedHiddenApi, "()Z"),
+  NATIVE_METHOD(VMRuntime, setHiddenApiExemptions, "([Ljava/lang/String;)V"),
   NATIVE_METHOD(VMRuntime, getTargetHeapUtilization, "()F"),
   FAST_NATIVE_METHOD(VMRuntime, isDebuggerActive, "()Z"),
   FAST_NATIVE_METHOD(VMRuntime, isNativeDebuggable, "()Z"),
diff --git a/runtime/native/dalvik_system_ZygoteHooks.cc b/runtime/native/dalvik_system_ZygoteHooks.cc
index 163a1a8..51fd2df 100644
--- a/runtime/native/dalvik_system_ZygoteHooks.cc
+++ b/runtime/native/dalvik_system_ZygoteHooks.cc
@@ -27,6 +27,7 @@
 #include "base/mutex.h"
 #include "base/runtime_debug.h"
 #include "debugger.h"
+#include "hidden_api.h"
 #include "java_vm_ext.h"
 #include "jit/jit.h"
 #include "jni_internal.h"
diff --git a/runtime/runtime.cc b/runtime/runtime.cc
index 53982ae..d02652e 100644
--- a/runtime/runtime.cc
+++ b/runtime/runtime.cc
@@ -86,6 +86,7 @@
 #include "gc/space/space-inl.h"
 #include "gc/system_weak.h"
 #include "handle_scope-inl.h"
+#include "hidden_api.h"
 #include "image-inl.h"
 #include "instrumentation.h"
 #include "intern_table.h"
diff --git a/runtime/runtime.h b/runtime/runtime.h
index dba31b2..03f17bc 100644
--- a/runtime/runtime.h
+++ b/runtime/runtime.h
@@ -536,6 +536,14 @@
     pending_hidden_api_warning_ = value;
   }
 
+  void SetHiddenApiExemptions(const std::vector<std::string>& exemptions) {
+    hidden_api_exemptions_ = exemptions;
+  }
+
+  const std::vector<std::string>& GetHiddenApiExemptions() {
+    return hidden_api_exemptions_;
+  }
+
   bool HasPendingHiddenApiWarning() const {
     return pending_hidden_api_warning_;
   }
@@ -996,6 +1004,9 @@
   // Whether access checks on hidden API should be performed.
   hiddenapi::EnforcementPolicy hidden_api_policy_;
 
+  // List of signature prefixes of methods that have been removed from the blacklist
+  std::vector<std::string> hidden_api_exemptions_;
+
   // Whether the application has used an API which is not restricted but we
   // should issue a warning about it.
   bool pending_hidden_api_warning_;
diff --git a/test/HiddenApiSignatures/Class1.java b/test/HiddenApiSignatures/Class1.java
new file mode 100644
index 0000000..a9004dc
--- /dev/null
+++ b/test/HiddenApiSignatures/Class1.java
@@ -0,0 +1,35 @@
+/*
+ * 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 mypackage.packagea;
+
+public class Class1 {
+    public int field1;
+    public int field12;
+
+    public Class1() {
+    }
+
+    public void method1() {
+    }
+
+    public void method1(int i) {
+    }
+
+    public void method12() {
+    }
+
+}
\ No newline at end of file
diff --git a/test/HiddenApiSignatures/Class12.java b/test/HiddenApiSignatures/Class12.java
new file mode 100644
index 0000000..82b22e3
--- /dev/null
+++ b/test/HiddenApiSignatures/Class12.java
@@ -0,0 +1,24 @@
+/*
+ * 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 mypackage.packagea;
+
+public class Class12 {
+    public int field1;
+
+    public void method1() {
+    }
+}
\ No newline at end of file
diff --git a/test/HiddenApiSignatures/Class2.java b/test/HiddenApiSignatures/Class2.java
new file mode 100644
index 0000000..dc92b9c
--- /dev/null
+++ b/test/HiddenApiSignatures/Class2.java
@@ -0,0 +1,27 @@
+/*
+ * 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 mypackage.packagea;
+
+public class Class2 {
+    public int field1;
+
+    public void method1() {
+    }
+
+    public void method1(int i) {
+    }
+}
\ No newline at end of file
diff --git a/test/HiddenApiSignatures/Class3.java b/test/HiddenApiSignatures/Class3.java
new file mode 100644
index 0000000..fbf0407
--- /dev/null
+++ b/test/HiddenApiSignatures/Class3.java
@@ -0,0 +1,27 @@
+/*
+ * 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 mypackage.packageb;
+
+public class Class3 {
+    public int field1;
+
+    public void method1() {
+    }
+
+    public void method1(int i) {
+    }
+}
\ No newline at end of file