Add resetJitCounters

Used to avoid Jit counters from class preloading being recorded in the
boot profiles.

Bug: 139883463
Bug: 142564450
Test: test/run-test 2230-profile-save-hotness
Change-Id: I69c548ea336e9fb33e74988668e5d3c93b8a6705
diff --git a/runtime/native/dalvik_system_VMRuntime.cc b/runtime/native/dalvik_system_VMRuntime.cc
index ca41ae8..2102713 100644
--- a/runtime/native/dalvik_system_VMRuntime.cc
+++ b/runtime/native/dalvik_system_VMRuntime.cc
@@ -733,6 +733,34 @@
   }
 }
 
+class ClearJitCountersVisitor : public ClassVisitor {
+ public:
+  bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
+    // Avoid some types of classes that don't need their methods visited.
+    if (klass->IsProxyClass() ||
+        klass->IsArrayClass() ||
+        klass->IsPrimitive() ||
+        !klass->IsResolved() ||
+        klass->IsErroneousResolved()) {
+      return true;
+    }
+    for (ArtMethod& m : klass->GetMethods(kRuntimePointerSize)) {
+      if (!m.IsAbstract()) {
+        if (m.GetCounter() != 0) {
+          m.SetCounter(0);
+        }
+      }
+    }
+    return true;
+  }
+};
+
+static void VMRuntime_resetJitCounters(JNIEnv* env, jclass klass ATTRIBUTE_UNUSED) {
+  ScopedObjectAccess soa(env);
+  ClearJitCountersVisitor visitor;
+  Runtime::Current()->GetClassLinker()->VisitClasses(&visitor);
+}
+
 static JNINativeMethod gMethods[] = {
   FAST_NATIVE_METHOD(VMRuntime, addressOf, "(Ljava/lang/Object;)J"),
   NATIVE_METHOD(VMRuntime, bootClassPath, "()Ljava/lang/String;"),
@@ -783,6 +811,7 @@
   NATIVE_METHOD(VMRuntime, setProcessPackageName, "(Ljava/lang/String;)V"),
   NATIVE_METHOD(VMRuntime, setProcessDataDirectory, "(Ljava/lang/String;)V"),
   NATIVE_METHOD(VMRuntime, bootCompleted, "()V"),
+  NATIVE_METHOD(VMRuntime, resetJitCounters, "()V"),
 };
 
 void register_dalvik_system_VMRuntime(JNIEnv* env) {
diff --git a/test/2230-profile-save-hotness/src-art/Main.java b/test/2230-profile-save-hotness/src-art/Main.java
index 7fa87df..97177cc 100644
--- a/test/2230-profile-save-hotness/src-art/Main.java
+++ b/test/2230-profile-save-hotness/src-art/Main.java
@@ -49,6 +49,14 @@
         System.out.println("App method not hot in profile " +
                 getHotnessCounter(Main.class, methodName));
       }
+      if (getHotnessCounter(Main.class, methodName) == 0) {
+        System.out.println("Hotness should be non zero " +
+                getHotnessCounter(Main.class, methodName));
+      }
+      VMRuntime.resetJitCounters();
+      if (getHotnessCounter(Main.class, methodName) != 0) {
+        System.out.println("Hotness should be zero " + getHotnessCounter(Main.class, methodName));
+      }
     } finally {
       if (file != null) {
         file.delete();