[profiler] Remove the need to pass a MonoProfiler pointer around everywhere.
[mono.git] / mono / profiler / log.c
index 7fbf71f6725b4b22bbd94c21a5dee1de4779a7f8..a0b58f0da923f5cece3d11339634fad4b4d61ac8 100644 (file)
@@ -23,6 +23,7 @@
 #include <mono/utils/lock-free-queue.h>
 #include <mono/utils/mono-conc-hashtable.h>
 #include <mono/utils/mono-counters.h>
+#include <mono/utils/mono-logger-internals.h>
 #include <mono/utils/mono-linked-list-set.h>
 #include <mono/utils/mono-membar.h>
 #include <mono/utils/mono-mmap.h>
@@ -79,11 +80,8 @@ static int max_call_depth = 0;
 static int command_port = 0;
 static int heapshot_requested = 0;
 static int do_mono_sample = 0;
-static int do_debug = 0;
 static int do_coverage = 0;
 static gboolean no_counters = FALSE;
-static gboolean only_coverage = FALSE;
-static gboolean debug_coverage = FALSE;
 static int max_allocated_sample_hits;
 
 #define ENABLED(EVT) (config.effective_mask & (EVT))
@@ -243,13 +241,13 @@ static MonoLinkedListSet profiler_thread_list;
  *     num is always an even number: the even items are the old
  *     addresses, the odd numbers are the respective new object addresses
  * if exinfo == TYPE_GC_HANDLE_CREATED[_BT]
- *     [handle_type: uleb128] GC handle type (System.Runtime.InteropServices.GCHandleType)
+ *     [handle_type: uleb128] MonoGCHandleType enum value
  *     upper bits reserved as flags
  *     [handle: uleb128] GC handle value
  *     [objaddr: sleb128] object pointer differences from obj_base
  *     If exinfo == TYPE_GC_HANDLE_CREATED_BT, a backtrace follows.
  * if exinfo == TYPE_GC_HANDLE_DESTROYED[_BT]
- *     [handle_type: uleb128] GC handle type (System.Runtime.InteropServices.GCHandleType)
+ *     [handle_type: uleb128] MonoGCHandleType enum value
  *     upper bits reserved as flags
  *     [handle: uleb128] GC handle value
  *     If exinfo == TYPE_GC_HANDLE_DESTROYED_BT, a backtrace follows.
@@ -258,7 +256,8 @@ static MonoLinkedListSet profiler_thread_list;
  *
  * type metadata format:
  * type: TYPE_METADATA
