2 * mono-profiler-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-linked-list-set.h>
27 #include <mono/utils/mono-membar.h>
28 #include <mono/utils/mono-mmap.h>
29 #include <mono/utils/mono-os-mutex.h>
30 #include <mono/utils/mono-os-semaphore.h>
31 #include <mono/utils/mono-threads.h>
32 #include <mono/utils/mono-threads-api.h>
45 #if defined(__APPLE__)
46 #include <mach/mach_time.h>
48 #include <netinet/in.h>
49 #ifdef HAVE_SYS_MMAN_H
52 #include <sys/socket.h>
53 #if defined (HAVE_SYS_ZLIB)
57 #define BUFFER_SIZE (4096 * 16)
59 /* Worst-case size in bytes of a 64-bit value encoded with LEB128. */
60 #define LEB128_SIZE 10
62 /* Size of a value encoded as a single byte. */
63 #undef BYTE_SIZE // mach/i386/vm_param.h on OS X defines this to 8, but it isn't used for anything.
66 /* Size in bytes of the event prefix (ID + time). */
67 #define EVENT_SIZE (BYTE_SIZE + LEB128_SIZE)
69 static volatile gint32 runtime_inited;
70 static volatile gint32 in_shutdown;
72 static ProfilerConfig config;
73 static int nocalls = 0;
74 static int notraces = 0;
75 static int use_zip = 0;
76 static int do_report = 0;
77 static int do_heap_shot = 0;
78 static int max_call_depth = 0;
79 static int command_port = 0;
80 static int heapshot_requested = 0;
81 static int do_mono_sample = 0;
82 static int do_debug = 0;
83 static int do_coverage = 0;
84 static gboolean no_counters = FALSE;
85 static gboolean only_coverage = FALSE;
86 static gboolean debug_coverage = FALSE;
87 static int max_allocated_sample_hits;
89 #define ENABLED(EVT) (config.effective_mask & (EVT))
91 // Statistics for internal profiler data structures.
92 static gint32 sample_allocations_ctr,
93 buffer_allocations_ctr;
95 // Statistics for profiler events.
96 static gint32 sync_points_ctr,
105 gc_handle_creations_ctr,
106 gc_handle_deletions_ctr,
109 finalize_object_begins_ctr,
110 finalize_object_ends_ctr,
114 assembly_unloads_ctr,
119 method_exception_exits_ctr,
122 exception_throws_ctr,
123 exception_clauses_ctr,
136 counter_descriptors_ctr,
138 perfcounter_descriptors_ctr,
139 perfcounter_samples_ctr,
140 coverage_methods_ctr,
141 coverage_statements_ctr,
142 coverage_classes_ctr,
143 coverage_assemblies_ctr;
145 static MonoLinkedListSet profiler_thread_list;
151 * The file is composed by a header followed by 0 or more buffers.
152 * Each buffer contains events that happened on a thread: for a given thread
153 * buffers that appear later in the file are guaranteed to contain events
154 * that happened later in time. Buffers from separate threads could be interleaved,
156 * Buffers are not required to be aligned.
159 * [id: 4 bytes] constant value: LOG_HEADER_ID
160 * [major: 1 byte] [minor: 1 byte] major and minor version of the log profiler
161 * [format: 1 byte] version of the data format for the rest of the file
162 * [ptrsize: 1 byte] size in bytes of a pointer in the profiled program
163 * [startup time: 8 bytes] time in milliseconds since the unix epoch when the program started
164 * [timer overhead: 4 bytes] approximate overhead in nanoseconds of the timer
165 * [flags: 4 bytes] file format flags, should be 0 for now
166 * [pid: 4 bytes] pid of the profiled process
167 * [port: 2 bytes] tcp port for server if != 0
168 * [args size: 4 bytes] size of args
169 * [args: string] arguments passed to the profiler
170 * [arch size: 4 bytes] size of arch
171 * [arch: string] architecture the profiler is running on
172 * [os size: 4 bytes] size of os
173 * [os: string] operating system the profiler is running on
175 * The multiple byte integers are in little-endian format.
178 * [buffer header] [event]*
179 * Buffers have a fixed-size header followed by 0 or more bytes of event data.
180 * Timing information and other values in the event data are usually stored
181 * as uleb128 or sleb128 integers. To save space, as noted for each item below,
182 * some data is represented as a difference between the actual value and
183 * either the last value of the same type (like for timing information) or
184 * as the difference from a value stored in a buffer header.
186 * For timing information the data is stored as uleb128, since timing
187 * increases in a monotonic way in each thread: the value is the number of
188 * nanoseconds to add to the last seen timing data in a buffer. The first value
189 * in a buffer will be calculated from the time_base field in the buffer head.
191 * Object or heap sizes are stored as uleb128.
192 * Pointer differences are stored as sleb128, instead.
194 * If an unexpected value is found, the rest of the buffer should be ignored,
195 * as generally the later values need the former to be interpreted correctly.
197 * buffer header format:
198 * [bufid: 4 bytes] constant value: BUF_ID
199 * [len: 4 bytes] size of the data following the buffer header
200 * [time_base: 8 bytes] time base in nanoseconds since an unspecified epoch
201 * [ptr_base: 8 bytes] base value for pointers
202 * [obj_base: 8 bytes] base value for object addresses
203 * [thread id: 8 bytes] system-specific thread ID (pthread_t for example)
204 * [method_base: 8 bytes] base value for MonoMethod pointers
207 * [extended info: upper 4 bits] [type: lower 4 bits]
208 * [time diff: uleb128] nanoseconds since last timing
210 * The data that follows depends on type and the extended info.
211 * Type is one of the enum values in mono-profiler-log.h: TYPE_ALLOC, TYPE_GC,
212 * TYPE_METADATA, TYPE_METHOD, TYPE_EXCEPTION, TYPE_MONITOR, TYPE_HEAP.
213 * The extended info bits are interpreted based on type, see
214 * each individual event description below.
215 * strings are represented as a 0-terminated utf8 sequence.
218 * [num: uleb128] number of frames following
219 * [frame: sleb128]* mum MonoMethod* as a pointer difference from the last such
220 * pointer or the buffer method_base
224 * exinfo: zero or TYPE_ALLOC_BT
225 * [ptr: sleb128] class as a byte difference from ptr_base
226 * [obj: sleb128] object address as a byte difference from obj_base
227 * [size: uleb128] size of the object in the heap
228 * If exinfo == TYPE_ALLOC_BT, a backtrace follows.
232 * exinfo: one of TYPE_GC_EVENT, TYPE_GC_RESIZE, TYPE_GC_MOVE, TYPE_GC_HANDLE_CREATED[_BT],
233 * TYPE_GC_HANDLE_DESTROYED[_BT], TYPE_GC_FINALIZE_START, TYPE_GC_FINALIZE_END,
234 * TYPE_GC_FINALIZE_OBJECT_START, TYPE_GC_FINALIZE_OBJECT_END
235 * if exinfo == TYPE_GC_RESIZE
236 * [heap_size: uleb128] new heap size
237 * if exinfo == TYPE_GC_EVENT
238 * [event type: byte] GC event (MONO_GC_EVENT_* from profiler.h)
239 * [generation: byte] GC generation event refers to
240 * if exinfo == TYPE_GC_MOVE
241 * [num_objects: uleb128] number of object moves that follow
242 * [objaddr: sleb128]+ num_objects object pointer differences from obj_base
243 * num is always an even number: the even items are the old
244 * addresses, the odd numbers are the respective new object addresses
245 * if exinfo == TYPE_GC_HANDLE_CREATED[_BT]
246 * [handle_type: uleb128] GC handle type (System.Runtime.InteropServices.GCHandleType)
247 * upper bits reserved as flags
248 * [handle: uleb128] GC handle value
249 * [objaddr: sleb128] object pointer differences from obj_base
250 * If exinfo == TYPE_GC_HANDLE_CREATED_BT, a backtrace follows.
251 * if exinfo == TYPE_GC_HANDLE_DESTROYED[_BT]
252 * [handle_type: uleb128] GC handle type (System.Runtime.InteropServices.GCHandleType)
253 * upper bits reserved as flags
254 * [handle: uleb128] GC handle value
255 * If exinfo == TYPE_GC_HANDLE_DESTROYED_BT, a backtrace follows.
256 * if exinfo == TYPE_GC_FINALIZE_OBJECT_{START,END}
257 * [object: sleb128] the object as a difference from obj_base
259 * type metadata format:
260 * type: TYPE_METADATA
261 * exinfo: one of: TYPE_END_LOAD, TYPE_END_UNLOAD (optional for TYPE_THREAD and TYPE_DOMAIN,
262 * doesn't occur for TYPE_CLASS)
263 * [mtype: byte] metadata type, one of: TYPE_CLASS, TYPE_IMAGE, TYPE_ASSEMBLY, TYPE_DOMAIN,
264 * TYPE_THREAD, TYPE_CONTEXT
265 * [pointer: sleb128] pointer of the metadata type depending on mtype
266 * if mtype == TYPE_CLASS
267 * [image: sleb128] MonoImage* as a pointer difference from ptr_base
268 * [name: string] full class name
269 * if mtype == TYPE_IMAGE
270 * [name: string] image file name
271 * if mtype == TYPE_ASSEMBLY
272 * [image: sleb128] MonoImage* as a pointer difference from ptr_base
273 * [name: string] assembly name
274 * if mtype == TYPE_DOMAIN && exinfo == 0
275 * [name: string] domain friendly name
276 * if mtype == TYPE_CONTEXT
277 * [domain: sleb128] domain id as pointer
278 * if mtype == TYPE_THREAD && exinfo == 0
279 * [name: string] thread name
281 * type method format:
283 * exinfo: one of: TYPE_LEAVE, TYPE_ENTER, TYPE_EXC_LEAVE, TYPE_JIT
284 * [method: sleb128] MonoMethod* as a pointer difference from the last such
285 * pointer or the buffer method_base
286 * if exinfo == TYPE_JIT
287 * [code address: sleb128] pointer to the native code as a diff from ptr_base
288 * [code size: uleb128] size of the generated code
289 * [name: string] full method name
291 * type exception format:
292 * type: TYPE_EXCEPTION
293 * exinfo: zero, TYPE_CLAUSE, or TYPE_THROW_BT
294 * if exinfo == TYPE_CLAUSE
295 * [clause type: byte] MonoExceptionEnum enum value
296 * [clause index: uleb128] index of the current clause
297 * [method: sleb128] MonoMethod* as a pointer difference from the last such
298 * pointer or the buffer method_base
299 * [object: sleb128] the exception object as a difference from obj_base
301 * [object: sleb128] the exception object as a difference from obj_base
302 * If exinfo == TYPE_THROW_BT, a backtrace follows.
304 * type runtime format:
306 * exinfo: one of: TYPE_JITHELPER
307 * if exinfo == TYPE_JITHELPER
308 * [type: byte] MonoProfilerCodeBufferType enum value
309 * [buffer address: sleb128] pointer to the native code as a diff from ptr_base
310 * [buffer size: uleb128] size of the generated code
311 * if type == MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE
312 * [name: string] buffer description name
314 * type monitor format:
316 * exinfo: zero or TYPE_MONITOR_BT
317 * [type: byte] MONO_PROFILER_MONITOR_{CONTENTION,FAIL,DONE}
318 * [object: sleb128] the lock object as a difference from obj_base
319 * If exinfo == TYPE_MONITOR_BT, a backtrace follows.
323 * exinfo: one of TYPE_HEAP_START, TYPE_HEAP_END, TYPE_HEAP_OBJECT, TYPE_HEAP_ROOT
324 * if exinfo == TYPE_HEAP_OBJECT
325 * [object: sleb128] the object as a difference from obj_base
326 * [class: sleb128] the object MonoClass* as a difference from ptr_base
327 * [size: uleb128] size of the object on the heap
328 * [num_refs: uleb128] number of object references
329 * each referenced objref is preceded by a uleb128 encoded offset: the
330 * first offset is from the object address and each next offset is relative
331 * to the previous one
332 * [objrefs: sleb128]+ object referenced as a difference from obj_base
333 * The same object can appear multiple times, but only the first time
334 * with size != 0: in the other cases this data will only be used to
335 * provide additional referenced objects.
336 * if exinfo == TYPE_HEAP_ROOT
337 * [num_roots: uleb128] number of root references
338 * [num_gc: uleb128] number of major gcs
339 * [object: sleb128] the object as a difference from obj_base
340 * [root_type: byte] the root_type: MonoProfileGCRootType (profiler.h)
341 * [extra_info: uleb128] the extra_info value
342 * object, root_type and extra_info are repeated num_roots times
346 * exinfo: one of TYPE_SAMPLE_HIT, TYPE_SAMPLE_USYM, TYPE_SAMPLE_UBIN, TYPE_SAMPLE_COUNTERS_DESC, TYPE_SAMPLE_COUNTERS
347 * if exinfo == TYPE_SAMPLE_HIT
348 * [thread: sleb128] thread id as difference from ptr_base
349 * [count: uleb128] number of following instruction addresses
350 * [ip: sleb128]* instruction pointer as difference from ptr_base
351 * [mbt_count: uleb128] number of managed backtrace frames
352 * [method: sleb128]* MonoMethod* as a pointer difference from the last such
353 * pointer or the buffer method_base (the first such method can be also indentified by ip, but this is not neccessarily true)
354 * if exinfo == TYPE_SAMPLE_USYM
355 * [address: sleb128] symbol address as a difference from ptr_base
356 * [size: uleb128] symbol size (may be 0 if unknown)
357 * [name: string] symbol name
358 * if exinfo == TYPE_SAMPLE_UBIN
359 * [address: sleb128] address where binary has been loaded as a difference from ptr_base
360 * [offset: uleb128] file offset of mapping (the same file can be mapped multiple times)
361 * [size: uleb128] memory size
362 * [name: string] binary name
363 * if exinfo == TYPE_SAMPLE_COUNTERS_DESC
364 * [len: uleb128] number of counters
366 * [section: uleb128] section of counter
367 * if section == MONO_COUNTER_PERFCOUNTERS:
368 * [section_name: string] section name of counter
369 * [name: string] name of counter
370 * [type: byte] type of counter
371 * [unit: byte] unit of counter
372 * [variance: byte] variance of counter
373 * [index: uleb128] unique index of counter
374 * if exinfo == TYPE_SAMPLE_COUNTERS
376 * [index: uleb128] unique index of counter
379 * [type: byte] type of counter value
382 * [0: byte] 0 -> value is null
384 * [1: byte] 1 -> value is not null
385 * [value: string] counter value
387 * [value: uleb128/sleb128/double] counter value, can be sleb128, uleb128 or double (determined by using type)
389 * type coverage format
390 * type: TYPE_COVERAGE
391 * exinfo: one of TYPE_COVERAGE_METHOD, TYPE_COVERAGE_STATEMENT, TYPE_COVERAGE_ASSEMBLY, TYPE_COVERAGE_CLASS
392 * if exinfo == TYPE_COVERAGE_METHOD
393 * [assembly: string] name of assembly
394 * [class: string] name of the class
395 * [name: string] name of the method
396 * [signature: string] the signature of the method
397 * [filename: string] the file path of the file that contains this method
398 * [token: uleb128] the method token
399 * [method_id: uleb128] an ID for this data to associate with the buffers of TYPE_COVERAGE_STATEMENTS
400 * [len: uleb128] the number of TYPE_COVERAGE_BUFFERS associated with this method
401 * if exinfo == TYPE_COVERAGE_STATEMENTS
402 * [method_id: uleb128] an the TYPE_COVERAGE_METHOD buffer to associate this with
403 * [offset: uleb128] the il offset relative to the previous offset
404 * [counter: uleb128] the counter for this instruction
405 * [line: uleb128] the line of filename containing this instruction
406 * [column: uleb128] the column containing this instruction
407 * if exinfo == TYPE_COVERAGE_ASSEMBLY
408 * [name: string] assembly name
409 * [guid: string] assembly GUID
410 * [filename: string] assembly filename
411 * [number_of_methods: uleb128] the number of methods in this assembly
412 * [fully_covered: uleb128] the number of fully covered methods
413 * [partially_covered: uleb128] the number of partially covered methods
414 * currently partially_covered will always be 0, and fully_covered is the
415 * number of methods that are fully and partially covered.
416 * if exinfo == TYPE_COVERAGE_CLASS
417 * [name: string] assembly name
418 * [class: string] class name
419 * [number_of_methods: uleb128] the number of methods in this class
420 * [fully_covered: uleb128] the number of fully covered methods
421 * [partially_covered: uleb128] the number of partially covered methods
422 * currently partially_covered will always be 0, and fully_covered is the
423 * number of methods that are fully and partially covered.
427 * exinfo: one of: TYPE_SYNC_POINT
428 * if exinfo == TYPE_SYNC_POINT
429 * [type: byte] MonoProfilerSyncPointType enum value
432 // Pending data to be written to the log, for a single thread.
433 // Threads periodically flush their own LogBuffers by calling safe_send
434 typedef struct _LogBuffer LogBuffer;
436 // Next (older) LogBuffer in processing queue
442 uintptr_t method_base;
443 uintptr_t last_method;
447 // Bytes allocated for this LogBuffer
450 // Start of currently unused space in buffer
451 unsigned char* cursor;
453 // Pointer to start-of-structure-plus-size (for convenience)
454 unsigned char* buf_end;
456 // Start of data in buffer. Contents follow "buffer format" described above.
457 unsigned char buf [1];
461 MonoLinkedListSetNode node;
463 // Convenience pointer to the profiler structure.
464 MonoProfiler *profiler;
466 // Was this thread added to the LLS?
469 // The current log buffer for this thread.
472 // Methods referenced by events in `buffer`, see `MethodInfo`.
475 // Current call depth for enter/leave events.
478 // Indicates whether this thread is currently writing to its `buffer`.
481 // Has this thread written a thread end event to `buffer`?
484 // Stored in `buffer_lock_state` to take the exclusive lock.
486 } MonoProfilerThread;
488 // Do not use these TLS macros directly unless you know what you're doing.
492 #define PROF_TLS_SET(VAL) (TlsSetValue (profiler_tls, (VAL)))
493 #define PROF_TLS_GET() ((MonoProfilerThread *) TlsGetValue (profiler_tls))
494 #define PROF_TLS_INIT() (profiler_tls = TlsAlloc ())
495 #define PROF_TLS_FREE() (TlsFree (profiler_tls))
497 static DWORD profiler_tls;
501 #define PROF_TLS_SET(VAL) (profiler_tls = (VAL))
502 #define PROF_TLS_GET() (profiler_tls)
503 #define PROF_TLS_INIT()
504 #define PROF_TLS_FREE()
506 static __thread MonoProfilerThread *profiler_tls;
510 #define PROF_TLS_SET(VAL) (pthread_setspecific (profiler_tls, (VAL)))
511 #define PROF_TLS_GET() ((MonoProfilerThread *) pthread_getspecific (profiler_tls))
512 #define PROF_TLS_INIT() (pthread_key_create (&profiler_tls, NULL))
513 #define PROF_TLS_FREE() (pthread_key_delete (profiler_tls))
515 static pthread_key_t profiler_tls;
522 return (uintptr_t) mono_native_thread_id_get ();
529 return (uintptr_t) GetCurrentProcessId ();
531 return (uintptr_t) getpid ();
536 static mach_timebase_info_data_t timebase_info;
537 #elif defined (HOST_WIN32)
538 static LARGE_INTEGER pcounter_freq;
541 #define TICKS_PER_SEC 1000000000LL
547 uint64_t time = mach_absolute_time ();
549 time *= timebase_info.numer;
550 time /= timebase_info.denom;
553 #elif defined (HOST_WIN32)
556 QueryPerformanceCounter (&value);
558 return value.QuadPart * TICKS_PER_SEC / pcounter_freq.QuadPart;
559 #elif defined (CLOCK_MONOTONIC)
560 struct timespec tspec;
562 clock_gettime (CLOCK_MONOTONIC, &tspec);
564 return ((uint64_t) tspec.tv_sec * TICKS_PER_SEC + tspec.tv_nsec);
568 gettimeofday (&tv, NULL);
570 return ((uint64_t) tv.tv_sec * TICKS_PER_SEC + tv.tv_usec * 1000);
574 static int timer_overhead;
580 mach_timebase_info (&timebase_info);
581 #elif defined (HOST_WIN32)
582 QueryPerformanceFrequency (&pcounter_freq);
585 uint64_t time_start = current_time ();
587 for (int i = 0; i < 256; ++i)
590 uint64_t time_end = current_time ();
592 timer_overhead = (time_end - time_start) / 256;
596 * These macros should be used when writing an event to a log buffer. They
597 * take care of a bunch of stuff that can be repetitive and error-prone, such
598 * as attaching the current thread, acquiring/releasing the buffer lock,
599 * incrementing the event counter, expanding the log buffer, etc. They also
600 * create a scope so that it's harder to leak the LogBuffer pointer, which can
601 * be problematic as the pointer is unstable when the buffer lock isn't
604 * If the calling thread is already attached, these macros will not alter its
605 * attach mode (i.e. whether it's added to the LLS). If the thread is not
606 * attached, init_thread () will be called with add_to_lls = TRUE.
609 #define ENTER_LOG(COUNTER, BUFFER, SIZE) \
611 MonoProfilerThread *thread__ = get_thread (); \
612 if (thread__->attached) \
614 g_assert (!thread__->busy && "Why are we trying to write a new event while already writing one?"); \
615 thread__->busy = TRUE; \
616 InterlockedIncrement ((COUNTER)); \
617 LogBuffer *BUFFER = ensure_logbuf_unsafe (thread__, (SIZE))
619 #define EXIT_LOG_EXPLICIT(SEND) \
620 thread__->busy = FALSE; \
622 send_log_unsafe (TRUE); \
623 if (thread__->attached) \
627 // Pass these to EXIT_LOG_EXPLICIT () for easier reading.
629 #define NO_SEND FALSE
631 #define EXIT_LOG EXIT_LOG_EXPLICIT (DO_SEND)
633 typedef struct _BinaryObject BinaryObject;
634 struct _BinaryObject {
640 static MonoProfiler *log_profiler;
642 struct _MonoProfiler {
644 #if defined (HAVE_SYS_ZLIB)
648 uint64_t startup_time;
653 MonoNativeThreadId helper_thread;
654 MonoNativeThreadId writer_thread;
655 MonoNativeThreadId dumper_thread;
656 volatile gint32 run_writer_thread;
657 MonoLockFreeAllocSizeClass writer_entry_size_class;
658 MonoLockFreeAllocator writer_entry_allocator;
659 MonoLockFreeQueue writer_queue;
660 MonoSemType writer_queue_sem;
661 MonoConcurrentHashTable *method_table;
662 mono_mutex_t method_table_mutex;
663 volatile gint32 run_dumper_thread;
664 MonoLockFreeQueue dumper_queue;
665 MonoSemType dumper_queue_sem;
666 MonoLockFreeAllocSizeClass sample_size_class;
667 MonoLockFreeAllocator sample_allocator;
668 MonoLockFreeQueue sample_reuse_queue;
669 BinaryObject *binary_objects;
670 GPtrArray *coverage_filters;
674 MonoLockFreeQueueNode node;
679 #define WRITER_ENTRY_BLOCK_SIZE (mono_pagesize ())
688 pstrdup (const char *s)
690 int len = strlen (s) + 1;
691 char *p = (char *) g_malloc (len);
697 alloc_buffer (int size)
699 return mono_valloc (NULL, size, MONO_MMAP_READ | MONO_MMAP_WRITE | MONO_MMAP_ANON | MONO_MMAP_PRIVATE, MONO_MEM_ACCOUNT_PROFILER);
703 free_buffer (void *buf, int size)
705 mono_vfree (buf, size, MONO_MEM_ACCOUNT_PROFILER);
709 create_buffer (uintptr_t tid, int bytes)
711 LogBuffer* buf = (LogBuffer *) alloc_buffer (MAX (BUFFER_SIZE, bytes));
713 InterlockedIncrement (&buffer_allocations_ctr);
715 buf->size = BUFFER_SIZE;
716 buf->time_base = current_time ();
717 buf->last_time = buf->time_base;
718 buf->buf_end = (unsigned char *) buf + buf->size;
719 buf->cursor = buf->buf;
720 buf->thread_id = tid;
726 * Must be called with the reader lock held if thread is the current thread, or
727 * the exclusive lock if thread is a different thread. However, if thread is
728 * the current thread, and init_thread () was called with add_to_lls = FALSE,
729 * then no locking is necessary.
732 init_buffer_state (MonoProfilerThread *thread)
734 thread->buffer = create_buffer (thread->node.key, 0);
735 thread->methods = NULL;
739 clear_hazard_pointers (MonoThreadHazardPointers *hp)
741 mono_hazard_pointer_clear (hp, 0);
742 mono_hazard_pointer_clear (hp, 1);
743 mono_hazard_pointer_clear (hp, 2);
746 static MonoProfilerThread *
747 init_thread (MonoProfiler *prof, gboolean add_to_lls)
749 MonoProfilerThread *thread = PROF_TLS_GET ();
752 * Sometimes we may try to initialize a thread twice. One example is the
753 * main thread: We initialize it when setting up the profiler, but we will
754 * also get a thread_start () callback for it. Another example is when
755 * attaching new threads to the runtime: We may get a gc_alloc () callback
756 * for that thread's thread object (where we initialize it), soon followed
757 * by a thread_start () callback.
759 * These cases are harmless anyhow. Just return if we've already done the
760 * initialization work.
765 thread = g_malloc (sizeof (MonoProfilerThread));
766 thread->node.key = thread_id ();
767 thread->profiler = prof;
768 thread->attached = add_to_lls;
769 thread->call_depth = 0;
771 thread->ended = FALSE;
773 init_buffer_state (thread);
775 thread->small_id = mono_thread_info_register_small_id ();
778 * Some internal profiler threads don't need to be cleaned up
779 * by the main thread on shutdown.
782 MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
783 g_assert (mono_lls_insert (&profiler_thread_list, hp, &thread->node) && "Why can't we insert the thread in the LLS?");
784 clear_hazard_pointers (hp);
787 PROF_TLS_SET (thread);
792 // Only valid if init_thread () was called with add_to_lls = FALSE.
794 deinit_thread (MonoProfilerThread *thread)
796 g_assert (!thread->attached && "Why are we manually freeing an attached thread?");
802 static MonoProfilerThread *
805 return init_thread (log_profiler, TRUE);
808 // Only valid if init_thread () was called with add_to_lls = FALSE.
810 ensure_logbuf_unsafe (MonoProfilerThread *thread, int bytes)
812 LogBuffer *old = thread->buffer;
814 if (old->cursor + bytes < old->buf_end)
817 LogBuffer *new_ = create_buffer (thread->node.key, bytes);
819 thread->buffer = new_;
825 * This is a reader/writer spin lock of sorts used to protect log buffers.
826 * When a thread modifies its own log buffer, it increments the reader
827 * count. When a thread wants to access log buffers of other threads, it
828 * takes the exclusive lock.
830 * `buffer_lock_state` holds the reader count in its lower 16 bits, and
831 * the small ID of the thread currently holding the exclusive (writer)
832 * lock in its upper 16 bits. Both can be zero. It's important that the
833 * whole lock state is a single word that can be read/written atomically
834 * to avoid race conditions where there could end up being readers while
835 * the writer lock is held.
837 * The lock is writer-biased. When a thread wants to take the exclusive
838 * lock, it increments `buffer_lock_exclusive_intent` which will make new
839 * readers spin until it's back to zero, then takes the exclusive lock
840 * once the reader count has reached zero. After releasing the exclusive
841 * lock, it decrements `buffer_lock_exclusive_intent`, which, when it
842 * reaches zero again, allows readers to increment the reader count.
844 * The writer bias is necessary because we take the exclusive lock in
845 * `gc_event ()` during STW. If the writer bias was not there, and a
846 * program had a large number of threads, STW-induced pauses could be
847 * significantly longer than they have to be. Also, we emit periodic
848 * sync points from the helper thread, which requires taking the
849 * exclusive lock, and we need those to arrive with a reasonably
850 * consistent frequency so that readers don't have to queue up too many
851 * events between sync points.
853 * The lock does not support recursion.
855 static volatile gint32 buffer_lock_state;
856 static volatile gint32 buffer_lock_exclusive_intent;
862 * If the thread holding the exclusive lock tries to modify the
863 * reader count, just make it a no-op. This way, we also avoid
864 * invoking the GC safe point macros below, which could break if
865 * done from a thread that is currently the initiator of STW.
867 * In other words, we rely on the fact that the GC thread takes
868 * the exclusive lock in the gc_event () callback when the world
871 if (InterlockedRead (&buffer_lock_state) != get_thread ()->small_id << 16) {
878 // Hold off if a thread wants to take the exclusive lock.
879 while (InterlockedRead (&buffer_lock_exclusive_intent))
880 mono_thread_info_yield ();
882 old = InterlockedRead (&buffer_lock_state);
884 // Is a thread holding the exclusive lock?
886 mono_thread_info_yield ();
891 } while (InterlockedCompareExchange (&buffer_lock_state, new_, old) != old);
896 mono_memory_barrier ();
902 mono_memory_barrier ();
904 gint32 state = InterlockedRead (&buffer_lock_state);
906 // See the comment in buffer_lock ().
907 if (state == PROF_TLS_GET ()->small_id << 16)
910 g_assert (state && "Why are we decrementing a zero reader count?");
911 g_assert (!(state >> 16) && "Why is the exclusive lock held?");
913 InterlockedDecrement (&buffer_lock_state);
917 buffer_lock_excl (void)
919 gint32 new_ = get_thread ()->small_id << 16;
921 g_assert (InterlockedRead (&buffer_lock_state) != new_ && "Why are we taking the exclusive lock twice?");
923 InterlockedIncrement (&buffer_lock_exclusive_intent);
927 while (InterlockedCompareExchange (&buffer_lock_state, new_, 0))
928 mono_thread_info_yield ();
932 mono_memory_barrier ();
936 buffer_unlock_excl (void)
938 mono_memory_barrier ();
940 gint32 state = InterlockedRead (&buffer_lock_state);
941 gint32 excl = state >> 16;
943 g_assert (excl && "Why is the exclusive lock not held?");
944 g_assert (excl == PROF_TLS_GET ()->small_id && "Why does another thread hold the exclusive lock?");
945 g_assert (!(state & 0xFFFF) && "Why are there readers when the exclusive lock is held?");
947 InterlockedWrite (&buffer_lock_state, 0);
948 InterlockedDecrement (&buffer_lock_exclusive_intent);
952 encode_uleb128 (uint64_t value, uint8_t *buf, uint8_t **endbuf)
957 uint8_t b = value & 0x7f;
960 if (value != 0) /* more bytes to come */
970 encode_sleb128 (intptr_t value, uint8_t *buf, uint8_t **endbuf)
973 int negative = (value < 0);
974 unsigned int size = sizeof (intptr_t) * 8;
982 /* the following is unnecessary if the
983 * implementation of >>= uses an arithmetic rather
984 * than logical shift for a signed left operand
988 value |= - ((intptr_t) 1 <<(size - 7));
990 /* sign bit of byte is second high order bit (0x40) */
991 if ((value == 0 && !(byte & 0x40)) ||
992 (value == -1 && (byte & 0x40)))
1004 emit_byte (LogBuffer *logbuffer, int value)
1006 logbuffer->cursor [0] = value;
1007 logbuffer->cursor++;
1009 g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
1013 emit_value (LogBuffer *logbuffer, int value)
1015 encode_uleb128 (value, logbuffer->cursor, &logbuffer->cursor);
1017 g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
1021 emit_time (LogBuffer *logbuffer, uint64_t value)
1023 uint64_t tdiff = value - logbuffer->last_time;
1024 encode_uleb128 (tdiff, logbuffer->cursor, &logbuffer->cursor);
1025 logbuffer->last_time = value;
1027 g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
1031 emit_event_time (LogBuffer *logbuffer, int event, uint64_t time)
1033 emit_byte (logbuffer, event);
1034 emit_time (logbuffer, time);
1038 emit_event (LogBuffer *logbuffer, int event)
1040 emit_event_time (logbuffer, event, current_time ());
1044 emit_svalue (LogBuffer *logbuffer, int64_t value)
1046 encode_sleb128 (value, logbuffer->cursor, &logbuffer->cursor);
1048 g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
1052 emit_uvalue (LogBuffer *logbuffer, uint64_t value)
1054 encode_uleb128 (value, logbuffer->cursor, &logbuffer->cursor);
1056 g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
1060 emit_ptr (LogBuffer *logbuffer, void *ptr)
1062 if (!logbuffer->ptr_base)
1063 logbuffer->ptr_base = (uintptr_t) ptr;
1065 emit_svalue (logbuffer, (intptr_t) ptr - logbuffer->ptr_base);
1067 g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
1071 emit_method_inner (LogBuffer *logbuffer, void *method)
1073 if (!logbuffer->method_base) {
1074 logbuffer->method_base = (intptr_t) method;
1075 logbuffer->last_method = (intptr_t) method;
1078 encode_sleb128 ((intptr_t) ((char *) method - (char *) logbuffer->last_method), logbuffer->cursor, &logbuffer->cursor);
1079 logbuffer->last_method = (intptr_t) method;
1081 g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
1084 // The reader lock must be held.
1086 register_method_local (MonoMethod *method, MonoJitInfo *ji)
1088 MonoProfilerThread *thread = get_thread ();
1090 if (!mono_conc_hashtable_lookup (thread->profiler->method_table, method)) {
1091 MethodInfo *info = (MethodInfo *) g_malloc (sizeof (MethodInfo));
1093 info->method = method;
1095 info->time = current_time ();
1097 GPtrArray *arr = thread->methods ? thread->methods : (thread->methods = g_ptr_array_new ());
1098 g_ptr_array_add (arr, info);
1103 emit_method (LogBuffer *logbuffer, MonoMethod *method)
1105 register_method_local (method, NULL);
1106 emit_method_inner (logbuffer, method);
1110 emit_obj (LogBuffer *logbuffer, void *ptr)
1112 if (!logbuffer->obj_base)
1113 logbuffer->obj_base = (uintptr_t) ptr >> 3;
1115 emit_svalue (logbuffer, ((uintptr_t) ptr >> 3) - logbuffer->obj_base);
1117 g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
1121 emit_string (LogBuffer *logbuffer, const char *str, size_t size)
1125 for (; i < size; i++) {
1128 emit_byte (logbuffer, str [i]);
1131 emit_byte (logbuffer, '\0');
1135 emit_double (LogBuffer *logbuffer, double value)
1138 unsigned char buffer[8];
1139 memcpy (buffer, &value, 8);
1140 #if G_BYTE_ORDER == G_BIG_ENDIAN
1141 for (i = 7; i >= 0; i--)
1143 for (i = 0; i < 8; i++)
1145 emit_byte (logbuffer, buffer[i]);
1149 write_int16 (char *buf, int32_t value)
1152 for (i = 0; i < 2; ++i) {
1160 write_int32 (char *buf, int32_t value)
1163 for (i = 0; i < 4; ++i) {
1171 write_int64 (char *buf, int64_t value)
1174 for (i = 0; i < 8; ++i) {
1182 write_header_string (char *p, const char *str)
1184 size_t len = strlen (str) + 1;
1186 p = write_int32 (p, len);
1193 dump_header (MonoProfiler *profiler)
1195 const char *args = profiler->args;
1196 const char *arch = mono_config_get_cpu ();
1197 const char *os = mono_config_get_os ();
1199 char *hbuf = g_malloc (
1200 sizeof (gint32) /* header id */ +
1201 sizeof (gint8) /* major version */ +
1202 sizeof (gint8) /* minor version */ +
1203 sizeof (gint8) /* data version */ +
1204 sizeof (gint8) /* word size */ +
1205 sizeof (gint64) /* startup time */ +
1206 sizeof (gint32) /* timer overhead */ +
1207 sizeof (gint32) /* flags */ +
1208 sizeof (gint32) /* process id */ +
1209 sizeof (gint16) /* command port */ +
1210 sizeof (gint32) + strlen (args) + 1 /* arguments */ +
1211 sizeof (gint32) + strlen (arch) + 1 /* architecture */ +
1212 sizeof (gint32) + strlen (os) + 1 /* operating system */
1216 p = write_int32 (p, LOG_HEADER_ID);
1217 *p++ = LOG_VERSION_MAJOR;
1218 *p++ = LOG_VERSION_MINOR;
1219 *p++ = LOG_DATA_VERSION;
1220 *p++ = sizeof (void *);
1221 p = write_int64 (p, ((uint64_t) time (NULL)) * 1000);
1222 p = write_int32 (p, timer_overhead);
1223 p = write_int32 (p, 0); /* flags */
1224 p = write_int32 (p, process_id ());
1225 p = write_int16 (p, profiler->command_port);
1226 p = write_header_string (p, args);
1227 p = write_header_string (p, arch);
1228 p = write_header_string (p, os);
1230 #if defined (HAVE_SYS_ZLIB)
1231 if (profiler->gzfile) {
1232 gzwrite (profiler->gzfile, hbuf, p - hbuf);
1236 fwrite (hbuf, p - hbuf, 1, profiler->file);
1237 fflush (profiler->file);
1244 * Must be called with the reader lock held if thread is the current thread, or
1245 * the exclusive lock if thread is a different thread. However, if thread is
1246 * the current thread, and init_thread () was called with add_to_lls = FALSE,
1247 * then no locking is necessary.
1250 send_buffer (MonoProfilerThread *thread)
1252 WriterQueueEntry *entry = mono_lock_free_alloc (&thread->profiler->writer_entry_allocator);
1253 entry->methods = thread->methods;
1254 entry->buffer = thread->buffer;
1256 mono_lock_free_queue_node_init (&entry->node, FALSE);
1258 mono_lock_free_queue_enqueue (&thread->profiler->writer_queue, &entry->node);
1259 mono_os_sem_post (&thread->profiler->writer_queue_sem);
1263 free_thread (gpointer p)
1265 MonoProfilerThread *thread = p;
1267 if (!thread->ended) {
1269 * The thread is being cleaned up by the main thread during
1270 * shutdown. This typically happens for internal runtime
1271 * threads. We need to synthesize a thread end event.
1274 InterlockedIncrement (&thread_ends_ctr);
1276 if (ENABLED (PROFLOG_THREAD_EVENTS)) {
1277 LogBuffer *buf = ensure_logbuf_unsafe (thread,
1278 EVENT_SIZE /* event */ +
1279 BYTE_SIZE /* type */ +
1280 LEB128_SIZE /* tid */
1283 emit_event (buf, TYPE_END_UNLOAD | TYPE_METADATA);
1284 emit_byte (buf, TYPE_THREAD);
1285 emit_ptr (buf, (void *) thread->node.key);
1289 send_buffer (thread);
1295 remove_thread (MonoProfilerThread *thread)
1297 MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
1299 if (mono_lls_remove (&profiler_thread_list, hp, &thread->node))
1300 mono_thread_hazardous_try_free (thread, free_thread);
1302 clear_hazard_pointers (hp);
1306 dump_buffer (MonoProfiler *profiler, LogBuffer *buf)
1312 dump_buffer (profiler, buf->next);
1314 if (buf->cursor - buf->buf) {
1315 p = write_int32 (p, BUF_ID);
1316 p = write_int32 (p, buf->cursor - buf->buf);
1317 p = write_int64 (p, buf->time_base);
1318 p = write_int64 (p, buf->ptr_base);
1319 p = write_int64 (p, buf->obj_base);
1320 p = write_int64 (p, buf->thread_id);
1321 p = write_int64 (p, buf->method_base);
1323 #if defined (HAVE_SYS_ZLIB)
1324 if (profiler->gzfile) {
1325 gzwrite (profiler->gzfile, hbuf, p - hbuf);
1326 gzwrite (profiler->gzfile, buf->buf, buf->cursor - buf->buf);
1330 fwrite (hbuf, p - hbuf, 1, profiler->file);
1331 fwrite (buf->buf, buf->cursor - buf->buf, 1, profiler->file);
1332 fflush (profiler->file);
1336 free_buffer (buf, buf->size);
1340 dump_buffer_threadless (MonoProfiler *profiler, LogBuffer *buf)
1342 for (LogBuffer *iter = buf; iter; iter = iter->next)
1343 iter->thread_id = 0;
1345 dump_buffer (profiler, buf);
1348 // Only valid if init_thread () was called with add_to_lls = FALSE.
1350 send_log_unsafe (gboolean if_needed)
1352 MonoProfilerThread *thread = PROF_TLS_GET ();
1354 if (!if_needed || (if_needed && thread->buffer->next)) {
1355 if (!thread->attached)
1356 for (LogBuffer *iter = thread->buffer; iter; iter = iter->next)
1357 iter->thread_id = 0;
1359 send_buffer (thread);
1360 init_buffer_state (thread);
1364 // Assumes that the exclusive lock is held.
1366 sync_point_flush (void)
1368 g_assert (InterlockedRead (&buffer_lock_state) == PROF_TLS_GET ()->small_id << 16 && "Why don't we hold the exclusive lock?");
1370 MONO_LLS_FOREACH_SAFE (&profiler_thread_list, MonoProfilerThread, thread) {
1371 g_assert (thread->attached && "Why is a thread in the LLS not attached?");
1373 send_buffer (thread);
1374 init_buffer_state (thread);
1375 } MONO_LLS_FOREACH_SAFE_END
1378 // Assumes that the exclusive lock is held.
1380 sync_point_mark (MonoProfilerSyncPointType type)
1382 g_assert (InterlockedRead (&buffer_lock_state) == PROF_TLS_GET ()->small_id << 16 && "Why don't we hold the exclusive lock?");
1384 ENTER_LOG (&sync_points_ctr, logbuffer,
1385 EVENT_SIZE /* event */ +
1386 LEB128_SIZE /* type */
1389 emit_event (logbuffer, TYPE_META | TYPE_SYNC_POINT);
1390 emit_byte (logbuffer, type);
1392 EXIT_LOG_EXPLICIT (NO_SEND);
1394 send_log_unsafe (FALSE);
1397 // Assumes that the exclusive lock is held.
1399 sync_point (MonoProfilerSyncPointType type)
1401 sync_point_flush ();
1402 sync_point_mark (type);
1406 gc_reference (MonoObject *obj, MonoClass *klass, uintptr_t size, uintptr_t num, MonoObject **refs, uintptr_t *offsets, void *data)
1408 /* account for object alignment in the heap */
1412 ENTER_LOG (&heap_objects_ctr, logbuffer,
1413 EVENT_SIZE /* event */ +
1414 LEB128_SIZE /* obj */ +
1415 LEB128_SIZE /* klass */ +
1416 LEB128_SIZE /* size */ +
1417 LEB128_SIZE /* num */ +
1419 LEB128_SIZE /* offset */ +
1420 LEB128_SIZE /* ref */
1424 emit_event (logbuffer, TYPE_HEAP_OBJECT | TYPE_HEAP);
1425 emit_obj (logbuffer, obj);
1426 emit_ptr (logbuffer, klass);
1427 emit_value (logbuffer, size);
1428 emit_value (logbuffer, num);
1430 uintptr_t last_offset = 0;
1432 for (int i = 0; i < num; ++i) {
1433 emit_value (logbuffer, offsets [i] - last_offset);
1434 last_offset = offsets [i];
1435 emit_obj (logbuffer, refs [i]);
1438 EXIT_LOG_EXPLICIT (DO_SEND);
1443 static unsigned int hs_mode_ms = 0;
1444 static unsigned int hs_mode_gc = 0;
1445 static unsigned int hs_mode_ondemand = 0;
1446 static unsigned int gc_count = 0;
1447 static uint64_t last_hs_time = 0;
1448 static gboolean do_heap_walk = FALSE;
1449 static gboolean ignore_heap_events;
1452 gc_roots (MonoProfiler *prof, int num, void **objects, int *root_types, uintptr_t *extra_info)
1454 if (ignore_heap_events)
1457 ENTER_LOG (&heap_roots_ctr, logbuffer,
1458 EVENT_SIZE /* event */ +
1459 LEB128_SIZE /* num */ +
1460 LEB128_SIZE /* collections */ +
1462 LEB128_SIZE /* object */ +
1463 LEB128_SIZE /* root type */ +
1464 LEB128_SIZE /* extra info */
1468 emit_event (logbuffer, TYPE_HEAP_ROOT | TYPE_HEAP);
1469 emit_value (logbuffer, num);
1470 emit_value (logbuffer, mono_gc_collection_count (mono_gc_max_generation ()));
1472 for (int i = 0; i < num; ++i) {
1473 emit_obj (logbuffer, objects [i]);
1474 emit_byte (logbuffer, root_types [i]);
1475 emit_value (logbuffer, extra_info [i]);
1478 EXIT_LOG_EXPLICIT (DO_SEND);
1483 trigger_on_demand_heapshot (void)
1485 if (heapshot_requested)
1486 mono_gc_collect (mono_gc_max_generation ());
1489 #define ALL_GC_EVENTS_MASK (PROFLOG_GC_MOVES_EVENTS | PROFLOG_GC_ROOT_EVENTS | PROFLOG_GC_EVENTS | PROFLOG_HEAPSHOT_FEATURE)
1492 gc_event (MonoProfiler *profiler, MonoGCEvent ev, int generation)
1494 if (ev == MONO_GC_EVENT_START) {
1495 uint64_t now = current_time ();
1497 if (hs_mode_ms && (now - last_hs_time) / 1000 * 1000 >= hs_mode_ms)
1498 do_heap_walk = TRUE;
1499 else if (hs_mode_gc && !(gc_count % hs_mode_gc))
1500 do_heap_walk = TRUE;
1501 else if (hs_mode_ondemand)
1502 do_heap_walk = heapshot_requested;
1503 else if (!hs_mode_ms && !hs_mode_gc && generation == mono_gc_max_generation ())
1504 do_heap_walk = TRUE;
1506 //If using heapshot, ignore events for collections we don't care
1507 if (ENABLED (PROFLOG_HEAPSHOT_FEATURE)) {
1508 // Ignore events generated during the collection itself (IE GC ROOTS)
1509 ignore_heap_events = !do_heap_walk;
1514 if (ENABLED (PROFLOG_GC_EVENTS)) {
1515 ENTER_LOG (&gc_events_ctr, logbuffer,
1516 EVENT_SIZE /* event */ +
1517 BYTE_SIZE /* gc event */ +
1518 BYTE_SIZE /* generation */
1521 emit_event (logbuffer, TYPE_GC_EVENT | TYPE_GC);
1522 emit_byte (logbuffer, ev);
1523 emit_byte (logbuffer, generation);
1525 EXIT_LOG_EXPLICIT (NO_SEND);
1529 case MONO_GC_EVENT_START:
1530 if (generation == mono_gc_max_generation ())
1534 case MONO_GC_EVENT_PRE_STOP_WORLD_LOCKED:
1536 * Ensure that no thread can be in the middle of writing to
1537 * a buffer when the world stops...
1539 buffer_lock_excl ();
1541 case MONO_GC_EVENT_POST_STOP_WORLD:
1543 * ... So that we now have a consistent view of all buffers.
1544 * This allows us to flush them. We need to do this because
1545 * they may contain object allocation events that need to be
1546 * committed to the log file before any object move events
1547 * that will be produced during this GC.
1549 if (ENABLED (ALL_GC_EVENTS_MASK))
1550 sync_point (SYNC_POINT_WORLD_STOP);
1553 * All heap events are surrounded by a HEAP_START and a HEAP_ENV event.
1554 * Right now, that's the case for GC Moves, GC Roots or heapshots.
1556 if (ENABLED (PROFLOG_GC_MOVES_EVENTS | PROFLOG_GC_ROOT_EVENTS) || do_heap_walk) {
1557 ENTER_LOG (&heap_starts_ctr, logbuffer,
1558 EVENT_SIZE /* event */
1561 emit_event (logbuffer, TYPE_HEAP_START | TYPE_HEAP);
1563 EXIT_LOG_EXPLICIT (DO_SEND);
1567 case MONO_GC_EVENT_PRE_START_WORLD:
1568 if (do_heap_shot && do_heap_walk)
1569 mono_gc_walk_heap (0, gc_reference, NULL);
1571 /* Matching HEAP_END to the HEAP_START from above */
1572 if (ENABLED (PROFLOG_GC_MOVES_EVENTS | PROFLOG_GC_ROOT_EVENTS) || do_heap_walk) {
1573 ENTER_LOG (&heap_ends_ctr, logbuffer,
1574 EVENT_SIZE /* event */
1577 emit_event (logbuffer, TYPE_HEAP_END | TYPE_HEAP);
1579 EXIT_LOG_EXPLICIT (DO_SEND);
1582 if (do_heap_shot && do_heap_walk) {
1583 do_heap_walk = FALSE;
1584 heapshot_requested = 0;
1585 last_hs_time = current_time ();
1589 * Similarly, we must now make sure that any object moves
1590 * written to the GC thread's buffer are flushed. Otherwise,
1591 * object allocation events for certain addresses could come
1592 * after the move events that made those addresses available.
1594 if (ENABLED (ALL_GC_EVENTS_MASK))
1595 sync_point_mark (SYNC_POINT_WORLD_START);
1597 case MONO_GC_EVENT_POST_START_WORLD_UNLOCKED:
1599 * Finally, it is safe to allow other threads to write to
1600 * their buffers again.
1602 buffer_unlock_excl ();
1610 gc_resize (MonoProfiler *profiler, int64_t new_size)
1612 ENTER_LOG (&gc_resizes_ctr, logbuffer,
1613 EVENT_SIZE /* event */ +
1614 LEB128_SIZE /* new size */
1617 emit_event (logbuffer, TYPE_GC_RESIZE | TYPE_GC);
1618 emit_value (logbuffer, new_size);
1620 EXIT_LOG_EXPLICIT (DO_SEND);
1625 MonoMethod* methods [MAX_FRAMES];
1626 int32_t il_offsets [MAX_FRAMES];
1627 int32_t native_offsets [MAX_FRAMES];
1630 static int num_frames = MAX_FRAMES;
1633 walk_stack (MonoMethod *method, int32_t native_offset, int32_t il_offset, mono_bool managed, void* data)
1635 FrameData *frame = (FrameData *)data;
1636 if (method && frame->count < num_frames) {
1637 frame->il_offsets [frame->count] = il_offset;
1638 frame->native_offsets [frame->count] = native_offset;
1639 frame->methods [frame->count++] = method;
1640 //printf ("In %d %s at %d (native: %d)\n", frame->count, mono_method_get_name (method), il_offset, native_offset);
1642 return frame->count == num_frames;
1646 * a note about stack walks: they can cause more profiler events to fire,
1647 * so we need to make sure they don't happen after we started emitting an
1648 * event, hence the collect_bt/emit_bt split.
1651 collect_bt (FrameData *data)
1654 mono_stack_walk_no_il (walk_stack, data);
1658 emit_bt (MonoProfiler *prof, LogBuffer *logbuffer, FrameData *data)
1660 if (data->count > num_frames)
1661 printf ("bad num frames: %d\n", data->count);
1663 emit_value (logbuffer, data->count);
1666 emit_method (logbuffer, data->methods [--data->count]);
1670 gc_alloc (MonoProfiler *prof, MonoObject *obj, MonoClass *klass)
1672 int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces) ? TYPE_ALLOC_BT : 0;
1674 uintptr_t len = mono_object_get_size (obj);
1675 /* account for object alignment in the heap */
1682 ENTER_LOG (&gc_allocs_ctr, logbuffer,
1683 EVENT_SIZE /* event */ +
1684 LEB128_SIZE /* klass */ +
1685 LEB128_SIZE /* obj */ +
1686 LEB128_SIZE /* size */ +
1688 LEB128_SIZE /* count */ +
1690 LEB128_SIZE /* method */
1695 emit_event (logbuffer, do_bt | TYPE_ALLOC);
1696 emit_ptr (logbuffer, klass);
1697 emit_obj (logbuffer, obj);
1698 emit_value (logbuffer, len);
1701 emit_bt (prof, logbuffer, &data);
1707 gc_moves (MonoProfiler *prof, void **objects, int num)
1709 ENTER_LOG (&gc_moves_ctr, logbuffer,
1710 EVENT_SIZE /* event */ +
1711 LEB128_SIZE /* num */ +
1713 LEB128_SIZE /* object */
1717 emit_event (logbuffer, TYPE_GC_MOVE | TYPE_GC);
1718 emit_value (logbuffer, num);
1720 for (int i = 0; i < num; ++i)
1721 emit_obj (logbuffer, objects [i]);
1723 EXIT_LOG_EXPLICIT (DO_SEND);
1727 gc_handle (MonoProfiler *prof, int op, int type, uintptr_t handle, MonoObject *obj)
1729 int do_bt = nocalls && InterlockedRead (&runtime_inited) && !notraces;
1735 gint32 *ctr = op == MONO_PROFILER_GC_HANDLE_CREATED ? &gc_handle_creations_ctr : &gc_handle_deletions_ctr;
1737 ENTER_LOG (ctr, logbuffer,
1738 EVENT_SIZE /* event */ +
1739 LEB128_SIZE /* type */ +
1740 LEB128_SIZE /* handle */ +
1741 (op == MONO_PROFILER_GC_HANDLE_CREATED ? (
1742 LEB128_SIZE /* obj */
1745 LEB128_SIZE /* count */ +
1747 LEB128_SIZE /* method */
1752 if (op == MONO_PROFILER_GC_HANDLE_CREATED)
1753 emit_event (logbuffer, (do_bt ? TYPE_GC_HANDLE_CREATED_BT : TYPE_GC_HANDLE_CREATED) | TYPE_GC);
1754 else if (op == MONO_PROFILER_GC_HANDLE_DESTROYED)
1755 emit_event (logbuffer, (do_bt ? TYPE_GC_HANDLE_DESTROYED_BT : TYPE_GC_HANDLE_DESTROYED) | TYPE_GC);
1757 g_assert_not_reached ();
1759 emit_value (logbuffer, type);
1760 emit_value (logbuffer, handle);
1762 if (op == MONO_PROFILER_GC_HANDLE_CREATED)
1763 emit_obj (logbuffer, obj);
1766 emit_bt (prof, logbuffer, &data);
1772 finalize_begin (MonoProfiler *prof)
1774 ENTER_LOG (&finalize_begins_ctr, buf,
1775 EVENT_SIZE /* event */
1778 emit_event (buf, TYPE_GC_FINALIZE_START | TYPE_GC);
1784 finalize_end (MonoProfiler *prof)
1786 trigger_on_demand_heapshot ();
1787 if (ENABLED (PROFLOG_FINALIZATION_EVENTS)) {
1788 ENTER_LOG (&finalize_ends_ctr, buf,
1789 EVENT_SIZE /* event */
1792 emit_event (buf, TYPE_GC_FINALIZE_END | TYPE_GC);
1799 finalize_object_begin (MonoProfiler *prof, MonoObject *obj)
1801 ENTER_LOG (&finalize_object_begins_ctr, buf,
1802 EVENT_SIZE /* event */ +
1803 LEB128_SIZE /* obj */
1806 emit_event (buf, TYPE_GC_FINALIZE_OBJECT_START | TYPE_GC);
1807 emit_obj (buf, obj);
1813 finalize_object_end (MonoProfiler *prof, MonoObject *obj)
1815 ENTER_LOG (&finalize_object_ends_ctr, buf,
1816 EVENT_SIZE /* event */ +
1817 LEB128_SIZE /* obj */
1820 emit_event (buf, TYPE_GC_FINALIZE_OBJECT_END | TYPE_GC);
1821 emit_obj (buf, obj);
1827 push_nesting (char *p, MonoClass *klass)
1832 nesting = mono_class_get_nesting_type (klass);
1834 p = push_nesting (p, nesting);
1838 name = mono_class_get_name (klass);
1839 nspace = mono_class_get_namespace (klass);
1842 p += strlen (nspace);
1852 type_name (MonoClass *klass)
1856 push_nesting (buf, klass);
1857 p = (char *) g_malloc (strlen (buf) + 1);
1863 image_loaded (MonoProfiler *prof, MonoImage *image, int result)
1865 if (result != MONO_PROFILE_OK)
1868 const char *name = mono_image_get_filename (image);
1869 int nlen = strlen (name) + 1;
1871 ENTER_LOG (&image_loads_ctr, logbuffer,
1872 EVENT_SIZE /* event */ +
1873 BYTE_SIZE /* type */ +
1874 LEB128_SIZE /* image */ +
1878 emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1879 emit_byte (logbuffer, TYPE_IMAGE);
1880 emit_ptr (logbuffer, image);
1881 memcpy (logbuffer->cursor, name, nlen);
1882 logbuffer->cursor += nlen;
1888 image_unloaded (MonoProfiler *prof, MonoImage *image)
1890 const char *name = mono_image_get_filename (image);
1891 int nlen = strlen (name) + 1;
1893 ENTER_LOG (&image_unloads_ctr, logbuffer,
1894 EVENT_SIZE /* event */ +
1895 BYTE_SIZE /* type */ +
1896 LEB128_SIZE /* image */ +
1900 emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1901 emit_byte (logbuffer, TYPE_IMAGE);
1902 emit_ptr (logbuffer, image);
1903 memcpy (logbuffer->cursor, name, nlen);
1904 logbuffer->cursor += nlen;
1910 assembly_loaded (MonoProfiler *prof, MonoAssembly *assembly, int result)
1912 if (result != MONO_PROFILE_OK)
1915 char *name = mono_stringify_assembly_name (mono_assembly_get_name (assembly));
1916 int nlen = strlen (name) + 1;
1917 MonoImage *image = mono_assembly_get_image (assembly);
1919 ENTER_LOG (&assembly_loads_ctr, logbuffer,
1920 EVENT_SIZE /* event */ +
1921 BYTE_SIZE /* type */ +
1922 LEB128_SIZE /* assembly */ +
1923 LEB128_SIZE /* image */ +
1927 emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1928 emit_byte (logbuffer, TYPE_ASSEMBLY);
1929 emit_ptr (logbuffer, assembly);
1930 emit_ptr (logbuffer, image);
1931 memcpy (logbuffer->cursor, name, nlen);
1932 logbuffer->cursor += nlen;
1940 assembly_unloaded (MonoProfiler *prof, MonoAssembly *assembly)
1942 char *name = mono_stringify_assembly_name (mono_assembly_get_name (assembly));
1943 int nlen = strlen (name) + 1;
1944 MonoImage *image = mono_assembly_get_image (assembly);
1946 ENTER_LOG (&assembly_unloads_ctr, logbuffer,
1947 EVENT_SIZE /* event */ +
1948 BYTE_SIZE /* type */ +
1949 LEB128_SIZE /* assembly */ +
1950 LEB128_SIZE /* image */ +
1954 emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1955 emit_byte (logbuffer, TYPE_ASSEMBLY);
1956 emit_ptr (logbuffer, assembly);
1957 emit_ptr (logbuffer, image);
1958 memcpy (logbuffer->cursor, name, nlen);
1959 logbuffer->cursor += nlen;
1967 class_loaded (MonoProfiler *prof, MonoClass *klass, int result)
1969 if (result != MONO_PROFILE_OK)
1974 if (InterlockedRead (&runtime_inited))
1975 name = mono_type_get_name (mono_class_get_type (klass));
1977 name = type_name (klass);
1979 int nlen = strlen (name) + 1;
1980 MonoImage *image = mono_class_get_image (klass);
1982 ENTER_LOG (&class_loads_ctr, logbuffer,
1983 EVENT_SIZE /* event */ +
1984 BYTE_SIZE /* type */ +
1985 LEB128_SIZE /* klass */ +
1986 LEB128_SIZE /* image */ +
1990 emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1991 emit_byte (logbuffer, TYPE_CLASS);
1992 emit_ptr (logbuffer, klass);
1993 emit_ptr (logbuffer, image);
1994 memcpy (logbuffer->cursor, name, nlen);
1995 logbuffer->cursor += nlen;
2005 static void process_method_enter_coverage (MonoProfiler *prof, MonoMethod *method);
2008 method_enter (MonoProfiler *prof, MonoMethod *method)
2010 process_method_enter_coverage (prof, method);
2012 if (!only_coverage && get_thread ()->call_depth++ <= max_call_depth) {
2013 ENTER_LOG (&method_entries_ctr, logbuffer,
2014 EVENT_SIZE /* event */ +
2015 LEB128_SIZE /* method */
2018 emit_event (logbuffer, TYPE_ENTER | TYPE_METHOD);
2019 emit_method (logbuffer, method);
2026 method_leave (MonoProfiler *prof, MonoMethod *method)
2028 if (!only_coverage && --get_thread ()->call_depth <= max_call_depth) {
2029 ENTER_LOG (&method_exits_ctr, logbuffer,
2030 EVENT_SIZE /* event */ +
2031 LEB128_SIZE /* method */
2034 emit_event (logbuffer, TYPE_LEAVE | TYPE_METHOD);
2035 emit_method (logbuffer, method);
2042 method_exc_leave (MonoProfiler *prof, MonoMethod *method)
2044 if (!only_coverage && !nocalls && --get_thread ()->call_depth <= max_call_depth) {
2045 ENTER_LOG (&method_exception_exits_ctr, logbuffer,
2046 EVENT_SIZE /* event */ +
2047 LEB128_SIZE /* method */
2050 emit_event (logbuffer, TYPE_EXC_LEAVE | TYPE_METHOD);
2051 emit_method (logbuffer, method);
2058 method_jitted (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *ji, int result)
2060 if (result != MONO_PROFILE_OK)
2065 register_method_local (method, ji);
2071 code_buffer_new (MonoProfiler *prof, void *buffer, int size, MonoProfilerCodeBufferType type, void *data)
2076 if (type == MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE) {
2077 name = (char *) data;
2078 nlen = strlen (name) + 1;
2084 ENTER_LOG (&code_buffers_ctr, logbuffer,
2085 EVENT_SIZE /* event */ +
2086 BYTE_SIZE /* type */ +
2087 LEB128_SIZE /* buffer */ +
2088 LEB128_SIZE /* size */ +
2094 emit_event (logbuffer, TYPE_JITHELPER | TYPE_RUNTIME);
2095 emit_byte (logbuffer, type);
2096 emit_ptr (logbuffer, buffer);
2097 emit_value (logbuffer, size);
2100 memcpy (logbuffer->cursor, name, nlen);
2101 logbuffer->cursor += nlen;
2108 throw_exc (MonoProfiler *prof, MonoObject *object)
2110 int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces) ? TYPE_THROW_BT : 0;
2116 ENTER_LOG (&exception_throws_ctr, logbuffer,
2117 EVENT_SIZE /* event */ +
2118 LEB128_SIZE /* object */ +
2120 LEB128_SIZE /* count */ +
2122 LEB128_SIZE /* method */
2127 emit_event (logbuffer, do_bt | TYPE_EXCEPTION);
2128 emit_obj (logbuffer, object);
2131 emit_bt (prof, logbuffer, &data);
2137 clause_exc (MonoProfiler *prof, MonoMethod *method, int clause_type, int clause_num, MonoObject *exc)
2139 ENTER_LOG (&exception_clauses_ctr, logbuffer,
2140 EVENT_SIZE /* event */ +
2141 BYTE_SIZE /* clause type */ +
2142 LEB128_SIZE /* clause num */ +
2143 LEB128_SIZE /* method */
2146 emit_event (logbuffer, TYPE_EXCEPTION | TYPE_CLAUSE);
2147 emit_byte (logbuffer, clause_type);
2148 emit_value (logbuffer, clause_num);
2149 emit_method (logbuffer, method);
2150 emit_obj (logbuffer, exc);
2156 monitor_event (MonoProfiler *profiler, MonoObject *object, MonoProfilerMonitorEvent ev)
2158 int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces) ? TYPE_MONITOR_BT : 0;
2164 ENTER_LOG (&monitor_events_ctr, logbuffer,
2165 EVENT_SIZE /* event */ +
2166 BYTE_SIZE /* ev */ +
2167 LEB128_SIZE /* object */ +
2169 LEB128_SIZE /* count */ +
2171 LEB128_SIZE /* method */
2176 emit_event (logbuffer, do_bt | TYPE_MONITOR);
2177 emit_byte (logbuffer, ev);
2178 emit_obj (logbuffer, object);
2181 emit_bt (profiler, logbuffer, &data);
2187 thread_start (MonoProfiler *prof, uintptr_t tid)
2189 if (ENABLED (PROFLOG_THREAD_EVENTS)) {
2190 ENTER_LOG (&thread_starts_ctr, logbuffer,
2191 EVENT_SIZE /* event */ +
2192 BYTE_SIZE /* type */ +
2193 LEB128_SIZE /* tid */
2196 emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
2197 emit_byte (logbuffer, TYPE_THREAD);
2198 emit_ptr (logbuffer, (void*) tid);
2205 thread_end (MonoProfiler *prof, uintptr_t tid)
2207 if (ENABLED (PROFLOG_THREAD_EVENTS)) {
2208 ENTER_LOG (&thread_ends_ctr, logbuffer,
2209 EVENT_SIZE /* event */ +
2210 BYTE_SIZE /* type */ +
2211 LEB128_SIZE /* tid */
2214 emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
2215 emit_byte (logbuffer, TYPE_THREAD);
2216 emit_ptr (logbuffer, (void*) tid);
2218 EXIT_LOG_EXPLICIT (NO_SEND);
2221 MonoProfilerThread *thread = get_thread ();
2223 thread->ended = TRUE;
2224 remove_thread (thread);
2226 PROF_TLS_SET (NULL);
2230 thread_name (MonoProfiler *prof, uintptr_t tid, const char *name)
2232 int len = strlen (name) + 1;
2234 if (ENABLED (PROFLOG_THREAD_EVENTS)) {
2235 ENTER_LOG (&thread_names_ctr, logbuffer,
2236 EVENT_SIZE /* event */ +
2237 BYTE_SIZE /* type */ +
2238 LEB128_SIZE /* tid */ +
2242 emit_event (logbuffer, TYPE_METADATA);
2243 emit_byte (logbuffer, TYPE_THREAD);
2244 emit_ptr (logbuffer, (void*)tid);
2245 memcpy (logbuffer->cursor, name, len);
2246 logbuffer->cursor += len;
2253 domain_loaded (MonoProfiler *prof, MonoDomain *domain, int result)
2255 if (result != MONO_PROFILE_OK)
2258 ENTER_LOG (&domain_loads_ctr, logbuffer,
2259 EVENT_SIZE /* event */ +
2260 BYTE_SIZE /* type */ +
2261 LEB128_SIZE /* domain id */
2264 emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
2265 emit_byte (logbuffer, TYPE_DOMAIN);
2266 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
2272 domain_unloaded (MonoProfiler *prof, MonoDomain *domain)
2274 ENTER_LOG (&domain_unloads_ctr, logbuffer,
2275 EVENT_SIZE /* event */ +
2276 BYTE_SIZE /* type */ +
2277 LEB128_SIZE /* domain id */
2280 emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
2281 emit_byte (logbuffer, TYPE_DOMAIN);
2282 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
2288 domain_name (MonoProfiler *prof, MonoDomain *domain, const char *name)
2290 int nlen = strlen (name) + 1;
2292 ENTER_LOG (&domain_names_ctr, logbuffer,
2293 EVENT_SIZE /* event */ +
2294 BYTE_SIZE /* type */ +
2295 LEB128_SIZE /* domain id */ +
2299 emit_event (logbuffer, TYPE_METADATA);
2300 emit_byte (logbuffer, TYPE_DOMAIN);
2301 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
2302 memcpy (logbuffer->cursor, name, nlen);
2303 logbuffer->cursor += nlen;
2309 context_loaded (MonoProfiler *prof, MonoAppContext *context)
2311 ENTER_LOG (&context_loads_ctr, logbuffer,
2312 EVENT_SIZE /* event */ +
2313 BYTE_SIZE /* type */ +
2314 LEB128_SIZE /* context id */ +
2315 LEB128_SIZE /* domain id */
2318 emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
2319 emit_byte (logbuffer, TYPE_CONTEXT);
2320 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_id (context));
2321 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_domain_id (context));
2327 context_unloaded (MonoProfiler *prof, MonoAppContext *context)
2329 ENTER_LOG (&context_unloads_ctr, logbuffer,
2330 EVENT_SIZE /* event */ +
2331 BYTE_SIZE /* type */ +
2332 LEB128_SIZE /* context id */ +
2333 LEB128_SIZE /* domain id */
2336 emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
2337 emit_byte (logbuffer, TYPE_CONTEXT);
2338 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_id (context));
2339 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_domain_id (context));
2352 MonoLockFreeQueueNode node;
2358 AsyncFrameInfo frames [MONO_ZERO_LEN_ARRAY];
2362 async_walk_stack (MonoMethod *method, MonoDomain *domain, void *base_address, int offset, void *data)
2364 SampleHit *sample = (SampleHit *) data;
2366 if (sample->count < num_frames) {
2367 int i = sample->count;
2369 sample->frames [i].method = method;
2370 sample->frames [i].domain = domain;
2371 sample->frames [i].base_address = base_address;
2372 sample->frames [i].offset = offset;
2377 return sample->count == num_frames;
2380 #define SAMPLE_SLOT_SIZE(FRAMES) (sizeof (SampleHit) + sizeof (AsyncFrameInfo) * (FRAMES - MONO_ZERO_LEN_ARRAY))
2381 #define SAMPLE_BLOCK_SIZE (mono_pagesize ())
2384 enqueue_sample_hit (gpointer p)
2386 SampleHit *sample = p;
2388 mono_lock_free_queue_node_unpoison (&sample->node);
2389 mono_lock_free_queue_enqueue (&sample->prof->dumper_queue, &sample->node);
2390 mono_os_sem_post (&sample->prof->dumper_queue_sem);
2394 mono_sample_hit (MonoProfiler *profiler, unsigned char *ip, void *context)
2397 * Please note: We rely on the runtime loading the profiler with
2398 * MONO_DL_EAGER (RTLD_NOW) so that references to runtime functions within
2399 * this function (and its siblings) are resolved when the profiler is
2400 * loaded. Otherwise, we would potentially invoke the dynamic linker when
2401 * invoking runtime functions, which is not async-signal-safe.
2404 if (InterlockedRead (&in_shutdown))
2407 SampleHit *sample = (SampleHit *) mono_lock_free_queue_dequeue (&profiler->sample_reuse_queue);
2411 * If we're out of reusable sample events and we're not allowed to
2412 * allocate more, we have no choice but to drop the event.
2414 if (InterlockedRead (&sample_allocations_ctr) >= max_allocated_sample_hits)
2417 sample = mono_lock_free_alloc (&profiler->sample_allocator);
2418 sample->prof = profiler;
2419 mono_lock_free_queue_node_init (&sample->node, TRUE);
2421 InterlockedIncrement (&sample_allocations_ctr);
2425 mono_stack_walk_async_safe (&async_walk_stack, context, sample);
2427 sample->time = current_time ();
2428 sample->tid = thread_id ();
2431 mono_thread_hazardous_try_free (sample, enqueue_sample_hit);
2434 static uintptr_t *code_pages = 0;
2435 static int num_code_pages = 0;
2436 static int size_code_pages = 0;
2437 #define CPAGE_SHIFT (9)
2438 #define CPAGE_SIZE (1 << CPAGE_SHIFT)
2439 #define CPAGE_MASK (~(CPAGE_SIZE - 1))
2440 #define CPAGE_ADDR(p) ((p) & CPAGE_MASK)
2443 add_code_page (uintptr_t *hash, uintptr_t hsize, uintptr_t page)
2446 uintptr_t start_pos;
2447 start_pos = (page >> CPAGE_SHIFT) % hsize;
2450 if (hash [i] && CPAGE_ADDR (hash [i]) == CPAGE_ADDR (page)) {
2452 } else if (!hash [i]) {
2459 } while (i != start_pos);
2460 /* should not happen */
2461 printf ("failed code page store\n");
2466 add_code_pointer (uintptr_t ip)
2469 if (num_code_pages * 2 >= size_code_pages) {
2471 uintptr_t old_size = size_code_pages;
2472 size_code_pages *= 2;
2473 if (size_code_pages == 0)
2474 size_code_pages = 16;
2475 n = (uintptr_t *) g_calloc (sizeof (uintptr_t) * size_code_pages, 1);
2476 for (i = 0; i < old_size; ++i) {
2478 add_code_page (n, size_code_pages, code_pages [i]);
2481 g_free (code_pages);
2484 num_code_pages += add_code_page (code_pages, size_code_pages, ip & CPAGE_MASK);
2487 /* ELF code crashes on some systems. */
2488 //#if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
2491 dump_ubin (MonoProfiler *prof, const char *filename, uintptr_t load_addr, uint64_t offset, uintptr_t size)
2493 int len = strlen (filename) + 1;
2495 ENTER_LOG (&sample_ubins_ctr, logbuffer,
2496 EVENT_SIZE /* event */ +
2497 LEB128_SIZE /* load address */ +
2498 LEB128_SIZE /* offset */ +
2499 LEB128_SIZE /* size */ +
2500 nlen /* file name */
2503 emit_event (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_UBIN);
2504 emit_ptr (logbuffer, load_addr);
2505 emit_uvalue (logbuffer, offset);
2506 emit_uvalue (logbuffer, size);
2507 memcpy (logbuffer->cursor, filename, len);
2508 logbuffer->cursor += len;
2510 EXIT_LOG_EXPLICIT (DO_SEND);
2515 dump_usym (MonoProfiler *prof, const char *name, uintptr_t value, uintptr_t size)
2517 int len = strlen (name) + 1;
2519 ENTER_LOG (&sample_usyms_ctr, logbuffer,
2520 EVENT_SIZE /* event */ +
2521 LEB128_SIZE /* value */ +
2522 LEB128_SIZE /* size */ +
2526 emit_event (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_USYM);
2527 emit_ptr (logbuffer, (void*)value);
2528 emit_value (logbuffer, size);
2529 memcpy (logbuffer->cursor, name, len);
2530 logbuffer->cursor += len;
2532 EXIT_LOG_EXPLICIT (DO_SEND);
2535 /* ELF code crashes on some systems. */
2536 //#if defined(ELFMAG0)
2539 #if SIZEOF_VOID_P == 4
2540 #define ELF_WSIZE 32
2542 #define ELF_WSIZE 64
2545 #define ElfW(type) _ElfW (Elf, ELF_WSIZE, type)
2546 #define _ElfW(e,w,t) _ElfW_1 (e, w, _##t)
2547 #define _ElfW_1(e,w,t) e##w##t
2551 dump_elf_symbols (MonoProfiler *prof, ElfW(Sym) *symbols, int num_symbols, const char *strtab, void *load_addr)
2554 for (i = 0; i < num_symbols; ++i) {
2556 sym = strtab + symbols [i].st_name;
2557 if (!symbols [i].st_name || !symbols [i].st_size || (symbols [i].st_info & 0xf) != STT_FUNC)
2559 //printf ("symbol %s at %d\n", sym, symbols [i].st_value);
2560 dump_usym (sym, (uintptr_t)load_addr + symbols [i].st_value, symbols [i].st_size);
2565 read_elf_symbols (MonoProfiler *prof, const char *filename, void *load_addr)
2572 ElfW(Shdr) *sheader;
2573 ElfW(Shdr) *shstrtabh;
2574 ElfW(Shdr) *symtabh = NULL;
2575 ElfW(Shdr) *strtabh = NULL;
2576 ElfW(Sym) *symbols = NULL;
2580 fd = open (filename, O_RDONLY);
2583 if (fstat (fd, &statb) != 0) {
2587 file_size = statb.st_size;
2588 data = mmap (NULL, file_size, PROT_READ, MAP_PRIVATE, fd, 0);
2590 if (data == MAP_FAILED)
2593 if (header->e_ident [EI_MAG0] != ELFMAG0 ||
2594 header->e_ident [EI_MAG1] != ELFMAG1 ||
2595 header->e_ident [EI_MAG2] != ELFMAG2 ||
2596 header->e_ident [EI_MAG3] != ELFMAG3 ) {
2597 munmap (data, file_size);
2600 sheader = (void*)((char*)data + header->e_shoff);
2601 shstrtabh = (void*)((char*)sheader + (header->e_shentsize * header->e_shstrndx));
2602 strtab = (const char*)data + shstrtabh->sh_offset;
2603 for (i = 0; i < header->e_shnum; ++i) {
2604 //printf ("section header: %d\n", sheader->sh_type);
2605 if (sheader->sh_type == SHT_SYMTAB) {
2607 strtabh = (void*)((char*)data + header->e_shoff + sheader->sh_link * header->e_shentsize);
2608 /*printf ("symtab section header: %d, .strstr: %d\n", i, sheader->sh_link);*/
2611 sheader = (void*)((char*)sheader + header->e_shentsize);
2613 if (!symtabh || !strtabh) {
2614 munmap (data, file_size);
2617 strtab = (const char*)data + strtabh->sh_offset;
2618 num_symbols = symtabh->sh_size / symtabh->sh_entsize;
2619 symbols = (void*)((char*)data + symtabh->sh_offset);
2620 dump_elf_symbols (symbols, num_symbols, strtab, load_addr);
2621 munmap (data, file_size);
2626 /* ELF code crashes on some systems. */
2627 //#if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
2630 elf_dl_callback (struct dl_phdr_info *info, size_t size, void *data)
2632 MonoProfiler *prof = data;
2634 const char *filename;
2636 char *a = (void*)info->dlpi_addr;
2638 ElfW(Dyn) *dyn = NULL;
2639 ElfW(Sym) *symtab = NULL;
2640 ElfW(Word) *hash_table = NULL;
2641 ElfW(Ehdr) *header = NULL;
2642 const char* strtab = NULL;
2643 for (obj = prof->binary_objects; obj; obj = obj->next) {
2647 filename = info->dlpi_name;
2650 if (!info->dlpi_addr && !filename [0]) {
2651 int l = readlink ("/proc/self/exe", buf, sizeof (buf) - 1);
2657 obj = g_calloc (sizeof (BinaryObject), 1);
2658 obj->addr = (void*)info->dlpi_addr;
2659 obj->name = pstrdup (filename);
2660 obj->next = prof->binary_objects;
2661 prof->binary_objects = obj;
2662 //printf ("loaded file: %s at %p, segments: %d\n", filename, (void*)info->dlpi_addr, info->dlpi_phnum);
2664 for (i = 0; i < info->dlpi_phnum; ++i) {
2665 //printf ("segment type %d file offset: %d, size: %d\n", info->dlpi_phdr[i].p_type, info->dlpi_phdr[i].p_offset, info->dlpi_phdr[i].p_memsz);
2666 if (info->dlpi_phdr[i].p_type == PT_LOAD && !header) {
2667 header = (ElfW(Ehdr)*)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
2668 if (header->e_ident [EI_MAG0] != ELFMAG0 ||
2669 header->e_ident [EI_MAG1] != ELFMAG1 ||
2670 header->e_ident [EI_MAG2] != ELFMAG2 ||
2671 header->e_ident [EI_MAG3] != ELFMAG3 ) {
2674 dump_ubin (prof, filename, info->dlpi_addr + info->dlpi_phdr[i].p_vaddr, info->dlpi_phdr[i].p_offset, info->dlpi_phdr[i].p_memsz);
2675 } else if (info->dlpi_phdr[i].p_type == PT_DYNAMIC) {
2676 dyn = (ElfW(Dyn) *)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
2679 if (read_elf_symbols (prof, filename, (void*)info->dlpi_addr))
2681 if (!info->dlpi_name || !info->dlpi_name[0])
2685 for (i = 0; dyn [i].d_tag != DT_NULL; ++i) {
2686 if (dyn [i].d_tag == DT_SYMTAB) {
2687 if (symtab && do_debug)
2688 printf ("multiple symtabs: %d\n", i);
2689 symtab = (ElfW(Sym) *)(a + dyn [i].d_un.d_ptr);
2690 } else if (dyn [i].d_tag == DT_HASH) {
2691 hash_table = (ElfW(Word) *)(a + dyn [i].d_un.d_ptr);
2692 } else if (dyn [i].d_tag == DT_STRTAB) {
2693 strtab = (const char*)(a + dyn [i].d_un.d_ptr);
2698 num_sym = hash_table [1];
2699 dump_elf_symbols (prof, symtab, num_sym, strtab, (void*)info->dlpi_addr);
2704 load_binaries (MonoProfiler *prof)
2706 dl_iterate_phdr (elf_dl_callback, prof);
2711 load_binaries (MonoProfiler *prof)
2718 symbol_for (uintptr_t code)
2721 void *ip = (void*)code;
2723 if (dladdr (ip, &di)) {
2725 return di.dli_sname;
2728 names = backtrace_symbols (&ip, 1);
2730 const char* p = names [0];
2741 dump_unmanaged_coderefs (MonoProfiler *prof)
2744 const char* last_symbol;
2745 uintptr_t addr, page_end;
2747 if (load_binaries (prof))
2749 for (i = 0; i < size_code_pages; ++i) {
2751 if (!code_pages [i] || code_pages [i] & 1)
2754 addr = CPAGE_ADDR (code_pages [i]);
2755 page_end = addr + CPAGE_SIZE;
2756 code_pages [i] |= 1;
2757 /* we dump the symbols for the whole page */
2758 for (; addr < page_end; addr += 16) {
2759 sym = symbol_for (addr);
2760 if (sym && sym == last_symbol)
2765 dump_usym (prof, sym, addr, 0); /* let's not guess the size */
2766 //printf ("found symbol at %p: %s\n", (void*)addr, sym);
2771 typedef struct MonoCounterAgent {
2772 MonoCounter *counter;
2773 // MonoCounterAgent specific data :
2778 struct MonoCounterAgent *next;
2781 static MonoCounterAgent* counters;
2782 static int counters_index = 1;
2783 static mono_mutex_t counters_mutex;
2786 counters_add_agent (MonoCounter *counter)
2788 if (InterlockedRead (&in_shutdown))
2791 MonoCounterAgent *agent, *item;
2793 mono_os_mutex_lock (&counters_mutex);
2795 for (agent = counters; agent; agent = agent->next) {
2796 if (agent->counter == counter) {
2797 agent->value_size = 0;
2799 g_free (agent->value);
2800 agent->value = NULL;
2806 agent = (MonoCounterAgent *) g_malloc (sizeof (MonoCounterAgent));
2807 agent->counter = counter;
2808 agent->value = NULL;
2809 agent->value_size = 0;
2810 agent->index = counters_index++;
2824 mono_os_mutex_unlock (&counters_mutex);
2828 counters_init_foreach_callback (MonoCounter *counter, gpointer data)
2830 counters_add_agent (counter);
2835 counters_init (MonoProfiler *profiler)
2837 mono_os_mutex_init (&counters_mutex);
2839 mono_counters_on_register (&counters_add_agent);
2840 mono_counters_foreach (counters_init_foreach_callback, NULL);
2844 counters_emit (MonoProfiler *profiler)
2846 MonoCounterAgent *agent;
2849 EVENT_SIZE /* event */ +
2850 LEB128_SIZE /* len */
2853 mono_os_mutex_lock (&counters_mutex);
2855 for (agent = counters; agent; agent = agent->next) {
2860 LEB128_SIZE /* section */ +
2861 strlen (mono_counter_get_name (agent->counter)) + 1 /* name */ +
2862 BYTE_SIZE /* type */ +
2863 BYTE_SIZE /* unit */ +
2864 BYTE_SIZE /* variance */ +
2865 LEB128_SIZE /* index */
2874 ENTER_LOG (&counter_descriptors_ctr, logbuffer, size);
2876 emit_event (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
2877 emit_value (logbuffer, len);
2879 for (agent = counters; agent; agent = agent->next) {
2885 name = mono_counter_get_name (agent->counter);
2886 emit_value (logbuffer, mono_counter_get_section (agent->counter));
2887 emit_string (logbuffer, name, strlen (name) + 1);
2888 emit_byte (logbuffer, mono_counter_get_type (agent->counter));
2889 emit_byte (logbuffer, mono_counter_get_unit (agent->counter));
2890 emit_byte (logbuffer, mono_counter_get_variance (agent->counter));
2891 emit_value (logbuffer, agent->index);
2896 EXIT_LOG_EXPLICIT (DO_SEND);
2899 mono_os_mutex_unlock (&counters_mutex);
2903 counters_sample (MonoProfiler *profiler, uint64_t timestamp)
2905 MonoCounterAgent *agent;
2906 MonoCounter *counter;
2912 counters_emit (profiler);
2915 buffer = g_calloc (1, buffer_size);
2917 mono_os_mutex_lock (&counters_mutex);
2920 EVENT_SIZE /* event */
2923 for (agent = counters; agent; agent = agent->next) {
2925 LEB128_SIZE /* index */ +
2926 BYTE_SIZE /* type */ +
2927 mono_counter_get_size (agent->counter) /* value */
2932 LEB128_SIZE /* stop marker */
2935 ENTER_LOG (&counter_samples_ctr, logbuffer, size);
2937 emit_event_time (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE, timestamp);
2939 for (agent = counters; agent; agent = agent->next) {
2942 counter = agent->counter;
2944 size = mono_counter_get_size (counter);
2946 if (size > buffer_size) {
2948 buffer = g_realloc (buffer, buffer_size);
2951 memset (buffer, 0, buffer_size);
2953 g_assert (mono_counters_sample (counter, buffer, size));
2955 type = mono_counter_get_type (counter);
2957 if (!agent->value) {
2958 agent->value = g_calloc (1, size);
2959 agent->value_size = size;
2961 if (type == MONO_COUNTER_STRING) {
2962 if (strcmp (agent->value, buffer) == 0)
2965 if (agent->value_size == size && memcmp (agent->value, buffer, size) == 0)
2970 emit_uvalue (logbuffer, agent->index);
2971 emit_byte (logbuffer, type);
2973 case MONO_COUNTER_INT:
2974 #if SIZEOF_VOID_P == 4
2975 case MONO_COUNTER_WORD:
2977 emit_svalue (logbuffer, *(int*)buffer - *(int*)agent->value);
2979 case MONO_COUNTER_UINT:
2980 emit_uvalue (logbuffer, *(guint*)buffer - *(guint*)agent->value);
2982 case MONO_COUNTER_TIME_INTERVAL:
2983 case MONO_COUNTER_LONG:
2984 #if SIZEOF_VOID_P == 8
2985 case MONO_COUNTER_WORD:
2987 emit_svalue (logbuffer, *(gint64*)buffer - *(gint64*)agent->value);
2989 case MONO_COUNTER_ULONG:
2990 emit_uvalue (logbuffer, *(guint64*)buffer - *(guint64*)agent->value);
2992 case MONO_COUNTER_DOUBLE:
2993 emit_double (logbuffer, *(double*)buffer);
2995 case MONO_COUNTER_STRING:
2997 emit_byte (logbuffer, 0);
2999 emit_byte (logbuffer, 1);
3000 emit_string (logbuffer, (char*)buffer, size);
3004 g_assert_not_reached ();
3007 if (type == MONO_COUNTER_STRING && size > agent->value_size) {
3008 agent->value = g_realloc (agent->value, size);
3009 agent->value_size = size;
3013 memcpy (agent->value, buffer, size);
3017 emit_value (logbuffer, 0);
3019 EXIT_LOG_EXPLICIT (DO_SEND);
3021 mono_os_mutex_unlock (&counters_mutex);
3024 typedef struct _PerfCounterAgent PerfCounterAgent;
3025 struct _PerfCounterAgent {
3026 PerfCounterAgent *next;
3028 char *category_name;
3037 static PerfCounterAgent *perfcounters = NULL;
3040 perfcounters_emit (MonoProfiler *profiler)
3042 PerfCounterAgent *pcagent;
3045 EVENT_SIZE /* event */ +
3046 LEB128_SIZE /* len */
3049 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3050 if (pcagent->emitted)
3054 LEB128_SIZE /* section */ +
3055 strlen (pcagent->category_name) + 1 /* category name */ +
3056 strlen (pcagent->name) + 1 /* name */ +
3057 BYTE_SIZE /* type */ +
3058 BYTE_SIZE /* unit */ +
3059 BYTE_SIZE /* variance */ +
3060 LEB128_SIZE /* index */
3069 ENTER_LOG (&perfcounter_descriptors_ctr, logbuffer, size);
3071 emit_event (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
3072 emit_value (logbuffer, len);
3074 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3075 if (pcagent->emitted)
3078 emit_value (logbuffer, MONO_COUNTER_PERFCOUNTERS);
3079 emit_string (logbuffer, pcagent->category_name, strlen (pcagent->category_name) + 1);
3080 emit_string (logbuffer, pcagent->name, strlen (pcagent->name) + 1);
3081 emit_byte (logbuffer, MONO_COUNTER_LONG);
3082 emit_byte (logbuffer, MONO_COUNTER_RAW);
3083 emit_byte (logbuffer, MONO_COUNTER_VARIABLE);
3084 emit_value (logbuffer, pcagent->index);
3086 pcagent->emitted = 1;
3089 EXIT_LOG_EXPLICIT (DO_SEND);
3093 perfcounters_foreach (char *category_name, char *name, unsigned char type, gint64 value, gpointer user_data)
3095 PerfCounterAgent *pcagent;
3097 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3098 if (strcmp (pcagent->category_name, category_name) != 0 || strcmp (pcagent->name, name) != 0)
3100 if (pcagent->value == value)
3103 pcagent->value = value;
3104 pcagent->updated = 1;
3105 pcagent->deleted = 0;
3109 pcagent = g_new0 (PerfCounterAgent, 1);
3110 pcagent->next = perfcounters;
3111 pcagent->index = counters_index++;
3112 pcagent->category_name = g_strdup (category_name);
3113 pcagent->name = g_strdup (name);
3114 pcagent->type = (int) type;
3115 pcagent->value = value;
3116 pcagent->emitted = 0;
3117 pcagent->updated = 1;
3118 pcagent->deleted = 0;
3120 perfcounters = pcagent;
3126 perfcounters_sample (MonoProfiler *profiler, uint64_t timestamp)
3128 PerfCounterAgent *pcagent;
3132 mono_os_mutex_lock (&counters_mutex);
3134 /* mark all perfcounters as deleted, foreach will unmark them as necessary */
3135 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next)
3136 pcagent->deleted = 1;
3138 mono_perfcounter_foreach (perfcounters_foreach, perfcounters);
3140 perfcounters_emit (profiler);
3143 EVENT_SIZE /* event */
3146 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3147 if (pcagent->deleted || !pcagent->updated)
3151 LEB128_SIZE /* index */ +
3152 BYTE_SIZE /* type */ +
3153 LEB128_SIZE /* value */
3163 LEB128_SIZE /* stop marker */
3166 ENTER_LOG (&perfcounter_samples_ctr, logbuffer, size);
3168 emit_event_time (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE, timestamp);
3170 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3171 if (pcagent->deleted || !pcagent->updated)
3173 emit_uvalue (logbuffer, pcagent->index);
3174 emit_byte (logbuffer, MONO_COUNTER_LONG);
3175 emit_svalue (logbuffer, pcagent->value);
3177 pcagent->updated = 0;
3180 emit_value (logbuffer, 0);
3182 EXIT_LOG_EXPLICIT (DO_SEND);
3185 mono_os_mutex_unlock (&counters_mutex);
3189 counters_and_perfcounters_sample (MonoProfiler *prof)
3191 uint64_t now = current_time ();
3193 counters_sample (prof, now);
3194 perfcounters_sample (prof, now);
3197 #define COVERAGE_DEBUG(x) if (debug_coverage) {x}
3198 static mono_mutex_t coverage_mutex;
3199 static MonoConcurrentHashTable *coverage_methods = NULL;
3200 static MonoConcurrentHashTable *coverage_assemblies = NULL;
3201 static MonoConcurrentHashTable *coverage_classes = NULL;
3203 static MonoConcurrentHashTable *filtered_classes = NULL;
3204 static MonoConcurrentHashTable *entered_methods = NULL;
3205 static MonoConcurrentHashTable *image_to_methods = NULL;
3206 static MonoConcurrentHashTable *suppressed_assemblies = NULL;
3207 static gboolean coverage_initialized = FALSE;
3209 static GPtrArray *coverage_data = NULL;
3210 static int previous_offset = 0;
3213 MonoLockFreeQueueNode node;
3226 free_coverage_entry (gpointer data, gpointer userdata)
3228 CoverageEntry *entry = (CoverageEntry *)data;
3229 g_free (entry->filename);
3234 obtain_coverage_for_method (MonoProfiler *prof, const MonoProfileCoverageEntry *entry)
3236 int offset = entry->iloffset - previous_offset;
3237 CoverageEntry *e = g_new (CoverageEntry, 1);
3239 previous_offset = entry->iloffset;
3242 e->counter = entry->counter;
3243 e->filename = g_strdup(entry->filename ? entry->filename : "");
3244 e->line = entry->line;
3245 e->column = entry->col;
3247 g_ptr_array_add (coverage_data, e);
3251 parse_generic_type_names(char *name)
3253 char *new_name, *ret;
3254 int within_generic_declaration = 0, generic_members = 1;
3256 if (name == NULL || *name == '\0')
3257 return g_strdup ("");
3259 if (!(ret = new_name = (char *) g_calloc (strlen (name) * 4 + 1, sizeof (char))))
3265 within_generic_declaration = 1;
3269 within_generic_declaration = 0;
3271 if (*(name - 1) != '<') {
3273 *new_name++ = '0' + generic_members;
3275 memcpy (new_name, "<>", 8);
3279 generic_members = 0;
3287 if (!within_generic_declaration)
3288 *new_name++ = *name;
3297 static int method_id;
3299 build_method_buffer (gpointer key, gpointer value, gpointer userdata)
3301 MonoMethod *method = (MonoMethod *)value;
3302 MonoProfiler *prof = (MonoProfiler *)userdata;
3306 const char *image_name, *method_name, *sig, *first_filename;
3309 previous_offset = 0;
3310 coverage_data = g_ptr_array_new ();
3312 mono_profiler_coverage_get (prof, method, obtain_coverage_for_method);
3314 klass = mono_method_get_class (method);
3315 image = mono_class_get_image (klass);
3316 image_name = mono_image_get_name (image);
3318 sig = mono_signature_get_desc (mono_method_signature (method), TRUE);
3319 class_name = parse_generic_type_names (mono_type_get_name (mono_class_get_type (klass)));
3320 method_name = mono_method_get_name (method);
3322 if (coverage_data->len != 0) {
3323 CoverageEntry *entry = (CoverageEntry *)coverage_data->pdata[0];
3324 first_filename = entry->filename ? entry->filename : "";
3326 first_filename = "";
3328 image_name = image_name ? image_name : "";
3329 sig = sig ? sig : "";
3330 method_name = method_name ? method_name : "";
3332 ENTER_LOG (&coverage_methods_ctr, logbuffer,
3333 EVENT_SIZE /* event */ +
3334 strlen (image_name) + 1 /* image name */ +
3335 strlen (class_name) + 1 /* class name */ +
3336 strlen (method_name) + 1 /* method name */ +
3337 strlen (sig) + 1 /* signature */ +
3338 strlen (first_filename) + 1 /* first file name */ +
3339 LEB128_SIZE /* token */ +
3340 LEB128_SIZE /* method id */ +
3341 LEB128_SIZE /* entries */
3344 emit_event (logbuffer, TYPE_COVERAGE_METHOD | TYPE_COVERAGE);
3345 emit_string (logbuffer, image_name, strlen (image_name) + 1);
3346 emit_string (logbuffer, class_name, strlen (class_name) + 1);
3347 emit_string (logbuffer, method_name, strlen (method_name) + 1);
3348 emit_string (logbuffer, sig, strlen (sig) + 1);
3349 emit_string (logbuffer, first_filename, strlen (first_filename) + 1);
3351 emit_uvalue (logbuffer, mono_method_get_token (method));
3352 emit_uvalue (logbuffer, method_id);
3353 emit_value (logbuffer, coverage_data->len);
3355 EXIT_LOG_EXPLICIT (DO_SEND);
3357 for (i = 0; i < coverage_data->len; i++) {
3358 CoverageEntry *entry = (CoverageEntry *)coverage_data->pdata[i];
3360 ENTER_LOG (&coverage_statements_ctr, logbuffer,
3361 EVENT_SIZE /* event */ +
3362 LEB128_SIZE /* method id */ +
3363 LEB128_SIZE /* offset */ +
3364 LEB128_SIZE /* counter */ +
3365 LEB128_SIZE /* line */ +
3366 LEB128_SIZE /* column */
3369 emit_event (logbuffer, TYPE_COVERAGE_STATEMENT | TYPE_COVERAGE);
3370 emit_uvalue (logbuffer, method_id);
3371 emit_uvalue (logbuffer, entry->offset);
3372 emit_uvalue (logbuffer, entry->counter);
3373 emit_uvalue (logbuffer, entry->line);
3374 emit_uvalue (logbuffer, entry->column);
3376 EXIT_LOG_EXPLICIT (DO_SEND);
3381 g_free (class_name);
3383 g_ptr_array_foreach (coverage_data, free_coverage_entry, NULL);
3384 g_ptr_array_free (coverage_data, TRUE);
3385 coverage_data = NULL;
3388 /* This empties the queue */
3390 count_queue (MonoLockFreeQueue *queue)
3392 MonoLockFreeQueueNode *node;
3395 while ((node = mono_lock_free_queue_dequeue (queue))) {
3397 mono_thread_hazardous_try_free (node, g_free);
3404 build_class_buffer (gpointer key, gpointer value, gpointer userdata)
3406 MonoClass *klass = (MonoClass *)key;
3407 MonoLockFreeQueue *class_methods = (MonoLockFreeQueue *)value;
3410 const char *assembly_name;
3411 int number_of_methods, partially_covered;
3412 guint fully_covered;
3414 image = mono_class_get_image (klass);
3415 assembly_name = mono_image_get_name (image);
3416 class_name = mono_type_get_name (mono_class_get_type (klass));
3418 assembly_name = assembly_name ? assembly_name : "";
3419 number_of_methods = mono_class_num_methods (klass);
3420 fully_covered = count_queue (class_methods);
3421 /* We don't handle partial covered yet */
3422 partially_covered = 0;
3424 ENTER_LOG (&coverage_classes_ctr, logbuffer,
3425 EVENT_SIZE /* event */ +
3426 strlen (assembly_name) + 1 /* assembly name */ +
3427 strlen (class_name) + 1 /* class name */ +
3428 LEB128_SIZE /* no. methods */ +
3429 LEB128_SIZE /* fully covered */ +
3430 LEB128_SIZE /* partially covered */
3433 emit_event (logbuffer, TYPE_COVERAGE_CLASS | TYPE_COVERAGE);
3434 emit_string (logbuffer, assembly_name, strlen (assembly_name) + 1);
3435 emit_string (logbuffer, class_name, strlen (class_name) + 1);
3436 emit_uvalue (logbuffer, number_of_methods);
3437 emit_uvalue (logbuffer, fully_covered);
3438 emit_uvalue (logbuffer, partially_covered);
3440 EXIT_LOG_EXPLICIT (DO_SEND);
3442 g_free (class_name);
3446 get_coverage_for_image (MonoImage *image, int *number_of_methods, guint *fully_covered, int *partially_covered)
3448 MonoLockFreeQueue *image_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (image_to_methods, image);
3450 *number_of_methods = mono_image_get_table_rows (image, MONO_TABLE_METHOD);
3452 *fully_covered = count_queue (image_methods);
3456 // FIXME: We don't handle partially covered yet.
3457 *partially_covered = 0;
3461 build_assembly_buffer (gpointer key, gpointer value, gpointer userdata)
3463 MonoAssembly *assembly = (MonoAssembly *)value;
3464 MonoImage *image = mono_assembly_get_image (assembly);
3465 const char *name, *guid, *filename;
3466 int number_of_methods = 0, partially_covered = 0;
3467 guint fully_covered = 0;
3469 name = mono_image_get_name (image);
3470 guid = mono_image_get_guid (image);
3471 filename = mono_image_get_filename (image);
3473 name = name ? name : "";
3474 guid = guid ? guid : "";
3475 filename = filename ? filename : "";
3477 get_coverage_for_image (image, &number_of_methods, &fully_covered, &partially_covered);
3479 ENTER_LOG (&coverage_assemblies_ctr, logbuffer,
3480 EVENT_SIZE /* event */ +
3481 strlen (name) + 1 /* name */ +
3482 strlen (guid) + 1 /* guid */ +
3483 strlen (filename) + 1 /* file name */ +
3484 LEB128_SIZE /* no. methods */ +
3485 LEB128_SIZE /* fully covered */ +
3486 LEB128_SIZE /* partially covered */
3489 emit_event (logbuffer, TYPE_COVERAGE_ASSEMBLY | TYPE_COVERAGE);
3490 emit_string (logbuffer, name, strlen (name) + 1);
3491 emit_string (logbuffer, guid, strlen (guid) + 1);
3492 emit_string (logbuffer, filename, strlen (filename) + 1);
3493 emit_uvalue (logbuffer, number_of_methods);
3494 emit_uvalue (logbuffer, fully_covered);
3495 emit_uvalue (logbuffer, partially_covered);
3497 EXIT_LOG_EXPLICIT (DO_SEND);
3501 dump_coverage (MonoProfiler *prof)
3503 if (!coverage_initialized)
3506 COVERAGE_DEBUG(fprintf (stderr, "Coverage: Started dump\n");)
3509 mono_os_mutex_lock (&coverage_mutex);
3510 mono_conc_hashtable_foreach (coverage_assemblies, build_assembly_buffer, NULL);
3511 mono_conc_hashtable_foreach (coverage_classes, build_class_buffer, NULL);
3512 mono_conc_hashtable_foreach (coverage_methods, build_method_buffer, prof);
3513 mono_os_mutex_unlock (&coverage_mutex);
3515 COVERAGE_DEBUG(fprintf (stderr, "Coverage: Finished dump\n");)
3519 process_method_enter_coverage (MonoProfiler *prof, MonoMethod *method)
3524 if (!coverage_initialized)
3527 klass = mono_method_get_class (method);
3528 image = mono_class_get_image (klass);
3530 if (mono_conc_hashtable_lookup (suppressed_assemblies, (gpointer) mono_image_get_name (image)))
3533 mono_os_mutex_lock (&coverage_mutex);
3534 mono_conc_hashtable_insert (entered_methods, method, method);
3535 mono_os_mutex_unlock (&coverage_mutex);
3538 static MonoLockFreeQueueNode *
3539 create_method_node (MonoMethod *method)
3541 MethodNode *node = (MethodNode *) g_malloc (sizeof (MethodNode));
3542 mono_lock_free_queue_node_init ((MonoLockFreeQueueNode *) node, FALSE);
3543 node->method = method;
3545 return (MonoLockFreeQueueNode *) node;
3549 coverage_filter (MonoProfiler *prof, MonoMethod *method)
3554 MonoAssembly *assembly;
3555 MonoMethodHeader *header;
3556 guint32 iflags, flags, code_size;
3557 char *fqn, *classname;
3558 gboolean has_positive, found;
3559 MonoLockFreeQueue *image_methods, *class_methods;
3560 MonoLockFreeQueueNode *node;
3562 g_assert (coverage_initialized && "Why are we being asked for coverage filter info when we're not doing coverage?");
3564 COVERAGE_DEBUG(fprintf (stderr, "Coverage filter for %s\n", mono_method_get_name (method));)
3566 flags = mono_method_get_flags (method, &iflags);
3567 if ((iflags & 0x1000 /*METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL*/) ||
3568 (flags & 0x2000 /*METHOD_ATTRIBUTE_PINVOKE_IMPL*/)) {
3569 COVERAGE_DEBUG(fprintf (stderr, " Internal call or pinvoke - ignoring\n");)
3573 // Don't need to do anything else if we're already tracking this method
3574 if (mono_conc_hashtable_lookup (coverage_methods, method)) {
3575 COVERAGE_DEBUG(fprintf (stderr, " Already tracking\n");)
3579 klass = mono_method_get_class (method);
3580 image = mono_class_get_image (klass);
3582 // Don't handle coverage for the core assemblies
3583 if (mono_conc_hashtable_lookup (suppressed_assemblies, (gpointer) mono_image_get_name (image)) != NULL)
3586 if (prof->coverage_filters) {
3587 /* Check already filtered classes first */
3588 if (mono_conc_hashtable_lookup (filtered_classes, klass)) {
3589 COVERAGE_DEBUG(fprintf (stderr, " Already filtered\n");)
3593 classname = mono_type_get_name (mono_class_get_type (klass));
3595 fqn = g_strdup_printf ("[%s]%s", mono_image_get_name (image), classname);
3597 COVERAGE_DEBUG(fprintf (stderr, " Looking for %s in filter\n", fqn);)
3598 // Check positive filters first
3599 has_positive = FALSE;
3601 for (guint i = 0; i < prof->coverage_filters->len; ++i) {
3602 char *filter = (char *)g_ptr_array_index (prof->coverage_filters, i);
3604 if (filter [0] == '+') {
3605 filter = &filter [1];
3607 COVERAGE_DEBUG(fprintf (stderr, " Checking against +%s ...", filter);)
3609 if (strstr (fqn, filter) != NULL) {
3610 COVERAGE_DEBUG(fprintf (stderr, "matched\n");)
3613 COVERAGE_DEBUG(fprintf (stderr, "no match\n");)
3615 has_positive = TRUE;
3619 if (has_positive && !found) {
3620 COVERAGE_DEBUG(fprintf (stderr, " Positive match was not found\n");)
3622 mono_os_mutex_lock (&coverage_mutex);
3623 mono_conc_hashtable_insert (filtered_classes, klass, klass);
3624 mono_os_mutex_unlock (&coverage_mutex);
3631 for (guint i = 0; i < prof->coverage_filters->len; ++i) {
3632 // FIXME: Is substring search sufficient?
3633 char *filter = (char *)g_ptr_array_index (prof->coverage_filters, i);
3634 if (filter [0] == '+')
3638 filter = &filter [1];
3639 COVERAGE_DEBUG(fprintf (stderr, " Checking against -%s ...", filter);)
3641 if (strstr (fqn, filter) != NULL) {
3642 COVERAGE_DEBUG(fprintf (stderr, "matched\n");)
3644 mono_os_mutex_lock (&coverage_mutex);
3645 mono_conc_hashtable_insert (filtered_classes, klass, klass);
3646 mono_os_mutex_unlock (&coverage_mutex);
3652 COVERAGE_DEBUG(fprintf (stderr, "no match\n");)
3660 COVERAGE_DEBUG(fprintf (stderr, " Handling coverage for %s\n", mono_method_get_name (method));)
3661 header = mono_method_get_header_checked (method, &error);
3662 mono_error_cleanup (&error);
3664 mono_method_header_get_code (header, &code_size, NULL);
3666 assembly = mono_image_get_assembly (image);
3668 // Need to keep the assemblies around for as long as they are kept in the hashtable
3669 // Nunit, for example, has a habit of unloading them before the coverage statistics are
3670 // generated causing a crash. See https://bugzilla.xamarin.com/show_bug.cgi?id=39325
3671 mono_assembly_addref (assembly);
3673 mono_os_mutex_lock (&coverage_mutex);
3674 mono_conc_hashtable_insert (coverage_methods, method, method);
3675 mono_conc_hashtable_insert (coverage_assemblies, assembly, assembly);
3676 mono_os_mutex_unlock (&coverage_mutex);
3678 image_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (image_to_methods, image);
3680 if (image_methods == NULL) {
3681 image_methods = (MonoLockFreeQueue *) g_malloc (sizeof (MonoLockFreeQueue));
3682 mono_lock_free_queue_init (image_methods);
3683 mono_os_mutex_lock (&coverage_mutex);
3684 mono_conc_hashtable_insert (image_to_methods, image, image_methods);
3685 mono_os_mutex_unlock (&coverage_mutex);
3688 node = create_method_node (method);
3689 mono_lock_free_queue_enqueue (image_methods, node);
3691 class_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (coverage_classes, klass);
3693 if (class_methods == NULL) {
3694 class_methods = (MonoLockFreeQueue *) g_malloc (sizeof (MonoLockFreeQueue));
3695 mono_lock_free_queue_init (class_methods);
3696 mono_os_mutex_lock (&coverage_mutex);
3697 mono_conc_hashtable_insert (coverage_classes, klass, class_methods);
3698 mono_os_mutex_unlock (&coverage_mutex);
3701 node = create_method_node (method);
3702 mono_lock_free_queue_enqueue (class_methods, node);
3707 #define LINE_BUFFER_SIZE 4096
3708 /* Max file limit of 128KB */
3709 #define MAX_FILE_SIZE 128 * 1024
3711 get_file_content (FILE *stream)
3716 int res, offset = 0;
3718 res = fseek (stream, 0, SEEK_END);
3722 filesize = ftell (stream);
3726 res = fseek (stream, 0, SEEK_SET);
3730 if (filesize > MAX_FILE_SIZE)
3733 buffer = (char *) g_malloc ((filesize + 1) * sizeof (char));
3734 while ((bytes_read = fread (buffer + offset, 1, LINE_BUFFER_SIZE, stream)) > 0)
3735 offset += bytes_read;
3737 /* NULL terminate our buffer */
3738 buffer[filesize] = '\0';
3743 get_next_line (char *contents, char **next_start)
3747 if (p == NULL || *p == '\0') {
3752 while (*p != '\n' && *p != '\0')
3757 *next_start = p + 1;
3765 init_suppressed_assemblies (void)
3771 suppressed_assemblies = mono_conc_hashtable_new (g_str_hash, g_str_equal);
3772 sa_file = fopen (SUPPRESSION_DIR "/mono-profiler-log.suppression", "r");
3773 if (sa_file == NULL)
3776 /* Don't need to free @content as it is referred to by the lines stored in @suppressed_assemblies */
3777 content = get_file_content (sa_file);
3778 if (content == NULL) {
3779 g_error ("mono-profiler-log.suppression is greater than 128kb - aborting\n");
3782 while ((line = get_next_line (content, &content))) {
3783 line = g_strchomp (g_strchug (line));
3784 /* No locking needed as we're doing initialization */
3785 mono_conc_hashtable_insert (suppressed_assemblies, line, line);
3792 parse_cov_filter_file (GPtrArray *filters, const char *file)
3795 char *line, *content;
3797 filter_file = fopen (file, "r");
3798 if (filter_file == NULL) {
3799 fprintf (stderr, "Unable to open %s\n", file);
3803 /* Don't need to free content as it is referred to by the lines stored in @filters */
3804 content = get_file_content (filter_file);
3805 if (content == NULL)
3806 fprintf (stderr, "WARNING: %s is greater than 128kb - ignoring\n", file);
3808 while ((line = get_next_line (content, &content)))
3809 g_ptr_array_add (filters, g_strchug (g_strchomp (line)));
3811 fclose (filter_file);
3815 coverage_init (MonoProfiler *prof)
3817 g_assert (!coverage_initialized && "Why are we initializing coverage twice?");
3819 COVERAGE_DEBUG(fprintf (stderr, "Coverage initialized\n");)
3821 mono_os_mutex_init (&coverage_mutex);
3822 coverage_methods = mono_conc_hashtable_new (NULL, NULL);
3823 coverage_assemblies = mono_conc_hashtable_new (NULL, NULL);
3824 coverage_classes = mono_conc_hashtable_new (NULL, NULL);
3825 filtered_classes = mono_conc_hashtable_new (NULL, NULL);
3826 entered_methods = mono_conc_hashtable_new (NULL, NULL);
3827 image_to_methods = mono_conc_hashtable_new (NULL, NULL);
3828 init_suppressed_assemblies ();
3830 coverage_initialized = TRUE;
3834 unref_coverage_assemblies (gpointer key, gpointer value, gpointer userdata)
3836 MonoAssembly *assembly = (MonoAssembly *)value;
3837 mono_assembly_close (assembly);
3841 free_sample_hit (gpointer p)
3843 mono_lock_free_free (p, SAMPLE_BLOCK_SIZE);
3847 cleanup_reusable_samples (MonoProfiler *prof)
3851 while ((sample = (SampleHit *) mono_lock_free_queue_dequeue (&prof->sample_reuse_queue)))
3852 mono_thread_hazardous_try_free (sample, free_sample_hit);
3856 log_shutdown (MonoProfiler *prof)
3858 InterlockedWrite (&in_shutdown, 1);
3861 counters_and_perfcounters_sample (prof);
3863 dump_coverage (prof);
3867 if (write (prof->pipes [1], &c, 1) != 1) {
3868 fprintf (stderr, "Could not write to pipe: %s\n", strerror (errno));
3872 mono_native_thread_join (prof->helper_thread);
3874 mono_os_mutex_destroy (&counters_mutex);
3876 MonoCounterAgent *mc_next;
3878 for (MonoCounterAgent *cur = counters; cur; cur = mc_next) {
3879 mc_next = cur->next;
3883 PerfCounterAgent *pc_next;
3885 for (PerfCounterAgent *cur = perfcounters; cur; cur = pc_next) {
3886 pc_next = cur->next;
3891 * Ensure that we empty the LLS completely, even if some nodes are
3892 * not immediately removed upon calling mono_lls_remove (), by
3893 * iterating until the head is NULL.
3895 while (profiler_thread_list.head) {
3896 MONO_LLS_FOREACH_SAFE (&profiler_thread_list, MonoProfilerThread, thread) {
3897 g_assert (thread->attached && "Why is a thread in the LLS not attached?");
3899 remove_thread (thread);
3900 } MONO_LLS_FOREACH_SAFE_END
3904 * Ensure that all threads have been freed, so that we don't miss any
3905 * buffers when we shut down the writer thread below.
3907 mono_thread_hazardous_try_free_all ();
3909 InterlockedWrite (&prof->run_dumper_thread, 0);
3910 mono_os_sem_post (&prof->dumper_queue_sem);
3911 mono_native_thread_join (prof->dumper_thread);
3912 mono_os_sem_destroy (&prof->dumper_queue_sem);
3914 InterlockedWrite (&prof->run_writer_thread, 0);
3915 mono_os_sem_post (&prof->writer_queue_sem);
3916 mono_native_thread_join (prof->writer_thread);
3917 mono_os_sem_destroy (&prof->writer_queue_sem);
3920 * Free all writer queue entries, and ensure that all sample hits will be
3921 * added to the sample reuse queue.
3923 mono_thread_hazardous_try_free_all ();
3925 cleanup_reusable_samples (prof);
3928 * Finally, make sure that all sample hits are freed. This should cover all
3929 * hazardous data from the profiler. We can now be sure that the runtime
3930 * won't later invoke free functions in the profiler library after it has
3933 mono_thread_hazardous_try_free_all ();
3935 gint32 state = InterlockedRead (&buffer_lock_state);
3937 g_assert (!(state & 0xFFFF) && "Why is the reader count still non-zero?");
3938 g_assert (!(state >> 16) && "Why is the exclusive lock still held?");
3940 #if defined (HAVE_SYS_ZLIB)
3942 gzclose (prof->gzfile);
3944 if (prof->pipe_output)
3945 pclose (prof->file);
3947 fclose (prof->file);
3949 mono_conc_hashtable_destroy (prof->method_table);
3950 mono_os_mutex_destroy (&prof->method_table_mutex);
3952 if (coverage_initialized) {
3953 mono_os_mutex_lock (&coverage_mutex);
3954 mono_conc_hashtable_foreach (coverage_assemblies, unref_coverage_assemblies, prof);
3955 mono_os_mutex_unlock (&coverage_mutex);
3957 mono_conc_hashtable_destroy (coverage_methods);
3958 mono_conc_hashtable_destroy (coverage_assemblies);
3959 mono_conc_hashtable_destroy (coverage_classes);
3960 mono_conc_hashtable_destroy (filtered_classes);
3962 mono_conc_hashtable_destroy (entered_methods);
3963 mono_conc_hashtable_destroy (image_to_methods);
3964 mono_conc_hashtable_destroy (suppressed_assemblies);
3965 mono_os_mutex_destroy (&coverage_mutex);
3970 g_free (prof->args);
3975 new_filename (const char* filename)
3977 time_t t = time (NULL);
3978 int pid = process_id ();
3983 int count_dates = 0;
3987 for (p = filename; *p; p++) {
3998 if (!count_dates && !count_pids)
3999 return pstrdup (filename);
4000 snprintf (pid_buf, sizeof (pid_buf), "%d", pid);
4002 snprintf (time_buf, sizeof (time_buf), "%d%02d%02d%02d%02d%02d",
4003 1900 + ts->tm_year, 1 + ts->tm_mon, ts->tm_mday, ts->tm_hour, ts->tm_min, ts->tm_sec);
4004 s_date = strlen (time_buf);
4005 s_pid = strlen (pid_buf);
4006 d = res = (char *) g_malloc (strlen (filename) + s_date * count_dates + s_pid * count_pids);
4007 for (p = filename; *p; p++) {
4014 strcpy (d, time_buf);
4017 } else if (*p == 'p') {
4018 strcpy (d, pid_buf);
4021 } else if (*p == '%') {
4034 add_to_fd_set (fd_set *set, int fd, int *max_fd)
4037 * This should only trigger for the basic FDs (server socket, pipes) at
4038 * startup if for some mysterious reason they're too large. In this case,
4039 * the profiler really can't function, and we're better off printing an
4040 * error and exiting.
4042 if (fd >= FD_SETSIZE) {
4043 fprintf (stderr, "File descriptor is out of bounds for fd_set: %d\n", fd);
4054 helper_thread (void *arg)
4056 MonoProfiler *prof = (MonoProfiler *) arg;
4058 mono_threads_attach_tools_thread ();
4059 mono_native_thread_set_name (mono_native_thread_id_get (), "Profiler helper");
4061 MonoProfilerThread *thread = init_thread (prof, FALSE);
4063 GArray *command_sockets = g_array_new (FALSE, FALSE, sizeof (int));
4071 add_to_fd_set (&rfds, prof->server_socket, &max_fd);
4072 add_to_fd_set (&rfds, prof->pipes [0], &max_fd);
4074 for (gint i = 0; i < command_sockets->len; i++)
4075 add_to_fd_set (&rfds, g_array_index (command_sockets, int, i), &max_fd);
4077 struct timeval tv = { .tv_sec = 1, .tv_usec = 0 };
4079 // Sleep for 1sec or until a file descriptor has data.
4080 if (select (max_fd + 1, &rfds, NULL, NULL, &tv) == -1) {
4084 fprintf (stderr, "Error in mono-profiler-log server: %s", strerror (errno));
4089 counters_and_perfcounters_sample (prof);
4091 buffer_lock_excl ();
4093 sync_point (SYNC_POINT_PERIODIC);
4095 buffer_unlock_excl ();
4097 // Are we shutting down?
4098 if (FD_ISSET (prof->pipes [0], &rfds)) {
4100 read (prof->pipes [0], &c, 1);
4104 for (gint i = 0; i < command_sockets->len; i++) {
4105 int fd = g_array_index (command_sockets, int, i);
4107 if (!FD_ISSET (fd, &rfds))
4111 int len = read (fd, buf, sizeof (buf) - 1);
4117 // The other end disconnected.
4118 g_array_remove_index (command_sockets, i);
4126 if (!strcmp (buf, "heapshot\n") && hs_mode_ondemand) {
4127 // Rely on the finalization callback triggering a GC.
4128 heapshot_requested = 1;
4129 mono_gc_finalize_notify ();
4133 if (FD_ISSET (prof->server_socket, &rfds)) {
4134 int fd = accept (prof->server_socket, NULL, NULL);
4137 if (fd >= FD_SETSIZE)
4140 g_array_append_val (command_sockets, fd);
4145 for (gint i = 0; i < command_sockets->len; i++)
4146 close (g_array_index (command_sockets, int, i));
4148 g_array_free (command_sockets, TRUE);
4150 send_log_unsafe (FALSE);
4151 deinit_thread (thread);
4153 mono_thread_info_detach ();
4159 start_helper_thread (MonoProfiler* prof)
4161 if (pipe (prof->pipes) == -1) {
4162 fprintf (stderr, "Cannot create pipe: %s\n", strerror (errno));
4166 prof->server_socket = socket (PF_INET, SOCK_STREAM, 0);
4168 if (prof->server_socket == -1) {
4169 fprintf (stderr, "Cannot create server socket: %s\n", strerror (errno));
4173 struct sockaddr_in server_address;
4175 memset (&server_address, 0, sizeof (server_address));
4176 server_address.sin_family = AF_INET;
4177 server_address.sin_addr.s_addr = INADDR_ANY;
4178 server_address.sin_port = htons (prof->command_port);
4180 if (bind (prof->server_socket, (struct sockaddr *) &server_address, sizeof (server_address)) == -1) {
4181 fprintf (stderr, "Cannot bind server socket on port %d: %s\n", prof->command_port, strerror (errno));
4182 close (prof->server_socket);
4186 if (listen (prof->server_socket, 1) == -1) {
4187 fprintf (stderr, "Cannot listen on server socket: %s\n", strerror (errno));
4188 close (prof->server_socket);
4192 socklen_t slen = sizeof (server_address);
4194 if (getsockname (prof->server_socket, (struct sockaddr *) &server_address, &slen)) {
4195 fprintf (stderr, "Could not get assigned port: %s\n", strerror (errno));
4196 close (prof->server_socket);
4200 prof->command_port = ntohs (server_address.sin_port);
4202 if (!mono_native_thread_create (&prof->helper_thread, helper_thread, prof)) {
4203 fprintf (stderr, "Could not start helper thread\n");
4204 close (prof->server_socket);
4210 free_writer_entry (gpointer p)
4212 mono_lock_free_free (p, WRITER_ENTRY_BLOCK_SIZE);
4216 handle_writer_queue_entry (MonoProfiler *prof)
4218 WriterQueueEntry *entry;
4220 if ((entry = (WriterQueueEntry *) mono_lock_free_queue_dequeue (&prof->writer_queue))) {
4221 if (!entry->methods)
4224 gboolean wrote_methods = FALSE;
4227 * Encode the method events in a temporary log buffer that we
4228 * flush to disk before the main buffer, ensuring that all
4229 * methods have metadata emitted before they're referenced.
4231 * We use a 'proper' thread-local buffer for this as opposed
4232 * to allocating and freeing a buffer by hand because the call
4233 * to mono_method_full_name () below may trigger class load
4234 * events when it retrieves the signature of the method. So a
4235 * thread-local buffer needs to exist when such events occur.
4237 for (guint i = 0; i < entry->methods->len; i++) {
4238 MethodInfo *info = (MethodInfo *) g_ptr_array_index (entry->methods, i);
4240 if (mono_conc_hashtable_lookup (prof->method_table, info->method))
4241 goto free_info; // This method already has metadata emitted.
4244 * Other threads use this hash table to get a general
4245 * idea of whether a method has already been emitted to
4246 * the stream. Due to the way we add to this table, it
4247 * can easily happen that multiple threads queue up the
4248 * same methods, but that's OK since eventually all
4249 * methods will be in this table and the thread-local
4250 * method lists will just be empty for the rest of the
4253 mono_os_mutex_lock (&prof->method_table_mutex);
4254 mono_conc_hashtable_insert (prof->method_table, info->method, info->method);
4255 mono_os_mutex_unlock (&prof->method_table_mutex);
4257 char *name = mono_method_full_name (info->method, 1);
4258 int nlen = strlen (name) + 1;
4259 void *cstart = info->ji ? mono_jit_info_get_code_start (info->ji) : NULL;
4260 int csize = info->ji ? mono_jit_info_get_code_size (info->ji) : 0;
4262 ENTER_LOG (&method_jits_ctr, logbuffer,
4263 EVENT_SIZE /* event */ +
4264 LEB128_SIZE /* method */ +
4265 LEB128_SIZE /* start */ +
4266 LEB128_SIZE /* size */ +
4270 emit_event_time (logbuffer, TYPE_JIT | TYPE_METHOD, info->time);
4271 emit_method_inner (logbuffer, info->method);
4272 emit_ptr (logbuffer, cstart);
4273 emit_value (logbuffer, csize);
4275 memcpy (logbuffer->cursor, name, nlen);
4276 logbuffer->cursor += nlen;
4278 EXIT_LOG_EXPLICIT (NO_SEND);
4282 wrote_methods = TRUE;
4288 g_ptr_array_free (entry->methods, TRUE);
4290 if (wrote_methods) {
4291 MonoProfilerThread *thread = PROF_TLS_GET ();
4293 dump_buffer_threadless (prof, thread->buffer);
4294 init_buffer_state (thread);
4298 dump_buffer (prof, entry->buffer);
4300 mono_thread_hazardous_try_free (entry, free_writer_entry);
4309 writer_thread (void *arg)
4311 MonoProfiler *prof = (MonoProfiler *)arg;
4313 mono_threads_attach_tools_thread ();
4314 mono_native_thread_set_name (mono_native_thread_id_get (), "Profiler writer");
4318 MonoProfilerThread *thread = init_thread (prof, FALSE);
4320 while (InterlockedRead (&prof->run_writer_thread)) {
4321 mono_os_sem_wait (&prof->writer_queue_sem, MONO_SEM_FLAGS_NONE);
4322 handle_writer_queue_entry (prof);
4325 /* Drain any remaining entries on shutdown. */
4326 while (handle_writer_queue_entry (prof));
4328 free_buffer (thread->buffer, thread->buffer->size);
4329 deinit_thread (thread);
4331 mono_thread_info_detach ();
4337 start_writer_thread (MonoProfiler* prof)
4339 InterlockedWrite (&prof->run_writer_thread, 1);
4341 if (!mono_native_thread_create (&prof->writer_thread, writer_thread, prof)) {
4342 fprintf (stderr, "Could not start writer thread\n");
4348 reuse_sample_hit (gpointer p)
4350 SampleHit *sample = p;
4352 mono_lock_free_queue_node_unpoison (&sample->node);
4353 mono_lock_free_queue_enqueue (&sample->prof->sample_reuse_queue, &sample->node);
4357 handle_dumper_queue_entry (MonoProfiler *prof)
4361 if ((sample = (SampleHit *) mono_lock_free_queue_dequeue (&prof->dumper_queue))) {
4362 for (int i = 0; i < sample->count; ++i) {
4363 MonoMethod *method = sample->frames [i].method;
4364 MonoDomain *domain = sample->frames [i].domain;
4365 void *address = sample->frames [i].base_address;
4368 g_assert (domain && "What happened to the domain pointer?");
4369 g_assert (address && "What happened to the instruction pointer?");
4371 MonoJitInfo *ji = mono_jit_info_table_find (domain, (char *) address);
4374 sample->frames [i].method = mono_jit_info_get_method (ji);
4378 ENTER_LOG (&sample_hits_ctr, logbuffer,
4379 EVENT_SIZE /* event */ +
4380 BYTE_SIZE /* type */ +
4381 LEB128_SIZE /* tid */ +
4382 LEB128_SIZE /* count */ +
4384 LEB128_SIZE /* ip */
4386 LEB128_SIZE /* managed count */ +
4388 LEB128_SIZE /* method */
4392 emit_event_time (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_HIT, sample->time);
4393 emit_byte (logbuffer, SAMPLE_CYCLES);
4394 emit_ptr (logbuffer, (void *) sample->tid);
4395 emit_value (logbuffer, 1);
4397 // TODO: Actual native unwinding.
4398 for (int i = 0; i < 1; ++i) {
4399 emit_ptr (logbuffer, sample->ip);
4400 add_code_pointer ((uintptr_t) sample->ip);
4403 /* new in data version 6 */
4404 emit_uvalue (logbuffer, sample->count);
4406 for (int i = 0; i < sample->count; ++i)
4407 emit_method (logbuffer, sample->frames [i].method);
4409 EXIT_LOG_EXPLICIT (DO_SEND);
4411 mono_thread_hazardous_try_free (sample, reuse_sample_hit);
4413 dump_unmanaged_coderefs (prof);
4420 dumper_thread (void *arg)
4422 MonoProfiler *prof = (MonoProfiler *)arg;
4424 mono_threads_attach_tools_thread ();
4425 mono_native_thread_set_name (mono_native_thread_id_get (), "Profiler dumper");
4427 MonoProfilerThread *thread = init_thread (prof, FALSE);
4429 while (InterlockedRead (&prof->run_dumper_thread)) {
4431 * Flush samples every second so it doesn't seem like the profiler is
4432 * not working if the program is mostly idle.
4434 if (mono_os_sem_timedwait (&prof->dumper_queue_sem, 1000, MONO_SEM_FLAGS_NONE) == MONO_SEM_TIMEDWAIT_RET_TIMEDOUT)
4435 send_log_unsafe (FALSE);
4437 handle_dumper_queue_entry (prof);
4440 /* Drain any remaining entries on shutdown. */
4441 while (handle_dumper_queue_entry (prof));
4443 send_log_unsafe (FALSE);
4444 deinit_thread (thread);
4446 mono_thread_info_detach ();
4452 start_dumper_thread (MonoProfiler* prof)
4454 InterlockedWrite (&prof->run_dumper_thread, 1);
4456 if (!mono_native_thread_create (&prof->dumper_thread, dumper_thread, prof)) {
4457 fprintf (stderr, "Could not start dumper thread\n");
4463 register_counter (const char *name, gint32 *counter)
4465 mono_counters_register (name, MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, counter);
4469 runtime_initialized (MonoProfiler *profiler)
4471 InterlockedWrite (&runtime_inited, 1);
4473 register_counter ("Sample events allocated", &sample_allocations_ctr);
4474 register_counter ("Log buffers allocated", &buffer_allocations_ctr);
4476 register_counter ("Event: Sync points", &sync_points_ctr);
4477 register_counter ("Event: Heap objects", &heap_objects_ctr);
4478 register_counter ("Event: Heap starts", &heap_starts_ctr);
4479 register_counter ("Event: Heap ends", &heap_ends_ctr);
4480 register_counter ("Event: Heap roots", &heap_roots_ctr);
4481 register_counter ("Event: GC events", &gc_events_ctr);
4482 register_counter ("Event: GC resizes", &gc_resizes_ctr);
4483 register_counter ("Event: GC allocations", &gc_allocs_ctr);
4484 register_counter ("Event: GC moves", &gc_moves_ctr);
4485 register_counter ("Event: GC handle creations", &gc_handle_creations_ctr);
4486 register_counter ("Event: GC handle deletions", &gc_handle_deletions_ctr);
4487 register_counter ("Event: GC finalize starts", &finalize_begins_ctr);
4488 register_counter ("Event: GC finalize ends", &finalize_ends_ctr);
4489 register_counter ("Event: GC finalize object starts", &finalize_object_begins_ctr);
4490 register_counter ("Event: GC finalize object ends", &finalize_object_ends_ctr);
4491 register_counter ("Event: Image loads", &image_loads_ctr);
4492 register_counter ("Event: Image unloads", &image_unloads_ctr);
4493 register_counter ("Event: Assembly loads", &assembly_loads_ctr);
4494 register_counter ("Event: Assembly unloads", &assembly_unloads_ctr);
4495 register_counter ("Event: Class loads", &class_loads_ctr);
4496 register_counter ("Event: Class unloads", &class_unloads_ctr);
4497 register_counter ("Event: Method entries", &method_entries_ctr);
4498 register_counter ("Event: Method exits", &method_exits_ctr);
4499 register_counter ("Event: Method exception leaves", &method_exception_exits_ctr);
4500 register_counter ("Event: Method JITs", &method_jits_ctr);
4501 register_counter ("Event: Code buffers", &code_buffers_ctr);
4502 register_counter ("Event: Exception throws", &exception_throws_ctr);
4503 register_counter ("Event: Exception clauses", &exception_clauses_ctr);
4504 register_counter ("Event: Monitor events", &monitor_events_ctr);
4505 register_counter ("Event: Thread starts", &thread_starts_ctr);
4506 register_counter ("Event: Thread ends", &thread_ends_ctr);
4507 register_counter ("Event: Thread names", &thread_names_ctr);
4508 register_counter ("Event: Domain loads", &domain_loads_ctr);
4509 register_counter ("Event: Domain unloads", &domain_unloads_ctr);
4510 register_counter ("Event: Domain names", &domain_names_ctr);
4511 register_counter ("Event: Context loads", &context_loads_ctr);
4512 register_counter ("Event: Context unloads", &context_unloads_ctr);
4513 register_counter ("Event: Sample binaries", &sample_ubins_ctr);
4514 register_counter ("Event: Sample symbols", &sample_usyms_ctr);
4515 register_counter ("Event: Sample hits", &sample_hits_ctr);
4516 register_counter ("Event: Counter descriptors", &counter_descriptors_ctr);
4517 register_counter ("Event: Counter samples", &counter_samples_ctr);
4518 register_counter ("Event: Performance counter descriptors", &perfcounter_descriptors_ctr);
4519 register_counter ("Event: Performance counter samples", &perfcounter_samples_ctr);
4520 register_counter ("Event: Coverage methods", &coverage_methods_ctr);
4521 register_counter ("Event: Coverage statements", &coverage_statements_ctr);
4522 register_counter ("Event: Coverage classes", &coverage_classes_ctr);
4523 register_counter ("Event: Coverage assemblies", &coverage_assemblies_ctr);
4525 counters_init (profiler);
4528 * We must start the helper thread before the writer thread. This is
4529 * because the helper thread sets up the command port which is written to
4530 * the log header by the writer thread.
4532 start_helper_thread (profiler);
4533 start_writer_thread (profiler);
4534 start_dumper_thread (profiler);
4538 create_profiler (const char *args, const char *filename, GPtrArray *filters)
4541 int force_delete = 0;
4543 log_profiler = (MonoProfiler *) g_calloc (1, sizeof (MonoProfiler));
4544 log_profiler->args = pstrdup (args);
4545 log_profiler->command_port = command_port;
4547 if (filename && *filename == '-') {
4550 g_warning ("WARNING: the output:-FILENAME option is deprecated, the profiler now always overrides the output file\n");
4553 //If filename begin with +, append the pid at the end
4554 if (filename && *filename == '+')
4555 filename = g_strdup_printf ("%s.%d", filename + 1, getpid ());
4560 filename = "|mprof-report -";
4562 filename = "output.mlpd";
4563 nf = (char*)filename;
4565 nf = new_filename (filename);
4567 int s = strlen (nf) + 32;
4568 char *p = (char *) g_malloc (s);
4569 snprintf (p, s, "|mprof-report '--out=%s' -", nf);
4575 log_profiler->file = popen (nf + 1, "w");
4576 log_profiler->pipe_output = 1;
4577 } else if (*nf == '#') {
4578 int fd = strtol (nf + 1, NULL, 10);
4579 log_profiler->file = fdopen (fd, "a");
4583 log_profiler->file = fopen (nf, "wb");
4585 if (!log_profiler->file) {
4586 fprintf (stderr, "Cannot create profiler output: %s\n", nf);
4590 #if defined (HAVE_SYS_ZLIB)
4592 log_profiler->gzfile = gzdopen (fileno (log_profiler->file), "wb");
4596 * If you hit this assert while increasing MAX_FRAMES, you need to increase
4597 * SAMPLE_BLOCK_SIZE as well.
4599 g_assert (SAMPLE_SLOT_SIZE (MAX_FRAMES) * 2 < LOCK_FREE_ALLOC_SB_USABLE_SIZE (SAMPLE_BLOCK_SIZE));
4601 // FIXME: We should free this stuff too.
4602 mono_lock_free_allocator_init_size_class (&log_profiler->sample_size_class, SAMPLE_SLOT_SIZE (num_frames), SAMPLE_BLOCK_SIZE);
4603 mono_lock_free_allocator_init_allocator (&log_profiler->sample_allocator, &log_profiler->sample_size_class, MONO_MEM_ACCOUNT_PROFILER);
4605 mono_lock_free_queue_init (&log_profiler->sample_reuse_queue);
4607 g_assert (sizeof (WriterQueueEntry) * 2 < LOCK_FREE_ALLOC_SB_USABLE_SIZE (WRITER_ENTRY_BLOCK_SIZE));
4609 // FIXME: We should free this stuff too.
4610 mono_lock_free_allocator_init_size_class (&log_profiler->writer_entry_size_class, sizeof (WriterQueueEntry), WRITER_ENTRY_BLOCK_SIZE);
4611 mono_lock_free_allocator_init_allocator (&log_profiler->writer_entry_allocator, &log_profiler->writer_entry_size_class, MONO_MEM_ACCOUNT_PROFILER);
4613 mono_lock_free_queue_init (&log_profiler->writer_queue);
4614 mono_os_sem_init (&log_profiler->writer_queue_sem, 0);
4616 mono_lock_free_queue_init (&log_profiler->dumper_queue);
4617 mono_os_sem_init (&log_profiler->dumper_queue_sem, 0);
4619 mono_os_mutex_init (&log_profiler->method_table_mutex);
4620 log_profiler->method_table = mono_conc_hashtable_new (NULL, NULL);
4623 coverage_init (log_profiler);
4624 log_profiler->coverage_filters = filters;
4626 log_profiler->startup_time = current_time ();
4630 * declaration to silence the compiler: this is the entry point that
4631 * mono will load from the shared library and call.
4634 mono_profiler_startup (const char *desc);
4637 mono_profiler_startup_log (const char *desc);
4640 * this is the entry point that will be used when the profiler
4641 * is embedded inside the main executable.
4644 mono_profiler_startup_log (const char *desc)
4646 mono_profiler_startup (desc);
4650 mono_profiler_startup (const char *desc)
4652 GPtrArray *filters = NULL;
4654 proflog_parse_args (&config, desc [3] == ':' ? desc + 4 : "");
4656 //XXX maybe later cleanup to use config directly
4657 nocalls = !(config.effective_mask & PROFLOG_CALL_EVENTS);
4658 no_counters = !(config.effective_mask & PROFLOG_COUNTER_EVENTS);
4659 do_report = config.do_report;
4660 do_debug = config.do_debug;
4661 do_heap_shot = (config.effective_mask & PROFLOG_HEAPSHOT_FEATURE);
4662 hs_mode_ondemand = config.hs_mode_ondemand;
4663 hs_mode_ms = config.hs_mode_ms;
4664 hs_mode_gc = config.hs_mode_gc;
4665 do_mono_sample = (config.effective_mask & PROFLOG_SAMPLING_FEATURE);
4666 use_zip = config.use_zip;
4667 command_port = config.command_port;
4668 num_frames = config.num_frames;
4669 notraces = config.notraces;
4670 max_allocated_sample_hits = config.max_allocated_sample_hits;
4671 max_call_depth = config.max_call_depth;
4672 do_coverage = (config.effective_mask & PROFLOG_CODE_COV_FEATURE);
4673 debug_coverage = config.debug_coverage;
4674 only_coverage = config.only_coverage;
4676 if (config.cov_filter_files) {
4677 filters = g_ptr_array_new ();
4679 for (i = 0; i < config.cov_filter_files->len; ++i) {
4680 const char *name = config.cov_filter_files->pdata [i];
4681 parse_cov_filter_file (filters, name);
4689 create_profiler (desc, config.output_filename, filters);
4691 mono_lls_init (&profiler_thread_list, NULL);
4693 //This two events are required for the profiler to work
4694 int events = MONO_PROFILE_THREADS | MONO_PROFILE_GC;
4696 //Required callbacks
4697 mono_profiler_install (log_profiler, log_shutdown);
4698 mono_profiler_install_runtime_initialized (runtime_initialized);
4700 mono_profiler_install_gc (gc_event, gc_resize);
4701 mono_profiler_install_thread (thread_start, thread_end);
4703 //It's questionable whether we actually want this to be mandatory, maybe put it behind the actual event?
4704 mono_profiler_install_thread_name (thread_name);
4707 if (config.effective_mask & PROFLOG_DOMAIN_EVENTS) {
4708 events |= MONO_PROFILE_APPDOMAIN_EVENTS;
4709 mono_profiler_install_appdomain (NULL, domain_loaded, domain_unloaded, NULL);
4710 mono_profiler_install_appdomain_name (domain_name);
4713 if (config.effective_mask & PROFLOG_ASSEMBLY_EVENTS) {
4714 events |= MONO_PROFILE_ASSEMBLY_EVENTS;
4715 mono_profiler_install_assembly (NULL, assembly_loaded, assembly_unloaded, NULL);
4718 if (config.effective_mask & PROFLOG_MODULE_EVENTS) {
4719 events |= MONO_PROFILE_MODULE_EVENTS;
4720 mono_profiler_install_module (NULL, image_loaded, image_unloaded, NULL);
4723 if (config.effective_mask & PROFLOG_CLASS_EVENTS) {
4724 events |= MONO_PROFILE_CLASS_EVENTS;
4725 mono_profiler_install_class (NULL, class_loaded, NULL, NULL);
4728 if (config.effective_mask & PROFLOG_JIT_COMPILATION_EVENTS) {
4729 events |= MONO_PROFILE_JIT_COMPILATION;
4730 mono_profiler_install_jit_end (method_jitted);
4731 mono_profiler_install_code_buffer_new (code_buffer_new);
4734 if (config.effective_mask & PROFLOG_EXCEPTION_EVENTS) {
4735 events |= MONO_PROFILE_EXCEPTIONS;
4736 mono_profiler_install_exception (throw_exc, method_exc_leave, NULL);
4737 mono_profiler_install_exception_clause (clause_exc);
4740 if (config.effective_mask & PROFLOG_ALLOCATION_EVENTS) {
4741 events |= MONO_PROFILE_ALLOCATIONS;
4742 mono_profiler_install_allocation (gc_alloc);
4745 //PROFLOG_GC_EVENTS is mandatory
4746 //PROFLOG_THREAD_EVENTS is mandatory
4748 if (config.effective_mask & PROFLOG_CALL_EVENTS) {
4749 events |= MONO_PROFILE_ENTER_LEAVE;
4750 mono_profiler_install_enter_leave (method_enter, method_leave);
4753 if (config.effective_mask & PROFLOG_INS_COVERAGE_EVENTS) {
4754 events |= MONO_PROFILE_INS_COVERAGE;
4755 mono_profiler_install_coverage_filter (coverage_filter);
4758 //XXX should we check for PROFLOG_SAMPLING_FEATURE instead??
4759 if (config.effective_mask & PROFLOG_SAMPLING_EVENTS) {
4760 events |= MONO_PROFILE_STATISTICAL;
4761 mono_profiler_set_statistical_mode (config.sampling_mode, config.sample_freq);
4762 mono_profiler_install_statistical (mono_sample_hit);
4765 if (config.effective_mask & PROFLOG_MONITOR_EVENTS) {
4766 events |= MONO_PROFILE_MONITOR_EVENTS;
4767 mono_profiler_install_monitor (monitor_event);
4770 if (config.effective_mask & PROFLOG_GC_MOVES_EVENTS) {
4771 events |= MONO_PROFILE_GC_MOVES;
4772 mono_profiler_install_gc_moves (gc_moves);
4775 // TODO split those in two profiler events
4776 if (config.effective_mask & (PROFLOG_GC_ROOT_EVENTS | PROFLOG_GC_HANDLE_EVENTS)) {
4777 events |= MONO_PROFILE_GC_ROOTS;
4778 mono_profiler_install_gc_roots (
4779 config.effective_mask & (PROFLOG_GC_HANDLE_EVENTS) ? gc_handle : NULL,
4780 (config.effective_mask & PROFLOG_GC_ROOT_EVENTS) ? gc_roots : NULL);
4783 if (config.effective_mask & PROFLOG_CONTEXT_EVENTS) {
4784 events |= MONO_PROFILE_CONTEXT_EVENTS;
4785 mono_profiler_install_context (context_loaded, context_unloaded);
4788 if (config.effective_mask & PROFLOG_FINALIZATION_EVENTS) {
4789 events |= MONO_PROFILE_GC_FINALIZATION;
4790 mono_profiler_install_gc_finalize (finalize_begin, finalize_object_begin, finalize_object_end, finalize_end);
4791 } else if (ENABLED (PROFLOG_HEAPSHOT_FEATURE) && config.hs_mode_ondemand) {
4792 //On Demand heapshot uses the finalizer thread to force a collection and thus a heapshot
4793 events |= MONO_PROFILE_GC_FINALIZATION;
4794 mono_profiler_install_gc_finalize (NULL, NULL, NULL, finalize_end);
4797 //PROFLOG_COUNTER_EVENTS is a pseudo event controled by the no_counters global var
4798 //PROFLOG_GC_HANDLE_EVENTS is handled together with PROFLOG_GC_ROOT_EVENTS
4800 mono_profiler_set_events ((MonoProfileFlags)events);