Merge "Add a reference table implementation." into dalvik-dev
diff --git a/build/Android.common.mk b/build/Android.common.mk
index 08dc43f..ae276f5 100644
--- a/build/Android.common.mk
+++ b/build/Android.common.mk
@@ -55,11 +55,13 @@
 	src/object_bitmap.cc \
 	src/offsets.cc \
 	src/os_linux.cc \
+	src/reference_table.cc \
 	src/runtime.cc \
 	src/space.cc \
 	src/stringpiece.cc \
 	src/stringprintf.cc \
 	src/thread.cc \
+	src/utils.cc \
 	src/zip_archive.cc
 
 LIBART_TARGET_SRC_FILES := \
@@ -97,8 +99,10 @@
 	src/jni_internal_test.cc.arm \
 	src/jni_compiler_test.cc.arm \
 	src/object_test.cc \
+	src/reference_table_test.cc \
 	src/runtime_test.cc \
 	src/space_test.cc \
+	src/utils_test.cc \
 	src/zip_archive_test.cc
 
 TEST_TARGET_SRC_FILES := \
diff --git a/src/reference_table.cc b/src/reference_table.cc
new file mode 100644
index 0000000..3f0c5d5
--- /dev/null
+++ b/src/reference_table.cc
@@ -0,0 +1,238 @@
+/*
+ * Copyright (C) 2008 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 "reference_table.h"
+
+#include "object.h"
+
+namespace art {
+
+ReferenceTable::ReferenceTable(const char* name,
+    size_t initial_size, size_t max_size)
+        : name_(name), max_size_(max_size) {
+  CHECK_LE(initial_size, max_size);
+  entries_.reserve(initial_size);
+}
+
+void ReferenceTable::Add(Object* obj) {
+  DCHECK(obj != NULL);
+  if (entries_.size() == max_size_) {
+    LOG(FATAL) << "ReferenceTable '" << name_ << "' "
+               << "overflowed (" << max_size_ << " entries)";
+  }
+  entries_.push_back(obj);
+}
+
+void ReferenceTable::Remove(Object* obj) {
+  // We iterate backwards on the assumption that references are LIFO.
+  for (int i = entries_.size() - 1; i >= 0; --i) {
+    if (entries_[i] == obj) {
+      entries_.erase(entries_.begin() + i);
+      return;
+    }
+  }
+}
+
+/*
+ * If "obj" is an array, return the number of elements in the array.
+ * Otherwise, return zero.
+ */
+size_t GetElementCount(const Object* obj) {
+  if (obj == NULL || obj == kClearedJniWeakGlobal || !obj->IsArray()) {
+    return 0;
+  }
+  return obj->AsArray()->GetLength();
+}
+
+struct ObjectComparator {
+  bool operator()(Object* obj1, Object* obj2){
+    // Ensure null references and cleared jweaks appear at the end.
+    if (obj1 == NULL) {
+      return true;
+    } else if (obj2 == NULL) {
+      return false;
+    }
+    if (obj1 == kClearedJniWeakGlobal) {
+      return true;
+    } else if (obj2 == kClearedJniWeakGlobal) {
+      return false;
+    }
+
+    // Sort by class...
+    if (obj1->GetClass() != obj2->GetClass()) {
+      return reinterpret_cast<uintptr_t>(obj1->GetClass()) <
+          reinterpret_cast<uintptr_t>(obj2->GetClass());
+    } else {
+      // ...then by size...
+      size_t count1 = obj1->SizeOf();
+      size_t count2 = obj2->SizeOf();
+      if (count1 != count2) {
+        return count1 < count2;
+      } else {
+        // ...and finally by address.
+        return reinterpret_cast<uintptr_t>(obj1) <
+            reinterpret_cast<uintptr_t>(obj2);
+      }
+    }
+  }
+};
+
+/*
+ * Log an object with some additional info.
+ *
+ * Pass in the number of elements in the array (or 0 if this is not an
+ * array object), and the number of additional objects that are identical
+ * or equivalent to the original.
+ */
+void LogSummaryLine(const Object* obj, size_t elems, int identical, int equiv) {
+  if (obj == NULL) {
+    LOG(WARNING) << "    NULL reference (count=" << equiv << ")";
+    return;
+  }
+  if (obj == kClearedJniWeakGlobal) {
+    LOG(WARNING) << "    cleared jweak (count=" << equiv << ")";
+    return;
+  }
+
+  std::string className(PrettyType(obj));
+  if (obj->IsClass()) {
+    // We're summarizing multiple instances, so using the exemplar
+    // Class' type parameter here would be misleading.
+    className = "java.lang.Class";
+  }
+  if (elems != 0) {
+    StringAppendF(&className, " (%zd elements)", elems);
+  }
+
+  size_t total = identical + equiv + 1;
+  std::string msg(StringPrintf("%5d of %s", total, className.c_str()));
+  if (identical + equiv != 0) {
+    StringAppendF(&msg, " (%d unique instances)", equiv + 1);
+  }
+  LOG(WARNING) << "    " << msg;
+}
+
+size_t ReferenceTable::Size() const {
+  return entries_.size();
+}
+
+/*
+ * Dump a summary of an array of references to the log file.
+ *
+ * This is used to dump the contents of ReferenceTable and IndirectRefTable
+ * structs.
+ */
+void ReferenceTable::Dump() const {
+  LOG(WARNING) << name_ << " reference table dump:";
+
+  if (entries_.empty()) {
+    LOG(WARNING) << "  (empty)";
+    return;
+  }
+
+  // Dump the most recent N entries.
+  const size_t kLast = 10;
+  size_t count = entries_.size();
+  int first = count - kLast;
+  if (first < 0) {
+    first = 0;
+  }
+  LOG(WARNING) << "  Last " << (count - first) << " entries (of " << count << "):";
+  for (int idx = count - 1; idx >= first; --idx) {
+    const Object* ref = entries_[idx];
+    if (ref == NULL) {
+      continue;
+    }
+    if (ref == kClearedJniWeakGlobal) {
+      LOG(WARNING) << StringPrintf("    %5d: cleared jweak", idx);
+      continue;
+    }
+    if (ref->GetClass() == NULL) {
+      // should only be possible right after a plain dvmMalloc().
+      size_t size = ref->SizeOf();
+      LOG(WARNING) << StringPrintf("    %5d: %p (raw) (%zd bytes)", idx, ref, size);
+      continue;
+    }
+
+    std::string className(PrettyType(ref));
+
+    std::string extras;
+    size_t elems = GetElementCount(ref);
+    if (elems != 0) {
+      StringAppendF(&extras, " (%zd elements)", elems);
+    }
+#if 0
+    // TODO: support dumping string data.
+    else if (ref->GetClass() == gDvm.classJavaLangString) {
+      const StringObject* str = reinterpret_cast<const StringObject*>(ref);
+      extras += " \"";
+      size_t count = 0;
+      char* s = dvmCreateCstrFromString(str);
+      char* p = s;
+      for (; *p && count < 16; ++p, ++count) {
+        extras += *p;
+      }
+      if (*p == 0) {
+        extras += "\"";
+      } else {
+        StringAppendF(&extras, "... (%d chars)", str->length());
+      }
+      free(s);
+    }
+#endif
+    LOG(WARNING) << StringPrintf("    %5d: ", idx) << ref << " " << className << extras;
+  }
+
+  // Make a copy of the table and sort it.
+  std::vector<Object*> sorted_entries(entries_.begin(), entries_.end());
+  std::sort(sorted_entries.begin(), sorted_entries.end(), ObjectComparator());
+
+  // Remove any uninteresting stuff from the list. The sort moved them all to the end.
+  while (!sorted_entries.empty() && sorted_entries.back() == NULL) {
+    sorted_entries.pop_back();
+  }
+  while (!sorted_entries.empty() && sorted_entries.back() == kClearedJniWeakGlobal) {
+    sorted_entries.pop_back();
+  }
+  if (sorted_entries.empty()) {
+    return;
+  }
+
+  // Dump a summary of the whole table.
+  LOG(WARNING) << "  Summary:";
+  size_t equiv = 0;
+  size_t identical = 0;
+  for (size_t idx = 1; idx < count; idx++) {
+    Object* prev = sorted_entries[idx-1];
+    Object* current = sorted_entries[idx];
+    size_t elems = GetElementCount(prev);
+    if (current == prev) {
+      // Same reference, added more than once.
+      identical++;
+    } else if (current->GetClass() == prev->GetClass() && GetElementCount(current) == elems) {
+      // Same class / element count, different object.
+      equiv++;
+    } else {
+      // Different class.
+      LogSummaryLine(prev, elems, identical, equiv);
+      equiv = identical = 0;
+    }
+  }
+  // Handle the last entry.
+  LogSummaryLine(sorted_entries.back(), GetElementCount(sorted_entries.back()), identical, equiv);
+}
+
+}  // namespace art
diff --git a/src/reference_table.h b/src/reference_table.h
new file mode 100644
index 0000000..140cc37
--- /dev/null
+++ b/src/reference_table.h
@@ -0,0 +1,58 @@
+/*
+ * Copyright (C) 2008 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_SRC_REFERENCE_TABLE_H_
+#define ART_SRC_REFERENCE_TABLE_H_
+
+#include <cstddef>
+#include <iosfwd>
+#include <string>
+#include <vector>
+
+namespace art {
+
+class Object;
+
+#define kInvalidIndirectRefObject reinterpret_cast<Object*>(0xdead4321)
+#define kClearedJniWeakGlobal reinterpret_cast<Object*>(0xdead1234)
+
+/*
+ * Maintain a table of references.  Used for internal local references,
+ * JNI monitor references, and JNI pinned array references.
+ *
+ * None of the functions are synchronized.
+ */
+class ReferenceTable {
+ public:
+  ReferenceTable(const char* name, size_t initial_size, size_t max_size);
+
+  void Add(Object* obj);
+
+  void Remove(Object* obj);
+
+  size_t Size() const;
+
+  void Dump() const;
+
+ private:
+  std::string name_;
+  std::vector<Object*> entries_;
+  size_t max_size_;
+};
+
+}  // namespace art
+
+#endif  // ART_SRC_REFERENCE_TABLE_H_
diff --git a/src/reference_table_test.cc b/src/reference_table_test.cc
new file mode 100644
index 0000000..c61e3c9
--- /dev/null
+++ b/src/reference_table_test.cc
@@ -0,0 +1,38 @@
+// Copyright 2011 Google Inc. All Rights Reserved.
+
+#include "common_test.h"
+
+#include "reference_table.h"
+
+#include "gtest/gtest.h"
+
+namespace art {
+
+class ReferenceTableTest : public RuntimeTest {
+};
+
+TEST_F(ReferenceTableTest, Basics) {
+  Object* o1 = String::AllocFromModifiedUtf8(0, "hello");
+  Object* o2 = ShortArray::Alloc(0);
+
+  // TODO: rewrite Dump to take a std::ostream& so we can test it better.
+
+  ReferenceTable rt("test", 0, 4);
+  rt.Dump();
+  EXPECT_EQ(0U, rt.Size());
+  rt.Remove(NULL);
+  EXPECT_EQ(0U, rt.Size());
+  rt.Remove(o1);
+  EXPECT_EQ(0U, rt.Size());
+  rt.Add(o1);
+  EXPECT_EQ(1U, rt.Size());
+  rt.Add(o2);
+  EXPECT_EQ(2U, rt.Size());
+  rt.Dump();
+  rt.Remove(o1);
+  EXPECT_EQ(1U, rt.Size());
+  rt.Remove(o2);
+  EXPECT_EQ(0U, rt.Size());
+}
+
+}  // namespace art
diff --git a/src/utils.cc b/src/utils.cc
new file mode 100644
index 0000000..419eb1c
--- /dev/null
+++ b/src/utils.cc
@@ -0,0 +1,71 @@
+// Copyright 2011 Google Inc. All Rights Reserved.
+// Author: enh@google.com (Elliott Hughes)
+
+#include "object.h"
+#include "utils.h"
+
+namespace art {
+
+std::string PrettyDescriptor(const StringPiece& descriptor) {
+  // Count the number of '['s to get the dimensionality.
+  const char* c = descriptor.data();
+  size_t dim = 0;
+  while (*c == '[') {
+    dim++;
+    c++;
+  }
+
+  // Reference or primitive?
+  if (*c == 'L') {
+    // "[[La/b/C;" -> "a.b.C[][]".
+    c++; // Skip the 'L'.
+  } else {
+    // "[[B" -> "byte[][]".
+    // To make life easier, we make primitives look like unqualified
+    // reference types.
+    switch (*c) {
+    case 'B': c = "byte;"; break;
+    case 'C': c = "char;"; break;
+    case 'D': c = "double;"; break;
+    case 'F': c = "float;"; break;
+    case 'I': c = "int;"; break;
+    case 'J': c = "long;"; break;
+    case 'S': c = "short;"; break;
+    case 'Z': c = "boolean;"; break;
+    default: return descriptor.ToString();
+    }
+  }
+
+  // At this point, 'c' is a string of the form "fully/qualified/Type;"
+  // or "primitive;". Rewrite the type with '.' instead of '/':
+  std::string result;
+  const char* p = c;
+  while (*p != ';') {
+    char ch = *p++;
+    if (ch == '/') {
+      ch = '.';
+    }
+    result.push_back(ch);
+  }
+  // ...and replace the semicolon with 'dim' "[]" pairs:
+  while (dim--) {
+    result += "[]";
+  }
+  return result;
+}
+
+std::string PrettyType(const Object* obj) {
+  if (obj == NULL) {
+    return "null";
+  }
+  if (obj->GetClass() == NULL) {
+    return "(raw)";
+  }
+  std::string result(PrettyDescriptor(obj->GetClass()->GetDescriptor()));
+  if (obj->IsClass()) {
+    result += "<" + PrettyDescriptor(obj->AsClass()->GetDescriptor()) + ">";
+  }
+  return result;
+}
+
+}  // namespace art
diff --git a/src/utils.h b/src/utils.h
index 842db63..ea51d1e 100644
--- a/src/utils.h
+++ b/src/utils.h
@@ -5,10 +5,13 @@
 
 #include "globals.h"
 #include "logging.h"
