Merge pull request #5095 from kumpera/fix_fullaot
[mono.git] / mono / profiler / log.c
index c1f56da19038b5d83b6cedf8df75256ef57e518a..d84ee526ca223d52314688d838b9f6cc6b1e1ed7 100644 (file)
@@ -69,6 +69,7 @@
 static volatile gint32 runtime_inited;
 static volatile gint32 in_shutdown;
 
+static ProfilerConfig config;
 static int nocalls = 0;
 static int notraces = 0;
 static int use_zip = 0;
@@ -85,6 +86,8 @@ static gboolean only_coverage = FALSE;
 static gboolean debug_coverage = FALSE;
 static int max_allocated_sample_hits;
 
+#define ENABLED(EVT) (config.effective_mask & (EVT))
+
 // Statistics for internal profiler data structures.
 static gint32 sample_allocations_ctr,
               buffer_allocations_ctr;
@@ -118,9 +121,7 @@ static gint32 sync_points_ctr,
               code_buffers_ctr,
               exception_throws_ctr,
               exception_clauses_ctr,
-              monitor_contentions_ctr,
-              monitor_acquisitions_ctr,
-              monitor_failures_ctr,
+              monitor_events_ctr,
               thread_starts_ctr,
               thread_ends_ctr,
               thread_names_ctr,
@@ -220,11 +221,11 @@ static MonoLinkedListSet profiler_thread_list;
  *
  * type alloc format:
  * type: TYPE_ALLOC
- * exinfo: flags: TYPE_ALLOC_BT
+ * exinfo: zero or TYPE_ALLOC_BT
  * [ptr: sleb128] class as a byte difference from ptr_base
  * [obj: sleb128] object address as a byte difference from obj_base
  * [size: uleb128] size of the object in the heap
- * If the TYPE_ALLOC_BT flag is set, a backtrace follows.
+ * If exinfo == TYPE_ALLOC_BT, a backtrace follows.
  *
  * type GC format:
  * type: TYPE_GC
@@ -257,7 +258,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
@@ -267,6 +269,7 @@ static MonoLinkedListSet profiler_thread_list;
  * if mtype == TYPE_IMAGE
  *     [name: string] image file name
  * if mtype == TYPE_ASSEMBLY
+ *     [image: sleb128] MonoImage* as a pointer difference from ptr_base
  *     [name: string] assembly name
  * if mtype == TYPE_DOMAIN && exinfo == 0
  *     [name: string] domain friendly name
@@ -287,15 +290,16 @@ static MonoLinkedListSet profiler_thread_list;
  *
  * type exception format:
  * type: TYPE_EXCEPTION
- * exinfo: TYPE_THROW_BT flag or one of: TYPE_CLAUSE
+ * exinfo: zero, TYPE_CLAUSE, or TYPE_THROW_BT
  * if exinfo == TYPE_CLAUSE
  *     [clause type: byte] MonoExceptionEnum enum value
  *     [clause index: uleb128] index of the current clause
  *     [method: sleb128] MonoMethod* as a pointer difference from the last such
  *     pointer or the buffer method_base
+ *     [object: sleb128] the exception object as a difference from obj_base
  * else
  *     [object: sleb128] the exception object as a difference from obj_base
- *     if exinfo has TYPE_THROW_BT set, a backtrace follows.
+ *     If exinfo == TYPE_THROW_BT, a backtrace follows.
  *
  * type runtime format:
  * type: TYPE_RUNTIME
@@ -309,10 +313,10 @@ static MonoLinkedListSet profiler_thread_list;
  *
  * type monitor format:
  * type: TYPE_MONITOR
- * exinfo: TYPE_MONITOR_BT flag and one of: MONO_PROFILER_MONITOR_(CONTENTION|FAIL|DONE)
+ * exinfo: zero or TYPE_MONITOR_BT
+ * [type: byte] MONO_PROFILER_MONITOR_{CONTENTION,FAIL,DONE}
  * [object: sleb128] the lock object as a difference from obj_base
- * if exinfo.low3bits == MONO_PROFILER_MONITOR_CONTENTION
- *     If the TYPE_MONITOR_BT flag is set, a backtrace follows.
+ * If exinfo == TYPE_MONITOR_BT, a backtrace follows.
  *
  * type heap format
  * type: TYPE_HEAP
@@ -352,7 +356,7 @@ static MonoLinkedListSet profiler_thread_list;
  *     [size: uleb128] symbol size (may be 0 if unknown)
  *     [name: string] symbol name
  * if exinfo == TYPE_SAMPLE_UBIN
- *     [address: sleb128] address where binary has been loaded
+ *     [address: sleb128] address where binary has been loaded as a difference from ptr_base
  *     [offset: uleb128] file offset of mapping (the same file can be mapped multiple times)
  *     [size: uleb128] memory size
  *     [name: string] binary name
@@ -375,9 +379,9 @@ static MonoLinkedListSet profiler_thread_list;
  *             [type: byte] type of counter value
  *             if type == string:
  *                     if value == null:
