2 * log.c: mono log profiler
5 * Paolo Molaro (lupus@ximian.com)
6 * Alex Rønne Petersen (alexrp@xamarin.com)
8 * Copyright 2010 Novell, Inc (http://www.novell.com)
9 * Copyright 2011 Xamarin Inc (http://www.xamarin.com)
10 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
14 #include <mono/metadata/assembly.h>
15 #include <mono/metadata/debug-helpers.h>
16 #include "../metadata/metadata-internals.h"
17 #include <mono/metadata/mono-config.h>
18 #include <mono/metadata/mono-gc.h>
19 #include <mono/metadata/mono-perfcounters.h>
20 #include <mono/utils/atomic.h>
21 #include <mono/utils/hazard-pointer.h>
22 #include <mono/utils/lock-free-alloc.h>
23 #include <mono/utils/lock-free-queue.h>
24 #include <mono/utils/mono-conc-hashtable.h>
25 #include <mono/utils/mono-counters.h>
26 #include <mono/utils/mono-logger-internals.h>
27 #include <mono/utils/mono-linked-list-set.h>
28 #include <mono/utils/mono-membar.h>
29 #include <mono/utils/mono-mmap.h>
30 #include <mono/utils/mono-os-mutex.h>
31 #include <mono/utils/mono-os-semaphore.h>
32 #include <mono/utils/mono-threads.h>
33 #include <mono/utils/mono-threads-api.h>
46 #if defined(__APPLE__)
47 #include <mach/mach_time.h>
49 #include <netinet/in.h>
50 #ifdef HAVE_SYS_MMAN_H
53 #include <sys/socket.h>
54 #if defined (HAVE_SYS_ZLIB)
58 // Statistics for internal profiler data structures.
59 static gint32 sample_allocations_ctr,
60 buffer_allocations_ctr;
62 // Statistics for profiler events.
63 static gint32 sync_points_ctr,
72 gc_handle_creations_ctr,
73 gc_handle_deletions_ctr,
76 finalize_object_begins_ctr,
77 finalize_object_ends_ctr,
86 method_exception_exits_ctr,
90 exception_clauses_ctr,
103 counter_descriptors_ctr,
105 perfcounter_descriptors_ctr,
106 perfcounter_samples_ctr,
107 coverage_methods_ctr,
108 coverage_statements_ctr,
109 coverage_classes_ctr,
110 coverage_assemblies_ctr;
112 // Pending data to be written to the log, for a single thread.
113 // Threads periodically flush their own LogBuffers by calling safe_send
114 typedef struct _LogBuffer LogBuffer;
116 // Next (older) LogBuffer in processing queue
122 uintptr_t method_base;
123 uintptr_t last_method;
127 // Bytes allocated for this LogBuffer
130 // Start of currently unused space in buffer
131 unsigned char* cursor;
133 // Pointer to start-of-structure-plus-size (for convenience)
134 unsigned char* buf_end;
136 // Start of data in buffer. Contents follow "buffer format" described above.
137 unsigned char buf [1];
141 MonoLinkedListSetNode node;
143 // Was this thread added to the LLS?
146 // The current log buffer for this thread.
149 // Methods referenced by events in `buffer`, see `MethodInfo`.
152 // Current call depth for enter/leave events.
155 // Indicates whether this thread is currently writing to its `buffer`.
158 // Has this thread written a thread end event to `buffer`?
161 // Stored in `buffer_lock_state` to take the exclusive lock.
163 } MonoProfilerThread;
165 // Do not use these TLS macros directly unless you know what you're doing.
169 #define PROF_TLS_SET(VAL) (TlsSetValue (profiler_tls, (VAL)))
170 #define PROF_TLS_GET() ((MonoProfilerThread *) TlsGetValue (profiler_tls))
171 #define PROF_TLS_INIT() (profiler_tls = TlsAlloc ())
172 #define PROF_TLS_FREE() (TlsFree (profiler_tls))
174 static DWORD profiler_tls;
178 #define PROF_TLS_SET(VAL) (profiler_tls = (VAL))
179 #define PROF_TLS_GET() (profiler_tls)
180 #define PROF_TLS_INIT()
181 #define PROF_TLS_FREE()
183 static __thread MonoProfilerThread *profiler_tls;
187 #define PROF_TLS_SET(VAL) (pthread_setspecific (profiler_tls, (VAL)))
188 #define PROF_TLS_GET() ((MonoProfilerThread *) pthread_getspecific (profiler_tls))
189 #define PROF_TLS_INIT() (pthread_key_create (&profiler_tls, NULL))
190 #define PROF_TLS_FREE() (pthread_key_delete (profiler_tls))
192 static pthread_key_t profiler_tls;
199 return (uintptr_t) mono_native_thread_id_get ();
206 return (uintptr_t) GetCurrentProcessId ();
208 return (uintptr_t) getpid ();
212 #define ENABLED(EVT) (log_config.effective_mask & (EVT))
215 * These macros should be used when writing an event to a log buffer. They
216 * take care of a bunch of stuff that can be repetitive and error-prone, such
217 * as attaching the current thread, acquiring/releasing the buffer lock,
218 * incrementing the event counter, expanding the log buffer, etc. They also
219 * create a scope so that it's harder to leak the LogBuffer pointer, which can
220 * be problematic as the pointer is unstable when the buffer lock isn't
223 * If the calling thread is already attached, these macros will not alter its
224 * attach mode (i.e. whether it's added to the LLS). If the thread is not
225 * attached, init_thread () will be called with add_to_lls = TRUE.
228 #define ENTER_LOG(COUNTER, BUFFER, SIZE) \
230 MonoProfilerThread *thread__ = get_thread (); \
231 if (thread__->attached) \
233 g_assert (!thread__->busy && "Why are we trying to write a new event while already writing one?"); \
234 thread__->busy = TRUE; \
235 InterlockedIncrement ((COUNTER)); \
236 LogBuffer *BUFFER = ensure_logbuf_unsafe (thread__, (SIZE))
238 #define EXIT_LOG_EXPLICIT(SEND) \
239 thread__->busy = FALSE; \
241 send_log_unsafe (TRUE); \
242 if (thread__->attached) \
246 // Pass these to EXIT_LOG_EXPLICIT () for easier reading.
248 #define NO_SEND FALSE
250 #define EXIT_LOG EXIT_LOG_EXPLICIT (DO_SEND)
252 typedef struct _BinaryObject BinaryObject;
253 struct _BinaryObject {
259 typedef struct MonoCounterAgent {
260 MonoCounter *counter;
261 // MonoCounterAgent specific data :
266 struct MonoCounterAgent *next;
269 typedef struct _PerfCounterAgent PerfCounterAgent;
270 struct _PerfCounterAgent {
271 PerfCounterAgent *next;
281 struct _MonoProfiler {
282 MonoProfilerHandle handle;
285 #if defined (HAVE_SYS_ZLIB)
290 uint64_t startup_time;
294 mach_timebase_info_data_t timebase_info;
295 #elif defined (HOST_WIN32)
296 LARGE_INTEGER pcounter_freq;
304 MonoLinkedListSet profiler_thread_list;
305 volatile gint32 buffer_lock_state;
306 volatile gint32 buffer_lock_exclusive_intent;
308 volatile gint32 runtime_inited;
309 volatile gint32 in_shutdown;
311 MonoNativeThreadId helper_thread;
313 MonoNativeThreadId writer_thread;
314 volatile gint32 run_writer_thread;
315 MonoLockFreeQueue writer_queue;
316 MonoSemType writer_queue_sem;
318 MonoLockFreeAllocSizeClass writer_entry_size_class;
319 MonoLockFreeAllocator writer_entry_allocator;
321 MonoConcurrentHashTable *method_table;
322 mono_mutex_t method_table_mutex;
324 MonoNativeThreadId dumper_thread;
325 volatile gint32 run_dumper_thread;
326 MonoLockFreeQueue dumper_queue;
327 MonoSemType dumper_queue_sem;
329 MonoLockFreeAllocSizeClass sample_size_class;
330 MonoLockFreeAllocator sample_allocator;
331 MonoLockFreeQueue sample_reuse_queue;
333 BinaryObject *binary_objects;
335 volatile gint32 heapshot_requested;
337 guint64 last_hs_time;
338 gboolean do_heap_walk;
340 mono_mutex_t counters_mutex;
341 MonoCounterAgent *counters;
342 PerfCounterAgent *perfcounters;
343 guint32 counters_index;
345 mono_mutex_t coverage_mutex;
346 GPtrArray *coverage_data;
348 GPtrArray *coverage_filters;
349 MonoConcurrentHashTable *coverage_filtered_classes;
350 MonoConcurrentHashTable *coverage_suppressed_assemblies;
352 MonoConcurrentHashTable *coverage_methods;
353 MonoConcurrentHashTable *coverage_assemblies;
354 MonoConcurrentHashTable *coverage_classes;
356 MonoConcurrentHashTable *coverage_image_to_methods;
358 guint32 coverage_previous_offset;
359 guint32 coverage_method_id;
362 static ProfilerConfig log_config;
363 static struct _MonoProfiler log_profiler;
366 MonoLockFreeQueueNode node;
371 #define WRITER_ENTRY_BLOCK_SIZE (mono_pagesize ())
379 #define TICKS_PER_SEC 1000000000LL
385 uint64_t time = mach_absolute_time ();
387 time *= log_profiler.timebase_info.numer;
388 time /= log_profiler.timebase_info.denom;
391 #elif defined (HOST_WIN32)
394 QueryPerformanceCounter (&value);
396 return value.QuadPart * TICKS_PER_SEC / log_profiler.pcounter_freq.QuadPart;
397 #elif defined (CLOCK_MONOTONIC)
398 struct timespec tspec;
400 clock_gettime (CLOCK_MONOTONIC, &tspec);
402 return ((uint64_t) tspec.tv_sec * TICKS_PER_SEC + tspec.tv_nsec);
406 gettimeofday (&tv, NULL);
408 return ((uint64_t) tv.tv_sec * TICKS_PER_SEC + tv.tv_usec * 1000);
416 mach_timebase_info (&log_profiler.timebase_info);
417 #elif defined (HOST_WIN32)
418 QueryPerformanceFrequency (&log_profiler.pcounter_freq);
421 uint64_t time_start = current_time ();
423 for (int i = 0; i < 256; ++i)
426 uint64_t time_end = current_time ();
428 log_profiler.timer_overhead = (time_end - time_start) / 256;
432 pstrdup (const char *s)
434 int len = strlen (s) + 1;
435 char *p = (char *) g_malloc (len);
440 #define BUFFER_SIZE (4096 * 16)
442 /* Worst-case size in bytes of a 64-bit value encoded with LEB128. */
443 #define LEB128_SIZE 10
445 /* Size of a value encoded as a single byte. */
446 #undef BYTE_SIZE // mach/i386/vm_param.h on OS X defines this to 8, but it isn't used for anything.
449 /* Size in bytes of the event prefix (ID + time). */
450 #define EVENT_SIZE (BYTE_SIZE + LEB128_SIZE)
453 alloc_buffer (int size)
455 return mono_valloc (NULL, size, MONO_MMAP_READ | MONO_MMAP_WRITE | MONO_MMAP_ANON | MONO_MMAP_PRIVATE, MONO_MEM_ACCOUNT_PROFILER);
459 free_buffer (void *buf, int size)
461 mono_vfree (buf, size, MONO_MEM_ACCOUNT_PROFILER);
465 create_buffer (uintptr_t tid, int bytes)
467 LogBuffer* buf = (LogBuffer *) alloc_buffer (MAX (BUFFER_SIZE, bytes));
469 InterlockedIncrement (&buffer_allocations_ctr);
471 buf->size = BUFFER_SIZE;
472 buf->time_base = current_time ();
473 buf->last_time = buf->time_base;
474 buf->buf_end = (unsigned char *) buf + buf->size;
475 buf->cursor = buf->buf;
476 buf->thread_id = tid;
482 * Must be called with the reader lock held if thread is the current thread, or
483 * the exclusive lock if thread is a different thread. However, if thread is
484 * the current thread, and init_thread () was called with add_to_lls = FALSE,
485 * then no locking is necessary.
488 init_buffer_state (MonoProfilerThread *thread)
490 thread->buffer = create_buffer (thread->node.key, 0);
491 thread->methods = NULL;
495 clear_hazard_pointers (MonoThreadHazardPointers *hp)
497 mono_hazard_pointer_clear (hp, 0);
498 mono_hazard_pointer_clear (hp, 1);
499 mono_hazard_pointer_clear (hp, 2);
502 static MonoProfilerThread *
503 init_thread (gboolean add_to_lls)
505 MonoProfilerThread *thread = PROF_TLS_GET ();
508 * Sometimes we may try to initialize a thread twice. One example is the
509 * main thread: We initialize it when setting up the profiler, but we will
510 * also get a thread_start () callback for it. Another example is when
511 * attaching new threads to the runtime: We may get a gc_alloc () callback
512 * for that thread's thread object (where we initialize it), soon followed
513 * by a thread_start () callback.
515 * These cases are harmless anyhow. Just return if we've already done the
516 * initialization work.
521 thread = g_malloc (sizeof (MonoProfilerThread));
522 thread->node.key = thread_id ();
523 thread->attached = add_to_lls;
524 thread->call_depth = 0;
526 thread->ended = FALSE;
528 init_buffer_state (thread);
530 thread->small_id = mono_thread_info_register_small_id ();
533 * Some internal profiler threads don't need to be cleaned up
534 * by the main thread on shutdown.
537 MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
538 g_assert (mono_lls_insert (&log_profiler.profiler_thread_list, hp, &thread->node) && "Why can't we insert the thread in the LLS?");
539 clear_hazard_pointers (hp);
542 PROF_TLS_SET (thread);
547 // Only valid if init_thread () was called with add_to_lls = FALSE.
549 deinit_thread (MonoProfilerThread *thread)
551 g_assert (!thread->attached && "Why are we manually freeing an attached thread?");
557 static MonoProfilerThread *
560 return init_thread (TRUE);
563 // Only valid if init_thread () was called with add_to_lls = FALSE.
565 ensure_logbuf_unsafe (MonoProfilerThread *thread, int bytes)
567 LogBuffer *old = thread->buffer;
569 if (old->cursor + bytes < old->buf_end)
572 LogBuffer *new_ = create_buffer (thread->node.key, bytes);
574 thread->buffer = new_;
580 * This is a reader/writer spin lock of sorts used to protect log buffers.
581 * When a thread modifies its own log buffer, it increments the reader
582 * count. When a thread wants to access log buffers of other threads, it
583 * takes the exclusive lock.
585 * `buffer_lock_state` holds the reader count in its lower 16 bits, and
586 * the small ID of the thread currently holding the exclusive (writer)
587 * lock in its upper 16 bits. Both can be zero. It's important that the
588 * whole lock state is a single word that can be read/written atomically
589 * to avoid race conditions where there could end up being readers while
590 * the writer lock is held.
592 * The lock is writer-biased. When a thread wants to take the exclusive
593 * lock, it increments `buffer_lock_exclusive_intent` which will make new
594 * readers spin until it's back to zero, then takes the exclusive lock
595 * once the reader count has reached zero. After releasing the exclusive
596 * lock, it decrements `buffer_lock_exclusive_intent`, which, when it
597 * reaches zero again, allows readers to increment the reader count.
599 * The writer bias is necessary because we take the exclusive lock in
600 * `gc_event ()` during STW. If the writer bias was not there, and a
601 * program had a large number of threads, STW-induced pauses could be
602 * significantly longer than they have to be. Also, we emit periodic
603 * sync points from the helper thread, which requires taking the
604 * exclusive lock, and we need those to arrive with a reasonably
605 * consistent frequency so that readers don't have to queue up too many
606 * events between sync points.
608 * The lock does not support recursion.
615 * If the thread holding the exclusive lock tries to modify the
616 * reader count, just make it a no-op. This way, we also avoid
617 * invoking the GC safe point macros below, which could break if
618 * done from a thread that is currently the initiator of STW.
620 * In other words, we rely on the fact that the GC thread takes
621 * the exclusive lock in the gc_event () callback when the world
624 if (InterlockedRead (&log_profiler.buffer_lock_state) != get_thread ()->small_id << 16) {
631 // Hold off if a thread wants to take the exclusive lock.
632 while (InterlockedRead (&log_profiler.buffer_lock_exclusive_intent))
633 mono_thread_info_yield ();
635 old = InterlockedRead (&log_profiler.buffer_lock_state);
637 // Is a thread holding the exclusive lock?
639 mono_thread_info_yield ();
644 } while (InterlockedCompareExchange (&log_profiler.buffer_lock_state, new_, old) != old);
649 mono_memory_barrier ();
655 mono_memory_barrier ();
657 gint32 state = InterlockedRead (&log_profiler.buffer_lock_state);
659 // See the comment in buffer_lock ().
660 if (state == PROF_TLS_GET ()->small_id << 16)
663 g_assert (state && "Why are we decrementing a zero reader count?");
664 g_assert (!(state >> 16) && "Why is the exclusive lock held?");
666 InterlockedDecrement (&log_profiler.buffer_lock_state);
670 buffer_lock_excl (void)
672 gint32 new_ = get_thread ()->small_id << 16;
674 g_assert (InterlockedRead (&log_profiler.buffer_lock_state) != new_ && "Why are we taking the exclusive lock twice?");
676 InterlockedIncrement (&log_profiler.buffer_lock_exclusive_intent);
680 while (InterlockedCompareExchange (&log_profiler.buffer_lock_state, new_, 0))
681 mono_thread_info_yield ();
685 mono_memory_barrier ();
689 buffer_unlock_excl (void)
691 mono_memory_barrier ();
693 gint32 state = InterlockedRead (&log_profiler.buffer_lock_state);
694 gint32 excl = state >> 16;
696 g_assert (excl && "Why is the exclusive lock not held?");
697 g_assert (excl == PROF_TLS_GET ()->small_id && "Why does another thread hold the exclusive lock?");
698 g_assert (!(state & 0xFFFF) && "Why are there readers when the exclusive lock is held?");
700 InterlockedWrite (&log_profiler.buffer_lock_state, 0);
701 InterlockedDecrement (&log_profiler.buffer_lock_exclusive_intent);
705 encode_uleb128 (uint64_t value, uint8_t *buf, uint8_t **endbuf)
710 uint8_t b = value & 0x7f;
713 if (value != 0) /* more bytes to come */
723 encode_sleb128 (intptr_t value, uint8_t *buf, uint8_t **endbuf)
726 int negative = (value < 0);
727 unsigned int size = sizeof (intptr_t) * 8;
735 /* the following is unnecessary if the
736 * implementation of >>= uses an arithmetic rather
737 * than logical shift for a signed left operand
741 value |= - ((intptr_t) 1 <<(size - 7));
743 /* sign bit of byte is second high order bit (0x40) */
744 if ((value == 0 && !(byte & 0x40)) ||
745 (value == -1 && (byte & 0x40)))
757 emit_byte (LogBuffer *logbuffer, int value)
759 logbuffer->cursor [0] = value;
762 g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
766 emit_value (LogBuffer *logbuffer, int value)
768 encode_uleb128 (value, logbuffer->cursor, &logbuffer->cursor);
770 g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
774 emit_time (LogBuffer *logbuffer, uint64_t value)
776 uint64_t tdiff = value - logbuffer->last_time;
777 encode_uleb128 (tdiff, logbuffer->cursor, &logbuffer->cursor);
778 logbuffer->last_time = value;
780 g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
784 emit_event_time (LogBuffer *logbuffer, int event, uint64_t time)
786 emit_byte (logbuffer, event);
787 emit_time (logbuffer, time);
791 emit_event (LogBuffer *logbuffer, int event)
793 emit_event_time (logbuffer, event, current_time ());
797 emit_svalue (LogBuffer *logbuffer, int64_t value)
799 encode_sleb128 (value, logbuffer->cursor, &logbuffer->cursor);
801 g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
805 emit_uvalue (LogBuffer *logbuffer, uint64_t value)
807 encode_uleb128 (value, logbuffer->cursor, &logbuffer->cursor);
809 g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
813 emit_ptr (LogBuffer *logbuffer, const void *ptr)
815 if (!logbuffer->ptr_base)
816 logbuffer->ptr_base = (uintptr_t) ptr;
818 emit_svalue (logbuffer, (intptr_t) ptr - logbuffer->ptr_base);
820 g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
824 emit_method_inner (LogBuffer *logbuffer, void *method)
826 if (!logbuffer->method_base) {
827 logbuffer->method_base = (intptr_t) method;
828 logbuffer->last_method = (intptr_t) method;
831 encode_sleb128 ((intptr_t) ((char *) method - (char *) logbuffer->last_method), logbuffer->cursor, &logbuffer->cursor);
832 logbuffer->last_method = (intptr_t) method;
834 g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
837 // The reader lock must be held.
839 register_method_local (MonoMethod *method, MonoJitInfo *ji)
841 MonoProfilerThread *thread = get_thread ();
843 if (!mono_conc_hashtable_lookup (log_profiler.method_table, method)) {
844 MethodInfo *info = (MethodInfo *) g_malloc (sizeof (MethodInfo));
846 info->method = method;
848 info->time = current_time ();
850 GPtrArray *arr = thread->methods ? thread->methods : (thread->methods = g_ptr_array_new ());
851 g_ptr_array_add (arr, info);
856 emit_method (LogBuffer *logbuffer, MonoMethod *method)
858 register_method_local (method, NULL);
859 emit_method_inner (logbuffer, method);
863 emit_obj (LogBuffer *logbuffer, void *ptr)
865 if (!logbuffer->obj_base)
866 logbuffer->obj_base = (uintptr_t) ptr >> 3;
868 emit_svalue (logbuffer, ((uintptr_t) ptr >> 3) - logbuffer->obj_base);
870 g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
874 emit_string (LogBuffer *logbuffer, const char *str, size_t size)
878 for (; i < size; i++) {
881 emit_byte (logbuffer, str [i]);
884 emit_byte (logbuffer, '\0');
888 emit_double (LogBuffer *logbuffer, double value)
891 unsigned char buffer[8];
892 memcpy (buffer, &value, 8);
893 #if G_BYTE_ORDER == G_BIG_ENDIAN
894 for (i = 7; i >= 0; i--)
896 for (i = 0; i < 8; i++)
898 emit_byte (logbuffer, buffer[i]);
902 write_int16 (char *buf, int32_t value)
905 for (i = 0; i < 2; ++i) {
913 write_int32 (char *buf, int32_t value)
916 for (i = 0; i < 4; ++i) {
924 write_int64 (char *buf, int64_t value)
927 for (i = 0; i < 8; ++i) {
935 write_header_string (char *p, const char *str)
937 size_t len = strlen (str) + 1;
939 p = write_int32 (p, len);
948 const char *args = log_profiler.args;
949 const char *arch = mono_config_get_cpu ();
950 const char *os = mono_config_get_os ();
952 char *hbuf = g_malloc (
953 sizeof (gint32) /* header id */ +
954 sizeof (gint8) /* major version */ +
955 sizeof (gint8) /* minor version */ +
956 sizeof (gint8) /* data version */ +
957 sizeof (gint8) /* word size */ +
958 sizeof (gint64) /* startup time */ +
959 sizeof (gint32) /* timer overhead */ +
960 sizeof (gint32) /* flags */ +
961 sizeof (gint32) /* process id */ +
962 sizeof (gint16) /* command port */ +
963 sizeof (gint32) + strlen (args) + 1 /* arguments */ +
964 sizeof (gint32) + strlen (arch) + 1 /* architecture */ +
965 sizeof (gint32) + strlen (os) + 1 /* operating system */
969 p = write_int32 (p, LOG_HEADER_ID);
970 *p++ = LOG_VERSION_MAJOR;
971 *p++ = LOG_VERSION_MINOR;
972 *p++ = LOG_DATA_VERSION;
973 *p++ = sizeof (void *);
974 p = write_int64 (p, ((uint64_t) time (NULL)) * 1000);
975 p = write_int32 (p, log_profiler.timer_overhead);
976 p = write_int32 (p, 0); /* flags */
977 p = write_int32 (p, process_id ());
978 p = write_int16 (p, log_profiler.command_port);
979 p = write_header_string (p, args);
980 p = write_header_string (p, arch);
981 p = write_header_string (p, os);
983 #if defined (HAVE_SYS_ZLIB)
984 if (log_profiler.gzfile) {
985 gzwrite (log_profiler.gzfile, hbuf, p - hbuf);
989 fwrite (hbuf, p - hbuf, 1, log_profiler.file);
990 fflush (log_profiler.file);
997 * Must be called with the reader lock held if thread is the current thread, or
998 * the exclusive lock if thread is a different thread. However, if thread is
999 * the current thread, and init_thread () was called with add_to_lls = FALSE,
1000 * then no locking is necessary.
1003 send_buffer (MonoProfilerThread *thread)
1005 WriterQueueEntry *entry = mono_lock_free_alloc (&log_profiler.writer_entry_allocator);
1006 entry->methods = thread->methods;
1007 entry->buffer = thread->buffer;
1009 mono_lock_free_queue_node_init (&entry->node, FALSE);
1011 mono_lock_free_queue_enqueue (&log_profiler.writer_queue, &entry->node);
1012 mono_os_sem_post (&log_profiler.writer_queue_sem);
1016 free_thread (gpointer p)
1018 MonoProfilerThread *thread = p;
1020 if (!thread->ended) {
1022 * The thread is being cleaned up by the main thread during
1023 * shutdown. This typically happens for internal runtime
1024 * threads. We need to synthesize a thread end event.
1027 InterlockedIncrement (&thread_ends_ctr);
1029 LogBuffer *buf = ensure_logbuf_unsafe (thread,
1030 EVENT_SIZE /* event */ +
1031 BYTE_SIZE /* type */ +
1032 LEB128_SIZE /* tid */
1035 emit_event (buf, TYPE_END_UNLOAD | TYPE_METADATA);
1036 emit_byte (buf, TYPE_THREAD);
1037 emit_ptr (buf, (void *) thread->node.key);
1040 send_buffer (thread);
1046 remove_thread (MonoProfilerThread *thread)
1048 MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
1050 if (mono_lls_remove (&log_profiler.profiler_thread_list, hp, &thread->node))
1051 mono_thread_hazardous_try_free (thread, free_thread);
1053 clear_hazard_pointers (hp);
1057 dump_buffer (LogBuffer *buf)
1063 dump_buffer (buf->next);
1065 if (buf->cursor - buf->buf) {
1066 p = write_int32 (p, BUF_ID);
1067 p = write_int32 (p, buf->cursor - buf->buf);
1068 p = write_int64 (p, buf->time_base);
1069 p = write_int64 (p, buf->ptr_base);
1070 p = write_int64 (p, buf->obj_base);
1071 p = write_int64 (p, buf->thread_id);
1072 p = write_int64 (p, buf->method_base);
1074 #if defined (HAVE_SYS_ZLIB)
1075 if (log_profiler.gzfile) {
1076 gzwrite (log_profiler.gzfile, hbuf, p - hbuf);
1077 gzwrite (log_profiler.gzfile, buf->buf, buf->cursor - buf->buf);
1081 fwrite (hbuf, p - hbuf, 1, log_profiler.file);
1082 fwrite (buf->buf, buf->cursor - buf->buf, 1, log_profiler.file);
1083 fflush (log_profiler.file);
1087 free_buffer (buf, buf->size);
1091 dump_buffer_threadless (LogBuffer *buf)
1093 for (LogBuffer *iter = buf; iter; iter = iter->next)
1094 iter->thread_id = 0;
1099 // Only valid if init_thread () was called with add_to_lls = FALSE.
1101 send_log_unsafe (gboolean if_needed)
1103 MonoProfilerThread *thread = PROF_TLS_GET ();
1105 if (!if_needed || (if_needed && thread->buffer->next)) {
1106 if (!thread->attached)
1107 for (LogBuffer *iter = thread->buffer; iter; iter = iter->next)
1108 iter->thread_id = 0;
1110 send_buffer (thread);
1111 init_buffer_state (thread);
1115 // Assumes that the exclusive lock is held.
1117 sync_point_flush (void)
1119 g_assert (InterlockedRead (&log_profiler.buffer_lock_state) == PROF_TLS_GET ()->small_id << 16 && "Why don't we hold the exclusive lock?");
1121 MONO_LLS_FOREACH_SAFE (&log_profiler.profiler_thread_list, MonoProfilerThread, thread) {
1122 g_assert (thread->attached && "Why is a thread in the LLS not attached?");
1124 send_buffer (thread);
1125 init_buffer_state (thread);
1126 } MONO_LLS_FOREACH_SAFE_END
1129 // Assumes that the exclusive lock is held.
1131 sync_point_mark (MonoProfilerSyncPointType type)
1133 g_assert (InterlockedRead (&log_profiler.buffer_lock_state) == PROF_TLS_GET ()->small_id << 16 && "Why don't we hold the exclusive lock?");
1135 ENTER_LOG (&sync_points_ctr, logbuffer,
1136 EVENT_SIZE /* event */ +
1137 LEB128_SIZE /* type */
1140 emit_event (logbuffer, TYPE_META | TYPE_SYNC_POINT);
1141 emit_byte (logbuffer, type);
1143 EXIT_LOG_EXPLICIT (NO_SEND);
1145 send_log_unsafe (FALSE);
1148 // Assumes that the exclusive lock is held.
1150 sync_point (MonoProfilerSyncPointType type)
1152 sync_point_flush ();
1153 sync_point_mark (type);
1157 gc_reference (MonoObject *obj, MonoClass *klass, uintptr_t size, uintptr_t num, MonoObject **refs, uintptr_t *offsets, void *data)
1159 /* account for object alignment in the heap */
1163 ENTER_LOG (&heap_objects_ctr, logbuffer,
1164 EVENT_SIZE /* event */ +
1165 LEB128_SIZE /* obj */ +
1166 LEB128_SIZE /* klass */ +
1167 LEB128_SIZE /* size */ +
1168 LEB128_SIZE /* num */ +
1170 LEB128_SIZE /* offset */ +
1171 LEB128_SIZE /* ref */
1175 emit_event (logbuffer, TYPE_HEAP_OBJECT | TYPE_HEAP);
1176 emit_obj (logbuffer, obj);
1177 emit_ptr (logbuffer, klass);
1178 emit_value (logbuffer, size);
1179 emit_value (logbuffer, num);
1181 uintptr_t last_offset = 0;
1183 for (int i = 0; i < num; ++i) {
1184 emit_value (logbuffer, offsets [i] - last_offset);
1185 last_offset = offsets [i];
1186 emit_obj (logbuffer, refs [i]);
1195 gc_roots (MonoProfiler *prof, MonoObject *const *objects, const MonoProfilerGCRootType *root_types, const uintptr_t *extra_info, uint64_t num)
1197 ENTER_LOG (&heap_roots_ctr, logbuffer,
1198 EVENT_SIZE /* event */ +
1199 LEB128_SIZE /* num */ +
1200 LEB128_SIZE /* collections */ +
1202 LEB128_SIZE /* object */ +
1203 LEB128_SIZE /* root type */ +
1204 LEB128_SIZE /* extra info */
1208 emit_event (logbuffer, TYPE_HEAP_ROOT | TYPE_HEAP);
1209 emit_value (logbuffer, num);
1210 emit_value (logbuffer, mono_gc_collection_count (mono_gc_max_generation ()));
1212 for (int i = 0; i < num; ++i) {
1213 emit_obj (logbuffer, objects [i]);
1214 emit_byte (logbuffer, root_types [i]);
1215 emit_value (logbuffer, extra_info [i]);
1223 trigger_on_demand_heapshot (void)
1225 if (InterlockedRead (&log_profiler.heapshot_requested))
1226 mono_gc_collect (mono_gc_max_generation ());
1229 #define ALL_GC_EVENTS_MASK (PROFLOG_GC_EVENTS | PROFLOG_GC_MOVE_EVENTS | PROFLOG_GC_ROOT_EVENTS)
1232 gc_event (MonoProfiler *profiler, MonoProfilerGCEvent ev, uint32_t generation)
1234 if (ENABLED (PROFLOG_GC_EVENTS)) {
1235 ENTER_LOG (&gc_events_ctr, logbuffer,
1236 EVENT_SIZE /* event */ +
1237 BYTE_SIZE /* gc event */ +
1238 BYTE_SIZE /* generation */
1241 emit_event (logbuffer, TYPE_GC_EVENT | TYPE_GC);
1242 emit_byte (logbuffer, ev);
1243 emit_byte (logbuffer, generation);
1249 case MONO_GC_EVENT_START:
1250 if (generation == mono_gc_max_generation ())
1251 log_profiler.gc_count++;
1253 switch (log_config.hs_mode) {
1254 case MONO_PROFILER_HEAPSHOT_NONE:
1255 log_profiler.do_heap_walk = FALSE;
1257 case MONO_PROFILER_HEAPSHOT_MAJOR:
1258 log_profiler.do_heap_walk = generation == mono_gc_max_generation ();
1260 case MONO_PROFILER_HEAPSHOT_ON_DEMAND:
1261 log_profiler.do_heap_walk = InterlockedRead (&log_profiler.heapshot_requested);
1263 case MONO_PROFILER_HEAPSHOT_X_GC:
1264 log_profiler.do_heap_walk = !(log_profiler.gc_count % log_config.hs_freq_gc);
1266 case MONO_PROFILER_HEAPSHOT_X_MS:
1267 log_profiler.do_heap_walk = (current_time () - log_profiler.last_hs_time) / 1000 * 1000 >= log_config.hs_freq_ms;
1270 g_assert_not_reached ();
1273 if (ENABLED (PROFLOG_GC_ROOT_EVENTS) && log_profiler.do_heap_walk)
1274 mono_profiler_set_gc_roots_callback (log_profiler.handle, gc_roots);
1277 case MONO_GC_EVENT_PRE_STOP_WORLD_LOCKED:
1279 * Ensure that no thread can be in the middle of writing to
1280 * a buffer when the world stops...
1282 buffer_lock_excl ();
1284 case MONO_GC_EVENT_POST_STOP_WORLD:
1286 * ... So that we now have a consistent view of all buffers.
1287 * This allows us to flush them. We need to do this because
1288 * they may contain object allocation events that need to be
1289 * committed to the log file before any object move events
1290 * that will be produced during this GC.
1292 if (ENABLED (ALL_GC_EVENTS_MASK))
1293 sync_point (SYNC_POINT_WORLD_STOP);
1295 // Surround heapshots with HEAP_START/HEAP_END events.
1296 if (log_profiler.do_heap_walk) {
1297 ENTER_LOG (&heap_starts_ctr, logbuffer,
1298 EVENT_SIZE /* event */
1301 emit_event (logbuffer, TYPE_HEAP_START | TYPE_HEAP);
1307 case MONO_GC_EVENT_PRE_START_WORLD:
1308 mono_profiler_set_gc_roots_callback (log_profiler.handle, NULL);
1310 if (log_profiler.do_heap_walk) {
1311 mono_gc_walk_heap (0, gc_reference, NULL);
1313 ENTER_LOG (&heap_ends_ctr, logbuffer,
1314 EVENT_SIZE /* event */
1317 emit_event (logbuffer, TYPE_HEAP_END | TYPE_HEAP);
1321 log_profiler.do_heap_walk = FALSE;
1322 log_profiler.last_hs_time = current_time ();
1324 InterlockedWrite (&log_profiler.heapshot_requested, 0);
1328 * Similarly, we must now make sure that any object moves
1329 * written to the GC thread's buffer are flushed. Otherwise,
1330 * object allocation events for certain addresses could come
1331 * after the move events that made those addresses available.
1333 if (ENABLED (ALL_GC_EVENTS_MASK))
1334 sync_point_mark (SYNC_POINT_WORLD_START);
1336 case MONO_GC_EVENT_POST_START_WORLD_UNLOCKED:
1338 * Finally, it is safe to allow other threads to write to
1339 * their buffers again.
1341 buffer_unlock_excl ();
1349 gc_resize (MonoProfiler *profiler, uintptr_t new_size)
1351 ENTER_LOG (&gc_resizes_ctr, logbuffer,
1352 EVENT_SIZE /* event */ +
1353 LEB128_SIZE /* new size */
1356 emit_event (logbuffer, TYPE_GC_RESIZE | TYPE_GC);
1357 emit_value (logbuffer, new_size);
1364 MonoMethod* methods [MAX_FRAMES];
1365 int32_t il_offsets [MAX_FRAMES];
1366 int32_t native_offsets [MAX_FRAMES];
1370 walk_stack (MonoMethod *method, int32_t native_offset, int32_t il_offset, mono_bool managed, void* data)
1372 FrameData *frame = (FrameData *)data;
1373 if (method && frame->count < log_config.num_frames) {
1374 frame->il_offsets [frame->count] = il_offset;
1375 frame->native_offsets [frame->count] = native_offset;
1376 frame->methods [frame->count++] = method;
1378 return frame->count == log_config.num_frames;
1382 * a note about stack walks: they can cause more profiler events to fire,
1383 * so we need to make sure they don't happen after we started emitting an
1384 * event, hence the collect_bt/emit_bt split.
1387 collect_bt (FrameData *data)
1390 mono_stack_walk_no_il (walk_stack, data);
1394 emit_bt (LogBuffer *logbuffer, FrameData *data)
1396 emit_value (logbuffer, data->count);
1399 emit_method (logbuffer, data->methods [--data->count]);
1403 gc_alloc (MonoProfiler *prof, MonoObject *obj)
1405 int do_bt = (!log_config.enter_leave && InterlockedRead (&log_profiler.runtime_inited) && log_config.num_frames) ? TYPE_ALLOC_BT : 0;
1407 uintptr_t len = mono_object_get_size (obj);
1408 /* account for object alignment in the heap */
1415 ENTER_LOG (&gc_allocs_ctr, logbuffer,
1416 EVENT_SIZE /* event */ +
1417 LEB128_SIZE /* klass */ +
1418 LEB128_SIZE /* obj */ +
1419 LEB128_SIZE /* size */ +
1421 LEB128_SIZE /* count */ +
1423 LEB128_SIZE /* method */
1428 emit_event (logbuffer, do_bt | TYPE_ALLOC);
1429 emit_ptr (logbuffer, mono_object_get_class (obj));
1430 emit_obj (logbuffer, obj);
1431 emit_value (logbuffer, len);
1434 emit_bt (logbuffer, &data);
1440 gc_moves (MonoProfiler *prof, MonoObject *const *objects, uint64_t num)
1442 ENTER_LOG (&gc_moves_ctr, logbuffer,
1443 EVENT_SIZE /* event */ +
1444 LEB128_SIZE /* num */ +
1446 LEB128_SIZE /* object */
1450 emit_event (logbuffer, TYPE_GC_MOVE | TYPE_GC);
1451 emit_value (logbuffer, num);
1453 for (int i = 0; i < num; ++i)
1454 emit_obj (logbuffer, objects [i]);
1460 gc_handle (MonoProfiler *prof, int op, MonoGCHandleType type, uint32_t handle, MonoObject *obj)
1462 int do_bt = !log_config.enter_leave && InterlockedRead (&log_profiler.runtime_inited) && log_config.num_frames;
1468 gint32 *ctr = op == MONO_PROFILER_GC_HANDLE_CREATED ? &gc_handle_creations_ctr : &gc_handle_deletions_ctr;
1470 ENTER_LOG (ctr, logbuffer,
1471 EVENT_SIZE /* event */ +
1472 LEB128_SIZE /* type */ +
1473 LEB128_SIZE /* handle */ +
1474 (op == MONO_PROFILER_GC_HANDLE_CREATED ? (
1475 LEB128_SIZE /* obj */
1478 LEB128_SIZE /* count */ +
1480 LEB128_SIZE /* method */
1485 if (op == MONO_PROFILER_GC_HANDLE_CREATED)
1486 emit_event (logbuffer, (do_bt ? TYPE_GC_HANDLE_CREATED_BT : TYPE_GC_HANDLE_CREATED) | TYPE_GC);
1487 else if (op == MONO_PROFILER_GC_HANDLE_DESTROYED)
1488 emit_event (logbuffer, (do_bt ? TYPE_GC_HANDLE_DESTROYED_BT : TYPE_GC_HANDLE_DESTROYED) | TYPE_GC);
1490 g_assert_not_reached ();
1492 emit_value (logbuffer, type);
1493 emit_value (logbuffer, handle);
1495 if (op == MONO_PROFILER_GC_HANDLE_CREATED)
1496 emit_obj (logbuffer, obj);
1499 emit_bt (logbuffer, &data);
1505 gc_handle_created (MonoProfiler *prof, uint32_t handle, MonoGCHandleType type, MonoObject *obj)
1507 gc_handle (prof, MONO_PROFILER_GC_HANDLE_CREATED, type, handle, obj);
1511 gc_handle_deleted (MonoProfiler *prof, uint32_t handle, MonoGCHandleType type)
1513 gc_handle (prof, MONO_PROFILER_GC_HANDLE_DESTROYED, type, handle, NULL);
1517 finalize_begin (MonoProfiler *prof)
1519 ENTER_LOG (&finalize_begins_ctr, buf,
1520 EVENT_SIZE /* event */
1523 emit_event (buf, TYPE_GC_FINALIZE_START | TYPE_GC);
1529 finalize_end (MonoProfiler *prof)
1531 trigger_on_demand_heapshot ();
1532 if (ENABLED (PROFLOG_FINALIZATION_EVENTS)) {
1533 ENTER_LOG (&finalize_ends_ctr, buf,
1534 EVENT_SIZE /* event */
1537 emit_event (buf, TYPE_GC_FINALIZE_END | TYPE_GC);
1544 finalize_object_begin (MonoProfiler *prof, MonoObject *obj)
1546 ENTER_LOG (&finalize_object_begins_ctr, buf,
1547 EVENT_SIZE /* event */ +
1548 LEB128_SIZE /* obj */
1551 emit_event (buf, TYPE_GC_FINALIZE_OBJECT_START | TYPE_GC);
1552 emit_obj (buf, obj);
1558 finalize_object_end (MonoProfiler *prof, MonoObject *obj)
1560 ENTER_LOG (&finalize_object_ends_ctr, buf,
1561 EVENT_SIZE /* event */ +
1562 LEB128_SIZE /* obj */
1565 emit_event (buf, TYPE_GC_FINALIZE_OBJECT_END | TYPE_GC);
1566 emit_obj (buf, obj);
1572 push_nesting (char *p, MonoClass *klass)
1577 nesting = mono_class_get_nesting_type (klass);
1579 p = push_nesting (p, nesting);
1583 name = mono_class_get_name (klass);
1584 nspace = mono_class_get_namespace (klass);
1587 p += strlen (nspace);
1597 type_name (MonoClass *klass)
1601 push_nesting (buf, klass);
1602 p = (char *) g_malloc (strlen (buf) + 1);
1608 image_loaded (MonoProfiler *prof, MonoImage *image)
1610 const char *name = mono_image_get_filename (image);
1611 int nlen = strlen (name) + 1;
1613 ENTER_LOG (&image_loads_ctr, logbuffer,
1614 EVENT_SIZE /* event */ +
1615 BYTE_SIZE /* type */ +
1616 LEB128_SIZE /* image */ +
1620 emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1621 emit_byte (logbuffer, TYPE_IMAGE);
1622 emit_ptr (logbuffer, image);
1623 memcpy (logbuffer->cursor, name, nlen);
1624 logbuffer->cursor += nlen;
1630 image_unloaded (MonoProfiler *prof, MonoImage *image)
1632 const char *name = mono_image_get_filename (image);
1633 int nlen = strlen (name) + 1;
1635 ENTER_LOG (&image_unloads_ctr, logbuffer,
1636 EVENT_SIZE /* event */ +
1637 BYTE_SIZE /* type */ +
1638 LEB128_SIZE /* image */ +
1642 emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1643 emit_byte (logbuffer, TYPE_IMAGE);
1644 emit_ptr (logbuffer, image);
1645 memcpy (logbuffer->cursor, name, nlen);
1646 logbuffer->cursor += nlen;
1652 assembly_loaded (MonoProfiler *prof, MonoAssembly *assembly)
1654 char *name = mono_stringify_assembly_name (mono_assembly_get_name (assembly));
1655 int nlen = strlen (name) + 1;
1656 MonoImage *image = mono_assembly_get_image (assembly);
1658 ENTER_LOG (&assembly_loads_ctr, logbuffer,
1659 EVENT_SIZE /* event */ +
1660 BYTE_SIZE /* type */ +
1661 LEB128_SIZE /* assembly */ +
1662 LEB128_SIZE /* image */ +
1666 emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1667 emit_byte (logbuffer, TYPE_ASSEMBLY);
1668 emit_ptr (logbuffer, assembly);
1669 emit_ptr (logbuffer, image);
1670 memcpy (logbuffer->cursor, name, nlen);
1671 logbuffer->cursor += nlen;
1679 assembly_unloaded (MonoProfiler *prof, MonoAssembly *assembly)
1681 char *name = mono_stringify_assembly_name (mono_assembly_get_name (assembly));
1682 int nlen = strlen (name) + 1;
1683 MonoImage *image = mono_assembly_get_image (assembly);
1685 ENTER_LOG (&assembly_unloads_ctr, logbuffer,
1686 EVENT_SIZE /* event */ +
1687 BYTE_SIZE /* type */ +
1688 LEB128_SIZE /* assembly */ +
1689 LEB128_SIZE /* image */ +
1693 emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1694 emit_byte (logbuffer, TYPE_ASSEMBLY);
1695 emit_ptr (logbuffer, assembly);
1696 emit_ptr (logbuffer, image);
1697 memcpy (logbuffer->cursor, name, nlen);
1698 logbuffer->cursor += nlen;
1706 class_loaded (MonoProfiler *prof, MonoClass *klass)
1710 if (InterlockedRead (&log_profiler.runtime_inited))
1711 name = mono_type_get_name (mono_class_get_type (klass));
1713 name = type_name (klass);
1715 int nlen = strlen (name) + 1;
1716 MonoImage *image = mono_class_get_image (klass);
1718 ENTER_LOG (&class_loads_ctr, logbuffer,
1719 EVENT_SIZE /* event */ +
1720 BYTE_SIZE /* type */ +
1721 LEB128_SIZE /* klass */ +
1722 LEB128_SIZE /* image */ +
1726 emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1727 emit_byte (logbuffer, TYPE_CLASS);
1728 emit_ptr (logbuffer, klass);
1729 emit_ptr (logbuffer, image);
1730 memcpy (logbuffer->cursor, name, nlen);
1731 logbuffer->cursor += nlen;
1735 if (InterlockedRead (&log_profiler.runtime_inited))
1742 method_enter (MonoProfiler *prof, MonoMethod *method)
1744 if (get_thread ()->call_depth++ <= log_config.max_call_depth) {
1745 ENTER_LOG (&method_entries_ctr, logbuffer,
1746 EVENT_SIZE /* event */ +
1747 LEB128_SIZE /* method */
1750 emit_event (logbuffer, TYPE_ENTER | TYPE_METHOD);
1751 emit_method (logbuffer, method);
1758 method_leave (MonoProfiler *prof, MonoMethod *method)
1760 if (--get_thread ()->call_depth <= log_config.max_call_depth) {
1761 ENTER_LOG (&method_exits_ctr, logbuffer,
1762 EVENT_SIZE /* event */ +
1763 LEB128_SIZE /* method */
1766 emit_event (logbuffer, TYPE_LEAVE | TYPE_METHOD);
1767 emit_method (logbuffer, method);
1774 method_exc_leave (MonoProfiler *prof, MonoMethod *method, MonoObject *exc)
1776 if (--get_thread ()->call_depth <= log_config.max_call_depth) {
1777 ENTER_LOG (&method_exception_exits_ctr, logbuffer,
1778 EVENT_SIZE /* event */ +
1779 LEB128_SIZE /* method */
1782 emit_event (logbuffer, TYPE_EXC_LEAVE | TYPE_METHOD);
1783 emit_method (logbuffer, method);
1789 static MonoProfilerCallInstrumentationFlags
1790 method_filter (MonoProfiler *prof, MonoMethod *method)
1792 return MONO_PROFILER_CALL_INSTRUMENTATION_PROLOGUE | MONO_PROFILER_CALL_INSTRUMENTATION_EPILOGUE;
1796 method_jitted (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *ji)
1800 register_method_local (method, ji);
1806 code_buffer_new (MonoProfiler *prof, const mono_byte *buffer, uint64_t size, MonoProfilerCodeBufferType type, const void *data)
1811 if (type == MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE) {
1812 name = (const char *) data;
1813 nlen = strlen (name) + 1;
1819 ENTER_LOG (&code_buffers_ctr, logbuffer,
1820 EVENT_SIZE /* event */ +
1821 BYTE_SIZE /* type */ +
1822 LEB128_SIZE /* buffer */ +
1823 LEB128_SIZE /* size */ +
1829 emit_event (logbuffer, TYPE_JITHELPER | TYPE_RUNTIME);
1830 emit_byte (logbuffer, type);
1831 emit_ptr (logbuffer, buffer);
1832 emit_value (logbuffer, size);
1835 memcpy (logbuffer->cursor, name, nlen);
1836 logbuffer->cursor += nlen;
1843 throw_exc (MonoProfiler *prof, MonoObject *object)
1845 int do_bt = (!log_config.enter_leave && InterlockedRead (&log_profiler.runtime_inited) && log_config.num_frames) ? TYPE_THROW_BT : 0;
1851 ENTER_LOG (&exception_throws_ctr, logbuffer,
1852 EVENT_SIZE /* event */ +
1853 LEB128_SIZE /* object */ +
1855 LEB128_SIZE /* count */ +
1857 LEB128_SIZE /* method */
1862 emit_event (logbuffer, do_bt | TYPE_EXCEPTION);
1863 emit_obj (logbuffer, object);
1866 emit_bt (logbuffer, &data);
1872 clause_exc (MonoProfiler *prof, MonoMethod *method, uint32_t clause_num, MonoExceptionEnum clause_type, MonoObject *exc)
1874 ENTER_LOG (&exception_clauses_ctr, logbuffer,
1875 EVENT_SIZE /* event */ +
1876 BYTE_SIZE /* clause type */ +
1877 LEB128_SIZE /* clause num */ +
1878 LEB128_SIZE /* method */
1881 emit_event (logbuffer, TYPE_EXCEPTION | TYPE_CLAUSE);
1882 emit_byte (logbuffer, clause_type);
1883 emit_value (logbuffer, clause_num);
1884 emit_method (logbuffer, method);
1885 emit_obj (logbuffer, exc);
1891 monitor_event (MonoProfiler *profiler, MonoObject *object, MonoProfilerMonitorEvent ev)
1893 int do_bt = (!log_config.enter_leave && InterlockedRead (&log_profiler.runtime_inited) && log_config.num_frames) ? TYPE_MONITOR_BT : 0;
1899 ENTER_LOG (&monitor_events_ctr, logbuffer,
1900 EVENT_SIZE /* event */ +
1901 BYTE_SIZE /* ev */ +
1902 LEB128_SIZE /* object */ +
1904 LEB128_SIZE /* count */ +
1906 LEB128_SIZE /* method */
1911 emit_event (logbuffer, do_bt | TYPE_MONITOR);
1912 emit_byte (logbuffer, ev);
1913 emit_obj (logbuffer, object);
1916 emit_bt (logbuffer, &data);
1922 monitor_contention (MonoProfiler *prof, MonoObject *object)
1924 monitor_event (prof, object, MONO_PROFILER_MONITOR_CONTENTION);
1928 monitor_acquired (MonoProfiler *prof, MonoObject *object)
1930 monitor_event (prof, object, MONO_PROFILER_MONITOR_DONE);
1934 monitor_failed (MonoProfiler *prof, MonoObject *object)
1936 monitor_event (prof, object, MONO_PROFILER_MONITOR_FAIL);
1940 thread_start (MonoProfiler *prof, uintptr_t tid)
1942 ENTER_LOG (&thread_starts_ctr, logbuffer,
1943 EVENT_SIZE /* event */ +
1944 BYTE_SIZE /* type */ +
1945 LEB128_SIZE /* tid */
1948 emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1949 emit_byte (logbuffer, TYPE_THREAD);
1950 emit_ptr (logbuffer, (void*) tid);
1956 thread_end (MonoProfiler *prof, uintptr_t tid)
1958 ENTER_LOG (&thread_ends_ctr, logbuffer,
1959 EVENT_SIZE /* event */ +
1960 BYTE_SIZE /* type */ +
1961 LEB128_SIZE /* tid */
1964 emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1965 emit_byte (logbuffer, TYPE_THREAD);
1966 emit_ptr (logbuffer, (void*) tid);
1968 EXIT_LOG_EXPLICIT (NO_SEND);
1970 MonoProfilerThread *thread = get_thread ();
1972 thread->ended = TRUE;
1973 remove_thread (thread);
1975 PROF_TLS_SET (NULL);
1979 thread_name (MonoProfiler *prof, uintptr_t tid, const char *name)
1981 int len = strlen (name) + 1;
1983 ENTER_LOG (&thread_names_ctr, logbuffer,
1984 EVENT_SIZE /* event */ +
1985 BYTE_SIZE /* type */ +
1986 LEB128_SIZE /* tid */ +
1990 emit_event (logbuffer, TYPE_METADATA);
1991 emit_byte (logbuffer, TYPE_THREAD);
1992 emit_ptr (logbuffer, (void*)tid);
1993 memcpy (logbuffer->cursor, name, len);
1994 logbuffer->cursor += len;
2000 domain_loaded (MonoProfiler *prof, MonoDomain *domain)
2002 ENTER_LOG (&domain_loads_ctr, logbuffer,
2003 EVENT_SIZE /* event */ +
2004 BYTE_SIZE /* type */ +
2005 LEB128_SIZE /* domain id */
2008 emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
2009 emit_byte (logbuffer, TYPE_DOMAIN);
2010 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
2016 domain_unloaded (MonoProfiler *prof, MonoDomain *domain)
2018 ENTER_LOG (&domain_unloads_ctr, logbuffer,
2019 EVENT_SIZE /* event */ +
2020 BYTE_SIZE /* type */ +
2021 LEB128_SIZE /* domain id */
2024 emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
2025 emit_byte (logbuffer, TYPE_DOMAIN);
2026 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
2032 domain_name (MonoProfiler *prof, MonoDomain *domain, const char *name)
2034 int nlen = strlen (name) + 1;
2036 ENTER_LOG (&domain_names_ctr, logbuffer,
2037 EVENT_SIZE /* event */ +
2038 BYTE_SIZE /* type */ +
2039 LEB128_SIZE /* domain id */ +
2043 emit_event (logbuffer, TYPE_METADATA);
2044 emit_byte (logbuffer, TYPE_DOMAIN);
2045 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
2046 memcpy (logbuffer->cursor, name, nlen);
2047 logbuffer->cursor += nlen;
2053 context_loaded (MonoProfiler *prof, MonoAppContext *context)
2055 ENTER_LOG (&context_loads_ctr, logbuffer,
2056 EVENT_SIZE /* event */ +
2057 BYTE_SIZE /* type */ +
2058 LEB128_SIZE /* context id */ +
2059 LEB128_SIZE /* domain id */
2062 emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
2063 emit_byte (logbuffer, TYPE_CONTEXT);
2064 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_id (context));
2065 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_domain_id (context));
2071 context_unloaded (MonoProfiler *prof, MonoAppContext *context)
2073 ENTER_LOG (&context_unloads_ctr, logbuffer,
2074 EVENT_SIZE /* event */ +
2075 BYTE_SIZE /* type */ +
2076 LEB128_SIZE /* context id */ +
2077 LEB128_SIZE /* domain id */
2080 emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
2081 emit_byte (logbuffer, TYPE_CONTEXT);
2082 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_id (context));
2083 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_domain_id (context));
2096 MonoLockFreeQueueNode node;
2101 AsyncFrameInfo frames [MONO_ZERO_LEN_ARRAY];
2105 async_walk_stack (MonoMethod *method, MonoDomain *domain, void *base_address, int offset, void *data)
2107 SampleHit *sample = (SampleHit *) data;
2109 if (sample->count < log_config.num_frames) {
2110 int i = sample->count;
2112 sample->frames [i].method = method;
2113 sample->frames [i].domain = domain;
2114 sample->frames [i].base_address = base_address;
2115 sample->frames [i].offset = offset;
2120 return sample->count == log_config.num_frames;
2123 #define SAMPLE_SLOT_SIZE(FRAMES) (sizeof (SampleHit) + sizeof (AsyncFrameInfo) * (FRAMES - MONO_ZERO_LEN_ARRAY))
2124 #define SAMPLE_BLOCK_SIZE (mono_pagesize ())
2127 enqueue_sample_hit (gpointer p)
2129 SampleHit *sample = p;
2131 mono_lock_free_queue_node_unpoison (&sample->node);
2132 mono_lock_free_queue_enqueue (&log_profiler.dumper_queue, &sample->node);
2133 mono_os_sem_post (&log_profiler.dumper_queue_sem);
2137 mono_sample_hit (MonoProfiler *profiler, const mono_byte *ip, const void *context)
2140 * Please note: We rely on the runtime loading the profiler with
2141 * MONO_DL_EAGER (RTLD_NOW) so that references to runtime functions within
2142 * this function (and its siblings) are resolved when the profiler is
2143 * loaded. Otherwise, we would potentially invoke the dynamic linker when
2144 * invoking runtime functions, which is not async-signal-safe.
2147 if (InterlockedRead (&log_profiler.in_shutdown))
2150 SampleHit *sample = (SampleHit *) mono_lock_free_queue_dequeue (&profiler->sample_reuse_queue);
2154 * If we're out of reusable sample events and we're not allowed to
2155 * allocate more, we have no choice but to drop the event.
2157 if (InterlockedRead (&sample_allocations_ctr) >= log_config.max_allocated_sample_hits)
2160 sample = mono_lock_free_alloc (&profiler->sample_allocator);
2161 mono_lock_free_queue_node_init (&sample->node, TRUE);
2163 InterlockedIncrement (&sample_allocations_ctr);
2167 mono_stack_walk_async_safe (&async_walk_stack, (void *) context, sample);
2169 sample->time = current_time ();
2170 sample->tid = thread_id ();
2173 mono_thread_hazardous_try_free (sample, enqueue_sample_hit);
2176 static uintptr_t *code_pages = 0;
2177 static int num_code_pages = 0;
2178 static int size_code_pages = 0;
2179 #define CPAGE_SHIFT (9)
2180 #define CPAGE_SIZE (1 << CPAGE_SHIFT)
2181 #define CPAGE_MASK (~(CPAGE_SIZE - 1))
2182 #define CPAGE_ADDR(p) ((p) & CPAGE_MASK)
2185 add_code_page (uintptr_t *hash, uintptr_t hsize, uintptr_t page)
2188 uintptr_t start_pos;
2189 start_pos = (page >> CPAGE_SHIFT) % hsize;
2192 if (hash [i] && CPAGE_ADDR (hash [i]) == CPAGE_ADDR (page)) {
2194 } else if (!hash [i]) {
2201 } while (i != start_pos);
2202 g_assert_not_reached ();
2207 add_code_pointer (uintptr_t ip)
2210 if (num_code_pages * 2 >= size_code_pages) {
2212 uintptr_t old_size = size_code_pages;
2213 size_code_pages *= 2;
2214 if (size_code_pages == 0)
2215 size_code_pages = 16;
2216 n = (uintptr_t *) g_calloc (sizeof (uintptr_t) * size_code_pages, 1);
2217 for (i = 0; i < old_size; ++i) {
2219 add_code_page (n, size_code_pages, code_pages [i]);
2222 g_free (code_pages);
2225 num_code_pages += add_code_page (code_pages, size_code_pages, ip & CPAGE_MASK);
2228 /* ELF code crashes on some systems. */
2229 //#if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
2232 dump_ubin (const char *filename, uintptr_t load_addr, uint64_t offset, uintptr_t size)
2234 int len = strlen (filename) + 1;
2236 ENTER_LOG (&sample_ubins_ctr, logbuffer,
2237 EVENT_SIZE /* event */ +
2238 LEB128_SIZE /* load address */ +
2239 LEB128_SIZE /* offset */ +
2240 LEB128_SIZE /* size */ +
2241 nlen /* file name */
2244 emit_event (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_UBIN);
2245 emit_ptr (logbuffer, load_addr);
2246 emit_uvalue (logbuffer, offset);
2247 emit_uvalue (logbuffer, size);
2248 memcpy (logbuffer->cursor, filename, len);
2249 logbuffer->cursor += len;
2256 dump_usym (const char *name, uintptr_t value, uintptr_t size)
2258 int len = strlen (name) + 1;
2260 ENTER_LOG (&sample_usyms_ctr, logbuffer,
2261 EVENT_SIZE /* event */ +
2262 LEB128_SIZE /* value */ +
2263 LEB128_SIZE /* size */ +
2267 emit_event (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_USYM);
2268 emit_ptr (logbuffer, (void*)value);
2269 emit_value (logbuffer, size);
2270 memcpy (logbuffer->cursor, name, len);
2271 logbuffer->cursor += len;
2276 /* ELF code crashes on some systems. */
2277 //#if defined(ELFMAG0)
2280 #if SIZEOF_VOID_P == 4
2281 #define ELF_WSIZE 32
2283 #define ELF_WSIZE 64
2286 #define ElfW(type) _ElfW (Elf, ELF_WSIZE, type)
2287 #define _ElfW(e,w,t) _ElfW_1 (e, w, _##t)
2288 #define _ElfW_1(e,w,t) e##w##t
2292 dump_elf_symbols (ElfW(Sym) *symbols, int num_symbols, const char *strtab, void *load_addr)
2295 for (i = 0; i < num_symbols; ++i) {
2297 sym = strtab + symbols [i].st_name;
2298 if (!symbols [i].st_name || !symbols [i].st_size || (symbols [i].st_info & 0xf) != STT_FUNC)
2300 dump_usym (sym, (uintptr_t)load_addr + symbols [i].st_value, symbols [i].st_size);
2305 read_elf_symbols (MonoProfiler *prof, const char *filename, void *load_addr)
2312 ElfW(Shdr) *sheader;
2313 ElfW(Shdr) *shstrtabh;
2314 ElfW(Shdr) *symtabh = NULL;
2315 ElfW(Shdr) *strtabh = NULL;
2316 ElfW(Sym) *symbols = NULL;
2320 fd = open (filename, O_RDONLY);
2323 if (fstat (fd, &statb) != 0) {
2327 file_size = statb.st_size;
2328 data = mmap (NULL, file_size, PROT_READ, MAP_PRIVATE, fd, 0);
2330 if (data == MAP_FAILED)
2333 if (header->e_ident [EI_MAG0] != ELFMAG0 ||
2334 header->e_ident [EI_MAG1] != ELFMAG1 ||
2335 header->e_ident [EI_MAG2] != ELFMAG2 ||
2336 header->e_ident [EI_MAG3] != ELFMAG3 ) {
2337 munmap (data, file_size);
2340 sheader = (void*)((char*)data + header->e_shoff);
2341 shstrtabh = (void*)((char*)sheader + (header->e_shentsize * header->e_shstrndx));
2342 strtab = (const char*)data + shstrtabh->sh_offset;
2343 for (i = 0; i < header->e_shnum; ++i) {
2344 if (sheader->sh_type == SHT_SYMTAB) {
2346 strtabh = (void*)((char*)data + header->e_shoff + sheader->sh_link * header->e_shentsize);
2349 sheader = (void*)((char*)sheader + header->e_shentsize);
2351 if (!symtabh || !strtabh) {
2352 munmap (data, file_size);
2355 strtab = (const char*)data + strtabh->sh_offset;
2356 num_symbols = symtabh->sh_size / symtabh->sh_entsize;
2357 symbols = (void*)((char*)data + symtabh->sh_offset);
2358 dump_elf_symbols (symbols, num_symbols, strtab, load_addr);
2359 munmap (data, file_size);
2364 /* ELF code crashes on some systems. */
2365 //#if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
2368 elf_dl_callback (struct dl_phdr_info *info, size_t size, void *data)
2371 const char *filename;
2373 char *a = (void*)info->dlpi_addr;
2375 ElfW(Dyn) *dyn = NULL;
2376 ElfW(Sym) *symtab = NULL;
2377 ElfW(Word) *hash_table = NULL;
2378 ElfW(Ehdr) *header = NULL;
2379 const char* strtab = NULL;
2380 for (obj = log_profiler.binary_objects; obj; obj = obj->next) {
2384 filename = info->dlpi_name;
2387 if (!info->dlpi_addr && !filename [0]) {
2388 int l = readlink ("/proc/self/exe", buf, sizeof (buf) - 1);
2394 obj = g_calloc (sizeof (BinaryObject), 1);
2395 obj->addr = (void*)info->dlpi_addr;
2396 obj->name = pstrdup (filename);
2397 obj->next = log_profiler.binary_objects;
2398 log_profiler.binary_objects = obj;
2400 for (i = 0; i < info->dlpi_phnum; ++i) {
2401 if (info->dlpi_phdr[i].p_type == PT_LOAD && !header) {
2402 header = (ElfW(Ehdr)*)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
2403 if (header->e_ident [EI_MAG0] != ELFMAG0 ||
2404 header->e_ident [EI_MAG1] != ELFMAG1 ||
2405 header->e_ident [EI_MAG2] != ELFMAG2 ||
2406 header->e_ident [EI_MAG3] != ELFMAG3 ) {
2409 dump_ubin (filename, info->dlpi_addr + info->dlpi_phdr[i].p_vaddr, info->dlpi_phdr[i].p_offset, info->dlpi_phdr[i].p_memsz);
2410 } else if (info->dlpi_phdr[i].p_type == PT_DYNAMIC) {
2411 dyn = (ElfW(Dyn) *)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
2414 if (read_elf_symbols (filename, (void*)info->dlpi_addr))
2416 if (!info->dlpi_name || !info->dlpi_name[0])
2420 for (i = 0; dyn [i].d_tag != DT_NULL; ++i) {
2421 if (dyn [i].d_tag == DT_SYMTAB) {
2422 symtab = (ElfW(Sym) *)(a + dyn [i].d_un.d_ptr);
2423 } else if (dyn [i].d_tag == DT_HASH) {
2424 hash_table = (ElfW(Word) *)(a + dyn [i].d_un.d_ptr);
2425 } else if (dyn [i].d_tag == DT_STRTAB) {
2426 strtab = (const char*)(a + dyn [i].d_un.d_ptr);
2431 num_sym = hash_table [1];
2432 dump_elf_symbols (symtab, num_sym, strtab, (void*)info->dlpi_addr);
2437 load_binaries (void)
2439 dl_iterate_phdr (elf_dl_callback, NULL);
2444 load_binaries (void)
2451 symbol_for (uintptr_t code)
2454 void *ip = (void*)code;
2456 if (dladdr (ip, &di)) {
2458 return di.dli_sname;
2461 names = backtrace_symbols (&ip, 1);
2463 const char* p = names [0];
2474 dump_unmanaged_coderefs (void)
2477 const char* last_symbol;
2478 uintptr_t addr, page_end;
2480 if (load_binaries ())
2482 for (i = 0; i < size_code_pages; ++i) {
2484 if (!code_pages [i] || code_pages [i] & 1)
2487 addr = CPAGE_ADDR (code_pages [i]);
2488 page_end = addr + CPAGE_SIZE;
2489 code_pages [i] |= 1;
2490 /* we dump the symbols for the whole page */
2491 for (; addr < page_end; addr += 16) {
2492 sym = symbol_for (addr);
2493 if (sym && sym == last_symbol)
2498 dump_usym (sym, addr, 0); /* let's not guess the size */
2504 counters_add_agent (MonoCounter *counter)
2506 if (InterlockedRead (&log_profiler.in_shutdown))
2509 MonoCounterAgent *agent, *item;
2511 mono_os_mutex_lock (&log_profiler.counters_mutex);
2513 for (agent = log_profiler.counters; agent; agent = agent->next) {
2514 if (agent->counter == counter) {
2515 agent->value_size = 0;
2517 g_free (agent->value);
2518 agent->value = NULL;
2524 agent = (MonoCounterAgent *) g_malloc (sizeof (MonoCounterAgent));
2525 agent->counter = counter;
2526 agent->value = NULL;
2527 agent->value_size = 0;
2528 agent->index = log_profiler.counters_index++;
2529 agent->emitted = FALSE;
2532 if (!log_profiler.counters) {
2533 log_profiler.counters = agent;
2535 item = log_profiler.counters;
2542 mono_os_mutex_unlock (&log_profiler.counters_mutex);
2546 counters_init_foreach_callback (MonoCounter *counter, gpointer data)
2548 counters_add_agent (counter);
2553 counters_init (void)
2555 mono_os_mutex_init (&log_profiler.counters_mutex);
2557 log_profiler.counters_index = 1;
2559 mono_counters_on_register (&counters_add_agent);
2560 mono_counters_foreach (counters_init_foreach_callback, NULL);
2564 counters_emit (void)
2566 MonoCounterAgent *agent;
2569 EVENT_SIZE /* event */ +
2570 LEB128_SIZE /* len */
2573 mono_os_mutex_lock (&log_profiler.counters_mutex);
2575 for (agent = log_profiler.counters; agent; agent = agent->next) {
2580 LEB128_SIZE /* section */ +
2581 strlen (mono_counter_get_name (agent->counter)) + 1 /* name */ +
2582 BYTE_SIZE /* type */ +
2583 BYTE_SIZE /* unit */ +
2584 BYTE_SIZE /* variance */ +
2585 LEB128_SIZE /* index */
2594 ENTER_LOG (&counter_descriptors_ctr, logbuffer, size);
2596 emit_event (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
2597 emit_value (logbuffer, len);
2599 for (agent = log_profiler.counters; agent; agent = agent->next) {
2605 name = mono_counter_get_name (agent->counter);
2606 emit_value (logbuffer, mono_counter_get_section (agent->counter));
2607 emit_string (logbuffer, name, strlen (name) + 1);
2608 emit_byte (logbuffer, mono_counter_get_type (agent->counter));
2609 emit_byte (logbuffer, mono_counter_get_unit (agent->counter));
2610 emit_byte (logbuffer, mono_counter_get_variance (agent->counter));
2611 emit_value (logbuffer, agent->index);
2613 agent->emitted = TRUE;
2619 mono_os_mutex_unlock (&log_profiler.counters_mutex);
2623 counters_sample (uint64_t timestamp)
2625 MonoCounterAgent *agent;
2626 MonoCounter *counter;
2635 buffer = g_calloc (1, buffer_size);
2637 mono_os_mutex_lock (&log_profiler.counters_mutex);
2640 EVENT_SIZE /* event */
2643 for (agent = log_profiler.counters; agent; agent = agent->next) {
2645 LEB128_SIZE /* index */ +
2646 BYTE_SIZE /* type */ +
2647 mono_counter_get_size (agent->counter) /* value */
2652 LEB128_SIZE /* stop marker */
2655 ENTER_LOG (&counter_samples_ctr, logbuffer, size);
2657 emit_event_time (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE, timestamp);
2659 for (agent = log_profiler.counters; agent; agent = agent->next) {
2662 counter = agent->counter;
2664 size = mono_counter_get_size (counter);
2666 if (size > buffer_size) {
2668 buffer = g_realloc (buffer, buffer_size);
2671 memset (buffer, 0, buffer_size);
2673 g_assert (mono_counters_sample (counter, buffer, size));
2675 type = mono_counter_get_type (counter);
2677 if (!agent->value) {
2678 agent->value = g_calloc (1, size);
2679 agent->value_size = size;
2681 if (type == MONO_COUNTER_STRING) {
2682 if (strcmp (agent->value, buffer) == 0)
2685 if (agent->value_size == size && memcmp (agent->value, buffer, size) == 0)
2690 emit_uvalue (logbuffer, agent->index);
2691 emit_byte (logbuffer, type);
2693 case MONO_COUNTER_INT:
2694 #if SIZEOF_VOID_P == 4
2695 case MONO_COUNTER_WORD:
2697 emit_svalue (logbuffer, *(int*)buffer - *(int*)agent->value);
2699 case MONO_COUNTER_UINT:
2700 emit_uvalue (logbuffer, *(guint*)buffer - *(guint*)agent->value);
2702 case MONO_COUNTER_TIME_INTERVAL:
2703 case MONO_COUNTER_LONG:
2704 #if SIZEOF_VOID_P == 8
2705 case MONO_COUNTER_WORD:
2707 emit_svalue (logbuffer, *(gint64*)buffer - *(gint64*)agent->value);
2709 case MONO_COUNTER_ULONG:
2710 emit_uvalue (logbuffer, *(guint64*)buffer - *(guint64*)agent->value);
2712 case MONO_COUNTER_DOUBLE:
2713 emit_double (logbuffer, *(double*)buffer);
2715 case MONO_COUNTER_STRING:
2717 emit_byte (logbuffer, 0);
2719 emit_byte (logbuffer, 1);
2720 emit_string (logbuffer, (char*)buffer, size);
2724 g_assert_not_reached ();
2727 if (type == MONO_COUNTER_STRING && size > agent->value_size) {
2728 agent->value = g_realloc (agent->value, size);
2729 agent->value_size = size;
2733 memcpy (agent->value, buffer, size);
2737 emit_value (logbuffer, 0);
2741 mono_os_mutex_unlock (&log_profiler.counters_mutex);
2745 perfcounters_emit (void)
2747 PerfCounterAgent *pcagent;
2750 EVENT_SIZE /* event */ +
2751 LEB128_SIZE /* len */
2754 for (pcagent = log_profiler.perfcounters; pcagent; pcagent = pcagent->next) {
2755 if (pcagent->emitted)
2759 LEB128_SIZE /* section */ +
2760 strlen (pcagent->category_name) + 1 /* category name */ +
2761 strlen (pcagent->name) + 1 /* name */ +
2762 BYTE_SIZE /* type */ +
2763 BYTE_SIZE /* unit */ +
2764 BYTE_SIZE /* variance */ +
2765 LEB128_SIZE /* index */
2774 ENTER_LOG (&perfcounter_descriptors_ctr, logbuffer, size);
2776 emit_event (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
2777 emit_value (logbuffer, len);
2779 for (pcagent = log_profiler.perfcounters; pcagent; pcagent = pcagent->next) {
2780 if (pcagent->emitted)
2783 emit_value (logbuffer, MONO_COUNTER_PERFCOUNTERS);
2784 emit_string (logbuffer, pcagent->category_name, strlen (pcagent->category_name) + 1);
2785 emit_string (logbuffer, pcagent->name, strlen (pcagent->name) + 1);
2786 emit_byte (logbuffer, MONO_COUNTER_LONG);
2787 emit_byte (logbuffer, MONO_COUNTER_RAW);
2788 emit_byte (logbuffer, MONO_COUNTER_VARIABLE);
2789 emit_value (logbuffer, pcagent->index);
2791 pcagent->emitted = TRUE;
2798 perfcounters_foreach (char *category_name, char *name, unsigned char type, gint64 value, gpointer user_data)
2800 PerfCounterAgent *pcagent;
2802 for (pcagent = log_profiler.perfcounters; pcagent; pcagent = pcagent->next) {
2803 if (strcmp (pcagent->category_name, category_name) != 0 || strcmp (pcagent->name, name) != 0)
2805 if (pcagent->value == value)
2808 pcagent->value = value;
2809 pcagent->updated = TRUE;
2810 pcagent->deleted = FALSE;
2814 pcagent = g_new0 (PerfCounterAgent, 1);
2815 pcagent->next = log_profiler.perfcounters;
2816 pcagent->index = log_profiler.counters_index++;
2817 pcagent->category_name = g_strdup (category_name);
2818 pcagent->name = g_strdup (name);
2819 pcagent->value = value;
2820 pcagent->emitted = FALSE;
2821 pcagent->updated = TRUE;
2822 pcagent->deleted = FALSE;
2824 log_profiler.perfcounters = pcagent;
2830 perfcounters_sample (uint64_t timestamp)
2832 PerfCounterAgent *pcagent;
2836 mono_os_mutex_lock (&log_profiler.counters_mutex);
2838 /* mark all perfcounters as deleted, foreach will unmark them as necessary */
2839 for (pcagent = log_profiler.perfcounters; pcagent; pcagent = pcagent->next)
2840 pcagent->deleted = TRUE;
2842 mono_perfcounter_foreach (perfcounters_foreach, NULL);
2844 perfcounters_emit ();
2847 EVENT_SIZE /* event */
2850 for (pcagent = log_profiler.perfcounters; pcagent; pcagent = pcagent->next) {
2851 if (pcagent->deleted || !pcagent->updated)
2855 LEB128_SIZE /* index */ +
2856 BYTE_SIZE /* type */ +
2857 LEB128_SIZE /* value */
2867 LEB128_SIZE /* stop marker */
2870 ENTER_LOG (&perfcounter_samples_ctr, logbuffer, size);
2872 emit_event_time (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE, timestamp);
2874 for (pcagent = log_profiler.perfcounters; pcagent; pcagent = pcagent->next) {
2875 if (pcagent->deleted || !pcagent->updated)
2877 emit_uvalue (logbuffer, pcagent->index);
2878 emit_byte (logbuffer, MONO_COUNTER_LONG);
2879 emit_svalue (logbuffer, pcagent->value);
2881 pcagent->updated = FALSE;
2884 emit_value (logbuffer, 0);
2889 mono_os_mutex_unlock (&log_profiler.counters_mutex);
2893 counters_and_perfcounters_sample (void)
2895 uint64_t now = current_time ();
2897 counters_sample (now);
2898 perfcounters_sample (now);
2902 MonoLockFreeQueueNode node;
2915 free_coverage_entry (gpointer data, gpointer userdata)
2917 CoverageEntry *entry = (CoverageEntry *)data;
2918 g_free (entry->filename);
2923 obtain_coverage_for_method (MonoProfiler *prof, const MonoProfilerCoverageData *entry)
2925 int offset = entry->il_offset - log_profiler.coverage_previous_offset;
2926 CoverageEntry *e = g_new (CoverageEntry, 1);
2928 log_profiler.coverage_previous_offset = entry->il_offset;
2931 e->counter = entry->counter;
2932 e->filename = g_strdup(entry->file_name ? entry->file_name : "");
2933 e->line = entry->line;
2934 e->column = entry->column;
2936 g_ptr_array_add (log_profiler.coverage_data, e);
2940 parse_generic_type_names(char *name)
2942 char *new_name, *ret;
2943 int within_generic_declaration = 0, generic_members = 1;
2945 if (name == NULL || *name == '\0')
2946 return g_strdup ("");
2948 if (!(ret = new_name = (char *) g_calloc (strlen (name) * 4 + 1, sizeof (char))))
2954 within_generic_declaration = 1;
2958 within_generic_declaration = 0;
2960 if (*(name - 1) != '<') {
2962 *new_name++ = '0' + generic_members;
2964 memcpy (new_name, "<>", 8);
2968 generic_members = 0;
2976 if (!within_generic_declaration)
2977 *new_name++ = *name;
2987 build_method_buffer (gpointer key, gpointer value, gpointer userdata)
2989 MonoMethod *method = (MonoMethod *)value;
2993 const char *image_name, *method_name, *sig, *first_filename;
2996 log_profiler.coverage_previous_offset = 0;
2997 log_profiler.coverage_data = g_ptr_array_new ();
2999 mono_profiler_get_coverage_data (log_profiler.handle, method, obtain_coverage_for_method);
3001 klass = mono_method_get_class (method);
3002 image = mono_class_get_image (klass);
3003 image_name = mono_image_get_name (image);
3005 sig = mono_signature_get_desc (mono_method_signature (method), TRUE);
3006 class_name = parse_generic_type_names (mono_type_get_name (mono_class_get_type (klass)));
3007 method_name = mono_method_get_name (method);
3009 if (log_profiler.coverage_data->len != 0) {
3010 CoverageEntry *entry = (CoverageEntry *)log_profiler.coverage_data->pdata[0];
3011 first_filename = entry->filename ? entry->filename : "";
3013 first_filename = "";
3015 image_name = image_name ? image_name : "";
3016 sig = sig ? sig : "";
3017 method_name = method_name ? method_name : "";
3019 ENTER_LOG (&coverage_methods_ctr, logbuffer,
3020 EVENT_SIZE /* event */ +
3021 strlen (image_name) + 1 /* image name */ +
3022 strlen (class_name) + 1 /* class name */ +
3023 strlen (method_name) + 1 /* method name */ +
3024 strlen (sig) + 1 /* signature */ +
3025 strlen (first_filename) + 1 /* first file name */ +
3026 LEB128_SIZE /* token */ +
3027 LEB128_SIZE /* method id */ +
3028 LEB128_SIZE /* entries */
3031 emit_event (logbuffer, TYPE_COVERAGE_METHOD | TYPE_COVERAGE);
3032 emit_string (logbuffer, image_name, strlen (image_name) + 1);
3033 emit_string (logbuffer, class_name, strlen (class_name) + 1);
3034 emit_string (logbuffer, method_name, strlen (method_name) + 1);
3035 emit_string (logbuffer, sig, strlen (sig) + 1);
3036 emit_string (logbuffer, first_filename, strlen (first_filename) + 1);
3038 emit_uvalue (logbuffer, mono_method_get_token (method));
3039 emit_uvalue (logbuffer, log_profiler.coverage_method_id);
3040 emit_value (logbuffer, log_profiler.coverage_data->len);
3044 for (i = 0; i < log_profiler.coverage_data->len; i++) {
3045 CoverageEntry *entry = (CoverageEntry *)log_profiler.coverage_data->pdata[i];
3047 ENTER_LOG (&coverage_statements_ctr, logbuffer,
3048 EVENT_SIZE /* event */ +
3049 LEB128_SIZE /* method id */ +
3050 LEB128_SIZE /* offset */ +
3051 LEB128_SIZE /* counter */ +
3052 LEB128_SIZE /* line */ +
3053 LEB128_SIZE /* column */
3056 emit_event (logbuffer, TYPE_COVERAGE_STATEMENT | TYPE_COVERAGE);
3057 emit_uvalue (logbuffer, log_profiler.coverage_method_id);
3058 emit_uvalue (logbuffer, entry->offset);
3059 emit_uvalue (logbuffer, entry->counter);
3060 emit_uvalue (logbuffer, entry->line);
3061 emit_uvalue (logbuffer, entry->column);
3066 log_profiler.coverage_method_id++;
3068 g_free (class_name);
3070 g_ptr_array_foreach (log_profiler.coverage_data, free_coverage_entry, NULL);
3071 g_ptr_array_free (log_profiler.coverage_data, TRUE);
3074 /* This empties the queue */
3076 count_queue (MonoLockFreeQueue *queue)
3078 MonoLockFreeQueueNode *node;
3081 while ((node = mono_lock_free_queue_dequeue (queue))) {
3083 mono_thread_hazardous_try_free (node, g_free);
3090 build_class_buffer (gpointer key, gpointer value, gpointer userdata)
3092 MonoClass *klass = (MonoClass *)key;
3093 MonoLockFreeQueue *class_methods = (MonoLockFreeQueue *)value;
3096 const char *assembly_name;
3097 int number_of_methods, partially_covered;
3098 guint fully_covered;
3100 image = mono_class_get_image (klass);
3101 assembly_name = mono_image_get_name (image);
3102 class_name = mono_type_get_name (mono_class_get_type (klass));
3104 assembly_name = assembly_name ? assembly_name : "";
3105 number_of_methods = mono_class_num_methods (klass);
3106 fully_covered = count_queue (class_methods);
3107 /* We don't handle partial covered yet */
3108 partially_covered = 0;
3110 ENTER_LOG (&coverage_classes_ctr, logbuffer,
3111 EVENT_SIZE /* event */ +
3112 strlen (assembly_name) + 1 /* assembly name */ +
3113 strlen (class_name) + 1 /* class name */ +
3114 LEB128_SIZE /* no. methods */ +
3115 LEB128_SIZE /* fully covered */ +
3116 LEB128_SIZE /* partially covered */
3119 emit_event (logbuffer, TYPE_COVERAGE_CLASS | TYPE_COVERAGE);
3120 emit_string (logbuffer, assembly_name, strlen (assembly_name) + 1);
3121 emit_string (logbuffer, class_name, strlen (class_name) + 1);
3122 emit_uvalue (logbuffer, number_of_methods);
3123 emit_uvalue (logbuffer, fully_covered);
3124 emit_uvalue (logbuffer, partially_covered);
3128 g_free (class_name);
3132 get_coverage_for_image (MonoImage *image, int *number_of_methods, guint *fully_covered, int *partially_covered)
3134 MonoLockFreeQueue *image_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (log_profiler.coverage_image_to_methods, image);
3136 *number_of_methods = mono_image_get_table_rows (image, MONO_TABLE_METHOD);
3138 *fully_covered = count_queue (image_methods);
3142 // FIXME: We don't handle partially covered yet.
3143 *partially_covered = 0;
3147 build_assembly_buffer (gpointer key, gpointer value, gpointer userdata)
3149 MonoAssembly *assembly = (MonoAssembly *)value;
3150 MonoImage *image = mono_assembly_get_image (assembly);
3151 const char *name, *guid, *filename;
3152 int number_of_methods = 0, partially_covered = 0;
3153 guint fully_covered = 0;
3155 name = mono_image_get_name (image);
3156 guid = mono_image_get_guid (image);
3157 filename = mono_image_get_filename (image);
3159 name = name ? name : "";
3160 guid = guid ? guid : "";
3161 filename = filename ? filename : "";
3163 get_coverage_for_image (image, &number_of_methods, &fully_covered, &partially_covered);
3165 ENTER_LOG (&coverage_assemblies_ctr, logbuffer,
3166 EVENT_SIZE /* event */ +
3167 strlen (name) + 1 /* name */ +
3168 strlen (guid) + 1 /* guid */ +
3169 strlen (filename) + 1 /* file name */ +
3170 LEB128_SIZE /* no. methods */ +
3171 LEB128_SIZE /* fully covered */ +
3172 LEB128_SIZE /* partially covered */
3175 emit_event (logbuffer, TYPE_COVERAGE_ASSEMBLY | TYPE_COVERAGE);
3176 emit_string (logbuffer, name, strlen (name) + 1);
3177 emit_string (logbuffer, guid, strlen (guid) + 1);
3178 emit_string (logbuffer, filename, strlen (filename) + 1);
3179 emit_uvalue (logbuffer, number_of_methods);
3180 emit_uvalue (logbuffer, fully_covered);
3181 emit_uvalue (logbuffer, partially_covered);
3187 dump_coverage (void)
3189 mono_os_mutex_lock (&log_profiler.coverage_mutex);
3190 mono_conc_hashtable_foreach (log_profiler.coverage_assemblies, build_assembly_buffer, NULL);
3191 mono_conc_hashtable_foreach (log_profiler.coverage_classes, build_class_buffer, NULL);
3192 mono_conc_hashtable_foreach (log_profiler.coverage_methods, build_method_buffer, NULL);
3193 mono_os_mutex_unlock (&log_profiler.coverage_mutex);
3196 static MonoLockFreeQueueNode *
3197 create_method_node (MonoMethod *method)
3199 MethodNode *node = (MethodNode *) g_malloc (sizeof (MethodNode));
3200 mono_lock_free_queue_node_init ((MonoLockFreeQueueNode *) node, FALSE);
3201 node->method = method;
3203 return (MonoLockFreeQueueNode *) node;
3207 coverage_filter (MonoProfiler *prof, MonoMethod *method)
3212 MonoAssembly *assembly;
3213 MonoMethodHeader *header;
3214 guint32 iflags, flags, code_size;
3215 char *fqn, *classname;
3216 gboolean has_positive, found;
3217 MonoLockFreeQueue *image_methods, *class_methods;
3218 MonoLockFreeQueueNode *node;
3220 flags = mono_method_get_flags (method, &iflags);
3221 if ((iflags & 0x1000 /*METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL*/) ||
3222 (flags & 0x2000 /*METHOD_ATTRIBUTE_PINVOKE_IMPL*/))
3225 // Don't need to do anything else if we're already tracking this method
3226 if (mono_conc_hashtable_lookup (log_profiler.coverage_methods, method))
3229 klass = mono_method_get_class (method);
3230 image = mono_class_get_image (klass);
3232 // Don't handle coverage for the core assemblies
3233 if (mono_conc_hashtable_lookup (log_profiler.coverage_suppressed_assemblies, (gpointer) mono_image_get_name (image)) != NULL)
3236 if (prof->coverage_filters) {
3237 /* Check already filtered classes first */
3238 if (mono_conc_hashtable_lookup (log_profiler.coverage_filtered_classes, klass))
3241 classname = mono_type_get_name (mono_class_get_type (klass));
3243 fqn = g_strdup_printf ("[%s]%s", mono_image_get_name (image), classname);
3245 // Check positive filters first
3246 has_positive = FALSE;
3248 for (guint i = 0; i < prof->coverage_filters->len; ++i) {
3249 char *filter = (char *)g_ptr_array_index (prof->coverage_filters, i);
3251 if (filter [0] == '+') {
3252 filter = &filter [1];
3254 if (strstr (fqn, filter) != NULL)
3257 has_positive = TRUE;
3261 if (has_positive && !found) {
3262 mono_os_mutex_lock (&log_profiler.coverage_mutex);
3263 mono_conc_hashtable_insert (log_profiler.coverage_filtered_classes, klass, klass);
3264 mono_os_mutex_unlock (&log_profiler.coverage_mutex);
3271 for (guint i = 0; i < prof->coverage_filters->len; ++i) {
3272 // FIXME: Is substring search sufficient?
3273 char *filter = (char *)g_ptr_array_index (prof->coverage_filters, i);
3274 if (filter [0] == '+')
3278 filter = &filter [1];
3280 if (strstr (fqn, filter) != NULL) {
3281 mono_os_mutex_lock (&log_profiler.coverage_mutex);
3282 mono_conc_hashtable_insert (log_profiler.coverage_filtered_classes, klass, klass);
3283 mono_os_mutex_unlock (&log_profiler.coverage_mutex);
3295 header = mono_method_get_header_checked (method, &error);
3296 mono_error_cleanup (&error);
3298 mono_method_header_get_code (header, &code_size, NULL);
3300 assembly = mono_image_get_assembly (image);
3302 // Need to keep the assemblies around for as long as they are kept in the hashtable
3303 // Nunit, for example, has a habit of unloading them before the coverage statistics are
3304 // generated causing a crash. See https://bugzilla.xamarin.com/show_bug.cgi?id=39325
3305 mono_assembly_addref (assembly);
3307 mono_os_mutex_lock (&log_profiler.coverage_mutex);
3308 mono_conc_hashtable_insert (log_profiler.coverage_methods, method, method);
3309 mono_conc_hashtable_insert (log_profiler.coverage_assemblies, assembly, assembly);
3310 mono_os_mutex_unlock (&log_profiler.coverage_mutex);
3312 image_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (log_profiler.coverage_image_to_methods, image);
3314 if (image_methods == NULL) {
3315 image_methods = (MonoLockFreeQueue *) g_malloc (sizeof (MonoLockFreeQueue));
3316 mono_lock_free_queue_init (image_methods);
3317 mono_os_mutex_lock (&log_profiler.coverage_mutex);
3318 mono_conc_hashtable_insert (log_profiler.coverage_image_to_methods, image, image_methods);
3319 mono_os_mutex_unlock (&log_profiler.coverage_mutex);
3322 node = create_method_node (method);
3323 mono_lock_free_queue_enqueue (image_methods, node);
3325 class_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (log_profiler.coverage_classes, klass);
3327 if (class_methods == NULL) {
3328 class_methods = (MonoLockFreeQueue *) g_malloc (sizeof (MonoLockFreeQueue));
3329 mono_lock_free_queue_init (class_methods);
3330 mono_os_mutex_lock (&log_profiler.coverage_mutex);
3331 mono_conc_hashtable_insert (log_profiler.coverage_classes, klass, class_methods);
3332 mono_os_mutex_unlock (&log_profiler.coverage_mutex);
3335 node = create_method_node (method);
3336 mono_lock_free_queue_enqueue (class_methods, node);
3341 #define LINE_BUFFER_SIZE 4096
3342 /* Max file limit of 128KB */
3343 #define MAX_FILE_SIZE 128 * 1024
3345 get_file_content (FILE *stream)
3350 int res, offset = 0;
3352 res = fseek (stream, 0, SEEK_END);
3356 filesize = ftell (stream);
3360 res = fseek (stream, 0, SEEK_SET);
3364 if (filesize > MAX_FILE_SIZE)
3367 buffer = (char *) g_malloc ((filesize + 1) * sizeof (char));
3368 while ((bytes_read = fread (buffer + offset, 1, LINE_BUFFER_SIZE, stream)) > 0)
3369 offset += bytes_read;
3371 /* NULL terminate our buffer */
3372 buffer[filesize] = '\0';
3377 get_next_line (char *contents, char **next_start)
3381 if (p == NULL || *p == '\0') {
3386 while (*p != '\n' && *p != '\0')
3391 *next_start = p + 1;
3399 init_suppressed_assemblies (void)
3405 log_profiler.coverage_suppressed_assemblies = mono_conc_hashtable_new (g_str_hash, g_str_equal);
3406 sa_file = fopen (SUPPRESSION_DIR "/mono-profiler-log.suppression", "r");
3407 if (sa_file == NULL)
3410 /* Don't need to free @content as it is referred to by the lines stored in @suppressed_assemblies */
3411 content = get_file_content (sa_file);
3412 if (content == NULL)
3413 g_error ("mono-profiler-log.suppression is greater than 128kb - aborting.");
3415 while ((line = get_next_line (content, &content))) {
3416 line = g_strchomp (g_strchug (line));
3417 /* No locking needed as we're doing initialization */
3418 mono_conc_hashtable_insert (log_profiler.coverage_suppressed_assemblies, line, line);
3425 parse_cov_filter_file (GPtrArray *filters, const char *file)
3427 FILE *filter_file = fopen (file, "r");
3429 if (filter_file == NULL) {
3430 mono_profiler_printf_err ("Could not open coverage filter file '%s'.", file);
3434 /* Don't need to free content as it is referred to by the lines stored in @filters */
3435 char *content = get_file_content (filter_file);
3437 if (content == NULL)
3438 mono_profiler_printf_err ("Coverage filter file '%s' is larger than 128kb - ignoring.", file);
3442 while ((line = get_next_line (content, &content)))
3443 g_ptr_array_add (filters, g_strchug (g_strchomp (line)));
3445 fclose (filter_file);
3449 coverage_init (void)
3451 mono_os_mutex_init (&log_profiler.coverage_mutex);
3452 log_profiler.coverage_methods = mono_conc_hashtable_new (NULL, NULL);
3453 log_profiler.coverage_assemblies = mono_conc_hashtable_new (NULL, NULL);
3454 log_profiler.coverage_classes = mono_conc_hashtable_new (NULL, NULL);
3455 log_profiler.coverage_filtered_classes = mono_conc_hashtable_new (NULL, NULL);
3456 log_profiler.coverage_image_to_methods = mono_conc_hashtable_new (NULL, NULL);
3457 init_suppressed_assemblies ();
3461 unref_coverage_assemblies (gpointer key, gpointer value, gpointer userdata)
3463 MonoAssembly *assembly = (MonoAssembly *)value;
3464 mono_assembly_close (assembly);
3468 free_sample_hit (gpointer p)
3470 mono_lock_free_free (p, SAMPLE_BLOCK_SIZE);
3474 cleanup_reusable_samples (void)
3478 while ((sample = (SampleHit *) mono_lock_free_queue_dequeue (&log_profiler.sample_reuse_queue)))
3479 mono_thread_hazardous_try_free (sample, free_sample_hit);
3483 log_shutdown (MonoProfiler *prof)
3485 InterlockedWrite (&log_profiler.in_shutdown, 1);
3487 if (ENABLED (PROFLOG_COUNTER_EVENTS))
3488 counters_and_perfcounters_sample ();
3490 if (log_config.collect_coverage)
3495 if (write (prof->pipes [1], &c, 1) != 1) {
3496 mono_profiler_printf_err ("Could not write to log profiler pipe: %s", strerror (errno));
3500 mono_native_thread_join (prof->helper_thread);
3502 mono_os_mutex_destroy (&log_profiler.counters_mutex);
3504 MonoCounterAgent *mc_next;
3506 for (MonoCounterAgent *cur = log_profiler.counters; cur; cur = mc_next) {
3507 mc_next = cur->next;
3511 PerfCounterAgent *pc_next;
3513 for (PerfCounterAgent *cur = log_profiler.perfcounters; cur; cur = pc_next) {
3514 pc_next = cur->next;
3519 * Ensure that we empty the LLS completely, even if some nodes are
3520 * not immediately removed upon calling mono_lls_remove (), by
3521 * iterating until the head is NULL.
3523 while (log_profiler.profiler_thread_list.head) {
3524 MONO_LLS_FOREACH_SAFE (&log_profiler.profiler_thread_list, MonoProfilerThread, thread) {
3525 g_assert (thread->attached && "Why is a thread in the LLS not attached?");
3527 remove_thread (thread);
3528 } MONO_LLS_FOREACH_SAFE_END
3532 * Ensure that all threads have been freed, so that we don't miss any
3533 * buffers when we shut down the writer thread below.
3535 mono_thread_hazardous_try_free_all ();
3537 InterlockedWrite (&prof->run_dumper_thread, 0);
3538 mono_os_sem_post (&prof->dumper_queue_sem);
3539 mono_native_thread_join (prof->dumper_thread);
3540 mono_os_sem_destroy (&prof->dumper_queue_sem);
3542 InterlockedWrite (&prof->run_writer_thread, 0);
3543 mono_os_sem_post (&prof->writer_queue_sem);
3544 mono_native_thread_join (prof->writer_thread);
3545 mono_os_sem_destroy (&prof->writer_queue_sem);
3548 * Free all writer queue entries, and ensure that all sample hits will be
3549 * added to the sample reuse queue.
3551 mono_thread_hazardous_try_free_all ();
3553 cleanup_reusable_samples ();
3556 * Finally, make sure that all sample hits are freed. This should cover all
3557 * hazardous data from the profiler. We can now be sure that the runtime
3558 * won't later invoke free functions in the profiler library after it has
3561 mono_thread_hazardous_try_free_all ();
3563 gint32 state = InterlockedRead (&log_profiler.buffer_lock_state);
3565 g_assert (!(state & 0xFFFF) && "Why is the reader count still non-zero?");
3566 g_assert (!(state >> 16) && "Why is the exclusive lock still held?");
3568 #if defined (HAVE_SYS_ZLIB)
3570 gzclose (prof->gzfile);
3572 if (prof->pipe_output)
3573 pclose (prof->file);
3575 fclose (prof->file);
3577 mono_conc_hashtable_destroy (prof->method_table);
3578 mono_os_mutex_destroy (&prof->method_table_mutex);
3580 if (log_config.collect_coverage) {
3581 mono_os_mutex_lock (&log_profiler.coverage_mutex);
3582 mono_conc_hashtable_foreach (log_profiler.coverage_assemblies, unref_coverage_assemblies, NULL);
3583 mono_os_mutex_unlock (&log_profiler.coverage_mutex);
3585 mono_conc_hashtable_destroy (log_profiler.coverage_methods);
3586 mono_conc_hashtable_destroy (log_profiler.coverage_assemblies);
3587 mono_conc_hashtable_destroy (log_profiler.coverage_classes);
3588 mono_conc_hashtable_destroy (log_profiler.coverage_filtered_classes);
3590 mono_conc_hashtable_destroy (log_profiler.coverage_image_to_methods);
3591 mono_conc_hashtable_destroy (log_profiler.coverage_suppressed_assemblies);
3592 mono_os_mutex_destroy (&log_profiler.coverage_mutex);
3597 g_free (prof->args);
3601 new_filename (const char* filename)
3603 time_t t = time (NULL);
3604 int pid = process_id ();
3609 int count_dates = 0;
3613 for (p = filename; *p; p++) {
3624 if (!count_dates && !count_pids)
3625 return pstrdup (filename);
3626 snprintf (pid_buf, sizeof (pid_buf), "%d", pid);
3628 snprintf (time_buf, sizeof (time_buf), "%d%02d%02d%02d%02d%02d",
3629 1900 + ts->tm_year, 1 + ts->tm_mon, ts->tm_mday, ts->tm_hour, ts->tm_min, ts->tm_sec);
3630 s_date = strlen (time_buf);
3631 s_pid = strlen (pid_buf);
3632 d = res = (char *) g_malloc (strlen (filename) + s_date * count_dates + s_pid * count_pids);
3633 for (p = filename; *p; p++) {
3640 strcpy (d, time_buf);
3643 } else if (*p == 'p') {
3644 strcpy (d, pid_buf);
3647 } else if (*p == '%') {
3660 add_to_fd_set (fd_set *set, int fd, int *max_fd)
3663 * This should only trigger for the basic FDs (server socket, pipes) at
3664 * startup if for some mysterious reason they're too large. In this case,
3665 * the profiler really can't function, and we're better off printing an
3666 * error and exiting.
3668 if (fd >= FD_SETSIZE) {
3669 mono_profiler_printf_err ("File descriptor is out of bounds for fd_set: %d", fd);
3680 helper_thread (void *arg)
3682 mono_threads_attach_tools_thread ();
3683 mono_native_thread_set_name (mono_native_thread_id_get (), "Profiler helper");
3685 MonoProfilerThread *thread = init_thread (FALSE);
3687 GArray *command_sockets = g_array_new (FALSE, FALSE, sizeof (int));
3695 add_to_fd_set (&rfds, log_profiler.server_socket, &max_fd);
3696 add_to_fd_set (&rfds, log_profiler.pipes [0], &max_fd);
3698 for (gint i = 0; i < command_sockets->len; i++)
3699 add_to_fd_set (&rfds, g_array_index (command_sockets, int, i), &max_fd);
3701 struct timeval tv = { .tv_sec = 1, .tv_usec = 0 };
3703 // Sleep for 1sec or until a file descriptor has data.
3704 if (select (max_fd + 1, &rfds, NULL, NULL, &tv) == -1) {
3708 mono_profiler_printf_err ("Could not poll in log profiler helper thread: %s", strerror (errno));
3712 if (ENABLED (PROFLOG_COUNTER_EVENTS))
3713 counters_and_perfcounters_sample ();
3715 buffer_lock_excl ();
3717 sync_point (SYNC_POINT_PERIODIC);
3719 buffer_unlock_excl ();
3721 // Are we shutting down?
3722 if (FD_ISSET (log_profiler.pipes [0], &rfds)) {
3724 read (log_profiler.pipes [0], &c, 1);
3728 for (gint i = 0; i < command_sockets->len; i++) {
3729 int fd = g_array_index (command_sockets, int, i);
3731 if (!FD_ISSET (fd, &rfds))
3735 int len = read (fd, buf, sizeof (buf) - 1);
3741 // The other end disconnected.
3742 g_array_remove_index (command_sockets, i);
3750 if (log_config.hs_mode == MONO_PROFILER_HEAPSHOT_ON_DEMAND && !strcmp (buf, "heapshot\n")) {
3751 // Rely on the finalization callback triggering a GC.
3752 InterlockedWrite (&log_profiler.heapshot_requested, 1);
3753 mono_gc_finalize_notify ();
3757 if (FD_ISSET (log_profiler.server_socket, &rfds)) {
3758 int fd = accept (log_profiler.server_socket, NULL, NULL);
3761 if (fd >= FD_SETSIZE)
3764 g_array_append_val (command_sockets, fd);
3769 for (gint i = 0; i < command_sockets->len; i++)
3770 close (g_array_index (command_sockets, int, i));
3772 g_array_free (command_sockets, TRUE);
3774 send_log_unsafe (FALSE);
3775 deinit_thread (thread);
3777 mono_thread_info_detach ();
3783 start_helper_thread (void)
3785 if (pipe (log_profiler.pipes) == -1) {
3786 mono_profiler_printf_err ("Could not create log profiler pipe: %s", strerror (errno));
3790 log_profiler.server_socket = socket (PF_INET, SOCK_STREAM, 0);
3792 if (log_profiler.server_socket == -1) {
3793 mono_profiler_printf_err ("Could not create log profiler server socket: %s", strerror (errno));
3797 struct sockaddr_in server_address;
3799 memset (&server_address, 0, sizeof (server_address));
3800 server_address.sin_family = AF_INET;
3801 server_address.sin_addr.s_addr = INADDR_ANY;
3802 server_address.sin_port = htons (log_profiler.command_port);
3804 if (bind (log_profiler.server_socket, (struct sockaddr *) &server_address, sizeof (server_address)) == -1) {
3805 mono_profiler_printf_err ("Could not bind log profiler server socket on port %d: %s", log_profiler.command_port, strerror (errno));
3806 close (log_profiler.server_socket);
3810 if (listen (log_profiler.server_socket, 1) == -1) {
3811 mono_profiler_printf_err ("Could not listen on log profiler server socket: %s", strerror (errno));
3812 close (log_profiler.server_socket);
3816 socklen_t slen = sizeof (server_address);
3818 if (getsockname (log_profiler.server_socket, (struct sockaddr *) &server_address, &slen)) {
3819 mono_profiler_printf_err ("Could not retrieve assigned port for log profiler server socket: %s", strerror (errno));
3820 close (log_profiler.server_socket);
3824 log_profiler.command_port = ntohs (server_address.sin_port);
3826 if (!mono_native_thread_create (&log_profiler.helper_thread, helper_thread, NULL)) {
3827 mono_profiler_printf_err ("Could not start log profiler helper thread");
3828 close (log_profiler.server_socket);
3834 free_writer_entry (gpointer p)
3836 mono_lock_free_free (p, WRITER_ENTRY_BLOCK_SIZE);
3840 handle_writer_queue_entry (void)
3842 WriterQueueEntry *entry;
3844 if ((entry = (WriterQueueEntry *) mono_lock_free_queue_dequeue (&log_profiler.writer_queue))) {
3845 if (!entry->methods)
3848 gboolean wrote_methods = FALSE;
3851 * Encode the method events in a temporary log buffer that we
3852 * flush to disk before the main buffer, ensuring that all
3853 * methods have metadata emitted before they're referenced.
3855 * We use a 'proper' thread-local buffer for this as opposed
3856 * to allocating and freeing a buffer by hand because the call
3857 * to mono_method_full_name () below may trigger class load
3858 * events when it retrieves the signature of the method. So a
3859 * thread-local buffer needs to exist when such events occur.
3861 for (guint i = 0; i < entry->methods->len; i++) {
3862 MethodInfo *info = (MethodInfo *) g_ptr_array_index (entry->methods, i);
3864 if (mono_conc_hashtable_lookup (log_profiler.method_table, info->method))
3865 goto free_info; // This method already has metadata emitted.
3868 * Other threads use this hash table to get a general
3869 * idea of whether a method has already been emitted to
3870 * the stream. Due to the way we add to this table, it
3871 * can easily happen that multiple threads queue up the
3872 * same methods, but that's OK since eventually all
3873 * methods will be in this table and the thread-local
3874 * method lists will just be empty for the rest of the
3877 mono_os_mutex_lock (&log_profiler.method_table_mutex);
3878 mono_conc_hashtable_insert (log_profiler.method_table, info->method, info->method);
3879 mono_os_mutex_unlock (&log_profiler.method_table_mutex);
3881 char *name = mono_method_full_name (info->method, 1);
3882 int nlen = strlen (name) + 1;
3883 void *cstart = info->ji ? mono_jit_info_get_code_start (info->ji) : NULL;
3884 int csize = info->ji ? mono_jit_info_get_code_size (info->ji) : 0;
3886 ENTER_LOG (&method_jits_ctr, logbuffer,
3887 EVENT_SIZE /* event */ +
3888 LEB128_SIZE /* method */ +
3889 LEB128_SIZE /* start */ +
3890 LEB128_SIZE /* size */ +
3894 emit_event_time (logbuffer, TYPE_JIT | TYPE_METHOD, info->time);
3895 emit_method_inner (logbuffer, info->method);
3896 emit_ptr (logbuffer, cstart);
3897 emit_value (logbuffer, csize);
3899 memcpy (logbuffer->cursor, name, nlen);
3900 logbuffer->cursor += nlen;
3902 EXIT_LOG_EXPLICIT (NO_SEND);
3906 wrote_methods = TRUE;
3912 g_ptr_array_free (entry->methods, TRUE);
3914 if (wrote_methods) {
3915 MonoProfilerThread *thread = PROF_TLS_GET ();
3917 dump_buffer_threadless (thread->buffer);
3918 init_buffer_state (thread);
3922 dump_buffer (entry->buffer);
3924 mono_thread_hazardous_try_free (entry, free_writer_entry);
3933 writer_thread (void *arg)
3935 mono_threads_attach_tools_thread ();
3936 mono_native_thread_set_name (mono_native_thread_id_get (), "Profiler writer");
3940 MonoProfilerThread *thread = init_thread (FALSE);
3942 while (InterlockedRead (&log_profiler.run_writer_thread)) {
3943 mono_os_sem_wait (&log_profiler.writer_queue_sem, MONO_SEM_FLAGS_NONE);
3944 handle_writer_queue_entry ();
3947 /* Drain any remaining entries on shutdown. */
3948 while (handle_writer_queue_entry ());
3950 free_buffer (thread->buffer, thread->buffer->size);
3951 deinit_thread (thread);
3953 mono_thread_info_detach ();
3959 start_writer_thread (void)
3961 InterlockedWrite (&log_profiler.run_writer_thread, 1);
3963 if (!mono_native_thread_create (&log_profiler.writer_thread, writer_thread, NULL)) {
3964 mono_profiler_printf_err ("Could not start log profiler writer thread");
3970 reuse_sample_hit (gpointer p)
3972 SampleHit *sample = p;
3974 mono_lock_free_queue_node_unpoison (&sample->node);
3975 mono_lock_free_queue_enqueue (&log_profiler.sample_reuse_queue, &sample->node);
3979 handle_dumper_queue_entry (void)
3983 if ((sample = (SampleHit *) mono_lock_free_queue_dequeue (&log_profiler.dumper_queue))) {
3984 for (int i = 0; i < sample->count; ++i) {
3985 MonoMethod *method = sample->frames [i].method;
3986 MonoDomain *domain = sample->frames [i].domain;
3987 void *address = sample->frames [i].base_address;
3990 g_assert (domain && "What happened to the domain pointer?");
3991 g_assert (address && "What happened to the instruction pointer?");
3993 MonoJitInfo *ji = mono_jit_info_table_find (domain, (char *) address);
3996 sample->frames [i].method = mono_jit_info_get_method (ji);
4000 ENTER_LOG (&sample_hits_ctr, logbuffer,
4001 EVENT_SIZE /* event */ +
4002 LEB128_SIZE /* tid */ +
4003 LEB128_SIZE /* count */ +
4005 LEB128_SIZE /* ip */
4007 LEB128_SIZE /* managed count */ +
4009 LEB128_SIZE /* method */
4013 emit_event_time (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_HIT, sample->time);
4014 emit_ptr (logbuffer, (void *) sample->tid);
4015 emit_value (logbuffer, 1);
4017 // TODO: Actual native unwinding.
4018 for (int i = 0; i < 1; ++i) {
4019 emit_ptr (logbuffer, sample->ip);
4020 add_code_pointer ((uintptr_t) sample->ip);
4023 /* new in data version 6 */
4024 emit_uvalue (logbuffer, sample->count);
4026 for (int i = 0; i < sample->count; ++i)
4027 emit_method (logbuffer, sample->frames [i].method);
4031 mono_thread_hazardous_try_free (sample, reuse_sample_hit);
4033 dump_unmanaged_coderefs ();
4040 dumper_thread (void *arg)
4042 mono_threads_attach_tools_thread ();
4043 mono_native_thread_set_name (mono_native_thread_id_get (), "Profiler dumper");
4045 MonoProfilerThread *thread = init_thread (FALSE);
4047 while (InterlockedRead (&log_profiler.run_dumper_thread)) {
4049 * Flush samples every second so it doesn't seem like the profiler is
4050 * not working if the program is mostly idle.
4052 if (mono_os_sem_timedwait (&log_profiler.dumper_queue_sem, 1000, MONO_SEM_FLAGS_NONE) == MONO_SEM_TIMEDWAIT_RET_TIMEDOUT)
4053 send_log_unsafe (FALSE);
4055 handle_dumper_queue_entry ();
4058 /* Drain any remaining entries on shutdown. */
4059 while (handle_dumper_queue_entry ());
4061 send_log_unsafe (FALSE);
4062 deinit_thread (thread);
4064 mono_thread_info_detach ();
4070 start_dumper_thread (void)
4072 InterlockedWrite (&log_profiler.run_dumper_thread, 1);
4074 if (!mono_native_thread_create (&log_profiler.dumper_thread, dumper_thread, NULL)) {
4075 mono_profiler_printf_err ("Could not start log profiler dumper thread");
4081 register_counter (const char *name, gint32 *counter)
4083 mono_counters_register (name, MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, counter);
4087 runtime_initialized (MonoProfiler *profiler)
4089 InterlockedWrite (&log_profiler.runtime_inited, 1);
4091 register_counter ("Sample events allocated", &sample_allocations_ctr);
4092 register_counter ("Log buffers allocated", &buffer_allocations_ctr);
4094 register_counter ("Event: Sync points", &sync_points_ctr);
4095 register_counter ("Event: Heap objects", &heap_objects_ctr);
4096 register_counter ("Event: Heap starts", &heap_starts_ctr);
4097 register_counter ("Event: Heap ends", &heap_ends_ctr);
4098 register_counter ("Event: Heap roots", &heap_roots_ctr);
4099 register_counter ("Event: GC events", &gc_events_ctr);
4100 register_counter ("Event: GC resizes", &gc_resizes_ctr);
4101 register_counter ("Event: GC allocations", &gc_allocs_ctr);
4102 register_counter ("Event: GC moves", &gc_moves_ctr);
4103 register_counter ("Event: GC handle creations", &gc_handle_creations_ctr);
4104 register_counter ("Event: GC handle deletions", &gc_handle_deletions_ctr);
4105 register_counter ("Event: GC finalize starts", &finalize_begins_ctr);
4106 register_counter ("Event: GC finalize ends", &finalize_ends_ctr);
4107 register_counter ("Event: GC finalize object starts", &finalize_object_begins_ctr);
4108 register_counter ("Event: GC finalize object ends", &finalize_object_ends_ctr);
4109 register_counter ("Event: Image loads", &image_loads_ctr);
4110 register_counter ("Event: Image unloads", &image_unloads_ctr);
4111 register_counter ("Event: Assembly loads", &assembly_loads_ctr);
4112 register_counter ("Event: Assembly unloads", &assembly_unloads_ctr);
4113 register_counter ("Event: Class loads", &class_loads_ctr);
4114 register_counter ("Event: Class unloads", &class_unloads_ctr);
4115 register_counter ("Event: Method entries", &method_entries_ctr);
4116 register_counter ("Event: Method exits", &method_exits_ctr);
4117 register_counter ("Event: Method exception leaves", &method_exception_exits_ctr);
4118 register_counter ("Event: Method JITs", &method_jits_ctr);
4119 register_counter ("Event: Code buffers", &code_buffers_ctr);
4120 register_counter ("Event: Exception throws", &exception_throws_ctr);
4121 register_counter ("Event: Exception clauses", &exception_clauses_ctr);
4122 register_counter ("Event: Monitor events", &monitor_events_ctr);
4123 register_counter ("Event: Thread starts", &thread_starts_ctr);
4124 register_counter ("Event: Thread ends", &thread_ends_ctr);
4125 register_counter ("Event: Thread names", &thread_names_ctr);
4126 register_counter ("Event: Domain loads", &domain_loads_ctr);
4127 register_counter ("Event: Domain unloads", &domain_unloads_ctr);
4128 register_counter ("Event: Domain names", &domain_names_ctr);
4129 register_counter ("Event: Context loads", &context_loads_ctr);
4130 register_counter ("Event: Context unloads", &context_unloads_ctr);
4131 register_counter ("Event: Sample binaries", &sample_ubins_ctr);
4132 register_counter ("Event: Sample symbols", &sample_usyms_ctr);
4133 register_counter ("Event: Sample hits", &sample_hits_ctr);
4134 register_counter ("Event: Counter descriptors", &counter_descriptors_ctr);
4135 register_counter ("Event: Counter samples", &counter_samples_ctr);
4136 register_counter ("Event: Performance counter descriptors", &perfcounter_descriptors_ctr);
4137 register_counter ("Event: Performance counter samples", &perfcounter_samples_ctr);
4138 register_counter ("Event: Coverage methods", &coverage_methods_ctr);
4139 register_counter ("Event: Coverage statements", &coverage_statements_ctr);
4140 register_counter ("Event: Coverage classes", &coverage_classes_ctr);
4141 register_counter ("Event: Coverage assemblies", &coverage_assemblies_ctr);
4146 * We must start the helper thread before the writer thread. This is
4147 * because the helper thread sets up the command port which is written to
4148 * the log header by the writer thread.
4150 start_helper_thread ();
4151 start_writer_thread ();
4152 start_dumper_thread ();
4156 create_profiler (const char *args, const char *filename, GPtrArray *filters)
4160 log_profiler.args = pstrdup (args);
4161 log_profiler.command_port = log_config.command_port;
4163 //If filename begin with +, append the pid at the end
4164 if (filename && *filename == '+')
4165 filename = g_strdup_printf ("%s.%d", filename + 1, getpid ());
4168 if (log_config.do_report)
4169 filename = "|mprof-report -";
4171 filename = "output.mlpd";
4172 nf = (char*)filename;
4174 nf = new_filename (filename);
4175 if (log_config.do_report) {
4176 int s = strlen (nf) + 32;
4177 char *p = (char *) g_malloc (s);
4178 snprintf (p, s, "|mprof-report '--out=%s' -", nf);
4184 log_profiler.file = popen (nf + 1, "w");
4185 log_profiler.pipe_output = 1;
4186 } else if (*nf == '#') {
4187 int fd = strtol (nf + 1, NULL, 10);
4188 log_profiler.file = fdopen (fd, "a");
4190 log_profiler.file = fopen (nf, "wb");
4192 if (!log_profiler.file) {
4193 mono_profiler_printf_err ("Could not create log profiler output file '%s'.", nf);
4197 #if defined (HAVE_SYS_ZLIB)
4198 if (log_config.use_zip)
4199 log_profiler.gzfile = gzdopen (fileno (log_profiler.file), "wb");
4203 * If you hit this assert while increasing MAX_FRAMES, you need to increase
4204 * SAMPLE_BLOCK_SIZE as well.
4206 g_assert (SAMPLE_SLOT_SIZE (MAX_FRAMES) * 2 < LOCK_FREE_ALLOC_SB_USABLE_SIZE (SAMPLE_BLOCK_SIZE));
4208 // FIXME: We should free this stuff too.
4209 mono_lock_free_allocator_init_size_class (&log_profiler.sample_size_class, SAMPLE_SLOT_SIZE (log_config.num_frames), SAMPLE_BLOCK_SIZE);
4210 mono_lock_free_allocator_init_allocator (&log_profiler.sample_allocator, &log_profiler.sample_size_class, MONO_MEM_ACCOUNT_PROFILER);
4212 mono_lock_free_queue_init (&log_profiler.sample_reuse_queue);
4214 g_assert (sizeof (WriterQueueEntry) * 2 < LOCK_FREE_ALLOC_SB_USABLE_SIZE (WRITER_ENTRY_BLOCK_SIZE));
4216 // FIXME: We should free this stuff too.
4217 mono_lock_free_allocator_init_size_class (&log_profiler.writer_entry_size_class, sizeof (WriterQueueEntry), WRITER_ENTRY_BLOCK_SIZE);
4218 mono_lock_free_allocator_init_allocator (&log_profiler.writer_entry_allocator, &log_profiler.writer_entry_size_class, MONO_MEM_ACCOUNT_PROFILER);
4220 mono_lock_free_queue_init (&log_profiler.writer_queue);
4221 mono_os_sem_init (&log_profiler.writer_queue_sem, 0);
4223 mono_lock_free_queue_init (&log_profiler.dumper_queue);
4224 mono_os_sem_init (&log_profiler.dumper_queue_sem, 0);
4226 mono_os_mutex_init (&log_profiler.method_table_mutex);
4227 log_profiler.method_table = mono_conc_hashtable_new (NULL, NULL);
4229 if (log_config.collect_coverage)
4232 log_profiler.coverage_filters = filters;
4234 log_profiler.startup_time = current_time ();
4238 * declaration to silence the compiler: this is the entry point that
4239 * mono will load from the shared library and call.
4242 mono_profiler_init (const char *desc);
4245 mono_profiler_init_log (const char *desc);
4248 * this is the entry point that will be used when the profiler
4249 * is embedded inside the main executable.
4252 mono_profiler_init_log (const char *desc)
4254 mono_profiler_init (desc);
4258 mono_profiler_init (const char *desc)
4260 GPtrArray *filters = NULL;
4262 proflog_parse_args (&log_config, desc [3] == ':' ? desc + 4 : "");
4264 if (log_config.cov_filter_files) {
4265 filters = g_ptr_array_new ();
4267 for (i = 0; i < log_config.cov_filter_files->len; ++i) {
4268 const char *name = log_config.cov_filter_files->pdata [i];
4269 parse_cov_filter_file (filters, name);
4277 create_profiler (desc, log_config.output_filename, filters);
4279 mono_lls_init (&log_profiler.profiler_thread_list, NULL);
4281 MonoProfilerHandle handle = log_profiler.handle = mono_profiler_install (&log_profiler);
4284 * Required callbacks. These are either necessary for the profiler itself
4285 * to function, or provide metadata that's needed if other events (e.g.
4286 * allocations, exceptions) are dynamically enabled/disabled.
4289 mono_profiler_set_runtime_shutdown_end_callback (handle, log_shutdown);
4290 mono_profiler_set_runtime_initialized_callback (handle, runtime_initialized);
4292 mono_profiler_set_gc_event_callback (handle, gc_event);
4294 mono_profiler_set_thread_started_callback (handle, thread_start);
4295 mono_profiler_set_thread_stopped_callback (handle, thread_end);
4296 mono_profiler_set_thread_name_callback (handle, thread_name);
4298 mono_profiler_set_domain_loaded_callback (handle, domain_loaded);
4299 mono_profiler_set_domain_unloading_callback (handle, domain_unloaded);
4300 mono_profiler_set_domain_name_callback (handle, domain_name);
4302 mono_profiler_set_context_loaded_callback (handle, context_loaded);
4303 mono_profiler_set_context_unloaded_callback (handle, context_unloaded);
4305 mono_profiler_set_assembly_loaded_callback (handle, assembly_loaded);
4306 mono_profiler_set_assembly_unloading_callback (handle, assembly_unloaded);
4308 mono_profiler_set_image_loaded_callback (handle, image_loaded);
4309 mono_profiler_set_image_unloading_callback (handle, image_unloaded);
4311 mono_profiler_set_class_loaded_callback (handle, class_loaded);
4313 mono_profiler_set_jit_done_callback (handle, method_jitted);
4315 if (ENABLED (PROFLOG_EXCEPTION_EVENTS)) {
4316 mono_profiler_set_exception_throw_callback (handle, throw_exc);
4317 mono_profiler_set_exception_clause_callback (handle, clause_exc);
4320 if (ENABLED (PROFLOG_MONITOR_EVENTS)) {
4321 mono_profiler_set_monitor_contention_callback (handle, monitor_contention);
4322 mono_profiler_set_monitor_acquired_callback (handle, monitor_acquired);
4323 mono_profiler_set_monitor_failed_callback (handle, monitor_failed);
4326 if (ENABLED (PROFLOG_GC_EVENTS))
4327 mono_profiler_set_gc_resize_callback (handle, gc_resize);
4329 if (ENABLED (PROFLOG_GC_ALLOCATION_EVENTS)) {
4330 mono_profiler_enable_allocations ();
4331 mono_profiler_set_gc_allocation_callback (handle, gc_alloc);
4334 if (ENABLED (PROFLOG_GC_MOVE_EVENTS))
4335 mono_profiler_set_gc_moves_callback (handle, gc_moves);
4337 if (ENABLED (PROFLOG_GC_ROOT_EVENTS))
4338 mono_profiler_set_gc_roots_callback (handle, gc_roots);
4340 if (ENABLED (PROFLOG_GC_HANDLE_EVENTS)) {
4341 mono_profiler_set_gc_handle_created_callback (handle, gc_handle_created);
4342 mono_profiler_set_gc_handle_deleted_callback (handle, gc_handle_deleted);
4345 if (ENABLED (PROFLOG_FINALIZATION_EVENTS)) {
4346 mono_profiler_set_gc_finalizing_callback (handle, finalize_begin);
4347 mono_profiler_set_gc_finalized_callback (handle, finalize_end);
4348 mono_profiler_set_gc_finalizing_object_callback (handle, finalize_object_begin);
4349 mono_profiler_set_gc_finalized_object_callback (handle, finalize_object_end);
4350 } else if (log_config.hs_mode == MONO_PROFILER_HEAPSHOT_ON_DEMAND) {
4351 //On Demand heapshot uses the finalizer thread to force a collection and thus a heapshot
4352 mono_profiler_set_gc_finalized_callback (handle, finalize_end);
4355 if (ENABLED (PROFLOG_SAMPLE_EVENTS))
4356 mono_profiler_set_sample_hit_callback (handle, mono_sample_hit);
4358 if (ENABLED (PROFLOG_JIT_EVENTS))
4359 mono_profiler_set_jit_code_buffer_callback (handle, code_buffer_new);
4361 if (log_config.enter_leave) {
4362 mono_profiler_set_call_instrumentation_filter_callback (handle, method_filter);
4363 mono_profiler_set_method_enter_callback (handle, method_enter);
4364 mono_profiler_set_method_leave_callback (handle, method_leave);
4365 mono_profiler_set_method_exception_leave_callback (handle, method_exc_leave);
4368 if (log_config.collect_coverage)
4369 mono_profiler_set_coverage_filter_callback (handle, coverage_filter);
4371 mono_profiler_enable_sampling (handle);
4374 * If no sample option was given by the user, this just leaves the sampling
4375 * thread in idle mode. We do this even if no option was given so that we
4376 * can warn if another profiler controls sampling parameters.
4378 if (!mono_profiler_set_sample_mode (handle, log_config.sampling_mode, log_config.sample_freq))
4379 mono_profiler_printf_err ("Another profiler controls sampling parameters; the log profiler will not be able to modify them.");