Fix local reference leaks in debugger and use a cache.

Changed alloc record stack trace element to use jmethodID instead of
JNI weak global references. Added code to delete the local ref
created in AllocRecord::SetType.

Bug: 15886342
External bug: https://code.google.com/p/android/issues/detail?id=72330

Change-Id: Id18e765820baad02246768dc9d633aada60f4fed
diff --git a/runtime/debugger.h b/runtime/debugger.h
index 1cf0b0c..2589638 100644
--- a/runtime/debugger.h
+++ b/runtime/debugger.h
@@ -23,6 +23,7 @@
 
 #include <pthread.h>
 
+#include <map>
 #include <set>
 #include <string>
 #include <vector>
@@ -160,6 +161,17 @@
 
 class Dbg {
  public:
+  class TypeCache {
+   public:
+    // Returns a weak global for the input type. Deduplicates.
+    jobject Add(mirror::Class* t) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
+    // Clears the type cache and deletes all the weak global refs.
+    void Clear();
+
+   private:
+    std::multimap<int32_t, jobject> objects_;
+  };
+
   static bool ParseJdwpOptions(const std::string& options);
   static void SetJdwpAllowed(bool allowed);
 
@@ -555,6 +567,10 @@
   static void DdmSendHeapSegments(bool native)
       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
 
+  static TypeCache& GetTypeCache() {
+    return type_cache_;
+  }
+
  private:
   static void DdmBroadcast(bool connect) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
   static void PostThreadStartOrStop(Thread*, uint32_t)
@@ -604,6 +620,9 @@
 
   static size_t* GetReferenceCounterForEvent(uint32_t instrumentation_event);
 
+  // Weak global type cache, TODO improve this.
+  static TypeCache type_cache_;
+
   // Instrumentation event reference counters.
   // TODO we could use an array instead of having all these dedicated counters. Instrumentation
   // events are bits of a mask so we could convert them to array index.