Changed tracer to use an instance to hold state instead of statics.

Change-Id: I2fdcf5de7fbc745273b1a33cb409d13e72d24ab4
diff --git a/src/dalvik_system_VMDebug.cc b/src/dalvik_system_VMDebug.cc
index c4c43f1..c388e62 100644
--- a/src/dalvik_system_VMDebug.cc
+++ b/src/dalvik_system_VMDebug.cc
@@ -92,7 +92,7 @@
 }
 
 jboolean VMDebug_isMethodTracingActive(JNIEnv*, jclass) {
-  return Trace::IsMethodTracingActive();
+  return Runtime::Current()->IsMethodTracingActive();
 }
 
 void VMDebug_stopMethodTracing(JNIEnv*, jclass) {
diff --git a/src/object.cc b/src/object.cc
index b98235b..f43bec9 100644
--- a/src/object.cc
+++ b/src/object.cc
@@ -447,7 +447,7 @@
     return DexFile::kDexNoIndex;   // Special no mapping case
   }
   size_t mapping_table_length = GetMappingTableLength();
-  const void* code_offset = Trace::IsMethodTracingActive() ? Trace::GetSavedCodeFromMap(this) : GetCode();
+  const void* code_offset = Runtime::Current()->IsMethodTracingActive() ? Runtime::Current()->GetTracer()->GetSavedCodeFromMap(this) : GetCode();
   uint32_t sought_offset = pc - reinterpret_cast<uintptr_t>(code_offset);
   uint32_t best_offset = 0;
   uint32_t best_dex_offset = 0;