- *                             [0: uleb128] 0 -> value is null
+ *                             [0: byte] 0 -> value is null
  *                     else:
- *                             [1: uleb128] 1 -> value is not null
+ *                             [1: byte] 1 -> value is not null
  *                             [value: string] counter value
  *             else:
  *                     [value: uleb128/sleb128/double] counter value, can be sleb128, uleb128 or double (determined by using type)
@@ -476,8 +480,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)
 {
@@ -555,17 +593,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?"); \
@@ -573,101 +616,19 @@ init_time (void)
                InterlockedIncrement ((COUNTER)); \
                LogBuffer *BUFFER = ensure_logbuf_unsafe (thread__, (SIZE))
 
-#define EXIT_LOG_EXPLICIT(SEND, REQUESTS) \
+#define EXIT_LOG_EXPLICIT(SEND) \
                thread__->busy = FALSE; \
                if ((SEND)) \
                        send_log_unsafe (TRUE); \
                if (thread__->attached) \
                        buffer_unlock (); \
-               if ((REQUESTS)) \
-                       process_requests (); \
        } while (0)
 
 // Pass these to EXIT_LOG_EXPLICIT () for easier reading.
 #define DO_SEND TRUE
 #define NO_SEND FALSE
-#define DO_REQUESTS TRUE
-#define NO_REQUESTS FALSE
 
-#define EXIT_LOG EXIT_LOG_EXPLICIT (DO_SEND, DO_REQUESTS)
-
-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);
-}
+#define EXIT_LOG EXIT_LOG_EXPLICIT (DO_SEND)
 
 typedef struct _BinaryObject BinaryObject;
 struct _BinaryObject {
@@ -676,6 +637,8 @@ struct _BinaryObject {
        char *name;
 };
 
+static MonoProfiler *log_profiler;
+
 struct _MonoProfiler {
        FILE* file;
 #if defined (HAVE_SYS_ZLIB)
@@ -721,35 +684,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)
 {
@@ -772,9 +706,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);
 
@@ -797,7 +731,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;
 }
 
@@ -838,6 +772,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.
@@ -863,22 +799,155 @@ deinit_thread (MonoProfilerThread *thread)
        PROF_TLS_SET (NULL);
 }
 
+static MonoProfilerThread *
+get_thread (void)
+{
+       return init_thread (log_profiler, 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)
 {
@@ -1012,10 +1081,11 @@ 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)) {
                MethodInfo *info = (MethodInfo *) g_malloc (sizeof (MethodInfo));
@@ -1203,15 +1273,17 @@ free_thread (gpointer p)
 
                InterlockedIncrement (&thread_ends_ctr);
 
-               LogBuffer *buf = ensure_logbuf_unsafe (thread,
-                       EVENT_SIZE /* event */ +
-                       BYTE_SIZE /* type */ +
-                       LEB128_SIZE /* tid */
-               );
+               if (ENABLED (PROFLOG_THREAD_EVENTS)) {
+                       LogBuffer *buf = ensure_logbuf_unsafe (thread,
+                               EVENT_SIZE /* event */ +
+                               BYTE_SIZE /* type */ +
+                               LEB128_SIZE /* tid */
+                       );
 
-               emit_event (buf, TYPE_END_UNLOAD | TYPE_METADATA);
-               emit_byte (buf, TYPE_THREAD);
-               emit_ptr (buf, (void *) thread->node.key);
+                       emit_event (buf, TYPE_END_UNLOAD | TYPE_METADATA);
+                       emit_byte (buf, TYPE_THREAD);
+                       emit_ptr (buf, (void *) thread->node.key);
+               }
        }
 
        send_buffer (thread);
@@ -1273,13 +1345,6 @@ dump_buffer_threadless (MonoProfiler *profiler, LogBuffer *buf)
        dump_buffer (profiler, buf);
 }
 
-static void
-process_requests (void)
-{
-       if (heapshot_requested)
-               mono_gc_collect (mono_gc_max_generation ());
-}
-
 // Only valid if init_thread () was called with add_to_lls = FALSE.
 static void
 send_log_unsafe (gboolean if_needed)
@@ -1300,7 +1365,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?");
@@ -1314,7 +1379,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 */ +
@@ -1324,7 +1389,7 @@ sync_point_mark (MonoProfilerSyncPointType type)
        emit_event (logbuffer, TYPE_META | TYPE_SYNC_POINT);
        emit_byte (logbuffer, type);
 
-       EXIT_LOG_EXPLICIT (NO_SEND, NO_REQUESTS);
+       EXIT_LOG_EXPLICIT (NO_SEND);
 
        send_log_unsafe (FALSE);
 }
@@ -1370,7 +1435,7 @@ gc_reference (MonoObject *obj, MonoClass *klass, uintptr_t size, uintptr_t num,
                emit_obj (logbuffer, refs [i]);
        }
 
