ART: Support object tagging

Add support for tagging in the JVMTI plugin.

Bug: 31385027
Test: m test-art-host
Change-Id: I4d8fb12cd23ca60dc0b0ce9051d1c77e5eb18aa9
diff --git a/runtime/openjdkjvmti/OpenjdkJvmTi.cc b/runtime/openjdkjvmti/OpenjdkJvmTi.cc
index a1a2361..bebc2fc 100644
--- a/runtime/openjdkjvmti/OpenjdkJvmTi.cc
+++ b/runtime/openjdkjvmti/OpenjdkJvmTi.cc
@@ -38,7 +38,11 @@
 
 #include "art_jvmti.h"
 #include "jni_env_ext-inl.h"
+#include "object_tagging.h"
+#include "obj_ptr-inl.h"
 #include "runtime.h"
+#include "scoped_thread_state_change-inl.h"
+#include "thread_list.h"
 #include "transform.h"
 
 // TODO Remove this at some point by annotating all the methods. It was put in to make the skeleton
@@ -47,6 +51,8 @@
 
 namespace openjdkjvmti {
 
+ObjectTagTable gObjectTagTable;
+
 class JvmtiFunctions {
  private:
   static bool IsValidEnv(jvmtiEnv* env) {
@@ -270,11 +276,42 @@
   }
 
   static jvmtiError GetTag(jvmtiEnv* env, jobject object, jlong* tag_ptr) {
-    return ERR(NOT_IMPLEMENTED);
+    if (object == nullptr || tag_ptr == nullptr) {
+      return ERR(NULL_POINTER);
+    }
+
+    JNIEnv* jni_env = GetJniEnv(env);
+    if (jni_env == nullptr) {
+      return ERR(INTERNAL);
+    }
+
+    art::ScopedObjectAccess soa(jni_env);
+    art::ObjPtr<art::mirror::Object> obj = soa.Decode<art::mirror::Object>(object);
+    if (!gObjectTagTable.GetTag(obj.Ptr(), tag_ptr)) {
+      *tag_ptr = 0;
+    }
+
+    return ERR(NONE);
   }
 
   static jvmtiError SetTag(jvmtiEnv* env, jobject object, jlong tag) {
-    return ERR(NOT_IMPLEMENTED);
+    if (object == nullptr) {
+      return ERR(NULL_POINTER);
+    }
+
+    JNIEnv* jni_env = GetJniEnv(env);
+    if (jni_env == nullptr) {
+      return ERR(INTERNAL);
+    }
+
+    art::ScopedObjectAccess soa(jni_env);
+    art::ObjPtr<art::mirror::Object> obj = soa.Decode<art::mirror::Object>(object);
+    gObjectTagTable.Remove(obj.Ptr(), /* tag* */ nullptr);
+    if (tag != 0) {
+      gObjectTagTable.Add(obj.Ptr(), tag);
+    }
+
+    return ERR(NONE);
   }
 
   static jvmtiError GetObjectsWithTags(jvmtiEnv* env,
diff --git a/runtime/openjdkjvmti/object_tagging.h b/runtime/openjdkjvmti/object_tagging.h
new file mode 100644
index 0000000..e276c52
--- /dev/null
+++ b/runtime/openjdkjvmti/object_tagging.h
@@ -0,0 +1,137 @@
+/*
+ * Copyright (C) 2016 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.
+ */
+
+#ifndef ART_RUNTIME_OPENJDKJVMTI_OBJECT_TAGGING_H_
+#define ART_RUNTIME_OPENJDKJVMTI_OBJECT_TAGGING_H_
+
+#include "base/mutex.h"
+#include "gc/system_weak.h"
+#include "gc_root-inl.h"
+#include "mirror/object.h"
+#include "thread-inl.h"
+
+namespace openjdkjvmti {
+
+class ObjectTagTable : public art::gc::SystemWeakHolder {
+ public:
+  ObjectTagTable() : art::gc::SystemWeakHolder(art::LockLevel::kAllocTrackerLock) {
+  }
+
+  void Add(art::mirror::Object* obj, jlong tag)
+      REQUIRES_SHARED(art::Locks::mutator_lock_)
+      REQUIRES(!allow_disallow_lock_) {
+    art::Thread* self = art::Thread::Current();
+    art::MutexLock mu(self, allow_disallow_lock_);
+    Wait(self);
+
+    if (first_free_ == tagged_objects_.size()) {
+      tagged_objects_.push_back(Entry(art::GcRoot<art::mirror::Object>(obj), tag));
+      first_free_++;
+    } else {
+      DCHECK_LT(first_free_, tagged_objects_.size());
+      DCHECK(tagged_objects_[first_free_].first.IsNull());
+      tagged_objects_[first_free_] = Entry(art::GcRoot<art::mirror::Object>(obj), tag);
+      // TODO: scan for free elements.
+      first_free_ = tagged_objects_.size();
+    }
+  }
+
+  bool GetTag(art::mirror::Object* obj, jlong* result)
+      REQUIRES_SHARED(art::Locks::mutator_lock_)
+      REQUIRES(!allow_disallow_lock_) {
+    art::Thread* self = art::Thread::Current();
+    art::MutexLock mu(self, allow_disallow_lock_);
+    Wait(self);
+
+    for (const auto& pair : tagged_objects_) {
+      if (pair.first.Read(nullptr) == obj) {
+        *result = pair.second;
+        return true;
+      }
+    }
+
+    return false;
+  }
+
+  bool Remove(art::mirror::Object* obj, jlong* tag)
+      REQUIRES_SHARED(art::Locks::mutator_lock_)
+      REQUIRES(!allow_disallow_lock_) {
+    art::Thread* self = art::Thread::Current();
+    art::MutexLock mu(self, allow_disallow_lock_);
+    Wait(self);
+
+    for (auto it = tagged_objects_.begin(); it != tagged_objects_.end(); ++it) {
+      if (it->first.Read(nullptr) == obj) {
+        if (tag != nullptr) {
+          *tag = it->second;
+        }
+        it->first = art::GcRoot<art::mirror::Object>(nullptr);
+
+        size_t index = it - tagged_objects_.begin();
+        if (index < first_free_) {
+          first_free_ = index;
+        }
+
+        // TODO: compaction.
+
+        return true;
+      }
+    }
+
+    return false;
+  }
+
+  void Sweep(art::IsMarkedVisitor* visitor)
+      REQUIRES_SHARED(art::Locks::mutator_lock_)
+      REQUIRES(!allow_disallow_lock_) {
+    art::Thread* self = art::Thread::Current();
+    art::MutexLock mu(self, allow_disallow_lock_);
+
+    for (auto it = tagged_objects_.begin(); it != tagged_objects_.end(); ++it) {
+      if (!it->first.IsNull()) {
+        art::mirror::Object* original_obj = it->first.Read();
+        art::mirror::Object* target_obj = visitor->IsMarked(original_obj);
+        if (original_obj != target_obj) {
+          it->first = art::GcRoot<art::mirror::Object>(target_obj);
+
+          if (target_obj == nullptr) {
+            HandleNullSweep(it->second);
+          }
+        }
+      } else {
+        size_t index = it - tagged_objects_.begin();
+        if (index < first_free_) {
+          first_free_ = index;
+        }
+      }
+    }
+  }
+
+ private:
+  using Entry = std::pair<art::GcRoot<art::mirror::Object>, jlong>;
+
+  void HandleNullSweep(jlong tag ATTRIBUTE_UNUSED) {
+    // TODO: Handle deallocation reporting here. We'll have to enqueue tags temporarily, as we
+    //       probably shouldn't call the callbacks directly (to avoid any issues).
+  }
+
+  std::vector<Entry> tagged_objects_ GUARDED_BY(allow_disallow_lock_);
+  size_t first_free_ = 0;
+};
+
+}  // namespace openjdkjvmti
+
+#endif  // ART_RUNTIME_OPENJDKJVMTI_OBJECT_TAGGING_H_
diff --git a/test/903-hello-tagging/build b/test/903-hello-tagging/build
new file mode 100755
index 0000000..898e2e5
--- /dev/null
+++ b/test/903-hello-tagging/build
@@ -0,0 +1,17 @@
+#!/bin/bash
+#
+# Copyright 2016 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.
+
+./default-build "$@" --experimental agents
diff --git a/test/903-hello-tagging/expected.txt b/test/903-hello-tagging/expected.txt
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/test/903-hello-tagging/expected.txt
diff --git a/test/903-hello-tagging/info.txt b/test/903-hello-tagging/info.txt
new file mode 100644
index 0000000..875a5f6
--- /dev/null
+++ b/test/903-hello-tagging/info.txt
@@ -0,0 +1 @@
+Tests basic functions in the jvmti plugin.
diff --git a/test/903-hello-tagging/run b/test/903-hello-tagging/run
new file mode 100755
index 0000000..5e3c0bd
--- /dev/null
+++ b/test/903-hello-tagging/run
@@ -0,0 +1,43 @@
+#!/bin/bash
+#
+# Copyright 2016 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.
+
+plugin=libopenjdkjvmtid.so
+agent=libtiagentd.so
+lib=tiagentd
+if  [[ "$@" == *"-O"* ]]; then
+  agent=libtiagent.so
+  plugin=libopenjdkjvmti.so
+  lib=tiagent
+fi
+
+if [[ "$@" == *"--jvm"* ]]; then
+  arg="jvm"
+else
+  arg="art"
+fi
+
+if [[ "$@" != *"--debuggable"* ]]; then
+  other_args=" -Xcompiler-option --debuggable "
+else
+  other_args=""
+fi
+
+./default-run "$@" --experimental agents \
+                   --experimental runtime-plugins \
+                   --runtime-option -agentpath:${agent}=903-hello-tagging,${arg} \
+                   --android-runtime-option -Xplugin:${plugin} \
+                   ${other_args} \
+                   --args ${lib}
diff --git a/test/903-hello-tagging/src/Main.java b/test/903-hello-tagging/src/Main.java
new file mode 100644
index 0000000..2856a39
--- /dev/null
+++ b/test/903-hello-tagging/src/Main.java
@@ -0,0 +1,73 @@
+/*
+ * Copyright (C) 2016 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 java.lang.ref.WeakReference;
+
+public class Main {
+  public static void main(String[] args) {
+    System.loadLibrary(args[1]);
+    doTest();
+  }
+
+  public static void doTest() {
+    WeakReference<Object> weak = test();
+
+    Runtime.getRuntime().gc();
+    Runtime.getRuntime().gc();
+
+    if (weak.get() != null) {
+      throw new RuntimeException("WeakReference not cleared");
+    }
+  }
+
+  private static WeakReference<Object> test() {
+    Object o1 = new Object();
+    setTag(o1, 1);
+
+    Object o2 = new Object();
+    setTag(o2, 2);
+
+    checkTag(o1, 1);
+    checkTag(o2, 2);
+
+    Runtime.getRuntime().gc();
+    Runtime.getRuntime().gc();
+
+    checkTag(o1, 1);
+    checkTag(o2, 2);
+
+    Runtime.getRuntime().gc();
+    Runtime.getRuntime().gc();
+
+    setTag(o1, 10);
+    setTag(o2, 20);
+
+    checkTag(o1, 10);
+    checkTag(o2, 20);
+
+    return new WeakReference<Object>(o1);
+  }
+
+  private static void checkTag(Object o, long expectedTag) {
+    long tag = getTag(o);
+    if (expectedTag != tag) {
+      throw new RuntimeException("Unexpected tag " + tag + ", expected " + expectedTag);
+    }
+  }
+
+  private static native void setTag(Object o, long tag);
+  private static native long getTag(Object o);
+}
diff --git a/test/903-hello-tagging/tagging.cc b/test/903-hello-tagging/tagging.cc
new file mode 100644
index 0000000..8ccdf49
--- /dev/null
+++ b/test/903-hello-tagging/tagging.cc
@@ -0,0 +1,73 @@
+/*
+ * Copyright (C) 2013 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 "tagging.h"
+
+#include <iostream>
+#include <pthread.h>
+#include <stdio.h>
+#include <vector>
+
+#include "art_method-inl.h"
+#include "base/logging.h"
+#include "jni.h"
+#include "openjdkjvmti/jvmti.h"
+#include "utils.h"
+
+namespace art {
+namespace Test903HelloTagging {
+
+static jvmtiEnv* jvmti_env;
+
+extern "C" JNIEXPORT void JNICALL Java_Main_setTag(JNIEnv* env ATTRIBUTE_UNUSED,
+                                                   jclass,
+                                                   jobject obj,
+                                                   jlong tag) {
+  jvmtiError ret = jvmti_env->SetTag(obj, tag);
+  if (ret != JVMTI_ERROR_NONE) {
+    char* err;
+    jvmti_env->GetErrorName(ret, &err);
+    printf("Error setting tag: %s\n", err);
+  }
+}
+
+extern "C" JNIEXPORT jlong JNICALL Java_Main_getTag(JNIEnv* env ATTRIBUTE_UNUSED,
+                                                    jclass,
+                                                    jobject obj) {
+  jlong tag = 0;
+  jvmtiError ret = jvmti_env->GetTag(obj, &tag);
+  if (ret != JVMTI_ERROR_NONE) {
+    char* err;
+    jvmti_env->GetErrorName(ret, &err);
+    printf("Error getting tag: %s\n", err);
+  }
+  return tag;
+}
+
+// Don't do anything
+jint OnLoad(JavaVM* vm,
+            char* options ATTRIBUTE_UNUSED,
+            void* reserved ATTRIBUTE_UNUSED) {
+  if (vm->GetEnv(reinterpret_cast<void**>(&jvmti_env), JVMTI_VERSION_1_0)) {
+    printf("Unable to get jvmti env!\n");
+    return 1;
+  }
+  return 0;
+}
+
+}  // namespace Test903HelloTagging
+}  // namespace art
+
diff --git a/test/903-hello-tagging/tagging.h b/test/903-hello-tagging/tagging.h
new file mode 100644
index 0000000..f062d44
--- /dev/null
+++ b/test/903-hello-tagging/tagging.h
@@ -0,0 +1,30 @@
+/*
+ * Copyright (C) 2016 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.
+ */
+
+#ifndef ART_TEST_903_HELLO_TAGGING_TAGGING_H_
+#define ART_TEST_903_HELLO_TAGGING_TAGGING_H_
+
+#include <jni.h>
+
+namespace art {
+namespace Test903HelloTagging {
+
+jint OnLoad(JavaVM* vm, char* options, void* reserved);
+
+}  // namespace Test903HelloTagging
+}  // namespace art
+
+#endif  // ART_TEST_903_HELLO_TAGGING_TAGGING_H_
diff --git a/test/Android.bp b/test/Android.bp
index 628f377..d17261c 100644
--- a/test/Android.bp
+++ b/test/Android.bp
@@ -245,6 +245,7 @@
         "ti-agent/common_load.cc",
         "901-hello-ti-agent/basics.cc",
         "902-hello-transformation/transform.cc",
+        "903-hello-tagging/tagging.cc",
     ],
     shared_libs: [
         "libart",
@@ -263,9 +264,11 @@
         "ti-agent/common_load.cc",
         "901-hello-ti-agent/basics.cc",
         "902-hello-transformation/transform.cc",
+        "903-hello-tagging/tagging.cc",
     ],
     shared_libs: [
         "libartd",
+        "libbase",
         "libopenjdkjvmtid",
     ],
 }
diff --git a/test/ti-agent/common_load.cc b/test/ti-agent/common_load.cc
index 53bb153..4c7df97 100644
--- a/test/ti-agent/common_load.cc
+++ b/test/ti-agent/common_load.cc
@@ -25,6 +25,7 @@
 
 #include "901-hello-ti-agent/basics.h"
 #include "902-hello-transformation/transform.h"
+#include "903-hello-tagging/tagging.h"
 
 namespace art {
 
@@ -41,6 +42,7 @@
 AgentLib agents[] = {
   { "901-hello-ti-agent", Test901HelloTi::OnLoad, nullptr },
   { "902-hello-transformation", Test902HelloTransformation::OnLoad, nullptr },
+  { "903-hello-tagging", Test903HelloTagging::OnLoad, nullptr },
 };
 
 static AgentLib* FindAgent(char* name) {