@@ -478,8 +478,9 @@
     uint32_t map_offset = mapping_table[i];
     uint32_t map_dex_offset = mapping_table[i + 1];
     if (map_dex_offset == dex_pc) {
-      if (Trace::IsMethodTracingActive()) {
-        return reinterpret_cast<uintptr_t>(Trace::GetSavedCodeFromMap(this)) + map_offset;
+      if (Runtime::Current()->IsMethodTracingActive()) {
+        Trace* tracer = Runtime::Current()->GetTracer();
+        return reinterpret_cast<uintptr_t>(tracer->GetSavedCodeFromMap(this)) + map_offset;
       } else {
         return reinterpret_cast<uintptr_t>(GetCode()) + map_offset;
       }
diff --git a/src/runtime.cc b/src/runtime.cc
index a00ebcd..4d95b4b 100644
--- a/src/runtime.cc
+++ b/src/runtime.cc
@@ -47,7 +47,8 @@
       vfprintf_(NULL),
       exit_(NULL),
       abort_(NULL),
-      stats_enabled_(false) {
+      stats_enabled_(false),
+      tracer_(NULL) {
   for (int i = 0; i < Runtime::kLastTrampolineMethodType; i++) {
     resolution_stub_array_[i] = NULL;
   }
@@ -870,4 +871,24 @@
   callee_save_method_[type] = method;
 }
 
+void Runtime::EnableMethodTracing(Trace* tracer) {
+  CHECK(!IsMethodTracingActive());
+  tracer_ = tracer;
+}
+
+void Runtime::DisableMethodTracing() {
+  CHECK(IsMethodTracingActive());
+  delete tracer_;
+  tracer_ = NULL;
+}
+
+bool Runtime::IsMethodTracingActive() const {
+  return (tracer_ != NULL);
+}
+
+Trace* Runtime::GetTracer() const {
+  CHECK(IsMethodTracingActive());
+  return tracer_;
+}
+
 }  // namespace art
diff --git a/src/runtime.h b/src/runtime.h
index 7f5f6f6..d30f465 100644
--- a/src/runtime.h
+++ b/src/runtime.h
@@ -34,6 +34,7 @@
 class SignalCatcher;
 class String;
 class ThreadList;
+class Trace;
 
 class Runtime {
  public:
@@ -203,6 +204,11 @@
 
   void DidForkFromZygote();
 
+  void EnableMethodTracing(Trace* tracer);
+  void DisableMethodTracing();
+  bool IsMethodTracingActive() const;
+  Trace* GetTracer() const;
+
  private:
   static void PlatformAbort(const char*, int);
 
@@ -272,6 +278,8 @@
   bool stats_enabled_;
   RuntimeStats stats_;
 
+  Trace* tracer_;
+
   // A pointer to the active runtime or NULL.
   static Runtime* instance_;
 
diff --git a/src/runtime_support.cc b/src/runtime_support.cc
index cdd773f..2ee64a1 100644
--- a/src/runtime_support.cc
+++ b/src/runtime_support.cc
@@ -141,7 +141,7 @@
 extern "C" void artThrowStackOverflowFromCode(Method* method, Thread* thread, Method** sp) {
   FinishCalleeSaveFrameSetup(thread, sp, Runtime::kSaveAll);
   // Remove extra entry pushed onto second stack during method tracing
-  if (Trace::IsMethodTracingActive()) {
+  if (Runtime::Current()->IsMethodTracingActive()) {
     artTraceMethodUnwindFromCode(thread);
   }
   thread->SetStackEndForStackOverflow();  // Allow space on the stack for constructor to execute
@@ -1183,30 +1183,33 @@
 }
 
 extern "C" const void* artTraceMethodEntryFromCode(Method* method, Thread* self, uintptr_t lr) {
+  Trace* tracer = Runtime::Current()->GetTracer();
   TraceStackFrame trace_frame = TraceStackFrame(method, lr);
   self->PushTraceStackFrame(trace_frame);
 
-  Trace::LogMethodTraceEvent(self, method, Trace::kMethodTraceEnter);
+  tracer->LogMethodTraceEvent(self, method, Trace::kMethodTraceEnter);
 
-  return Trace::GetSavedCodeFromMap(method);
+  return tracer->GetSavedCodeFromMap(method);
 }
 
 extern "C" uintptr_t artTraceMethodExitFromCode() {
+  Trace* tracer = Runtime::Current()->GetTracer();
   TraceStackFrame trace_frame = Thread::Current()->PopTraceStackFrame();
   Method* method = trace_frame.method_;
   uintptr_t lr = trace_frame.return_pc_;
 
-  Trace::LogMethodTraceEvent(Thread::Current(), method, Trace::kMethodTraceExit);
+  tracer->LogMethodTraceEvent(Thread::Current(), method, Trace::kMethodTraceExit);
 
   return lr;
 }
 
 uintptr_t artTraceMethodUnwindFromCode(Thread* self) {
+  Trace* tracer = Runtime::Current()->GetTracer();
   TraceStackFrame trace_frame = self->PopTraceStackFrame();
   Method* method = trace_frame.method_;
   uintptr_t lr = trace_frame.return_pc_;
 
-  Trace::LogMethodTraceEvent(self, method, Trace::kMethodTraceUnwind);
+  tracer->LogMethodTraceEvent(self, method, Trace::kMethodTraceUnwind);
 
   return lr;
 }
diff --git a/src/thread.cc b/src/thread.cc
index f6ce34d..4adf1e0 100644
--- a/src/thread.cc
+++ b/src/thread.cc
@@ -1114,7 +1114,7 @@
       // DCHECK(frame.GetMethod()->IsWithinCode(pc));  // TODO: restore IsWithinCode
       visitor->VisitFrame(frame, pc);
       pc = ManglePc(frame.GetReturnPC());
-      if (Trace::IsMethodTracingActive()) {
+      if (Runtime::Current()->IsMethodTracingActive()) {
 #if defined(__arm__)
         uintptr_t trace_exit = reinterpret_cast<uintptr_t>(art_trace_exit_from_code);
         if (ManglePc(trace_exit) == pc) {
@@ -1359,7 +1359,7 @@
         native_method_count_++;
       } else {
         // Unwind stack during method tracing
-        if (Trace::IsMethodTracingActive()) {
+        if (Runtime::Current()->IsMethodTracingActive()) {
 #if defined(__arm__)
           uintptr_t trace_exit = reinterpret_cast<uintptr_t>(art_trace_exit_from_code);
           if (ManglePc(trace_exit) == pc) {
diff --git a/src/trace.cc b/src/trace.cc
index 56e1eac..ff828a3 100644
--- a/src/trace.cc
+++ b/src/trace.cc
@@ -12,6 +12,9 @@
 #include "runtime_support.h"
 #include "thread.h"
 
+
+namespace art {
+
 static const uint32_t kTraceMethodActionMask      = 0x03; // two bits
 static const char     kTraceTokenChar             = '*';
 static const uint16_t kTraceHeaderLength          = 32;
@@ -28,23 +31,6 @@
   return (method | traceEvent);
 }
 
-namespace art {
-
-// TODO: Replace class statics with singleton instance
-bool Trace::method_tracing_active_ = false;
-std::map<const Method*, const void*> Trace::saved_code_map_;
-std::set<const Method*> Trace::visited_methods_;
-std::map<Thread*, uint64_t> Trace::thread_clock_base_map_;
-uint8_t* Trace::buf_;
-File* Trace::trace_file_;
-bool Trace::direct_to_ddms_ = false;
-int Trace::buffer_size_ = 0;
-uint64_t Trace::start_time_ = 0;
-bool Trace::overflow_ = false;
-uint16_t Trace::trace_version_;
-uint16_t Trace::record_size_;
-volatile int32_t Trace::cur_offset_;
-
 bool UseThreadCpuClock() {
   // TODO: Allow control over which clock is used
   return true;
@@ -107,17 +93,18 @@
 
 #if defined(__arm__)
 static bool InstallStubsClassVisitor(Class* klass, void* trace_stub) {
+  Trace* tracer = Runtime::Current()->GetTracer();
   for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
     Method* method = klass->GetDirectMethod(i);
     if (method->GetCode() != trace_stub) {
-      Trace::SaveAndUpdateCode(method, trace_stub);
+      tracer->SaveAndUpdateCode(method, trace_stub);
     }
   }
 
   for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
     Method* method = klass->GetVirtualMethod(i);
     if (method->GetCode() != trace_stub) {
-      Trace::SaveAndUpdateCode(method, trace_stub);
+      tracer->SaveAndUpdateCode(method, trace_stub);
     }
   }
 
@@ -134,17 +121,18 @@
 }
 
 static bool UninstallStubsClassVisitor(Class* klass, void* trace_stub) {
+  Trace* tracer = Runtime::Current()->GetTracer();
   for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
     Method* method = klass->GetDirectMethod(i);
-    if (Trace::GetSavedCodeFromMap(method) != NULL) {
-      Trace::ResetSavedCode(method);
+    if (tracer->GetSavedCodeFromMap(method) != NULL) {
+      tracer->ResetSavedCode(method);
     }
   }
 
   for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
     Method* method = klass->GetVirtualMethod(i);
-    if (Trace::GetSavedCodeFromMap(method) != NULL) {
-      Trace::ResetSavedCode(method);
+    if (tracer->GetSavedCodeFromMap(method) != NULL) {
+      tracer->ResetSavedCode(method);
     }
   }
 
@@ -154,8 +142,8 @@
       const void* code = c_and_dm->GetResolvedCode(i);
       if (code == trace_stub) {
         Method* method = klass->GetDexCache()->GetResolvedMethod(i);
-        if (Trace::GetSavedCodeFromMap(method) != NULL) {
-          Trace::ResetSavedCode(method);
+        if (tracer->GetSavedCodeFromMap(method) != NULL) {
+          tracer->ResetSavedCode(method);
         }
         c_and_dm->SetResolvedDirectMethod(i, method);
       }
@@ -186,62 +174,53 @@
 #endif
 
 void Trace::AddSavedCodeToMap(const Method* method, const void* code) {
-  CHECK(IsMethodTracingActive());
   saved_code_map_.insert(std::make_pair(method, code));
 }
 
 void Trace::RemoveSavedCodeFromMap(const Method* method) {
-  CHECK(IsMethodTracingActive());
   saved_code_map_.erase(method);
 }
 
 const void* Trace::GetSavedCodeFromMap(const Method* method) {
-  CHECK(IsMethodTracingActive());
-  return saved_code_map_.find(method)->second;
+  typedef std::map<const Method*, const void*>::const_iterator It; // TODO: C++0x auto
+  It it = saved_code_map_.find(method);
+  if (it == saved_code_map_.end()) {
+    return NULL;
+  } else {
+    return it->second;
+  }
 }
 
 void Trace::SaveAndUpdateCode(Method* method, const void* new_code) {
-  CHECK(IsMethodTracingActive());
   CHECK(GetSavedCodeFromMap(method) == NULL);
   AddSavedCodeToMap(method, method->GetCode());
   method->SetCode(new_code);
 }
 
 void Trace::ResetSavedCode(Method* method) {
-  CHECK(IsMethodTracingActive());
   CHECK(GetSavedCodeFromMap(method) != NULL);
   method->SetCode(GetSavedCodeFromMap(method));
   RemoveSavedCodeFromMap(method);
 }
 
-bool Trace::IsMethodTracingActive() {
-  return method_tracing_active_;
-}
-
-void Trace::SetMethodTracingActive(bool value) {
-  method_tracing_active_ = value;
-}
-
 void Trace::Start(const char* trace_filename, int trace_fd, int buffer_size, int flags, bool direct_to_ddms) {
-  LOG(INFO) << "Starting method tracing...";
-  if (IsMethodTracingActive()) {
-    // TODO: Stop the trace, then start it up again instead of returning.
+  if (Runtime::Current()->IsMethodTracingActive()) {
     LOG(INFO) << "Trace already in progress, ignoring this request";
     return;
   }
 
-  // Suspend all threads.
   ScopedThreadStateChange tsc(Thread::Current(), Thread::kRunnable);
   Runtime::Current()->GetThreadList()->SuspendAll(false);
 
-  // Open files and allocate storage.
+  // Open trace file if not going directly to ddms.
+  File* trace_file = NULL;
   if (!direct_to_ddms) {
     if (trace_fd < 0) {
-      trace_file_ = OS::OpenFile(trace_filename, true);
+      trace_file = OS::OpenFile(trace_filename, true);
     } else {
-      trace_file_ = OS::FileFromFd("tracefile", trace_fd);
+      trace_file = OS::FileFromFd("tracefile", trace_fd);
     }
-    if (trace_file_ == NULL) {
+    if (trace_file == NULL) {
       PLOG(ERROR) << "Unable to open trace file '" << trace_filename;
       Thread::Current()->ThrowNewException("Ljava/lang/RuntimeException;",
           StringPrintf("Unable to open trace file '%s'", trace_filename).c_str());
@@ -249,14 +228,35 @@
       return;
     }
   }
-  buf_ = new uint8_t[buffer_size]();
 
-  // Populate profiler state.
-  direct_to_ddms_ = direct_to_ddms;
-  buffer_size_ = buffer_size;
-  overflow_ = false;
+  // Create Trace object.
+  Trace* tracer(new Trace(trace_file, buffer_size));
+  Runtime::Current()->EnableMethodTracing(tracer);
+  tracer->BeginTracing();
+
+  Runtime::Current()->GetThreadList()->ResumeAll(false);
+}
+
+void Trace::Stop() {
+  if (!Runtime::Current()->IsMethodTracingActive()) {
+    LOG(INFO) << "Trace stop requested, but no trace currently running";
+    return;
+  }
+
+  ScopedThreadStateChange tsc(Thread::Current(), Thread::kRunnable);
+  Runtime::Current()->GetThreadList()->SuspendAll(false);
+
+  Runtime::Current()->GetTracer()->FinishTracing();
+  Runtime::Current()->DisableMethodTracing();
+
+  Runtime::Current()->GetThreadList()->ResumeAll(false);
+}
+
+void Trace::BeginTracing() {
+  // Set the start time of tracing.
   start_time_ = MicroTime();
 
+  // Set trace version and record size.
   if (UseThreadCpuClock() && UseWallClock()) {
     trace_version_ = kTraceVersionDualClock;
     record_size_ = kTraceRecordSizeDualClock;
@@ -265,46 +265,27 @@
     record_size_ = kTraceRecordSizeSingleClock;
   }
 
-  saved_code_map_.clear();
-  visited_methods_.clear();
-  thread_clock_base_map_.clear();
-
   // Set up the beginning of the trace.
-  memset(buf_, 0, kTraceHeaderLength);
-  Append4LE(buf_, kTraceMagicValue);
-  Append2LE(buf_ + 4, trace_version_);
-  Append2LE(buf_ + 6, kTraceHeaderLength);
-  Append8LE(buf_ + 8, start_time_);
+  memset(buf_.get(), 0, kTraceHeaderLength);
+  Append4LE(buf_.get(), kTraceMagicValue);
+  Append2LE(buf_.get() + 4, trace_version_);
+  Append2LE(buf_.get() + 6, kTraceHeaderLength);
+  Append8LE(buf_.get() + 8, start_time_);
   if (trace_version_ >= kTraceVersionDualClock) {
-    Append2LE(buf_ + 16, record_size_);
+    Append2LE(buf_.get() + 16, record_size_);
   }
-  cur_offset_ = kTraceHeaderLength;
 
-  SetMethodTracingActive(true);
+  // Update current offset.
+  cur_offset_ = kTraceHeaderLength;
 
   // Install all method tracing stubs.
   InstallStubs();
-  LOG(INFO) << "Method tracing started";
-
-  Runtime::Current()->GetThreadList()->ResumeAll(false);
 }
 
-void Trace::Stop() {
-  LOG(INFO) << "Stopping method tracing...";
-  if (!IsMethodTracingActive()) {
-    LOG(INFO) << "Trace stop requested, but no trace currently running";
-    return;
-  }
-
-  // Suspend all threads.
-  ScopedThreadStateChange tsc(Thread::Current(), Thread::kRunnable);
-  Runtime::Current()->GetThreadList()->SuspendAll(false);
-
+void Trace::FinishTracing() {
   // Uninstall all method tracing stubs.
   UninstallStubs();
 
-  SetMethodTracingActive(false);
-
   // Compute elapsed time.
   uint64_t elapsed = MicroTime() - start_time_;
 
@@ -338,29 +319,22 @@
   os << StringPrintf("%cend\n", kTraceTokenChar);
 
   std::string header(os.str());
-  if (direct_to_ddms_) {
+  if (trace_file_.get() == NULL) {
     struct iovec iov[2];
     iov[0].iov_base = reinterpret_cast<void*>(const_cast<char*>(header.c_str()));
     iov[0].iov_len = header.length();
-    iov[1].iov_base = buf_;
+    iov[1].iov_base = buf_.get();
     iov[1].iov_len = final_offset;
     Dbg::DdmSendChunkV(CHUNK_TYPE("MPSE"), iov, 2);
   } else {
     if (!trace_file_->WriteFully(header.c_str(), header.length()) ||
-        !trace_file_->WriteFully(buf_, final_offset)) {
+        !trace_file_->WriteFully(buf_.get(), final_offset)) {
       int err = errno;
       LOG(ERROR) << "Trace data write failed: " << strerror(err);
       Thread::Current()->ThrowNewException("Ljava/lang/RuntimeException;",
           StringPrintf("Trace data write failed: %s", strerror(err)).c_str());
     }
-    delete trace_file_;
   }
-
-  delete buf_;
-
-  LOG(INFO) << "Method tracing stopped";
-
-  Runtime::Current()->GetThreadList()->ResumeAll(false);
 }
 
 void Trace::LogMethodTraceEvent(Thread* self, const Method* method, Trace::TraceEvent event) {
@@ -384,7 +358,7 @@
   uint32_t method_value = TraceMethodCombine(reinterpret_cast<uint32_t>(method), event);
 
   // Write data
-  uint8_t* ptr = buf_ + old_offset;
+  uint8_t* ptr = buf_.get() + old_offset;
   Append2LE(ptr, self->GetTid());
   Append4LE(ptr + 2, method_value);
   ptr += 6;
@@ -403,8 +377,8 @@
 }
 
 void Trace::GetVisitedMethods(size_t end_offset) {
-  uint8_t* ptr = buf_ + kTraceHeaderLength;
-  uint8_t* end = buf_ + end_offset;
+  uint8_t* ptr = buf_.get() + kTraceHeaderLength;
+  uint8_t* end = buf_.get() + end_offset;
 
   while (ptr < end) {
     uint32_t method_value = ptr[2] | (ptr[3] << 8) | (ptr[4] << 16) | (ptr[5] << 24);
@@ -424,7 +398,6 @@
         mh.GetSignature().c_str(), mh.GetDeclaringClassSourceFile(),
         mh.GetLineNumFromNativePC(0));
   }
-  visited_methods_.clear();
 }
 
 static void DumpThread(Thread* t, void* arg) {
diff --git a/src/trace.h b/src/trace.h
index 9637163..85d328c 100644
--- a/src/trace.h
+++ b/src/trace.h
@@ -11,6 +11,7 @@
 #include "file.h"
 #include "globals.h"
 #include "macros.h"
+#include "UniquePtr.h"
 
 namespace art {
 
@@ -38,50 +39,57 @@
   static void Start(const char* trace_filename, int trace_fd, int buffer_size, int flags, bool direct_to_ddms);
   static void Stop();
 
-  static void LogMethodTraceEvent(Thread* self, const Method* method, TraceEvent event);
+  void LogMethodTraceEvent(Thread* self, const Method* method, TraceEvent event);
 
-  static bool IsMethodTracingActive();
-  static void SetMethodTracingActive(bool value);
+  void AddSavedCodeToMap(const Method* method, const void* code);
+  void RemoveSavedCodeFromMap(const Method* method);
+  const void* GetSavedCodeFromMap(const Method* method);
 
-  static void AddSavedCodeToMap(const Method* method, const void* code);
-  static void RemoveSavedCodeFromMap(const Method* method);
-  static const void* GetSavedCodeFromMap(const Method* method);
-
-  static void SaveAndUpdateCode(Method* method, const void* new_code);
-  static void ResetSavedCode(Method* method);
+  void SaveAndUpdateCode(Method* method, const void* new_code);
+  void ResetSavedCode(Method* method);
 
  private:
+  explicit Trace(File* trace_file, int buffer_size)
+      : trace_file_(trace_file), buf_(new uint8_t[buffer_size]()), overflow_(false), buffer_size_(buffer_size),
+        start_time_(0), trace_version_(0), record_size_(0), cur_offset_(0) {
+  }
+
+  void BeginTracing();
+  void FinishTracing();
+
   // Replaces code of each method with a pointer to a stub for method tracing.
-  static void InstallStubs();
+  void InstallStubs();
 
   // Restores original code for each method and fixes the return values of each thread's stack.
-  static void UninstallStubs();
+  void UninstallStubs();
 
   // Methods to output traced methods and threads.
-  static void GetVisitedMethods(size_t end_offset);
-  static void DumpMethodList(std::ostream& os);
-  static void DumpThreadList(std::ostream& os);
+  void GetVisitedMethods(size_t end_offset);
+  void DumpMethodList(std::ostream& os);
+  void DumpThreadList(std::ostream& os);
 
-  static bool method_tracing_active_;
+  // Maps a method to its original code pointer.
+  std::map<const Method*, const void*> saved_code_map_;
 
-  // Maps a method to its original code pointer
-  static std::map<const Method*, const void*> saved_code_map_;
+  // Set of methods visited by the profiler.
+  std::set<const Method*> visited_methods_;
 
-  // Set of methods visited by the profiler
-  static std::set<const Method*> visited_methods_;
+  // Maps a thread to its clock base.
+  std::map<Thread*, uint64_t> thread_clock_base_map_;
 
-  // Maps a thread to its clock base
-  static std::map<Thread*, uint64_t> thread_clock_base_map_;
+  // File to write trace data out to, NULL if direct to ddms.
+  UniquePtr<File> trace_file_;
 
-  static uint8_t* buf_;
-  static File* trace_file_;
-  static bool direct_to_ddms_;
-  static int buffer_size_;
-  static uint64_t start_time_;
-  static bool overflow_;
-  static uint16_t trace_version_;
-  static uint16_t record_size_;
-  static volatile int32_t cur_offset_;
+  // Buffer to store trace data.
+  UniquePtr<uint8_t> buf_;
+
+  bool overflow_;
+  int buffer_size_;
+  uint64_t start_time_;
+  uint16_t trace_version_;
+  uint16_t record_size_;
+
+  volatile int32_t cur_offset_;
 
   DISALLOW_COPY_AND_ASSIGN(Trace);
 };