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,
124 monitor_contentions_ctr,
125 monitor_acquisitions_ctr,
126 monitor_failures_ctr,
138 counter_descriptors_ctr,
140 perfcounter_descriptors_ctr,
141 perfcounter_samples_ctr,
142 coverage_methods_ctr,
143 coverage_statements_ctr,
144 coverage_classes_ctr,
145 coverage_assemblies_ctr;
147 static MonoLinkedListSet profiler_thread_list;
153 * The file is composed by a header followed by 0 or more buffers.
154 * Each buffer contains events that happened on a thread: for a given thread
155 * buffers that appear later in the file are guaranteed to contain events
156 * that happened later in time. Buffers from separate threads could be interleaved,
158 * Buffers are not required to be aligned.
161 * [id: 4 bytes] constant value: LOG_HEADER_ID
162 * [major: 1 byte] [minor: 1 byte] major and minor version of the log profiler
163 * [format: 1 byte] version of the data format for the rest of the file
164 * [ptrsize: 1 byte] size in bytes of a pointer in the profiled program
165 * [startup time: 8 bytes] time in milliseconds since the unix epoch when the program started
166 * [timer overhead: 4 bytes] approximate overhead in nanoseconds of the timer
167 * [flags: 4 bytes] file format flags, should be 0 for now
168 * [pid: 4 bytes] pid of the profiled process
169 * [port: 2 bytes] tcp port for server if != 0
170 * [args size: 4 bytes] size of args
171 * [args: string] arguments passed to the profiler
172 * [arch size: 4 bytes] size of arch
173 * [arch: string] architecture the profiler is running on
174 * [os size: 4 bytes] size of os
175 * [os: string] operating system the profiler is running on
177 * The multiple byte integers are in little-endian format.
180 * [buffer header] [event]*
181 * Buffers have a fixed-size header followed by 0 or more bytes of event data.
182 * Timing information and other values in the event data are usually stored
183 * as uleb128 or sleb128 integers. To save space, as noted for each item below,
184 * some data is represented as a difference between the actual value and
185 * either the last value of the same type (like for timing information) or
186 * as the difference from a value stored in a buffer header.
188 * For timing information the data is stored as uleb128, since timing
189 * increases in a monotonic way in each thread: the value is the number of
190 * nanoseconds to add to the last seen timing data in a buffer. The first value
191 * in a buffer will be calculated from the time_base field in the buffer head.
193 * Object or heap sizes are stored as uleb128.
194 * Pointer differences are stored as sleb128, instead.
196 * If an unexpected value is found, the rest of the buffer should be ignored,
197 * as generally the later values need the former to be interpreted correctly.
199 * buffer header format:
200 * [bufid: 4 bytes] constant value: BUF_ID
201 * [len: 4 bytes] size of the data following the buffer header
202 * [time_base: 8 bytes] time base in nanoseconds since an unspecified epoch
203 * [ptr_base: 8 bytes] base value for pointers
204 * [obj_base: 8 bytes] base value for object addresses
205 * [thread id: 8 bytes] system-specific thread ID (pthread_t for example)
206 * [method_base: 8 bytes] base value for MonoMethod pointers
209 * [extended info: upper 4 bits] [type: lower 4 bits]
210 * [time diff: uleb128] nanoseconds since last timing
212 * The data that follows depends on type and the extended info.
213 * Type is one of the enum values in mono-profiler-log.h: TYPE_ALLOC, TYPE_GC,
214 * TYPE_METADATA, TYPE_METHOD, TYPE_EXCEPTION, TYPE_MONITOR, TYPE_HEAP.
215 * The extended info bits are interpreted based on type, see
216 * each individual event description below.
217 * strings are represented as a 0-terminated utf8 sequence.
220 * [num: uleb128] number of frames following
221 * [frame: sleb128]* mum MonoMethod* as a pointer difference from the last such
222 * pointer or the buffer method_base
226 * exinfo: flags: TYPE_ALLOC_BT
227 * [ptr: sleb128] class as a byte difference from ptr_base
228 * [obj: sleb128] object address as a byte difference from obj_base
229 * [size: uleb128] size of the object in the heap
230 * If the TYPE_ALLOC_BT flag is set, a backtrace follows.
234 * exinfo: one of TYPE_GC_EVENT, TYPE_GC_RESIZE, TYPE_GC_MOVE, TYPE_GC_HANDLE_CREATED[_BT],
235 * TYPE_GC_HANDLE_DESTROYED[_BT], TYPE_GC_FINALIZE_START, TYPE_GC_FINALIZE_END,
236 * TYPE_GC_FINALIZE_OBJECT_START, TYPE_GC_FINALIZE_OBJECT_END
237 * if exinfo == TYPE_GC_RESIZE
238 * [heap_size: uleb128] new heap size
239 * if exinfo == TYPE_GC_EVENT
240 * [event type: byte] GC event (MONO_GC_EVENT_* from profiler.h)
241 * [generation: byte] GC generation event refers to
242 * if exinfo == TYPE_GC_MOVE
243 * [num_objects: uleb128] number of object moves that follow
244 * [objaddr: sleb128]+ num_objects object pointer differences from obj_base
245 * num is always an even number: the even items are the old
246 * addresses, the odd numbers are the respective new object addresses
247 * if exinfo == TYPE_GC_HANDLE_CREATED[_BT]
248 * [handle_type: uleb128] GC handle type (System.Runtime.InteropServices.GCHandleType)
249 * upper bits reserved as flags
250 * [handle: uleb128] GC handle value
251 * [objaddr: sleb128] object pointer differences from obj_base
252 * If exinfo == TYPE_GC_HANDLE_CREATED_BT, a backtrace follows.
253 * if exinfo == TYPE_GC_HANDLE_DESTROYED[_BT]
254 * [handle_type: uleb128] GC handle type (System.Runtime.InteropServices.GCHandleType)
255 * upper bits reserved as flags
256 * [handle: uleb128] GC handle value
257 * If exinfo == TYPE_GC_HANDLE_DESTROYED_BT, a backtrace follows.
258 * if exinfo == TYPE_GC_FINALIZE_OBJECT_{START,END}
259 * [object: sleb128] the object as a difference from obj_base
261 * type metadata format:
262 * type: TYPE_METADATA
263 * exinfo: one of: TYPE_END_LOAD, TYPE_END_UNLOAD (optional for TYPE_THREAD and TYPE_DOMAIN)
264 * [mtype: byte] metadata type, one of: TYPE_CLASS, TYPE_IMAGE, TYPE_ASSEMBLY, TYPE_DOMAIN,
265 * TYPE_THREAD, TYPE_CONTEXT
266 * [pointer: sleb128] pointer of the metadata type depending on mtype
267 * if mtype == TYPE_CLASS
268 * [image: sleb128] MonoImage* as a pointer difference from ptr_base
269 * [name: string] full class name
270 * if mtype == TYPE_IMAGE
271 * [name: string] image file name
272 * if mtype == TYPE_ASSEMBLY
273 * [name: string] assembly name
274 * if mtype == TYPE_DOMAIN && exinfo == 0
275 * [name: string] domain friendly name
276 * if mtype == TYPE_CONTEXT
277 * [domain: sleb128] domain id as pointer
278 * if mtype == TYPE_THREAD && exinfo == 0
279 * [name: string] thread name
281 * type method format:
283 * exinfo: one of: TYPE_LEAVE, TYPE_ENTER, TYPE_EXC_LEAVE, TYPE_JIT
284 * [method: sleb128] MonoMethod* as a pointer difference from the last such
285 * pointer or the buffer method_base
286 * if exinfo == TYPE_JIT
287 * [code address: sleb128] pointer to the native code as a diff from ptr_base
288 * [code size: uleb128] size of the generated code
289 * [name: string] full method name
291 * type exception format:
292 * type: TYPE_EXCEPTION
293 * exinfo: TYPE_THROW_BT flag or one of: TYPE_CLAUSE
294 * if exinfo == TYPE_CLAUSE
295 * [clause type: byte] MonoExceptionEnum enum value
296 * [clause index: uleb128] index of the current clause
297 * [method: sleb128] MonoMethod* as a pointer difference from the last such
298 * pointer or the buffer method_base
300 * [object: sleb128] the exception object as a difference from obj_base
301 * if exinfo has TYPE_THROW_BT set, 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: TYPE_MONITOR_BT flag and one of: MONO_PROFILER_MONITOR_(CONTENTION|FAIL|DONE)
316 * [object: sleb128] the lock object as a difference from obj_base
317 * if exinfo.low3bits == MONO_PROFILER_MONITOR_CONTENTION
318 * If the TYPE_MONITOR_BT flag is set, 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
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: uleb128] 0 -> value is null
383 * [1: uleb128] 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 take
562 * care of a bunch of stuff that can be repetitive and error-prone, such as
563 * acquiring/releasing the buffer lock, incrementing the event counter,
564 * expanding the log buffer, processing requests, etc. They also create a scope
565 * so that it's harder to leak the LogBuffer pointer, which can be problematic
566 * as the pointer is unstable when the buffer lock isn't acquired.
569 #define ENTER_LOG(COUNTER, BUFFER, SIZE) \
571 MonoProfilerThread *thread__ = PROF_TLS_GET (); \
572 if (thread__->attached) \
574 g_assert (!thread__->busy && "Why are we trying to write a new event while already writing one?"); \
575 thread__->busy = TRUE; \
576 InterlockedIncrement ((COUNTER)); \
577 LogBuffer *BUFFER = ensure_logbuf_unsafe (thread__, (SIZE))
579 #define EXIT_LOG_EXPLICIT(SEND) \
580 thread__->busy = FALSE; \
582 send_log_unsafe (TRUE); \
583 if (thread__->attached) \
587 // Pass these to EXIT_LOG_EXPLICIT () for easier reading.
589 #define NO_SEND FALSE
591 #define EXIT_LOG EXIT_LOG_EXPLICIT (DO_SEND)
593 static volatile gint32 buffer_rwlock_count;
594 static volatile gpointer buffer_rwlock_exclusive;
596 // Can be used recursively.
601 * If the thread holding the exclusive lock tries to modify the
602 * reader count, just make it a no-op. This way, we also avoid
603 * invoking the GC safe point macros below, which could break if
604 * done from a thread that is currently the initiator of STW.
606 * In other words, we rely on the fact that the GC thread takes
607 * the exclusive lock in the gc_event () callback when the world
610 if (InterlockedReadPointer (&buffer_rwlock_exclusive) != (gpointer) thread_id ()) {
613 while (InterlockedReadPointer (&buffer_rwlock_exclusive))
614 mono_thread_info_yield ();
616 InterlockedIncrement (&buffer_rwlock_count);
621 mono_memory_barrier ();
627 mono_memory_barrier ();
629 // See the comment in buffer_lock ().
630 if (InterlockedReadPointer (&buffer_rwlock_exclusive) == (gpointer) thread_id ())
633 g_assert (InterlockedRead (&buffer_rwlock_count) && "Why are we trying to decrement a zero reader count?");
635 InterlockedDecrement (&buffer_rwlock_count);
638 // Cannot be used recursively.
640 buffer_lock_excl (void)
642 gpointer tid = (gpointer) thread_id ();
644 g_assert (InterlockedReadPointer (&buffer_rwlock_exclusive) != tid && "Why are we taking the exclusive lock twice?");
648 while (InterlockedCompareExchangePointer (&buffer_rwlock_exclusive, tid, 0))
649 mono_thread_info_yield ();
651 while (InterlockedRead (&buffer_rwlock_count))
652 mono_thread_info_yield ();
656 mono_memory_barrier ();
660 buffer_unlock_excl (void)
662 mono_memory_barrier ();
664 g_assert (InterlockedReadPointer (&buffer_rwlock_exclusive) && "Why is the exclusive lock not held?");
665 g_assert (InterlockedReadPointer (&buffer_rwlock_exclusive) == (gpointer) thread_id () && "Why does another thread hold the exclusive lock?");
666 g_assert (!InterlockedRead (&buffer_rwlock_count) && "Why are there readers when the exclusive lock is held?");
668 InterlockedWritePointer (&buffer_rwlock_exclusive, NULL);
671 typedef struct _BinaryObject BinaryObject;
672 struct _BinaryObject {
678 struct _MonoProfiler {
680 #if defined (HAVE_SYS_ZLIB)
684 uint64_t startup_time;
689 MonoNativeThreadId helper_thread;
690 MonoNativeThreadId writer_thread;
691 MonoNativeThreadId dumper_thread;
692 volatile gint32 run_writer_thread;
693 MonoLockFreeAllocSizeClass writer_entry_size_class;
694 MonoLockFreeAllocator writer_entry_allocator;
695 MonoLockFreeQueue writer_queue;
696 MonoSemType writer_queue_sem;
697 MonoConcurrentHashTable *method_table;
698 mono_mutex_t method_table_mutex;
699 volatile gint32 run_dumper_thread;
700 MonoLockFreeQueue dumper_queue;
701 MonoSemType dumper_queue_sem;
702 MonoLockFreeAllocSizeClass sample_size_class;
703 MonoLockFreeAllocator sample_allocator;
704 MonoLockFreeQueue sample_reuse_queue;
705 BinaryObject *binary_objects;
706 GPtrArray *coverage_filters;
710 MonoLockFreeQueueNode node;
715 #define WRITER_ENTRY_BLOCK_SIZE (mono_pagesize ())
725 #define PROF_TLS_SET(VAL) (TlsSetValue (profiler_tls, (VAL)))
726 #define PROF_TLS_GET() ((MonoProfilerThread *) TlsGetValue (profiler_tls))
727 #define PROF_TLS_INIT() (profiler_tls = TlsAlloc ())
728 #define PROF_TLS_FREE() (TlsFree (profiler_tls))
730 static DWORD profiler_tls;
734 #define PROF_TLS_SET(VAL) (profiler_tls = (VAL))
735 #define PROF_TLS_GET() (profiler_tls)
736 #define PROF_TLS_INIT()
737 #define PROF_TLS_FREE()
739 static __thread MonoProfilerThread *profiler_tls;
743 #define PROF_TLS_SET(VAL) (pthread_setspecific (profiler_tls, (VAL)))
744 #define PROF_TLS_GET() ((MonoProfilerThread *) pthread_getspecific (profiler_tls))
745 #define PROF_TLS_INIT() (pthread_key_create (&profiler_tls, NULL))
746 #define PROF_TLS_FREE() (pthread_key_delete (profiler_tls))
748 static pthread_key_t profiler_tls;
753 pstrdup (const char *s)
755 int len = strlen (s) + 1;
756 char *p = (char *) g_malloc (len);
762 alloc_buffer (int size)
764 return mono_valloc (NULL, size, MONO_MMAP_READ | MONO_MMAP_WRITE | MONO_MMAP_ANON | MONO_MMAP_PRIVATE, MONO_MEM_ACCOUNT_PROFILER);
768 free_buffer (void *buf, int size)
770 mono_vfree (buf, size, MONO_MEM_ACCOUNT_PROFILER);
774 create_buffer (uintptr_t tid)
776 LogBuffer* buf = (LogBuffer *) alloc_buffer (BUFFER_SIZE);
778 InterlockedIncrement (&buffer_allocations_ctr);
780 buf->size = BUFFER_SIZE;
781 buf->time_base = current_time ();
782 buf->last_time = buf->time_base;
783 buf->buf_end = (unsigned char *) buf + buf->size;
784 buf->cursor = buf->buf;
785 buf->thread_id = tid;
791 * Must be called with the reader lock held if thread is the current thread, or
792 * the exclusive lock if thread is a different thread. However, if thread is
793 * the current thread, and init_thread () was called with add_to_lls = FALSE,
794 * then no locking is necessary.
797 init_buffer_state (MonoProfilerThread *thread)
799 thread->buffer = create_buffer (thread->node.key);
800 thread->methods = NULL;
804 clear_hazard_pointers (MonoThreadHazardPointers *hp)
806 mono_hazard_pointer_clear (hp, 0);
807 mono_hazard_pointer_clear (hp, 1);
808 mono_hazard_pointer_clear (hp, 2);
811 static MonoProfilerThread *
812 init_thread (MonoProfiler *prof, gboolean add_to_lls)
814 MonoProfilerThread *thread = PROF_TLS_GET ();
817 * Sometimes we may try to initialize a thread twice. One example is the
818 * main thread: We initialize it when setting up the profiler, but we will
819 * also get a thread_start () callback for it. Another example is when
820 * attaching new threads to the runtime: We may get a gc_alloc () callback
821 * for that thread's thread object (where we initialize it), soon followed
822 * by a thread_start () callback.
824 * These cases are harmless anyhow. Just return if we've already done the
825 * initialization work.
830 thread = g_malloc (sizeof (MonoProfilerThread));
831 thread->node.key = thread_id ();
832 thread->profiler = prof;
833 thread->attached = add_to_lls;
834 thread->call_depth = 0;
836 thread->ended = FALSE;
838 init_buffer_state (thread);
841 * Some internal profiler threads don't need to be cleaned up
842 * by the main thread on shutdown.
845 MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
846 g_assert (mono_lls_insert (&profiler_thread_list, hp, &thread->node) && "Why can't we insert the thread in the LLS?");
847 clear_hazard_pointers (hp);
850 PROF_TLS_SET (thread);
855 // Only valid if init_thread () was called with add_to_lls = FALSE.
857 deinit_thread (MonoProfilerThread *thread)
859 g_assert (!thread->attached && "Why are we manually freeing an attached thread?");
865 // Only valid if init_thread () was called with add_to_lls = FALSE.
867 ensure_logbuf_unsafe (MonoProfilerThread *thread, int bytes)
869 LogBuffer *old = thread->buffer;
871 if (old && old->cursor + bytes + 100 < old->buf_end)
874 LogBuffer *new_ = create_buffer (thread->node.key);
876 thread->buffer = new_;
882 encode_uleb128 (uint64_t value, uint8_t *buf, uint8_t **endbuf)
887 uint8_t b = value & 0x7f;
890 if (value != 0) /* more bytes to come */
900 encode_sleb128 (intptr_t value, uint8_t *buf, uint8_t **endbuf)
903 int negative = (value < 0);
904 unsigned int size = sizeof (intptr_t) * 8;
912 /* the following is unnecessary if the
913 * implementation of >>= uses an arithmetic rather
914 * than logical shift for a signed left operand
918 value |= - ((intptr_t) 1 <<(size - 7));
920 /* sign bit of byte is second high order bit (0x40) */
921 if ((value == 0 && !(byte & 0x40)) ||
922 (value == -1 && (byte & 0x40)))
934 emit_byte (LogBuffer *logbuffer, int value)
936 logbuffer->cursor [0] = value;
939 g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
943 emit_value (LogBuffer *logbuffer, int value)
945 encode_uleb128 (value, logbuffer->cursor, &logbuffer->cursor);
947 g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
951 emit_time (LogBuffer *logbuffer, uint64_t value)
953 uint64_t tdiff = value - logbuffer->last_time;
954 encode_uleb128 (tdiff, logbuffer->cursor, &logbuffer->cursor);
955 logbuffer->last_time = value;
957 g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
961 emit_event_time (LogBuffer *logbuffer, int event, uint64_t time)
963 emit_byte (logbuffer, event);
964 emit_time (logbuffer, time);
968 emit_event (LogBuffer *logbuffer, int event)
970 emit_event_time (logbuffer, event, current_time ());
974 emit_svalue (LogBuffer *logbuffer, int64_t value)
976 encode_sleb128 (value, logbuffer->cursor, &logbuffer->cursor);
978 g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
982 emit_uvalue (LogBuffer *logbuffer, uint64_t value)
984 encode_uleb128 (value, logbuffer->cursor, &logbuffer->cursor);
986 g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
990 emit_ptr (LogBuffer *logbuffer, void *ptr)
992 if (!logbuffer->ptr_base)
993 logbuffer->ptr_base = (uintptr_t) ptr;
995 emit_svalue (logbuffer, (intptr_t) ptr - logbuffer->ptr_base);
997 g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
1001 emit_method_inner (LogBuffer *logbuffer, void *method)
1003 if (!logbuffer->method_base) {
1004 logbuffer->method_base = (intptr_t) method;
1005 logbuffer->last_method = (intptr_t) method;
1008 encode_sleb128 ((intptr_t) ((char *) method - (char *) logbuffer->last_method), logbuffer->cursor, &logbuffer->cursor);
1009 logbuffer->last_method = (intptr_t) method;
1011 g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
1015 register_method_local (MonoMethod *method, MonoJitInfo *ji)
1017 MonoProfilerThread *thread = PROF_TLS_GET ();
1019 if (!mono_conc_hashtable_lookup (thread->profiler->method_table, method)) {
1020 MethodInfo *info = (MethodInfo *) g_malloc (sizeof (MethodInfo));
1022 info->method = method;
1024 info->time = current_time ();
1026 GPtrArray *arr = thread->methods ? thread->methods : (thread->methods = g_ptr_array_new ());
1027 g_ptr_array_add (arr, info);
1032 emit_method (LogBuffer *logbuffer, MonoMethod *method)
1034 register_method_local (method, NULL);
1035 emit_method_inner (logbuffer, method);
1039 emit_obj (LogBuffer *logbuffer, void *ptr)
1041 if (!logbuffer->obj_base)
1042 logbuffer->obj_base = (uintptr_t) ptr >> 3;
1044 emit_svalue (logbuffer, ((uintptr_t) ptr >> 3) - logbuffer->obj_base);
1046 g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
1050 emit_string (LogBuffer *logbuffer, const char *str, size_t size)
1054 for (; i < size; i++) {
1057 emit_byte (logbuffer, str [i]);
1060 emit_byte (logbuffer, '\0');
1064 emit_double (LogBuffer *logbuffer, double value)
1067 unsigned char buffer[8];
1068 memcpy (buffer, &value, 8);
1069 #if G_BYTE_ORDER == G_BIG_ENDIAN
1070 for (i = 7; i >= 0; i--)
1072 for (i = 0; i < 8; i++)
1074 emit_byte (logbuffer, buffer[i]);
1078 write_int16 (char *buf, int32_t value)
1081 for (i = 0; i < 2; ++i) {
1089 write_int32 (char *buf, int32_t value)
1092 for (i = 0; i < 4; ++i) {
1100 write_int64 (char *buf, int64_t value)
1103 for (i = 0; i < 8; ++i) {
1111 write_header_string (char *p, const char *str)
1113 size_t len = strlen (str) + 1;
1115 p = write_int32 (p, len);
1122 dump_header (MonoProfiler *profiler)
1124 const char *args = profiler->args;
1125 const char *arch = mono_config_get_cpu ();
1126 const char *os = mono_config_get_os ();
1128 char *hbuf = g_malloc (
1129 sizeof (gint32) /* header id */ +
1130 sizeof (gint8) /* major version */ +
1131 sizeof (gint8) /* minor version */ +
1132 sizeof (gint8) /* data version */ +
1133 sizeof (gint8) /* word size */ +
1134 sizeof (gint64) /* startup time */ +
1135 sizeof (gint32) /* timer overhead */ +
1136 sizeof (gint32) /* flags */ +
1137 sizeof (gint32) /* process id */ +
1138 sizeof (gint16) /* command port */ +
1139 sizeof (gint32) + strlen (args) + 1 /* arguments */ +
1140 sizeof (gint32) + strlen (arch) + 1 /* architecture */ +
1141 sizeof (gint32) + strlen (os) + 1 /* operating system */
1145 p = write_int32 (p, LOG_HEADER_ID);
1146 *p++ = LOG_VERSION_MAJOR;
1147 *p++ = LOG_VERSION_MINOR;
1148 *p++ = LOG_DATA_VERSION;
1149 *p++ = sizeof (void *);
1150 p = write_int64 (p, ((uint64_t) time (NULL)) * 1000);
1151 p = write_int32 (p, timer_overhead);
1152 p = write_int32 (p, 0); /* flags */
1153 p = write_int32 (p, process_id ());
1154 p = write_int16 (p, profiler->command_port);
1155 p = write_header_string (p, args);
1156 p = write_header_string (p, arch);
1157 p = write_header_string (p, os);
1159 #if defined (HAVE_SYS_ZLIB)
1160 if (profiler->gzfile) {
1161 gzwrite (profiler->gzfile, hbuf, p - hbuf);
1165 fwrite (hbuf, p - hbuf, 1, profiler->file);
1166 fflush (profiler->file);
1173 * Must be called with the reader lock held if thread is the current thread, or
1174 * the exclusive lock if thread is a different thread. However, if thread is
1175 * the current thread, and init_thread () was called with add_to_lls = FALSE,
1176 * then no locking is necessary.
1179 send_buffer (MonoProfilerThread *thread)
1181 WriterQueueEntry *entry = mono_lock_free_alloc (&thread->profiler->writer_entry_allocator);
1182 entry->methods = thread->methods;
1183 entry->buffer = thread->buffer;
1185 mono_lock_free_queue_node_init (&entry->node, FALSE);
1187 mono_lock_free_queue_enqueue (&thread->profiler->writer_queue, &entry->node);
1188 mono_os_sem_post (&thread->profiler->writer_queue_sem);
1192 free_thread (gpointer p)
1194 MonoProfilerThread *thread = p;
1196 if (!thread->ended) {
1198 * The thread is being cleaned up by the main thread during
1199 * shutdown. This typically happens for internal runtime
1200 * threads. We need to synthesize a thread end event.
1203 InterlockedIncrement (&thread_ends_ctr);
1205 if (ENABLED (PROFLOG_THREAD_EVENTS)) {
1206 LogBuffer *buf = ensure_logbuf_unsafe (thread,
1207 EVENT_SIZE /* event */ +
1208 BYTE_SIZE /* type */ +
1209 LEB128_SIZE /* tid */
1212 emit_event (buf, TYPE_END_UNLOAD | TYPE_METADATA);
1213 emit_byte (buf, TYPE_THREAD);
1214 emit_ptr (buf, (void *) thread->node.key);
1218 send_buffer (thread);
1224 remove_thread (MonoProfilerThread *thread)
1226 MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
1228 if (mono_lls_remove (&profiler_thread_list, hp, &thread->node))
1229 mono_thread_hazardous_try_free (thread, free_thread);
1231 clear_hazard_pointers (hp);
1235 dump_buffer (MonoProfiler *profiler, LogBuffer *buf)
1241 dump_buffer (profiler, buf->next);
1243 if (buf->cursor - buf->buf) {
1244 p = write_int32 (p, BUF_ID);
1245 p = write_int32 (p, buf->cursor - buf->buf);
1246 p = write_int64 (p, buf->time_base);
1247 p = write_int64 (p, buf->ptr_base);
1248 p = write_int64 (p, buf->obj_base);
1249 p = write_int64 (p, buf->thread_id);
1250 p = write_int64 (p, buf->method_base);
1252 #if defined (HAVE_SYS_ZLIB)
1253 if (profiler->gzfile) {
1254 gzwrite (profiler->gzfile, hbuf, p - hbuf);
1255 gzwrite (profiler->gzfile, buf->buf, buf->cursor - buf->buf);
1259 fwrite (hbuf, p - hbuf, 1, profiler->file);
1260 fwrite (buf->buf, buf->cursor - buf->buf, 1, profiler->file);
1261 fflush (profiler->file);
1265 free_buffer (buf, buf->size);
1269 dump_buffer_threadless (MonoProfiler *profiler, LogBuffer *buf)
1271 for (LogBuffer *iter = buf; iter; iter = iter->next)
1272 iter->thread_id = 0;
1274 dump_buffer (profiler, buf);
1277 // Only valid if init_thread () was called with add_to_lls = FALSE.
1279 send_log_unsafe (gboolean if_needed)
1281 MonoProfilerThread *thread = PROF_TLS_GET ();
1283 if (!if_needed || (if_needed && thread->buffer->next)) {
1284 if (!thread->attached)
1285 for (LogBuffer *iter = thread->buffer; iter; iter = iter->next)
1286 iter->thread_id = 0;
1288 send_buffer (thread);
1289 init_buffer_state (thread);
1293 // Assumes that the exclusive lock is held.
1295 sync_point_flush (void)
1297 g_assert (InterlockedReadPointer (&buffer_rwlock_exclusive) == (gpointer) thread_id () && "Why don't we hold the exclusive lock?");
1299 MONO_LLS_FOREACH_SAFE (&profiler_thread_list, MonoProfilerThread, thread) {
1300 g_assert (thread->attached && "Why is a thread in the LLS not attached?");
1302 send_buffer (thread);
1303 init_buffer_state (thread);
1304 } MONO_LLS_FOREACH_SAFE_END
1307 // Assumes that the exclusive lock is held.
1309 sync_point_mark (MonoProfilerSyncPointType type)
1311 g_assert (InterlockedReadPointer (&buffer_rwlock_exclusive) == (gpointer) thread_id () && "Why don't we hold the exclusive lock?");
1313 ENTER_LOG (&sync_points_ctr, logbuffer,
1314 EVENT_SIZE /* event */ +
1315 LEB128_SIZE /* type */
1318 emit_event (logbuffer, TYPE_META | TYPE_SYNC_POINT);
1319 emit_byte (logbuffer, type);
1321 EXIT_LOG_EXPLICIT (NO_SEND);
1323 send_log_unsafe (FALSE);
1326 // Assumes that the exclusive lock is held.
1328 sync_point (MonoProfilerSyncPointType type)
1330 sync_point_flush ();
1331 sync_point_mark (type);
1335 gc_reference (MonoObject *obj, MonoClass *klass, uintptr_t size, uintptr_t num, MonoObject **refs, uintptr_t *offsets, void *data)
1337 /* account for object alignment in the heap */
1341 ENTER_LOG (&heap_objects_ctr, logbuffer,
1342 EVENT_SIZE /* event */ +
1343 LEB128_SIZE /* obj */ +
1344 LEB128_SIZE /* klass */ +
1345 LEB128_SIZE /* size */ +
1346 LEB128_SIZE /* num */ +
1348 LEB128_SIZE /* offset */ +
1349 LEB128_SIZE /* ref */
1353 emit_event (logbuffer, TYPE_HEAP_OBJECT | TYPE_HEAP);
1354 emit_obj (logbuffer, obj);
1355 emit_ptr (logbuffer, klass);
1356 emit_value (logbuffer, size);
1357 emit_value (logbuffer, num);
1359 uintptr_t last_offset = 0;
1361 for (int i = 0; i < num; ++i) {
1362 emit_value (logbuffer, offsets [i] - last_offset);
1363 last_offset = offsets [i];
1364 emit_obj (logbuffer, refs [i]);
1367 EXIT_LOG_EXPLICIT (DO_SEND);
1372 static unsigned int hs_mode_ms = 0;
1373 static unsigned int hs_mode_gc = 0;
1374 static unsigned int hs_mode_ondemand = 0;
1375 static unsigned int gc_count = 0;
1376 static uint64_t last_hs_time = 0;
1377 static gboolean do_heap_walk = FALSE;
1378 static gboolean ignore_heap_events;
1381 heap_walk (MonoProfiler *profiler)
1383 ENTER_LOG (&heap_starts_ctr, logbuffer,
1384 EVENT_SIZE /* event */
1387 emit_event (logbuffer, TYPE_HEAP_START | TYPE_HEAP);
1389 EXIT_LOG_EXPLICIT (DO_SEND);
1391 mono_gc_walk_heap (0, gc_reference, NULL);
1393 ENTER_LOG (&heap_ends_ctr, logbuffer,
1394 EVENT_SIZE /* event */
1397 emit_event (logbuffer, TYPE_HEAP_END | TYPE_HEAP);
1399 EXIT_LOG_EXPLICIT (DO_SEND);
1403 gc_roots (MonoProfiler *prof, int num, void **objects, int *root_types, uintptr_t *extra_info)
1405 if (ignore_heap_events)
1408 ENTER_LOG (&heap_roots_ctr, logbuffer,
1409 EVENT_SIZE /* event */ +
1410 LEB128_SIZE /* num */ +
1411 LEB128_SIZE /* collections */ +
1413 LEB128_SIZE /* object */ +
1414 LEB128_SIZE /* root type */ +
1415 LEB128_SIZE /* extra info */
1419 emit_event (logbuffer, TYPE_HEAP_ROOT | TYPE_HEAP);
1420 emit_value (logbuffer, num);
1421 emit_value (logbuffer, mono_gc_collection_count (mono_gc_max_generation ()));
1423 for (int i = 0; i < num; ++i) {
1424 emit_obj (logbuffer, objects [i]);
1425 emit_byte (logbuffer, root_types [i]);
1426 emit_value (logbuffer, extra_info [i]);
1429 EXIT_LOG_EXPLICIT (DO_SEND);
1434 trigger_on_demand_heapshot (void)
1436 if (heapshot_requested)
1437 mono_gc_collect (mono_gc_max_generation ());
1441 gc_event (MonoProfiler *profiler, MonoGCEvent ev, int generation)
1443 if (ev == MONO_GC_EVENT_START) {
1444 uint64_t now = current_time ();
1446 if (hs_mode_ms && (now - last_hs_time) / 1000 * 1000 >= hs_mode_ms)
1447 do_heap_walk = TRUE;
1448 else if (hs_mode_gc && !(gc_count % hs_mode_gc))
1449 do_heap_walk = TRUE;
1450 else if (hs_mode_ondemand)
1451 do_heap_walk = heapshot_requested;
1452 else if (!hs_mode_ms && !hs_mode_gc && generation == mono_gc_max_generation ())
1453 do_heap_walk = TRUE;
1455 //If using heapshot, ignore events for collections we don't care
1456 if (ENABLED (PROFLOG_HEAPSHOT_FEATURE)) {
1457 // Ignore events generated during the collection itself (IE GC ROOTS)
1458 ignore_heap_events = !do_heap_walk;
1463 if (ENABLED (PROFLOG_GC_EVENTS)) {
1464 ENTER_LOG (&gc_events_ctr, logbuffer,
1465 EVENT_SIZE /* event */ +
1466 BYTE_SIZE /* gc event */ +
1467 BYTE_SIZE /* generation */
1470 emit_event (logbuffer, TYPE_GC_EVENT | TYPE_GC);
1471 emit_byte (logbuffer, ev);
1472 emit_byte (logbuffer, generation);
1474 EXIT_LOG_EXPLICIT (NO_SEND);
1479 case MONO_GC_EVENT_START:
1480 if (generation == mono_gc_max_generation ())
1484 case MONO_GC_EVENT_PRE_STOP_WORLD_LOCKED:
1486 * Ensure that no thread can be in the middle of writing to
1487 * a buffer when the world stops...
1489 buffer_lock_excl ();
1491 case MONO_GC_EVENT_POST_STOP_WORLD:
1493 * ... So that we now have a consistent view of all buffers.
1494 * This allows us to flush them. We need to do this because
1495 * they may contain object allocation events that need to be
1496 * committed to the log file before any object move events
1497 * that will be produced during this GC.
1499 if (ENABLED (PROFLOG_ALLOCATION_EVENTS))
1500 sync_point (SYNC_POINT_WORLD_STOP);
1502 case MONO_GC_EVENT_PRE_START_WORLD:
1503 if (do_heap_shot && do_heap_walk) {
1504 heap_walk (profiler);
1506 do_heap_walk = FALSE;
1507 heapshot_requested = 0;
1508 last_hs_time = current_time ();
1511 case MONO_GC_EVENT_POST_START_WORLD_UNLOCKED:
1513 * Similarly, we must now make sure that any object moves
1514 * written to the GC thread's buffer are flushed. Otherwise,
1515 * object allocation events for certain addresses could come
1516 * after the move events that made those addresses available.
1518 if (ENABLED (PROFLOG_GC_EVENTS | PROFLOG_GC_MOVES_EVENTS))
1519 sync_point_mark (SYNC_POINT_WORLD_START);
1522 * Finally, it is safe to allow other threads to write to
1523 * their buffers again.
1525 buffer_unlock_excl ();
1533 gc_resize (MonoProfiler *profiler, int64_t new_size)
1535 ENTER_LOG (&gc_resizes_ctr, logbuffer,
1536 EVENT_SIZE /* event */ +
1537 LEB128_SIZE /* new size */
1540 emit_event (logbuffer, TYPE_GC_RESIZE | TYPE_GC);
1541 emit_value (logbuffer, new_size);
1543 EXIT_LOG_EXPLICIT (DO_SEND);
1548 MonoMethod* methods [MAX_FRAMES];
1549 int32_t il_offsets [MAX_FRAMES];
1550 int32_t native_offsets [MAX_FRAMES];
1553 static int num_frames = MAX_FRAMES;
1556 walk_stack (MonoMethod *method, int32_t native_offset, int32_t il_offset, mono_bool managed, void* data)
1558 FrameData *frame = (FrameData *)data;
1559 if (method && frame->count < num_frames) {
1560 frame->il_offsets [frame->count] = il_offset;
1561 frame->native_offsets [frame->count] = native_offset;
1562 frame->methods [frame->count++] = method;
1563 //printf ("In %d %s at %d (native: %d)\n", frame->count, mono_method_get_name (method), il_offset, native_offset);
1565 return frame->count == num_frames;
1569 * a note about stack walks: they can cause more profiler events to fire,
1570 * so we need to make sure they don't happen after we started emitting an
1571 * event, hence the collect_bt/emit_bt split.
1574 collect_bt (FrameData *data)
1577 mono_stack_walk_no_il (walk_stack, data);
1581 emit_bt (MonoProfiler *prof, LogBuffer *logbuffer, FrameData *data)
1583 /* FIXME: this is actually tons of data and we should
1584 * just output it the first time and use an id the next
1586 if (data->count > num_frames)
1587 printf ("bad num frames: %d\n", data->count);
1588 emit_value (logbuffer, data->count);
1589 //if (*p != data.count) {
1590 // printf ("bad num frames enc at %d: %d -> %d\n", count, data.count, *p); printf ("frames end: %p->%p\n", p, logbuffer->cursor); exit(0);}
1591 while (data->count) {
1592 emit_method (logbuffer, data->methods [--data->count]);
1597 gc_alloc (MonoProfiler *prof, MonoObject *obj, MonoClass *klass)
1599 init_thread (prof, TRUE);
1601 int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces) ? TYPE_ALLOC_BT : 0;
1603 uintptr_t len = mono_object_get_size (obj);
1604 /* account for object alignment in the heap */
1611 ENTER_LOG (&gc_allocs_ctr, logbuffer,
1612 EVENT_SIZE /* event */ +
1613 LEB128_SIZE /* klass */ +
1614 LEB128_SIZE /* obj */ +
1615 LEB128_SIZE /* size */ +
1617 LEB128_SIZE /* count */ +
1619 LEB128_SIZE /* method */
1624 emit_event (logbuffer, do_bt | TYPE_ALLOC);
1625 emit_ptr (logbuffer, klass);
1626 emit_obj (logbuffer, obj);
1627 emit_value (logbuffer, len);
1630 emit_bt (prof, logbuffer, &data);
1636 gc_moves (MonoProfiler *prof, void **objects, int num)
1638 ENTER_LOG (&gc_moves_ctr, logbuffer,
1639 EVENT_SIZE /* event */ +
1640 LEB128_SIZE /* num */ +
1642 LEB128_SIZE /* object */
1646 emit_event (logbuffer, TYPE_GC_MOVE | TYPE_GC);
1647 emit_value (logbuffer, num);
1649 for (int i = 0; i < num; ++i)
1650 emit_obj (logbuffer, objects [i]);
1652 EXIT_LOG_EXPLICIT (DO_SEND);
1656 gc_handle (MonoProfiler *prof, int op, int type, uintptr_t handle, MonoObject *obj)
1658 int do_bt = nocalls && InterlockedRead (&runtime_inited) && !notraces;
1664 gint32 *ctr = op == MONO_PROFILER_GC_HANDLE_CREATED ? &gc_handle_creations_ctr : &gc_handle_deletions_ctr;
1666 ENTER_LOG (ctr, logbuffer,
1667 EVENT_SIZE /* event */ +
1668 LEB128_SIZE /* type */ +
1669 LEB128_SIZE /* handle */ +
1670 (op == MONO_PROFILER_GC_HANDLE_CREATED ? (
1671 LEB128_SIZE /* obj */
1674 LEB128_SIZE /* count */ +
1676 LEB128_SIZE /* method */
1681 if (op == MONO_PROFILER_GC_HANDLE_CREATED)
1682 emit_event (logbuffer, (do_bt ? TYPE_GC_HANDLE_CREATED_BT : TYPE_GC_HANDLE_CREATED) | TYPE_GC);
1683 else if (op == MONO_PROFILER_GC_HANDLE_DESTROYED)
1684 emit_event (logbuffer, (do_bt ? TYPE_GC_HANDLE_DESTROYED_BT : TYPE_GC_HANDLE_DESTROYED) | TYPE_GC);
1686 g_assert_not_reached ();
1688 emit_value (logbuffer, type);
1689 emit_value (logbuffer, handle);
1691 if (op == MONO_PROFILER_GC_HANDLE_CREATED)
1692 emit_obj (logbuffer, obj);
1695 emit_bt (prof, logbuffer, &data);
1701 finalize_begin (MonoProfiler *prof)
1703 ENTER_LOG (&finalize_begins_ctr, buf,
1704 EVENT_SIZE /* event */
1707 emit_event (buf, TYPE_GC_FINALIZE_START | TYPE_GC);
1713 finalize_end (MonoProfiler *prof)
1715 trigger_on_demand_heapshot ();
1716 if (ENABLED (PROFLOG_FINALIZATION_EVENTS)) {
1717 ENTER_LOG (&finalize_ends_ctr, buf,
1718 EVENT_SIZE /* event */
1721 emit_event (buf, TYPE_GC_FINALIZE_END | TYPE_GC);
1728 finalize_object_begin (MonoProfiler *prof, MonoObject *obj)
1730 ENTER_LOG (&finalize_object_begins_ctr, buf,
1731 EVENT_SIZE /* event */ +
1732 LEB128_SIZE /* obj */
1735 emit_event (buf, TYPE_GC_FINALIZE_OBJECT_START | TYPE_GC);
1736 emit_obj (buf, obj);
1742 finalize_object_end (MonoProfiler *prof, MonoObject *obj)
1744 ENTER_LOG (&finalize_object_ends_ctr, buf,
1745 EVENT_SIZE /* event */ +
1746 LEB128_SIZE /* obj */
1749 emit_event (buf, TYPE_GC_FINALIZE_OBJECT_END | TYPE_GC);
1750 emit_obj (buf, obj);
1756 push_nesting (char *p, MonoClass *klass)
1761 nesting = mono_class_get_nesting_type (klass);
1763 p = push_nesting (p, nesting);
1767 name = mono_class_get_name (klass);
1768 nspace = mono_class_get_namespace (klass);
1771 p += strlen (nspace);
1781 type_name (MonoClass *klass)
1785 push_nesting (buf, klass);
1786 p = (char *) g_malloc (strlen (buf) + 1);
1792 image_loaded (MonoProfiler *prof, MonoImage *image, int result)
1794 if (result != MONO_PROFILE_OK)
1797 const char *name = mono_image_get_filename (image);
1798 int nlen = strlen (name) + 1;
1800 ENTER_LOG (&image_loads_ctr, logbuffer,
1801 EVENT_SIZE /* event */ +
1802 BYTE_SIZE /* type */ +
1803 LEB128_SIZE /* image */ +
1807 emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1808 emit_byte (logbuffer, TYPE_IMAGE);
1809 emit_ptr (logbuffer, image);
1810 memcpy (logbuffer->cursor, name, nlen);
1811 logbuffer->cursor += nlen;
1817 image_unloaded (MonoProfiler *prof, MonoImage *image)
1819 const char *name = mono_image_get_filename (image);
1820 int nlen = strlen (name) + 1;
1822 ENTER_LOG (&image_unloads_ctr, logbuffer,
1823 EVENT_SIZE /* event */ +
1824 BYTE_SIZE /* type */ +
1825 LEB128_SIZE /* image */ +
1829 emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1830 emit_byte (logbuffer, TYPE_IMAGE);
1831 emit_ptr (logbuffer, image);
1832 memcpy (logbuffer->cursor, name, nlen);
1833 logbuffer->cursor += nlen;
1839 assembly_loaded (MonoProfiler *prof, MonoAssembly *assembly, int result)
1841 if (result != MONO_PROFILE_OK)
1844 char *name = mono_stringify_assembly_name (mono_assembly_get_name (assembly));
1845 int nlen = strlen (name) + 1;
1847 ENTER_LOG (&assembly_loads_ctr, logbuffer,
1848 EVENT_SIZE /* event */ +
1849 BYTE_SIZE /* type */ +
1850 LEB128_SIZE /* assembly */ +
1854 emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1855 emit_byte (logbuffer, TYPE_ASSEMBLY);
1856 emit_ptr (logbuffer, assembly);
1857 memcpy (logbuffer->cursor, name, nlen);
1858 logbuffer->cursor += nlen;
1866 assembly_unloaded (MonoProfiler *prof, MonoAssembly *assembly)
1868 char *name = mono_stringify_assembly_name (mono_assembly_get_name (assembly));
1869 int nlen = strlen (name) + 1;
1871 ENTER_LOG (&assembly_unloads_ctr, logbuffer,
1872 EVENT_SIZE /* event */ +
1873 BYTE_SIZE /* type */ +
1874 LEB128_SIZE /* assembly */ +
1878 emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1879 emit_byte (logbuffer, TYPE_ASSEMBLY);
1880 emit_ptr (logbuffer, assembly);
1881 memcpy (logbuffer->cursor, name, nlen);
1882 logbuffer->cursor += nlen;
1890 class_loaded (MonoProfiler *prof, MonoClass *klass, int result)
1892 if (result != MONO_PROFILE_OK)
1897 if (InterlockedRead (&runtime_inited))
1898 name = mono_type_get_name (mono_class_get_type (klass));
1900 name = type_name (klass);
1902 int nlen = strlen (name) + 1;
1903 MonoImage *image = mono_class_get_image (klass);
1905 ENTER_LOG (&class_loads_ctr, logbuffer,
1906 EVENT_SIZE /* event */ +
1907 BYTE_SIZE /* type */ +
1908 LEB128_SIZE /* klass */ +
1909 LEB128_SIZE /* image */ +
1913 emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1914 emit_byte (logbuffer, TYPE_CLASS);
1915 emit_ptr (logbuffer, klass);
1916 emit_ptr (logbuffer, image);
1917 memcpy (logbuffer->cursor, name, nlen);
1918 logbuffer->cursor += nlen;
1929 class_unloaded (MonoProfiler *prof, MonoClass *klass)
1933 if (InterlockedRead (&runtime_inited))
1934 name = mono_type_get_name (mono_class_get_type (klass));
1936 name = type_name (klass);
1938 int nlen = strlen (name) + 1;
1939 MonoImage *image = mono_class_get_image (klass);
1941 ENTER_LOG (&class_unloads_ctr, logbuffer,
1942 EVENT_SIZE /* event */ +
1943 BYTE_SIZE /* type */ +
1944 LEB128_SIZE /* klass */ +
1945 LEB128_SIZE /* image */ +
1949 emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1950 emit_byte (logbuffer, TYPE_CLASS);
1951 emit_ptr (logbuffer, klass);
1952 emit_ptr (logbuffer, image);
1953 memcpy (logbuffer->cursor, name, nlen);
1954 logbuffer->cursor += nlen;
1964 static void process_method_enter_coverage (MonoProfiler *prof, MonoMethod *method);
1967 method_enter (MonoProfiler *prof, MonoMethod *method)
1969 process_method_enter_coverage (prof, method);
1971 if (!only_coverage && PROF_TLS_GET ()->call_depth++ <= max_call_depth) {
1972 ENTER_LOG (&method_entries_ctr, logbuffer,
1973 EVENT_SIZE /* event */ +
1974 LEB128_SIZE /* method */
1977 emit_event (logbuffer, TYPE_ENTER | TYPE_METHOD);
1978 emit_method (logbuffer, method);
1985 method_leave (MonoProfiler *prof, MonoMethod *method)
1987 if (!only_coverage && --PROF_TLS_GET ()->call_depth <= max_call_depth) {
1988 ENTER_LOG (&method_exits_ctr, logbuffer,
1989 EVENT_SIZE /* event */ +
1990 LEB128_SIZE /* method */
1993 emit_event (logbuffer, TYPE_LEAVE | TYPE_METHOD);
1994 emit_method (logbuffer, method);
2001 method_exc_leave (MonoProfiler *prof, MonoMethod *method)
2003 if (!only_coverage && !nocalls && --PROF_TLS_GET ()->call_depth <= max_call_depth) {
2004 ENTER_LOG (&method_exception_exits_ctr, logbuffer,
2005 EVENT_SIZE /* event */ +
2006 LEB128_SIZE /* method */
2009 emit_event (logbuffer, TYPE_EXC_LEAVE | TYPE_METHOD);
2010 emit_method (logbuffer, method);
2017 method_jitted (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *ji, int result)
2019 if (result != MONO_PROFILE_OK)
2022 register_method_local (method, ji);
2026 code_buffer_new (MonoProfiler *prof, void *buffer, int size, MonoProfilerCodeBufferType type, void *data)
2031 if (type == MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE) {
2032 name = (char *) data;
2033 nlen = strlen (name) + 1;
2039 ENTER_LOG (&code_buffers_ctr, logbuffer,
2040 EVENT_SIZE /* event */ +
2041 BYTE_SIZE /* type */ +
2042 LEB128_SIZE /* buffer */ +
2043 LEB128_SIZE /* size */ +
2049 emit_event (logbuffer, TYPE_JITHELPER | TYPE_RUNTIME);
2050 emit_byte (logbuffer, type);
2051 emit_ptr (logbuffer, buffer);
2052 emit_value (logbuffer, size);
2055 memcpy (logbuffer->cursor, name, nlen);
2056 logbuffer->cursor += nlen;
2063 throw_exc (MonoProfiler *prof, MonoObject *object)
2065 int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces) ? TYPE_THROW_BT : 0;
2071 ENTER_LOG (&exception_throws_ctr, logbuffer,
2072 EVENT_SIZE /* event */ +
2073 LEB128_SIZE /* object */ +
2075 LEB128_SIZE /* count */ +
2077 LEB128_SIZE /* method */
2082 emit_event (logbuffer, do_bt | TYPE_EXCEPTION);
2083 emit_obj (logbuffer, object);
2086 emit_bt (prof, logbuffer, &data);
2092 clause_exc (MonoProfiler *prof, MonoMethod *method, int clause_type, int clause_num)
2094 ENTER_LOG (&exception_clauses_ctr, logbuffer,
2095 EVENT_SIZE /* event */ +
2096 BYTE_SIZE /* clause type */ +
2097 LEB128_SIZE /* clause num */ +
2098 LEB128_SIZE /* method */
2101 emit_event (logbuffer, TYPE_EXCEPTION | TYPE_CLAUSE);
2102 emit_byte (logbuffer, clause_type);
2103 emit_value (logbuffer, clause_num);
2104 emit_method (logbuffer, method);
2110 monitor_event (MonoProfiler *profiler, MonoObject *object, MonoProfilerMonitorEvent event)
2112 int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces && event == MONO_PROFILER_MONITOR_CONTENTION) ? TYPE_MONITOR_BT : 0;
2121 case MONO_PROFILER_MONITOR_CONTENTION:
2122 ctr = &monitor_contentions_ctr;
2124 case MONO_PROFILER_MONITOR_DONE:
2125 ctr = &monitor_acquisitions_ctr;
2127 case MONO_PROFILER_MONITOR_FAIL:
2128 ctr = &monitor_failures_ctr;
2131 g_assert_not_reached ();
2135 ENTER_LOG (ctr, logbuffer,
2136 EVENT_SIZE /* event */ +
2137 LEB128_SIZE /* object */ +
2139 LEB128_SIZE /* count */ +
2141 LEB128_SIZE /* method */
2146 emit_event (logbuffer, (event << 4) | do_bt | TYPE_MONITOR);
2147 emit_obj (logbuffer, object);
2150 emit_bt (profiler, logbuffer, &data);
2156 thread_start (MonoProfiler *prof, uintptr_t tid)
2158 init_thread (prof, TRUE);
2160 if (ENABLED (PROFLOG_THREAD_EVENTS)) {
2161 ENTER_LOG (&thread_starts_ctr, logbuffer,
2162 EVENT_SIZE /* event */ +
2163 BYTE_SIZE /* type */ +
2164 LEB128_SIZE /* tid */
2167 emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
2168 emit_byte (logbuffer, TYPE_THREAD);
2169 emit_ptr (logbuffer, (void*) tid);
2176 thread_end (MonoProfiler *prof, uintptr_t tid)
2178 if (ENABLED (PROFLOG_THREAD_EVENTS)) {
2179 ENTER_LOG (&thread_ends_ctr, logbuffer,
2180 EVENT_SIZE /* event */ +
2181 BYTE_SIZE /* type */ +
2182 LEB128_SIZE /* tid */
2185 emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
2186 emit_byte (logbuffer, TYPE_THREAD);
2187 emit_ptr (logbuffer, (void*) tid);
2189 EXIT_LOG_EXPLICIT (NO_SEND);
2192 MonoProfilerThread *thread = PROF_TLS_GET ();
2194 thread->ended = TRUE;
2195 remove_thread (thread);
2197 PROF_TLS_SET (NULL);
2201 thread_name (MonoProfiler *prof, uintptr_t tid, const char *name)
2203 int len = strlen (name) + 1;
2205 if (ENABLED (PROFLOG_THREAD_EVENTS)) {
2206 ENTER_LOG (&thread_names_ctr, logbuffer,
2207 EVENT_SIZE /* event */ +
2208 BYTE_SIZE /* type */ +
2209 LEB128_SIZE /* tid */ +
2213 emit_event (logbuffer, TYPE_METADATA);
2214 emit_byte (logbuffer, TYPE_THREAD);
2215 emit_ptr (logbuffer, (void*)tid);
2216 memcpy (logbuffer->cursor, name, len);
2217 logbuffer->cursor += len;
2224 domain_loaded (MonoProfiler *prof, MonoDomain *domain, int result)
2226 if (result != MONO_PROFILE_OK)
2229 ENTER_LOG (&domain_loads_ctr, logbuffer,
2230 EVENT_SIZE /* event */ +
2231 BYTE_SIZE /* type */ +
2232 LEB128_SIZE /* domain id */
2235 emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
2236 emit_byte (logbuffer, TYPE_DOMAIN);
2237 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
2243 domain_unloaded (MonoProfiler *prof, MonoDomain *domain)
2245 ENTER_LOG (&domain_unloads_ctr, logbuffer,
2246 EVENT_SIZE /* event */ +
2247 BYTE_SIZE /* type */ +
2248 LEB128_SIZE /* domain id */
2251 emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
2252 emit_byte (logbuffer, TYPE_DOMAIN);
2253 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
2259 domain_name (MonoProfiler *prof, MonoDomain *domain, const char *name)
2261 int nlen = strlen (name) + 1;
2263 ENTER_LOG (&domain_names_ctr, logbuffer,
2264 EVENT_SIZE /* event */ +
2265 BYTE_SIZE /* type */ +
2266 LEB128_SIZE /* domain id */ +
2270 emit_event (logbuffer, TYPE_METADATA);
2271 emit_byte (logbuffer, TYPE_DOMAIN);
2272 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
2273 memcpy (logbuffer->cursor, name, nlen);
2274 logbuffer->cursor += nlen;
2280 context_loaded (MonoProfiler *prof, MonoAppContext *context)
2282 ENTER_LOG (&context_loads_ctr, logbuffer,
2283 EVENT_SIZE /* event */ +
2284 BYTE_SIZE /* type */ +
2285 LEB128_SIZE /* context id */ +
2286 LEB128_SIZE /* domain id */
2289 emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
2290 emit_byte (logbuffer, TYPE_CONTEXT);
2291 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_id (context));
2292 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_domain_id (context));
2298 context_unloaded (MonoProfiler *prof, MonoAppContext *context)
2300 ENTER_LOG (&context_unloads_ctr, logbuffer,
2301 EVENT_SIZE /* event */ +
2302 BYTE_SIZE /* type */ +
2303 LEB128_SIZE /* context id */ +
2304 LEB128_SIZE /* domain id */
2307 emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
2308 emit_byte (logbuffer, TYPE_CONTEXT);
2309 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_id (context));
2310 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_domain_id (context));
2323 MonoLockFreeQueueNode node;
2329 AsyncFrameInfo frames [MONO_ZERO_LEN_ARRAY];
2333 async_walk_stack (MonoMethod *method, MonoDomain *domain, void *base_address, int offset, void *data)
2335 SampleHit *sample = (SampleHit *) data;
2337 if (sample->count < num_frames) {
2338 int i = sample->count;
2340 sample->frames [i].method = method;
2341 sample->frames [i].domain = domain;
2342 sample->frames [i].base_address = base_address;
2343 sample->frames [i].offset = offset;
2348 return sample->count == num_frames;
2351 #define SAMPLE_SLOT_SIZE(FRAMES) (sizeof (SampleHit) + sizeof (AsyncFrameInfo) * (FRAMES - MONO_ZERO_LEN_ARRAY))
2352 #define SAMPLE_BLOCK_SIZE (mono_pagesize ())
2355 enqueue_sample_hit (gpointer p)
2357 SampleHit *sample = p;
2359 mono_lock_free_queue_node_unpoison (&sample->node);
2360 mono_lock_free_queue_enqueue (&sample->prof->dumper_queue, &sample->node);
2361 mono_os_sem_post (&sample->prof->dumper_queue_sem);
2365 mono_sample_hit (MonoProfiler *profiler, unsigned char *ip, void *context)
2368 * Please note: We rely on the runtime loading the profiler with
2369 * MONO_DL_EAGER (RTLD_NOW) so that references to runtime functions within
2370 * this function (and its siblings) are resolved when the profiler is
2371 * loaded. Otherwise, we would potentially invoke the dynamic linker when
2372 * invoking runtime functions, which is not async-signal-safe.
2375 if (InterlockedRead (&in_shutdown))
2378 SampleHit *sample = (SampleHit *) mono_lock_free_queue_dequeue (&profiler->sample_reuse_queue);
2382 * If we're out of reusable sample events and we're not allowed to
2383 * allocate more, we have no choice but to drop the event.
2385 if (InterlockedRead (&sample_allocations_ctr) >= max_allocated_sample_hits)
2388 sample = mono_lock_free_alloc (&profiler->sample_allocator);
2389 sample->prof = profiler;
2390 mono_lock_free_queue_node_init (&sample->node, TRUE);
2392 InterlockedIncrement (&sample_allocations_ctr);
2396 mono_stack_walk_async_safe (&async_walk_stack, context, sample);
2398 sample->time = current_time ();
2399 sample->tid = thread_id ();
2402 mono_thread_hazardous_try_free (sample, enqueue_sample_hit);
2405 static uintptr_t *code_pages = 0;
2406 static int num_code_pages = 0;
2407 static int size_code_pages = 0;
2408 #define CPAGE_SHIFT (9)
2409 #define CPAGE_SIZE (1 << CPAGE_SHIFT)
2410 #define CPAGE_MASK (~(CPAGE_SIZE - 1))
2411 #define CPAGE_ADDR(p) ((p) & CPAGE_MASK)
2414 add_code_page (uintptr_t *hash, uintptr_t hsize, uintptr_t page)
2417 uintptr_t start_pos;
2418 start_pos = (page >> CPAGE_SHIFT) % hsize;
2421 if (hash [i] && CPAGE_ADDR (hash [i]) == CPAGE_ADDR (page)) {
2423 } else if (!hash [i]) {
2430 } while (i != start_pos);
2431 /* should not happen */
2432 printf ("failed code page store\n");
2437 add_code_pointer (uintptr_t ip)
2440 if (num_code_pages * 2 >= size_code_pages) {
2442 uintptr_t old_size = size_code_pages;
2443 size_code_pages *= 2;
2444 if (size_code_pages == 0)
2445 size_code_pages = 16;
2446 n = (uintptr_t *) g_calloc (sizeof (uintptr_t) * size_code_pages, 1);
2447 for (i = 0; i < old_size; ++i) {
2449 add_code_page (n, size_code_pages, code_pages [i]);
2452 g_free (code_pages);
2455 num_code_pages += add_code_page (code_pages, size_code_pages, ip & CPAGE_MASK);
2458 /* ELF code crashes on some systems. */
2459 //#if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
2462 dump_ubin (MonoProfiler *prof, const char *filename, uintptr_t load_addr, uint64_t offset, uintptr_t size)
2464 int len = strlen (filename) + 1;
2466 ENTER_LOG (&sample_ubins_ctr, logbuffer,
2467 EVENT_SIZE /* event */ +
2468 LEB128_SIZE /* load address */ +
2469 LEB128_SIZE /* offset */ +
2470 LEB128_SIZE /* size */ +
2471 nlen /* file name */
2474 emit_event (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_UBIN);
2475 emit_svalue (logbuffer, load_addr);
2476 emit_uvalue (logbuffer, offset);
2477 emit_uvalue (logbuffer, size);
2478 memcpy (logbuffer->cursor, filename, len);
2479 logbuffer->cursor += len;
2481 EXIT_LOG_EXPLICIT (DO_SEND);
2486 dump_usym (MonoProfiler *prof, const char *name, uintptr_t value, uintptr_t size)
2488 int len = strlen (name) + 1;
2490 ENTER_LOG (&sample_usyms_ctr, logbuffer,
2491 EVENT_SIZE /* event */ +
2492 LEB128_SIZE /* value */ +
2493 LEB128_SIZE /* size */ +
2497 emit_event (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_USYM);
2498 emit_ptr (logbuffer, (void*)value);
2499 emit_value (logbuffer, size);
2500 memcpy (logbuffer->cursor, name, len);
2501 logbuffer->cursor += len;
2503 EXIT_LOG_EXPLICIT (DO_SEND);
2506 /* ELF code crashes on some systems. */
2507 //#if defined(ELFMAG0)
2510 #if SIZEOF_VOID_P == 4
2511 #define ELF_WSIZE 32
2513 #define ELF_WSIZE 64
2516 #define ElfW(type) _ElfW (Elf, ELF_WSIZE, type)
2517 #define _ElfW(e,w,t) _ElfW_1 (e, w, _##t)
2518 #define _ElfW_1(e,w,t) e##w##t
2522 dump_elf_symbols (MonoProfiler *prof, ElfW(Sym) *symbols, int num_symbols, const char *strtab, void *load_addr)
2525 for (i = 0; i < num_symbols; ++i) {
2527 sym = strtab + symbols [i].st_name;
2528 if (!symbols [i].st_name || !symbols [i].st_size || (symbols [i].st_info & 0xf) != STT_FUNC)
2530 //printf ("symbol %s at %d\n", sym, symbols [i].st_value);
2531 dump_usym (sym, (uintptr_t)load_addr + symbols [i].st_value, symbols [i].st_size);
2536 read_elf_symbols (MonoProfiler *prof, const char *filename, void *load_addr)
2543 ElfW(Shdr) *sheader;
2544 ElfW(Shdr) *shstrtabh;
2545 ElfW(Shdr) *symtabh = NULL;
2546 ElfW(Shdr) *strtabh = NULL;
2547 ElfW(Sym) *symbols = NULL;
2551 fd = open (filename, O_RDONLY);
2554 if (fstat (fd, &statb) != 0) {
2558 file_size = statb.st_size;
2559 data = mmap (NULL, file_size, PROT_READ, MAP_PRIVATE, fd, 0);
2561 if (data == MAP_FAILED)
2564 if (header->e_ident [EI_MAG0] != ELFMAG0 ||
2565 header->e_ident [EI_MAG1] != ELFMAG1 ||
2566 header->e_ident [EI_MAG2] != ELFMAG2 ||
2567 header->e_ident [EI_MAG3] != ELFMAG3 ) {
2568 munmap (data, file_size);
2571 sheader = (void*)((char*)data + header->e_shoff);
2572 shstrtabh = (void*)((char*)sheader + (header->e_shentsize * header->e_shstrndx));
2573 strtab = (const char*)data + shstrtabh->sh_offset;
2574 for (i = 0; i < header->e_shnum; ++i) {
2575 //printf ("section header: %d\n", sheader->sh_type);
2576 if (sheader->sh_type == SHT_SYMTAB) {
2578 strtabh = (void*)((char*)data + header->e_shoff + sheader->sh_link * header->e_shentsize);
2579 /*printf ("symtab section header: %d, .strstr: %d\n", i, sheader->sh_link);*/
2582 sheader = (void*)((char*)sheader + header->e_shentsize);
2584 if (!symtabh || !strtabh) {
2585 munmap (data, file_size);
2588 strtab = (const char*)data + strtabh->sh_offset;
2589 num_symbols = symtabh->sh_size / symtabh->sh_entsize;
2590 symbols = (void*)((char*)data + symtabh->sh_offset);
2591 dump_elf_symbols (symbols, num_symbols, strtab, load_addr);
2592 munmap (data, file_size);
2597 /* ELF code crashes on some systems. */
2598 //#if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
2601 elf_dl_callback (struct dl_phdr_info *info, size_t size, void *data)
2603 MonoProfiler *prof = data;
2605 const char *filename;
2607 char *a = (void*)info->dlpi_addr;
2609 ElfW(Dyn) *dyn = NULL;
2610 ElfW(Sym) *symtab = NULL;
2611 ElfW(Word) *hash_table = NULL;
2612 ElfW(Ehdr) *header = NULL;
2613 const char* strtab = NULL;
2614 for (obj = prof->binary_objects; obj; obj = obj->next) {
2618 filename = info->dlpi_name;
2621 if (!info->dlpi_addr && !filename [0]) {
2622 int l = readlink ("/proc/self/exe", buf, sizeof (buf) - 1);
2628 obj = g_calloc (sizeof (BinaryObject), 1);
2629 obj->addr = (void*)info->dlpi_addr;
2630 obj->name = pstrdup (filename);
2631 obj->next = prof->binary_objects;
2632 prof->binary_objects = obj;
2633 //printf ("loaded file: %s at %p, segments: %d\n", filename, (void*)info->dlpi_addr, info->dlpi_phnum);
2635 for (i = 0; i < info->dlpi_phnum; ++i) {
2636 //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);
2637 if (info->dlpi_phdr[i].p_type == PT_LOAD && !header) {
2638 header = (ElfW(Ehdr)*)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
2639 if (header->e_ident [EI_MAG0] != ELFMAG0 ||
2640 header->e_ident [EI_MAG1] != ELFMAG1 ||
2641 header->e_ident [EI_MAG2] != ELFMAG2 ||
2642 header->e_ident [EI_MAG3] != ELFMAG3 ) {
2645 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);
2646 } else if (info->dlpi_phdr[i].p_type == PT_DYNAMIC) {
2647 dyn = (ElfW(Dyn) *)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
2650 if (read_elf_symbols (prof, filename, (void*)info->dlpi_addr))
2652 if (!info->dlpi_name || !info->dlpi_name[0])
2656 for (i = 0; dyn [i].d_tag != DT_NULL; ++i) {
2657 if (dyn [i].d_tag == DT_SYMTAB) {
2658 if (symtab && do_debug)
2659 printf ("multiple symtabs: %d\n", i);
2660 symtab = (ElfW(Sym) *)(a + dyn [i].d_un.d_ptr);
2661 } else if (dyn [i].d_tag == DT_HASH) {
2662 hash_table = (ElfW(Word) *)(a + dyn [i].d_un.d_ptr);
2663 } else if (dyn [i].d_tag == DT_STRTAB) {
2664 strtab = (const char*)(a + dyn [i].d_un.d_ptr);
2669 num_sym = hash_table [1];
2670 dump_elf_symbols (prof, symtab, num_sym, strtab, (void*)info->dlpi_addr);
2675 load_binaries (MonoProfiler *prof)
2677 dl_iterate_phdr (elf_dl_callback, prof);
2682 load_binaries (MonoProfiler *prof)
2689 symbol_for (uintptr_t code)
2692 void *ip = (void*)code;
2694 if (dladdr (ip, &di)) {
2696 return di.dli_sname;
2699 names = backtrace_symbols (&ip, 1);
2701 const char* p = names [0];
2712 dump_unmanaged_coderefs (MonoProfiler *prof)
2715 const char* last_symbol;
2716 uintptr_t addr, page_end;
2718 if (load_binaries (prof))
2720 for (i = 0; i < size_code_pages; ++i) {
2722 if (!code_pages [i] || code_pages [i] & 1)
2725 addr = CPAGE_ADDR (code_pages [i]);
2726 page_end = addr + CPAGE_SIZE;
2727 code_pages [i] |= 1;
2728 /* we dump the symbols for the whole page */
2729 for (; addr < page_end; addr += 16) {
2730 sym = symbol_for (addr);
2731 if (sym && sym == last_symbol)
2736 dump_usym (prof, sym, addr, 0); /* let's not guess the size */
2737 //printf ("found symbol at %p: %s\n", (void*)addr, sym);
2742 typedef struct MonoCounterAgent {
2743 MonoCounter *counter;
2744 // MonoCounterAgent specific data :
2749 struct MonoCounterAgent *next;
2752 static MonoCounterAgent* counters;
2753 static int counters_index = 1;
2754 static mono_mutex_t counters_mutex;
2757 counters_add_agent (MonoCounter *counter)
2759 if (InterlockedRead (&in_shutdown))
2762 MonoCounterAgent *agent, *item;
2764 mono_os_mutex_lock (&counters_mutex);
2766 for (agent = counters; agent; agent = agent->next) {
2767 if (agent->counter == counter) {
2768 agent->value_size = 0;
2770 g_free (agent->value);
2771 agent->value = NULL;
2777 agent = (MonoCounterAgent *) g_malloc (sizeof (MonoCounterAgent));
2778 agent->counter = counter;
2779 agent->value = NULL;
2780 agent->value_size = 0;
2781 agent->index = counters_index++;
2795 mono_os_mutex_unlock (&counters_mutex);
2799 counters_init_foreach_callback (MonoCounter *counter, gpointer data)
2801 counters_add_agent (counter);
2806 counters_init (MonoProfiler *profiler)
2808 mono_os_mutex_init (&counters_mutex);
2810 mono_counters_on_register (&counters_add_agent);
2811 mono_counters_foreach (counters_init_foreach_callback, NULL);
2815 counters_emit (MonoProfiler *profiler)
2817 MonoCounterAgent *agent;
2820 EVENT_SIZE /* event */ +
2821 LEB128_SIZE /* len */
2824 mono_os_mutex_lock (&counters_mutex);
2826 for (agent = counters; agent; agent = agent->next) {
2831 LEB128_SIZE /* section */ +
2832 strlen (mono_counter_get_name (agent->counter)) + 1 /* name */ +
2833 BYTE_SIZE /* type */ +
2834 BYTE_SIZE /* unit */ +
2835 BYTE_SIZE /* variance */ +
2836 LEB128_SIZE /* index */
2845 ENTER_LOG (&counter_descriptors_ctr, logbuffer, size);
2847 emit_event (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
2848 emit_value (logbuffer, len);
2850 for (agent = counters; agent; agent = agent->next) {
2856 name = mono_counter_get_name (agent->counter);
2857 emit_value (logbuffer, mono_counter_get_section (agent->counter));
2858 emit_string (logbuffer, name, strlen (name) + 1);
2859 emit_byte (logbuffer, mono_counter_get_type (agent->counter));
2860 emit_byte (logbuffer, mono_counter_get_unit (agent->counter));
2861 emit_byte (logbuffer, mono_counter_get_variance (agent->counter));
2862 emit_value (logbuffer, agent->index);
2867 EXIT_LOG_EXPLICIT (DO_SEND);
2870 mono_os_mutex_unlock (&counters_mutex);
2874 counters_sample (MonoProfiler *profiler, uint64_t timestamp)
2876 MonoCounterAgent *agent;
2877 MonoCounter *counter;
2883 counters_emit (profiler);
2886 buffer = g_calloc (1, buffer_size);
2888 mono_os_mutex_lock (&counters_mutex);
2891 EVENT_SIZE /* event */
2894 for (agent = counters; agent; agent = agent->next) {
2896 LEB128_SIZE /* index */ +
2897 BYTE_SIZE /* type */ +
2898 mono_counter_get_size (agent->counter) /* value */
2903 LEB128_SIZE /* stop marker */
2906 ENTER_LOG (&counter_samples_ctr, logbuffer, size);
2908 emit_event_time (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE, timestamp);
2910 for (agent = counters; agent; agent = agent->next) {
2913 counter = agent->counter;
2915 size = mono_counter_get_size (counter);
2917 if (size > buffer_size) {
2919 buffer = g_realloc (buffer, buffer_size);
2922 memset (buffer, 0, buffer_size);
2924 g_assert (mono_counters_sample (counter, buffer, size));
2926 type = mono_counter_get_type (counter);
2928 if (!agent->value) {
2929 agent->value = g_calloc (1, size);
2930 agent->value_size = size;
2932 if (type == MONO_COUNTER_STRING) {
2933 if (strcmp (agent->value, buffer) == 0)
2936 if (agent->value_size == size && memcmp (agent->value, buffer, size) == 0)
2941 emit_uvalue (logbuffer, agent->index);
2942 emit_byte (logbuffer, type);
2944 case MONO_COUNTER_INT:
2945 #if SIZEOF_VOID_P == 4
2946 case MONO_COUNTER_WORD:
2948 emit_svalue (logbuffer, *(int*)buffer - *(int*)agent->value);
2950 case MONO_COUNTER_UINT:
2951 emit_uvalue (logbuffer, *(guint*)buffer - *(guint*)agent->value);
2953 case MONO_COUNTER_TIME_INTERVAL:
2954 case MONO_COUNTER_LONG:
2955 #if SIZEOF_VOID_P == 8
2956 case MONO_COUNTER_WORD:
2958 emit_svalue (logbuffer, *(gint64*)buffer - *(gint64*)agent->value);
2960 case MONO_COUNTER_ULONG:
2961 emit_uvalue (logbuffer, *(guint64*)buffer - *(guint64*)agent->value);
2963 case MONO_COUNTER_DOUBLE:
2964 emit_double (logbuffer, *(double*)buffer);
2966 case MONO_COUNTER_STRING:
2968 emit_byte (logbuffer, 0);
2970 emit_byte (logbuffer, 1);
2971 emit_string (logbuffer, (char*)buffer, size);
2975 g_assert_not_reached ();
2978 if (type == MONO_COUNTER_STRING && size > agent->value_size) {
2979 agent->value = g_realloc (agent->value, size);
2980 agent->value_size = size;
2984 memcpy (agent->value, buffer, size);
2988 emit_value (logbuffer, 0);
2990 EXIT_LOG_EXPLICIT (DO_SEND);
2992 mono_os_mutex_unlock (&counters_mutex);
2995 typedef struct _PerfCounterAgent PerfCounterAgent;
2996 struct _PerfCounterAgent {
2997 PerfCounterAgent *next;
2999 char *category_name;
3008 static PerfCounterAgent *perfcounters = NULL;
3011 perfcounters_emit (MonoProfiler *profiler)
3013 PerfCounterAgent *pcagent;
3016 EVENT_SIZE /* event */ +
3017 LEB128_SIZE /* len */
3020 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3021 if (pcagent->emitted)
3025 LEB128_SIZE /* section */ +
3026 strlen (pcagent->category_name) + 1 /* category name */ +
3027 strlen (pcagent->name) + 1 /* name */ +
3028 BYTE_SIZE /* type */ +
3029 BYTE_SIZE /* unit */ +
3030 BYTE_SIZE /* variance */ +
3031 LEB128_SIZE /* index */
3040 ENTER_LOG (&perfcounter_descriptors_ctr, logbuffer, size);
3042 emit_event (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
3043 emit_value (logbuffer, len);
3045 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3046 if (pcagent->emitted)
3049 emit_value (logbuffer, MONO_COUNTER_PERFCOUNTERS);
3050 emit_string (logbuffer, pcagent->category_name, strlen (pcagent->category_name) + 1);
3051 emit_string (logbuffer, pcagent->name, strlen (pcagent->name) + 1);
3052 emit_byte (logbuffer, MONO_COUNTER_LONG);
3053 emit_byte (logbuffer, MONO_COUNTER_RAW);
3054 emit_byte (logbuffer, MONO_COUNTER_VARIABLE);
3055 emit_value (logbuffer, pcagent->index);
3057 pcagent->emitted = 1;
3060 EXIT_LOG_EXPLICIT (DO_SEND);
3064 perfcounters_foreach (char *category_name, char *name, unsigned char type, gint64 value, gpointer user_data)
3066 PerfCounterAgent *pcagent;
3068 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3069 if (strcmp (pcagent->category_name, category_name) != 0 || strcmp (pcagent->name, name) != 0)
3071 if (pcagent->value == value)
3074 pcagent->value = value;
3075 pcagent->updated = 1;
3076 pcagent->deleted = 0;
3080 pcagent = g_new0 (PerfCounterAgent, 1);
3081 pcagent->next = perfcounters;
3082 pcagent->index = counters_index++;
3083 pcagent->category_name = g_strdup (category_name);
3084 pcagent->name = g_strdup (name);
3085 pcagent->type = (int) type;
3086 pcagent->value = value;
3087 pcagent->emitted = 0;
3088 pcagent->updated = 1;
3089 pcagent->deleted = 0;
3091 perfcounters = pcagent;
3097 perfcounters_sample (MonoProfiler *profiler, uint64_t timestamp)
3099 PerfCounterAgent *pcagent;
3103 mono_os_mutex_lock (&counters_mutex);
3105 /* mark all perfcounters as deleted, foreach will unmark them as necessary */
3106 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next)
3107 pcagent->deleted = 1;
3109 mono_perfcounter_foreach (perfcounters_foreach, perfcounters);
3111 perfcounters_emit (profiler);
3114 EVENT_SIZE /* event */
3117 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3118 if (pcagent->deleted || !pcagent->updated)
3122 LEB128_SIZE /* index */ +
3123 BYTE_SIZE /* type */ +
3124 LEB128_SIZE /* value */
3134 LEB128_SIZE /* stop marker */
3137 ENTER_LOG (&perfcounter_samples_ctr, logbuffer, size);
3139 emit_event_time (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE, timestamp);
3141 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3142 if (pcagent->deleted || !pcagent->updated)
3144 emit_uvalue (logbuffer, pcagent->index);
3145 emit_byte (logbuffer, MONO_COUNTER_LONG);
3146 emit_svalue (logbuffer, pcagent->value);
3148 pcagent->updated = 0;
3151 emit_value (logbuffer, 0);
3153 EXIT_LOG_EXPLICIT (DO_SEND);
3156 mono_os_mutex_unlock (&counters_mutex);
3160 counters_and_perfcounters_sample (MonoProfiler *prof)
3162 uint64_t now = current_time ();
3164 counters_sample (prof, now);
3165 perfcounters_sample (prof, now);
3168 #define COVERAGE_DEBUG(x) if (debug_coverage) {x}
3169 static mono_mutex_t coverage_mutex;
3170 static MonoConcurrentHashTable *coverage_methods = NULL;
3171 static MonoConcurrentHashTable *coverage_assemblies = NULL;
3172 static MonoConcurrentHashTable *coverage_classes = NULL;
3174 static MonoConcurrentHashTable *filtered_classes = NULL;
3175 static MonoConcurrentHashTable *entered_methods = NULL;
3176 static MonoConcurrentHashTable *image_to_methods = NULL;
3177 static MonoConcurrentHashTable *suppressed_assemblies = NULL;
3178 static gboolean coverage_initialized = FALSE;
3180 static GPtrArray *coverage_data = NULL;
3181 static int previous_offset = 0;
3184 MonoLockFreeQueueNode node;
3197 free_coverage_entry (gpointer data, gpointer userdata)
3199 CoverageEntry *entry = (CoverageEntry *)data;
3200 g_free (entry->filename);
3205 obtain_coverage_for_method (MonoProfiler *prof, const MonoProfileCoverageEntry *entry)
3207 int offset = entry->iloffset - previous_offset;
3208 CoverageEntry *e = g_new (CoverageEntry, 1);
3210 previous_offset = entry->iloffset;
3213 e->counter = entry->counter;
3214 e->filename = g_strdup(entry->filename ? entry->filename : "");
3215 e->line = entry->line;
3216 e->column = entry->col;
3218 g_ptr_array_add (coverage_data, e);
3222 parse_generic_type_names(char *name)
3224 char *new_name, *ret;
3225 int within_generic_declaration = 0, generic_members = 1;
3227 if (name == NULL || *name == '\0')
3228 return g_strdup ("");
3230 if (!(ret = new_name = (char *) g_calloc (strlen (name) * 4 + 1, sizeof (char))))
3236 within_generic_declaration = 1;
3240 within_generic_declaration = 0;
3242 if (*(name - 1) != '<') {
3244 *new_name++ = '0' + generic_members;
3246 memcpy (new_name, "<>", 8);
3250 generic_members = 0;
3258 if (!within_generic_declaration)
3259 *new_name++ = *name;
3268 static int method_id;
3270 build_method_buffer (gpointer key, gpointer value, gpointer userdata)
3272 MonoMethod *method = (MonoMethod *)value;
3273 MonoProfiler *prof = (MonoProfiler *)userdata;
3277 const char *image_name, *method_name, *sig, *first_filename;
3280 previous_offset = 0;
3281 coverage_data = g_ptr_array_new ();
3283 mono_profiler_coverage_get (prof, method, obtain_coverage_for_method);
3285 klass = mono_method_get_class (method);
3286 image = mono_class_get_image (klass);
3287 image_name = mono_image_get_name (image);
3289 sig = mono_signature_get_desc (mono_method_signature (method), TRUE);
3290 class_name = parse_generic_type_names (mono_type_get_name (mono_class_get_type (klass)));
3291 method_name = mono_method_get_name (method);
3293 if (coverage_data->len != 0) {
3294 CoverageEntry *entry = (CoverageEntry *)coverage_data->pdata[0];
3295 first_filename = entry->filename ? entry->filename : "";
3297 first_filename = "";
3299 image_name = image_name ? image_name : "";
3300 sig = sig ? sig : "";
3301 method_name = method_name ? method_name : "";
3303 ENTER_LOG (&coverage_methods_ctr, logbuffer,
3304 EVENT_SIZE /* event */ +
3305 strlen (image_name) + 1 /* image name */ +
3306 strlen (class_name) + 1 /* class name */ +
3307 strlen (method_name) + 1 /* method name */ +
3308 strlen (sig) + 1 /* signature */ +
3309 strlen (first_filename) + 1 /* first file name */ +
3310 LEB128_SIZE /* token */ +
3311 LEB128_SIZE /* method id */ +
3312 LEB128_SIZE /* entries */
3315 emit_event (logbuffer, TYPE_COVERAGE_METHOD | TYPE_COVERAGE);
3316 emit_string (logbuffer, image_name, strlen (image_name) + 1);
3317 emit_string (logbuffer, class_name, strlen (class_name) + 1);
3318 emit_string (logbuffer, method_name, strlen (method_name) + 1);
3319 emit_string (logbuffer, sig, strlen (sig) + 1);
3320 emit_string (logbuffer, first_filename, strlen (first_filename) + 1);
3322 emit_uvalue (logbuffer, mono_method_get_token (method));
3323 emit_uvalue (logbuffer, method_id);
3324 emit_value (logbuffer, coverage_data->len);
3326 EXIT_LOG_EXPLICIT (DO_SEND);
3328 for (i = 0; i < coverage_data->len; i++) {
3329 CoverageEntry *entry = (CoverageEntry *)coverage_data->pdata[i];
3331 ENTER_LOG (&coverage_statements_ctr, logbuffer,
3332 EVENT_SIZE /* event */ +
3333 LEB128_SIZE /* method id */ +
3334 LEB128_SIZE /* offset */ +
3335 LEB128_SIZE /* counter */ +
3336 LEB128_SIZE /* line */ +
3337 LEB128_SIZE /* column */
3340 emit_event (logbuffer, TYPE_COVERAGE_STATEMENT | TYPE_COVERAGE);
3341 emit_uvalue (logbuffer, method_id);
3342 emit_uvalue (logbuffer, entry->offset);
3343 emit_uvalue (logbuffer, entry->counter);
3344 emit_uvalue (logbuffer, entry->line);
3345 emit_uvalue (logbuffer, entry->column);
3347 EXIT_LOG_EXPLICIT (DO_SEND);
3352 g_free (class_name);
3354 g_ptr_array_foreach (coverage_data, free_coverage_entry, NULL);
3355 g_ptr_array_free (coverage_data, TRUE);
3356 coverage_data = NULL;
3359 /* This empties the queue */
3361 count_queue (MonoLockFreeQueue *queue)
3363 MonoLockFreeQueueNode *node;
3366 while ((node = mono_lock_free_queue_dequeue (queue))) {
3368 mono_thread_hazardous_try_free (node, g_free);
3375 build_class_buffer (gpointer key, gpointer value, gpointer userdata)
3377 MonoClass *klass = (MonoClass *)key;
3378 MonoLockFreeQueue *class_methods = (MonoLockFreeQueue *)value;
3381 const char *assembly_name;
3382 int number_of_methods, partially_covered;
3383 guint fully_covered;
3385 image = mono_class_get_image (klass);
3386 assembly_name = mono_image_get_name (image);
3387 class_name = mono_type_get_name (mono_class_get_type (klass));
3389 assembly_name = assembly_name ? assembly_name : "";
3390 number_of_methods = mono_class_num_methods (klass);
3391 fully_covered = count_queue (class_methods);
3392 /* We don't handle partial covered yet */
3393 partially_covered = 0;
3395 ENTER_LOG (&coverage_classes_ctr, logbuffer,
3396 EVENT_SIZE /* event */ +
3397 strlen (assembly_name) + 1 /* assembly name */ +
3398 strlen (class_name) + 1 /* class name */ +
3399 LEB128_SIZE /* no. methods */ +
3400 LEB128_SIZE /* fully covered */ +
3401 LEB128_SIZE /* partially covered */
3404 emit_event (logbuffer, TYPE_COVERAGE_CLASS | TYPE_COVERAGE);
3405 emit_string (logbuffer, assembly_name, strlen (assembly_name) + 1);
3406 emit_string (logbuffer, class_name, strlen (class_name) + 1);
3407 emit_uvalue (logbuffer, number_of_methods);
3408 emit_uvalue (logbuffer, fully_covered);
3409 emit_uvalue (logbuffer, partially_covered);
3411 EXIT_LOG_EXPLICIT (DO_SEND);
3413 g_free (class_name);
3417 get_coverage_for_image (MonoImage *image, int *number_of_methods, guint *fully_covered, int *partially_covered)
3419 MonoLockFreeQueue *image_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (image_to_methods, image);
3421 *number_of_methods = mono_image_get_table_rows (image, MONO_TABLE_METHOD);
3423 *fully_covered = count_queue (image_methods);
3427 // FIXME: We don't handle partially covered yet.
3428 *partially_covered = 0;
3432 build_assembly_buffer (gpointer key, gpointer value, gpointer userdata)
3434 MonoAssembly *assembly = (MonoAssembly *)value;
3435 MonoImage *image = mono_assembly_get_image (assembly);
3436 const char *name, *guid, *filename;
3437 int number_of_methods = 0, partially_covered = 0;
3438 guint fully_covered = 0;
3440 name = mono_image_get_name (image);
3441 guid = mono_image_get_guid (image);
3442 filename = mono_image_get_filename (image);
3444 name = name ? name : "";
3445 guid = guid ? guid : "";
3446 filename = filename ? filename : "";
3448 get_coverage_for_image (image, &number_of_methods, &fully_covered, &partially_covered);
3450 ENTER_LOG (&coverage_assemblies_ctr, logbuffer,
3451 EVENT_SIZE /* event */ +
3452 strlen (name) + 1 /* name */ +
3453 strlen (guid) + 1 /* guid */ +
3454 strlen (filename) + 1 /* file name */ +
3455 LEB128_SIZE /* no. methods */ +
3456 LEB128_SIZE /* fully covered */ +
3457 LEB128_SIZE /* partially covered */
3460 emit_event (logbuffer, TYPE_COVERAGE_ASSEMBLY | TYPE_COVERAGE);
3461 emit_string (logbuffer, name, strlen (name) + 1);
3462 emit_string (logbuffer, guid, strlen (guid) + 1);
3463 emit_string (logbuffer, filename, strlen (filename) + 1);
3464 emit_uvalue (logbuffer, number_of_methods);
3465 emit_uvalue (logbuffer, fully_covered);
3466 emit_uvalue (logbuffer, partially_covered);
3468 EXIT_LOG_EXPLICIT (DO_SEND);
3472 dump_coverage (MonoProfiler *prof)
3474 if (!coverage_initialized)
3477 COVERAGE_DEBUG(fprintf (stderr, "Coverage: Started dump\n");)
3480 mono_os_mutex_lock (&coverage_mutex);
3481 mono_conc_hashtable_foreach (coverage_assemblies, build_assembly_buffer, NULL);
3482 mono_conc_hashtable_foreach (coverage_classes, build_class_buffer, NULL);
3483 mono_conc_hashtable_foreach (coverage_methods, build_method_buffer, prof);
3484 mono_os_mutex_unlock (&coverage_mutex);
3486 COVERAGE_DEBUG(fprintf (stderr, "Coverage: Finished dump\n");)
3490 process_method_enter_coverage (MonoProfiler *prof, MonoMethod *method)
3495 if (!coverage_initialized)
3498 klass = mono_method_get_class (method);
3499 image = mono_class_get_image (klass);
3501 if (mono_conc_hashtable_lookup (suppressed_assemblies, (gpointer) mono_image_get_name (image)))
3504 mono_os_mutex_lock (&coverage_mutex);
3505 mono_conc_hashtable_insert (entered_methods, method, method);
3506 mono_os_mutex_unlock (&coverage_mutex);
3509 static MonoLockFreeQueueNode *
3510 create_method_node (MonoMethod *method)
3512 MethodNode *node = (MethodNode *) g_malloc (sizeof (MethodNode));
3513 mono_lock_free_queue_node_init ((MonoLockFreeQueueNode *) node, FALSE);
3514 node->method = method;
3516 return (MonoLockFreeQueueNode *) node;
3520 coverage_filter (MonoProfiler *prof, MonoMethod *method)
3525 MonoAssembly *assembly;
3526 MonoMethodHeader *header;
3527 guint32 iflags, flags, code_size;
3528 char *fqn, *classname;
3529 gboolean has_positive, found;
3530 MonoLockFreeQueue *image_methods, *class_methods;
3531 MonoLockFreeQueueNode *node;
3533 g_assert (coverage_initialized && "Why are we being asked for coverage filter info when we're not doing coverage?");
3535 COVERAGE_DEBUG(fprintf (stderr, "Coverage filter for %s\n", mono_method_get_name (method));)
3537 flags = mono_method_get_flags (method, &iflags);
3538 if ((iflags & 0x1000 /*METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL*/) ||
3539 (flags & 0x2000 /*METHOD_ATTRIBUTE_PINVOKE_IMPL*/)) {
3540 COVERAGE_DEBUG(fprintf (stderr, " Internal call or pinvoke - ignoring\n");)
3544 // Don't need to do anything else if we're already tracking this method
3545 if (mono_conc_hashtable_lookup (coverage_methods, method)) {
3546 COVERAGE_DEBUG(fprintf (stderr, " Already tracking\n");)
3550 klass = mono_method_get_class (method);
3551 image = mono_class_get_image (klass);
3553 // Don't handle coverage for the core assemblies
3554 if (mono_conc_hashtable_lookup (suppressed_assemblies, (gpointer) mono_image_get_name (image)) != NULL)
3557 if (prof->coverage_filters) {
3558 /* Check already filtered classes first */
3559 if (mono_conc_hashtable_lookup (filtered_classes, klass)) {
3560 COVERAGE_DEBUG(fprintf (stderr, " Already filtered\n");)
3564 classname = mono_type_get_name (mono_class_get_type (klass));
3566 fqn = g_strdup_printf ("[%s]%s", mono_image_get_name (image), classname);
3568 COVERAGE_DEBUG(fprintf (stderr, " Looking for %s in filter\n", fqn);)
3569 // Check positive filters first
3570 has_positive = FALSE;
3572 for (guint i = 0; i < prof->coverage_filters->len; ++i) {
3573 char *filter = (char *)g_ptr_array_index (prof->coverage_filters, i);
3575 if (filter [0] == '+') {
3576 filter = &filter [1];
3578 COVERAGE_DEBUG(fprintf (stderr, " Checking against +%s ...", filter);)
3580 if (strstr (fqn, filter) != NULL) {
3581 COVERAGE_DEBUG(fprintf (stderr, "matched\n");)
3584 COVERAGE_DEBUG(fprintf (stderr, "no match\n");)
3586 has_positive = TRUE;
3590 if (has_positive && !found) {
3591 COVERAGE_DEBUG(fprintf (stderr, " Positive match was not found\n");)
3593 mono_os_mutex_lock (&coverage_mutex);
3594 mono_conc_hashtable_insert (filtered_classes, klass, klass);
3595 mono_os_mutex_unlock (&coverage_mutex);
3602 for (guint i = 0; i < prof->coverage_filters->len; ++i) {
3603 // FIXME: Is substring search sufficient?
3604 char *filter = (char *)g_ptr_array_index (prof->coverage_filters, i);
3605 if (filter [0] == '+')
3609 filter = &filter [1];
3610 COVERAGE_DEBUG(fprintf (stderr, " Checking against -%s ...", filter);)
3612 if (strstr (fqn, filter) != NULL) {
3613 COVERAGE_DEBUG(fprintf (stderr, "matched\n");)
3615 mono_os_mutex_lock (&coverage_mutex);
3616 mono_conc_hashtable_insert (filtered_classes, klass, klass);
3617 mono_os_mutex_unlock (&coverage_mutex);
3623 COVERAGE_DEBUG(fprintf (stderr, "no match\n");)
3631 COVERAGE_DEBUG(fprintf (stderr, " Handling coverage for %s\n", mono_method_get_name (method));)
3632 header = mono_method_get_header_checked (method, &error);
3633 mono_error_cleanup (&error);
3635 mono_method_header_get_code (header, &code_size, NULL);
3637 assembly = mono_image_get_assembly (image);
3639 // Need to keep the assemblies around for as long as they are kept in the hashtable
3640 // Nunit, for example, has a habit of unloading them before the coverage statistics are
3641 // generated causing a crash. See https://bugzilla.xamarin.com/show_bug.cgi?id=39325
3642 mono_assembly_addref (assembly);
3644 mono_os_mutex_lock (&coverage_mutex);
3645 mono_conc_hashtable_insert (coverage_methods, method, method);
3646 mono_conc_hashtable_insert (coverage_assemblies, assembly, assembly);
3647 mono_os_mutex_unlock (&coverage_mutex);
3649 image_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (image_to_methods, image);
3651 if (image_methods == NULL) {
3652 image_methods = (MonoLockFreeQueue *) g_malloc (sizeof (MonoLockFreeQueue));
3653 mono_lock_free_queue_init (image_methods);
3654 mono_os_mutex_lock (&coverage_mutex);
3655 mono_conc_hashtable_insert (image_to_methods, image, image_methods);
3656 mono_os_mutex_unlock (&coverage_mutex);
3659 node = create_method_node (method);
3660 mono_lock_free_queue_enqueue (image_methods, node);
3662 class_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (coverage_classes, klass);
3664 if (class_methods == NULL) {
3665 class_methods = (MonoLockFreeQueue *) g_malloc (sizeof (MonoLockFreeQueue));
3666 mono_lock_free_queue_init (class_methods);
3667 mono_os_mutex_lock (&coverage_mutex);
3668 mono_conc_hashtable_insert (coverage_classes, klass, class_methods);
3669 mono_os_mutex_unlock (&coverage_mutex);
3672 node = create_method_node (method);
3673 mono_lock_free_queue_enqueue (class_methods, node);
3678 #define LINE_BUFFER_SIZE 4096
3679 /* Max file limit of 128KB */
3680 #define MAX_FILE_SIZE 128 * 1024
3682 get_file_content (FILE *stream)
3687 int res, offset = 0;
3689 res = fseek (stream, 0, SEEK_END);
3693 filesize = ftell (stream);
3697 res = fseek (stream, 0, SEEK_SET);
3701 if (filesize > MAX_FILE_SIZE)
3704 buffer = (char *) g_malloc ((filesize + 1) * sizeof (char));
3705 while ((bytes_read = fread (buffer + offset, 1, LINE_BUFFER_SIZE, stream)) > 0)
3706 offset += bytes_read;
3708 /* NULL terminate our buffer */
3709 buffer[filesize] = '\0';
3714 get_next_line (char *contents, char **next_start)
3718 if (p == NULL || *p == '\0') {
3723 while (*p != '\n' && *p != '\0')
3728 *next_start = p + 1;
3736 init_suppressed_assemblies (void)
3742 suppressed_assemblies = mono_conc_hashtable_new (g_str_hash, g_str_equal);
3743 sa_file = fopen (SUPPRESSION_DIR "/mono-profiler-log.suppression", "r");
3744 if (sa_file == NULL)
3747 /* Don't need to free @content as it is referred to by the lines stored in @suppressed_assemblies */
3748 content = get_file_content (sa_file);
3749 if (content == NULL) {
3750 g_error ("mono-profiler-log.suppression is greater than 128kb - aborting\n");
3753 while ((line = get_next_line (content, &content))) {
3754 line = g_strchomp (g_strchug (line));
3755 /* No locking needed as we're doing initialization */
3756 mono_conc_hashtable_insert (suppressed_assemblies, line, line);
3763 parse_cov_filter_file (GPtrArray *filters, const char *file)
3766 char *line, *content;
3768 filter_file = fopen (file, "r");
3769 if (filter_file == NULL) {
3770 fprintf (stderr, "Unable to open %s\n", file);
3774 /* Don't need to free content as it is referred to by the lines stored in @filters */
3775 content = get_file_content (filter_file);
3776 if (content == NULL)
3777 fprintf (stderr, "WARNING: %s is greater than 128kb - ignoring\n", file);
3779 while ((line = get_next_line (content, &content)))
3780 g_ptr_array_add (filters, g_strchug (g_strchomp (line)));
3782 fclose (filter_file);
3786 coverage_init (MonoProfiler *prof)
3788 g_assert (!coverage_initialized && "Why are we initializing coverage twice?");
3790 COVERAGE_DEBUG(fprintf (stderr, "Coverage initialized\n");)
3792 mono_os_mutex_init (&coverage_mutex);
3793 coverage_methods = mono_conc_hashtable_new (NULL, NULL);
3794 coverage_assemblies = mono_conc_hashtable_new (NULL, NULL);
3795 coverage_classes = mono_conc_hashtable_new (NULL, NULL);
3796 filtered_classes = mono_conc_hashtable_new (NULL, NULL);
3797 entered_methods = mono_conc_hashtable_new (NULL, NULL);
3798 image_to_methods = mono_conc_hashtable_new (NULL, NULL);
3799 init_suppressed_assemblies ();
3801 coverage_initialized = TRUE;
3805 unref_coverage_assemblies (gpointer key, gpointer value, gpointer userdata)
3807 MonoAssembly *assembly = (MonoAssembly *)value;
3808 mono_assembly_close (assembly);
3812 free_sample_hit (gpointer p)
3814 mono_lock_free_free (p, SAMPLE_BLOCK_SIZE);
3818 cleanup_reusable_samples (MonoProfiler *prof)
3822 while ((sample = (SampleHit *) mono_lock_free_queue_dequeue (&prof->sample_reuse_queue)))
3823 mono_thread_hazardous_try_free (sample, free_sample_hit);
3827 log_shutdown (MonoProfiler *prof)
3829 InterlockedWrite (&in_shutdown, 1);
3832 counters_and_perfcounters_sample (prof);
3834 dump_coverage (prof);
3838 if (write (prof->pipes [1], &c, 1) != 1) {
3839 fprintf (stderr, "Could not write to pipe: %s\n", strerror (errno));
3843 mono_native_thread_join (prof->helper_thread);
3845 mono_os_mutex_destroy (&counters_mutex);
3847 MonoCounterAgent *mc_next;
3849 for (MonoCounterAgent *cur = counters; cur; cur = mc_next) {
3850 mc_next = cur->next;
3854 PerfCounterAgent *pc_next;
3856 for (PerfCounterAgent *cur = perfcounters; cur; cur = pc_next) {
3857 pc_next = cur->next;
3862 * Ensure that we empty the LLS completely, even if some nodes are
3863 * not immediately removed upon calling mono_lls_remove (), by
3864 * iterating until the head is NULL.
3866 while (profiler_thread_list.head) {
3867 MONO_LLS_FOREACH_SAFE (&profiler_thread_list, MonoProfilerThread, thread) {
3868 g_assert (thread->attached && "Why is a thread in the LLS not attached?");
3870 remove_thread (thread);
3871 } MONO_LLS_FOREACH_SAFE_END
3875 * Ensure that all threads have been freed, so that we don't miss any
3876 * buffers when we shut down the writer thread below.
3878 mono_thread_hazardous_try_free_all ();
3880 InterlockedWrite (&prof->run_dumper_thread, 0);
3881 mono_os_sem_post (&prof->dumper_queue_sem);
3882 mono_native_thread_join (prof->dumper_thread);
3883 mono_os_sem_destroy (&prof->dumper_queue_sem);
3885 InterlockedWrite (&prof->run_writer_thread, 0);
3886 mono_os_sem_post (&prof->writer_queue_sem);
3887 mono_native_thread_join (prof->writer_thread);
3888 mono_os_sem_destroy (&prof->writer_queue_sem);
3891 * Free all writer queue entries, and ensure that all sample hits will be
3892 * added to the sample reuse queue.
3894 mono_thread_hazardous_try_free_all ();
3896 cleanup_reusable_samples (prof);
3899 * Finally, make sure that all sample hits are freed. This should cover all
3900 * hazardous data from the profiler. We can now be sure that the runtime
3901 * won't later invoke free functions in the profiler library after it has
3904 mono_thread_hazardous_try_free_all ();
3906 g_assert (!InterlockedRead (&buffer_rwlock_count) && "Why is the reader count still non-zero?");
3907 g_assert (!InterlockedReadPointer (&buffer_rwlock_exclusive) && "Why does someone still hold the exclusive lock?");
3909 #if defined (HAVE_SYS_ZLIB)
3911 gzclose (prof->gzfile);
3913 if (prof->pipe_output)
3914 pclose (prof->file);
3916 fclose (prof->file);
3918 mono_conc_hashtable_destroy (prof->method_table);
3919 mono_os_mutex_destroy (&prof->method_table_mutex);
3921 if (coverage_initialized) {
3922 mono_os_mutex_lock (&coverage_mutex);
3923 mono_conc_hashtable_foreach (coverage_assemblies, unref_coverage_assemblies, prof);
3924 mono_os_mutex_unlock (&coverage_mutex);
3926 mono_conc_hashtable_destroy (coverage_methods);
3927 mono_conc_hashtable_destroy (coverage_assemblies);
3928 mono_conc_hashtable_destroy (coverage_classes);
3929 mono_conc_hashtable_destroy (filtered_classes);
3931 mono_conc_hashtable_destroy (entered_methods);
3932 mono_conc_hashtable_destroy (image_to_methods);
3933 mono_conc_hashtable_destroy (suppressed_assemblies);
3934 mono_os_mutex_destroy (&coverage_mutex);
3939 g_free (prof->args);
3944 new_filename (const char* filename)
3946 time_t t = time (NULL);
3947 int pid = process_id ();
3952 int count_dates = 0;
3956 for (p = filename; *p; p++) {
3967 if (!count_dates && !count_pids)
3968 return pstrdup (filename);
3969 snprintf (pid_buf, sizeof (pid_buf), "%d", pid);
3971 snprintf (time_buf, sizeof (time_buf), "%d%02d%02d%02d%02d%02d",
3972 1900 + ts->tm_year, 1 + ts->tm_mon, ts->tm_mday, ts->tm_hour, ts->tm_min, ts->tm_sec);
3973 s_date = strlen (time_buf);
3974 s_pid = strlen (pid_buf);
3975 d = res = (char *) g_malloc (strlen (filename) + s_date * count_dates + s_pid * count_pids);
3976 for (p = filename; *p; p++) {
3983 strcpy (d, time_buf);
3986 } else if (*p == 'p') {
3987 strcpy (d, pid_buf);
3990 } else if (*p == '%') {
4003 add_to_fd_set (fd_set *set, int fd, int *max_fd)
4006 * This should only trigger for the basic FDs (server socket, pipes) at
4007 * startup if for some mysterious reason they're too large. In this case,
4008 * the profiler really can't function, and we're better off printing an
4009 * error and exiting.
4011 if (fd >= FD_SETSIZE) {
4012 fprintf (stderr, "File descriptor is out of bounds for fd_set: %d\n", fd);
4023 helper_thread (void *arg)
4025 MonoProfiler *prof = (MonoProfiler *) arg;
4027 mono_threads_attach_tools_thread ();
4028 mono_native_thread_set_name (mono_native_thread_id_get (), "Profiler helper");
4030 MonoProfilerThread *thread = init_thread (prof, FALSE);
4032 GArray *command_sockets = g_array_new (FALSE, FALSE, sizeof (int));
4040 add_to_fd_set (&rfds, prof->server_socket, &max_fd);
4041 add_to_fd_set (&rfds, prof->pipes [0], &max_fd);
4043 for (gint i = 0; i < command_sockets->len; i++)
4044 add_to_fd_set (&rfds, g_array_index (command_sockets, int, i), &max_fd);
4046 struct timeval tv = { .tv_sec = 1, .tv_usec = 0 };
4048 // Sleep for 1sec or until a file descriptor has data.
4049 if (select (max_fd + 1, &rfds, NULL, NULL, &tv) == -1) {
4053 fprintf (stderr, "Error in mono-profiler-log server: %s", strerror (errno));
4058 counters_and_perfcounters_sample (prof);
4060 buffer_lock_excl ();
4062 sync_point (SYNC_POINT_PERIODIC);
4064 buffer_unlock_excl ();
4066 // Are we shutting down?
4067 if (FD_ISSET (prof->pipes [0], &rfds)) {
4069 read (prof->pipes [0], &c, 1);
4073 for (gint i = 0; i < command_sockets->len; i++) {
4074 int fd = g_array_index (command_sockets, int, i);
4076 if (!FD_ISSET (fd, &rfds))
4080 int len = read (fd, buf, sizeof (buf) - 1);
4086 // The other end disconnected.
4087 g_array_remove_index (command_sockets, i);
4095 if (!strcmp (buf, "heapshot\n") && hs_mode_ondemand) {
4096 // Rely on the finalization callback triggering a GC.
4097 heapshot_requested = 1;
4098 mono_gc_finalize_notify ();
4102 if (FD_ISSET (prof->server_socket, &rfds)) {
4103 int fd = accept (prof->server_socket, NULL, NULL);
4106 if (fd >= FD_SETSIZE)
4109 g_array_append_val (command_sockets, fd);
4114 for (gint i = 0; i < command_sockets->len; i++)
4115 close (g_array_index (command_sockets, int, i));
4117 g_array_free (command_sockets, TRUE);
4119 send_log_unsafe (FALSE);
4120 deinit_thread (thread);
4122 mono_thread_info_detach ();
4128 start_helper_thread (MonoProfiler* prof)
4130 if (pipe (prof->pipes) == -1) {
4131 fprintf (stderr, "Cannot create pipe: %s\n", strerror (errno));
4135 prof->server_socket = socket (PF_INET, SOCK_STREAM, 0);
4137 if (prof->server_socket == -1) {
4138 fprintf (stderr, "Cannot create server socket: %s\n", strerror (errno));
4142 struct sockaddr_in server_address;
4144 memset (&server_address, 0, sizeof (server_address));
4145 server_address.sin_family = AF_INET;
4146 server_address.sin_addr.s_addr = INADDR_ANY;
4147 server_address.sin_port = htons (prof->command_port);
4149 if (bind (prof->server_socket, (struct sockaddr *) &server_address, sizeof (server_address)) == -1) {
4150 fprintf (stderr, "Cannot bind server socket on port %d: %s\n", prof->command_port, strerror (errno));
4151 close (prof->server_socket);
4155 if (listen (prof->server_socket, 1) == -1) {
4156 fprintf (stderr, "Cannot listen on server socket: %s\n", strerror (errno));
4157 close (prof->server_socket);
4161 socklen_t slen = sizeof (server_address);
4163 if (getsockname (prof->server_socket, (struct sockaddr *) &server_address, &slen)) {
4164 fprintf (stderr, "Could not get assigned port: %s\n", strerror (errno));
4165 close (prof->server_socket);
4169 prof->command_port = ntohs (server_address.sin_port);
4171 if (!mono_native_thread_create (&prof->helper_thread, helper_thread, prof)) {
4172 fprintf (stderr, "Could not start helper thread\n");
4173 close (prof->server_socket);
4179 free_writer_entry (gpointer p)
4181 mono_lock_free_free (p, WRITER_ENTRY_BLOCK_SIZE);
4185 handle_writer_queue_entry (MonoProfiler *prof)
4187 WriterQueueEntry *entry;
4189 if ((entry = (WriterQueueEntry *) mono_lock_free_queue_dequeue (&prof->writer_queue))) {
4190 if (!entry->methods)
4193 gboolean wrote_methods = FALSE;
4196 * Encode the method events in a temporary log buffer that we
4197 * flush to disk before the main buffer, ensuring that all
4198 * methods have metadata emitted before they're referenced.
4200 * We use a 'proper' thread-local buffer for this as opposed
4201 * to allocating and freeing a buffer by hand because the call
4202 * to mono_method_full_name () below may trigger class load
4203 * events when it retrieves the signature of the method. So a
4204 * thread-local buffer needs to exist when such events occur.
4206 for (guint i = 0; i < entry->methods->len; i++) {
4207 MethodInfo *info = (MethodInfo *) g_ptr_array_index (entry->methods, i);
4209 if (mono_conc_hashtable_lookup (prof->method_table, info->method))
4210 goto free_info; // This method already has metadata emitted.
4213 * Other threads use this hash table to get a general
4214 * idea of whether a method has already been emitted to
4215 * the stream. Due to the way we add to this table, it
4216 * can easily happen that multiple threads queue up the
4217 * same methods, but that's OK since eventually all
4218 * methods will be in this table and the thread-local
4219 * method lists will just be empty for the rest of the
4222 mono_os_mutex_lock (&prof->method_table_mutex);
4223 mono_conc_hashtable_insert (prof->method_table, info->method, info->method);
4224 mono_os_mutex_unlock (&prof->method_table_mutex);
4226 char *name = mono_method_full_name (info->method, 1);
4227 int nlen = strlen (name) + 1;
4228 void *cstart = info->ji ? mono_jit_info_get_code_start (info->ji) : NULL;
4229 int csize = info->ji ? mono_jit_info_get_code_size (info->ji) : 0;
4231 ENTER_LOG (&method_jits_ctr, logbuffer,
4232 EVENT_SIZE /* event */ +
4233 LEB128_SIZE /* method */ +
4234 LEB128_SIZE /* start */ +
4235 LEB128_SIZE /* size */ +
4239 emit_event_time (logbuffer, TYPE_JIT | TYPE_METHOD, info->time);
4240 emit_method_inner (logbuffer, info->method);
4241 emit_ptr (logbuffer, cstart);
4242 emit_value (logbuffer, csize);
4244 memcpy (logbuffer->cursor, name, nlen);
4245 logbuffer->cursor += nlen;
4247 EXIT_LOG_EXPLICIT (NO_SEND);
4251 wrote_methods = TRUE;
4257 g_ptr_array_free (entry->methods, TRUE);
4259 if (wrote_methods) {
4260 dump_buffer_threadless (prof, PROF_TLS_GET ()->buffer);
4261 init_buffer_state (PROF_TLS_GET ());
4265 dump_buffer (prof, entry->buffer);
4267 mono_thread_hazardous_try_free (entry, free_writer_entry);
4276 writer_thread (void *arg)
4278 MonoProfiler *prof = (MonoProfiler *)arg;
4280 mono_threads_attach_tools_thread ();
4281 mono_native_thread_set_name (mono_native_thread_id_get (), "Profiler writer");
4285 MonoProfilerThread *thread = init_thread (prof, FALSE);
4287 while (InterlockedRead (&prof->run_writer_thread)) {
4288 mono_os_sem_wait (&prof->writer_queue_sem, MONO_SEM_FLAGS_NONE);
4289 handle_writer_queue_entry (prof);
4292 /* Drain any remaining entries on shutdown. */
4293 while (handle_writer_queue_entry (prof));
4295 free_buffer (thread->buffer, thread->buffer->size);
4296 deinit_thread (thread);
4298 mono_thread_info_detach ();
4304 start_writer_thread (MonoProfiler* prof)
4306 InterlockedWrite (&prof->run_writer_thread, 1);
4308 if (!mono_native_thread_create (&prof->writer_thread, writer_thread, prof)) {
4309 fprintf (stderr, "Could not start writer thread\n");
4315 reuse_sample_hit (gpointer p)
4317 SampleHit *sample = p;
4319 mono_lock_free_queue_node_unpoison (&sample->node);
4320 mono_lock_free_queue_enqueue (&sample->prof->sample_reuse_queue, &sample->node);
4324 handle_dumper_queue_entry (MonoProfiler *prof)
4328 if ((sample = (SampleHit *) mono_lock_free_queue_dequeue (&prof->dumper_queue))) {
4329 for (int i = 0; i < sample->count; ++i) {
4330 MonoMethod *method = sample->frames [i].method;
4331 MonoDomain *domain = sample->frames [i].domain;
4332 void *address = sample->frames [i].base_address;
4335 g_assert (domain && "What happened to the domain pointer?");
4336 g_assert (address && "What happened to the instruction pointer?");
4338 MonoJitInfo *ji = mono_jit_info_table_find (domain, (char *) address);
4341 sample->frames [i].method = mono_jit_info_get_method (ji);
4345 ENTER_LOG (&sample_hits_ctr, logbuffer,
4346 EVENT_SIZE /* event */ +
4347 BYTE_SIZE /* type */ +
4348 LEB128_SIZE /* tid */ +
4349 LEB128_SIZE /* count */ +
4351 LEB128_SIZE /* ip */
4353 LEB128_SIZE /* managed count */ +
4355 LEB128_SIZE /* method */
4359 emit_event_time (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_HIT, sample->time);
4360 emit_byte (logbuffer, SAMPLE_CYCLES);
4361 emit_ptr (logbuffer, (void *) sample->tid);
4362 emit_value (logbuffer, 1);
4364 // TODO: Actual native unwinding.
4365 for (int i = 0; i < 1; ++i) {
4366 emit_ptr (logbuffer, sample->ip);
4367 add_code_pointer ((uintptr_t) sample->ip);
4370 /* new in data version 6 */
4371 emit_uvalue (logbuffer, sample->count);
4373 for (int i = 0; i < sample->count; ++i)
4374 emit_method (logbuffer, sample->frames [i].method);
4376 EXIT_LOG_EXPLICIT (DO_SEND);
4378 mono_thread_hazardous_try_free (sample, reuse_sample_hit);
4380 dump_unmanaged_coderefs (prof);
4387 dumper_thread (void *arg)
4389 MonoProfiler *prof = (MonoProfiler *)arg;
4391 mono_threads_attach_tools_thread ();
4392 mono_native_thread_set_name (mono_native_thread_id_get (), "Profiler dumper");
4394 MonoProfilerThread *thread = init_thread (prof, FALSE);
4396 while (InterlockedRead (&prof->run_dumper_thread)) {
4397 mono_os_sem_wait (&prof->dumper_queue_sem, MONO_SEM_FLAGS_NONE);
4398 handle_dumper_queue_entry (prof);
4401 /* Drain any remaining entries on shutdown. */
4402 while (handle_dumper_queue_entry (prof));
4404 send_log_unsafe (FALSE);
4405 deinit_thread (thread);
4407 mono_thread_info_detach ();
4413 start_dumper_thread (MonoProfiler* prof)
4415 InterlockedWrite (&prof->run_dumper_thread, 1);
4417 if (!mono_native_thread_create (&prof->dumper_thread, dumper_thread, prof)) {
4418 fprintf (stderr, "Could not start dumper thread\n");
4424 register_counter (const char *name, gint32 *counter)
4426 mono_counters_register (name, MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, counter);
4430 runtime_initialized (MonoProfiler *profiler)
4432 InterlockedWrite (&runtime_inited, 1);
4434 register_counter ("Sample events allocated", &sample_allocations_ctr);
4435 register_counter ("Log buffers allocated", &buffer_allocations_ctr);
4437 register_counter ("Event: Sync points", &sync_points_ctr);
4438 register_counter ("Event: Heap objects", &heap_objects_ctr);
4439 register_counter ("Event: Heap starts", &heap_starts_ctr);
4440 register_counter ("Event: Heap ends", &heap_ends_ctr);
4441 register_counter ("Event: Heap roots", &heap_roots_ctr);
4442 register_counter ("Event: GC events", &gc_events_ctr);
4443 register_counter ("Event: GC resizes", &gc_resizes_ctr);
4444 register_counter ("Event: GC allocations", &gc_allocs_ctr);
4445 register_counter ("Event: GC moves", &gc_moves_ctr);
4446 register_counter ("Event: GC handle creations", &gc_handle_creations_ctr);
4447 register_counter ("Event: GC handle deletions", &gc_handle_deletions_ctr);
4448 register_counter ("Event: GC finalize starts", &finalize_begins_ctr);
4449 register_counter ("Event: GC finalize ends", &finalize_ends_ctr);
4450 register_counter ("Event: GC finalize object starts", &finalize_object_begins_ctr);
4451 register_counter ("Event: GC finalize object ends", &finalize_object_ends_ctr);
4452 register_counter ("Event: Image loads", &image_loads_ctr);
4453 register_counter ("Event: Image unloads", &image_unloads_ctr);
4454 register_counter ("Event: Assembly loads", &assembly_loads_ctr);
4455 register_counter ("Event: Assembly unloads", &assembly_unloads_ctr);
4456 register_counter ("Event: Class loads", &class_loads_ctr);
4457 register_counter ("Event: Class unloads", &class_unloads_ctr);
4458 register_counter ("Event: Method entries", &method_entries_ctr);
4459 register_counter ("Event: Method exits", &method_exits_ctr);
4460 register_counter ("Event: Method exception leaves", &method_exception_exits_ctr);
4461 register_counter ("Event: Method JITs", &method_jits_ctr);
4462 register_counter ("Event: Code buffers", &code_buffers_ctr);
4463 register_counter ("Event: Exception throws", &exception_throws_ctr);
4464 register_counter ("Event: Exception clauses", &exception_clauses_ctr);
4465 register_counter ("Event: Monitor contentions", &monitor_contentions_ctr);
4466 register_counter ("Event: Monitor acquisitions", &monitor_acquisitions_ctr);
4467 register_counter ("Event: Monitor failures", &monitor_failures_ctr);
4468 register_counter ("Event: Thread starts", &thread_starts_ctr);
4469 register_counter ("Event: Thread ends", &thread_ends_ctr);
4470 register_counter ("Event: Thread names", &thread_names_ctr);
4471 register_counter ("Event: Domain loads", &domain_loads_ctr);
4472 register_counter ("Event: Domain unloads", &domain_unloads_ctr);
4473 register_counter ("Event: Domain names", &domain_names_ctr);
4474 register_counter ("Event: Context loads", &context_loads_ctr);
4475 register_counter ("Event: Context unloads", &context_unloads_ctr);
4476 register_counter ("Event: Sample binaries", &sample_ubins_ctr);
4477 register_counter ("Event: Sample symbols", &sample_usyms_ctr);
4478 register_counter ("Event: Sample hits", &sample_hits_ctr);
4479 register_counter ("Event: Counter descriptors", &counter_descriptors_ctr);
4480 register_counter ("Event: Counter samples", &counter_samples_ctr);
4481 register_counter ("Event: Performance counter descriptors", &perfcounter_descriptors_ctr);
4482 register_counter ("Event: Performance counter samples", &perfcounter_samples_ctr);
4483 register_counter ("Event: Coverage methods", &coverage_methods_ctr);
4484 register_counter ("Event: Coverage statements", &coverage_statements_ctr);
4485 register_counter ("Event: Coverage classes", &coverage_classes_ctr);
4486 register_counter ("Event: Coverage assemblies", &coverage_assemblies_ctr);
4488 counters_init (profiler);
4491 * We must start the helper thread before the writer thread. This is
4492 * because the helper thread sets up the command port which is written to
4493 * the log header by the writer thread.
4495 start_helper_thread (profiler);
4496 start_writer_thread (profiler);
4497 start_dumper_thread (profiler);
4500 static MonoProfiler*
4501 create_profiler (const char *args, const char *filename, GPtrArray *filters)
4505 int force_delete = 0;
4506 prof = (MonoProfiler *) g_calloc (1, sizeof (MonoProfiler));
4508 prof->args = pstrdup (args);
4509 prof->command_port = command_port;
4510 if (filename && *filename == '-') {
4513 g_warning ("WARNING: the output:-FILENAME option is deprecated, the profiler now always overrides the output file\n");
4517 filename = "|mprof-report -";
4519 filename = "output.mlpd";
4520 nf = (char*)filename;
4522 nf = new_filename (filename);
4524 int s = strlen (nf) + 32;
4525 char *p = (char *) g_malloc (s);
4526 snprintf (p, s, "|mprof-report '--out=%s' -", nf);
4532 prof->file = popen (nf + 1, "w");
4533 prof->pipe_output = 1;
4534 } else if (*nf == '#') {
4535 int fd = strtol (nf + 1, NULL, 10);
4536 prof->file = fdopen (fd, "a");
4540 prof->file = fopen (nf, "wb");
4543 fprintf (stderr, "Cannot create profiler output: %s\n", nf);
4547 #if defined (HAVE_SYS_ZLIB)
4549 prof->gzfile = gzdopen (fileno (prof->file), "wb");
4553 * If you hit this assert while increasing MAX_FRAMES, you need to increase
4554 * SAMPLE_BLOCK_SIZE as well.
4556 g_assert (SAMPLE_SLOT_SIZE (MAX_FRAMES) * 2 < LOCK_FREE_ALLOC_SB_USABLE_SIZE (SAMPLE_BLOCK_SIZE));
4558 // FIXME: We should free this stuff too.
4559 mono_lock_free_allocator_init_size_class (&prof->sample_size_class, SAMPLE_SLOT_SIZE (num_frames), SAMPLE_BLOCK_SIZE);
4560 mono_lock_free_allocator_init_allocator (&prof->sample_allocator, &prof->sample_size_class, MONO_MEM_ACCOUNT_PROFILER);
4562 mono_lock_free_queue_init (&prof->sample_reuse_queue);
4564 g_assert (sizeof (WriterQueueEntry) * 2 < LOCK_FREE_ALLOC_SB_USABLE_SIZE (WRITER_ENTRY_BLOCK_SIZE));
4566 // FIXME: We should free this stuff too.
4567 mono_lock_free_allocator_init_size_class (&prof->writer_entry_size_class, sizeof (WriterQueueEntry), WRITER_ENTRY_BLOCK_SIZE);
4568 mono_lock_free_allocator_init_allocator (&prof->writer_entry_allocator, &prof->writer_entry_size_class, MONO_MEM_ACCOUNT_PROFILER);
4570 mono_lock_free_queue_init (&prof->writer_queue);
4571 mono_os_sem_init (&prof->writer_queue_sem, 0);
4573 mono_lock_free_queue_init (&prof->dumper_queue);
4574 mono_os_sem_init (&prof->dumper_queue_sem, 0);
4576 mono_os_mutex_init (&prof->method_table_mutex);
4577 prof->method_table = mono_conc_hashtable_new (NULL, NULL);
4580 coverage_init (prof);
4581 prof->coverage_filters = filters;
4583 prof->startup_time = current_time ();
4588 * declaration to silence the compiler: this is the entry point that
4589 * mono will load from the shared library and call.
4592 mono_profiler_startup (const char *desc);
4595 mono_profiler_startup_log (const char *desc);
4598 * this is the entry point that will be used when the profiler
4599 * is embedded inside the main executable.
4602 mono_profiler_startup_log (const char *desc)
4604 mono_profiler_startup (desc);
4608 mono_profiler_startup (const char *desc)
4610 GPtrArray *filters = NULL;
4613 proflog_parse_args (&config, desc [3] == ':' ? desc + 4 : "");
4615 //XXX maybe later cleanup to use config directly
4616 nocalls = !(config.effective_mask & PROFLOG_CALL_EVENTS);
4617 no_counters = !(config.effective_mask & PROFLOG_COUNTER_EVENTS);
4618 do_report = config.do_report;
4619 do_debug = config.do_debug;
4620 do_heap_shot = (config.effective_mask & PROFLOG_HEAPSHOT_FEATURE);
4621 hs_mode_ondemand = config.hs_mode_ondemand;
4622 hs_mode_ms = config.hs_mode_ms;
4623 hs_mode_gc = config.hs_mode_gc;
4624 do_mono_sample = (config.effective_mask & PROFLOG_SAMPLING_FEATURE);
4625 use_zip = config.use_zip;
4626 command_port = config.command_port;
4627 num_frames = config.num_frames;
4628 notraces = config.notraces;
4629 max_allocated_sample_hits = config.max_allocated_sample_hits;
4630 max_call_depth = config.max_call_depth;
4631 do_coverage = (config.effective_mask & PROFLOG_CODE_COV_FEATURE);
4632 debug_coverage = config.debug_coverage;
4633 only_coverage = config.only_coverage;
4635 if (config.cov_filter_files) {
4636 filters = g_ptr_array_new ();
4638 for (i = 0; i < config.cov_filter_files->len; ++i) {
4639 const char *name = config.cov_filter_files->pdata [i];
4640 parse_cov_filter_file (filters, name);
4648 prof = create_profiler (desc, config.output_filename, filters);
4654 mono_lls_init (&profiler_thread_list, NULL);
4656 init_thread (prof, TRUE);
4658 //This two events are required for the profiler to work
4659 int events = MONO_PROFILE_THREADS | MONO_PROFILE_GC;
4661 //Required callbacks
4662 mono_profiler_install (prof, log_shutdown);
4663 mono_profiler_install_runtime_initialized (runtime_initialized);
4665 mono_profiler_install_gc (gc_event, gc_resize);
4666 mono_profiler_install_thread (thread_start, thread_end);
4668 //It's questionable whether we actually want this to be mandatory, maybe put it behind the actual event?
4669 mono_profiler_install_thread_name (thread_name);
4672 if (config.effective_mask & PROFLOG_DOMAIN_EVENTS) {
4673 events |= MONO_PROFILE_APPDOMAIN_EVENTS;
4674 mono_profiler_install_appdomain (NULL, domain_loaded, domain_unloaded, NULL);
4675 mono_profiler_install_appdomain_name (domain_name);
4678 if (config.effective_mask & PROFLOG_ASSEMBLY_EVENTS) {
4679 events |= MONO_PROFILE_ASSEMBLY_EVENTS;
4680 mono_profiler_install_assembly (NULL, assembly_loaded, assembly_unloaded, NULL);
4683 if (config.effective_mask & PROFLOG_MODULE_EVENTS) {
4684 events |= MONO_PROFILE_MODULE_EVENTS;
4685 mono_profiler_install_module (NULL, image_loaded, image_unloaded, NULL);
4688 if (config.effective_mask & PROFLOG_CLASS_EVENTS) {
4689 events |= MONO_PROFILE_CLASS_EVENTS;
4690 mono_profiler_install_class (NULL, class_loaded, class_unloaded, NULL);
4693 if (config.effective_mask & PROFLOG_JIT_COMPILATION_EVENTS) {
4694 events |= MONO_PROFILE_JIT_COMPILATION;
4695 mono_profiler_install_jit_end (method_jitted);
4696 mono_profiler_install_code_buffer_new (code_buffer_new);
4699 if (config.effective_mask & PROFLOG_EXCEPTION_EVENTS) {
4700 events |= MONO_PROFILE_EXCEPTIONS;
4701 mono_profiler_install_exception (throw_exc, method_exc_leave, clause_exc);
4704 if (config.effective_mask & PROFLOG_ALLOCATION_EVENTS) {
4705 events |= MONO_PROFILE_ALLOCATIONS;
4706 mono_profiler_install_allocation (gc_alloc);
4709 //PROFLOG_GC_EVENTS is mandatory
4710 //PROFLOG_THREAD_EVENTS is mandatory
4712 if (config.effective_mask & PROFLOG_CALL_EVENTS) {
4713 events |= MONO_PROFILE_ENTER_LEAVE;
4714 mono_profiler_install_enter_leave (method_enter, method_leave);
4717 if (config.effective_mask & PROFLOG_INS_COVERAGE_EVENTS) {
4718 events |= MONO_PROFILE_INS_COVERAGE;
4719 mono_profiler_install_coverage_filter (coverage_filter);
4722 //XXX should we check for PROFLOG_SAMPLING_FEATURE instead??
4723 if (config.effective_mask & PROFLOG_SAMPLING_EVENTS) {
4724 events |= MONO_PROFILE_STATISTICAL;
4725 mono_profiler_set_statistical_mode (config.sampling_mode, config.sample_freq);
4726 mono_profiler_install_statistical (mono_sample_hit);
4729 if (config.effective_mask & PROFLOG_MONITOR_EVENTS) {
4730 events |= MONO_PROFILE_MONITOR_EVENTS;
4731 mono_profiler_install_monitor (monitor_event);
4734 if (config.effective_mask & PROFLOG_GC_MOVES_EVENTS) {
4735 events |= MONO_PROFILE_GC_MOVES;
4736 mono_profiler_install_gc_moves (gc_moves);
4739 // TODO split those in two profiler events
4740 if (config.effective_mask & (PROFLOG_GC_ROOT_EVENTS | PROFLOG_GC_HANDLE_EVENTS)) {
4741 events |= MONO_PROFILE_GC_ROOTS;
4742 mono_profiler_install_gc_roots (
4743 config.effective_mask & (PROFLOG_GC_HANDLE_EVENTS) ? gc_handle : NULL,
4744 (config.effective_mask & PROFLOG_GC_ROOT_EVENTS) ? gc_roots : NULL);
4747 if (config.effective_mask & PROFLOG_CONTEXT_EVENTS) {
4748 events |= MONO_PROFILE_CONTEXT_EVENTS;
4749 mono_profiler_install_context (context_loaded, context_unloaded);
4752 if (config.effective_mask & PROFLOG_FINALIZATION_EVENTS) {
4753 events |= MONO_PROFILE_GC_FINALIZATION;
4754 mono_profiler_install_gc_finalize (finalize_begin, finalize_object_begin, finalize_object_end, finalize_end);
4755 } else if (ENABLED (PROFLOG_HEAPSHOT_FEATURE) && config.hs_mode_ondemand) {
4756 //On Demand heapshot uses the finalizer thread to force a collection and thus a heapshot
4757 events |= MONO_PROFILE_GC_FINALIZATION;
4758 mono_profiler_install_gc_finalize (NULL, NULL, NULL, finalize_end);
4761 //PROFLOG_COUNTER_EVENTS is a pseudo event controled by the no_counters global var
4762 //PROFLOG_GC_HANDLE_EVENTS is handled together with PROFLOG_GC_ROOT_EVENTS
4764 mono_profiler_set_events ((MonoProfileFlags)events);