-       EXIT_LOG_EXPLICIT (DO_SEND, NO_REQUESTS);
+       EXIT_LOG_EXPLICIT (DO_SEND);
 
        return 0;
 }
@@ -1381,32 +1446,14 @@ static unsigned int hs_mode_ondemand = 0;
 static unsigned int gc_count = 0;
 static uint64_t last_hs_time = 0;
 static gboolean do_heap_walk = FALSE;
-
-static void
-heap_walk (MonoProfiler *profiler)
-{
-       ENTER_LOG (&heap_starts_ctr, logbuffer,
-               EVENT_SIZE /* event */
-       );
-
-       emit_event (logbuffer, TYPE_HEAP_START | TYPE_HEAP);
-
-       EXIT_LOG_EXPLICIT (DO_SEND, NO_REQUESTS);
-
-       mono_gc_walk_heap (0, gc_reference, NULL);
-
-       ENTER_LOG (&heap_ends_ctr, logbuffer,
-               EVENT_SIZE /* event */
-       );
-
-       emit_event (logbuffer, TYPE_HEAP_END | TYPE_HEAP);
-
-       EXIT_LOG_EXPLICIT (DO_SEND, NO_REQUESTS);
-}
+static gboolean ignore_heap_events;
 
 static void
 gc_roots (MonoProfiler *prof, int num, void **objects, int *root_types, uintptr_t *extra_info)
 {
+       if (ignore_heap_events)
+               return;
+
        ENTER_LOG (&heap_roots_ctr, logbuffer,
                EVENT_SIZE /* event */ +
                LEB128_SIZE /* num */ +
@@ -1428,29 +1475,23 @@ gc_roots (MonoProfiler *prof, int num, void **objects, int *root_types, uintptr_
                emit_value (logbuffer, extra_info [i]);
        }
 
-       EXIT_LOG_EXPLICIT (DO_SEND, NO_REQUESTS);
+       EXIT_LOG_EXPLICIT (DO_SEND);
 }
 
+
 static void
-gc_event (MonoProfiler *profiler, MonoGCEvent ev, int generation)
+trigger_on_demand_heapshot (void)
 {
-       ENTER_LOG (&gc_events_ctr, logbuffer,
-               EVENT_SIZE /* event */ +
-               BYTE_SIZE /* gc event */ +
-               BYTE_SIZE /* generation */
-       );
-
-       emit_event (logbuffer, TYPE_GC_EVENT | TYPE_GC);
-       emit_byte (logbuffer, ev);
-       emit_byte (logbuffer, generation);
-
-       EXIT_LOG_EXPLICIT (NO_SEND, NO_REQUESTS);
+       if (heapshot_requested)
+               mono_gc_collect (mono_gc_max_generation ());
+}
 
-       switch (ev) {
-       case MONO_GC_EVENT_START:
-               if (generation == mono_gc_max_generation ())
-                       gc_count++;
+#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)
+{
+       if (ev == MONO_GC_EVENT_START) {
                uint64_t now = current_time ();
 
                if (hs_mode_ms && (now - last_hs_time) / 1000 * 1000 >= hs_mode_ms)
@@ -1461,6 +1502,34 @@ gc_event (MonoProfiler *profiler, MonoGCEvent ev, int generation)
                        do_heap_walk = heapshot_requested;
                else if (!hs_mode_ms && !hs_mode_gc && generation == mono_gc_max_generation ())
                        do_heap_walk = TRUE;
+
+               //If using heapshot, ignore events for collections we don't care
+               if (ENABLED (PROFLOG_HEAPSHOT_FEATURE)) {
+                       // Ignore events generated during the collection itself (IE GC ROOTS)
+                       ignore_heap_events = !do_heap_walk;
+               }
+       }
+
+
+       if (ENABLED (PROFLOG_GC_EVENTS)) {
+               ENTER_LOG (&gc_events_ctr, logbuffer,
+                       EVENT_SIZE /* event */ +
+                       BYTE_SIZE /* gc event */ +
+                       BYTE_SIZE /* generation */
+               );
+
+               emit_event (logbuffer, TYPE_GC_EVENT | TYPE_GC);
+               emit_byte (logbuffer, ev);
+               emit_byte (logbuffer, generation);
+
+               EXIT_LOG_EXPLICIT (NO_SEND);
+       }
+
+       switch (ev) {
+       case MONO_GC_EVENT_START:
+               if (generation == mono_gc_max_generation ())
+                       gc_count++;
+
                break;
        case MONO_GC_EVENT_PRE_STOP_WORLD_LOCKED:
                /*
@@ -1477,26 +1546,55 @@ gc_event (MonoProfiler *profiler, MonoGCEvent ev, int generation)
                 * committed to the log file before any object move events
                 * that will be produced during this GC.
                 */
-               sync_point (SYNC_POINT_WORLD_STOP);
+               if (ENABLED (ALL_GC_EVENTS_MASK))
+                       sync_point (SYNC_POINT_WORLD_STOP);
+
+               /*
+                * All heap events are surrounded by a HEAP_START and a HEAP_ENV event.
+                * Right now, that's the case for GC Moves, GC Roots or heapshots.
+                */
+               if (ENABLED (PROFLOG_GC_MOVES_EVENTS | PROFLOG_GC_ROOT_EVENTS) || do_heap_walk) {
+                       ENTER_LOG (&heap_starts_ctr, logbuffer,
+                               EVENT_SIZE /* event */
+                       );
+
+                       emit_event (logbuffer, TYPE_HEAP_START | TYPE_HEAP);
+
+                       EXIT_LOG_EXPLICIT (DO_SEND);
+               }
+
                break;
        case MONO_GC_EVENT_PRE_START_WORLD:
-               if (do_heap_shot && do_heap_walk) {
-                       heap_walk (profiler);
+               if (do_heap_shot && do_heap_walk)
+                       mono_gc_walk_heap (0, gc_reference, NULL);
+
+               /* Matching HEAP_END to the HEAP_START from above */
+               if (ENABLED (PROFLOG_GC_MOVES_EVENTS | PROFLOG_GC_ROOT_EVENTS) || do_heap_walk) {
+                       ENTER_LOG (&heap_ends_ctr, logbuffer,
+                               EVENT_SIZE /* event */
+                       );
+
+                       emit_event (logbuffer, TYPE_HEAP_END | TYPE_HEAP);
+
+                       EXIT_LOG_EXPLICIT (DO_SEND);
+               }
 
+               if (do_heap_shot && do_heap_walk) {
                        do_heap_walk = FALSE;
                        heapshot_requested = 0;
                        last_hs_time = current_time ();
                }
-               break;
-       case MONO_GC_EVENT_POST_START_WORLD_UNLOCKED:
+
                /*
                 * Similarly, we must now make sure that any object moves
                 * written to the GC thread's buffer are flushed. Otherwise,
                 * object allocation events for certain addresses could come
                 * after the move events that made those addresses available.
                 */
-               sync_point_mark (SYNC_POINT_WORLD_START);
-
+               if (ENABLED (ALL_GC_EVENTS_MASK))
+                       sync_point_mark (SYNC_POINT_WORLD_START);
+               break;
+       case MONO_GC_EVENT_POST_START_WORLD_UNLOCKED:
                /*
                 * Finally, it is safe to allow other threads to write to
                 * their buffers again.
@@ -1519,7 +1617,7 @@ gc_resize (MonoProfiler *profiler, int64_t new_size)
        emit_event (logbuffer, TYPE_GC_RESIZE | TYPE_GC);
        emit_value (logbuffer, new_size);
 
-       EXIT_LOG_EXPLICIT (DO_SEND, NO_REQUESTS);
+       EXIT_LOG_EXPLICIT (DO_SEND);
 }
 
 typedef struct {
@@ -1559,24 +1657,18 @@ collect_bt (FrameData *data)
 static void
 emit_bt (MonoProfiler *prof, 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)
 {
-       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);
@@ -1628,7 +1720,7 @@ gc_moves (MonoProfiler *prof, void **objects, int num)
        for (int i = 0; i < num; ++i)
                emit_obj (logbuffer, objects [i]);
 
-       EXIT_LOG_EXPLICIT (DO_SEND, NO_REQUESTS);
+       EXIT_LOG_EXPLICIT (DO_SEND);
 }
 
 static void
@@ -1691,13 +1783,16 @@ finalize_begin (MonoProfiler *prof)
 static void
 finalize_end (MonoProfiler *prof)
 {
-       ENTER_LOG (&finalize_ends_ctr, buf,
-               EVENT_SIZE /* event */
-       );
+       trigger_on_demand_heapshot ();
+       if (ENABLED (PROFLOG_FINALIZATION_EVENTS)) {
+               ENTER_LOG (&finalize_ends_ctr, buf,
+                       EVENT_SIZE /* event */
+               );
 
-       emit_event (buf, TYPE_GC_FINALIZE_END | TYPE_GC);
+               emit_event (buf, TYPE_GC_FINALIZE_END | TYPE_GC);
 
-       EXIT_LOG;
+               EXIT_LOG;
+       }
 }
 
 static void
@@ -1819,17 +1914,20 @@ assembly_loaded (MonoProfiler *prof, MonoAssembly *assembly, int result)
 
        char *name = mono_stringify_assembly_name (mono_assembly_get_name (assembly));
        int nlen = strlen (name) + 1;
+       MonoImage *image = mono_assembly_get_image (assembly);
 
        ENTER_LOG (&assembly_loads_ctr, logbuffer,
                EVENT_SIZE /* event */ +
                BYTE_SIZE /* type */ +
                LEB128_SIZE /* assembly */ +
+               LEB128_SIZE /* image */ +
                nlen /* name */
        );
 
        emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
        emit_byte (logbuffer, TYPE_ASSEMBLY);
        emit_ptr (logbuffer, assembly);
+       emit_ptr (logbuffer, image);
        memcpy (logbuffer->cursor, name, nlen);
        logbuffer->cursor += nlen;
 
@@ -1843,17 +1941,20 @@ assembly_unloaded (MonoProfiler *prof, MonoAssembly *assembly)
 {
        char *name = mono_stringify_assembly_name (mono_assembly_get_name (assembly));
        int nlen = strlen (name) + 1;
+       MonoImage *image = mono_assembly_get_image (assembly);
 
        ENTER_LOG (&assembly_unloads_ctr, logbuffer,
                EVENT_SIZE /* event */ +
                BYTE_SIZE /* type */ +
                LEB128_SIZE /* assembly */ +
+               LEB128_SIZE /* image */ +
                nlen /* name */
        );
 
        emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
        emit_byte (logbuffer, TYPE_ASSEMBLY);
        emit_ptr (logbuffer, assembly);
+       emit_ptr (logbuffer, image);
        memcpy (logbuffer->cursor, name, nlen);
        logbuffer->cursor += nlen;
 
@@ -1901,42 +2002,6 @@ 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
@@ -1944,7 +2009,7 @@ method_enter (MonoProfiler *prof, MonoMethod *method)
 {
        process_method_enter_coverage (prof, method);
 
-       if (!only_coverage && PROF_TLS_GET ()->call_depth++ <= max_call_depth) {
+       if (!only_coverage && get_thread ()->call_depth++ <= max_call_depth) {
                ENTER_LOG (&method_entries_ctr, logbuffer,
                        EVENT_SIZE /* event */ +
                        LEB128_SIZE /* method */
@@ -1960,7 +2025,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 (!only_coverage && --get_thread ()->call_depth <= max_call_depth) {
                ENTER_LOG (&method_exits_ctr, logbuffer,
                        EVENT_SIZE /* event */ +
                        LEB128_SIZE /* method */
@@ -1976,7 +2041,7 @@ method_leave (MonoProfiler *prof, MonoMethod *method)
 static void
 method_exc_leave (MonoProfiler *prof, MonoMethod *method)
 {
-       if (!only_coverage && !nocalls && --PROF_TLS_GET ()->call_depth <= max_call_depth) {
+       if (!only_coverage && !nocalls && --get_thread ()->call_depth <= max_call_depth) {
                ENTER_LOG (&method_exception_exits_ctr, logbuffer,
                        EVENT_SIZE /* event */ +
                        LEB128_SIZE /* method */
@@ -1995,9 +2060,11 @@ method_jitted (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *ji, int resu
        if (result != MONO_PROFILE_OK)
                return;
 
+       buffer_lock ();
+
        register_method_local (method, ji);
 
-       process_requests ();
+       buffer_unlock ();
 }
 
 static void
@@ -2067,7 +2134,7 @@ throw_exc (MonoProfiler *prof, MonoObject *object)
 }
 
 static void
-clause_exc (MonoProfiler *prof, MonoMethod *method, int clause_type, int clause_num)
+clause_exc (MonoProfiler *prof, MonoMethod *method, int clause_type, int clause_num, MonoObject *exc)
 {
        ENTER_LOG (&exception_clauses_ctr, logbuffer,
                EVENT_SIZE /* event */ +
@@ -2080,38 +2147,23 @@ clause_exc (MonoProfiler *prof, MonoMethod *method, int clause_type, int clause_
        emit_byte (logbuffer, clause_type);
        emit_value (logbuffer, clause_num);
        emit_method (logbuffer, method);
+       emit_obj (logbuffer, exc);
 
        EXIT_LOG;
 }
 
 static void
-monitor_event (MonoProfiler *profiler, MonoObject *object, MonoProfilerMonitorEvent event)
+monitor_event (MonoProfiler *profiler, MonoObject *object, MonoProfilerMonitorEvent ev)
 {
-       int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces && event == MONO_PROFILER_MONITOR_CONTENTION) ? TYPE_MONITOR_BT : 0;
+       int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces) ? TYPE_MONITOR_BT : 0;
        FrameData data;
 
        if (do_bt)
                collect_bt (&data);
 
-       gint32 *ctr;
-
-       switch (event) {
-       case MONO_PROFILER_MONITOR_CONTENTION:
-               ctr = &monitor_contentions_ctr;
-               break;
-       case MONO_PROFILER_MONITOR_DONE:
-               ctr = &monitor_acquisitions_ctr;
-               break;
-       case MONO_PROFILER_MONITOR_FAIL:
-               ctr = &monitor_failures_ctr;
-               break;
-       default:
-               g_assert_not_reached ();
-               break;
-       }
-
-       ENTER_LOG (ctr, logbuffer,
+       ENTER_LOG (&monitor_events_ctr, logbuffer,
                EVENT_SIZE /* event */ +
+               BYTE_SIZE /* ev */ +
                LEB128_SIZE /* object */ +
                (do_bt ? (
                        LEB128_SIZE /* count */ +
@@ -2121,7 +2173,8 @@ monitor_event (MonoProfiler *profiler, MonoObject *object, MonoProfilerMonitorEv
                ) : 0)
        );
 
-       emit_event (logbuffer, (event << 4) | do_bt | TYPE_MONITOR);
+       emit_event (logbuffer, do_bt | TYPE_MONITOR);
+       emit_byte (logbuffer, ev);
        emit_obj (logbuffer, object);
 
        if (do_bt)
@@ -2133,37 +2186,39 @@ monitor_event (MonoProfiler *profiler, MonoObject *object, MonoProfilerMonitorEv
 static void
 thread_start (MonoProfiler *prof, uintptr_t tid)
 {
-       init_thread (prof, TRUE);
-
-       ENTER_LOG (&thread_starts_ctr, logbuffer,
-               EVENT_SIZE /* event */ +
-               BYTE_SIZE /* type */ +
-               LEB128_SIZE /* tid */
-       );
+       if (ENABLED (PROFLOG_THREAD_EVENTS)) {
+               ENTER_LOG (&thread_starts_ctr, logbuffer,
+                       EVENT_SIZE /* event */ +
+                       BYTE_SIZE /* type */ +
+                       LEB128_SIZE /* tid */
+               );
 
-       emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
-       emit_byte (logbuffer, TYPE_THREAD);
-       emit_ptr (logbuffer, (void*) tid);
+               emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
+               emit_byte (logbuffer, TYPE_THREAD);
+               emit_ptr (logbuffer, (void*) tid);
 
-       EXIT_LOG;
+               EXIT_LOG;
+       }
 }
 
 static void
 thread_end (MonoProfiler *prof, uintptr_t tid)
 {
-       ENTER_LOG (&thread_ends_ctr, logbuffer,
-               EVENT_SIZE /* event */ +
-               BYTE_SIZE /* type */ +
-               LEB128_SIZE /* tid */
-       );
+       if (ENABLED (PROFLOG_THREAD_EVENTS)) {
+               ENTER_LOG (&thread_ends_ctr, logbuffer,
+                       EVENT_SIZE /* event */ +
+                       BYTE_SIZE /* type */ +
+                       LEB128_SIZE /* tid */
+               );
 
-       emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
-       emit_byte (logbuffer, TYPE_THREAD);
-       emit_ptr (logbuffer, (void*) tid);
+               emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
+               emit_byte (logbuffer, TYPE_THREAD);
+               emit_ptr (logbuffer, (void*) tid);
 
-       EXIT_LOG_EXPLICIT (NO_SEND, NO_REQUESTS);
+               EXIT_LOG_EXPLICIT (NO_SEND);
+       }
 
-       MonoProfilerThread *thread = PROF_TLS_GET ();
+       MonoProfilerThread *thread = get_thread ();
 
        thread->ended = TRUE;
        remove_thread (thread);
@@ -2176,20 +2231,22 @@ thread_name (MonoProfiler *prof, uintptr_t tid, const char *name)
 {
        int len = strlen (name) + 1;
 
-       ENTER_LOG (&thread_names_ctr, logbuffer,
-               EVENT_SIZE /* event */ +
-               BYTE_SIZE /* type */ +
-               LEB128_SIZE /* tid */ +
-               len /* name */
-       );
+       if (ENABLED (PROFLOG_THREAD_EVENTS)) {
+               ENTER_LOG (&thread_names_ctr, logbuffer,
+                       EVENT_SIZE /* event */ +
+                       BYTE_SIZE /* type */ +
+                       LEB128_SIZE /* tid */ +
+                       len /* name */
+               );
 
-       emit_event (logbuffer, TYPE_METADATA);
-       emit_byte (logbuffer, TYPE_THREAD);
-       emit_ptr (logbuffer, (void*)tid);
-       memcpy (logbuffer->cursor, name, len);
-       logbuffer->cursor += len;
+               emit_event (logbuffer, TYPE_METADATA);
+               emit_byte (logbuffer, TYPE_THREAD);
+               emit_ptr (logbuffer, (void*)tid);
+               memcpy (logbuffer->cursor, name, len);
+               logbuffer->cursor += len;
 
-       EXIT_LOG;
+               EXIT_LOG;
+       }
 }
 
 static void
@@ -2444,13 +2501,13 @@ dump_ubin (MonoProfiler *prof, const char *filename, uintptr_t load_addr, uint64
        );
 
        emit_event (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_UBIN);
-       emit_svalue (logbuffer, load_addr);
+       emit_ptr (logbuffer, load_addr);
        emit_uvalue (logbuffer, offset);
        emit_uvalue (logbuffer, size);
        memcpy (logbuffer->cursor, filename, len);
        logbuffer->cursor += len;
 
-       EXIT_LOG_EXPLICIT (DO_SEND, NO_REQUESTS);
+       EXIT_LOG_EXPLICIT (DO_SEND);
 }
 #endif
 
@@ -2472,7 +2529,7 @@ dump_usym (MonoProfiler *prof, const char *name, uintptr_t value, uintptr_t size
        memcpy (logbuffer->cursor, name, len);
        logbuffer->cursor += len;
 
-       EXIT_LOG_EXPLICIT (DO_SEND, NO_REQUESTS);
+       EXIT_LOG_EXPLICIT (DO_SEND);
 }
 
 /* ELF code crashes on some systems. */
@@ -2836,7 +2893,7 @@ counters_emit (MonoProfiler *profiler)
                agent->emitted = 1;
        }
 
-       EXIT_LOG_EXPLICIT (DO_SEND, NO_REQUESTS);
+       EXIT_LOG_EXPLICIT (DO_SEND);
 
 done:
        mono_os_mutex_unlock (&counters_mutex);
@@ -2959,7 +3016,7 @@ counters_sample (MonoProfiler *profiler, uint64_t timestamp)
 
        emit_value (logbuffer, 0);
 
-       EXIT_LOG_EXPLICIT (DO_SEND, NO_REQUESTS);
+       EXIT_LOG_EXPLICIT (DO_SEND);
 
        mono_os_mutex_unlock (&counters_mutex);
 }
@@ -3029,7 +3086,7 @@ perfcounters_emit (MonoProfiler *profiler)
                pcagent->emitted = 1;
        }
 
-       EXIT_LOG_EXPLICIT (DO_SEND, NO_REQUESTS);
+       EXIT_LOG_EXPLICIT (DO_SEND);
 }
 
 static gboolean
@@ -3122,7 +3179,7 @@ perfcounters_sample (MonoProfiler *profiler, uint64_t timestamp)
 
        emit_value (logbuffer, 0);
 
-       EXIT_LOG_EXPLICIT (DO_SEND, NO_REQUESTS);
+       EXIT_LOG_EXPLICIT (DO_SEND);
 
 done:
        mono_os_mutex_unlock (&counters_mutex);
@@ -3295,7 +3352,7 @@ build_method_buffer (gpointer key, gpointer value, gpointer userdata)
        emit_uvalue (logbuffer, method_id);
        emit_value (logbuffer, coverage_data->len);
 
-       EXIT_LOG_EXPLICIT (DO_SEND, NO_REQUESTS);
+       EXIT_LOG_EXPLICIT (DO_SEND);
 
        for (i = 0; i < coverage_data->len; i++) {
                CoverageEntry *entry = (CoverageEntry *)coverage_data->pdata[i];
@@ -3316,7 +3373,7 @@ build_method_buffer (gpointer key, gpointer value, gpointer userdata)
                emit_uvalue (logbuffer, entry->line);
                emit_uvalue (logbuffer, entry->column);
 
-               EXIT_LOG_EXPLICIT (DO_SEND, NO_REQUESTS);
+               EXIT_LOG_EXPLICIT (DO_SEND);
        }
 
        method_id++;
@@ -3380,7 +3437,7 @@ build_class_buffer (gpointer key, gpointer value, gpointer userdata)
        emit_uvalue (logbuffer, fully_covered);
        emit_uvalue (logbuffer, partially_covered);
 
-       EXIT_LOG_EXPLICIT (DO_SEND, NO_REQUESTS);
+       EXIT_LOG_EXPLICIT (DO_SEND);
 
        g_free (class_name);
 }
@@ -3437,7 +3494,7 @@ build_assembly_buffer (gpointer key, gpointer value, gpointer userdata)
        emit_uvalue (logbuffer, fully_covered);
        emit_uvalue (logbuffer, partially_covered);
 
-       EXIT_LOG_EXPLICIT (DO_SEND, NO_REQUESTS);
+       EXIT_LOG_EXPLICIT (DO_SEND);
 }
 
 static void
@@ -3875,8 +3932,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)
@@ -4065,7 +4124,7 @@ helper_thread (void *arg)
                        buf [len] = 0;
 
                        if (!strcmp (buf, "heapshot\n") && hs_mode_ondemand) {
-                               // Rely on the finalization callbacks invoking process_requests ().
+                               // Rely on the finalization callback triggering a GC.
                                heapshot_requested = 1;
                                mono_gc_finalize_notify ();
                        }
@@ -4216,7 +4275,7 @@ handle_writer_queue_entry (MonoProfiler *prof)
                        memcpy (logbuffer->cursor, name, nlen);
                        logbuffer->cursor += nlen;
 
-                       EXIT_LOG_EXPLICIT (NO_SEND, NO_REQUESTS);
+                       EXIT_LOG_EXPLICIT (NO_SEND);
 
                        mono_free (name);
 
@@ -4229,8 +4288,10 @@ 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 (prof, thread->buffer);
+                       init_buffer_state (thread);
                }
 
        no_methods:
@@ -4345,7 +4406,7 @@ handle_dumper_queue_entry (MonoProfiler *prof)
                for (int i = 0; i < sample->count; ++i)
                        emit_method (logbuffer, sample->frames [i].method);
 
-               EXIT_LOG_EXPLICIT (DO_SEND, NO_REQUESTS);
+               EXIT_LOG_EXPLICIT (DO_SEND);
 
                mono_thread_hazardous_try_free (sample, reuse_sample_hit);
 
@@ -4366,7 +4427,13 @@ dumper_thread (void *arg)
        MonoProfilerThread *thread = init_thread (prof, FALSE);
 
        while (InterlockedRead (&prof->run_dumper_thread)) {
-               mono_os_sem_wait (&prof->dumper_queue_sem, MONO_SEM_FLAGS_NONE);
+               /*
+                * 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)
+                       send_log_unsafe (FALSE);
+
                handle_dumper_queue_entry (prof);
        }
 
@@ -4434,9 +4501,7 @@ runtime_initialized (MonoProfiler *profiler)
        register_counter ("Event: Code buffers", &code_buffers_ctr);
        register_counter ("Event: Exception throws", &exception_throws_ctr);
        register_counter ("Event: Exception clauses", &exception_clauses_ctr);
-       register_counter ("Event: Monitor contentions", &monitor_contentions_ctr);
-       register_counter ("Event: Monitor acquisitions", &monitor_acquisitions_ctr);
-       register_counter ("Event: Monitor failures", &monitor_failures_ctr);
+       register_counter ("Event: Monitor events", &monitor_events_ctr);
        register_counter ("Event: Thread starts", &thread_starts_ctr);
        register_counter ("Event: Thread ends", &thread_ends_ctr);
        register_counter ("Event: Thread names", &thread_names_ctr);
@@ -4469,21 +4534,27 @@ runtime_initialized (MonoProfiler *profiler)
        start_dumper_thread (profiler);
 }
 
-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;
+       log_profiler = (MonoProfiler *) g_calloc (1, sizeof (MonoProfiler));
+       log_profiler->args = pstrdup (args);
+       log_profiler->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");
        }
+
+       //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 -";
@@ -4501,24 +4572,24 @@ 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");
+               log_profiler->file = fdopen (fd, "a");
        } else {
                if (force_delete)
                        unlink (nf);
-               prof->file = fopen (nf, "wb");
+               log_profiler->file = fopen (nf, "wb");
        }
-       if (!prof->file) {
+       if (!log_profiler->file) {
                fprintf (stderr, "Cannot create profiler output: %s\n", 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
 
        /*
@@ -4528,32 +4599,31 @@ 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 (log_profiler);
+       log_profiler->coverage_filters = filters;
 
-       prof->startup_time = current_time ();
-       return prof;
+       log_profiler->startup_time = current_time ();
 }
 
 /*
@@ -4576,13 +4646,10 @@ mono_profiler_startup_log (const char *desc)
        mono_profiler_startup (desc);
 }
 
-static ProfilerConfig config;
-
 void
 mono_profiler_startup (const char *desc)
 {
        GPtrArray *filters = NULL;
-       MonoProfiler *prof;
 
        proflog_parse_args (&config, desc [3] == ':' ? desc + 4 : "");
 
@@ -4619,21 +4686,15 @@ 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;
 
        //Required callbacks
-       mono_profiler_install (prof, log_shutdown);
+       mono_profiler_install (log_profiler, log_shutdown);
        mono_profiler_install_runtime_initialized (runtime_initialized);
 
        mono_profiler_install_gc (gc_event, gc_resize);
@@ -4661,7 +4722,7 @@ mono_profiler_startup (const char *desc)
 
        if (config.effective_mask & PROFLOG_CLASS_EVENTS) {
                events |= MONO_PROFILE_CLASS_EVENTS;
-               mono_profiler_install_class (NULL, class_loaded, class_unloaded, NULL);
+               mono_profiler_install_class (NULL, class_loaded, NULL, NULL);
        }
 
        if (config.effective_mask & PROFLOG_JIT_COMPILATION_EVENTS) {
@@ -4672,7 +4733,8 @@ mono_profiler_startup (const char *desc)
 
        if (config.effective_mask & PROFLOG_EXCEPTION_EVENTS) {
                events |= MONO_PROFILE_EXCEPTIONS;
-               mono_profiler_install_exception (throw_exc, method_exc_leave, clause_exc);
+               mono_profiler_install_exception (throw_exc, method_exc_leave, NULL);
+               mono_profiler_install_exception_clause (clause_exc);
        }
 
        if (config.effective_mask & PROFLOG_ALLOCATION_EVENTS) {
@@ -4726,6 +4788,10 @@ mono_profiler_startup (const char *desc)
        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);   
+       } 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);
        }
 
        //PROFLOG_COUNTER_EVENTS is a pseudo event controled by the no_counters global var