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 * [mtype: byte] metadata type, one of: TYPE_CLASS, TYPE_IMAGE, TYPE_ASSEMBLY, TYPE_DOMAIN,
263 * TYPE_THREAD, TYPE_CONTEXT
264 * [pointer: sleb128] pointer of the metadata type depending on mtype
265 * if mtype == TYPE_CLASS
266 * [image: sleb128] MonoImage* as a pointer difference from ptr_base
267 * [name: string] full class name
268 * if mtype == TYPE_IMAGE
269 * [name: string] image file name
270 * if mtype == TYPE_ASSEMBLY
271 * [image: sleb128] MonoImage* as a pointer difference from ptr_base
272 * [name: string] assembly name
273 * if mtype == TYPE_DOMAIN && exinfo == 0
274 * [name: string] domain friendly name
275 * if mtype == TYPE_CONTEXT
276 * [domain: sleb128] domain id as pointer
277 * if mtype == TYPE_THREAD && exinfo == 0
278 * [name: string] thread name
280 * type method format:
282 * exinfo: one of: TYPE_LEAVE, TYPE_ENTER, TYPE_EXC_LEAVE, TYPE_JIT
283 * [method: sleb128] MonoMethod* as a pointer difference from the last such
284 * pointer or the buffer method_base
285 * if exinfo == TYPE_JIT
286 * [code address: sleb128] pointer to the native code as a diff from ptr_base
287 * [code size: uleb128] size of the generated code
288 * [name: string] full method name
290 * type exception format:
291 * type: TYPE_EXCEPTION
292 * exinfo: zero, TYPE_CLAUSE, or TYPE_THROW_BT
293 * if exinfo == TYPE_CLAUSE
294 * [clause type: byte] MonoExceptionEnum enum value
295 * [clause index: uleb128] index of the current clause
296 * [method: sleb128] MonoMethod* as a pointer difference from the last such
297 * pointer or the buffer method_base
298 * [object: sleb128] the exception object as a difference from obj_base
300 * [object: sleb128] the exception object as a difference from obj_base
301 * If exinfo == TYPE_THROW_BT, a backtrace follows.
303 * type runtime format:
305 * exinfo: one of: TYPE_JITHELPER
306 * if exinfo == TYPE_JITHELPER
307 * [type: byte] MonoProfilerCodeBufferType enum value
308 * [buffer address: sleb128] pointer to the native code as a diff from ptr_base
309 * [buffer size: uleb128] size of the generated code
310 * if type == MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE
311 * [name: string] buffer description name
313 * type monitor format:
315 * exinfo: zero or TYPE_MONITOR_BT
316 * [type: byte] MONO_PROFILER_MONITOR_{CONTENTION,FAIL,DONE}
317 * [object: sleb128] the lock object as a difference from obj_base
318 * If exinfo == TYPE_MONITOR_BT, a backtrace follows.
322 * exinfo: one of TYPE_HEAP_START, TYPE_HEAP_END, TYPE_HEAP_OBJECT, TYPE_HEAP_ROOT
323 * if exinfo == TYPE_HEAP_OBJECT
324 * [object: sleb128] the object as a difference from obj_base
325 * [class: sleb128] the object MonoClass* as a difference from ptr_base
326 * [size: uleb128] size of the object on the heap
327 * [num_refs: uleb128] number of object references
328 * each referenced objref is preceded by a uleb128 encoded offset: the
329 * first offset is from the object address and each next offset is relative
330 * to the previous one
331 * [objrefs: sleb128]+ object referenced as a difference from obj_base
332 * The same object can appear multiple times, but only the first time
333 * with size != 0: in the other cases this data will only be used to
334 * provide additional referenced objects.
335 * if exinfo == TYPE_HEAP_ROOT
336 * [num_roots: uleb128] number of root references
337 * [num_gc: uleb128] number of major gcs
338 * [object: sleb128] the object as a difference from obj_base
339 * [root_type: byte] the root_type: MonoProfileGCRootType (profiler.h)
340 * [extra_info: uleb128] the extra_info value
341 * object, root_type and extra_info are repeated num_roots times
345 * exinfo: one of TYPE_SAMPLE_HIT, TYPE_SAMPLE_USYM, TYPE_SAMPLE_UBIN, TYPE_SAMPLE_COUNTERS_DESC, TYPE_SAMPLE_COUNTERS
346 * if exinfo == TYPE_SAMPLE_HIT
347 * [thread: sleb128] thread id as difference from ptr_base
348 * [count: uleb128] number of following instruction addresses
349 * [ip: sleb128]* instruction pointer as difference from ptr_base
350 * [mbt_count: uleb128] number of managed backtrace frames
351 * [method: sleb128]* MonoMethod* as a pointer difference from the last such
352 * pointer or the buffer method_base (the first such method can be also indentified by ip, but this is not neccessarily true)
353 * if exinfo == TYPE_SAMPLE_USYM
354 * [address: sleb128] symbol address as a difference from ptr_base
355 * [size: uleb128] symbol size (may be 0 if unknown)
356 * [name: string] symbol name
357 * if exinfo == TYPE_SAMPLE_UBIN
358 * [address: sleb128] address where binary has been loaded as a difference from ptr_base
359 * [offset: uleb128] file offset of mapping (the same file can be mapped multiple times)
360 * [size: uleb128] memory size
361 * [name: string] binary name
362 * if exinfo == TYPE_SAMPLE_COUNTERS_DESC
363 * [len: uleb128] number of counters
365 * [section: uleb128] section of counter
366 * if section == MONO_COUNTER_PERFCOUNTERS:
367 * [section_name: string] section name of counter
368 * [name: string] name of counter
369 * [type: byte] type of counter
370 * [unit: byte] unit of counter
371 * [variance: byte] variance of counter
372 * [index: uleb128] unique index of counter
373 * if exinfo == TYPE_SAMPLE_COUNTERS
375 * [index: uleb128] unique index of counter
378 * [type: byte] type of counter value
381 * [0: byte] 0 -> value is null
383 * [1: byte] 1 -> value is not null
384 * [value: string] counter value
386 * [value: uleb128/sleb128/double] counter value, can be sleb128, uleb128 or double (determined by using type)
388 * type coverage format
389 * type: TYPE_COVERAGE
390 * exinfo: one of TYPE_COVERAGE_METHOD, TYPE_COVERAGE_STATEMENT, TYPE_COVERAGE_ASSEMBLY, TYPE_COVERAGE_CLASS
391 * if exinfo == TYPE_COVERAGE_METHOD
392 * [assembly: string] name of assembly
393 * [class: string] name of the class
394 * [name: string] name of the method
395 * [signature: string] the signature of the method
396 * [filename: string] the file path of the file that contains this method
397 * [token: uleb128] the method token
398 * [method_id: uleb128] an ID for this data to associate with the buffers of TYPE_COVERAGE_STATEMENTS
399 * [len: uleb128] the number of TYPE_COVERAGE_BUFFERS associated with this method
400 * if exinfo == TYPE_COVERAGE_STATEMENTS
401 * [method_id: uleb128] an the TYPE_COVERAGE_METHOD buffer to associate this with
402 * [offset: uleb128] the il offset relative to the previous offset
403 * [counter: uleb128] the counter for this instruction
404 * [line: uleb128] the line of filename containing this instruction
405 * [column: uleb128] the column containing this instruction
406 * if exinfo == TYPE_COVERAGE_ASSEMBLY
407 * [name: string] assembly name
408 * [guid: string] assembly GUID
409 * [filename: string] assembly filename
410 * [number_of_methods: uleb128] the number of methods in this assembly
411 * [fully_covered: uleb128] the number of fully covered methods
412 * [partially_covered: uleb128] the number of partially covered methods
413 * currently partially_covered will always be 0, and fully_covered is the
414 * number of methods that are fully and partially covered.
415 * if exinfo == TYPE_COVERAGE_CLASS
416 * [name: string] assembly name
417 * [class: string] class name
418 * [number_of_methods: uleb128] the number of methods in this class
419 * [fully_covered: uleb128] the number of fully covered methods
420 * [partially_covered: uleb128] the number of partially covered methods
421 * currently partially_covered will always be 0, and fully_covered is the
422 * number of methods that are fully and partially covered.
426 * exinfo: one of: TYPE_SYNC_POINT
427 * if exinfo == TYPE_SYNC_POINT
428 * [type: byte] MonoProfilerSyncPointType enum value
431 // Pending data to be written to the log, for a single thread.
432 // Threads periodically flush their own LogBuffers by calling safe_send
433 typedef struct _LogBuffer LogBuffer;
435 // Next (older) LogBuffer in processing queue
441 uintptr_t method_base;
442 uintptr_t last_method;
446 // Bytes allocated for this LogBuffer
449 // Start of currently unused space in buffer
450 unsigned char* cursor;
452 // Pointer to start-of-structure-plus-size (for convenience)
453 unsigned char* buf_end;
455 // Start of data in buffer. Contents follow "buffer format" described above.
456 unsigned char buf [1];
460 MonoLinkedListSetNode node;
462 // Convenience pointer to the profiler structure.
463 MonoProfiler *profiler;
465 // Was this thread added to the LLS?
468 // The current log buffer for this thread.
471 // Methods referenced by events in `buffer`, see `MethodInfo`.
474 // Current call depth for enter/leave events.
477 // Indicates whether this thread is currently writing to its `buffer`.
480 // Has this thread written a thread end event to `buffer`?
482 } MonoProfilerThread;
487 return (uintptr_t) mono_native_thread_id_get ();
494 return (uintptr_t) GetCurrentProcessId ();
496 return (uintptr_t) getpid ();
501 static mach_timebase_info_data_t timebase_info;
502 #elif defined (HOST_WIN32)
503 static LARGE_INTEGER pcounter_freq;
506 #define TICKS_PER_SEC 1000000000LL
512 uint64_t time = mach_absolute_time ();
514 time *= timebase_info.numer;
515 time /= timebase_info.denom;
518 #elif defined (HOST_WIN32)
521 QueryPerformanceCounter (&value);
523 return value.QuadPart * TICKS_PER_SEC / pcounter_freq.QuadPart;
524 #elif defined (CLOCK_MONOTONIC)
525 struct timespec tspec;
527 clock_gettime (CLOCK_MONOTONIC, &tspec);
529 return ((uint64_t) tspec.tv_sec * TICKS_PER_SEC + tspec.tv_nsec);
533 gettimeofday (&tv, NULL);
535 return ((uint64_t) tv.tv_sec * TICKS_PER_SEC + tv.tv_usec * 1000);
539 static int timer_overhead;
545 mach_timebase_info (&timebase_info);
546 #elif defined (HOST_WIN32)
547 QueryPerformanceFrequency (&pcounter_freq);
550 uint64_t time_start = current_time ();
552 for (int i = 0; i < 256; ++i)
555 uint64_t time_end = current_time ();
557 timer_overhead = (time_end - time_start) / 256;
561 * These macros should be used when writing an event to a log buffer. They
562 * take care of a bunch of stuff that can be repetitive and error-prone, such
563 * as attaching the current thread, acquiring/releasing the buffer lock,
564 * incrementing the event counter, expanding the log buffer, etc. They also
565 * create a scope so that it's harder to leak the LogBuffer pointer, which can
566 * be problematic as the pointer is unstable when the buffer lock isn't
569 * If the calling thread is already attached, these macros will not alter its
570 * attach mode (i.e. whether it's added to the LLS). If the thread is not
571 * attached, init_thread () will be called with add_to_lls = TRUE.
574 #define ENTER_LOG(COUNTER, BUFFER, SIZE) \
576 MonoProfilerThread *thread__ = get_thread (); \
577 if (thread__->attached) \
579 g_assert (!thread__->busy && "Why are we trying to write a new event while already writing one?"); \
580 thread__->busy = TRUE; \
581 InterlockedIncrement ((COUNTER)); \
582 LogBuffer *BUFFER = ensure_logbuf_unsafe (thread__, (SIZE))
584 #define EXIT_LOG_EXPLICIT(SEND) \
585 thread__->busy = FALSE; \
587 send_log_unsafe (TRUE); \
588 if (thread__->attached) \
592 // Pass these to EXIT_LOG_EXPLICIT () for easier reading.
594 #define NO_SEND FALSE
596 #define EXIT_LOG EXIT_LOG_EXPLICIT (DO_SEND)
598 static volatile gint32 buffer_rwlock_count;
599 static volatile gpointer buffer_rwlock_exclusive;
601 // Can be used recursively.
606 * If the thread holding the exclusive lock tries to modify the
607 * reader count, just make it a no-op. This way, we also avoid
608 * invoking the GC safe point macros below, which could break if
609 * done from a thread that is currently the initiator of STW.
611 * In other words, we rely on the fact that the GC thread takes
612 * the exclusive lock in the gc_event () callback when the world
615 if (InterlockedReadPointer (&buffer_rwlock_exclusive) != (gpointer) thread_id ()) {
618 while (InterlockedReadPointer (&buffer_rwlock_exclusive))
619 mono_thread_info_yield ();
621 InterlockedIncrement (&buffer_rwlock_count);
626 mono_memory_barrier ();
632 mono_memory_barrier ();
634 // See the comment in buffer_lock ().
635 if (InterlockedReadPointer (&buffer_rwlock_exclusive) == (gpointer) thread_id ())
638 g_assert (InterlockedRead (&buffer_rwlock_count) && "Why are we trying to decrement a zero reader count?");
640 InterlockedDecrement (&buffer_rwlock_count);
643 // Cannot be used recursively.
645 buffer_lock_excl (void)
647 gpointer tid = (gpointer) thread_id ();
649 g_assert (InterlockedReadPointer (&buffer_rwlock_exclusive) != tid && "Why are we taking the exclusive lock twice?");
653 while (InterlockedCompareExchangePointer (&buffer_rwlock_exclusive, tid, 0))
654 mono_thread_info_yield ();
656 while (InterlockedRead (&buffer_rwlock_count))
657 mono_thread_info_yield ();
661 mono_memory_barrier ();
665 buffer_unlock_excl (void)
667 mono_memory_barrier ();
669 g_assert (InterlockedReadPointer (&buffer_rwlock_exclusive) && "Why is the exclusive lock not held?");
670 g_assert (InterlockedReadPointer (&buffer_rwlock_exclusive) == (gpointer) thread_id () && "Why does another thread hold the exclusive lock?");
671 g_assert (!InterlockedRead (&buffer_rwlock_count) && "Why are there readers when the exclusive lock is held?");
673 InterlockedWritePointer (&buffer_rwlock_exclusive, NULL);
676 typedef struct _BinaryObject BinaryObject;
677 struct _BinaryObject {
683 static MonoProfiler *log_profiler;
685 struct _MonoProfiler {
687 #if defined (HAVE_SYS_ZLIB)
691 uint64_t startup_time;
696 MonoNativeThreadId helper_thread;
697 MonoNativeThreadId writer_thread;
698 MonoNativeThreadId dumper_thread;
699 volatile gint32 run_writer_thread;
700 MonoLockFreeAllocSizeClass writer_entry_size_class;
701 MonoLockFreeAllocator writer_entry_allocator;
702 MonoLockFreeQueue writer_queue;
703 MonoSemType writer_queue_sem;
704 MonoConcurrentHashTable *method_table;
705 mono_mutex_t method_table_mutex;
706 volatile gint32 run_dumper_thread;
707 MonoLockFreeQueue dumper_queue;
708 MonoSemType dumper_queue_sem;
709 MonoLockFreeAllocSizeClass sample_size_class;
710 MonoLockFreeAllocator sample_allocator;
711 MonoLockFreeQueue sample_reuse_queue;
712 BinaryObject *binary_objects;
713 GPtrArray *coverage_filters;
717 MonoLockFreeQueueNode node;
722 #define WRITER_ENTRY_BLOCK_SIZE (mono_pagesize ())
730 // Do not use these TLS macros directly unless you know what you're doing.
734 #define PROF_TLS_SET(VAL) (TlsSetValue (profiler_tls, (VAL)))
735 #define PROF_TLS_GET() ((MonoProfilerThread *) TlsGetValue (profiler_tls))
736 #define PROF_TLS_INIT() (profiler_tls = TlsAlloc ())
737 #define PROF_TLS_FREE() (TlsFree (profiler_tls))
739 static DWORD profiler_tls;
743 #define PROF_TLS_SET(VAL) (profiler_tls = (VAL))
744 #define PROF_TLS_GET() (profiler_tls)
745 #define PROF_TLS_INIT()
746 #define PROF_TLS_FREE()
748 static __thread MonoProfilerThread *profiler_tls;
752 #define PROF_TLS_SET(VAL) (pthread_setspecific (profiler_tls, (VAL)))
753 #define PROF_TLS_GET() ((MonoProfilerThread *) pthread_getspecific (profiler_tls))
754 #define PROF_TLS_INIT() (pthread_key_create (&profiler_tls, NULL))
755 #define PROF_TLS_FREE() (pthread_key_delete (profiler_tls))
757 static pthread_key_t profiler_tls;
762 pstrdup (const char *s)
764 int len = strlen (s) + 1;
765 char *p = (char *) g_malloc (len);
771 alloc_buffer (int size)
773 return mono_valloc (NULL, size, MONO_MMAP_READ | MONO_MMAP_WRITE | MONO_MMAP_ANON | MONO_MMAP_PRIVATE, MONO_MEM_ACCOUNT_PROFILER);
777 free_buffer (void *buf, int size)
779 mono_vfree (buf, size, MONO_MEM_ACCOUNT_PROFILER);
783 create_buffer (uintptr_t tid, int bytes)
785 LogBuffer* buf = (LogBuffer *) alloc_buffer (MAX (BUFFER_SIZE, bytes));
787 InterlockedIncrement (&buffer_allocations_ctr);
789 buf->size = BUFFER_SIZE;
790 buf->time_base = current_time ();
791 buf->last_time = buf->time_base;
792 buf->buf_end = (unsigned char *) buf + buf->size;
793 buf->cursor = buf->buf;
794 buf->thread_id = tid;
800 * Must be called with the reader lock held if thread is the current thread, or
801 * the exclusive lock if thread is a different thread. However, if thread is
802 * the current thread, and init_thread () was called with add_to_lls = FALSE,
803 * then no locking is necessary.
806 init_buffer_state (MonoProfilerThread *thread)
808 thread->buffer = create_buffer (thread->node.key, 0);
809 thread->methods = NULL;
813 clear_hazard_pointers (MonoThreadHazardPointers *hp)
815 mono_hazard_pointer_clear (hp, 0);
816 mono_hazard_pointer_clear (hp, 1);
817 mono_hazard_pointer_clear (hp, 2);
820 static MonoProfilerThread *
821 init_thread (MonoProfiler *prof, gboolean add_to_lls)
823 MonoProfilerThread *thread = PROF_TLS_GET ();
826 * Sometimes we may try to initialize a thread twice. One example is the
827 * main thread: We initialize it when setting up the profiler, but we will
828 * also get a thread_start () callback for it. Another example is when
829 * attaching new threads to the runtime: We may get a gc_alloc () callback
830 * for that thread's thread object (where we initialize it), soon followed
831 * by a thread_start () callback.
833 * These cases are harmless anyhow. Just return if we've already done the
834 * initialization work.
839 thread = g_malloc (sizeof (MonoProfilerThread));
840 thread->node.key = thread_id ();
841 thread->profiler = prof;
842 thread->attached = add_to_lls;
843 thread->call_depth = 0;
845 thread->ended = FALSE;
847 init_buffer_state (thread);
850 * Some internal profiler threads don't need to be cleaned up
851 * by the main thread on shutdown.
854 MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
855 g_assert (mono_lls_insert (&profiler_thread_list, hp, &thread->node) && "Why can't we insert the thread in the LLS?");
856 clear_hazard_pointers (hp);
859 PROF_TLS_SET (thread);
864 // Only valid if init_thread () was called with add_to_lls = FALSE.
866 deinit_thread (MonoProfilerThread *thread)
868 g_assert (!thread->attached && "Why are we manually freeing an attached thread?");
874 static MonoProfilerThread *
877 return init_thread (log_profiler, TRUE);
880 // Only valid if init_thread () was called with add_to_lls = FALSE.
882 ensure_logbuf_unsafe (MonoProfilerThread *thread, int bytes)
884 LogBuffer *old = thread->buffer;
886 if (old && old->cursor + bytes < old->buf_end)
889 LogBuffer *new_ = create_buffer (thread->node.key, bytes);
891 thread->buffer = new_;
897 encode_uleb128 (uint64_t value, uint8_t *buf, uint8_t **endbuf)
902 uint8_t b = value & 0x7f;
905 if (value != 0) /* more bytes to come */
915 encode_sleb128 (intptr_t value, uint8_t *buf, uint8_t **endbuf)
918 int negative = (value < 0);
919 unsigned int size = sizeof (intptr_t) * 8;
927 /* the following is unnecessary if the
928 * implementation of >>= uses an arithmetic rather
929 * than logical shift for a signed left operand
933 value |= - ((intptr_t) 1 <<(size - 7));
935 /* sign bit of byte is second high order bit (0x40) */
936 if ((value == 0 && !(byte & 0x40)) ||
937 (value == -1 && (byte & 0x40)))
949 emit_byte (LogBuffer *logbuffer, int value)
951 logbuffer->cursor [0] = value;
954 g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
958 emit_value (LogBuffer *logbuffer, int value)
960 encode_uleb128 (value, logbuffer->cursor, &logbuffer->cursor);
962 g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
966 emit_time (LogBuffer *logbuffer, uint64_t value)
968 uint64_t tdiff = value - logbuffer->last_time;
969 encode_uleb128 (tdiff, logbuffer->cursor, &logbuffer->cursor);
970 logbuffer->last_time = value;
972 g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
976 emit_event_time (LogBuffer *logbuffer, int event, uint64_t time)
978 emit_byte (logbuffer, event);
979 emit_time (logbuffer, time);
983 emit_event (LogBuffer *logbuffer, int event)
985 emit_event_time (logbuffer, event, current_time ());
989 emit_svalue (LogBuffer *logbuffer, int64_t value)
991 encode_sleb128 (value, logbuffer->cursor, &logbuffer->cursor);
993 g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
997 emit_uvalue (LogBuffer *logbuffer, uint64_t value)
999 encode_uleb128 (value, logbuffer->cursor, &logbuffer->cursor);
1001 g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
1005 emit_ptr (LogBuffer *logbuffer, void *ptr)
1007 if (!logbuffer->ptr_base)
1008 logbuffer->ptr_base = (uintptr_t) ptr;
1010 emit_svalue (logbuffer, (intptr_t) ptr - logbuffer->ptr_base);
1012 g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
1016 emit_method_inner (LogBuffer *logbuffer, void *method)
1018 if (!logbuffer->method_base) {
1019 logbuffer->method_base = (intptr_t) method;
1020 logbuffer->last_method = (intptr_t) method;
1023 encode_sleb128 ((intptr_t) ((char *) method - (char *) logbuffer->last_method), logbuffer->cursor, &logbuffer->cursor);
1024 logbuffer->last_method = (intptr_t) method;
1026 g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
1030 register_method_local (MonoMethod *method, MonoJitInfo *ji)
1032 MonoProfilerThread *thread = get_thread ();
1034 if (!mono_conc_hashtable_lookup (thread->profiler->method_table, method)) {
1035 MethodInfo *info = (MethodInfo *) g_malloc (sizeof (MethodInfo));
1037 info->method = method;
1039 info->time = current_time ();
1043 GPtrArray *arr = thread->methods ? thread->methods : (thread->methods = g_ptr_array_new ());
1044 g_ptr_array_add (arr, info);
1051 emit_method (LogBuffer *logbuffer, MonoMethod *method)
1053 register_method_local (method, NULL);
1054 emit_method_inner (logbuffer, method);
1058 emit_obj (LogBuffer *logbuffer, void *ptr)
1060 if (!logbuffer->obj_base)
1061 logbuffer->obj_base = (uintptr_t) ptr >> 3;
1063 emit_svalue (logbuffer, ((uintptr_t) ptr >> 3) - logbuffer->obj_base);
1065 g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
1069 emit_string (LogBuffer *logbuffer, const char *str, size_t size)
1073 for (; i < size; i++) {
1076 emit_byte (logbuffer, str [i]);
1079 emit_byte (logbuffer, '\0');
1083 emit_double (LogBuffer *logbuffer, double value)
1086 unsigned char buffer[8];
1087 memcpy (buffer, &value, 8);
1088 #if G_BYTE_ORDER == G_BIG_ENDIAN
1089 for (i = 7; i >= 0; i--)
1091 for (i = 0; i < 8; i++)
1093 emit_byte (logbuffer, buffer[i]);
1097 write_int16 (char *buf, int32_t value)
1100 for (i = 0; i < 2; ++i) {
1108 write_int32 (char *buf, int32_t value)
1111 for (i = 0; i < 4; ++i) {
1119 write_int64 (char *buf, int64_t value)
1122 for (i = 0; i < 8; ++i) {
1130 write_header_string (char *p, const char *str)
1132 size_t len = strlen (str) + 1;
1134 p = write_int32 (p, len);
1141 dump_header (MonoProfiler *profiler)
1143 const char *args = profiler->args;
1144 const char *arch = mono_config_get_cpu ();
1145 const char *os = mono_config_get_os ();
1147 char *hbuf = g_malloc (
1148 sizeof (gint32) /* header id */ +
1149 sizeof (gint8) /* major version */ +
1150 sizeof (gint8) /* minor version */ +
1151 sizeof (gint8) /* data version */ +
1152 sizeof (gint8) /* word size */ +
1153 sizeof (gint64) /* startup time */ +
1154 sizeof (gint32) /* timer overhead */ +
1155 sizeof (gint32) /* flags */ +
1156 sizeof (gint32) /* process id */ +
1157 sizeof (gint16) /* command port */ +
1158 sizeof (gint32) + strlen (args) + 1 /* arguments */ +
1159 sizeof (gint32) + strlen (arch) + 1 /* architecture */ +
1160 sizeof (gint32) + strlen (os) + 1 /* operating system */
1164 p = write_int32 (p, LOG_HEADER_ID);
1165 *p++ = LOG_VERSION_MAJOR;
1166 *p++ = LOG_VERSION_MINOR;
1167 *p++ = LOG_DATA_VERSION;
1168 *p++ = sizeof (void *);
1169 p = write_int64 (p, ((uint64_t) time (NULL)) * 1000);
1170 p = write_int32 (p, timer_overhead);
1171 p = write_int32 (p, 0); /* flags */
1172 p = write_int32 (p, process_id ());
1173 p = write_int16 (p, profiler->command_port);
1174 p = write_header_string (p, args);
1175 p = write_header_string (p, arch);
1176 p = write_header_string (p, os);
1178 #if defined (HAVE_SYS_ZLIB)
1179 if (profiler->gzfile) {
1180 gzwrite (profiler->gzfile, hbuf, p - hbuf);
1184 fwrite (hbuf, p - hbuf, 1, profiler->file);
1185 fflush (profiler->file);
1192 * Must be called with the reader lock held if thread is the current thread, or
1193 * the exclusive lock if thread is a different thread. However, if thread is
1194 * the current thread, and init_thread () was called with add_to_lls = FALSE,
1195 * then no locking is necessary.
1198 send_buffer (MonoProfilerThread *thread)
1200 WriterQueueEntry *entry = mono_lock_free_alloc (&thread->profiler->writer_entry_allocator);
1201 entry->methods = thread->methods;
1202 entry->buffer = thread->buffer;
1204 mono_lock_free_queue_node_init (&entry->node, FALSE);
1206 mono_lock_free_queue_enqueue (&thread->profiler->writer_queue, &entry->node);
1207 mono_os_sem_post (&thread->profiler->writer_queue_sem);
1211 free_thread (gpointer p)
1213 MonoProfilerThread *thread = p;
1215 if (!thread->ended) {
1217 * The thread is being cleaned up by the main thread during
1218 * shutdown. This typically happens for internal runtime
1219 * threads. We need to synthesize a thread end event.
1222 InterlockedIncrement (&thread_ends_ctr);
1224 if (ENABLED (PROFLOG_THREAD_EVENTS)) {
1225 LogBuffer *buf = ensure_logbuf_unsafe (thread,
1226 EVENT_SIZE /* event */ +
1227 BYTE_SIZE /* type */ +
1228 LEB128_SIZE /* tid */
1231 emit_event (buf, TYPE_END_UNLOAD | TYPE_METADATA);
1232 emit_byte (buf, TYPE_THREAD);
1233 emit_ptr (buf, (void *) thread->node.key);
1237 send_buffer (thread);
1243 remove_thread (MonoProfilerThread *thread)
1245 MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
1247 if (mono_lls_remove (&profiler_thread_list, hp, &thread->node))
1248 mono_thread_hazardous_try_free (thread, free_thread);
1250 clear_hazard_pointers (hp);
1254 dump_buffer (MonoProfiler *profiler, LogBuffer *buf)
1260 dump_buffer (profiler, buf->next);
1262 if (buf->cursor - buf->buf) {
1263 p = write_int32 (p, BUF_ID);
1264 p = write_int32 (p, buf->cursor - buf->buf);
1265 p = write_int64 (p, buf->time_base);
1266 p = write_int64 (p, buf->ptr_base);
1267 p = write_int64 (p, buf->obj_base);
1268 p = write_int64 (p, buf->thread_id);
1269 p = write_int64 (p, buf->method_base);
1271 #if defined (HAVE_SYS_ZLIB)
1272 if (profiler->gzfile) {
1273 gzwrite (profiler->gzfile, hbuf, p - hbuf);
1274 gzwrite (profiler->gzfile, buf->buf, buf->cursor - buf->buf);
1278 fwrite (hbuf, p - hbuf, 1, profiler->file);
1279 fwrite (buf->buf, buf->cursor - buf->buf, 1, profiler->file);
1280 fflush (profiler->file);
1284 free_buffer (buf, buf->size);
1288 dump_buffer_threadless (MonoProfiler *profiler, LogBuffer *buf)
1290 for (LogBuffer *iter = buf; iter; iter = iter->next)
1291 iter->thread_id = 0;
1293 dump_buffer (profiler, buf);
1296 // Only valid if init_thread () was called with add_to_lls = FALSE.
1298 send_log_unsafe (gboolean if_needed)
1300 MonoProfilerThread *thread = PROF_TLS_GET ();
1302 if (!if_needed || (if_needed && thread->buffer->next)) {
1303 if (!thread->attached)
1304 for (LogBuffer *iter = thread->buffer; iter; iter = iter->next)
1305 iter->thread_id = 0;
1307 send_buffer (thread);
1308 init_buffer_state (thread);
1312 // Assumes that the exclusive lock is held.
1314 sync_point_flush (void)
1316 g_assert (InterlockedReadPointer (&buffer_rwlock_exclusive) == (gpointer) thread_id () && "Why don't we hold the exclusive lock?");
1318 MONO_LLS_FOREACH_SAFE (&profiler_thread_list, MonoProfilerThread, thread) {
1319 g_assert (thread->attached && "Why is a thread in the LLS not attached?");
1321 send_buffer (thread);
1322 init_buffer_state (thread);
1323 } MONO_LLS_FOREACH_SAFE_END
1326 // Assumes that the exclusive lock is held.
1328 sync_point_mark (MonoProfilerSyncPointType type)
1330 g_assert (InterlockedReadPointer (&buffer_rwlock_exclusive) == (gpointer) thread_id () && "Why don't we hold the exclusive lock?");
1332 ENTER_LOG (&sync_points_ctr, logbuffer,
1333 EVENT_SIZE /* event */ +
1334 LEB128_SIZE /* type */
1337 emit_event (logbuffer, TYPE_META | TYPE_SYNC_POINT);
1338 emit_byte (logbuffer, type);
1340 EXIT_LOG_EXPLICIT (NO_SEND);
1342 send_log_unsafe (FALSE);
1345 // Assumes that the exclusive lock is held.
1347 sync_point (MonoProfilerSyncPointType type)
1349 sync_point_flush ();
1350 sync_point_mark (type);
1354 gc_reference (MonoObject *obj, MonoClass *klass, uintptr_t size, uintptr_t num, MonoObject **refs, uintptr_t *offsets, void *data)
1356 /* account for object alignment in the heap */
1360 ENTER_LOG (&heap_objects_ctr, logbuffer,
1361 EVENT_SIZE /* event */ +
1362 LEB128_SIZE /* obj */ +
1363 LEB128_SIZE /* klass */ +
1364 LEB128_SIZE /* size */ +
1365 LEB128_SIZE /* num */ +
1367 LEB128_SIZE /* offset */ +
1368 LEB128_SIZE /* ref */
1372 emit_event (logbuffer, TYPE_HEAP_OBJECT | TYPE_HEAP);
1373 emit_obj (logbuffer, obj);
1374 emit_ptr (logbuffer, klass);
1375 emit_value (logbuffer, size);
1376 emit_value (logbuffer, num);
1378 uintptr_t last_offset = 0;
1380 for (int i = 0; i < num; ++i) {
1381 emit_value (logbuffer, offsets [i] - last_offset);
1382 last_offset = offsets [i];
1383 emit_obj (logbuffer, refs [i]);
1386 EXIT_LOG_EXPLICIT (DO_SEND);
1391 static unsigned int hs_mode_ms = 0;
1392 static unsigned int hs_mode_gc = 0;
1393 static unsigned int hs_mode_ondemand = 0;
1394 static unsigned int gc_count = 0;
1395 static uint64_t last_hs_time = 0;
1396 static gboolean do_heap_walk = FALSE;
1397 static gboolean ignore_heap_events;
1400 gc_roots (MonoProfiler *prof, int num, void **objects, int *root_types, uintptr_t *extra_info)
1402 if (ignore_heap_events)
1405 ENTER_LOG (&heap_roots_ctr, logbuffer,
1406 EVENT_SIZE /* event */ +
1407 LEB128_SIZE /* num */ +
1408 LEB128_SIZE /* collections */ +
1410 LEB128_SIZE /* object */ +
1411 LEB128_SIZE /* root type */ +
1412 LEB128_SIZE /* extra info */
1416 emit_event (logbuffer, TYPE_HEAP_ROOT | TYPE_HEAP);
1417 emit_value (logbuffer, num);
1418 emit_value (logbuffer, mono_gc_collection_count (mono_gc_max_generation ()));
1420 for (int i = 0; i < num; ++i) {
1421 emit_obj (logbuffer, objects [i]);
1422 emit_byte (logbuffer, root_types [i]);
1423 emit_value (logbuffer, extra_info [i]);
1426 EXIT_LOG_EXPLICIT (DO_SEND);
1431 trigger_on_demand_heapshot (void)
1433 if (heapshot_requested)
1434 mono_gc_collect (mono_gc_max_generation ());
1437 #define ALL_GC_EVENTS_MASK (PROFLOG_GC_MOVES_EVENTS | PROFLOG_GC_ROOT_EVENTS | PROFLOG_GC_EVENTS | PROFLOG_HEAPSHOT_FEATURE)
1440 gc_event (MonoProfiler *profiler, MonoGCEvent ev, int generation)
1442 if (ev == MONO_GC_EVENT_START) {
1443 uint64_t now = current_time ();
1445 if (hs_mode_ms && (now - last_hs_time) / 1000 * 1000 >= hs_mode_ms)
1446 do_heap_walk = TRUE;
1447 else if (hs_mode_gc && !(gc_count % hs_mode_gc))
1448 do_heap_walk = TRUE;
1449 else if (hs_mode_ondemand)
1450 do_heap_walk = heapshot_requested;
1451 else if (!hs_mode_ms && !hs_mode_gc && generation == mono_gc_max_generation ())
1452 do_heap_walk = TRUE;
1454 //If using heapshot, ignore events for collections we don't care
1455 if (ENABLED (PROFLOG_HEAPSHOT_FEATURE)) {
1456 // Ignore events generated during the collection itself (IE GC ROOTS)
1457 ignore_heap_events = !do_heap_walk;
1462 if (ENABLED (PROFLOG_GC_EVENTS)) {
1463 ENTER_LOG (&gc_events_ctr, logbuffer,
1464 EVENT_SIZE /* event */ +
1465 BYTE_SIZE /* gc event */ +
1466 BYTE_SIZE /* generation */
1469 emit_event (logbuffer, TYPE_GC_EVENT | TYPE_GC);
1470 emit_byte (logbuffer, ev);
1471 emit_byte (logbuffer, generation);
1473 EXIT_LOG_EXPLICIT (NO_SEND);
1477 case MONO_GC_EVENT_START:
1478 if (generation == mono_gc_max_generation ())
1482 case MONO_GC_EVENT_PRE_STOP_WORLD_LOCKED:
1484 * Ensure that no thread can be in the middle of writing to
1485 * a buffer when the world stops...
1487 buffer_lock_excl ();
1489 case MONO_GC_EVENT_POST_STOP_WORLD:
1491 * ... So that we now have a consistent view of all buffers.
1492 * This allows us to flush them. We need to do this because
1493 * they may contain object allocation events that need to be
1494 * committed to the log file before any object move events
1495 * that will be produced during this GC.
1497 if (ENABLED (ALL_GC_EVENTS_MASK))
1498 sync_point (SYNC_POINT_WORLD_STOP);
1501 * All heap events are surrounded by a HEAP_START and a HEAP_ENV event.
1502 * Right now, that's the case for GC Moves, GC Roots or heapshots.
1504 if (ENABLED (PROFLOG_GC_MOVES_EVENTS | PROFLOG_GC_ROOT_EVENTS) || do_heap_walk) {
1505 ENTER_LOG (&heap_starts_ctr, logbuffer,
1506 EVENT_SIZE /* event */
1509 emit_event (logbuffer, TYPE_HEAP_START | TYPE_HEAP);
1511 EXIT_LOG_EXPLICIT (DO_SEND);
1515 case MONO_GC_EVENT_PRE_START_WORLD:
1516 if (do_heap_shot && do_heap_walk)
1517 mono_gc_walk_heap (0, gc_reference, NULL);
1519 /* Matching HEAP_END to the HEAP_START from above */
1520 if (ENABLED (PROFLOG_GC_MOVES_EVENTS | PROFLOG_GC_ROOT_EVENTS) || do_heap_walk) {
1521 ENTER_LOG (&heap_ends_ctr, logbuffer,
1522 EVENT_SIZE /* event */
1525 emit_event (logbuffer, TYPE_HEAP_END | TYPE_HEAP);
1527 EXIT_LOG_EXPLICIT (DO_SEND);
1530 if (do_heap_shot && do_heap_walk) {
1531 do_heap_walk = FALSE;
1532 heapshot_requested = 0;
1533 last_hs_time = current_time ();
1537 * Similarly, we must now make sure that any object moves
1538 * written to the GC thread's buffer are flushed. Otherwise,
1539 * object allocation events for certain addresses could come
1540 * after the move events that made those addresses available.
1542 if (ENABLED (ALL_GC_EVENTS_MASK))
1543 sync_point_mark (SYNC_POINT_WORLD_START);
1545 case MONO_GC_EVENT_POST_START_WORLD_UNLOCKED:
1547 * Finally, it is safe to allow other threads to write to
1548 * their buffers again.
1550 buffer_unlock_excl ();
1558 gc_resize (MonoProfiler *profiler, int64_t new_size)
1560 ENTER_LOG (&gc_resizes_ctr, logbuffer,
1561 EVENT_SIZE /* event */ +
1562 LEB128_SIZE /* new size */
1565 emit_event (logbuffer, TYPE_GC_RESIZE | TYPE_GC);
1566 emit_value (logbuffer, new_size);
1568 EXIT_LOG_EXPLICIT (DO_SEND);
1573 MonoMethod* methods [MAX_FRAMES];
1574 int32_t il_offsets [MAX_FRAMES];
1575 int32_t native_offsets [MAX_FRAMES];
1578 static int num_frames = MAX_FRAMES;
1581 walk_stack (MonoMethod *method, int32_t native_offset, int32_t il_offset, mono_bool managed, void* data)
1583 FrameData *frame = (FrameData *)data;
1584 if (method && frame->count < num_frames) {
1585 frame->il_offsets [frame->count] = il_offset;
1586 frame->native_offsets [frame->count] = native_offset;
1587 frame->methods [frame->count++] = method;
1588 //printf ("In %d %s at %d (native: %d)\n", frame->count, mono_method_get_name (method), il_offset, native_offset);
1590 return frame->count == num_frames;
1594 * a note about stack walks: they can cause more profiler events to fire,
1595 * so we need to make sure they don't happen after we started emitting an
1596 * event, hence the collect_bt/emit_bt split.
1599 collect_bt (FrameData *data)
1602 mono_stack_walk_no_il (walk_stack, data);
1606 emit_bt (MonoProfiler *prof, LogBuffer *logbuffer, FrameData *data)
1608 if (data->count > num_frames)
1609 printf ("bad num frames: %d\n", data->count);
1611 emit_value (logbuffer, data->count);
1614 emit_method (logbuffer, data->methods [--data->count]);
1618 gc_alloc (MonoProfiler *prof, MonoObject *obj, MonoClass *klass)
1620 int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces) ? TYPE_ALLOC_BT : 0;
1622 uintptr_t len = mono_object_get_size (obj);
1623 /* account for object alignment in the heap */
1630 ENTER_LOG (&gc_allocs_ctr, logbuffer,
1631 EVENT_SIZE /* event */ +
1632 LEB128_SIZE /* klass */ +
1633 LEB128_SIZE /* obj */ +
1634 LEB128_SIZE /* size */ +
1636 LEB128_SIZE /* count */ +
1638 LEB128_SIZE /* method */
1643 emit_event (logbuffer, do_bt | TYPE_ALLOC);
1644 emit_ptr (logbuffer, klass);
1645 emit_obj (logbuffer, obj);
1646 emit_value (logbuffer, len);
1649 emit_bt (prof, logbuffer, &data);
1655 gc_moves (MonoProfiler *prof, void **objects, int num)
1657 ENTER_LOG (&gc_moves_ctr, logbuffer,
1658 EVENT_SIZE /* event */ +
1659 LEB128_SIZE /* num */ +
1661 LEB128_SIZE /* object */
1665 emit_event (logbuffer, TYPE_GC_MOVE | TYPE_GC);
1666 emit_value (logbuffer, num);
1668 for (int i = 0; i < num; ++i)
1669 emit_obj (logbuffer, objects [i]);
1671 EXIT_LOG_EXPLICIT (DO_SEND);
1675 gc_handle (MonoProfiler *prof, int op, int type, uintptr_t handle, MonoObject *obj)
1677 int do_bt = nocalls && InterlockedRead (&runtime_inited) && !notraces;
1683 gint32 *ctr = op == MONO_PROFILER_GC_HANDLE_CREATED ? &gc_handle_creations_ctr : &gc_handle_deletions_ctr;
1685 ENTER_LOG (ctr, logbuffer,
1686 EVENT_SIZE /* event */ +
1687 LEB128_SIZE /* type */ +
1688 LEB128_SIZE /* handle */ +
1689 (op == MONO_PROFILER_GC_HANDLE_CREATED ? (
1690 LEB128_SIZE /* obj */
1693 LEB128_SIZE /* count */ +
1695 LEB128_SIZE /* method */
1700 if (op == MONO_PROFILER_GC_HANDLE_CREATED)
1701 emit_event (logbuffer, (do_bt ? TYPE_GC_HANDLE_CREATED_BT : TYPE_GC_HANDLE_CREATED) | TYPE_GC);
1702 else if (op == MONO_PROFILER_GC_HANDLE_DESTROYED)
1703 emit_event (logbuffer, (do_bt ? TYPE_GC_HANDLE_DESTROYED_BT : TYPE_GC_HANDLE_DESTROYED) | TYPE_GC);
1705 g_assert_not_reached ();
1707 emit_value (logbuffer, type);
1708 emit_value (logbuffer, handle);
1710 if (op == MONO_PROFILER_GC_HANDLE_CREATED)
1711 emit_obj (logbuffer, obj);
1714 emit_bt (prof, logbuffer, &data);
1720 finalize_begin (MonoProfiler *prof)
1722 ENTER_LOG (&finalize_begins_ctr, buf,
1723 EVENT_SIZE /* event */
1726 emit_event (buf, TYPE_GC_FINALIZE_START | TYPE_GC);
1732 finalize_end (MonoProfiler *prof)
1734 trigger_on_demand_heapshot ();
1735 if (ENABLED (PROFLOG_FINALIZATION_EVENTS)) {
1736 ENTER_LOG (&finalize_ends_ctr, buf,
1737 EVENT_SIZE /* event */
1740 emit_event (buf, TYPE_GC_FINALIZE_END | TYPE_GC);
1747 finalize_object_begin (MonoProfiler *prof, MonoObject *obj)
1749 ENTER_LOG (&finalize_object_begins_ctr, buf,
1750 EVENT_SIZE /* event */ +
1751 LEB128_SIZE /* obj */
1754 emit_event (buf, TYPE_GC_FINALIZE_OBJECT_START | TYPE_GC);
1755 emit_obj (buf, obj);
1761 finalize_object_end (MonoProfiler *prof, MonoObject *obj)
1763 ENTER_LOG (&finalize_object_ends_ctr, buf,
1764 EVENT_SIZE /* event */ +
1765 LEB128_SIZE /* obj */
1768 emit_event (buf, TYPE_GC_FINALIZE_OBJECT_END | TYPE_GC);
1769 emit_obj (buf, obj);
1775 push_nesting (char *p, MonoClass *klass)
1780 nesting = mono_class_get_nesting_type (klass);
1782 p = push_nesting (p, nesting);
1786 name = mono_class_get_name (klass);
1787 nspace = mono_class_get_namespace (klass);
1790 p += strlen (nspace);
1800 type_name (MonoClass *klass)
1804 push_nesting (buf, klass);
1805 p = (char *) g_malloc (strlen (buf) + 1);
1811 image_loaded (MonoProfiler *prof, MonoImage *image, int result)
1813 if (result != MONO_PROFILE_OK)
1816 const char *name = mono_image_get_filename (image);
1817 int nlen = strlen (name) + 1;
1819 ENTER_LOG (&image_loads_ctr, logbuffer,
1820 EVENT_SIZE /* event */ +
1821 BYTE_SIZE /* type */ +
1822 LEB128_SIZE /* image */ +
1826 emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1827 emit_byte (logbuffer, TYPE_IMAGE);
1828 emit_ptr (logbuffer, image);
1829 memcpy (logbuffer->cursor, name, nlen);
1830 logbuffer->cursor += nlen;
1836 image_unloaded (MonoProfiler *prof, MonoImage *image)
1838 const char *name = mono_image_get_filename (image);
1839 int nlen = strlen (name) + 1;
1841 ENTER_LOG (&image_unloads_ctr, logbuffer,
1842 EVENT_SIZE /* event */ +
1843 BYTE_SIZE /* type */ +
1844 LEB128_SIZE /* image */ +
1848 emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1849 emit_byte (logbuffer, TYPE_IMAGE);
1850 emit_ptr (logbuffer, image);
1851 memcpy (logbuffer->cursor, name, nlen);
1852 logbuffer->cursor += nlen;
1858 assembly_loaded (MonoProfiler *prof, MonoAssembly *assembly, int result)
1860 if (result != MONO_PROFILE_OK)
1863 char *name = mono_stringify_assembly_name (mono_assembly_get_name (assembly));
1864 int nlen = strlen (name) + 1;
1865 MonoImage *image = mono_assembly_get_image (assembly);
1867 ENTER_LOG (&assembly_loads_ctr, logbuffer,
1868 EVENT_SIZE /* event */ +
1869 BYTE_SIZE /* type */ +
1870 LEB128_SIZE /* assembly */ +
1871 LEB128_SIZE /* image */ +
1875 emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1876 emit_byte (logbuffer, TYPE_ASSEMBLY);
1877 emit_ptr (logbuffer, assembly);
1878 emit_ptr (logbuffer, image);
1879 memcpy (logbuffer->cursor, name, nlen);
1880 logbuffer->cursor += nlen;
1888 assembly_unloaded (MonoProfiler *prof, MonoAssembly *assembly)
1890 char *name = mono_stringify_assembly_name (mono_assembly_get_name (assembly));
1891 int nlen = strlen (name) + 1;
1892 MonoImage *image = mono_assembly_get_image (assembly);
1894 ENTER_LOG (&assembly_unloads_ctr, logbuffer,
1895 EVENT_SIZE /* event */ +
1896 BYTE_SIZE /* type */ +
1897 LEB128_SIZE /* assembly */ +
1898 LEB128_SIZE /* image */ +
1902 emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1903 emit_byte (logbuffer, TYPE_ASSEMBLY);
1904 emit_ptr (logbuffer, assembly);
1905 emit_ptr (logbuffer, image);
1906 memcpy (logbuffer->cursor, name, nlen);
1907 logbuffer->cursor += nlen;
1915 class_loaded (MonoProfiler *prof, MonoClass *klass, int result)
1917 if (result != MONO_PROFILE_OK)
1922 if (InterlockedRead (&runtime_inited))
1923 name = mono_type_get_name (mono_class_get_type (klass));
1925 name = type_name (klass);
1927 int nlen = strlen (name) + 1;
1928 MonoImage *image = mono_class_get_image (klass);
1930 ENTER_LOG (&class_loads_ctr, logbuffer,
1931 EVENT_SIZE /* event */ +
1932 BYTE_SIZE /* type */ +
1933 LEB128_SIZE /* klass */ +
1934 LEB128_SIZE /* image */ +
1938 emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1939 emit_byte (logbuffer, TYPE_CLASS);
1940 emit_ptr (logbuffer, klass);
1941 emit_ptr (logbuffer, image);
1942 memcpy (logbuffer->cursor, name, nlen);
1943 logbuffer->cursor += nlen;
1954 class_unloaded (MonoProfiler *prof, MonoClass *klass)
1958 if (InterlockedRead (&runtime_inited))
1959 name = mono_type_get_name (mono_class_get_type (klass));
1961 name = type_name (klass);
1963 int nlen = strlen (name) + 1;
1964 MonoImage *image = mono_class_get_image (klass);
1966 ENTER_LOG (&class_unloads_ctr, logbuffer,
1967 EVENT_SIZE /* event */ +
1968 BYTE_SIZE /* type */ +
1969 LEB128_SIZE /* klass */ +
1970 LEB128_SIZE /* image */ +
1974 emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1975 emit_byte (logbuffer, TYPE_CLASS);
1976 emit_ptr (logbuffer, klass);
1977 emit_ptr (logbuffer, image);
1978 memcpy (logbuffer->cursor, name, nlen);
1979 logbuffer->cursor += nlen;
1989 static void process_method_enter_coverage (MonoProfiler *prof, MonoMethod *method);
1992 method_enter (MonoProfiler *prof, MonoMethod *method)
1994 process_method_enter_coverage (prof, method);
1996 if (!only_coverage && get_thread ()->call_depth++ <= max_call_depth) {
1997 ENTER_LOG (&method_entries_ctr, logbuffer,
1998 EVENT_SIZE /* event */ +
1999 LEB128_SIZE /* method */
2002 emit_event (logbuffer, TYPE_ENTER | TYPE_METHOD);
2003 emit_method (logbuffer, method);
2010 method_leave (MonoProfiler *prof, MonoMethod *method)
2012 if (!only_coverage && --get_thread ()->call_depth <= max_call_depth) {
2013 ENTER_LOG (&method_exits_ctr, logbuffer,
2014 EVENT_SIZE /* event */ +
2015 LEB128_SIZE /* method */
2018 emit_event (logbuffer, TYPE_LEAVE | TYPE_METHOD);
2019 emit_method (logbuffer, method);
2026 method_exc_leave (MonoProfiler *prof, MonoMethod *method)
2028 if (!only_coverage && !nocalls && --get_thread ()->call_depth <= max_call_depth) {
2029 ENTER_LOG (&method_exception_exits_ctr, logbuffer,
2030 EVENT_SIZE /* event */ +
2031 LEB128_SIZE /* method */
2034 emit_event (logbuffer, TYPE_EXC_LEAVE | TYPE_METHOD);
2035 emit_method (logbuffer, method);
2042 method_jitted (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *ji, int result)
2044 if (result != MONO_PROFILE_OK)
2047 register_method_local (method, ji);
2051 code_buffer_new (MonoProfiler *prof, void *buffer, int size, MonoProfilerCodeBufferType type, void *data)
2056 if (type == MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE) {
2057 name = (char *) data;
2058 nlen = strlen (name) + 1;
2064 ENTER_LOG (&code_buffers_ctr, logbuffer,
2065 EVENT_SIZE /* event */ +
2066 BYTE_SIZE /* type */ +
2067 LEB128_SIZE /* buffer */ +
2068 LEB128_SIZE /* size */ +
2074 emit_event (logbuffer, TYPE_JITHELPER | TYPE_RUNTIME);
2075 emit_byte (logbuffer, type);
2076 emit_ptr (logbuffer, buffer);
2077 emit_value (logbuffer, size);
2080 memcpy (logbuffer->cursor, name, nlen);
2081 logbuffer->cursor += nlen;
2088 throw_exc (MonoProfiler *prof, MonoObject *object)
2090 int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces) ? TYPE_THROW_BT : 0;
2096 ENTER_LOG (&exception_throws_ctr, logbuffer,
2097 EVENT_SIZE /* event */ +
2098 LEB128_SIZE /* object */ +
2100 LEB128_SIZE /* count */ +
2102 LEB128_SIZE /* method */
2107 emit_event (logbuffer, do_bt | TYPE_EXCEPTION);
2108 emit_obj (logbuffer, object);
2111 emit_bt (prof, logbuffer, &data);
2117 clause_exc (MonoProfiler *prof, MonoMethod *method, int clause_type, int clause_num, MonoObject *exc)
2119 ENTER_LOG (&exception_clauses_ctr, logbuffer,
2120 EVENT_SIZE /* event */ +
2121 BYTE_SIZE /* clause type */ +
2122 LEB128_SIZE /* clause num */ +
2123 LEB128_SIZE /* method */
2126 emit_event (logbuffer, TYPE_EXCEPTION | TYPE_CLAUSE);
2127 emit_byte (logbuffer, clause_type);
2128 emit_value (logbuffer, clause_num);
2129 emit_method (logbuffer, method);
2130 emit_obj (logbuffer, exc);
2136 monitor_event (MonoProfiler *profiler, MonoObject *object, MonoProfilerMonitorEvent ev)
2138 int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces) ? TYPE_MONITOR_BT : 0;
2144 ENTER_LOG (&monitor_events_ctr, logbuffer,
2145 EVENT_SIZE /* event */ +
2146 BYTE_SIZE /* ev */ +
2147 LEB128_SIZE /* object */ +
2149 LEB128_SIZE /* count */ +
2151 LEB128_SIZE /* method */
2156 emit_event (logbuffer, do_bt | TYPE_MONITOR);
2157 emit_byte (logbuffer, ev);
2158 emit_obj (logbuffer, object);
2161 emit_bt (profiler, logbuffer, &data);
2167 thread_start (MonoProfiler *prof, uintptr_t tid)
2169 if (ENABLED (PROFLOG_THREAD_EVENTS)) {
2170 ENTER_LOG (&thread_starts_ctr, logbuffer,
2171 EVENT_SIZE /* event */ +
2172 BYTE_SIZE /* type */ +
2173 LEB128_SIZE /* tid */
2176 emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
2177 emit_byte (logbuffer, TYPE_THREAD);
2178 emit_ptr (logbuffer, (void*) tid);
2185 thread_end (MonoProfiler *prof, uintptr_t tid)
2187 if (ENABLED (PROFLOG_THREAD_EVENTS)) {
2188 ENTER_LOG (&thread_ends_ctr, logbuffer,
2189 EVENT_SIZE /* event */ +
2190 BYTE_SIZE /* type */ +
2191 LEB128_SIZE /* tid */
2194 emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
2195 emit_byte (logbuffer, TYPE_THREAD);
2196 emit_ptr (logbuffer, (void*) tid);
2198 EXIT_LOG_EXPLICIT (NO_SEND);
2201 MonoProfilerThread *thread = get_thread ();
2203 thread->ended = TRUE;
2204 remove_thread (thread);
2206 PROF_TLS_SET (NULL);
2210 thread_name (MonoProfiler *prof, uintptr_t tid, const char *name)
2212 int len = strlen (name) + 1;
2214 if (ENABLED (PROFLOG_THREAD_EVENTS)) {
2215 ENTER_LOG (&thread_names_ctr, logbuffer,
2216 EVENT_SIZE /* event */ +
2217 BYTE_SIZE /* type */ +
2218 LEB128_SIZE /* tid */ +
2222 emit_event (logbuffer, TYPE_METADATA);
2223 emit_byte (logbuffer, TYPE_THREAD);
2224 emit_ptr (logbuffer, (void*)tid);
2225 memcpy (logbuffer->cursor, name, len);
2226 logbuffer->cursor += len;
2233 domain_loaded (MonoProfiler *prof, MonoDomain *domain, int result)
2235 if (result != MONO_PROFILE_OK)
2238 ENTER_LOG (&domain_loads_ctr, logbuffer,
2239 EVENT_SIZE /* event */ +
2240 BYTE_SIZE /* type */ +
2241 LEB128_SIZE /* domain id */
2244 emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
2245 emit_byte (logbuffer, TYPE_DOMAIN);
2246 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
2252 domain_unloaded (MonoProfiler *prof, MonoDomain *domain)
2254 ENTER_LOG (&domain_unloads_ctr, logbuffer,
2255 EVENT_SIZE /* event */ +
2256 BYTE_SIZE /* type */ +
2257 LEB128_SIZE /* domain id */
2260 emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
2261 emit_byte (logbuffer, TYPE_DOMAIN);
2262 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
2268 domain_name (MonoProfiler *prof, MonoDomain *domain, const char *name)
2270 int nlen = strlen (name) + 1;
2272 ENTER_LOG (&domain_names_ctr, logbuffer,
2273 EVENT_SIZE /* event */ +
2274 BYTE_SIZE /* type */ +
2275 LEB128_SIZE /* domain id */ +
2279 emit_event (logbuffer, TYPE_METADATA);
2280 emit_byte (logbuffer, TYPE_DOMAIN);
2281 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
2282 memcpy (logbuffer->cursor, name, nlen);
2283 logbuffer->cursor += nlen;
2289 context_loaded (MonoProfiler *prof, MonoAppContext *context)
2291 ENTER_LOG (&context_loads_ctr, logbuffer,
2292 EVENT_SIZE /* event */ +
2293 BYTE_SIZE /* type */ +
2294 LEB128_SIZE /* context id */ +
2295 LEB128_SIZE /* domain id */
2298 emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
2299 emit_byte (logbuffer, TYPE_CONTEXT);
2300 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_id (context));
2301 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_domain_id (context));
2307 context_unloaded (MonoProfiler *prof, MonoAppContext *context)
2309 ENTER_LOG (&context_unloads_ctr, logbuffer,
2310 EVENT_SIZE /* event */ +
2311 BYTE_SIZE /* type */ +
2312 LEB128_SIZE /* context id */ +
2313 LEB128_SIZE /* domain id */
2316 emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
2317 emit_byte (logbuffer, TYPE_CONTEXT);
2318 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_id (context));
2319 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_domain_id (context));
2332 MonoLockFreeQueueNode node;
2338 AsyncFrameInfo frames [MONO_ZERO_LEN_ARRAY];
2342 async_walk_stack (MonoMethod *method, MonoDomain *domain, void *base_address, int offset, void *data)
2344 SampleHit *sample = (SampleHit *) data;
2346 if (sample->count < num_frames) {
2347 int i = sample->count;
2349 sample->frames [i].method = method;
2350 sample->frames [i].domain = domain;
2351 sample->frames [i].base_address = base_address;
2352 sample->frames [i].offset = offset;
2357 return sample->count == num_frames;
2360 #define SAMPLE_SLOT_SIZE(FRAMES) (sizeof (SampleHit) + sizeof (AsyncFrameInfo) * (FRAMES - MONO_ZERO_LEN_ARRAY))
2361 #define SAMPLE_BLOCK_SIZE (mono_pagesize ())
2364 enqueue_sample_hit (gpointer p)
2366 SampleHit *sample = p;
2368 mono_lock_free_queue_node_unpoison (&sample->node);
2369 mono_lock_free_queue_enqueue (&sample->prof->dumper_queue, &sample->node);
2370 mono_os_sem_post (&sample->prof->dumper_queue_sem);
2374 mono_sample_hit (MonoProfiler *profiler, unsigned char *ip, void *context)
2377 * Please note: We rely on the runtime loading the profiler with
2378 * MONO_DL_EAGER (RTLD_NOW) so that references to runtime functions within
2379 * this function (and its siblings) are resolved when the profiler is
2380 * loaded. Otherwise, we would potentially invoke the dynamic linker when
2381 * invoking runtime functions, which is not async-signal-safe.
2384 if (InterlockedRead (&in_shutdown))
2387 SampleHit *sample = (SampleHit *) mono_lock_free_queue_dequeue (&profiler->sample_reuse_queue);
2391 * If we're out of reusable sample events and we're not allowed to
2392 * allocate more, we have no choice but to drop the event.
2394 if (InterlockedRead (&sample_allocations_ctr) >= max_allocated_sample_hits)
2397 sample = mono_lock_free_alloc (&profiler->sample_allocator);
2398 sample->prof = profiler;
2399 mono_lock_free_queue_node_init (&sample->node, TRUE);
2401 InterlockedIncrement (&sample_allocations_ctr);
2405 mono_stack_walk_async_safe (&async_walk_stack, context, sample);
2407 sample->time = current_time ();
2408 sample->tid = thread_id ();
2411 mono_thread_hazardous_try_free (sample, enqueue_sample_hit);
2414 static uintptr_t *code_pages = 0;
2415 static int num_code_pages = 0;
2416 static int size_code_pages = 0;
2417 #define CPAGE_SHIFT (9)
2418 #define CPAGE_SIZE (1 << CPAGE_SHIFT)
2419 #define CPAGE_MASK (~(CPAGE_SIZE - 1))
2420 #define CPAGE_ADDR(p) ((p) & CPAGE_MASK)
2423 add_code_page (uintptr_t *hash, uintptr_t hsize, uintptr_t page)
2426 uintptr_t start_pos;
2427 start_pos = (page >> CPAGE_SHIFT) % hsize;
2430 if (hash [i] && CPAGE_ADDR (hash [i]) == CPAGE_ADDR (page)) {
2432 } else if (!hash [i]) {
2439 } while (i != start_pos);
2440 /* should not happen */
2441 printf ("failed code page store\n");
2446 add_code_pointer (uintptr_t ip)
2449 if (num_code_pages * 2 >= size_code_pages) {
2451 uintptr_t old_size = size_code_pages;
2452 size_code_pages *= 2;
2453 if (size_code_pages == 0)
2454 size_code_pages = 16;
2455 n = (uintptr_t *) g_calloc (sizeof (uintptr_t) * size_code_pages, 1);
2456 for (i = 0; i < old_size; ++i) {
2458 add_code_page (n, size_code_pages, code_pages [i]);
2461 g_free (code_pages);
2464 num_code_pages += add_code_page (code_pages, size_code_pages, ip & CPAGE_MASK);
2467 /* ELF code crashes on some systems. */
2468 //#if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
2471 dump_ubin (MonoProfiler *prof, const char *filename, uintptr_t load_addr, uint64_t offset, uintptr_t size)
2473 int len = strlen (filename) + 1;
2475 ENTER_LOG (&sample_ubins_ctr, logbuffer,
2476 EVENT_SIZE /* event */ +
2477 LEB128_SIZE /* load address */ +
2478 LEB128_SIZE /* offset */ +
2479 LEB128_SIZE /* size */ +
2480 nlen /* file name */
2483 emit_event (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_UBIN);
2484 emit_ptr (logbuffer, load_addr);
2485 emit_uvalue (logbuffer, offset);
2486 emit_uvalue (logbuffer, size);
2487 memcpy (logbuffer->cursor, filename, len);
2488 logbuffer->cursor += len;
2490 EXIT_LOG_EXPLICIT (DO_SEND);
2495 dump_usym (MonoProfiler *prof, const char *name, uintptr_t value, uintptr_t size)
2497 int len = strlen (name) + 1;
2499 ENTER_LOG (&sample_usyms_ctr, logbuffer,
2500 EVENT_SIZE /* event */ +
2501 LEB128_SIZE /* value */ +
2502 LEB128_SIZE /* size */ +
2506 emit_event (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_USYM);
2507 emit_ptr (logbuffer, (void*)value);
2508 emit_value (logbuffer, size);
2509 memcpy (logbuffer->cursor, name, len);
2510 logbuffer->cursor += len;
2512 EXIT_LOG_EXPLICIT (DO_SEND);
2515 /* ELF code crashes on some systems. */
2516 //#if defined(ELFMAG0)
2519 #if SIZEOF_VOID_P == 4
2520 #define ELF_WSIZE 32
2522 #define ELF_WSIZE 64
2525 #define ElfW(type) _ElfW (Elf, ELF_WSIZE, type)
2526 #define _ElfW(e,w,t) _ElfW_1 (e, w, _##t)
2527 #define _ElfW_1(e,w,t) e##w##t
2531 dump_elf_symbols (MonoProfiler *prof, ElfW(Sym) *symbols, int num_symbols, const char *strtab, void *load_addr)
2534 for (i = 0; i < num_symbols; ++i) {
2536 sym = strtab + symbols [i].st_name;
2537 if (!symbols [i].st_name || !symbols [i].st_size || (symbols [i].st_info & 0xf) != STT_FUNC)
2539 //printf ("symbol %s at %d\n", sym, symbols [i].st_value);
2540 dump_usym (sym, (uintptr_t)load_addr + symbols [i].st_value, symbols [i].st_size);
2545 read_elf_symbols (MonoProfiler *prof, const char *filename, void *load_addr)
2552 ElfW(Shdr) *sheader;
2553 ElfW(Shdr) *shstrtabh;
2554 ElfW(Shdr) *symtabh = NULL;
2555 ElfW(Shdr) *strtabh = NULL;
2556 ElfW(Sym) *symbols = NULL;
2560 fd = open (filename, O_RDONLY);
2563 if (fstat (fd, &statb) != 0) {
2567 file_size = statb.st_size;
2568 data = mmap (NULL, file_size, PROT_READ, MAP_PRIVATE, fd, 0);
2570 if (data == MAP_FAILED)
2573 if (header->e_ident [EI_MAG0] != ELFMAG0 ||
2574 header->e_ident [EI_MAG1] != ELFMAG1 ||
2575 header->e_ident [EI_MAG2] != ELFMAG2 ||
2576 header->e_ident [EI_MAG3] != ELFMAG3 ) {
2577 munmap (data, file_size);
2580 sheader = (void*)((char*)data + header->e_shoff);
2581 shstrtabh = (void*)((char*)sheader + (header->e_shentsize * header->e_shstrndx));
2582 strtab = (const char*)data + shstrtabh->sh_offset;
2583 for (i = 0; i < header->e_shnum; ++i) {
2584 //printf ("section header: %d\n", sheader->sh_type);
2585 if (sheader->sh_type == SHT_SYMTAB) {
2587 strtabh = (void*)((char*)data + header->e_shoff + sheader->sh_link * header->e_shentsize);
2588 /*printf ("symtab section header: %d, .strstr: %d\n", i, sheader->sh_link);*/
2591 sheader = (void*)((char*)sheader + header->e_shentsize);
2593 if (!symtabh || !strtabh) {
2594 munmap (data, file_size);
2597 strtab = (const char*)data + strtabh->sh_offset;
2598 num_symbols = symtabh->sh_size / symtabh->sh_entsize;
2599 symbols = (void*)((char*)data + symtabh->sh_offset);
2600 dump_elf_symbols (symbols, num_symbols, strtab, load_addr);
2601 munmap (data, file_size);
2606 /* ELF code crashes on some systems. */
2607 //#if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
2610 elf_dl_callback (struct dl_phdr_info *info, size_t size, void *data)
2612 MonoProfiler *prof = data;
2614 const char *filename;
2616 char *a = (void*)info->dlpi_addr;
2618 ElfW(Dyn) *dyn = NULL;
2619 ElfW(Sym) *symtab = NULL;
2620 ElfW(Word) *hash_table = NULL;
2621 ElfW(Ehdr) *header = NULL;
2622 const char* strtab = NULL;
2623 for (obj = prof->binary_objects; obj; obj = obj->next) {
2627 filename = info->dlpi_name;
2630 if (!info->dlpi_addr && !filename [0]) {
2631 int l = readlink ("/proc/self/exe", buf, sizeof (buf) - 1);
2637 obj = g_calloc (sizeof (BinaryObject), 1);
2638 obj->addr = (void*)info->dlpi_addr;
2639 obj->name = pstrdup (filename);
2640 obj->next = prof->binary_objects;
2641 prof->binary_objects = obj;
2642 //printf ("loaded file: %s at %p, segments: %d\n", filename, (void*)info->dlpi_addr, info->dlpi_phnum);
2644 for (i = 0; i < info->dlpi_phnum; ++i) {
2645 //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);
2646 if (info->dlpi_phdr[i].p_type == PT_LOAD && !header) {
2647 header = (ElfW(Ehdr)*)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
2648 if (header->e_ident [EI_MAG0] != ELFMAG0 ||
2649 header->e_ident [EI_MAG1] != ELFMAG1 ||
2650 header->e_ident [EI_MAG2] != ELFMAG2 ||
2651 header->e_ident [EI_MAG3] != ELFMAG3 ) {
2654 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);
2655 } else if (info->dlpi_phdr[i].p_type == PT_DYNAMIC) {
2656 dyn = (ElfW(Dyn) *)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
2659 if (read_elf_symbols (prof, filename, (void*)info->dlpi_addr))
2661 if (!info->dlpi_name || !info->dlpi_name[0])
2665 for (i = 0; dyn [i].d_tag != DT_NULL; ++i) {
2666 if (dyn [i].d_tag == DT_SYMTAB) {
2667 if (symtab && do_debug)
2668 printf ("multiple symtabs: %d\n", i);
2669 symtab = (ElfW(Sym) *)(a + dyn [i].d_un.d_ptr);
2670 } else if (dyn [i].d_tag == DT_HASH) {
2671 hash_table = (ElfW(Word) *)(a + dyn [i].d_un.d_ptr);
2672 } else if (dyn [i].d_tag == DT_STRTAB) {
2673 strtab = (const char*)(a + dyn [i].d_un.d_ptr);
2678 num_sym = hash_table [1];
2679 dump_elf_symbols (prof, symtab, num_sym, strtab, (void*)info->dlpi_addr);
2684 load_binaries (MonoProfiler *prof)
2686 dl_iterate_phdr (elf_dl_callback, prof);
2691 load_binaries (MonoProfiler *prof)
2698 symbol_for (uintptr_t code)
2701 void *ip = (void*)code;
2703 if (dladdr (ip, &di)) {
2705 return di.dli_sname;
2708 names = backtrace_symbols (&ip, 1);
2710 const char* p = names [0];
2721 dump_unmanaged_coderefs (MonoProfiler *prof)
2724 const char* last_symbol;
2725 uintptr_t addr, page_end;
2727 if (load_binaries (prof))
2729 for (i = 0; i < size_code_pages; ++i) {
2731 if (!code_pages [i] || code_pages [i] & 1)
2734 addr = CPAGE_ADDR (code_pages [i]);
2735 page_end = addr + CPAGE_SIZE;
2736 code_pages [i] |= 1;
2737 /* we dump the symbols for the whole page */
2738 for (; addr < page_end; addr += 16) {
2739 sym = symbol_for (addr);
2740 if (sym && sym == last_symbol)
2745 dump_usym (prof, sym, addr, 0); /* let's not guess the size */
2746 //printf ("found symbol at %p: %s\n", (void*)addr, sym);
2751 typedef struct MonoCounterAgent {
2752 MonoCounter *counter;
2753 // MonoCounterAgent specific data :
2758 struct MonoCounterAgent *next;
2761 static MonoCounterAgent* counters;
2762 static int counters_index = 1;
2763 static mono_mutex_t counters_mutex;
2766 counters_add_agent (MonoCounter *counter)
2768 if (InterlockedRead (&in_shutdown))
2771 MonoCounterAgent *agent, *item;
2773 mono_os_mutex_lock (&counters_mutex);
2775 for (agent = counters; agent; agent = agent->next) {
2776 if (agent->counter == counter) {
2777 agent->value_size = 0;
2779 g_free (agent->value);
2780 agent->value = NULL;
2786 agent = (MonoCounterAgent *) g_malloc (sizeof (MonoCounterAgent));
2787 agent->counter = counter;
2788 agent->value = NULL;
2789 agent->value_size = 0;
2790 agent->index = counters_index++;
2804 mono_os_mutex_unlock (&counters_mutex);
2808 counters_init_foreach_callback (MonoCounter *counter, gpointer data)
2810 counters_add_agent (counter);
2815 counters_init (MonoProfiler *profiler)
2817 mono_os_mutex_init (&counters_mutex);
2819 mono_counters_on_register (&counters_add_agent);
2820 mono_counters_foreach (counters_init_foreach_callback, NULL);
2824 counters_emit (MonoProfiler *profiler)
2826 MonoCounterAgent *agent;
2829 EVENT_SIZE /* event */ +
2830 LEB128_SIZE /* len */
2833 mono_os_mutex_lock (&counters_mutex);
2835 for (agent = counters; agent; agent = agent->next) {
2840 LEB128_SIZE /* section */ +
2841 strlen (mono_counter_get_name (agent->counter)) + 1 /* name */ +
2842 BYTE_SIZE /* type */ +
2843 BYTE_SIZE /* unit */ +
2844 BYTE_SIZE /* variance */ +
2845 LEB128_SIZE /* index */
2854 ENTER_LOG (&counter_descriptors_ctr, logbuffer, size);
2856 emit_event (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
2857 emit_value (logbuffer, len);
2859 for (agent = counters; agent; agent = agent->next) {
2865 name = mono_counter_get_name (agent->counter);
2866 emit_value (logbuffer, mono_counter_get_section (agent->counter));
2867 emit_string (logbuffer, name, strlen (name) + 1);
2868 emit_byte (logbuffer, mono_counter_get_type (agent->counter));
2869 emit_byte (logbuffer, mono_counter_get_unit (agent->counter));
2870 emit_byte (logbuffer, mono_counter_get_variance (agent->counter));
2871 emit_value (logbuffer, agent->index);
2876 EXIT_LOG_EXPLICIT (DO_SEND);
2879 mono_os_mutex_unlock (&counters_mutex);
2883 counters_sample (MonoProfiler *profiler, uint64_t timestamp)
2885 MonoCounterAgent *agent;
2886 MonoCounter *counter;
2892 counters_emit (profiler);
2895 buffer = g_calloc (1, buffer_size);
2897 mono_os_mutex_lock (&counters_mutex);
2900 EVENT_SIZE /* event */
2903 for (agent = counters; agent; agent = agent->next) {
2905 LEB128_SIZE /* index */ +
2906 BYTE_SIZE /* type */ +
2907 mono_counter_get_size (agent->counter) /* value */
2912 LEB128_SIZE /* stop marker */
2915 ENTER_LOG (&counter_samples_ctr, logbuffer, size);
2917 emit_event_time (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE, timestamp);
2919 for (agent = counters; agent; agent = agent->next) {
2922 counter = agent->counter;
2924 size = mono_counter_get_size (counter);
2926 if (size > buffer_size) {
2928 buffer = g_realloc (buffer, buffer_size);
2931 memset (buffer, 0, buffer_size);
2933 g_assert (mono_counters_sample (counter, buffer, size));
2935 type = mono_counter_get_type (counter);
2937 if (!agent->value) {
2938 agent->value = g_calloc (1, size);
2939 agent->value_size = size;
2941 if (type == MONO_COUNTER_STRING) {
2942 if (strcmp (agent->value, buffer) == 0)
2945 if (agent->value_size == size && memcmp (agent->value, buffer, size) == 0)
2950 emit_uvalue (logbuffer, agent->index);
2951 emit_byte (logbuffer, type);
2953 case MONO_COUNTER_INT:
2954 #if SIZEOF_VOID_P == 4
2955 case MONO_COUNTER_WORD:
2957 emit_svalue (logbuffer, *(int*)buffer - *(int*)agent->value);
2959 case MONO_COUNTER_UINT:
2960 emit_uvalue (logbuffer, *(guint*)buffer - *(guint*)agent->value);
2962 case MONO_COUNTER_TIME_INTERVAL:
2963 case MONO_COUNTER_LONG:
2964 #if SIZEOF_VOID_P == 8
2965 case MONO_COUNTER_WORD:
2967 emit_svalue (logbuffer, *(gint64*)buffer - *(gint64*)agent->value);
2969 case MONO_COUNTER_ULONG:
2970 emit_uvalue (logbuffer, *(guint64*)buffer - *(guint64*)agent->value);
2972 case MONO_COUNTER_DOUBLE:
2973 emit_double (logbuffer, *(double*)buffer);
2975 case MONO_COUNTER_STRING:
2977 emit_byte (logbuffer, 0);
2979 emit_byte (logbuffer, 1);
2980 emit_string (logbuffer, (char*)buffer, size);
2984 g_assert_not_reached ();
2987 if (type == MONO_COUNTER_STRING && size > agent->value_size) {
2988 agent->value = g_realloc (agent->value, size);
2989 agent->value_size = size;
2993 memcpy (agent->value, buffer, size);
2997 emit_value (logbuffer, 0);
2999 EXIT_LOG_EXPLICIT (DO_SEND);
3001 mono_os_mutex_unlock (&counters_mutex);
3004 typedef struct _PerfCounterAgent PerfCounterAgent;
3005 struct _PerfCounterAgent {
3006 PerfCounterAgent *next;
3008 char *category_name;
3017 static PerfCounterAgent *perfcounters = NULL;
3020 perfcounters_emit (MonoProfiler *profiler)
3022 PerfCounterAgent *pcagent;
3025 EVENT_SIZE /* event */ +
3026 LEB128_SIZE /* len */
3029 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3030 if (pcagent->emitted)
3034 LEB128_SIZE /* section */ +
3035 strlen (pcagent->category_name) + 1 /* category name */ +
3036 strlen (pcagent->name) + 1 /* name */ +
3037 BYTE_SIZE /* type */ +
3038 BYTE_SIZE /* unit */ +
3039 BYTE_SIZE /* variance */ +
3040 LEB128_SIZE /* index */
3049 ENTER_LOG (&perfcounter_descriptors_ctr, logbuffer, size);
3051 emit_event (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
3052 emit_value (logbuffer, len);
3054 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3055 if (pcagent->emitted)
3058 emit_value (logbuffer, MONO_COUNTER_PERFCOUNTERS);
3059 emit_string (logbuffer, pcagent->category_name, strlen (pcagent->category_name) + 1);
3060 emit_string (logbuffer, pcagent->name, strlen (pcagent->name) + 1);
3061 emit_byte (logbuffer, MONO_COUNTER_LONG);
3062 emit_byte (logbuffer, MONO_COUNTER_RAW);
3063 emit_byte (logbuffer, MONO_COUNTER_VARIABLE);
3064 emit_value (logbuffer, pcagent->index);
3066 pcagent->emitted = 1;
3069 EXIT_LOG_EXPLICIT (DO_SEND);
3073 perfcounters_foreach (char *category_name, char *name, unsigned char type, gint64 value, gpointer user_data)
3075 PerfCounterAgent *pcagent;
3077 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3078 if (strcmp (pcagent->category_name, category_name) != 0 || strcmp (pcagent->name, name) != 0)
3080 if (pcagent->value == value)
3083 pcagent->value = value;
3084 pcagent->updated = 1;
3085 pcagent->deleted = 0;
3089 pcagent = g_new0 (PerfCounterAgent, 1);
3090 pcagent->next = perfcounters;
3091 pcagent->index = counters_index++;
3092 pcagent->category_name = g_strdup (category_name);
3093 pcagent->name = g_strdup (name);
3094 pcagent->type = (int) type;
3095 pcagent->value = value;
3096 pcagent->emitted = 0;
3097 pcagent->updated = 1;
3098 pcagent->deleted = 0;
3100 perfcounters = pcagent;
3106 perfcounters_sample (MonoProfiler *profiler, uint64_t timestamp)
3108 PerfCounterAgent *pcagent;
3112 mono_os_mutex_lock (&counters_mutex);
3114 /* mark all perfcounters as deleted, foreach will unmark them as necessary */
3115 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next)
3116 pcagent->deleted = 1;
3118 mono_perfcounter_foreach (perfcounters_foreach, perfcounters);
3120 perfcounters_emit (profiler);
3123 EVENT_SIZE /* event */
3126 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3127 if (pcagent->deleted || !pcagent->updated)
3131 LEB128_SIZE /* index */ +
3132 BYTE_SIZE /* type */ +
3133 LEB128_SIZE /* value */
3143 LEB128_SIZE /* stop marker */
3146 ENTER_LOG (&perfcounter_samples_ctr, logbuffer, size);
3148 emit_event_time (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE, timestamp);
3150 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3151 if (pcagent->deleted || !pcagent->updated)
3153 emit_uvalue (logbuffer, pcagent->index);
3154 emit_byte (logbuffer, MONO_COUNTER_LONG);
3155 emit_svalue (logbuffer, pcagent->value);
3157 pcagent->updated = 0;
3160 emit_value (logbuffer, 0);
3162 EXIT_LOG_EXPLICIT (DO_SEND);
3165 mono_os_mutex_unlock (&counters_mutex);
3169 counters_and_perfcounters_sample (MonoProfiler *prof)
3171 uint64_t now = current_time ();
3173 counters_sample (prof, now);
3174 perfcounters_sample (prof, now);
3177 #define COVERAGE_DEBUG(x) if (debug_coverage) {x}
3178 static mono_mutex_t coverage_mutex;
3179 static MonoConcurrentHashTable *coverage_methods = NULL;
3180 static MonoConcurrentHashTable *coverage_assemblies = NULL;
3181 static MonoConcurrentHashTable *coverage_classes = NULL;
3183 static MonoConcurrentHashTable *filtered_classes = NULL;
3184 static MonoConcurrentHashTable *entered_methods = NULL;
3185 static MonoConcurrentHashTable *image_to_methods = NULL;
3186 static MonoConcurrentHashTable *suppressed_assemblies = NULL;
3187 static gboolean coverage_initialized = FALSE;
3189 static GPtrArray *coverage_data = NULL;
3190 static int previous_offset = 0;
3193 MonoLockFreeQueueNode node;
3206 free_coverage_entry (gpointer data, gpointer userdata)
3208 CoverageEntry *entry = (CoverageEntry *)data;
3209 g_free (entry->filename);
3214 obtain_coverage_for_method (MonoProfiler *prof, const MonoProfileCoverageEntry *entry)
3216 int offset = entry->iloffset - previous_offset;
3217 CoverageEntry *e = g_new (CoverageEntry, 1);
3219 previous_offset = entry->iloffset;
3222 e->counter = entry->counter;
3223 e->filename = g_strdup(entry->filename ? entry->filename : "");
3224 e->line = entry->line;
3225 e->column = entry->col;
3227 g_ptr_array_add (coverage_data, e);
3231 parse_generic_type_names(char *name)
3233 char *new_name, *ret;
3234 int within_generic_declaration = 0, generic_members = 1;
3236 if (name == NULL || *name == '\0')
3237 return g_strdup ("");
3239 if (!(ret = new_name = (char *) g_calloc (strlen (name) * 4 + 1, sizeof (char))))
3245 within_generic_declaration = 1;
3249 within_generic_declaration = 0;
3251 if (*(name - 1) != '<') {
3253 *new_name++ = '0' + generic_members;
3255 memcpy (new_name, "<>", 8);
3259 generic_members = 0;
3267 if (!within_generic_declaration)
3268 *new_name++ = *name;
3277 static int method_id;
3279 build_method_buffer (gpointer key, gpointer value, gpointer userdata)
3281 MonoMethod *method = (MonoMethod *)value;
3282 MonoProfiler *prof = (MonoProfiler *)userdata;
3286 const char *image_name, *method_name, *sig, *first_filename;
3289 previous_offset = 0;
3290 coverage_data = g_ptr_array_new ();
3292 mono_profiler_coverage_get (prof, method, obtain_coverage_for_method);
3294 klass = mono_method_get_class (method);
3295 image = mono_class_get_image (klass);
3296 image_name = mono_image_get_name (image);
3298 sig = mono_signature_get_desc (mono_method_signature (method), TRUE);
3299 class_name = parse_generic_type_names (mono_type_get_name (mono_class_get_type (klass)));
3300 method_name = mono_method_get_name (method);
3302 if (coverage_data->len != 0) {
3303 CoverageEntry *entry = (CoverageEntry *)coverage_data->pdata[0];
3304 first_filename = entry->filename ? entry->filename : "";
3306 first_filename = "";
3308 image_name = image_name ? image_name : "";
3309 sig = sig ? sig : "";
3310 method_name = method_name ? method_name : "";
3312 ENTER_LOG (&coverage_methods_ctr, logbuffer,
3313 EVENT_SIZE /* event */ +
3314 strlen (image_name) + 1 /* image name */ +
3315 strlen (class_name) + 1 /* class name */ +
3316 strlen (method_name) + 1 /* method name */ +
3317 strlen (sig) + 1 /* signature */ +
3318 strlen (first_filename) + 1 /* first file name */ +
3319 LEB128_SIZE /* token */ +
3320 LEB128_SIZE /* method id */ +
3321 LEB128_SIZE /* entries */
3324 emit_event (logbuffer, TYPE_COVERAGE_METHOD | TYPE_COVERAGE);
3325 emit_string (logbuffer, image_name, strlen (image_name) + 1);
3326 emit_string (logbuffer, class_name, strlen (class_name) + 1);
3327 emit_string (logbuffer, method_name, strlen (method_name) + 1);
3328 emit_string (logbuffer, sig, strlen (sig) + 1);
3329 emit_string (logbuffer, first_filename, strlen (first_filename) + 1);
3331 emit_uvalue (logbuffer, mono_method_get_token (method));
3332 emit_uvalue (logbuffer, method_id);
3333 emit_value (logbuffer, coverage_data->len);
3335 EXIT_LOG_EXPLICIT (DO_SEND);
3337 for (i = 0; i < coverage_data->len; i++) {
3338 CoverageEntry *entry = (CoverageEntry *)coverage_data->pdata[i];
3340 ENTER_LOG (&coverage_statements_ctr, logbuffer,
3341 EVENT_SIZE /* event */ +
3342 LEB128_SIZE /* method id */ +
3343 LEB128_SIZE /* offset */ +
3344 LEB128_SIZE /* counter */ +
3345 LEB128_SIZE /* line */ +
3346 LEB128_SIZE /* column */
3349 emit_event (logbuffer, TYPE_COVERAGE_STATEMENT | TYPE_COVERAGE);
3350 emit_uvalue (logbuffer, method_id);
3351 emit_uvalue (logbuffer, entry->offset);
3352 emit_uvalue (logbuffer, entry->counter);
3353 emit_uvalue (logbuffer, entry->line);
3354 emit_uvalue (logbuffer, entry->column);
3356 EXIT_LOG_EXPLICIT (DO_SEND);
3361 g_free (class_name);
3363 g_ptr_array_foreach (coverage_data, free_coverage_entry, NULL);
3364 g_ptr_array_free (coverage_data, TRUE);
3365 coverage_data = NULL;
3368 /* This empties the queue */
3370 count_queue (MonoLockFreeQueue *queue)
3372 MonoLockFreeQueueNode *node;
3375 while ((node = mono_lock_free_queue_dequeue (queue))) {
3377 mono_thread_hazardous_try_free (node, g_free);
3384 build_class_buffer (gpointer key, gpointer value, gpointer userdata)
3386 MonoClass *klass = (MonoClass *)key;
3387 MonoLockFreeQueue *class_methods = (MonoLockFreeQueue *)value;
3390 const char *assembly_name;
3391 int number_of_methods, partially_covered;
3392 guint fully_covered;
3394 image = mono_class_get_image (klass);
3395 assembly_name = mono_image_get_name (image);
3396 class_name = mono_type_get_name (mono_class_get_type (klass));
3398 assembly_name = assembly_name ? assembly_name : "";
3399 number_of_methods = mono_class_num_methods (klass);
3400 fully_covered = count_queue (class_methods);
3401 /* We don't handle partial covered yet */
3402 partially_covered = 0;
3404 ENTER_LOG (&coverage_classes_ctr, logbuffer,
3405 EVENT_SIZE /* event */ +
3406 strlen (assembly_name) + 1 /* assembly name */ +
3407 strlen (class_name) + 1 /* class name */ +
3408 LEB128_SIZE /* no. methods */ +
3409 LEB128_SIZE /* fully covered */ +
3410 LEB128_SIZE /* partially covered */
3413 emit_event (logbuffer, TYPE_COVERAGE_CLASS | TYPE_COVERAGE);
3414 emit_string (logbuffer, assembly_name, strlen (assembly_name) + 1);
3415 emit_string (logbuffer, class_name, strlen (class_name) + 1);
3416 emit_uvalue (logbuffer, number_of_methods);
3417 emit_uvalue (logbuffer, fully_covered);
3418 emit_uvalue (logbuffer, partially_covered);
3420 EXIT_LOG_EXPLICIT (DO_SEND);
3422 g_free (class_name);
3426 get_coverage_for_image (MonoImage *image, int *number_of_methods, guint *fully_covered, int *partially_covered)
3428 MonoLockFreeQueue *image_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (image_to_methods, image);
3430 *number_of_methods = mono_image_get_table_rows (image, MONO_TABLE_METHOD);
3432 *fully_covered = count_queue (image_methods);
3436 // FIXME: We don't handle partially covered yet.
3437 *partially_covered = 0;
3441 build_assembly_buffer (gpointer key, gpointer value, gpointer userdata)
3443 MonoAssembly *assembly = (MonoAssembly *)value;
3444 MonoImage *image = mono_assembly_get_image (assembly);
3445 const char *name, *guid, *filename;
3446 int number_of_methods = 0, partially_covered = 0;
3447 guint fully_covered = 0;
3449 name = mono_image_get_name (image);
3450 guid = mono_image_get_guid (image);
3451 filename = mono_image_get_filename (image);
3453 name = name ? name : "";
3454 guid = guid ? guid : "";
3455 filename = filename ? filename : "";
3457 get_coverage_for_image (image, &number_of_methods, &fully_covered, &partially_covered);
3459 ENTER_LOG (&coverage_assemblies_ctr, logbuffer,
3460 EVENT_SIZE /* event */ +
3461 strlen (name) + 1 /* name */ +
3462 strlen (guid) + 1 /* guid */ +
3463 strlen (filename) + 1 /* file name */ +
3464 LEB128_SIZE /* no. methods */ +
3465 LEB128_SIZE /* fully covered */ +
3466 LEB128_SIZE /* partially covered */
3469 emit_event (logbuffer, TYPE_COVERAGE_ASSEMBLY | TYPE_COVERAGE);
3470 emit_string (logbuffer, name, strlen (name) + 1);
3471 emit_string (logbuffer, guid, strlen (guid) + 1);
3472 emit_string (logbuffer, filename, strlen (filename) + 1);
3473 emit_uvalue (logbuffer, number_of_methods);
3474 emit_uvalue (logbuffer, fully_covered);
3475 emit_uvalue (logbuffer, partially_covered);
3477 EXIT_LOG_EXPLICIT (DO_SEND);
3481 dump_coverage (MonoProfiler *prof)
3483 if (!coverage_initialized)
3486 COVERAGE_DEBUG(fprintf (stderr, "Coverage: Started dump\n");)
3489 mono_os_mutex_lock (&coverage_mutex);
3490 mono_conc_hashtable_foreach (coverage_assemblies, build_assembly_buffer, NULL);
3491 mono_conc_hashtable_foreach (coverage_classes, build_class_buffer, NULL);
3492 mono_conc_hashtable_foreach (coverage_methods, build_method_buffer, prof);
3493 mono_os_mutex_unlock (&coverage_mutex);
3495 COVERAGE_DEBUG(fprintf (stderr, "Coverage: Finished dump\n");)
3499 process_method_enter_coverage (MonoProfiler *prof, MonoMethod *method)
3504 if (!coverage_initialized)
3507 klass = mono_method_get_class (method);
3508 image = mono_class_get_image (klass);
3510 if (mono_conc_hashtable_lookup (suppressed_assemblies, (gpointer) mono_image_get_name (image)))
3513 mono_os_mutex_lock (&coverage_mutex);
3514 mono_conc_hashtable_insert (entered_methods, method, method);
3515 mono_os_mutex_unlock (&coverage_mutex);
3518 static MonoLockFreeQueueNode *
3519 create_method_node (MonoMethod *method)
3521 MethodNode *node = (MethodNode *) g_malloc (sizeof (MethodNode));
3522 mono_lock_free_queue_node_init ((MonoLockFreeQueueNode *) node, FALSE);
3523 node->method = method;
3525 return (MonoLockFreeQueueNode *) node;
3529 coverage_filter (MonoProfiler *prof, MonoMethod *method)
3534 MonoAssembly *assembly;
3535 MonoMethodHeader *header;
3536 guint32 iflags, flags, code_size;
3537 char *fqn, *classname;
3538 gboolean has_positive, found;
3539 MonoLockFreeQueue *image_methods, *class_methods;
3540 MonoLockFreeQueueNode *node;
3542 g_assert (coverage_initialized && "Why are we being asked for coverage filter info when we're not doing coverage?");
3544 COVERAGE_DEBUG(fprintf (stderr, "Coverage filter for %s\n", mono_method_get_name (method));)
3546 flags = mono_method_get_flags (method, &iflags);
3547 if ((iflags & 0x1000 /*METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL*/) ||
3548 (flags & 0x2000 /*METHOD_ATTRIBUTE_PINVOKE_IMPL*/)) {
3549 COVERAGE_DEBUG(fprintf (stderr, " Internal call or pinvoke - ignoring\n");)
3553 // Don't need to do anything else if we're already tracking this method
3554 if (mono_conc_hashtable_lookup (coverage_methods, method)) {
3555 COVERAGE_DEBUG(fprintf (stderr, " Already tracking\n");)
3559 klass = mono_method_get_class (method);
3560 image = mono_class_get_image (klass);
3562 // Don't handle coverage for the core assemblies
3563 if (mono_conc_hashtable_lookup (suppressed_assemblies, (gpointer) mono_image_get_name (image)) != NULL)
3566 if (prof->coverage_filters) {
3567 /* Check already filtered classes first */
3568 if (mono_conc_hashtable_lookup (filtered_classes, klass)) {
3569 COVERAGE_DEBUG(fprintf (stderr, " Already filtered\n");)
3573 classname = mono_type_get_name (mono_class_get_type (klass));
3575 fqn = g_strdup_printf ("[%s]%s", mono_image_get_name (image), classname);
3577 COVERAGE_DEBUG(fprintf (stderr, " Looking for %s in filter\n", fqn);)
3578 // Check positive filters first
3579 has_positive = FALSE;
3581 for (guint i = 0; i < prof->coverage_filters->len; ++i) {
3582 char *filter = (char *)g_ptr_array_index (prof->coverage_filters, i);
3584 if (filter [0] == '+') {
3585 filter = &filter [1];
3587 COVERAGE_DEBUG(fprintf (stderr, " Checking against +%s ...", filter);)
3589 if (strstr (fqn, filter) != NULL) {
3590 COVERAGE_DEBUG(fprintf (stderr, "matched\n");)
3593 COVERAGE_DEBUG(fprintf (stderr, "no match\n");)
3595 has_positive = TRUE;
3599 if (has_positive && !found) {
3600 COVERAGE_DEBUG(fprintf (stderr, " Positive match was not found\n");)
3602 mono_os_mutex_lock (&coverage_mutex);
3603 mono_conc_hashtable_insert (filtered_classes, klass, klass);
3604 mono_os_mutex_unlock (&coverage_mutex);
3611 for (guint i = 0; i < prof->coverage_filters->len; ++i) {
3612 // FIXME: Is substring search sufficient?
3613 char *filter = (char *)g_ptr_array_index (prof->coverage_filters, i);
3614 if (filter [0] == '+')
3618 filter = &filter [1];
3619 COVERAGE_DEBUG(fprintf (stderr, " Checking against -%s ...", filter);)
3621 if (strstr (fqn, filter) != NULL) {
3622 COVERAGE_DEBUG(fprintf (stderr, "matched\n");)
3624 mono_os_mutex_lock (&coverage_mutex);
3625 mono_conc_hashtable_insert (filtered_classes, klass, klass);
3626 mono_os_mutex_unlock (&coverage_mutex);
3632 COVERAGE_DEBUG(fprintf (stderr, "no match\n");)
3640 COVERAGE_DEBUG(fprintf (stderr, " Handling coverage for %s\n", mono_method_get_name (method));)
3641 header = mono_method_get_header_checked (method, &error);
3642 mono_error_cleanup (&error);
3644 mono_method_header_get_code (header, &code_size, NULL);
3646 assembly = mono_image_get_assembly (image);
3648 // Need to keep the assemblies around for as long as they are kept in the hashtable
3649 // Nunit, for example, has a habit of unloading them before the coverage statistics are
3650 // generated causing a crash. See https://bugzilla.xamarin.com/show_bug.cgi?id=39325
3651 mono_assembly_addref (assembly);
3653 mono_os_mutex_lock (&coverage_mutex);
3654 mono_conc_hashtable_insert (coverage_methods, method, method);
3655 mono_conc_hashtable_insert (coverage_assemblies, assembly, assembly);
3656 mono_os_mutex_unlock (&coverage_mutex);
3658 image_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (image_to_methods, image);
3660 if (image_methods == NULL) {
3661 image_methods = (MonoLockFreeQueue *) g_malloc (sizeof (MonoLockFreeQueue));
3662 mono_lock_free_queue_init (image_methods);
3663 mono_os_mutex_lock (&coverage_mutex);
3664 mono_conc_hashtable_insert (image_to_methods, image, image_methods);
3665 mono_os_mutex_unlock (&coverage_mutex);
3668 node = create_method_node (method);
3669 mono_lock_free_queue_enqueue (image_methods, node);
3671 class_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (coverage_classes, klass);
3673 if (class_methods == NULL) {
3674 class_methods = (MonoLockFreeQueue *) g_malloc (sizeof (MonoLockFreeQueue));
3675 mono_lock_free_queue_init (class_methods);
3676 mono_os_mutex_lock (&coverage_mutex);
3677 mono_conc_hashtable_insert (coverage_classes, klass, class_methods);
3678 mono_os_mutex_unlock (&coverage_mutex);
3681 node = create_method_node (method);
3682 mono_lock_free_queue_enqueue (class_methods, node);
3687 #define LINE_BUFFER_SIZE 4096
3688 /* Max file limit of 128KB */
3689 #define MAX_FILE_SIZE 128 * 1024
3691 get_file_content (FILE *stream)
3696 int res, offset = 0;
3698 res = fseek (stream, 0, SEEK_END);
3702 filesize = ftell (stream);
3706 res = fseek (stream, 0, SEEK_SET);
3710 if (filesize > MAX_FILE_SIZE)
3713 buffer = (char *) g_malloc ((filesize + 1) * sizeof (char));
3714 while ((bytes_read = fread (buffer + offset, 1, LINE_BUFFER_SIZE, stream)) > 0)
3715 offset += bytes_read;
3717 /* NULL terminate our buffer */
3718 buffer[filesize] = '\0';
3723 get_next_line (char *contents, char **next_start)
3727 if (p == NULL || *p == '\0') {
3732 while (*p != '\n' && *p != '\0')
3737 *next_start = p + 1;
3745 init_suppressed_assemblies (void)
3751 suppressed_assemblies = mono_conc_hashtable_new (g_str_hash, g_str_equal);
3752 sa_file = fopen (SUPPRESSION_DIR "/mono-profiler-log.suppression", "r");
3753 if (sa_file == NULL)
3756 /* Don't need to free @content as it is referred to by the lines stored in @suppressed_assemblies */
3757 content = get_file_content (sa_file);
3758 if (content == NULL) {
3759 g_error ("mono-profiler-log.suppression is greater than 128kb - aborting\n");
3762 while ((line = get_next_line (content, &content))) {
3763 line = g_strchomp (g_strchug (line));
3764 /* No locking needed as we're doing initialization */
3765 mono_conc_hashtable_insert (suppressed_assemblies, line, line);
3772 parse_cov_filter_file (GPtrArray *filters, const char *file)
3775 char *line, *content;
3777 filter_file = fopen (file, "r");
3778 if (filter_file == NULL) {
3779 fprintf (stderr, "Unable to open %s\n", file);
3783 /* Don't need to free content as it is referred to by the lines stored in @filters */
3784 content = get_file_content (filter_file);
3785 if (content == NULL)
3786 fprintf (stderr, "WARNING: %s is greater than 128kb - ignoring\n", file);
3788 while ((line = get_next_line (content, &content)))
3789 g_ptr_array_add (filters, g_strchug (g_strchomp (line)));
3791 fclose (filter_file);
3795 coverage_init (MonoProfiler *prof)
3797 g_assert (!coverage_initialized && "Why are we initializing coverage twice?");
3799 COVERAGE_DEBUG(fprintf (stderr, "Coverage initialized\n");)
3801 mono_os_mutex_init (&coverage_mutex);
3802 coverage_methods = mono_conc_hashtable_new (NULL, NULL);
3803 coverage_assemblies = mono_conc_hashtable_new (NULL, NULL);
3804 coverage_classes = mono_conc_hashtable_new (NULL, NULL);
3805 filtered_classes = mono_conc_hashtable_new (NULL, NULL);
3806 entered_methods = mono_conc_hashtable_new (NULL, NULL);
3807 image_to_methods = mono_conc_hashtable_new (NULL, NULL);
3808 init_suppressed_assemblies ();
3810 coverage_initialized = TRUE;
3814 unref_coverage_assemblies (gpointer key, gpointer value, gpointer userdata)
3816 MonoAssembly *assembly = (MonoAssembly *)value;
3817 mono_assembly_close (assembly);
3821 free_sample_hit (gpointer p)
3823 mono_lock_free_free (p, SAMPLE_BLOCK_SIZE);
3827 cleanup_reusable_samples (MonoProfiler *prof)
3831 while ((sample = (SampleHit *) mono_lock_free_queue_dequeue (&prof->sample_reuse_queue)))
3832 mono_thread_hazardous_try_free (sample, free_sample_hit);
3836 log_shutdown (MonoProfiler *prof)
3838 InterlockedWrite (&in_shutdown, 1);
3841 counters_and_perfcounters_sample (prof);
3843 dump_coverage (prof);
3847 if (write (prof->pipes [1], &c, 1) != 1) {
3848 fprintf (stderr, "Could not write to pipe: %s\n", strerror (errno));
3852 mono_native_thread_join (prof->helper_thread);
3854 mono_os_mutex_destroy (&counters_mutex);
3856 MonoCounterAgent *mc_next;
3858 for (MonoCounterAgent *cur = counters; cur; cur = mc_next) {
3859 mc_next = cur->next;
3863 PerfCounterAgent *pc_next;
3865 for (PerfCounterAgent *cur = perfcounters; cur; cur = pc_next) {
3866 pc_next = cur->next;
3871 * Ensure that we empty the LLS completely, even if some nodes are
3872 * not immediately removed upon calling mono_lls_remove (), by
3873 * iterating until the head is NULL.
3875 while (profiler_thread_list.head) {
3876 MONO_LLS_FOREACH_SAFE (&profiler_thread_list, MonoProfilerThread, thread) {
3877 g_assert (thread->attached && "Why is a thread in the LLS not attached?");
3879 remove_thread (thread);
3880 } MONO_LLS_FOREACH_SAFE_END
3884 * Ensure that all threads have been freed, so that we don't miss any
3885 * buffers when we shut down the writer thread below.
3887 mono_thread_hazardous_try_free_all ();
3889 InterlockedWrite (&prof->run_dumper_thread, 0);
3890 mono_os_sem_post (&prof->dumper_queue_sem);
3891 mono_native_thread_join (prof->dumper_thread);
3892 mono_os_sem_destroy (&prof->dumper_queue_sem);
3894 InterlockedWrite (&prof->run_writer_thread, 0);
3895 mono_os_sem_post (&prof->writer_queue_sem);
3896 mono_native_thread_join (prof->writer_thread);
3897 mono_os_sem_destroy (&prof->writer_queue_sem);
3900 * Free all writer queue entries, and ensure that all sample hits will be
3901 * added to the sample reuse queue.
3903 mono_thread_hazardous_try_free_all ();
3905 cleanup_reusable_samples (prof);
3908 * Finally, make sure that all sample hits are freed. This should cover all
3909 * hazardous data from the profiler. We can now be sure that the runtime
3910 * won't later invoke free functions in the profiler library after it has
3913 mono_thread_hazardous_try_free_all ();
3915 g_assert (!InterlockedRead (&buffer_rwlock_count) && "Why is the reader count still non-zero?");
3916 g_assert (!InterlockedReadPointer (&buffer_rwlock_exclusive) && "Why does someone still hold the exclusive lock?");
3918 #if defined (HAVE_SYS_ZLIB)
3920 gzclose (prof->gzfile);
3922 if (prof->pipe_output)
3923 pclose (prof->file);
3925 fclose (prof->file);
3927 mono_conc_hashtable_destroy (prof->method_table);
3928 mono_os_mutex_destroy (&prof->method_table_mutex);
3930 if (coverage_initialized) {
3931 mono_os_mutex_lock (&coverage_mutex);
3932 mono_conc_hashtable_foreach (coverage_assemblies, unref_coverage_assemblies, prof);
3933 mono_os_mutex_unlock (&coverage_mutex);
3935 mono_conc_hashtable_destroy (coverage_methods);
3936 mono_conc_hashtable_destroy (coverage_assemblies);
3937 mono_conc_hashtable_destroy (coverage_classes);
3938 mono_conc_hashtable_destroy (filtered_classes);
3940 mono_conc_hashtable_destroy (entered_methods);
3941 mono_conc_hashtable_destroy (image_to_methods);
3942 mono_conc_hashtable_destroy (suppressed_assemblies);
3943 mono_os_mutex_destroy (&coverage_mutex);
3948 g_free (prof->args);
3953 new_filename (const char* filename)
3955 time_t t = time (NULL);
3956 int pid = process_id ();
3961 int count_dates = 0;
3965 for (p = filename; *p; p++) {
3976 if (!count_dates && !count_pids)
3977 return pstrdup (filename);
3978 snprintf (pid_buf, sizeof (pid_buf), "%d", pid);
3980 snprintf (time_buf, sizeof (time_buf), "%d%02d%02d%02d%02d%02d",
3981 1900 + ts->tm_year, 1 + ts->tm_mon, ts->tm_mday, ts->tm_hour, ts->tm_min, ts->tm_sec);
3982 s_date = strlen (time_buf);
3983 s_pid = strlen (pid_buf);
3984 d = res = (char *) g_malloc (strlen (filename) + s_date * count_dates + s_pid * count_pids);
3985 for (p = filename; *p; p++) {
3992 strcpy (d, time_buf);
3995 } else if (*p == 'p') {
3996 strcpy (d, pid_buf);
3999 } else if (*p == '%') {
4012 add_to_fd_set (fd_set *set, int fd, int *max_fd)
4015 * This should only trigger for the basic FDs (server socket, pipes) at
4016 * startup if for some mysterious reason they're too large. In this case,
4017 * the profiler really can't function, and we're better off printing an
4018 * error and exiting.
4020 if (fd >= FD_SETSIZE) {
4021 fprintf (stderr, "File descriptor is out of bounds for fd_set: %d\n", fd);
4032 helper_thread (void *arg)
4034 MonoProfiler *prof = (MonoProfiler *) arg;
4036 mono_threads_attach_tools_thread ();
4037 mono_native_thread_set_name (mono_native_thread_id_get (), "Profiler helper");
4039 MonoProfilerThread *thread = init_thread (prof, FALSE);
4041 GArray *command_sockets = g_array_new (FALSE, FALSE, sizeof (int));
4049 add_to_fd_set (&rfds, prof->server_socket, &max_fd);
4050 add_to_fd_set (&rfds, prof->pipes [0], &max_fd);
4052 for (gint i = 0; i < command_sockets->len; i++)
4053 add_to_fd_set (&rfds, g_array_index (command_sockets, int, i), &max_fd);
4055 struct timeval tv = { .tv_sec = 1, .tv_usec = 0 };
4057 // Sleep for 1sec or until a file descriptor has data.
4058 if (select (max_fd + 1, &rfds, NULL, NULL, &tv) == -1) {
4062 fprintf (stderr, "Error in mono-profiler-log server: %s", strerror (errno));
4067 counters_and_perfcounters_sample (prof);
4069 buffer_lock_excl ();
4071 sync_point (SYNC_POINT_PERIODIC);
4073 buffer_unlock_excl ();
4075 // Are we shutting down?
4076 if (FD_ISSET (prof->pipes [0], &rfds)) {
4078 read (prof->pipes [0], &c, 1);
4082 for (gint i = 0; i < command_sockets->len; i++) {
4083 int fd = g_array_index (command_sockets, int, i);
4085 if (!FD_ISSET (fd, &rfds))
4089 int len = read (fd, buf, sizeof (buf) - 1);
4095 // The other end disconnected.
4096 g_array_remove_index (command_sockets, i);
4104 if (!strcmp (buf, "heapshot\n") && hs_mode_ondemand) {
4105 // Rely on the finalization callback triggering a GC.
4106 heapshot_requested = 1;
4107 mono_gc_finalize_notify ();
4111 if (FD_ISSET (prof->server_socket, &rfds)) {
4112 int fd = accept (prof->server_socket, NULL, NULL);
4115 if (fd >= FD_SETSIZE)
4118 g_array_append_val (command_sockets, fd);
4123 for (gint i = 0; i < command_sockets->len; i++)
4124 close (g_array_index (command_sockets, int, i));
4126 g_array_free (command_sockets, TRUE);
4128 send_log_unsafe (FALSE);
4129 deinit_thread (thread);
4131 mono_thread_info_detach ();
4137 start_helper_thread (MonoProfiler* prof)
4139 if (pipe (prof->pipes) == -1) {
4140 fprintf (stderr, "Cannot create pipe: %s\n", strerror (errno));
4144 prof->server_socket = socket (PF_INET, SOCK_STREAM, 0);
4146 if (prof->server_socket == -1) {
4147 fprintf (stderr, "Cannot create server socket: %s\n", strerror (errno));
4151 struct sockaddr_in server_address;
4153 memset (&server_address, 0, sizeof (server_address));
4154 server_address.sin_family = AF_INET;
4155 server_address.sin_addr.s_addr = INADDR_ANY;
4156 server_address.sin_port = htons (prof->command_port);
4158 if (bind (prof->server_socket, (struct sockaddr *) &server_address, sizeof (server_address)) == -1) {
4159 fprintf (stderr, "Cannot bind server socket on port %d: %s\n", prof->command_port, strerror (errno));
4160 close (prof->server_socket);
4164 if (listen (prof->server_socket, 1) == -1) {
4165 fprintf (stderr, "Cannot listen on server socket: %s\n", strerror (errno));
4166 close (prof->server_socket);
4170 socklen_t slen = sizeof (server_address);
4172 if (getsockname (prof->server_socket, (struct sockaddr *) &server_address, &slen)) {
4173 fprintf (stderr, "Could not get assigned port: %s\n", strerror (errno));
4174 close (prof->server_socket);
4178 prof->command_port = ntohs (server_address.sin_port);
4180 if (!mono_native_thread_create (&prof->helper_thread, helper_thread, prof)) {
4181 fprintf (stderr, "Could not start helper thread\n");
4182 close (prof->server_socket);
4188 free_writer_entry (gpointer p)
4190 mono_lock_free_free (p, WRITER_ENTRY_BLOCK_SIZE);
4194 handle_writer_queue_entry (MonoProfiler *prof)
4196 WriterQueueEntry *entry;
4198 if ((entry = (WriterQueueEntry *) mono_lock_free_queue_dequeue (&prof->writer_queue))) {
4199 if (!entry->methods)
4202 gboolean wrote_methods = FALSE;
4205 * Encode the method events in a temporary log buffer that we
4206 * flush to disk before the main buffer, ensuring that all
4207 * methods have metadata emitted before they're referenced.
4209 * We use a 'proper' thread-local buffer for this as opposed
4210 * to allocating and freeing a buffer by hand because the call
4211 * to mono_method_full_name () below may trigger class load
4212 * events when it retrieves the signature of the method. So a
4213 * thread-local buffer needs to exist when such events occur.
4215 for (guint i = 0; i < entry->methods->len; i++) {
4216 MethodInfo *info = (MethodInfo *) g_ptr_array_index (entry->methods, i);
4218 if (mono_conc_hashtable_lookup (prof->method_table, info->method))
4219 goto free_info; // This method already has metadata emitted.
4222 * Other threads use this hash table to get a general
4223 * idea of whether a method has already been emitted to
4224 * the stream. Due to the way we add to this table, it
4225 * can easily happen that multiple threads queue up the
4226 * same methods, but that's OK since eventually all
4227 * methods will be in this table and the thread-local
4228 * method lists will just be empty for the rest of the
4231 mono_os_mutex_lock (&prof->method_table_mutex);
4232 mono_conc_hashtable_insert (prof->method_table, info->method, info->method);
4233 mono_os_mutex_unlock (&prof->method_table_mutex);
4235 char *name = mono_method_full_name (info->method, 1);
4236 int nlen = strlen (name) + 1;
4237 void *cstart = info->ji ? mono_jit_info_get_code_start (info->ji) : NULL;
4238 int csize = info->ji ? mono_jit_info_get_code_size (info->ji) : 0;
4240 ENTER_LOG (&method_jits_ctr, logbuffer,
4241 EVENT_SIZE /* event */ +
4242 LEB128_SIZE /* method */ +
4243 LEB128_SIZE /* start */ +
4244 LEB128_SIZE /* size */ +
4248 emit_event_time (logbuffer, TYPE_JIT | TYPE_METHOD, info->time);
4249 emit_method_inner (logbuffer, info->method);
4250 emit_ptr (logbuffer, cstart);
4251 emit_value (logbuffer, csize);
4253 memcpy (logbuffer->cursor, name, nlen);
4254 logbuffer->cursor += nlen;
4256 EXIT_LOG_EXPLICIT (NO_SEND);
4260 wrote_methods = TRUE;
4266 g_ptr_array_free (entry->methods, TRUE);
4268 if (wrote_methods) {
4269 MonoProfilerThread *thread = PROF_TLS_GET ();
4271 dump_buffer_threadless (prof, thread->buffer);
4272 init_buffer_state (thread);
4276 dump_buffer (prof, entry->buffer);
4278 mono_thread_hazardous_try_free (entry, free_writer_entry);
4287 writer_thread (void *arg)
4289 MonoProfiler *prof = (MonoProfiler *)arg;
4291 mono_threads_attach_tools_thread ();
4292 mono_native_thread_set_name (mono_native_thread_id_get (), "Profiler writer");
4296 MonoProfilerThread *thread = init_thread (prof, FALSE);
4298 while (InterlockedRead (&prof->run_writer_thread)) {
4299 mono_os_sem_wait (&prof->writer_queue_sem, MONO_SEM_FLAGS_NONE);
4300 handle_writer_queue_entry (prof);
4303 /* Drain any remaining entries on shutdown. */
4304 while (handle_writer_queue_entry (prof));
4306 free_buffer (thread->buffer, thread->buffer->size);
4307 deinit_thread (thread);
4309 mono_thread_info_detach ();
4315 start_writer_thread (MonoProfiler* prof)
4317 InterlockedWrite (&prof->run_writer_thread, 1);
4319 if (!mono_native_thread_create (&prof->writer_thread, writer_thread, prof)) {
4320 fprintf (stderr, "Could not start writer thread\n");
4326 reuse_sample_hit (gpointer p)
4328 SampleHit *sample = p;
4330 mono_lock_free_queue_node_unpoison (&sample->node);
4331 mono_lock_free_queue_enqueue (&sample->prof->sample_reuse_queue, &sample->node);
4335 handle_dumper_queue_entry (MonoProfiler *prof)
4339 if ((sample = (SampleHit *) mono_lock_free_queue_dequeue (&prof->dumper_queue))) {
4340 for (int i = 0; i < sample->count; ++i) {
4341 MonoMethod *method = sample->frames [i].method;
4342 MonoDomain *domain = sample->frames [i].domain;
4343 void *address = sample->frames [i].base_address;
4346 g_assert (domain && "What happened to the domain pointer?");
4347 g_assert (address && "What happened to the instruction pointer?");
4349 MonoJitInfo *ji = mono_jit_info_table_find (domain, (char *) address);
4352 sample->frames [i].method = mono_jit_info_get_method (ji);
4356 ENTER_LOG (&sample_hits_ctr, logbuffer,
4357 EVENT_SIZE /* event */ +
4358 BYTE_SIZE /* type */ +
4359 LEB128_SIZE /* tid */ +
4360 LEB128_SIZE /* count */ +
4362 LEB128_SIZE /* ip */
4364 LEB128_SIZE /* managed count */ +
4366 LEB128_SIZE /* method */
4370 emit_event_time (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_HIT, sample->time);
4371 emit_byte (logbuffer, SAMPLE_CYCLES);
4372 emit_ptr (logbuffer, (void *) sample->tid);
4373 emit_value (logbuffer, 1);
4375 // TODO: Actual native unwinding.
4376 for (int i = 0; i < 1; ++i) {
4377 emit_ptr (logbuffer, sample->ip);
4378 add_code_pointer ((uintptr_t) sample->ip);
4381 /* new in data version 6 */
4382 emit_uvalue (logbuffer, sample->count);
4384 for (int i = 0; i < sample->count; ++i)
4385 emit_method (logbuffer, sample->frames [i].method);
4387 EXIT_LOG_EXPLICIT (DO_SEND);
4389 mono_thread_hazardous_try_free (sample, reuse_sample_hit);
4391 dump_unmanaged_coderefs (prof);
4398 dumper_thread (void *arg)
4400 MonoProfiler *prof = (MonoProfiler *)arg;
4402 mono_threads_attach_tools_thread ();
4403 mono_native_thread_set_name (mono_native_thread_id_get (), "Profiler dumper");
4405 MonoProfilerThread *thread = init_thread (prof, FALSE);
4407 while (InterlockedRead (&prof->run_dumper_thread)) {
4409 * Flush samples every second so it doesn't seem like the profiler is
4410 * not working if the program is mostly idle.
4412 if (mono_os_sem_timedwait (&prof->dumper_queue_sem, 1000, MONO_SEM_FLAGS_NONE) == MONO_SEM_TIMEDWAIT_RET_TIMEDOUT)
4413 send_log_unsafe (FALSE);
4415 handle_dumper_queue_entry (prof);
4418 /* Drain any remaining entries on shutdown. */
4419 while (handle_dumper_queue_entry (prof));
4421 send_log_unsafe (FALSE);
4422 deinit_thread (thread);
4424 mono_thread_info_detach ();
4430 start_dumper_thread (MonoProfiler* prof)
4432 InterlockedWrite (&prof->run_dumper_thread, 1);
4434 if (!mono_native_thread_create (&prof->dumper_thread, dumper_thread, prof)) {
4435 fprintf (stderr, "Could not start dumper thread\n");
4441 register_counter (const char *name, gint32 *counter)
4443 mono_counters_register (name, MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, counter);
4447 runtime_initialized (MonoProfiler *profiler)
4449 InterlockedWrite (&runtime_inited, 1);
4451 register_counter ("Sample events allocated", &sample_allocations_ctr);
4452 register_counter ("Log buffers allocated", &buffer_allocations_ctr);
4454 register_counter ("Event: Sync points", &sync_points_ctr);
4455 register_counter ("Event: Heap objects", &heap_objects_ctr);
4456 register_counter ("Event: Heap starts", &heap_starts_ctr);
4457 register_counter ("Event: Heap ends", &heap_ends_ctr);
4458 register_counter ("Event: Heap roots", &heap_roots_ctr);
4459 register_counter ("Event: GC events", &gc_events_ctr);
4460 register_counter ("Event: GC resizes", &gc_resizes_ctr);
4461 register_counter ("Event: GC allocations", &gc_allocs_ctr);
4462 register_counter ("Event: GC moves", &gc_moves_ctr);
4463 register_counter ("Event: GC handle creations", &gc_handle_creations_ctr);
4464 register_counter ("Event: GC handle deletions", &gc_handle_deletions_ctr);
4465 register_counter ("Event: GC finalize starts", &finalize_begins_ctr);
4466 register_counter ("Event: GC finalize ends", &finalize_ends_ctr);
4467 register_counter ("Event: GC finalize object starts", &finalize_object_begins_ctr);
4468 register_counter ("Event: GC finalize object ends", &finalize_object_ends_ctr);
4469 register_counter ("Event: Image loads", &image_loads_ctr);
4470 register_counter ("Event: Image unloads", &image_unloads_ctr);
4471 register_counter ("Event: Assembly loads", &assembly_loads_ctr);
4472 register_counter ("Event: Assembly unloads", &assembly_unloads_ctr);
4473 register_counter ("Event: Class loads", &class_loads_ctr);
4474 register_counter ("Event: Class unloads", &class_unloads_ctr);
4475 register_counter ("Event: Method entries", &method_entries_ctr);
4476 register_counter ("Event: Method exits", &method_exits_ctr);
4477 register_counter ("Event: Method exception leaves", &method_exception_exits_ctr);
4478 register_counter ("Event: Method JITs", &method_jits_ctr);
4479 register_counter ("Event: Code buffers", &code_buffers_ctr);
4480 register_counter ("Event: Exception throws", &exception_throws_ctr);
4481 register_counter ("Event: Exception clauses", &exception_clauses_ctr);
4482 register_counter ("Event: Monitor events", &monitor_events_ctr);
4483 register_counter ("Event: Thread starts", &thread_starts_ctr);
4484 register_counter ("Event: Thread ends", &thread_ends_ctr);
4485 register_counter ("Event: Thread names", &thread_names_ctr);
4486 register_counter ("Event: Domain loads", &domain_loads_ctr);
4487 register_counter ("Event: Domain unloads", &domain_unloads_ctr);
4488 register_counter ("Event: Domain names", &domain_names_ctr);
4489 register_counter ("Event: Context loads", &context_loads_ctr);
4490 register_counter ("Event: Context unloads", &context_unloads_ctr);
4491 register_counter ("Event: Sample binaries", &sample_ubins_ctr);
4492 register_counter ("Event: Sample symbols", &sample_usyms_ctr);
4493 register_counter ("Event: Sample hits", &sample_hits_ctr);
4494 register_counter ("Event: Counter descriptors", &counter_descriptors_ctr);
4495 register_counter ("Event: Counter samples", &counter_samples_ctr);
4496 register_counter ("Event: Performance counter descriptors", &perfcounter_descriptors_ctr);
4497 register_counter ("Event: Performance counter samples", &perfcounter_samples_ctr);
4498 register_counter ("Event: Coverage methods", &coverage_methods_ctr);
4499 register_counter ("Event: Coverage statements", &coverage_statements_ctr);
4500 register_counter ("Event: Coverage classes", &coverage_classes_ctr);
4501 register_counter ("Event: Coverage assemblies", &coverage_assemblies_ctr);
4503 counters_init (profiler);
4506 * We must start the helper thread before the writer thread. This is
4507 * because the helper thread sets up the command port which is written to
4508 * the log header by the writer thread.
4510 start_helper_thread (profiler);
4511 start_writer_thread (profiler);
4512 start_dumper_thread (profiler);
4516 create_profiler (const char *args, const char *filename, GPtrArray *filters)
4519 int force_delete = 0;
4521 log_profiler = (MonoProfiler *) g_calloc (1, sizeof (MonoProfiler));
4522 log_profiler->args = pstrdup (args);
4523 log_profiler->command_port = command_port;
4525 if (filename && *filename == '-') {
4528 g_warning ("WARNING: the output:-FILENAME option is deprecated, the profiler now always overrides the output file\n");
4531 //If filename begin with +, append the pid at the end
4532 if (filename && *filename == '+')
4533 filename = g_strdup_printf ("%s.%d", filename + 1, getpid ());
4538 filename = "|mprof-report -";
4540 filename = "output.mlpd";
4541 nf = (char*)filename;
4543 nf = new_filename (filename);
4545 int s = strlen (nf) + 32;
4546 char *p = (char *) g_malloc (s);
4547 snprintf (p, s, "|mprof-report '--out=%s' -", nf);
4553 log_profiler->file = popen (nf + 1, "w");
4554 log_profiler->pipe_output = 1;
4555 } else if (*nf == '#') {
4556 int fd = strtol (nf + 1, NULL, 10);
4557 log_profiler->file = fdopen (fd, "a");
4561 log_profiler->file = fopen (nf, "wb");
4563 if (!log_profiler->file) {
4564 fprintf (stderr, "Cannot create profiler output: %s\n", nf);
4568 #if defined (HAVE_SYS_ZLIB)
4570 log_profiler->gzfile = gzdopen (fileno (log_profiler->file), "wb");
4574 * If you hit this assert while increasing MAX_FRAMES, you need to increase
4575 * SAMPLE_BLOCK_SIZE as well.
4577 g_assert (SAMPLE_SLOT_SIZE (MAX_FRAMES) * 2 < LOCK_FREE_ALLOC_SB_USABLE_SIZE (SAMPLE_BLOCK_SIZE));
4579 // FIXME: We should free this stuff too.
4580 mono_lock_free_allocator_init_size_class (&log_profiler->sample_size_class, SAMPLE_SLOT_SIZE (num_frames), SAMPLE_BLOCK_SIZE);
4581 mono_lock_free_allocator_init_allocator (&log_profiler->sample_allocator, &log_profiler->sample_size_class, MONO_MEM_ACCOUNT_PROFILER);
4583 mono_lock_free_queue_init (&log_profiler->sample_reuse_queue);
4585 g_assert (sizeof (WriterQueueEntry) * 2 < LOCK_FREE_ALLOC_SB_USABLE_SIZE (WRITER_ENTRY_BLOCK_SIZE));
4587 // FIXME: We should free this stuff too.
4588 mono_lock_free_allocator_init_size_class (&log_profiler->writer_entry_size_class, sizeof (WriterQueueEntry), WRITER_ENTRY_BLOCK_SIZE);
4589 mono_lock_free_allocator_init_allocator (&log_profiler->writer_entry_allocator, &log_profiler->writer_entry_size_class, MONO_MEM_ACCOUNT_PROFILER);
4591 mono_lock_free_queue_init (&log_profiler->writer_queue);
4592 mono_os_sem_init (&log_profiler->writer_queue_sem, 0);
4594 mono_lock_free_queue_init (&log_profiler->dumper_queue);
4595 mono_os_sem_init (&log_profiler->dumper_queue_sem, 0);
4597 mono_os_mutex_init (&log_profiler->method_table_mutex);
4598 log_profiler->method_table = mono_conc_hashtable_new (NULL, NULL);
4601 coverage_init (log_profiler);
4602 log_profiler->coverage_filters = filters;
4604 log_profiler->startup_time = current_time ();
4608 * declaration to silence the compiler: this is the entry point that
4609 * mono will load from the shared library and call.
4612 mono_profiler_startup (const char *desc);
4615 mono_profiler_startup_log (const char *desc);
4618 * this is the entry point that will be used when the profiler
4619 * is embedded inside the main executable.
4622 mono_profiler_startup_log (const char *desc)
4624 mono_profiler_startup (desc);
4628 mono_profiler_startup (const char *desc)
4630 GPtrArray *filters = NULL;
4632 proflog_parse_args (&config, desc [3] == ':' ? desc + 4 : "");
4634 //XXX maybe later cleanup to use config directly
4635 nocalls = !(config.effective_mask & PROFLOG_CALL_EVENTS);
4636 no_counters = !(config.effective_mask & PROFLOG_COUNTER_EVENTS);
4637 do_report = config.do_report;
4638 do_debug = config.do_debug;
4639 do_heap_shot = (config.effective_mask & PROFLOG_HEAPSHOT_FEATURE);
4640 hs_mode_ondemand = config.hs_mode_ondemand;
4641 hs_mode_ms = config.hs_mode_ms;
4642 hs_mode_gc = config.hs_mode_gc;
4643 do_mono_sample = (config.effective_mask & PROFLOG_SAMPLING_FEATURE);
4644 use_zip = config.use_zip;
4645 command_port = config.command_port;
4646 num_frames = config.num_frames;
4647 notraces = config.notraces;
4648 max_allocated_sample_hits = config.max_allocated_sample_hits;
4649 max_call_depth = config.max_call_depth;
4650 do_coverage = (config.effective_mask & PROFLOG_CODE_COV_FEATURE);
4651 debug_coverage = config.debug_coverage;
4652 only_coverage = config.only_coverage;
4654 if (config.cov_filter_files) {
4655 filters = g_ptr_array_new ();
4657 for (i = 0; i < config.cov_filter_files->len; ++i) {
4658 const char *name = config.cov_filter_files->pdata [i];
4659 parse_cov_filter_file (filters, name);
4667 create_profiler (desc, config.output_filename, filters);
4669 mono_lls_init (&profiler_thread_list, NULL);
4671 //This two events are required for the profiler to work
4672 int events = MONO_PROFILE_THREADS | MONO_PROFILE_GC;
4674 //Required callbacks
4675 mono_profiler_install (log_profiler, log_shutdown);
4676 mono_profiler_install_runtime_initialized (runtime_initialized);
4678 mono_profiler_install_gc (gc_event, gc_resize);
4679 mono_profiler_install_thread (thread_start, thread_end);
4681 //It's questionable whether we actually want this to be mandatory, maybe put it behind the actual event?
4682 mono_profiler_install_thread_name (thread_name);
4685 if (config.effective_mask & PROFLOG_DOMAIN_EVENTS) {
4686 events |= MONO_PROFILE_APPDOMAIN_EVENTS;
4687 mono_profiler_install_appdomain (NULL, domain_loaded, domain_unloaded, NULL);
4688 mono_profiler_install_appdomain_name (domain_name);
4691 if (config.effective_mask & PROFLOG_ASSEMBLY_EVENTS) {
4692 events |= MONO_PROFILE_ASSEMBLY_EVENTS;
4693 mono_profiler_install_assembly (NULL, assembly_loaded, assembly_unloaded, NULL);
4696 if (config.effective_mask & PROFLOG_MODULE_EVENTS) {
4697 events |= MONO_PROFILE_MODULE_EVENTS;
4698 mono_profiler_install_module (NULL, image_loaded, image_unloaded, NULL);
4701 if (config.effective_mask & PROFLOG_CLASS_EVENTS) {
4702 events |= MONO_PROFILE_CLASS_EVENTS;
4703 mono_profiler_install_class (NULL, class_loaded, class_unloaded, NULL);
4706 if (config.effective_mask & PROFLOG_JIT_COMPILATION_EVENTS) {
4707 events |= MONO_PROFILE_JIT_COMPILATION;
4708 mono_profiler_install_jit_end (method_jitted);
4709 mono_profiler_install_code_buffer_new (code_buffer_new);
4712 if (config.effective_mask & PROFLOG_EXCEPTION_EVENTS) {
4713 events |= MONO_PROFILE_EXCEPTIONS;
4714 mono_profiler_install_exception (throw_exc, method_exc_leave, NULL);
4715 mono_profiler_install_exception_clause (clause_exc);
4718 if (config.effective_mask & PROFLOG_ALLOCATION_EVENTS) {
4719 events |= MONO_PROFILE_ALLOCATIONS;
4720 mono_profiler_install_allocation (gc_alloc);
4723 //PROFLOG_GC_EVENTS is mandatory
4724 //PROFLOG_THREAD_EVENTS is mandatory
4726 if (config.effective_mask & PROFLOG_CALL_EVENTS) {
4727 events |= MONO_PROFILE_ENTER_LEAVE;
4728 mono_profiler_install_enter_leave (method_enter, method_leave);
4731 if (config.effective_mask & PROFLOG_INS_COVERAGE_EVENTS) {
4732 events |= MONO_PROFILE_INS_COVERAGE;
4733 mono_profiler_install_coverage_filter (coverage_filter);
4736 //XXX should we check for PROFLOG_SAMPLING_FEATURE instead??
4737 if (config.effective_mask & PROFLOG_SAMPLING_EVENTS) {
4738 events |= MONO_PROFILE_STATISTICAL;
4739 mono_profiler_set_statistical_mode (config.sampling_mode, config.sample_freq);
4740 mono_profiler_install_statistical (mono_sample_hit);
4743 if (config.effective_mask & PROFLOG_MONITOR_EVENTS) {
4744 events |= MONO_PROFILE_MONITOR_EVENTS;
4745 mono_profiler_install_monitor (monitor_event);
4748 if (config.effective_mask & PROFLOG_GC_MOVES_EVENTS) {
4749 events |= MONO_PROFILE_GC_MOVES;
4750 mono_profiler_install_gc_moves (gc_moves);
4753 // TODO split those in two profiler events
4754 if (config.effective_mask & (PROFLOG_GC_ROOT_EVENTS | PROFLOG_GC_HANDLE_EVENTS)) {
4755 events |= MONO_PROFILE_GC_ROOTS;
4756 mono_profiler_install_gc_roots (
4757 config.effective_mask & (PROFLOG_GC_HANDLE_EVENTS) ? gc_handle : NULL,
4758 (config.effective_mask & PROFLOG_GC_ROOT_EVENTS) ? gc_roots : NULL);
4761 if (config.effective_mask & PROFLOG_CONTEXT_EVENTS) {
4762 events |= MONO_PROFILE_CONTEXT_EVENTS;
4763 mono_profiler_install_context (context_loaded, context_unloaded);
4766 if (config.effective_mask & PROFLOG_FINALIZATION_EVENTS) {
4767 events |= MONO_PROFILE_GC_FINALIZATION;
4768 mono_profiler_install_gc_finalize (finalize_begin, finalize_object_begin, finalize_object_end, finalize_end);
4769 } else if (ENABLED (PROFLOG_HEAPSHOT_FEATURE) && config.hs_mode_ondemand) {
4770 //On Demand heapshot uses the finalizer thread to force a collection and thus a heapshot
4771 events |= MONO_PROFILE_GC_FINALIZATION;
4772 mono_profiler_install_gc_finalize (NULL, NULL, NULL, finalize_end);
4775 //PROFLOG_COUNTER_EVENTS is a pseudo event controled by the no_counters global var
4776 //PROFLOG_GC_HANDLE_EVENTS is handled together with PROFLOG_GC_ROOT_EVENTS
4778 mono_profiler_set_events ((MonoProfileFlags)events);