+#include "stringpiece.h"
 #include "stringprintf.h"
 
 namespace art {
 
+class Object;
+
 template<typename T>
 static inline bool IsPowerOfTwo(T x) {
   return (x & (x - 1)) == 0;
@@ -132,6 +135,17 @@
   return result;
 }
 
+// Return a newly-allocated string containing a human-readable equivalent
+// of 'descriptor'. So "I" would be "int", "[[I" would be "int[][]",
+// "[Ljava/lang/String;" would be "java.lang.String[]", and so forth.
+std::string PrettyDescriptor(const StringPiece& descriptor);
+
+// Returns a human-readable string form of the name of the class of
+// the given object. So given a java.lang.String, the output would
+// be "java.lang.String". Given an array of int, the output would be "int[]".
+// Given String.class, the output would be "java.lang.Class<java.lang.String>".
+std::string PrettyType(const Object* obj);
+
 }  // namespace art
 
 #endif  // ART_SRC_UTILS_H_
diff --git a/src/utils_test.cc b/src/utils_test.cc
new file mode 100644
index 0000000..1b7315f
--- /dev/null
+++ b/src/utils_test.cc
@@ -0,0 +1,70 @@
+// Copyright 2011 Google Inc. All Rights Reserved.
+
+#include "object.h"
+#include "common_test.h"
+#include "utils.h"
+
+#include "gtest/gtest.h"
+
+namespace art {
+
+class UtilsTest : public RuntimeTest {
+};
+
+TEST(PrettyDescriptorTest, ArrayReferences) {
+  EXPECT_EQ("java.lang.Class[]", PrettyDescriptor("[Ljava/lang/Class;"));
+  EXPECT_EQ("java.lang.Class[][]", PrettyDescriptor("[[Ljava/lang/Class;"));
+}
+
+TEST(PrettyDescriptorTest, ScalarReferences) {
+  EXPECT_EQ("java.lang.String", PrettyDescriptor("Ljava.lang.String;"));
+  EXPECT_EQ("java.lang.String", PrettyDescriptor("Ljava/lang/String;"));
+}
+
+TEST(PrettyDescriptorTest, PrimitiveArrays) {
+  EXPECT_EQ("boolean[]", PrettyDescriptor("[Z"));
+  EXPECT_EQ("boolean[][]", PrettyDescriptor("[[Z"));
+  EXPECT_EQ("byte[]", PrettyDescriptor("[B"));
+  EXPECT_EQ("byte[][]", PrettyDescriptor("[[B"));
+  EXPECT_EQ("char[]", PrettyDescriptor("[C"));
+  EXPECT_EQ("char[][]", PrettyDescriptor("[[C"));
+  EXPECT_EQ("double[]", PrettyDescriptor("[D"));
+  EXPECT_EQ("double[][]", PrettyDescriptor("[[D"));
+  EXPECT_EQ("float[]", PrettyDescriptor("[F"));
+  EXPECT_EQ("float[][]", PrettyDescriptor("[[F"));
+  EXPECT_EQ("int[]", PrettyDescriptor("[I"));
+  EXPECT_EQ("int[][]", PrettyDescriptor("[[I"));
+  EXPECT_EQ("long[]", PrettyDescriptor("[J"));
+  EXPECT_EQ("long[][]", PrettyDescriptor("[[J"));
+  EXPECT_EQ("short[]", PrettyDescriptor("[S"));
+  EXPECT_EQ("short[][]", PrettyDescriptor("[[S"));
+}
+
+TEST(PrettyDescriptorTest, PrimitiveScalars) {
+  EXPECT_EQ("boolean", PrettyDescriptor("Z"));
+  EXPECT_EQ("byte", PrettyDescriptor("B"));
+  EXPECT_EQ("char", PrettyDescriptor("C"));
+  EXPECT_EQ("double", PrettyDescriptor("D"));
+  EXPECT_EQ("float", PrettyDescriptor("F"));
+  EXPECT_EQ("int", PrettyDescriptor("I"));
+  EXPECT_EQ("long", PrettyDescriptor("J"));
+  EXPECT_EQ("short", PrettyDescriptor("S"));
+}
+
+TEST_F(UtilsTest, PrettyType) {
+  EXPECT_EQ("null", PrettyType(NULL));
+
+  String* s = String::AllocFromModifiedUtf8(0, "");
+  EXPECT_EQ("java.lang.String", PrettyType(s));
+
+  ShortArray* a = ShortArray::Alloc(2);
+  EXPECT_EQ("short[]", PrettyType(a));
+
+  Class* c = class_linker_->FindSystemClass("[Ljava/lang/String;");
+  ASSERT_TRUE(c != NULL);
+  Object* o = ObjectArray<String>::Alloc(c, 0);
+  EXPECT_EQ("java.lang.String[]", PrettyType(o));
+  EXPECT_EQ("java.lang.Class<java.lang.String[]>", PrettyType(o->GetClass()));
+}
+
+}  // namespace art