- * exinfo: one of: TYPE_END_LOAD, TYPE_END_UNLOAD (optional for TYPE_THREAD and TYPE_DOMAIN)
+ * exinfo: one of: TYPE_END_LOAD, TYPE_END_UNLOAD (optional for TYPE_THREAD and TYPE_DOMAIN,
+ * doesn't occur for TYPE_CLASS)
  * [mtype: byte] metadata type, one of: TYPE_CLASS, TYPE_IMAGE, TYPE_ASSEMBLY, TYPE_DOMAIN,
  * TYPE_THREAD, TYPE_CONTEXT
  * [pointer: sleb128] pointer of the metadata type depending on mtype
@@ -313,7 +312,7 @@ static MonoLinkedListSet profiler_thread_list;
  * type monitor format:
  * type: TYPE_MONITOR
  * exinfo: zero or TYPE_MONITOR_BT
- * [type: byte] MONO_PROFILER_MONITOR_{CONTENTION,FAIL,DONE}
+ * [type: byte] MonoProfilerMonitorEvent enum value
  * [object: sleb128] the lock object as a difference from obj_base
  * If exinfo == TYPE_MONITOR_BT, a backtrace follows.
  *
@@ -459,9 +458,6 @@ struct _LogBuffer {
 typedef struct {
        MonoLinkedListSetNode node;
 
-       // Convenience pointer to the profiler structure.
-       MonoProfiler *profiler;
-
        // Was this thread added to the LLS?
        gboolean attached;
 
@@ -479,8 +475,42 @@ typedef struct {
 
        // Has this thread written a thread end event to `buffer`?
        gboolean ended;
+
+       // Stored in `buffer_lock_state` to take the exclusive lock.
+       int small_id;
 } MonoProfilerThread;
 
+// Do not use these TLS macros directly unless you know what you're doing.
+
+#ifdef HOST_WIN32
+
+#define PROF_TLS_SET(VAL) (TlsSetValue (profiler_tls, (VAL)))
+#define PROF_TLS_GET() ((MonoProfilerThread *) TlsGetValue (profiler_tls))
+#define PROF_TLS_INIT() (profiler_tls = TlsAlloc ())
+#define PROF_TLS_FREE() (TlsFree (profiler_tls))
+
+static DWORD profiler_tls;
+
+#elif HAVE_KW_THREAD
+
+#define PROF_TLS_SET(VAL) (profiler_tls = (VAL))
+#define PROF_TLS_GET() (profiler_tls)
+#define PROF_TLS_INIT()
+#define PROF_TLS_FREE()
+
+static __thread MonoProfilerThread *profiler_tls;
+
+#else
+
+#define PROF_TLS_SET(VAL) (pthread_setspecific (profiler_tls, (VAL)))
+#define PROF_TLS_GET() ((MonoProfilerThread *) pthread_getspecific (profiler_tls))
+#define PROF_TLS_INIT() (pthread_key_create (&profiler_tls, NULL))
+#define PROF_TLS_FREE() (pthread_key_delete (profiler_tls))
+
+static pthread_key_t profiler_tls;
+
+#endif
+
 static uintptr_t
 thread_id (void)
 {
@@ -558,17 +588,22 @@ init_time (void)
 }
 
 /*
- * These macros should be used when writing an event to a log buffer. They take
- * care of a bunch of stuff that can be repetitive and error-prone, such as
- * acquiring/releasing the buffer lock, incrementing the event counter,
- * expanding the log buffer, processing requests, etc. They also create a scope
- * so that it's harder to leak the LogBuffer pointer, which can be problematic
- * as the pointer is unstable when the buffer lock isn't acquired.
+ * These macros should be used when writing an event to a log buffer. They
+ * take care of a bunch of stuff that can be repetitive and error-prone, such
+ * as attaching the current thread, acquiring/releasing the buffer lock,
+ * incrementing the event counter, expanding the log buffer, etc. They also
+ * create a scope so that it's harder to leak the LogBuffer pointer, which can
+ * be problematic as the pointer is unstable when the buffer lock isn't
+ * acquired.
+ *
+ * If the calling thread is already attached, these macros will not alter its
+ * attach mode (i.e. whether it's added to the LLS). If the thread is not
+ * attached, init_thread () will be called with add_to_lls = TRUE.
  */
 
 #define ENTER_LOG(COUNTER, BUFFER, SIZE) \
        do { \
-               MonoProfilerThread *thread__ = PROF_TLS_GET (); \
+               MonoProfilerThread *thread__ = get_thread (); \
                if (thread__->attached) \
                        buffer_lock (); \
                g_assert (!thread__->busy && "Why are we trying to write a new event while already writing one?"); \
@@ -590,84 +625,6 @@ init_time (void)
 
 #define EXIT_LOG EXIT_LOG_EXPLICIT (DO_SEND)
 
-static volatile gint32 buffer_rwlock_count;
-static volatile gpointer buffer_rwlock_exclusive;
-
-// Can be used recursively.
-static void
-buffer_lock (void)
-{
-       /*
-        * If the thread holding the exclusive lock tries to modify the
-        * reader count, just make it a no-op. This way, we also avoid
-        * invoking the GC safe point macros below, which could break if
-        * done from a thread that is currently the initiator of STW.
-        *
-        * In other words, we rely on the fact that the GC thread takes
-        * the exclusive lock in the gc_event () callback when the world
-        * is about to stop.
-        */
-       if (InterlockedReadPointer (&buffer_rwlock_exclusive) != (gpointer) thread_id ()) {
-               MONO_ENTER_GC_SAFE;
-
-               while (InterlockedReadPointer (&buffer_rwlock_exclusive))
-                       mono_thread_info_yield ();
-
-               InterlockedIncrement (&buffer_rwlock_count);
-
-               MONO_EXIT_GC_SAFE;
-       }
-
-       mono_memory_barrier ();
-}
-
-static void
-buffer_unlock (void)
-{
-       mono_memory_barrier ();
-
-       // See the comment in buffer_lock ().
-       if (InterlockedReadPointer (&buffer_rwlock_exclusive) == (gpointer) thread_id ())
-               return;
-
-       g_assert (InterlockedRead (&buffer_rwlock_count) && "Why are we trying to decrement a zero reader count?");
-
-       InterlockedDecrement (&buffer_rwlock_count);
-}
-
-// Cannot be used recursively.
-static void
-buffer_lock_excl (void)
-{
-       gpointer tid = (gpointer) thread_id ();
-
-       g_assert (InterlockedReadPointer (&buffer_rwlock_exclusive) != tid && "Why are we taking the exclusive lock twice?");
-
-       MONO_ENTER_GC_SAFE;
-
-       while (InterlockedCompareExchangePointer (&buffer_rwlock_exclusive, tid, 0))
-               mono_thread_info_yield ();
-
-       while (InterlockedRead (&buffer_rwlock_count))
-               mono_thread_info_yield ();
-
-       MONO_EXIT_GC_SAFE;
-
-       mono_memory_barrier ();
-}
-
-static void
-buffer_unlock_excl (void)
-{
-       mono_memory_barrier ();
-
-       g_assert (InterlockedReadPointer (&buffer_rwlock_exclusive) && "Why is the exclusive lock not held?");
-       g_assert (InterlockedReadPointer (&buffer_rwlock_exclusive) == (gpointer) thread_id () && "Why does another thread hold the exclusive lock?");
-       g_assert (!InterlockedRead (&buffer_rwlock_count) && "Why are there readers when the exclusive lock is held?");
-
-       InterlockedWritePointer (&buffer_rwlock_exclusive, NULL);
-}
-
 typedef struct _BinaryObject BinaryObject;
 struct _BinaryObject {
        BinaryObject *next;
@@ -676,6 +633,7 @@ struct _BinaryObject {
 };
 
 struct _MonoProfiler {
+       MonoProfilerHandle handle;
        FILE* file;
 #if defined (HAVE_SYS_ZLIB)
        gzFile gzfile;
@@ -706,6 +664,8 @@ struct _MonoProfiler {
        GPtrArray *coverage_filters;
 };
 
+static struct _MonoProfiler log_profiler;
+
 typedef struct {
        MonoLockFreeQueueNode node;
        GPtrArray *methods;
@@ -720,35 +680,6 @@ typedef struct {
        uint64_t time;
 } MethodInfo;
 
-#ifdef HOST_WIN32
-
-#define PROF_TLS_SET(VAL) (TlsSetValue (profiler_tls, (VAL)))
-#define PROF_TLS_GET() ((MonoProfilerThread *) TlsGetValue (profiler_tls))
-#define PROF_TLS_INIT() (profiler_tls = TlsAlloc ())
-#define PROF_TLS_FREE() (TlsFree (profiler_tls))
-
-static DWORD profiler_tls;
-
-#elif HAVE_KW_THREAD
-
-#define PROF_TLS_SET(VAL) (profiler_tls = (VAL))
-#define PROF_TLS_GET() (profiler_tls)
-#define PROF_TLS_INIT()
-#define PROF_TLS_FREE()
-
-static __thread MonoProfilerThread *profiler_tls;
-
-#else
-
-#define PROF_TLS_SET(VAL) (pthread_setspecific (profiler_tls, (VAL)))
-#define PROF_TLS_GET() ((MonoProfilerThread *) pthread_getspecific (profiler_tls))
-#define PROF_TLS_INIT() (pthread_key_create (&profiler_tls, NULL))
-#define PROF_TLS_FREE() (pthread_key_delete (profiler_tls))
-
-static pthread_key_t profiler_tls;
-
-#endif
-
 static char*
 pstrdup (const char *s)
 {
@@ -771,9 +702,9 @@ free_buffer (void *buf, int size)
 }
 
 static LogBuffer*
-create_buffer (uintptr_t tid)
+create_buffer (uintptr_t tid, int bytes)
 {
-       LogBuffer* buf = (LogBuffer *) alloc_buffer (BUFFER_SIZE);
+       LogBuffer* buf = (LogBuffer *) alloc_buffer (MAX (BUFFER_SIZE, bytes));
 
        InterlockedIncrement (&buffer_allocations_ctr);
 
@@ -796,7 +727,7 @@ create_buffer (uintptr_t tid)
 static void
 init_buffer_state (MonoProfilerThread *thread)
 {
-       thread->buffer = create_buffer (thread->node.key);
+       thread->buffer = create_buffer (thread->node.key, 0);
        thread->methods = NULL;
 }
 
@@ -809,7 +740,7 @@ clear_hazard_pointers (MonoThreadHazardPointers *hp)
 }
 
 static MonoProfilerThread *
-init_thread (MonoProfiler *prof, gboolean add_to_lls)
+init_thread (gboolean add_to_lls)
 {
        MonoProfilerThread *thread = PROF_TLS_GET ();
 
@@ -829,7 +760,6 @@ init_thread (MonoProfiler *prof, gboolean add_to_lls)
 
        thread = g_malloc (sizeof (MonoProfilerThread));
        thread->node.key = thread_id ();
-       thread->profiler = prof;
        thread->attached = add_to_lls;
        thread->call_depth = 0;
        thread->busy = 0;
@@ -837,6 +767,8 @@ init_thread (MonoProfiler *prof, gboolean add_to_lls)
 
        init_buffer_state (thread);
 
+       thread->small_id = mono_thread_info_register_small_id ();
+
        /*
         * Some internal profiler threads don't need to be cleaned up
         * by the main thread on shutdown.
@@ -862,22 +794,155 @@ deinit_thread (MonoProfilerThread *thread)
        PROF_TLS_SET (NULL);
 }
 
+static MonoProfilerThread *
+get_thread (void)
+{
+       return init_thread (TRUE);
+}
+
 // Only valid if init_thread () was called with add_to_lls = FALSE.
 static LogBuffer *
 ensure_logbuf_unsafe (MonoProfilerThread *thread, int bytes)
 {
        LogBuffer *old = thread->buffer;
 
-       if (old && old->cursor + bytes + 100 < old->buf_end)
+       if (old->cursor + bytes < old->buf_end)
                return old;
 
-       LogBuffer *new_ = create_buffer (thread->node.key);
+       LogBuffer *new_ = create_buffer (thread->node.key, bytes);
        new_->next = old;
        thread->buffer = new_;
 
        return new_;
 }
 
+/*
+ * This is a reader/writer spin lock of sorts used to protect log buffers.
+ * When a thread modifies its own log buffer, it increments the reader
+ * count. When a thread wants to access log buffers of other threads, it
+ * takes the exclusive lock.
+ *
+ * `buffer_lock_state` holds the reader count in its lower 16 bits, and
+ * the small ID of the thread currently holding the exclusive (writer)
+ * lock in its upper 16 bits. Both can be zero. It's important that the
+ * whole lock state is a single word that can be read/written atomically
+ * to avoid race conditions where there could end up being readers while
+ * the writer lock is held.
+ *
+ * The lock is writer-biased. When a thread wants to take the exclusive
+ * lock, it increments `buffer_lock_exclusive_intent` which will make new
+ * readers spin until it's back to zero, then takes the exclusive lock
+ * once the reader count has reached zero. After releasing the exclusive
+ * lock, it decrements `buffer_lock_exclusive_intent`, which, when it
+ * reaches zero again, allows readers to increment the reader count.
+ *
+ * The writer bias is necessary because we take the exclusive lock in
+ * `gc_event ()` during STW. If the writer bias was not there, and a
+ * program had a large number of threads, STW-induced pauses could be
+ * significantly longer than they have to be. Also, we emit periodic
+ * sync points from the helper thread, which requires taking the
+ * exclusive lock, and we need those to arrive with a reasonably
+ * consistent frequency so that readers don't have to queue up too many
+ * events between sync points.
+ *
+ * The lock does not support recursion.
+ */
+static volatile gint32 buffer_lock_state;
+static volatile gint32 buffer_lock_exclusive_intent;
+
+static void
+buffer_lock (void)
+{
+       /*
+        * If the thread holding the exclusive lock tries to modify the
+        * reader count, just make it a no-op. This way, we also avoid
+        * invoking the GC safe point macros below, which could break if
+        * done from a thread that is currently the initiator of STW.
+        *
+        * In other words, we rely on the fact that the GC thread takes
+        * the exclusive lock in the gc_event () callback when the world
+        * is about to stop.
+        */
+       if (InterlockedRead (&buffer_lock_state) != get_thread ()->small_id << 16) {
+               MONO_ENTER_GC_SAFE;
+
+               gint32 old, new_;
+
+               do {
+               restart:
+                       // Hold off if a thread wants to take the exclusive lock.
+                       while (InterlockedRead (&buffer_lock_exclusive_intent))
+                               mono_thread_info_yield ();
+
+                       old = InterlockedRead (&buffer_lock_state);
+
+                       // Is a thread holding the exclusive lock?
+                       if (old >> 16) {
+                               mono_thread_info_yield ();
+                               goto restart;
+                       }
+
+                       new_ = old + 1;
+               } while (InterlockedCompareExchange (&buffer_lock_state, new_, old) != old);
+
+               MONO_EXIT_GC_SAFE;
+       }
+
+       mono_memory_barrier ();
+}
+
+static void
+buffer_unlock (void)
+{
+       mono_memory_barrier ();
+
+       gint32 state = InterlockedRead (&buffer_lock_state);
+
+       // See the comment in buffer_lock ().
+       if (state == PROF_TLS_GET ()->small_id << 16)
+               return;
+
+       g_assert (state && "Why are we decrementing a zero reader count?");
+       g_assert (!(state >> 16) && "Why is the exclusive lock held?");
+
+       InterlockedDecrement (&buffer_lock_state);
+}
+
+static void
+buffer_lock_excl (void)
+{
+       gint32 new_ = get_thread ()->small_id << 16;
+
+       g_assert (InterlockedRead (&buffer_lock_state) != new_ && "Why are we taking the exclusive lock twice?");
+
+       InterlockedIncrement (&buffer_lock_exclusive_intent);
+
+       MONO_ENTER_GC_SAFE;
+
+       while (InterlockedCompareExchange (&buffer_lock_state, new_, 0))
+               mono_thread_info_yield ();
+
+       MONO_EXIT_GC_SAFE;
+
+       mono_memory_barrier ();
+}
+
+static void
+buffer_unlock_excl (void)
+{
+       mono_memory_barrier ();
+
+       gint32 state = InterlockedRead (&buffer_lock_state);
+       gint32 excl = state >> 16;
+
+       g_assert (excl && "Why is the exclusive lock not held?");
+       g_assert (excl == PROF_TLS_GET ()->small_id && "Why does another thread hold the exclusive lock?");
+       g_assert (!(state & 0xFFFF) && "Why are there readers when the exclusive lock is held?");
+
+       InterlockedWrite (&buffer_lock_state, 0);
+       InterlockedDecrement (&buffer_lock_exclusive_intent);
+}
+
 static void
 encode_uleb128 (uint64_t value, uint8_t *buf, uint8_t **endbuf)
 {
@@ -987,7 +1052,7 @@ emit_uvalue (LogBuffer *logbuffer, uint64_t value)
 }
 
 static void
-emit_ptr (LogBuffer *logbuffer, void *ptr)
+emit_ptr (LogBuffer *logbuffer, const void *ptr)
 {
        if (!logbuffer->ptr_base)
                logbuffer->ptr_base = (uintptr_t) ptr;
@@ -1011,24 +1076,21 @@ emit_method_inner (LogBuffer *logbuffer, void *method)
        g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
 }
 
+// The reader lock must be held.
 static void
 register_method_local (MonoMethod *method, MonoJitInfo *ji)
 {
-       MonoProfilerThread *thread = PROF_TLS_GET ();
+       MonoProfilerThread *thread = get_thread ();
 
-       if (!mono_conc_hashtable_lookup (thread->profiler->method_table, method)) {
+       if (!mono_conc_hashtable_lookup (log_profiler.method_table, method)) {
                MethodInfo *info = (MethodInfo *) g_malloc (sizeof (MethodInfo));
 
                info->method = method;
                info->ji = ji;
                info->time = current_time ();
 
-               buffer_lock ();
-
                GPtrArray *arr = thread->methods ? thread->methods : (thread->methods = g_ptr_array_new ());
                g_ptr_array_add (arr, info);
-
-               buffer_unlock ();
        }
 }
 
@@ -1123,9 +1185,9 @@ write_header_string (char *p, const char *str)
 }
 
 static void
-dump_header (MonoProfiler *profiler)
+dump_header (void)
 {
-       const char *args = profiler->args;
+       const char *args = log_profiler.args;
        const char *arch = mono_config_get_cpu ();
        const char *os = mono_config_get_os ();
 
@@ -1155,19 +1217,19 @@ dump_header (MonoProfiler *profiler)
        p = write_int32 (p, timer_overhead);
        p = write_int32 (p, 0); /* flags */
        p = write_int32 (p, process_id ());
-       p = write_int16 (p, profiler->command_port);
+       p = write_int16 (p, log_profiler.command_port);
        p = write_header_string (p, args);
        p = write_header_string (p, arch);
        p = write_header_string (p, os);
 
 #if defined (HAVE_SYS_ZLIB)
-       if (profiler->gzfile) {
-               gzwrite (profiler->gzfile, hbuf, p - hbuf);
+       if (log_profiler.gzfile) {
+               gzwrite (log_profiler.gzfile, hbuf, p - hbuf);
        } else
 #endif
        {
-               fwrite (hbuf, p - hbuf, 1, profiler->file);
-               fflush (profiler->file);
+               fwrite (hbuf, p - hbuf, 1, log_profiler.file);
+               fflush (log_profiler.file);
        }
 
        g_free (hbuf);
@@ -1182,14 +1244,14 @@ dump_header (MonoProfiler *profiler)
 static void
 send_buffer (MonoProfilerThread *thread)
 {
-       WriterQueueEntry *entry = mono_lock_free_alloc (&thread->profiler->writer_entry_allocator);
+       WriterQueueEntry *entry = mono_lock_free_alloc (&log_profiler.writer_entry_allocator);
        entry->methods = thread->methods;
        entry->buffer = thread->buffer;
 
        mono_lock_free_queue_node_init (&entry->node, FALSE);
 
-       mono_lock_free_queue_enqueue (&thread->profiler->writer_queue, &entry->node);
-       mono_os_sem_post (&thread->profiler->writer_queue_sem);
+       mono_lock_free_queue_enqueue (&log_profiler.writer_queue, &entry->node);
+       mono_os_sem_post (&log_profiler.writer_queue_sem);
 }
 
 static void
@@ -1236,13 +1298,13 @@ remove_thread (MonoProfilerThread *thread)
 }
 
 static void
-dump_buffer (MonoProfiler *profiler, LogBuffer *buf)
+dump_buffer (LogBuffer *buf)
 {
        char hbuf [128];
        char *p = hbuf;
 
        if (buf->next)
-               dump_buffer (profiler, buf->next);
+               dump_buffer (buf->next);
 
        if (buf->cursor - buf->buf) {
                p = write_int32 (p, BUF_ID);
@@ -1254,15 +1316,15 @@ dump_buffer (MonoProfiler *profiler, LogBuffer *buf)
                p = write_int64 (p, buf->method_base);
 
 #if defined (HAVE_SYS_ZLIB)
-               if (profiler->gzfile) {
-                       gzwrite (profiler->gzfile, hbuf, p - hbuf);
-                       gzwrite (profiler->gzfile, buf->buf, buf->cursor - buf->buf);
+               if (log_profiler.gzfile) {
+                       gzwrite (log_profiler.gzfile, hbuf, p - hbuf);
+                       gzwrite (log_profiler.gzfile, buf->buf, buf->cursor - buf->buf);
                } else
 #endif
                {
-                       fwrite (hbuf, p - hbuf, 1, profiler->file);
-                       fwrite (buf->buf, buf->cursor - buf->buf, 1, profiler->file);
-                       fflush (profiler->file);
+                       fwrite (hbuf, p - hbuf, 1, log_profiler.file);
+                       fwrite (buf->buf, buf->cursor - buf->buf, 1, log_profiler.file);
+                       fflush (log_profiler.file);
                }
        }
 
@@ -1270,12 +1332,12 @@ dump_buffer (MonoProfiler *profiler, LogBuffer *buf)
 }
 
 static void
-dump_buffer_threadless (MonoProfiler *profiler, LogBuffer *buf)
+dump_buffer_threadless (LogBuffer *buf)
 {
        for (LogBuffer *iter = buf; iter; iter = iter->next)
                iter->thread_id = 0;
 
-       dump_buffer (profiler, buf);
+       dump_buffer (buf);
 }
 
 // Only valid if init_thread () was called with add_to_lls = FALSE.
@@ -1298,7 +1360,7 @@ send_log_unsafe (gboolean if_needed)
 static void
 sync_point_flush (void)
 {
-       g_assert (InterlockedReadPointer (&buffer_rwlock_exclusive) == (gpointer) thread_id () && "Why don't we hold the exclusive lock?");
+       g_assert (InterlockedRead (&buffer_lock_state) == PROF_TLS_GET ()->small_id << 16 && "Why don't we hold the exclusive lock?");
 
        MONO_LLS_FOREACH_SAFE (&profiler_thread_list, MonoProfilerThread, thread) {
                g_assert (thread->attached && "Why is a thread in the LLS not attached?");
@@ -1312,7 +1374,7 @@ sync_point_flush (void)
 static void
 sync_point_mark (MonoProfilerSyncPointType type)
 {
-       g_assert (InterlockedReadPointer (&buffer_rwlock_exclusive) == (gpointer) thread_id () && "Why don't we hold the exclusive lock?");
+       g_assert (InterlockedRead (&buffer_lock_state) == PROF_TLS_GET ()->small_id << 16 && "Why don't we hold the exclusive lock?");
 
        ENTER_LOG (&sync_points_ctr, logbuffer,
                EVENT_SIZE /* event */ +
@@ -1382,7 +1444,7 @@ static gboolean do_heap_walk = FALSE;
 static gboolean ignore_heap_events;
 
 static void
-gc_roots (MonoProfiler *prof, int num, void **objects, int *root_types, uintptr_t *extra_info)
+gc_roots (MonoProfiler *prof, MonoObject *const *objects, const MonoProfilerGCRootType *root_types, const uintptr_t *extra_info, uint64_t num)
 {
        if (ignore_heap_events)
                return;
@@ -1422,7 +1484,7 @@ trigger_on_demand_heapshot (void)
 #define ALL_GC_EVENTS_MASK (PROFLOG_GC_MOVES_EVENTS | PROFLOG_GC_ROOT_EVENTS | PROFLOG_GC_EVENTS | PROFLOG_HEAPSHOT_FEATURE)
 
 static void
-gc_event (MonoProfiler *profiler, MonoGCEvent ev, int generation)
+gc_event (MonoProfiler *profiler, MonoProfilerGCEvent ev, uint32_t generation)
 {
        if (ev == MONO_GC_EVENT_START) {
                uint64_t now = current_time ();
@@ -1540,7 +1602,7 @@ gc_event (MonoProfiler *profiler, MonoGCEvent ev, int generation)
 }
 
 static void
-gc_resize (MonoProfiler *profiler, int64_t new_size)
+gc_resize (MonoProfiler *profiler, uintptr_t new_size)
 {
        ENTER_LOG (&gc_resizes_ctr, logbuffer,
                EVENT_SIZE /* event */ +
@@ -1570,7 +1632,6 @@ walk_stack (MonoMethod *method, int32_t native_offset, int32_t il_offset, mono_b
                frame->il_offsets [frame->count] = il_offset;
                frame->native_offsets [frame->count] = native_offset;
                frame->methods [frame->count++] = method;
-               //printf ("In %d %s at %d (native: %d)\n", frame->count, mono_method_get_name (method), il_offset, native_offset);
        }
        return frame->count == num_frames;
 }
@@ -1588,26 +1649,17 @@ collect_bt (FrameData *data)
 }
 
 static void
-emit_bt (MonoProfiler *prof, LogBuffer *logbuffer, FrameData *data)
+emit_bt (LogBuffer *logbuffer, FrameData *data)
 {
-       /* FIXME: this is actually tons of data and we should
-        * just output it the first time and use an id the next
-        */
-       if (data->count > num_frames)
-               printf ("bad num frames: %d\n", data->count);
        emit_value (logbuffer, data->count);
-       //if (*p != data.count) {
-       //      printf ("bad num frames enc at %d: %d -> %d\n", count, data.count, *p); printf ("frames end: %p->%p\n", p, logbuffer->cursor); exit(0);}
-       while (data->count) {
+
+       while (data->count)
                emit_method (logbuffer, data->methods [--data->count]);
-       }
 }
 
 static void
-gc_alloc (MonoProfiler *prof, MonoObject *obj, MonoClass *klass)
+gc_alloc (MonoProfiler *prof, MonoObject *obj)
 {
-       init_thread (prof, TRUE);
-
        int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces) ? TYPE_ALLOC_BT : 0;
        FrameData data;
        uintptr_t len = mono_object_get_size (obj);
@@ -1632,18 +1684,18 @@ gc_alloc (MonoProfiler *prof, MonoObject *obj, MonoClass *klass)
        );
 
        emit_event (logbuffer, do_bt | TYPE_ALLOC);
-       emit_ptr (logbuffer, klass);
+       emit_ptr (logbuffer, mono_object_get_class (obj));
        emit_obj (logbuffer, obj);
        emit_value (logbuffer, len);
 
        if (do_bt)
-               emit_bt (prof, logbuffer, &data);
+               emit_bt (logbuffer, &data);
 
        EXIT_LOG;
 }
 
 static void
-gc_moves (MonoProfiler *prof, void **objects, int num)
+gc_moves (MonoProfiler *prof, MonoObject *const *objects, uint64_t num)
 {
        ENTER_LOG (&gc_moves_ctr, logbuffer,
                EVENT_SIZE /* event */ +
@@ -1663,7 +1715,7 @@ gc_moves (MonoProfiler *prof, void **objects, int num)
 }
 
 static void
-gc_handle (MonoProfiler *prof, int op, int type, uintptr_t handle, MonoObject *obj)
+gc_handle (MonoProfiler *prof, int op, MonoGCHandleType type, uint32_t handle, MonoObject *obj)
 {
        int do_bt = nocalls && InterlockedRead (&runtime_inited) && !notraces;
        FrameData data;
@@ -1702,11 +1754,23 @@ gc_handle (MonoProfiler *prof, int op, int type, uintptr_t handle, MonoObject *o
                emit_obj (logbuffer, obj);
 
        if (do_bt)
-               emit_bt (prof, logbuffer, &data);
+               emit_bt (logbuffer, &data);
 
        EXIT_LOG;
 }
 
+static void
+gc_handle_created (MonoProfiler *prof, uint32_t handle, MonoGCHandleType type, MonoObject *obj)
+{
+       gc_handle (prof, MONO_PROFILER_GC_HANDLE_CREATED, type, handle, obj);
+}
+
+static void
+gc_handle_deleted (MonoProfiler *prof, uint32_t handle, MonoGCHandleType type)
+{
+       gc_handle (prof, MONO_PROFILER_GC_HANDLE_DESTROYED, type, handle, NULL);
+}
+
 static void
 finalize_begin (MonoProfiler *prof)
 {
@@ -1799,11 +1863,8 @@ type_name (MonoClass *klass)
 }
 
 static void
-image_loaded (MonoProfiler *prof, MonoImage *image, int result)
+image_loaded (MonoProfiler *prof, MonoImage *image)
 {
-       if (result != MONO_PROFILE_OK)
-               return;
-
        const char *name = mono_image_get_filename (image);
        int nlen = strlen (name) + 1;
 
@@ -1846,11 +1907,8 @@ image_unloaded (MonoProfiler *prof, MonoImage *image)
 }
 
 static void
-assembly_loaded (MonoProfiler *prof, MonoAssembly *assembly, int result)
+assembly_loaded (MonoProfiler *prof, MonoAssembly *assembly)
 {
-       if (result != MONO_PROFILE_OK)
-               return;
-
        char *name = mono_stringify_assembly_name (mono_assembly_get_name (assembly));
        int nlen = strlen (name) + 1;
        MonoImage *image = mono_assembly_get_image (assembly);
@@ -1903,11 +1961,8 @@ assembly_unloaded (MonoProfiler *prof, MonoAssembly *assembly)
 }
 
 static void
-class_loaded (MonoProfiler *prof, MonoClass *klass, int result)
+class_loaded (MonoProfiler *prof, MonoClass *klass)
 {
-       if (result != MONO_PROFILE_OK)
-               return;
-
        char *name;
 
        if (InterlockedRead (&runtime_inited))
@@ -1941,50 +1996,10 @@ class_loaded (MonoProfiler *prof, MonoClass *klass, int result)
                g_free (name);
 }
 
-static void
-class_unloaded (MonoProfiler *prof, MonoClass *klass)
-{
-       char *name;
-
-       if (InterlockedRead (&runtime_inited))
-               name = mono_type_get_name (mono_class_get_type (klass));
-       else
-               name = type_name (klass);
-
-       int nlen = strlen (name) + 1;
-       MonoImage *image = mono_class_get_image (klass);
-
-       ENTER_LOG (&class_unloads_ctr, logbuffer,
-               EVENT_SIZE /* event */ +
-               BYTE_SIZE /* type */ +
-               LEB128_SIZE /* klass */ +
-               LEB128_SIZE /* image */ +
-               nlen /* name */
-       );
-
-       emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
-       emit_byte (logbuffer, TYPE_CLASS);
-       emit_ptr (logbuffer, klass);
-       emit_ptr (logbuffer, image);
-       memcpy (logbuffer->cursor, name, nlen);
-       logbuffer->cursor += nlen;
-
-       EXIT_LOG;
-
-       if (runtime_inited)
-               mono_free (name);
-       else
-               g_free (name);
-}
-
-static void process_method_enter_coverage (MonoProfiler *prof, MonoMethod *method);
-
 static void
 method_enter (MonoProfiler *prof, MonoMethod *method)
 {
-       process_method_enter_coverage (prof, method);
-
-       if (!only_coverage && PROF_TLS_GET ()->call_depth++ <= max_call_depth) {
+       if (get_thread ()->call_depth++ <= max_call_depth) {
                ENTER_LOG (&method_entries_ctr, logbuffer,
                        EVENT_SIZE /* event */ +
                        LEB128_SIZE /* method */
@@ -2000,7 +2015,7 @@ method_enter (MonoProfiler *prof, MonoMethod *method)
 static void
 method_leave (MonoProfiler *prof, MonoMethod *method)
 {
-       if (!only_coverage && --PROF_TLS_GET ()->call_depth <= max_call_depth) {
+       if (--get_thread ()->call_depth <= max_call_depth) {
                ENTER_LOG (&method_exits_ctr, logbuffer,
                        EVENT_SIZE /* event */ +
                        LEB128_SIZE /* method */
@@ -2014,9 +2029,9 @@ method_leave (MonoProfiler *prof, MonoMethod *method)
 }
 
 static void
-method_exc_leave (MonoProfiler *prof, MonoMethod *method)
+method_exc_leave (MonoProfiler *prof, MonoMethod *method, MonoObject *exc)
 {
-       if (!only_coverage && !nocalls && --PROF_TLS_GET ()->call_depth <= max_call_depth) {
+       if (!nocalls && --get_thread ()->call_depth <= max_call_depth) {
                ENTER_LOG (&method_exception_exits_ctr, logbuffer,
                        EVENT_SIZE /* event */ +
                        LEB128_SIZE /* method */
@@ -2029,23 +2044,30 @@ method_exc_leave (MonoProfiler *prof, MonoMethod *method)
        }
 }
 
+static MonoProfilerCallInstrumentationFlags
+method_filter (MonoProfiler *prof, MonoMethod *method)
+{
+       return MONO_PROFILER_CALL_INSTRUMENTATION_PROLOGUE | MONO_PROFILER_CALL_INSTRUMENTATION_EPILOGUE;
+}
+
 static void
-method_jitted (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *ji, int result)
+method_jitted (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *ji)
 {
-       if (result != MONO_PROFILE_OK)
-               return;
+       buffer_lock ();
 
        register_method_local (method, ji);
+
+       buffer_unlock ();
 }
 
 static void
-code_buffer_new (MonoProfiler *prof, void *buffer, int size, MonoProfilerCodeBufferType type, void *data)
+code_buffer_new (MonoProfiler *prof, const mono_byte *buffer, uint64_t size, MonoProfilerCodeBufferType type, const void *data)
 {
-       char *name;
+       const char *name;
        int nlen;
 
        if (type == MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE) {
-               name = (char *) data;
+               name = (const char *) data;
                nlen = strlen (name) + 1;
        } else {
                name = NULL;
@@ -2099,13 +2121,13 @@ throw_exc (MonoProfiler *prof, MonoObject *object)
        emit_obj (logbuffer, object);
 
        if (do_bt)
-               emit_bt (prof, logbuffer, &data);
+               emit_bt (logbuffer, &data);
 
        EXIT_LOG;
 }
 
 static void
-clause_exc (MonoProfiler *prof, MonoMethod *method, int clause_type, int clause_num, MonoObject *exc)
+clause_exc (MonoProfiler *prof, MonoMethod *method, uint32_t clause_num, MonoExceptionEnum clause_type, MonoObject *exc)
 {
        ENTER_LOG (&exception_clauses_ctr, logbuffer,
                EVENT_SIZE /* event */ +
@@ -2149,16 +2171,32 @@ monitor_event (MonoProfiler *profiler, MonoObject *object, MonoProfilerMonitorEv
        emit_obj (logbuffer, object);
 
        if (do_bt)
-               emit_bt (profiler, logbuffer, &data);
+               emit_bt (logbuffer, &data);
 
        EXIT_LOG;
 }
 
 static void
-thread_start (MonoProfiler *prof, uintptr_t tid)
+monitor_contention (MonoProfiler *prof, MonoObject *object)
 {
-       init_thread (prof, TRUE);
+       monitor_event (prof, object, MONO_PROFILER_MONITOR_CONTENTION);
+}
 
+static void
+monitor_acquired (MonoProfiler *prof, MonoObject *object)
+{
+       monitor_event (prof, object, MONO_PROFILER_MONITOR_DONE);
+}
+
+static void
+monitor_failed (MonoProfiler *prof, MonoObject *object)
+{
+       monitor_event (prof, object, MONO_PROFILER_MONITOR_FAIL);
+}
+
+static void
+thread_start (MonoProfiler *prof, uintptr_t tid)
+{
        if (ENABLED (PROFLOG_THREAD_EVENTS)) {
                ENTER_LOG (&thread_starts_ctr, logbuffer,
                        EVENT_SIZE /* event */ +
@@ -2191,7 +2229,7 @@ thread_end (MonoProfiler *prof, uintptr_t tid)
                EXIT_LOG_EXPLICIT (NO_SEND);
        }
 
-       MonoProfilerThread *thread = PROF_TLS_GET ();
+       MonoProfilerThread *thread = get_thread ();
 
        thread->ended = TRUE;
        remove_thread (thread);
@@ -2223,11 +2261,8 @@ thread_name (MonoProfiler *prof, uintptr_t tid, const char *name)
 }
 
 static void
-domain_loaded (MonoProfiler *prof, MonoDomain *domain, int result)
+domain_loaded (MonoProfiler *prof, MonoDomain *domain)
 {
-       if (result != MONO_PROFILE_OK)
-               return;
-
        ENTER_LOG (&domain_loads_ctr, logbuffer,
                EVENT_SIZE /* event */ +
                BYTE_SIZE /* type */ +
@@ -2323,10 +2358,9 @@ typedef struct {
 
 typedef struct {
        MonoLockFreeQueueNode node;
-       MonoProfiler *prof;
        uint64_t time;
        uintptr_t tid;
-       void *ip;
+       const void *ip;
        int count;
        AsyncFrameInfo frames [MONO_ZERO_LEN_ARRAY];
 } SampleHit;
@@ -2359,12 +2393,12 @@ enqueue_sample_hit (gpointer p)
        SampleHit *sample = p;
 
        mono_lock_free_queue_node_unpoison (&sample->node);
-       mono_lock_free_queue_enqueue (&sample->prof->dumper_queue, &sample->node);
-       mono_os_sem_post (&sample->prof->dumper_queue_sem);
+       mono_lock_free_queue_enqueue (&log_profiler.dumper_queue, &sample->node);
+       mono_os_sem_post (&log_profiler.dumper_queue_sem);
 }
 
 static void
-mono_sample_hit (MonoProfiler *profiler, unsigned char *ip, void *context)
+mono_sample_hit (MonoProfiler *profiler, const mono_byte *ip, const void *context)
 {
        /*
         * Please note: We rely on the runtime loading the profiler with
@@ -2388,14 +2422,13 @@ mono_sample_hit (MonoProfiler *profiler, unsigned char *ip, void *context)
                        return;
 
                sample = mono_lock_free_alloc (&profiler->sample_allocator);
-               sample->prof = profiler;
                mono_lock_free_queue_node_init (&sample->node, TRUE);
 
                InterlockedIncrement (&sample_allocations_ctr);
        }
 
        sample->count = 0;
-       mono_stack_walk_async_safe (&async_walk_stack, context, sample);
+       mono_stack_walk_async_safe (&async_walk_stack, (void *) context, sample);
 
        sample->time = current_time ();
        sample->tid = thread_id ();
@@ -2430,8 +2463,7 @@ add_code_page (uintptr_t *hash, uintptr_t hsize, uintptr_t page)
                if (++i == hsize)
                        i = 0;
        } while (i != start_pos);
-       /* should not happen */
-       printf ("failed code page store\n");
+       g_assert_not_reached ();
        return 0;
 }
 
@@ -2461,7 +2493,7 @@ add_code_pointer (uintptr_t ip)
 //#if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
 #if 0
 static void
-dump_ubin (MonoProfiler *prof, const char *filename, uintptr_t load_addr, uint64_t offset, uintptr_t size)
+dump_ubin (const char *filename, uintptr_t load_addr, uint64_t offset, uintptr_t size)
 {
        int len = strlen (filename) + 1;
 
@@ -2485,7 +2517,7 @@ dump_ubin (MonoProfiler *prof, const char *filename, uintptr_t load_addr, uint64
 #endif
 
 static void
-dump_usym (MonoProfiler *prof, const char *name, uintptr_t value, uintptr_t size)
+dump_usym (const char *name, uintptr_t value, uintptr_t size)
 {
        int len = strlen (name) + 1;
 
@@ -2521,7 +2553,7 @@ dump_usym (MonoProfiler *prof, const char *name, uintptr_t value, uintptr_t size
 #endif
 
 static void
-dump_elf_symbols (MonoProfiler *prof, ElfW(Sym) *symbols, int num_symbols, const char *strtab, void *load_addr)
+dump_elf_symbols (ElfW(Sym) *symbols, int num_symbols, const char *strtab, void *load_addr)
 {
        int i;
        for (i = 0; i < num_symbols; ++i) {
@@ -2529,7 +2561,6 @@ dump_elf_symbols (MonoProfiler *prof, ElfW(Sym) *symbols, int num_symbols, const
                sym =  strtab + symbols [i].st_name;
                if (!symbols [i].st_name || !symbols [i].st_size || (symbols [i].st_info & 0xf) != STT_FUNC)
                        continue;
-               //printf ("symbol %s at %d\n", sym, symbols [i].st_value);
                dump_usym (sym, (uintptr_t)load_addr + symbols [i].st_value, symbols [i].st_size);
        }
 }
@@ -2574,11 +2605,9 @@ read_elf_symbols (MonoProfiler *prof, const char *filename, void *load_addr)
        shstrtabh = (void*)((char*)sheader + (header->e_shentsize * header->e_shstrndx));
        strtab = (const char*)data + shstrtabh->sh_offset;
        for (i = 0; i < header->e_shnum; ++i) {
-               //printf ("section header: %d\n", sheader->sh_type);
                if (sheader->sh_type == SHT_SYMTAB) {
                        symtabh = sheader;
                        strtabh = (void*)((char*)data + header->e_shoff + sheader->sh_link * header->e_shentsize);
-                       /*printf ("symtab section header: %d, .strstr: %d\n", i, sheader->sh_link);*/
                        break;
                }
                sheader = (void*)((char*)sheader + header->e_shentsize);
@@ -2602,7 +2631,6 @@ read_elf_symbols (MonoProfiler *prof, const char *filename, void *load_addr)
 static int
 elf_dl_callback (struct dl_phdr_info *info, size_t size, void *data)
 {
-       MonoProfiler *prof = data;
        char buf [256];
        const char *filename;
        BinaryObject *obj;
@@ -2613,7 +2641,7 @@ elf_dl_callback (struct dl_phdr_info *info, size_t size, void *data)
        ElfW(Word) *hash_table = NULL;
        ElfW(Ehdr) *header = NULL;
        const char* strtab = NULL;
-       for (obj = prof->binary_objects; obj; obj = obj->next) {
+       for (obj = log_profiler.binary_objects; obj; obj = obj->next) {
                if (obj->addr == a)
                        return 0;
        }
@@ -2630,12 +2658,10 @@ elf_dl_callback (struct dl_phdr_info *info, size_t size, void *data)
        obj = g_calloc (sizeof (BinaryObject), 1);
        obj->addr = (void*)info->dlpi_addr;
        obj->name = pstrdup (filename);
-       obj->next = prof->binary_objects;
-       prof->binary_objects = obj;
-       //printf ("loaded file: %s at %p, segments: %d\n", filename, (void*)info->dlpi_addr, info->dlpi_phnum);
+       obj->next = log_profiler.binary_objects;
+       log_profiler.binary_objects = obj;
        a = NULL;
        for (i = 0; i < info->dlpi_phnum; ++i) {
-               //printf ("segment type %d file offset: %d, size: %d\n", info->dlpi_phdr[i].p_type, info->dlpi_phdr[i].p_offset, info->dlpi_phdr[i].p_memsz);
                if (info->dlpi_phdr[i].p_type == PT_LOAD && !header) {
                        header = (ElfW(Ehdr)*)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
                        if (header->e_ident [EI_MAG0] != ELFMAG0 ||
@@ -2644,12 +2670,12 @@ elf_dl_callback (struct dl_phdr_info *info, size_t size, void *data)
                                        header->e_ident [EI_MAG3] != ELFMAG3 ) {
                                header = NULL;
                        }
-                       dump_ubin (prof, filename, info->dlpi_addr + info->dlpi_phdr[i].p_vaddr, info->dlpi_phdr[i].p_offset, info->dlpi_phdr[i].p_memsz);
+                       dump_ubin (filename, info->dlpi_addr + info->dlpi_phdr[i].p_vaddr, info->dlpi_phdr[i].p_offset, info->dlpi_phdr[i].p_memsz);
                } else if (info->dlpi_phdr[i].p_type == PT_DYNAMIC) {
                        dyn = (ElfW(Dyn) *)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
                }
        }
-       if (read_elf_symbols (prof, filename, (void*)info->dlpi_addr))
+       if (read_elf_symbols (filename, (void*)info->dlpi_addr))
                return 0;
        if (!info->dlpi_name || !info->dlpi_name[0])
                return 0;
@@ -2657,8 +2683,6 @@ elf_dl_callback (struct dl_phdr_info *info, size_t size, void *data)
                return 0;
        for (i = 0; dyn [i].d_tag != DT_NULL; ++i) {
                if (dyn [i].d_tag == DT_SYMTAB) {
-                       if (symtab && do_debug)
-                               printf ("multiple symtabs: %d\n", i);
                        symtab = (ElfW(Sym) *)(a + dyn [i].d_un.d_ptr);
                } else if (dyn [i].d_tag == DT_HASH) {
                        hash_table = (ElfW(Word) *)(a + dyn [i].d_un.d_ptr);
@@ -2669,19 +2693,19 @@ elf_dl_callback (struct dl_phdr_info *info, size_t size, void *data)
        if (!hash_table)
                return 0;
        num_sym = hash_table [1];
-       dump_elf_symbols (prof, symtab, num_sym, strtab, (void*)info->dlpi_addr);
+       dump_elf_symbols (symtab, num_sym, strtab, (void*)info->dlpi_addr);
        return 0;
 }
 
 static int
-load_binaries (MonoProfiler *prof)
+load_binaries (void)
 {
-       dl_iterate_phdr (elf_dl_callback, prof);
+       dl_iterate_phdr (elf_dl_callback, NULL);
        return 1;
 }
 #else
 static int
-load_binaries (MonoProfiler *prof)
+load_binaries (void)
 {
        return 0;
 }
@@ -2711,13 +2735,13 @@ symbol_for (uintptr_t code)
 }
 
 static void
-dump_unmanaged_coderefs (MonoProfiler *prof)
+dump_unmanaged_coderefs (void)
 {
        int i;
        const char* last_symbol;
        uintptr_t addr, page_end;
 
-       if (load_binaries (prof))
+       if (load_binaries ())
                return;
        for (i = 0; i < size_code_pages; ++i) {
                const char* sym;
@@ -2735,8 +2759,7 @@ dump_unmanaged_coderefs (MonoProfiler *prof)
                        last_symbol = sym;
                        if (!sym)
                                continue;
-                       dump_usym (prof, sym, addr, 0); /* let's not guess the size */
-                       //printf ("found symbol at %p: %s\n", (void*)addr, sym);
+                       dump_usym (sym, addr, 0); /* let's not guess the size */
                }
        }
 }
@@ -2805,7 +2828,7 @@ counters_init_foreach_callback (MonoCounter *counter, gpointer data)
 }
 
 static void
-counters_init (MonoProfiler *profiler)
+counters_init (void)
 {
        mono_os_mutex_init (&counters_mutex);
 
@@ -2814,7 +2837,7 @@ counters_init (MonoProfiler *profiler)
 }
 
 static void
-counters_emit (MonoProfiler *profiler)
+counters_emit (void)
 {
        MonoCounterAgent *agent;
        int len = 0;
@@ -2873,7 +2896,7 @@ done:
 }
 
 static void
-counters_sample (MonoProfiler *profiler, uint64_t timestamp)
+counters_sample (uint64_t timestamp)
 {
        MonoCounterAgent *agent;
        MonoCounter *counter;
@@ -2882,7 +2905,7 @@ counters_sample (MonoProfiler *profiler, uint64_t timestamp)
        void *buffer;
        int size;
 
-       counters_emit (profiler);
+       counters_emit ();
 
        buffer_size = 8;
        buffer = g_calloc (1, buffer_size);
@@ -3010,7 +3033,7 @@ struct _PerfCounterAgent {
 static PerfCounterAgent *perfcounters = NULL;
 
 static void
-perfcounters_emit (MonoProfiler *profiler)
+perfcounters_emit (void)
 {
        PerfCounterAgent *pcagent;
        int len = 0;
@@ -3096,7 +3119,7 @@ perfcounters_foreach (char *category_name, char *name, unsigned char type, gint6
 }
 
 static void
-perfcounters_sample (MonoProfiler *profiler, uint64_t timestamp)
+perfcounters_sample (uint64_t timestamp)
 {
        PerfCounterAgent *pcagent;
        int len = 0;
@@ -3110,7 +3133,7 @@ perfcounters_sample (MonoProfiler *profiler, uint64_t timestamp)
 
        mono_perfcounter_foreach (perfcounters_foreach, perfcounters);
 
-       perfcounters_emit (profiler);
+       perfcounters_emit ();
 
        size =
                EVENT_SIZE /* event */
@@ -3159,22 +3182,20 @@ done:
 }
 
 static void
-counters_and_perfcounters_sample (MonoProfiler *prof)
+counters_and_perfcounters_sample (void)
 {
        uint64_t now = current_time ();
 
-       counters_sample (prof, now);
-       perfcounters_sample (prof, now);
+       counters_sample (now);
+       perfcounters_sample (now);
 }
 
-#define COVERAGE_DEBUG(x) if (debug_coverage) {x}
 static mono_mutex_t coverage_mutex;
 static MonoConcurrentHashTable *coverage_methods = NULL;
 static MonoConcurrentHashTable *coverage_assemblies = NULL;
 static MonoConcurrentHashTable *coverage_classes = NULL;
 
 static MonoConcurrentHashTable *filtered_classes = NULL;
-static MonoConcurrentHashTable *entered_methods = NULL;
 static MonoConcurrentHashTable *image_to_methods = NULL;
 static MonoConcurrentHashTable *suppressed_assemblies = NULL;
 static gboolean coverage_initialized = FALSE;
@@ -3204,18 +3225,18 @@ free_coverage_entry (gpointer data, gpointer userdata)
 }
 
 static void
-obtain_coverage_for_method (MonoProfiler *prof, const MonoProfileCoverageEntry *entry)
+obtain_coverage_for_method (MonoProfiler *prof, const MonoProfilerCoverageData *entry)
 {
-       int offset = entry->iloffset - previous_offset;
+       int offset = entry->il_offset - previous_offset;
        CoverageEntry *e = g_new (CoverageEntry, 1);
 
-       previous_offset = entry->iloffset;
+       previous_offset = entry->il_offset;
 
        e->offset = offset;
        e->counter = entry->counter;
-       e->filename = g_strdup(entry->filename ? entry->filename : "");
+       e->filename = g_strdup(entry->file_name ? entry->file_name : "");
        e->line = entry->line;
-       e->column = entry->col;
+       e->column = entry->column;
 
        g_ptr_array_add (coverage_data, e);
 }
@@ -3272,7 +3293,6 @@ static void
 build_method_buffer (gpointer key, gpointer value, gpointer userdata)
 {
        MonoMethod *method = (MonoMethod *)value;
-       MonoProfiler *prof = (MonoProfiler *)userdata;
        MonoClass *klass;
        MonoImage *image;
        char *class_name;
@@ -3282,7 +3302,7 @@ build_method_buffer (gpointer key, gpointer value, gpointer userdata)
        previous_offset = 0;
        coverage_data = g_ptr_array_new ();
 
-       mono_profiler_coverage_get (prof, method, obtain_coverage_for_method);
+       mono_profiler_get_coverage_data (log_profiler.handle, method, obtain_coverage_for_method);
 
        klass = mono_method_get_class (method);
        image = mono_class_get_image (klass);
@@ -3471,40 +3491,17 @@ build_assembly_buffer (gpointer key, gpointer value, gpointer userdata)
 }
 
 static void
-dump_coverage (MonoProfiler *prof)
+dump_coverage (void)
 {
        if (!coverage_initialized)
                return;
 
-       COVERAGE_DEBUG(fprintf (stderr, "Coverage: Started dump\n");)
        method_id = 0;
 
        mono_os_mutex_lock (&coverage_mutex);
        mono_conc_hashtable_foreach (coverage_assemblies, build_assembly_buffer, NULL);
        mono_conc_hashtable_foreach (coverage_classes, build_class_buffer, NULL);
-       mono_conc_hashtable_foreach (coverage_methods, build_method_buffer, prof);
-       mono_os_mutex_unlock (&coverage_mutex);
-
-       COVERAGE_DEBUG(fprintf (stderr, "Coverage: Finished dump\n");)
-}
-
-static void
-process_method_enter_coverage (MonoProfiler *prof, MonoMethod *method)
-{
-       MonoClass *klass;
-       MonoImage *image;
-
-       if (!coverage_initialized)
-               return;
-
-       klass = mono_method_get_class (method);
-       image = mono_class_get_image (klass);
-
-       if (mono_conc_hashtable_lookup (suppressed_assemblies, (gpointer) mono_image_get_name (image)))
-               return;
-
-       mono_os_mutex_lock (&coverage_mutex);
-       mono_conc_hashtable_insert (entered_methods, method, method);
+       mono_conc_hashtable_foreach (coverage_methods, build_method_buffer, NULL);
        mono_os_mutex_unlock (&coverage_mutex);
 }
 
@@ -3534,20 +3531,14 @@ coverage_filter (MonoProfiler *prof, MonoMethod *method)
 
        g_assert (coverage_initialized && "Why are we being asked for coverage filter info when we're not doing coverage?");
 
-       COVERAGE_DEBUG(fprintf (stderr, "Coverage filter for %s\n", mono_method_get_name (method));)
-
        flags = mono_method_get_flags (method, &iflags);
        if ((iflags & 0x1000 /*METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL*/) ||
-           (flags & 0x2000 /*METHOD_ATTRIBUTE_PINVOKE_IMPL*/)) {
-               COVERAGE_DEBUG(fprintf (stderr, "   Internal call or pinvoke - ignoring\n");)
+           (flags & 0x2000 /*METHOD_ATTRIBUTE_PINVOKE_IMPL*/))
                return FALSE;
-       }
 
        // Don't need to do anything else if we're already tracking this method
-       if (mono_conc_hashtable_lookup (coverage_methods, method)) {
-               COVERAGE_DEBUG(fprintf (stderr, "   Already tracking\n");)
+       if (mono_conc_hashtable_lookup (coverage_methods, method))
                return TRUE;
-       }
 
        klass = mono_method_get_class (method);
        image = mono_class_get_image (klass);
@@ -3558,16 +3549,13 @@ coverage_filter (MonoProfiler *prof, MonoMethod *method)
 
        if (prof->coverage_filters) {
                /* Check already filtered classes first */
-               if (mono_conc_hashtable_lookup (filtered_classes, klass)) {
-                       COVERAGE_DEBUG(fprintf (stderr, "   Already filtered\n");)
+               if (mono_conc_hashtable_lookup (filtered_classes, klass))
                        return FALSE;
-               }
 
                classname = mono_type_get_name (mono_class_get_type (klass));
 
                fqn = g_strdup_printf ("[%s]%s", mono_image_get_name (image), classname);
 
-               COVERAGE_DEBUG(fprintf (stderr, "   Looking for %s in filter\n", fqn);)
                // Check positive filters first
                has_positive = FALSE;
                found = FALSE;
@@ -3577,21 +3565,14 @@ coverage_filter (MonoProfiler *prof, MonoMethod *method)
                        if (filter [0] == '+') {
                                filter = &filter [1];
 
-                               COVERAGE_DEBUG(fprintf (stderr, "   Checking against +%s ...", filter);)
-
-                               if (strstr (fqn, filter) != NULL) {
-                                       COVERAGE_DEBUG(fprintf (stderr, "matched\n");)
+                               if (strstr (fqn, filter) != NULL)
                                        found = TRUE;
-                               } else
-                                       COVERAGE_DEBUG(fprintf (stderr, "no match\n");)
 
                                has_positive = TRUE;
                        }
                }
 
                if (has_positive && !found) {
-                       COVERAGE_DEBUG(fprintf (stderr, "   Positive match was not found\n");)
-
                        mono_os_mutex_lock (&coverage_mutex);
                        mono_conc_hashtable_insert (filtered_classes, klass, klass);
                        mono_os_mutex_unlock (&coverage_mutex);
@@ -3609,11 +3590,8 @@ coverage_filter (MonoProfiler *prof, MonoMethod *method)
 
                        // Skip '-'
                        filter = &filter [1];
-                       COVERAGE_DEBUG(fprintf (stderr, "   Checking against -%s ...", filter);)
 
                        if (strstr (fqn, filter) != NULL) {
-                               COVERAGE_DEBUG(fprintf (stderr, "matched\n");)
-
                                mono_os_mutex_lock (&coverage_mutex);
                                mono_conc_hashtable_insert (filtered_classes, klass, klass);
                                mono_os_mutex_unlock (&coverage_mutex);
@@ -3621,16 +3599,13 @@ coverage_filter (MonoProfiler *prof, MonoMethod *method)
                                g_free (classname);
 
                                return FALSE;
-                       } else
-                               COVERAGE_DEBUG(fprintf (stderr, "no match\n");)
-
+                       }
                }
 
                g_free (fqn);
                g_free (classname);
        }
 
-       COVERAGE_DEBUG(fprintf (stderr, "   Handling coverage for %s\n", mono_method_get_name (method));)
        header = mono_method_get_header_checked (method, &error);
        mono_error_cleanup (&error);
 
@@ -3748,9 +3723,8 @@ init_suppressed_assemblies (void)
 
        /* Don't need to free @content as it is referred to by the lines stored in @suppressed_assemblies */
        content = get_file_content (sa_file);
-       if (content == NULL) {
-               g_error ("mono-profiler-log.suppression is greater than 128kb - aborting\n");
-       }
+       if (content == NULL)
+               g_error ("mono-profiler-log.suppression is greater than 128kb - aborting.");
 
        while ((line = get_next_line (content, &content))) {
                line = g_strchomp (g_strchug (line));
@@ -3764,19 +3738,20 @@ init_suppressed_assemblies (void)
 static void
 parse_cov_filter_file (GPtrArray *filters, const char *file)
 {
-       FILE *filter_file;
-       char *line, *content;
+       FILE *filter_file = fopen (file, "r");
 
-       filter_file = fopen (file, "r");
        if (filter_file == NULL) {
-               fprintf (stderr, "Unable to open %s\n", file);
+               mono_profiler_printf_err ("Could not open coverage filter file '%s'.", file);
                return;
        }
 
        /* Don't need to free content as it is referred to by the lines stored in @filters */
-       content = get_file_content (filter_file);
+       char *content = get_file_content (filter_file);
+
        if (content == NULL)
-               fprintf (stderr, "WARNING: %s is greater than 128kb - ignoring\n", file);
+               mono_profiler_printf_err ("Coverage filter file '%s' is larger than 128kb - ignoring.", file);
+
+       char *line;
 
        while ((line = get_next_line (content, &content)))
                g_ptr_array_add (filters, g_strchug (g_strchomp (line)));
@@ -3785,18 +3760,15 @@ parse_cov_filter_file (GPtrArray *filters, const char *file)
 }
 
 static void
-coverage_init (MonoProfiler *prof)
+coverage_init (void)
 {
        g_assert (!coverage_initialized && "Why are we initializing coverage twice?");
 
-       COVERAGE_DEBUG(fprintf (stderr, "Coverage initialized\n");)
-
        mono_os_mutex_init (&coverage_mutex);
        coverage_methods = mono_conc_hashtable_new (NULL, NULL);
        coverage_assemblies = mono_conc_hashtable_new (NULL, NULL);
        coverage_classes = mono_conc_hashtable_new (NULL, NULL);
        filtered_classes = mono_conc_hashtable_new (NULL, NULL);
-       entered_methods = mono_conc_hashtable_new (NULL, NULL);
        image_to_methods = mono_conc_hashtable_new (NULL, NULL);
        init_suppressed_assemblies ();
 
@@ -3817,11 +3789,11 @@ free_sample_hit (gpointer p)
 }
 
 static void
-cleanup_reusable_samples (MonoProfiler *prof)
+cleanup_reusable_samples (void)
 {
        SampleHit *sample;
 
-       while ((sample = (SampleHit *) mono_lock_free_queue_dequeue (&prof->sample_reuse_queue)))
+       while ((sample = (SampleHit *) mono_lock_free_queue_dequeue (&log_profiler.sample_reuse_queue)))
                mono_thread_hazardous_try_free (sample, free_sample_hit);
 }
 
@@ -3831,14 +3803,14 @@ log_shutdown (MonoProfiler *prof)
        InterlockedWrite (&in_shutdown, 1);
 
        if (!no_counters)
-               counters_and_perfcounters_sample (prof);
+               counters_and_perfcounters_sample ();
 
-       dump_coverage (prof);
+       dump_coverage ();
 
        char c = 1;
 
        if (write (prof->pipes [1], &c, 1) != 1) {
-               fprintf (stderr, "Could not write to pipe: %s\n", strerror (errno));
+               mono_profiler_printf_err ("Could not write to log profiler pipe: %s", strerror (errno));
                exit (1);
        }
 
@@ -3895,7 +3867,7 @@ log_shutdown (MonoProfiler *prof)
         */
        mono_thread_hazardous_try_free_all ();
 
-       cleanup_reusable_samples (prof);
+       cleanup_reusable_samples ();
 
        /*
         * Finally, make sure that all sample hits are freed. This should cover all
@@ -3905,8 +3877,10 @@ log_shutdown (MonoProfiler *prof)
         */
        mono_thread_hazardous_try_free_all ();
 
-       g_assert (!InterlockedRead (&buffer_rwlock_count) && "Why is the reader count still non-zero?");
-       g_assert (!InterlockedReadPointer (&buffer_rwlock_exclusive) && "Why does someone still hold the exclusive lock?");
+       gint32 state = InterlockedRead (&buffer_lock_state);
+
+       g_assert (!(state & 0xFFFF) && "Why is the reader count still non-zero?");
+       g_assert (!(state >> 16) && "Why is the exclusive lock still held?");
 
 #if defined (HAVE_SYS_ZLIB)
        if (prof->gzfile)
@@ -3930,7 +3904,6 @@ log_shutdown (MonoProfiler *prof)
                mono_conc_hashtable_destroy (coverage_classes);
                mono_conc_hashtable_destroy (filtered_classes);
 
-               mono_conc_hashtable_destroy (entered_methods);
                mono_conc_hashtable_destroy (image_to_methods);
                mono_conc_hashtable_destroy (suppressed_assemblies);
                mono_os_mutex_destroy (&coverage_mutex);
@@ -3939,7 +3912,6 @@ log_shutdown (MonoProfiler *prof)
        PROF_TLS_FREE ();
 
        g_free (prof->args);
-       g_free (prof);
 }
 
 static char*
@@ -4011,7 +3983,7 @@ add_to_fd_set (fd_set *set, int fd, int *max_fd)
         * error and exiting.
         */
        if (fd >= FD_SETSIZE) {
-               fprintf (stderr, "File descriptor is out of bounds for fd_set: %d\n", fd);
+               mono_profiler_printf_err ("File descriptor is out of bounds for fd_set: %d", fd);
                exit (1);
        }
 
@@ -4024,12 +3996,10 @@ add_to_fd_set (fd_set *set, int fd, int *max_fd)
 static void *
 helper_thread (void *arg)
 {
-       MonoProfiler *prof = (MonoProfiler *) arg;
-
        mono_threads_attach_tools_thread ();
        mono_native_thread_set_name (mono_native_thread_id_get (), "Profiler helper");
 
-       MonoProfilerThread *thread = init_thread (prof, FALSE);
+       MonoProfilerThread *thread = init_thread (FALSE);
 
        GArray *command_sockets = g_array_new (FALSE, FALSE, sizeof (int));
 
@@ -4039,8 +4009,8 @@ helper_thread (void *arg)
 
                FD_ZERO (&rfds);
 
-               add_to_fd_set (&rfds, prof->server_socket, &max_fd);
-               add_to_fd_set (&rfds, prof->pipes [0], &max_fd);
+               add_to_fd_set (&rfds, log_profiler.server_socket, &max_fd);
+               add_to_fd_set (&rfds, log_profiler.pipes [0], &max_fd);
 
                for (gint i = 0; i < command_sockets->len; i++)
                        add_to_fd_set (&rfds, g_array_index (command_sockets, int, i), &max_fd);
@@ -4052,12 +4022,12 @@ helper_thread (void *arg)
                        if (errno == EINTR)
                                continue;
 
-                       fprintf (stderr, "Error in mono-profiler-log server: %s", strerror (errno));
+                       mono_profiler_printf_err ("Could not poll in log profiler helper thread: %s", strerror (errno));
                        exit (1);
                }
 
                if (!no_counters)
-                       counters_and_perfcounters_sample (prof);
+                       counters_and_perfcounters_sample ();
 
                buffer_lock_excl ();
 
@@ -4066,9 +4036,9 @@ helper_thread (void *arg)
                buffer_unlock_excl ();
 
                // Are we shutting down?
-               if (FD_ISSET (prof->pipes [0], &rfds)) {
+               if (FD_ISSET (log_profiler.pipes [0], &rfds)) {
                        char c;
-                       read (prof->pipes [0], &c, 1);
+                       read (log_profiler.pipes [0], &c, 1);
                        break;
                }
 
@@ -4101,8 +4071,8 @@ helper_thread (void *arg)
                        }
                }
 
-               if (FD_ISSET (prof->server_socket, &rfds)) {
-                       int fd = accept (prof->server_socket, NULL, NULL);
+               if (FD_ISSET (log_profiler.server_socket, &rfds)) {
+                       int fd = accept (log_profiler.server_socket, NULL, NULL);
 
                        if (fd != -1) {
                                if (fd >= FD_SETSIZE)
@@ -4127,17 +4097,17 @@ helper_thread (void *arg)
 }
 
 static void
-start_helper_thread (MonoProfiler* prof)
+start_helper_thread (void)
 {
-       if (pipe (prof->pipes) == -1) {
-               fprintf (stderr, "Cannot create pipe: %s\n", strerror (errno));
+       if (pipe (log_profiler.pipes) == -1) {
+               mono_profiler_printf_err ("Could not create log profiler pipe: %s", strerror (errno));
                exit (1);
        }
 
-       prof->server_socket = socket (PF_INET, SOCK_STREAM, 0);
+       log_profiler.server_socket = socket (PF_INET, SOCK_STREAM, 0);
 
-       if (prof->server_socket == -1) {
-               fprintf (stderr, "Cannot create server socket: %s\n", strerror (errno));
+       if (log_profiler.server_socket == -1) {
+               mono_profiler_printf_err ("Could not create log profiler server socket: %s", strerror (errno));
                exit (1);
        }
 
@@ -4146,33 +4116,33 @@ start_helper_thread (MonoProfiler* prof)
        memset (&server_address, 0, sizeof (server_address));
        server_address.sin_family = AF_INET;
        server_address.sin_addr.s_addr = INADDR_ANY;
-       server_address.sin_port = htons (prof->command_port);
+       server_address.sin_port = htons (log_profiler.command_port);
 
-       if (bind (prof->server_socket, (struct sockaddr *) &server_address, sizeof (server_address)) == -1) {
-               fprintf (stderr, "Cannot bind server socket on port %d: %s\n", prof->command_port, strerror (errno));
-               close (prof->server_socket);
+       if (bind (log_profiler.server_socket, (struct sockaddr *) &server_address, sizeof (server_address)) == -1) {
+               mono_profiler_printf_err ("Could not bind log profiler server socket on port %d: %s", log_profiler.command_port, strerror (errno));
+               close (log_profiler.server_socket);
                exit (1);
        }
 
-       if (listen (prof->server_socket, 1) == -1) {
-               fprintf (stderr, "Cannot listen on server socket: %s\n", strerror (errno));
-               close (prof->server_socket);
+       if (listen (log_profiler.server_socket, 1) == -1) {
+               mono_profiler_printf_err ("Could not listen on log profiler server socket: %s", strerror (errno));
+               close (log_profiler.server_socket);
                exit (1);
        }
 
        socklen_t slen = sizeof (server_address);
 
-       if (getsockname (prof->server_socket, (struct sockaddr *) &server_address, &slen)) {
-               fprintf (stderr, "Could not get assigned port: %s\n", strerror (errno));
-               close (prof->server_socket);
+       if (getsockname (log_profiler.server_socket, (struct sockaddr *) &server_address, &slen)) {
+               mono_profiler_printf_err ("Could not retrieve assigned port for log profiler server socket: %s", strerror (errno));
+               close (log_profiler.server_socket);
                exit (1);
        }
 
-       prof->command_port = ntohs (server_address.sin_port);
+       log_profiler.command_port = ntohs (server_address.sin_port);
 
-       if (!mono_native_thread_create (&prof->helper_thread, helper_thread, prof)) {
-               fprintf (stderr, "Could not start helper thread\n");
-               close (prof->server_socket);
+       if (!mono_native_thread_create (&log_profiler.helper_thread, helper_thread, NULL)) {
+               mono_profiler_printf_err ("Could not start log profiler helper thread");
+               close (log_profiler.server_socket);
                exit (1);
        }
 }
@@ -4184,11 +4154,11 @@ free_writer_entry (gpointer p)
 }
 
 static gboolean
-handle_writer_queue_entry (MonoProfiler *prof)
+handle_writer_queue_entry (void)
 {
        WriterQueueEntry *entry;
 
-       if ((entry = (WriterQueueEntry *) mono_lock_free_queue_dequeue (&prof->writer_queue))) {
+       if ((entry = (WriterQueueEntry *) mono_lock_free_queue_dequeue (&log_profiler.writer_queue))) {
                if (!entry->methods)
                        goto no_methods;
 
@@ -4208,7 +4178,7 @@ handle_writer_queue_entry (MonoProfiler *prof)
                for (guint i = 0; i < entry->methods->len; i++) {
                        MethodInfo *info = (MethodInfo *) g_ptr_array_index (entry->methods, i);
 
-                       if (mono_conc_hashtable_lookup (prof->method_table, info->method))
+                       if (mono_conc_hashtable_lookup (log_profiler.method_table, info->method))
                                goto free_info; // This method already has metadata emitted.
 
                        /*
@@ -4221,9 +4191,9 @@ handle_writer_queue_entry (MonoProfiler *prof)
                         * method lists will just be empty for the rest of the
                         * app's lifetime.
                         */
-                       mono_os_mutex_lock (&prof->method_table_mutex);
-                       mono_conc_hashtable_insert (prof->method_table, info->method, info->method);
-                       mono_os_mutex_unlock (&prof->method_table_mutex);
+                       mono_os_mutex_lock (&log_profiler.method_table_mutex);
+                       mono_conc_hashtable_insert (log_profiler.method_table, info->method, info->method);
+                       mono_os_mutex_unlock (&log_profiler.method_table_mutex);
 
                        char *name = mono_method_full_name (info->method, 1);
                        int nlen = strlen (name) + 1;
@@ -4259,12 +4229,14 @@ handle_writer_queue_entry (MonoProfiler *prof)
                g_ptr_array_free (entry->methods, TRUE);
 
                if (wrote_methods) {
-                       dump_buffer_threadless (prof, PROF_TLS_GET ()->buffer);
-                       init_buffer_state (PROF_TLS_GET ());
+                       MonoProfilerThread *thread = PROF_TLS_GET ();
+
+                       dump_buffer_threadless (thread->buffer);
+                       init_buffer_state (thread);
                }
 
        no_methods:
-               dump_buffer (prof, entry->buffer);
+               dump_buffer (entry->buffer);
 
                mono_thread_hazardous_try_free (entry, free_writer_entry);
 
@@ -4277,22 +4249,20 @@ handle_writer_queue_entry (MonoProfiler *prof)
 static void *
 writer_thread (void *arg)
 {
-       MonoProfiler *prof = (MonoProfiler *)arg;
-
        mono_threads_attach_tools_thread ();
        mono_native_thread_set_name (mono_native_thread_id_get (), "Profiler writer");
 
-       dump_header (prof);
+       dump_header ();
 
-       MonoProfilerThread *thread = init_thread (prof, FALSE);
+       MonoProfilerThread *thread = init_thread (FALSE);
 
-       while (InterlockedRead (&prof->run_writer_thread)) {
-               mono_os_sem_wait (&prof->writer_queue_sem, MONO_SEM_FLAGS_NONE);
-               handle_writer_queue_entry (prof);
+       while (InterlockedRead (&log_profiler.run_writer_thread)) {
+               mono_os_sem_wait (&log_profiler.writer_queue_sem, MONO_SEM_FLAGS_NONE);
+               handle_writer_queue_entry ();
        }
 
        /* Drain any remaining entries on shutdown. */
-       while (handle_writer_queue_entry (prof));
+       while (handle_writer_queue_entry ());
 
        free_buffer (thread->buffer, thread->buffer->size);
        deinit_thread (thread);
@@ -4303,12 +4273,12 @@ writer_thread (void *arg)
 }
 
 static void
-start_writer_thread (MonoProfiler* prof)
+start_writer_thread (void)
 {
-       InterlockedWrite (&prof->run_writer_thread, 1);
+       InterlockedWrite (&log_profiler.run_writer_thread, 1);
 
-       if (!mono_native_thread_create (&prof->writer_thread, writer_thread, prof)) {
-               fprintf (stderr, "Could not start writer thread\n");
+       if (!mono_native_thread_create (&log_profiler.writer_thread, writer_thread, NULL)) {
+               mono_profiler_printf_err ("Could not start log profiler writer thread");
                exit (1);
        }
 }
@@ -4319,15 +4289,15 @@ reuse_sample_hit (gpointer p)
        SampleHit *sample = p;
 
        mono_lock_free_queue_node_unpoison (&sample->node);
-       mono_lock_free_queue_enqueue (&sample->prof->sample_reuse_queue, &sample->node);
+       mono_lock_free_queue_enqueue (&log_profiler.sample_reuse_queue, &sample->node);
 }
 
 static gboolean
-handle_dumper_queue_entry (MonoProfiler *prof)
+handle_dumper_queue_entry (void)
 {
        SampleHit *sample;
 
-       if ((sample = (SampleHit *) mono_lock_free_queue_dequeue (&prof->dumper_queue))) {
+       if ((sample = (SampleHit *) mono_lock_free_queue_dequeue (&log_profiler.dumper_queue))) {
                for (int i = 0; i < sample->count; ++i) {
                        MonoMethod *method = sample->frames [i].method;
                        MonoDomain *domain = sample->frames [i].domain;
@@ -4346,7 +4316,6 @@ handle_dumper_queue_entry (MonoProfiler *prof)
 
                ENTER_LOG (&sample_hits_ctr, logbuffer,
                        EVENT_SIZE /* event */ +
-                       BYTE_SIZE /* type */ +
                        LEB128_SIZE /* tid */ +
                        LEB128_SIZE /* count */ +
                        1 * (
@@ -4359,7 +4328,6 @@ handle_dumper_queue_entry (MonoProfiler *prof)
                );
 
                emit_event_time (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_HIT, sample->time);
-               emit_byte (logbuffer, SAMPLE_CYCLES);
                emit_ptr (logbuffer, (void *) sample->tid);
                emit_value (logbuffer, 1);
 
@@ -4379,7 +4347,7 @@ handle_dumper_queue_entry (MonoProfiler *prof)
 
                mono_thread_hazardous_try_free (sample, reuse_sample_hit);
 
-               dump_unmanaged_coderefs (prof);
+               dump_unmanaged_coderefs ();
        }
 
        return FALSE;
@@ -4388,26 +4356,24 @@ handle_dumper_queue_entry (MonoProfiler *prof)
 static void *
 dumper_thread (void *arg)
 {
-       MonoProfiler *prof = (MonoProfiler *)arg;
-
        mono_threads_attach_tools_thread ();
        mono_native_thread_set_name (mono_native_thread_id_get (), "Profiler dumper");
 
-       MonoProfilerThread *thread = init_thread (prof, FALSE);
+       MonoProfilerThread *thread = init_thread (FALSE);
 
-       while (InterlockedRead (&prof->run_dumper_thread)) {
+       while (InterlockedRead (&log_profiler.run_dumper_thread)) {
                /*
                 * Flush samples every second so it doesn't seem like the profiler is
                 * not working if the program is mostly idle.
                 */
-               if (mono_os_sem_timedwait (&prof->dumper_queue_sem, 1000, MONO_SEM_FLAGS_NONE) == MONO_SEM_TIMEDWAIT_RET_TIMEDOUT)
+               if (mono_os_sem_timedwait (&log_profiler.dumper_queue_sem, 1000, MONO_SEM_FLAGS_NONE) == MONO_SEM_TIMEDWAIT_RET_TIMEDOUT)
                        send_log_unsafe (FALSE);
 
-               handle_dumper_queue_entry (prof);
+               handle_dumper_queue_entry ();
        }
 
        /* Drain any remaining entries on shutdown. */
-       while (handle_dumper_queue_entry (prof));
+       while (handle_dumper_queue_entry ());
 
        send_log_unsafe (FALSE);
        deinit_thread (thread);
@@ -4418,12 +4384,12 @@ dumper_thread (void *arg)
 }
 
 static void
-start_dumper_thread (MonoProfiler* prof)
+start_dumper_thread (void)
 {
-       InterlockedWrite (&prof->run_dumper_thread, 1);
+       InterlockedWrite (&log_profiler.run_dumper_thread, 1);
 
-       if (!mono_native_thread_create (&prof->dumper_thread, dumper_thread, prof)) {
-               fprintf (stderr, "Could not start dumper thread\n");
+       if (!mono_native_thread_create (&log_profiler.dumper_thread, dumper_thread, NULL)) {
+               mono_profiler_printf_err ("Could not start log profiler dumper thread");
                exit (1);
        }
 }
@@ -4491,39 +4457,30 @@ runtime_initialized (MonoProfiler *profiler)
        register_counter ("Event: Coverage classes", &coverage_classes_ctr);
        register_counter ("Event: Coverage assemblies", &coverage_assemblies_ctr);
 
-       counters_init (profiler);
+       counters_init ();
 
        /*
         * We must start the helper thread before the writer thread. This is
         * because the helper thread sets up the command port which is written to
         * the log header by the writer thread.
         */
-       start_helper_thread (profiler);
-       start_writer_thread (profiler);
-       start_dumper_thread (profiler);
+       start_helper_thread ();
+       start_writer_thread ();
+       start_dumper_thread ();
 }
 
-static MonoProfiler*
+static void
 create_profiler (const char *args, const char *filename, GPtrArray *filters)
 {
-       MonoProfiler *prof;
        char *nf;
-       int force_delete = 0;
-       prof = (MonoProfiler *) g_calloc (1, sizeof (MonoProfiler));
-
-       prof->args = pstrdup (args);
-       prof->command_port = command_port;
-       if (filename && *filename == '-') {
-               force_delete = 1;
-               filename++;
-               g_warning ("WARNING: the output:-FILENAME option is deprecated, the profiler now always overrides the output file\n");
-       }
+
+       log_profiler.args = pstrdup (args);
+       log_profiler.command_port = command_port;
 
        //If filename begin with +, append the pid at the end
        if (filename && *filename == '+')
                filename = g_strdup_printf ("%s.%d", filename + 1, getpid ());
 
-
        if (!filename) {
                if (do_report)
                        filename = "|mprof-report -";
@@ -4541,24 +4498,22 @@ create_profiler (const char *args, const char *filename, GPtrArray *filters)
                }
        }
        if (*nf == '|') {
-               prof->file = popen (nf + 1, "w");
-               prof->pipe_output = 1;
+               log_profiler.file = popen (nf + 1, "w");
+               log_profiler.pipe_output = 1;
        } else if (*nf == '#') {
                int fd = strtol (nf + 1, NULL, 10);
-               prof->file = fdopen (fd, "a");
-       } else {
-               if (force_delete)
-                       unlink (nf);
-               prof->file = fopen (nf, "wb");
-       }
-       if (!prof->file) {
-               fprintf (stderr, "Cannot create profiler output: %s\n", nf);
+               log_profiler.file = fdopen (fd, "a");
+       } else
+               log_profiler.file = fopen (nf, "wb");
+
+       if (!log_profiler.file) {
+               mono_profiler_printf_err ("Could not create log profiler output file '%s'.", nf);
                exit (1);
        }
 
 #if defined (HAVE_SYS_ZLIB)
        if (use_zip)
-               prof->gzfile = gzdopen (fileno (prof->file), "wb");
+               log_profiler.gzfile = gzdopen (fileno (log_profiler.file), "wb");
 #endif
 
        /*
@@ -4568,32 +4523,32 @@ create_profiler (const char *args, const char *filename, GPtrArray *filters)
        g_assert (SAMPLE_SLOT_SIZE (MAX_FRAMES) * 2 < LOCK_FREE_ALLOC_SB_USABLE_SIZE (SAMPLE_BLOCK_SIZE));
 
        // FIXME: We should free this stuff too.
-       mono_lock_free_allocator_init_size_class (&prof->sample_size_class, SAMPLE_SLOT_SIZE (num_frames), SAMPLE_BLOCK_SIZE);
-       mono_lock_free_allocator_init_allocator (&prof->sample_allocator, &prof->sample_size_class, MONO_MEM_ACCOUNT_PROFILER);
+       mono_lock_free_allocator_init_size_class (&log_profiler.sample_size_class, SAMPLE_SLOT_SIZE (num_frames), SAMPLE_BLOCK_SIZE);
+       mono_lock_free_allocator_init_allocator (&log_profiler.sample_allocator, &log_profiler.sample_size_class, MONO_MEM_ACCOUNT_PROFILER);
 
-       mono_lock_free_queue_init (&prof->sample_reuse_queue);
+       mono_lock_free_queue_init (&log_profiler.sample_reuse_queue);
 
        g_assert (sizeof (WriterQueueEntry) * 2 < LOCK_FREE_ALLOC_SB_USABLE_SIZE (WRITER_ENTRY_BLOCK_SIZE));
 
        // FIXME: We should free this stuff too.
-       mono_lock_free_allocator_init_size_class (&prof->writer_entry_size_class, sizeof (WriterQueueEntry), WRITER_ENTRY_BLOCK_SIZE);
-       mono_lock_free_allocator_init_allocator (&prof->writer_entry_allocator, &prof->writer_entry_size_class, MONO_MEM_ACCOUNT_PROFILER);
+       mono_lock_free_allocator_init_size_class (&log_profiler.writer_entry_size_class, sizeof (WriterQueueEntry), WRITER_ENTRY_BLOCK_SIZE);
+       mono_lock_free_allocator_init_allocator (&log_profiler.writer_entry_allocator, &log_profiler.writer_entry_size_class, MONO_MEM_ACCOUNT_PROFILER);
 
-       mono_lock_free_queue_init (&prof->writer_queue);
-       mono_os_sem_init (&prof->writer_queue_sem, 0);
+       mono_lock_free_queue_init (&log_profiler.writer_queue);
+       mono_os_sem_init (&log_profiler.writer_queue_sem, 0);
 
-       mono_lock_free_queue_init (&prof->dumper_queue);
-       mono_os_sem_init (&prof->dumper_queue_sem, 0);
+       mono_lock_free_queue_init (&log_profiler.dumper_queue);
+       mono_os_sem_init (&log_profiler.dumper_queue_sem, 0);
 
-       mono_os_mutex_init (&prof->method_table_mutex);
-       prof->method_table = mono_conc_hashtable_new (NULL, NULL);
+       mono_os_mutex_init (&log_profiler.method_table_mutex);
+       log_profiler.method_table = mono_conc_hashtable_new (NULL, NULL);
 
        if (do_coverage)
-               coverage_init (prof);
-       prof->coverage_filters = filters;
+               coverage_init ();
 
-       prof->startup_time = current_time ();
-       return prof;
+       log_profiler.coverage_filters = filters;
+
+       log_profiler.startup_time = current_time ();
 }
 
 /*
@@ -4601,26 +4556,25 @@ create_profiler (const char *args, const char *filename, GPtrArray *filters)
  * mono will load from the shared library and call.
  */
 extern void
-mono_profiler_startup (const char *desc);
+mono_profiler_init (const char *desc);
 
 extern void
-mono_profiler_startup_log (const char *desc);
+mono_profiler_init_log (const char *desc);
 
 /*
  * this is the entry point that will be used when the profiler
  * is embedded inside the main executable.
  */
 void
-mono_profiler_startup_log (const char *desc)
+mono_profiler_init_log (const char *desc)
 {
-       mono_profiler_startup (desc);
+       mono_profiler_init (desc);
 }
 
 void
-mono_profiler_startup (const char *desc)
+mono_profiler_init (const char *desc)
 {
        GPtrArray *filters = NULL;
-       MonoProfiler *prof;
 
        proflog_parse_args (&config, desc [3] == ':' ? desc + 4 : "");
 
@@ -4628,7 +4582,6 @@ mono_profiler_startup (const char *desc)
        nocalls = !(config.effective_mask & PROFLOG_CALL_EVENTS);
        no_counters = !(config.effective_mask & PROFLOG_COUNTER_EVENTS);
        do_report = config.do_report;
-       do_debug = config.do_debug;
        do_heap_shot = (config.effective_mask & PROFLOG_HEAPSHOT_FEATURE);
        hs_mode_ondemand = config.hs_mode_ondemand;
        hs_mode_ms = config.hs_mode_ms;
@@ -4641,8 +4594,6 @@ mono_profiler_startup (const char *desc)
        max_allocated_sample_hits = config.max_allocated_sample_hits;
        max_call_depth = config.max_call_depth;
        do_coverage = (config.effective_mask & PROFLOG_CODE_COV_FEATURE);
-       debug_coverage = config.debug_coverage;
-       only_coverage = config.only_coverage;
 
        if (config.cov_filter_files) {
                filters = g_ptr_array_new ();
@@ -4657,122 +4608,111 @@ mono_profiler_startup (const char *desc)
 
        PROF_TLS_INIT ();
 
-       prof = create_profiler (desc, config.output_filename, filters);
-       if (!prof) {
-               PROF_TLS_FREE ();
-               return;
-       }
+       create_profiler (desc, config.output_filename, filters);
 
        mono_lls_init (&profiler_thread_list, NULL);
 
-       init_thread (prof, TRUE);
-
-       //This two events are required for the profiler to work
-       int events = MONO_PROFILE_THREADS | MONO_PROFILE_GC;
+       MonoProfilerHandle handle = log_profiler.handle = mono_profiler_install (&log_profiler);
 
        //Required callbacks
-       mono_profiler_install (prof, log_shutdown);
-       mono_profiler_install_runtime_initialized (runtime_initialized);
+       mono_profiler_set_runtime_shutdown_end_callback (handle, log_shutdown);
+       mono_profiler_set_runtime_initialized_callback (handle, runtime_initialized);
 
-       mono_profiler_install_gc (gc_event, gc_resize);
-       mono_profiler_install_thread (thread_start, thread_end);
+       mono_profiler_set_gc_event_callback (handle, gc_event);
+       mono_profiler_set_gc_resize_callback (handle, gc_resize);
+       mono_profiler_set_thread_started_callback (handle, thread_start);
+       mono_profiler_set_thread_stopped_callback (handle, thread_end);
 
        //It's questionable whether we actually want this to be mandatory, maybe put it behind the actual event?
-       mono_profiler_install_thread_name (thread_name);
-
+       mono_profiler_set_thread_name_callback (handle, thread_name);
 
        if (config.effective_mask & PROFLOG_DOMAIN_EVENTS) {
-               events |= MONO_PROFILE_APPDOMAIN_EVENTS;
-               mono_profiler_install_appdomain (NULL, domain_loaded, domain_unloaded, NULL);
-               mono_profiler_install_appdomain_name (domain_name);
+               mono_profiler_set_domain_loaded_callback (handle, domain_loaded);
+               mono_profiler_set_domain_unloading_callback (handle, domain_unloaded);
+               mono_profiler_set_domain_name_callback (handle, domain_name);
        }
 
        if (config.effective_mask & PROFLOG_ASSEMBLY_EVENTS) {
-               events |= MONO_PROFILE_ASSEMBLY_EVENTS;
-               mono_profiler_install_assembly (NULL, assembly_loaded, assembly_unloaded, NULL);
+               mono_profiler_set_assembly_loaded_callback (handle, assembly_loaded);
+               mono_profiler_set_assembly_unloading_callback (handle, assembly_unloaded);
        }
 
        if (config.effective_mask & PROFLOG_MODULE_EVENTS) {
-               events |= MONO_PROFILE_MODULE_EVENTS;
-               mono_profiler_install_module (NULL, image_loaded, image_unloaded, NULL);
+               mono_profiler_set_image_loaded_callback (handle, image_loaded);
+               mono_profiler_set_image_unloading_callback (handle, image_unloaded);
        }
 
-       if (config.effective_mask & PROFLOG_CLASS_EVENTS) {
-               events |= MONO_PROFILE_CLASS_EVENTS;
-               mono_profiler_install_class (NULL, class_loaded, class_unloaded, NULL);
-       }
+       if (config.effective_mask & PROFLOG_CLASS_EVENTS)
+               mono_profiler_set_class_loaded_callback (handle, class_loaded);
 
        if (config.effective_mask & PROFLOG_JIT_COMPILATION_EVENTS) {
-               events |= MONO_PROFILE_JIT_COMPILATION;
-               mono_profiler_install_jit_end (method_jitted);
-               mono_profiler_install_code_buffer_new (code_buffer_new);
+               mono_profiler_set_jit_done_callback (handle, method_jitted);
+               mono_profiler_set_jit_code_buffer_callback (handle, code_buffer_new);
        }
 
        if (config.effective_mask & PROFLOG_EXCEPTION_EVENTS) {
-               events |= MONO_PROFILE_EXCEPTIONS;
-               mono_profiler_install_exception (throw_exc, method_exc_leave, NULL);
-               mono_profiler_install_exception_clause (clause_exc);
+               mono_profiler_set_exception_throw_callback (handle, throw_exc);
+               mono_profiler_set_exception_clause_callback (handle, clause_exc);
        }
 
        if (config.effective_mask & PROFLOG_ALLOCATION_EVENTS) {
-               events |= MONO_PROFILE_ALLOCATIONS;
-               mono_profiler_install_allocation (gc_alloc);
+               mono_profiler_enable_allocations ();
+               mono_profiler_set_gc_allocation_callback (handle, gc_alloc);
        }
 
        //PROFLOG_GC_EVENTS is mandatory
        //PROFLOG_THREAD_EVENTS is mandatory
 
        if (config.effective_mask & PROFLOG_CALL_EVENTS) {
-               events |= MONO_PROFILE_ENTER_LEAVE;
-               mono_profiler_install_enter_leave (method_enter, method_leave);
+               mono_profiler_set_call_instrumentation_filter_callback (handle, method_filter);
+               mono_profiler_set_method_enter_callback (handle, method_enter);
+               mono_profiler_set_method_leave_callback (handle, method_leave);
+               mono_profiler_set_method_exception_leave_callback (handle, method_exc_leave);
        }
 
-       if (config.effective_mask & PROFLOG_INS_COVERAGE_EVENTS) {
-               events |= MONO_PROFILE_INS_COVERAGE;
-               mono_profiler_install_coverage_filter (coverage_filter);
-       }
+       if (config.effective_mask & PROFLOG_INS_COVERAGE_EVENTS)
+               mono_profiler_set_coverage_filter_callback (handle, coverage_filter);
 
-       //XXX should we check for PROFLOG_SAMPLING_FEATURE instead??
        if (config.effective_mask & PROFLOG_SAMPLING_EVENTS) {
-               events |= MONO_PROFILE_STATISTICAL;
-               mono_profiler_set_statistical_mode (config.sampling_mode, config.sample_freq);
-               mono_profiler_install_statistical (mono_sample_hit);
+               mono_profiler_enable_sampling (handle);
+
+               if (!mono_profiler_set_sample_mode (handle, config.sampling_mode, config.sample_freq))
+                       mono_profiler_printf_err ("Another profiler controls sampling parameters; the log profiler will not be able to modify them.");
+
+               mono_profiler_set_sample_hit_callback (handle, mono_sample_hit);
        }
 
        if (config.effective_mask & PROFLOG_MONITOR_EVENTS) {
-               events |= MONO_PROFILE_MONITOR_EVENTS;
-               mono_profiler_install_monitor (monitor_event);
+               mono_profiler_set_monitor_contention_callback (handle, monitor_contention);
+               mono_profiler_set_monitor_acquired_callback (handle, monitor_acquired);
+               mono_profiler_set_monitor_failed_callback (handle, monitor_failed);
        }
 
-       if (config.effective_mask & PROFLOG_GC_MOVES_EVENTS) {
-               events |= MONO_PROFILE_GC_MOVES;
-               mono_profiler_install_gc_moves (gc_moves);
-       }
+       if (config.effective_mask & PROFLOG_GC_MOVES_EVENTS)
+               mono_profiler_set_gc_moves_callback (handle, gc_moves);
 
-       // TODO split those in two profiler events
-       if (config.effective_mask & (PROFLOG_GC_ROOT_EVENTS | PROFLOG_GC_HANDLE_EVENTS)) {
-               events |= MONO_PROFILE_GC_ROOTS;
-               mono_profiler_install_gc_roots (
-                       config.effective_mask & (PROFLOG_GC_HANDLE_EVENTS) ? gc_handle : NULL,
-                       (config.effective_mask & PROFLOG_GC_ROOT_EVENTS) ? gc_roots : NULL);
-       }
+       if (config.effective_mask & PROFLOG_GC_ROOT_EVENTS)
+               mono_profiler_set_gc_roots_callback (handle, gc_roots);
 
        if (config.effective_mask & PROFLOG_CONTEXT_EVENTS) {
-               events |= MONO_PROFILE_CONTEXT_EVENTS;
-               mono_profiler_install_context (context_loaded, context_unloaded);
+               mono_profiler_set_context_loaded_callback (handle, context_loaded);
+               mono_profiler_set_context_unloaded_callback (handle, context_unloaded);
        }
 
        if (config.effective_mask & PROFLOG_FINALIZATION_EVENTS) {
-               events |= MONO_PROFILE_GC_FINALIZATION;
-               mono_profiler_install_gc_finalize (finalize_begin, finalize_object_begin, finalize_object_end, finalize_end);   
+               mono_profiler_set_gc_finalizing_callback (handle, finalize_begin);
+               mono_profiler_set_gc_finalized_callback (handle, finalize_end);
+               mono_profiler_set_gc_finalizing_object_callback (handle, finalize_object_begin);
+               mono_profiler_set_gc_finalized_object_callback (handle, finalize_object_end);
        } else if (ENABLED (PROFLOG_HEAPSHOT_FEATURE) && config.hs_mode_ondemand) {
                //On Demand heapshot uses the finalizer thread to force a collection and thus a heapshot
-               events |= MONO_PROFILE_GC_FINALIZATION;
-               mono_profiler_install_gc_finalize (NULL, NULL, NULL, finalize_end);
+               mono_profiler_set_gc_finalized_callback (handle, finalize_end);
        }
 
        //PROFLOG_COUNTER_EVENTS is a pseudo event controled by the no_counters global var
-       //PROFLOG_GC_HANDLE_EVENTS is handled together with PROFLOG_GC_ROOT_EVENTS
 
-       mono_profiler_set_events ((MonoProfileFlags)events);
+       if (config.effective_mask & PROFLOG_GC_HANDLE_EVENTS) {
+               mono_profiler_set_gc_handle_created_callback (handle, gc_handle_created);
+               mono_profiler_set_gc_handle_deleted_callback (handle, gc_handle_deleted);
+       }
 }