2 * proflog.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 "../mini/jit.h"
15 #include "../metadata/metadata-internals.h"
16 #include <mono/metadata/profiler.h>
17 #include <mono/metadata/threads.h>
18 #include <mono/metadata/mono-gc.h>
19 #include <mono/metadata/debug-helpers.h>
20 #include <mono/metadata/mono-gc.h>
21 #include <mono/metadata/mono-perfcounters.h>
22 #include <mono/metadata/appdomain.h>
23 #include <mono/metadata/assembly.h>
24 #include <mono/metadata/tokentype.h>
25 #include <mono/metadata/tabledefs.h>
26 #include <mono/utils/atomic.h>
27 #include <mono/utils/mono-membar.h>
28 #include <mono/utils/mono-mmap.h>
29 #include <mono/utils/mono-counters.h>
30 #include <mono/utils/mono-os-mutex.h>
31 #include <mono/utils/mono-os-semaphore.h>
32 #include <mono/utils/mono-conc-hashtable.h>
33 #include <mono/utils/mono-linked-list-set.h>
34 #include <mono/utils/lock-free-alloc.h>
35 #include <mono/utils/lock-free-queue.h>
36 #include <mono/utils/hazard-pointer.h>
37 #include <mono/utils/mono-threads.h>
38 #include <mono/utils/mono-threads-api.h>
46 #ifdef HAVE_SCHED_GETAFFINITY
51 #if defined(HOST_WIN32) || defined(DISABLE_SOCKETS)
52 #define DISABLE_HELPER_THREAD 1
61 #ifdef HAVE_EXECINFO_H
68 #ifndef DISABLE_HELPER_THREAD
69 #include <sys/types.h>
70 #include <sys/socket.h>
71 #include <netinet/in.h>
72 #include <sys/select.h>
81 #ifdef HAVE_SYS_STAT_H
88 #if defined (HAVE_SYS_ZLIB)
92 #if defined(__linux__)
95 #include <sys/syscall.h>
97 #ifdef ENABLE_PERF_EVENTS
98 #include <linux/perf_event.h>
100 #define USE_PERF_EVENTS 1
102 static int read_perf_mmap (MonoProfiler* prof, int cpu);
107 #define BUFFER_SIZE (4096 * 16)
109 /* Worst-case size in bytes of a 64-bit value encoded with LEB128. */
110 #define LEB128_SIZE 10
111 /* Size of a value encoded as a single byte. */
113 /* Size in bytes of the event prefix (ID + time). */
114 #define EVENT_SIZE (BYTE_SIZE + LEB128_SIZE)
116 static int nocalls = 0;
117 static int notraces = 0;
118 static int use_zip = 0;
119 static int do_report = 0;
120 static int do_heap_shot = 0;
121 static int max_call_depth = 100;
122 static volatile int runtime_inited = 0;
123 static int need_helper_thread = 0;
124 static int command_port = 0;
125 static int heapshot_requested = 0;
126 static int sample_type = 0;
127 static int sample_freq = 0;
128 static int do_mono_sample = 0;
129 static int in_shutdown = 0;
130 static int do_debug = 0;
131 static int do_counters = 0;
132 static int do_coverage = 0;
133 static gboolean debug_coverage = FALSE;
134 static MonoProfileSamplingMode sampling_mode = MONO_PROFILER_STAT_MODE_PROCESS;
135 static int max_allocated_sample_hits;
137 static gint32 sample_hits;
138 static gint32 sample_flushes;
139 static gint32 sample_allocations;
140 static gint32 buffer_allocations;
141 static gint32 thread_starts;
142 static gint32 thread_ends;
143 static gint32 domain_loads;
144 static gint32 domain_unloads;
145 static gint32 context_loads;
146 static gint32 context_unloads;
147 static gint32 assembly_loads;
148 static gint32 assembly_unloads;
149 static gint32 image_loads;
150 static gint32 image_unloads;
151 static gint32 class_loads;
152 static gint32 class_unloads;
154 static MonoLinkedListSet profiler_thread_list;
160 * The file is composed by a header followed by 0 or more buffers.
161 * Each buffer contains events that happened on a thread: for a given thread
162 * buffers that appear later in the file are guaranteed to contain events
163 * that happened later in time. Buffers from separate threads could be interleaved,
165 * Buffers are not required to be aligned.
168 * [id: 4 bytes] constant value: LOG_HEADER_ID
169 * [major: 1 byte] [minor: 1 byte] major and minor version of the log profiler
170 * [format: 1 byte] version of the data format for the rest of the file
171 * [ptrsize: 1 byte] size in bytes of a pointer in the profiled program
172 * [startup time: 8 bytes] time in milliseconds since the unix epoch when the program started
173 * [timer overhead: 4 bytes] approximate overhead in nanoseconds of the timer
174 * [flags: 4 bytes] file format flags, should be 0 for now
175 * [pid: 4 bytes] pid of the profiled process
176 * [port: 2 bytes] tcp port for server if != 0
177 * [sysid: 2 bytes] operating system and architecture identifier
179 * The multiple byte integers are in little-endian format.
182 * [buffer header] [event]*
183 * Buffers have a fixed-size header followed by 0 or more bytes of event data.
184 * Timing information and other values in the event data are usually stored
185 * as uleb128 or sleb128 integers. To save space, as noted for each item below,
186 * some data is represented as a difference between the actual value and
187 * either the last value of the same type (like for timing information) or
188 * as the difference from a value stored in a buffer header.
190 * For timing information the data is stored as uleb128, since timing
191 * increases in a monotonic way in each thread: the value is the number of
192 * nanoseconds to add to the last seen timing data in a buffer. The first value
193 * in a buffer will be calculated from the time_base field in the buffer head.
195 * Object or heap sizes are stored as uleb128.
196 * Pointer differences are stored as sleb128, instead.
198 * If an unexpected value is found, the rest of the buffer should be ignored,
199 * as generally the later values need the former to be interpreted correctly.
201 * buffer header format:
202 * [bufid: 4 bytes] constant value: BUF_ID
203 * [len: 4 bytes] size of the data following the buffer header
204 * [time_base: 8 bytes] time base in nanoseconds since an unspecified epoch
205 * [ptr_base: 8 bytes] base value for pointers
206 * [obj_base: 8 bytes] base value for object addresses
207 * [thread id: 8 bytes] system-specific thread ID (pthread_t for example)
208 * [method_base: 8 bytes] base value for MonoMethod pointers
211 * [extended info: upper 4 bits] [type: lower 4 bits] [data]*
212 * The data that follows depends on type and the extended info.
213 * Type is one of the enum values in proflog.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]* num MonoMethod pointers as differences from ptr_base
225 * exinfo: flags: TYPE_ALLOC_BT
226 * [time diff: uleb128] nanoseconds since last timing
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 * [time diff: uleb128] nanoseconds since last timing
238 * if exinfo == TYPE_GC_RESIZE
239 * [heap_size: uleb128] new heap size
240 * if exinfo == TYPE_GC_EVENT
241 * [event type: byte] GC event (MONO_GC_EVENT_* from profiler.h)
242 * [generation: byte] GC generation event refers to
243 * if exinfo == TYPE_GC_MOVE
244 * [num_objects: uleb128] number of object moves that follow
245 * [objaddr: sleb128]+ num_objects object pointer differences from obj_base
246 * num is always an even number: the even items are the old
247 * addresses, the odd numbers are the respective new object addresses
248 * if exinfo == TYPE_GC_HANDLE_CREATED[_BT]
249 * [handle_type: uleb128] GC handle type (System.Runtime.InteropServices.GCHandleType)
250 * upper bits reserved as flags
251 * [handle: uleb128] GC handle value
252 * [objaddr: sleb128] object pointer differences from obj_base
253 * If exinfo == TYPE_GC_HANDLE_CREATED_BT, a backtrace follows.
254 * if exinfo == TYPE_GC_HANDLE_DESTROYED[_BT]
255 * [handle_type: uleb128] GC handle type (System.Runtime.InteropServices.GCHandleType)
256 * upper bits reserved as flags
257 * [handle: uleb128] GC handle value
258 * If exinfo == TYPE_GC_HANDLE_DESTROYED_BT, a backtrace follows.
259 * if exinfo == TYPE_GC_FINALIZE_OBJECT_{START,END}
260 * [object: sleb128] the object as a difference from obj_base
262 * type metadata format:
263 * type: TYPE_METADATA
264 * exinfo: one of: TYPE_END_LOAD, TYPE_END_UNLOAD (optional for TYPE_THREAD and TYPE_DOMAIN)
265 * [time diff: uleb128] nanoseconds since last timing
266 * [mtype: byte] metadata type, one of: TYPE_CLASS, TYPE_IMAGE, TYPE_ASSEMBLY, TYPE_DOMAIN,
267 * TYPE_THREAD, TYPE_CONTEXT
268 * [pointer: sleb128] pointer of the metadata type depending on mtype
269 * if mtype == TYPE_CLASS
270 * [image: sleb128] MonoImage* as a pointer difference from ptr_base
271 * [name: string] full class name
272 * if mtype == TYPE_IMAGE
273 * [name: string] image file name
274 * if mtype == TYPE_ASSEMBLY
275 * [name: string] assembly name
276 * if mtype == TYPE_DOMAIN && exinfo == 0
277 * [name: string] domain friendly name
278 * if mtype == TYPE_CONTEXT
279 * [domain: sleb128] domain id as pointer
280 * if mtype == TYPE_THREAD && exinfo == 0
281 * [name: string] thread name
283 * type method format:
285 * exinfo: one of: TYPE_LEAVE, TYPE_ENTER, TYPE_EXC_LEAVE, TYPE_JIT
286 * [time diff: uleb128] nanoseconds since last timing
287 * [method: sleb128] MonoMethod* as a pointer difference from the last such
288 * pointer or the buffer method_base
289 * if exinfo == TYPE_JIT
290 * [code address: sleb128] pointer to the native code as a diff from ptr_base
291 * [code size: uleb128] size of the generated code
292 * [name: string] full method name
294 * type runtime format:
296 * exinfo: one of: TYPE_JITHELPER
297 * [time diff: uleb128] nanoseconds since last timing
298 * if exinfo == TYPE_JITHELPER
299 * [type: byte] MonoProfilerCodeBufferType enum value
300 * [buffer address: sleb128] pointer to the native code as a diff from ptr_base
301 * [buffer size: uleb128] size of the generated code
302 * if type == MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE
303 * [name: string] buffer description name
305 * type monitor format:
307 * exinfo: TYPE_MONITOR_BT flag and one of: MONO_PROFILER_MONITOR_(CONTENTION|FAIL|DONE)
308 * [time diff: uleb128] nanoseconds since last timing
309 * [object: sleb128] the lock object as a difference from obj_base
310 * if exinfo.low3bits == MONO_PROFILER_MONITOR_CONTENTION
311 * If the TYPE_MONITOR_BT flag is set, a backtrace follows.
315 * exinfo: one of TYPE_HEAP_START, TYPE_HEAP_END, TYPE_HEAP_OBJECT, TYPE_HEAP_ROOT
316 * if exinfo == TYPE_HEAP_START
317 * [time diff: uleb128] nanoseconds since last timing
318 * if exinfo == TYPE_HEAP_END
319 * [time diff: uleb128] nanoseconds since last timing
320 * if exinfo == TYPE_HEAP_OBJECT
321 * [object: sleb128] the object as a difference from obj_base
322 * [class: sleb128] the object MonoClass* as a difference from ptr_base
323 * [size: uleb128] size of the object on the heap
324 * [num_refs: uleb128] number of object references
325 * each referenced objref is preceded by a uleb128 encoded offset: the
326 * first offset is from the object address and each next offset is relative
327 * to the previous one
328 * [objrefs: sleb128]+ object referenced as a difference from obj_base
329 * The same object can appear multiple times, but only the first time
330 * with size != 0: in the other cases this data will only be used to
331 * provide additional referenced objects.
332 * if exinfo == TYPE_HEAP_ROOT
333 * [num_roots: uleb128] number of root references
334 * [num_gc: uleb128] number of major gcs
335 * [object: sleb128] the object as a difference from obj_base
336 * [root_type: byte] the root_type: MonoProfileGCRootType (profiler.h)
337 * [extra_info: uleb128] the extra_info value
338 * object, root_type and extra_info are repeated num_roots times
342 * exinfo: one of TYPE_SAMPLE_HIT, TYPE_SAMPLE_USYM, TYPE_SAMPLE_UBIN, TYPE_SAMPLE_COUNTERS_DESC, TYPE_SAMPLE_COUNTERS
343 * if exinfo == TYPE_SAMPLE_HIT
344 * [sample_type: byte] type of sample (SAMPLE_*)
345 * [timestamp: uleb128] nanoseconds since startup (note: different from other timestamps!)
346 * [thread: sleb128] thread id as difference from ptr_base
347 * [count: uleb128] number of following instruction addresses
348 * [ip: sleb128]* instruction pointer as difference from ptr_base
349 * [mbt_count: uleb128] number of managed backtrace frames
350 * [method: sleb128]* MonoMethod* as a pointer difference from the last such
351 * pointer or the buffer method_base (the first such method can be also indentified by ip, but this is not neccessarily true)
352 * if exinfo == TYPE_SAMPLE_USYM
353 * [address: sleb128] symbol address as a difference from ptr_base
354 * [size: uleb128] symbol size (may be 0 if unknown)
355 * [name: string] symbol name
356 * if exinfo == TYPE_SAMPLE_UBIN
357 * [time diff: uleb128] nanoseconds since last timing
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
374 * [timestamp: uleb128] sampling timestamp
376 * [index: uleb128] unique index of counter
379 * [type: byte] type of counter value
382 * [0: uleb128] 0 -> value is null
384 * [1: uleb128] 1 -> value is not null
385 * [value: string] counter value
387 * [value: uleb128/sleb128/double] counter value, can be sleb128, uleb128 or double (determined by using type)
389 * type coverage format
390 * type: TYPE_COVERAGE
391 * exinfo: one of TYPE_COVERAGE_METHOD, TYPE_COVERAGE_STATEMENT, TYPE_COVERAGE_ASSEMBLY, TYPE_COVERAGE_CLASS
392 * if exinfo == TYPE_COVERAGE_METHOD
393 * [assembly: string] name of assembly
394 * [class: string] name of the class
395 * [name: string] name of the method
396 * [signature: string] the signature of the method
397 * [filename: string] the file path of the file that contains this method
398 * [token: uleb128] the method token
399 * [method_id: uleb128] an ID for this data to associate with the buffers of TYPE_COVERAGE_STATEMENTS
400 * [len: uleb128] the number of TYPE_COVERAGE_BUFFERS associated with this method
401 * if exinfo == TYPE_COVERAGE_STATEMENTS
402 * [method_id: uleb128] an the TYPE_COVERAGE_METHOD buffer to associate this with
403 * [offset: uleb128] the il offset relative to the previous offset
404 * [counter: uleb128] the counter for this instruction
405 * [line: uleb128] the line of filename containing this instruction
406 * [column: uleb128] the column containing this instruction
407 * if exinfo == TYPE_COVERAGE_ASSEMBLY
408 * [name: string] assembly name
409 * [guid: string] assembly GUID
410 * [filename: string] assembly filename
411 * [number_of_methods: uleb128] the number of methods in this assembly
412 * [fully_covered: uleb128] the number of fully covered methods
413 * [partially_covered: uleb128] the number of partially covered methods
414 * currently partially_covered will always be 0, and fully_covered is the
415 * number of methods that are fully and partially covered.
416 * if exinfo == TYPE_COVERAGE_CLASS
417 * [name: string] assembly name
418 * [class: string] class name
419 * [number_of_methods: uleb128] the number of methods in this class
420 * [fully_covered: uleb128] the number of fully covered methods
421 * [partially_covered: uleb128] the number of partially covered methods
422 * currently partially_covered will always be 0, and fully_covered is the
423 * number of methods that are fully and partially covered.
427 * exinfo: one of: TYPE_SYNC_POINT
428 * [time diff: uleb128] nanoseconds since last timing
429 * if exinfo == TYPE_SYNC_POINT
430 * [type: byte] MonoProfilerSyncPointType enum value
433 // Pending data to be written to the log, for a single thread.
434 // Threads periodically flush their own LogBuffers by calling safe_send
435 typedef struct _LogBuffer LogBuffer;
437 // Next (older) LogBuffer in processing queue
443 uintptr_t method_base;
444 uintptr_t last_method;
448 // Bytes allocated for this LogBuffer
451 // Start of currently unused space in buffer
452 unsigned char* cursor;
454 // Pointer to start-of-structure-plus-size (for convenience)
455 unsigned char* buf_end;
457 // Start of data in buffer. Contents follow "buffer format" described above.
458 unsigned char buf [1];
462 MonoLinkedListSetNode node;
464 // The current log buffer for this thread.
467 // Methods referenced by events in `buffer`, see `MethodInfo`.
470 // Current call depth for enter/leave events.
473 // Indicates whether this thread is currently writing to its `buffer`.
475 } MonoProfilerThread;
478 ign_res (int G_GNUC_UNUSED unused, ...)
483 * These macros create a scope to avoid leaking the buffer returned
484 * from ensure_logbuf () as it may have been invalidated by a GC
485 * thread during STW. If you called init_thread () with add_to_lls =
486 * FALSE, then don't use these macros.
492 g_assert (!PROF_TLS_GET ()->busy++ && "Why are we trying to write a new event while already writing one?")
495 PROF_TLS_GET ()->busy--; \
499 static volatile gint32 buffer_rwlock_count;
500 static volatile gpointer buffer_rwlock_exclusive;
502 // Can be used recursively.
507 * If the thread holding the exclusive lock tries to modify the
508 * reader count, just make it a no-op. This way, we also avoid
509 * invoking the GC safe point macros below, which could break if
510 * done from a thread that is currently the initiator of STW.
512 * In other words, we rely on the fact that the GC thread takes
513 * the exclusive lock in the gc_event () callback when the world
516 if (InterlockedReadPointer (&buffer_rwlock_exclusive) != (gpointer) thread_id ()) {
519 while (InterlockedReadPointer (&buffer_rwlock_exclusive))
520 mono_thread_info_yield ();
522 InterlockedIncrement (&buffer_rwlock_count);
527 mono_memory_barrier ();
533 mono_memory_barrier ();
535 // See the comment in buffer_lock ().
536 if (InterlockedReadPointer (&buffer_rwlock_exclusive) == (gpointer) thread_id ())
539 g_assert (InterlockedRead (&buffer_rwlock_count) && "Why are we trying to decrement a zero reader count?");
541 InterlockedDecrement (&buffer_rwlock_count);
544 // Cannot be used recursively.
546 buffer_lock_excl (void)
548 gpointer tid = (gpointer) thread_id ();
550 g_assert (InterlockedReadPointer (&buffer_rwlock_exclusive) != tid && "Why are we taking the exclusive lock twice?");
554 while (InterlockedCompareExchangePointer (&buffer_rwlock_exclusive, tid, 0))
555 mono_thread_info_yield ();
557 while (InterlockedRead (&buffer_rwlock_count))
558 mono_thread_info_yield ();
562 mono_memory_barrier ();
566 buffer_unlock_excl (void)
568 mono_memory_barrier ();
570 g_assert (InterlockedReadPointer (&buffer_rwlock_exclusive) && "Why is the exclusive lock not held?");
571 g_assert (InterlockedReadPointer (&buffer_rwlock_exclusive) == (gpointer) thread_id () && "Why does another thread hold the exclusive lock?");
572 g_assert (!InterlockedRead (&buffer_rwlock_count) && "Why are there readers when the exclusive lock is held?");
574 InterlockedWritePointer (&buffer_rwlock_exclusive, NULL);
577 typedef struct _BinaryObject BinaryObject;
578 struct _BinaryObject {
584 struct _MonoProfiler {
586 #if defined (HAVE_SYS_ZLIB)
589 uint64_t startup_time;
591 int last_gc_gen_started;
596 pthread_t helper_thread;
597 pthread_t writer_thread;
598 pthread_t dumper_thread;
600 volatile gint32 run_writer_thread;
601 MonoLockFreeAllocSizeClass writer_entry_size_class;
602 MonoLockFreeAllocator writer_entry_allocator;
603 MonoLockFreeQueue writer_queue;
604 MonoSemType writer_queue_sem;
605 MonoConcurrentHashTable *method_table;
606 mono_mutex_t method_table_mutex;
607 volatile gint32 run_dumper_thread;
608 MonoLockFreeQueue dumper_queue;
609 MonoSemType dumper_queue_sem;
610 MonoLockFreeAllocSizeClass sample_size_class;
611 MonoLockFreeAllocator sample_allocator;
612 MonoLockFreeQueue sample_reuse_queue;
613 BinaryObject *binary_objects;
614 GPtrArray *coverage_filters;
618 MonoLockFreeQueueNode node;
623 #define WRITER_ENTRY_BLOCK_SIZE (mono_pagesize ())
633 #define PROF_TLS_SET(VAL) (TlsSetValue (profiler_tls, (VAL)))
634 #define PROF_TLS_GET() ((MonoProfilerThread *) TlsGetValue (profiler_tls))
635 #define PROF_TLS_INIT() (profiler_tls = TlsAlloc ())
636 #define PROF_TLS_FREE() (TlsFree (profiler_tls))
638 static DWORD profiler_tls;
642 #define PROF_TLS_SET(VAL) (profiler_tls = (VAL))
643 #define PROF_TLS_GET() (profiler_tls)
644 #define PROF_TLS_INIT()
645 #define PROF_TLS_FREE()
647 static __thread MonoProfilerThread *profiler_tls;
651 #define PROF_TLS_SET(VAL) (pthread_setspecific (profiler_tls, (VAL)))
652 #define PROF_TLS_GET() ((MonoProfilerThread *) pthread_getspecific (profiler_tls))
653 #define PROF_TLS_INIT() (pthread_key_create (&profiler_tls, NULL))
654 #define PROF_TLS_FREE() (pthread_key_delete (&profiler_tls))
656 static pthread_key_t profiler_tls;
661 pstrdup (const char *s)
663 int len = strlen (s) + 1;
664 char *p = (char *)malloc (len);
672 LogBuffer* buf = (LogBuffer *)alloc_buffer (BUFFER_SIZE);
674 InterlockedIncrement (&buffer_allocations);
676 buf->size = BUFFER_SIZE;
677 buf->time_base = current_time ();
678 buf->last_time = buf->time_base;
679 buf->buf_end = (unsigned char*)buf + buf->size;
680 buf->cursor = buf->buf;
685 init_buffer_state (MonoProfilerThread *thread)
687 thread->buffer = create_buffer ();
688 thread->methods = NULL;
692 clear_hazard_pointers (MonoThreadHazardPointers *hp)
694 mono_hazard_pointer_clear (hp, 0);
695 mono_hazard_pointer_clear (hp, 1);
696 mono_hazard_pointer_clear (hp, 2);
699 static MonoProfilerThread *
700 init_thread (gboolean add_to_lls)
702 MonoProfilerThread *thread = PROF_TLS_GET ();
705 * Sometimes we may try to initialize a thread twice. One example is the
706 * main thread: We initialize it when setting up the profiler, but we will
707 * also get a thread_start () callback for it. Another example is when
708 * attaching new threads to the runtime: We may get a gc_alloc () callback
709 * for that thread's thread object (where we initialize it), soon followed
710 * by a thread_start () callback.
712 * These cases are harmless anyhow. Just return if we've already done the
713 * initialization work.
718 thread = malloc (sizeof (MonoProfilerThread));
719 thread->node.key = thread_id ();
720 thread->call_depth = 0;
723 init_buffer_state (thread);
726 * Some internal profiler threads don't need to be cleaned up
727 * by the main thread on shutdown.
730 MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
731 g_assert (mono_lls_insert (&profiler_thread_list, hp, &thread->node) && "Why can't we insert the thread in the LLS?");
732 clear_hazard_pointers (hp);
735 PROF_TLS_SET (thread);
740 // Only valid if init_thread () was called with add_to_lls = FALSE.
742 deinit_thread (MonoProfilerThread *thread)
749 ensure_logbuf_inner (LogBuffer *old, int bytes)
751 if (old && old->cursor + bytes + 100 < old->buf_end)
754 LogBuffer *new_ = create_buffer ();
760 // Only valid if init_thread () was called with add_to_lls = FALSE.
762 ensure_logbuf_unsafe (int bytes)
764 MonoProfilerThread *thread = PROF_TLS_GET ();
765 LogBuffer *old = thread->buffer;
766 LogBuffer *new_ = ensure_logbuf_inner (old, bytes);
769 return old; // Still enough space.
771 thread->buffer = new_;
777 * Any calls to this function should be wrapped in the ENTER_LOG and
778 * EXIT_LOG macros to prevent the returned pointer from leaking
779 * outside of the critical region created by the calls to buffer_lock ()
780 * and buffer_unlock () that those macros insert. If the pointer leaks,
781 * it can and will lead to crashes as the GC or helper thread may
782 * invalidate the pointer at any time.
784 * Note: If you're calling from a thread that called init_thread () with
785 * add_to_lls = FALSE, you should use ensure_logbuf_unsafe () and omit
789 ensure_logbuf (int bytes)
791 g_assert (PROF_TLS_GET ()->busy && "Why are we trying to expand our buffer without the busy flag set?");
793 return ensure_logbuf_unsafe (bytes);
797 emit_byte (LogBuffer *logbuffer, int value)
799 logbuffer->cursor [0] = value;
801 assert (logbuffer->cursor <= logbuffer->buf_end);
805 emit_value (LogBuffer *logbuffer, int value)
807 encode_uleb128 (value, logbuffer->cursor, &logbuffer->cursor);
808 assert (logbuffer->cursor <= logbuffer->buf_end);
812 emit_time (LogBuffer *logbuffer, uint64_t value)
814 uint64_t tdiff = value - logbuffer->last_time;
815 //if (value < logbuffer->last_time)
816 // printf ("time went backwards\n");
817 //if (tdiff > 1000000)
818 // printf ("large time offset: %llu\n", tdiff);
819 encode_uleb128 (tdiff, logbuffer->cursor, &logbuffer->cursor);
820 /*if (tdiff != decode_uleb128 (p, &p))
821 printf ("incorrect encoding: %llu\n", tdiff);*/
822 logbuffer->last_time = value;
823 assert (logbuffer->cursor <= logbuffer->buf_end);
827 emit_event_time (LogBuffer *logbuffer, int event, uint64_t time)
829 emit_byte (logbuffer, event);
830 emit_time (logbuffer, time);
834 emit_event (LogBuffer *logbuffer, int event)
836 emit_event_time (logbuffer, event, current_time ());
840 emit_svalue (LogBuffer *logbuffer, int64_t value)
842 encode_sleb128 (value, logbuffer->cursor, &logbuffer->cursor);
843 assert (logbuffer->cursor <= logbuffer->buf_end);
847 emit_uvalue (LogBuffer *logbuffer, uint64_t value)
849 encode_uleb128 (value, logbuffer->cursor, &logbuffer->cursor);
850 assert (logbuffer->cursor <= logbuffer->buf_end);
854 emit_ptr (LogBuffer *logbuffer, void *ptr)
856 if (!logbuffer->ptr_base)
857 logbuffer->ptr_base = (uintptr_t)ptr;
858 emit_svalue (logbuffer, (intptr_t)ptr - logbuffer->ptr_base);
859 assert (logbuffer->cursor <= logbuffer->buf_end);
863 emit_method_inner (LogBuffer *logbuffer, void *method)
865 if (!logbuffer->method_base) {
866 logbuffer->method_base = (intptr_t)method;
867 logbuffer->last_method = (intptr_t)method;
869 encode_sleb128 ((intptr_t)((char*)method - (char*)logbuffer->last_method), logbuffer->cursor, &logbuffer->cursor);
870 logbuffer->last_method = (intptr_t)method;
871 assert (logbuffer->cursor <= logbuffer->buf_end);
881 find_method (MonoDomain *domain, void *user_data)
883 MethodSearch *search = user_data;
888 MonoJitInfo *ji = mono_get_jit_info_from_method (domain, search->method);
890 // It could be AOT'd, so we need to get it from the AOT runtime's cache.
892 void *ip = mono_aot_get_method (domain, search->method);
894 // Avoid a slow path in mono_jit_info_table_find ().
896 ji = mono_jit_info_table_find (domain, ip);
905 register_method_local (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *ji)
907 if (!mono_conc_hashtable_lookup (prof->method_table, method)) {
909 * FIXME: In some cases, we crash while looking up JIT info for AOT'd methods.
910 * This usually happens for static constructors. This code is disabled for now
911 * as we don't need this info for anything critical.
913 * https://bugzilla.xamarin.com/show_bug.cgi?id=35171
917 MethodSearch search = { method, NULL };
919 mono_domain_foreach (find_method, &search);
926 * FIXME: We can't always find JIT info for a generic shared method, especially
927 * if we obtained the MonoMethod during an async stack walk. For now, we deal
928 * with this by giving the generic shared method name and dummy code start/size
929 * information (i.e. zeroes).
933 MethodInfo *info = (MethodInfo *) malloc (sizeof (MethodInfo));
935 info->method = method;
937 info->time = current_time ();
939 MonoProfilerThread *thread = PROF_TLS_GET ();
940 GPtrArray *arr = thread->methods ? thread->methods : (thread->methods = g_ptr_array_new ());
941 g_ptr_array_add (arr, info);
946 emit_method (MonoProfiler *prof, LogBuffer *logbuffer, MonoMethod *method)
948 register_method_local (prof, method, NULL);
949 emit_method_inner (logbuffer, method);
953 emit_obj (LogBuffer *logbuffer, void *ptr)
955 if (!logbuffer->obj_base)
956 logbuffer->obj_base = (uintptr_t)ptr >> 3;
957 emit_svalue (logbuffer, ((uintptr_t)ptr >> 3) - logbuffer->obj_base);
958 assert (logbuffer->cursor <= logbuffer->buf_end);
962 emit_string (LogBuffer *logbuffer, const char *str, size_t size)
966 for (; i < size; i++) {
969 emit_byte (logbuffer, str [i]);
972 emit_byte (logbuffer, '\0');
976 emit_double (LogBuffer *logbuffer, double value)
979 unsigned char buffer[8];
980 memcpy (buffer, &value, 8);
981 #if G_BYTE_ORDER == G_BIG_ENDIAN
982 for (i = 7; i >= 0; i--)
984 for (i = 0; i < 8; i++)
986 emit_byte (logbuffer, buffer[i]);
990 write_int16 (char *buf, int32_t value)
993 for (i = 0; i < 2; ++i) {
1001 write_int32 (char *buf, int32_t value)
1004 for (i = 0; i < 4; ++i) {
1012 write_int64 (char *buf, int64_t value)
1015 for (i = 0; i < 8; ++i) {
1023 dump_header (MonoProfiler *profiler)
1027 p = write_int32 (p, LOG_HEADER_ID);
1028 *p++ = LOG_VERSION_MAJOR;
1029 *p++ = LOG_VERSION_MINOR;
1030 *p++ = LOG_DATA_VERSION;
1031 *p++ = sizeof (void*);
1032 p = write_int64 (p, ((uint64_t)time (NULL)) * 1000); /* startup time */
1033 p = write_int32 (p, get_timer_overhead ()); /* timer overhead */
1034 p = write_int32 (p, 0); /* flags */
1035 p = write_int32 (p, process_id ()); /* pid */
1036 p = write_int16 (p, profiler->command_port); /* port */
1037 p = write_int16 (p, 0); /* opsystem */
1038 #if defined (HAVE_SYS_ZLIB)
1039 if (profiler->gzfile) {
1040 gzwrite (profiler->gzfile, hbuf, p - hbuf);
1042 fwrite (hbuf, p - hbuf, 1, profiler->file);
1045 fwrite (hbuf, p - hbuf, 1, profiler->file);
1046 fflush (profiler->file);
1051 send_buffer (MonoProfiler *prof, MonoProfilerThread *thread)
1053 WriterQueueEntry *entry = mono_lock_free_alloc (&prof->writer_entry_allocator);
1054 entry->methods = thread->methods;
1055 entry->buffer = thread->buffer;
1057 mono_lock_free_queue_node_init (&entry->node, FALSE);
1059 mono_lock_free_queue_enqueue (&prof->writer_queue, &entry->node);
1060 mono_os_sem_post (&prof->writer_queue_sem);
1064 remove_thread (MonoProfiler *prof, MonoProfilerThread *thread, gboolean from_callback)
1066 MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
1068 if (mono_lls_remove (&profiler_thread_list, hp, &thread->node)) {
1069 LogBuffer *buffer = thread->buffer;
1072 * No need to take the buffer lock here as no other threads can
1073 * be accessing this buffer anymore.
1076 if (!from_callback) {
1078 * The thread is being cleaned up by the main thread during
1079 * shutdown. This typically happens for internal runtime
1080 * threads. We need to synthesize a thread end event.
1083 buffer = ensure_logbuf_inner (buffer,
1084 EVENT_SIZE /* event */ +
1085 BYTE_SIZE /* type */ +
1086 LEB128_SIZE /* tid */
1089 emit_event (buffer, TYPE_END_UNLOAD | TYPE_METADATA);
1090 emit_byte (buffer, TYPE_THREAD);
1091 emit_ptr (buffer, (void *) thread->node.key);
1094 send_buffer (prof, thread);
1096 mono_thread_hazardous_try_free (thread, free);
1099 clear_hazard_pointers (hp);
1102 PROF_TLS_SET (NULL);
1106 dump_buffer (MonoProfiler *profiler, LogBuffer *buf)
1111 dump_buffer (profiler, buf->next);
1112 p = write_int32 (p, BUF_ID);
1113 p = write_int32 (p, buf->cursor - buf->buf);
1114 p = write_int64 (p, buf->time_base);
1115 p = write_int64 (p, buf->ptr_base);
1116 p = write_int64 (p, buf->obj_base);
1117 p = write_int64 (p, buf->thread_id);
1118 p = write_int64 (p, buf->method_base);
1119 #if defined (HAVE_SYS_ZLIB)
1120 if (profiler->gzfile) {
1121 gzwrite (profiler->gzfile, hbuf, p - hbuf);
1122 gzwrite (profiler->gzfile, buf->buf, buf->cursor - buf->buf);
1125 fwrite (hbuf, p - hbuf, 1, profiler->file);
1126 fwrite (buf->buf, buf->cursor - buf->buf, 1, profiler->file);
1127 fflush (profiler->file);
1128 #if defined (HAVE_SYS_ZLIB)
1131 free_buffer (buf, buf->size);
1135 dump_buffer_threadless (MonoProfiler *profiler, LogBuffer *buf)
1137 for (LogBuffer *iter = buf; iter; iter = iter->next)
1138 iter->thread_id = 0;
1140 dump_buffer (profiler, buf);
1144 process_requests (MonoProfiler *profiler)
1146 if (heapshot_requested)
1147 mono_gc_collect (mono_gc_max_generation ());
1150 static void counters_init (MonoProfiler *profiler);
1151 static void counters_sample (MonoProfiler *profiler, uint64_t timestamp);
1154 safe_send (MonoProfiler *profiler)
1156 /* We need the runtime initialized so that we have threads and hazard
1157 * pointers available. Otherwise, the lock free queue will not work and
1158 * there won't be a thread to process the data.
1160 * While the runtime isn't initialized, we just accumulate data in the
1161 * thread local buffer list.
1163 if (!InterlockedRead (&runtime_inited))
1166 MonoProfilerThread *thread = PROF_TLS_GET ();
1170 send_buffer (profiler, thread);
1171 init_buffer_state (thread);
1177 send_if_needed (MonoProfiler *prof)
1179 if (PROF_TLS_GET ()->buffer->next)
1184 safe_send_threadless (MonoProfiler *prof)
1186 LogBuffer *buf = PROF_TLS_GET ()->buffer;
1188 for (LogBuffer *iter = buf; iter; iter = iter->next)
1189 iter->thread_id = 0;
1195 send_if_needed_threadless (MonoProfiler *prof)
1197 if (PROF_TLS_GET ()->buffer->next)
1198 safe_send_threadless (prof);
1201 // Assumes that the exclusive lock is held.
1203 sync_point_flush (MonoProfiler *prof)
1205 g_assert (InterlockedReadPointer (&buffer_rwlock_exclusive) == (gpointer) thread_id () && "Why don't we hold the exclusive lock?");
1207 MONO_LLS_FOREACH_SAFE (&profiler_thread_list, MonoProfilerThread, thread) {
1208 send_buffer (prof, thread);
1209 init_buffer_state (thread);
1210 } MONO_LLS_FOREACH_SAFE_END
1213 // Assumes that the exclusive lock is held.
1215 sync_point_mark (MonoProfiler *prof, MonoProfilerSyncPointType type)
1217 g_assert (InterlockedReadPointer (&buffer_rwlock_exclusive) == (gpointer) thread_id () && "Why don't we hold the exclusive lock?");
1221 LogBuffer *logbuffer = ensure_logbuf (
1222 EVENT_SIZE /* event */ +
1223 LEB128_SIZE /* type */
1226 emit_event (logbuffer, TYPE_META | TYPE_SYNC_POINT);
1227 emit_byte (logbuffer, type);
1232 case SYNC_POINT_PERIODIC:
1233 safe_send_threadless (prof);
1235 case SYNC_POINT_WORLD_STOP:
1236 case SYNC_POINT_WORLD_START:
1240 g_assert_not_reached ();
1245 // Assumes that the exclusive lock is held.
1247 sync_point (MonoProfiler *prof, MonoProfilerSyncPointType type)
1249 sync_point_flush (prof);
1250 sync_point_mark (prof, type);
1254 gc_reference (MonoObject *obj, MonoClass *klass, uintptr_t size, uintptr_t num, MonoObject **refs, uintptr_t *offsets, void *data)
1256 /* account for object alignment in the heap */
1262 LogBuffer *logbuffer = ensure_logbuf (
1263 EVENT_SIZE /* event */ +
1264 LEB128_SIZE /* obj */ +
1265 LEB128_SIZE /* klass */ +
1266 LEB128_SIZE /* size */ +
1267 LEB128_SIZE /* num */ +
1269 LEB128_SIZE /* offset */ +
1270 LEB128_SIZE /* ref */
1274 emit_event (logbuffer, TYPE_HEAP_OBJECT | TYPE_HEAP);
1275 emit_obj (logbuffer, obj);
1276 emit_ptr (logbuffer, klass);
1277 emit_value (logbuffer, size);
1278 emit_value (logbuffer, num);
1280 uintptr_t last_offset = 0;
1282 for (int i = 0; i < num; ++i) {
1283 emit_value (logbuffer, offsets [i] - last_offset);
1284 last_offset = offsets [i];
1285 emit_obj (logbuffer, refs [i]);
1293 static unsigned int hs_mode_ms = 0;
1294 static unsigned int hs_mode_gc = 0;
1295 static unsigned int hs_mode_ondemand = 0;
1296 static unsigned int gc_count = 0;
1297 static uint64_t last_hs_time = 0;
1300 heap_walk (MonoProfiler *profiler)
1305 gboolean do_walk = 0;
1306 uint64_t now = current_time ();
1308 if (hs_mode_ms && (now - last_hs_time) / 1000000 >= hs_mode_ms)
1310 else if (hs_mode_gc && (gc_count % hs_mode_gc) == 0)
1312 else if (hs_mode_ondemand)
1313 do_walk = heapshot_requested;
1314 else if (!hs_mode_ms && !hs_mode_gc && profiler->last_gc_gen_started == mono_gc_max_generation ())
1320 heapshot_requested = 0;
1324 LogBuffer *logbuffer = ensure_logbuf (
1325 EVENT_SIZE /* event */
1328 emit_event (logbuffer, TYPE_HEAP_START | TYPE_HEAP);
1332 mono_gc_walk_heap (0, gc_reference, NULL);
1336 LogBuffer *logbuffer = ensure_logbuf (
1337 EVENT_SIZE /* event */
1340 now = current_time ();
1342 emit_event (logbuffer, TYPE_HEAP_END | TYPE_HEAP);
1350 gc_event (MonoProfiler *profiler, MonoGCEvent ev, int generation)
1354 LogBuffer *logbuffer = ensure_logbuf (
1355 EVENT_SIZE /* event */ +
1356 BYTE_SIZE /* gc event */ +
1357 BYTE_SIZE /* generation */
1360 emit_event (logbuffer, TYPE_GC_EVENT | TYPE_GC);
1361 emit_byte (logbuffer, ev);
1362 emit_byte (logbuffer, generation);
1367 case MONO_GC_EVENT_START:
1368 /* to deal with nested gen1 after gen0 started */
1369 profiler->last_gc_gen_started = generation;
1371 if (generation == mono_gc_max_generation ())
1374 case MONO_GC_EVENT_PRE_STOP_WORLD_LOCKED:
1376 * Ensure that no thread can be in the middle of writing to
1377 * a buffer when the world stops...
1379 buffer_lock_excl ();
1381 case MONO_GC_EVENT_POST_STOP_WORLD:
1383 * ... So that we now have a consistent view of all buffers.
1384 * This allows us to flush them. We need to do this because
1385 * they may contain object allocation events that need to be
1386 * committed to the log file before any object move events
1387 * that will be produced during this GC.
1389 sync_point (profiler, SYNC_POINT_WORLD_STOP);
1391 case MONO_GC_EVENT_PRE_START_WORLD:
1392 heap_walk (profiler);
1394 case MONO_GC_EVENT_POST_START_WORLD_UNLOCKED:
1396 * Similarly, we must now make sure that any object moves
1397 * written to the GC thread's buffer are flushed. Otherwise,
1398 * object allocation events for certain addresses could come
1399 * after the move events that made those addresses available.
1401 sync_point_mark (profiler, SYNC_POINT_WORLD_START);
1404 * Finally, it is safe to allow other threads to write to
1405 * their buffers again.
1407 buffer_unlock_excl ();
1415 gc_resize (MonoProfiler *profiler, int64_t new_size)
1419 LogBuffer *logbuffer = ensure_logbuf (
1420 EVENT_SIZE /* event */ +
1421 LEB128_SIZE /* new size */
1424 emit_event (logbuffer, TYPE_GC_RESIZE | TYPE_GC);
1425 emit_value (logbuffer, new_size);
1430 // If you alter MAX_FRAMES, you may need to alter SAMPLE_BLOCK_SIZE too.
1431 #define MAX_FRAMES 32
1435 MonoMethod* methods [MAX_FRAMES];
1436 int32_t il_offsets [MAX_FRAMES];
1437 int32_t native_offsets [MAX_FRAMES];
1440 static int num_frames = MAX_FRAMES;
1443 walk_stack (MonoMethod *method, int32_t native_offset, int32_t il_offset, mono_bool managed, void* data)
1445 FrameData *frame = (FrameData *)data;
1446 if (method && frame->count < num_frames) {
1447 frame->il_offsets [frame->count] = il_offset;
1448 frame->native_offsets [frame->count] = native_offset;
1449 frame->methods [frame->count++] = method;
1450 //printf ("In %d %s at %d (native: %d)\n", frame->count, mono_method_get_name (method), il_offset, native_offset);
1452 return frame->count == num_frames;
1456 * a note about stack walks: they can cause more profiler events to fire,
1457 * so we need to make sure they don't happen after we started emitting an
1458 * event, hence the collect_bt/emit_bt split.
1461 collect_bt (FrameData *data)
1464 mono_stack_walk_no_il (walk_stack, data);
1468 emit_bt (MonoProfiler *prof, LogBuffer *logbuffer, FrameData *data)
1470 /* FIXME: this is actually tons of data and we should
1471 * just output it the first time and use an id the next
1473 if (data->count > num_frames)
1474 printf ("bad num frames: %d\n", data->count);
1475 emit_value (logbuffer, data->count);
1476 //if (*p != data.count) {
1477 // 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);}
1478 while (data->count) {
1479 emit_method (prof, logbuffer, data->methods [--data->count]);
1484 gc_alloc (MonoProfiler *prof, MonoObject *obj, MonoClass *klass)
1488 int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces) ? TYPE_ALLOC_BT : 0;
1490 uintptr_t len = mono_object_get_size (obj);
1491 /* account for object alignment in the heap */
1500 LogBuffer *logbuffer = ensure_logbuf (
1501 EVENT_SIZE /* event */ +
1502 LEB128_SIZE /* klass */ +
1503 LEB128_SIZE /* obj */ +
1504 LEB128_SIZE /* size */ +
1506 LEB128_SIZE /* count */ +
1508 LEB128_SIZE /* method */
1513 emit_event (logbuffer, do_bt | TYPE_ALLOC);
1514 emit_ptr (logbuffer, klass);
1515 emit_obj (logbuffer, obj);
1516 emit_value (logbuffer, len);
1519 emit_bt (prof, logbuffer, &data);
1523 send_if_needed (prof);
1525 process_requests (prof);
1529 gc_moves (MonoProfiler *prof, void **objects, int num)
1533 LogBuffer *logbuffer = ensure_logbuf (
1534 EVENT_SIZE /* event */ +
1535 LEB128_SIZE /* num */ +
1537 LEB128_SIZE /* object */
1541 emit_event (logbuffer, TYPE_GC_MOVE | TYPE_GC);
1542 emit_value (logbuffer, num);
1544 for (int i = 0; i < num; ++i)
1545 emit_obj (logbuffer, objects [i]);
1551 gc_roots (MonoProfiler *prof, int num, void **objects, int *root_types, uintptr_t *extra_info)
1555 LogBuffer *logbuffer = ensure_logbuf (
1556 EVENT_SIZE /* event */ +
1557 LEB128_SIZE /* num */ +
1558 LEB128_SIZE /* collections */ +
1560 LEB128_SIZE /* object */ +
1561 LEB128_SIZE /* root type */ +
1562 LEB128_SIZE /* extra info */
1566 emit_event (logbuffer, TYPE_HEAP_ROOT | TYPE_HEAP);
1567 emit_value (logbuffer, num);
1568 emit_value (logbuffer, mono_gc_collection_count (mono_gc_max_generation ()));
1570 for (int i = 0; i < num; ++i) {
1571 emit_obj (logbuffer, objects [i]);
1572 emit_byte (logbuffer, root_types [i]);
1573 emit_value (logbuffer, extra_info [i]);
1580 gc_handle (MonoProfiler *prof, int op, int type, uintptr_t handle, MonoObject *obj)
1582 int do_bt = nocalls && InterlockedRead (&runtime_inited) && !notraces;
1590 LogBuffer *logbuffer = ensure_logbuf (
1591 EVENT_SIZE /* event */ +
1592 LEB128_SIZE /* type */ +
1593 LEB128_SIZE /* handle */ +
1594 (op == MONO_PROFILER_GC_HANDLE_CREATED ? (
1595 LEB128_SIZE /* obj */
1598 LEB128_SIZE /* count */ +
1600 LEB128_SIZE /* method */
1605 if (op == MONO_PROFILER_GC_HANDLE_CREATED)
1606 emit_event (logbuffer, (do_bt ? TYPE_GC_HANDLE_CREATED_BT : TYPE_GC_HANDLE_CREATED) | TYPE_GC);
1607 else if (op == MONO_PROFILER_GC_HANDLE_DESTROYED)
1608 emit_event (logbuffer, (do_bt ? TYPE_GC_HANDLE_DESTROYED_BT : TYPE_GC_HANDLE_DESTROYED) | TYPE_GC);
1610 g_assert_not_reached ();
1612 emit_value (logbuffer, type);
1613 emit_value (logbuffer, handle);
1615 if (op == MONO_PROFILER_GC_HANDLE_CREATED)
1616 emit_obj (logbuffer, obj);
1619 emit_bt (prof, logbuffer, &data);
1623 process_requests (prof);
1627 finalize_begin (MonoProfiler *prof)
1631 LogBuffer *buf = ensure_logbuf (
1632 EVENT_SIZE /* event */
1635 emit_event (buf, TYPE_GC_FINALIZE_START | TYPE_GC);
1639 process_requests (prof);
1643 finalize_end (MonoProfiler *prof)
1647 LogBuffer *buf = ensure_logbuf (
1648 EVENT_SIZE /* event */
1651 emit_event (buf, TYPE_GC_FINALIZE_END | TYPE_GC);
1655 process_requests (prof);
1659 finalize_object_begin (MonoProfiler *prof, MonoObject *obj)
1663 LogBuffer *buf = ensure_logbuf (
1664 EVENT_SIZE /* event */ +
1665 LEB128_SIZE /* obj */
1668 emit_event (buf, TYPE_GC_FINALIZE_OBJECT_START | TYPE_GC);
1669 emit_obj (buf, obj);
1673 process_requests (prof);
1677 finalize_object_end (MonoProfiler *prof, MonoObject *obj)
1681 LogBuffer *buf = ensure_logbuf (
1682 EVENT_SIZE /* event */ +
1683 LEB128_SIZE /* obj */
1686 emit_event (buf, TYPE_GC_FINALIZE_OBJECT_END | TYPE_GC);
1687 emit_obj (buf, obj);
1691 process_requests (prof);
1695 push_nesting (char *p, MonoClass *klass)
1700 nesting = mono_class_get_nesting_type (klass);
1702 p = push_nesting (p, nesting);
1706 name = mono_class_get_name (klass);
1707 nspace = mono_class_get_namespace (klass);
1710 p += strlen (nspace);
1720 type_name (MonoClass *klass)
1724 push_nesting (buf, klass);
1725 p = (char *)malloc (strlen (buf) + 1);
1731 image_loaded (MonoProfiler *prof, MonoImage *image, int result)
1733 if (result != MONO_PROFILE_OK)
1736 const char *name = mono_image_get_filename (image);
1737 int nlen = strlen (name) + 1;
1741 LogBuffer *logbuffer = ensure_logbuf (
1742 EVENT_SIZE /* event */ +
1743 BYTE_SIZE /* type */ +
1744 LEB128_SIZE /* image */ +
1748 emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1749 emit_byte (logbuffer, TYPE_IMAGE);
1750 emit_ptr (logbuffer, image);
1751 memcpy (logbuffer->cursor, name, nlen);
1752 logbuffer->cursor += nlen;
1756 send_if_needed (prof);
1758 process_requests (prof);
1760 InterlockedIncrement (&image_loads);
1764 image_unloaded (MonoProfiler *prof, MonoImage *image)
1766 const char *name = mono_image_get_filename (image);
1767 int nlen = strlen (name) + 1;
1771 LogBuffer *logbuffer = ensure_logbuf (
1772 EVENT_SIZE /* event */ +
1773 BYTE_SIZE /* type */ +
1774 LEB128_SIZE /* image */ +
1778 emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1779 emit_byte (logbuffer, TYPE_IMAGE);
1780 emit_ptr (logbuffer, image);
1781 memcpy (logbuffer->cursor, name, nlen);
1782 logbuffer->cursor += nlen;
1786 send_if_needed (prof);
1788 process_requests (prof);
1790 InterlockedIncrement (&image_unloads);
1794 assembly_loaded (MonoProfiler *prof, MonoAssembly *assembly, int result)
1796 if (result != MONO_PROFILE_OK)
1799 char *name = mono_stringify_assembly_name (mono_assembly_get_name (assembly));
1800 int nlen = strlen (name) + 1;
1804 LogBuffer *logbuffer = ensure_logbuf (
1805 EVENT_SIZE /* event */ +
1806 BYTE_SIZE /* type */ +
1807 LEB128_SIZE /* assembly */ +
1811 emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1812 emit_byte (logbuffer, TYPE_ASSEMBLY);
1813 emit_ptr (logbuffer, assembly);
1814 memcpy (logbuffer->cursor, name, nlen);
1815 logbuffer->cursor += nlen;
1821 send_if_needed (prof);
1823 process_requests (prof);
1825 InterlockedIncrement (&assembly_loads);
1829 assembly_unloaded (MonoProfiler *prof, MonoAssembly *assembly)
1831 char *name = mono_stringify_assembly_name (mono_assembly_get_name (assembly));
1832 int nlen = strlen (name) + 1;
1836 LogBuffer *logbuffer = ensure_logbuf (
1837 EVENT_SIZE /* event */ +
1838 BYTE_SIZE /* type */ +
1839 LEB128_SIZE /* assembly */ +
1843 emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1844 emit_byte (logbuffer, TYPE_ASSEMBLY);
1845 emit_ptr (logbuffer, assembly);
1846 memcpy (logbuffer->cursor, name, nlen);
1847 logbuffer->cursor += nlen;
1853 send_if_needed (prof);
1855 process_requests (prof);
1857 InterlockedIncrement (&assembly_unloads);
1861 class_loaded (MonoProfiler *prof, MonoClass *klass, int result)
1863 if (result != MONO_PROFILE_OK)
1868 if (InterlockedRead (&runtime_inited))
1869 name = mono_type_get_name (mono_class_get_type (klass));
1871 name = type_name (klass);
1873 int nlen = strlen (name) + 1;
1874 MonoImage *image = mono_class_get_image (klass);
1878 LogBuffer *logbuffer = ensure_logbuf (
1879 EVENT_SIZE /* event */ +
1880 BYTE_SIZE /* type */ +
1881 LEB128_SIZE /* klass */ +
1882 LEB128_SIZE /* image */ +
1886 emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1887 emit_byte (logbuffer, TYPE_CLASS);
1888 emit_ptr (logbuffer, klass);
1889 emit_ptr (logbuffer, image);
1890 memcpy (logbuffer->cursor, name, nlen);
1891 logbuffer->cursor += nlen;
1900 send_if_needed (prof);
1902 process_requests (prof);
1904 InterlockedIncrement (&class_loads);
1908 class_unloaded (MonoProfiler *prof, MonoClass *klass)
1912 if (InterlockedRead (&runtime_inited))
1913 name = mono_type_get_name (mono_class_get_type (klass));
1915 name = type_name (klass);
1917 int nlen = strlen (name) + 1;
1918 MonoImage *image = mono_class_get_image (klass);
1922 LogBuffer *logbuffer = ensure_logbuf (
1923 EVENT_SIZE /* event */ +
1924 BYTE_SIZE /* type */ +
1925 LEB128_SIZE /* klass */ +
1926 LEB128_SIZE /* image */ +
1930 emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1931 emit_byte (logbuffer, TYPE_CLASS);
1932 emit_ptr (logbuffer, klass);
1933 emit_ptr (logbuffer, image);
1934 memcpy (logbuffer->cursor, name, nlen);
1935 logbuffer->cursor += nlen;
1944 send_if_needed (prof);
1946 process_requests (prof);
1948 InterlockedIncrement (&class_unloads);
1951 #ifndef DISABLE_HELPER_THREAD
1952 static void process_method_enter_coverage (MonoProfiler *prof, MonoMethod *method);
1953 #endif /* DISABLE_HELPER_THREAD */
1956 method_enter (MonoProfiler *prof, MonoMethod *method)
1958 #ifndef DISABLE_HELPER_THREAD
1959 process_method_enter_coverage (prof, method);
1960 #endif /* DISABLE_HELPER_THREAD */
1962 if (PROF_TLS_GET ()->call_depth++ <= max_call_depth) {
1965 LogBuffer *logbuffer = ensure_logbuf (
1966 EVENT_SIZE /* event */ +
1967 LEB128_SIZE /* method */
1970 emit_event (logbuffer, TYPE_ENTER | TYPE_METHOD);
1971 emit_method (prof, logbuffer, method);
1976 send_if_needed (prof);
1978 process_requests (prof);
1982 method_leave (MonoProfiler *prof, MonoMethod *method)
1984 if (--PROF_TLS_GET ()->call_depth <= max_call_depth) {
1987 LogBuffer *logbuffer = ensure_logbuf (
1988 EVENT_SIZE /* event */ +
1989 LEB128_SIZE /* method */
1992 emit_event (logbuffer, TYPE_LEAVE | TYPE_METHOD);
1993 emit_method (prof, logbuffer, method);
1998 send_if_needed (prof);
2000 process_requests (prof);
2004 method_exc_leave (MonoProfiler *prof, MonoMethod *method)
2006 if (!nocalls && --PROF_TLS_GET ()->call_depth <= max_call_depth) {
2009 LogBuffer *logbuffer = ensure_logbuf (
2010 EVENT_SIZE /* event */ +
2011 LEB128_SIZE /* method */
2014 emit_event (logbuffer, TYPE_EXC_LEAVE | TYPE_METHOD);
2015 emit_method (prof, logbuffer, method);
2020 send_if_needed (prof);
2022 process_requests (prof);
2026 method_jitted (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *ji, int result)
2028 if (result != MONO_PROFILE_OK)
2031 register_method_local (prof, method, ji);
2033 process_requests (prof);
2037 code_buffer_new (MonoProfiler *prof, void *buffer, int size, MonoProfilerCodeBufferType type, void *data)
2042 if (type == MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE) {
2043 name = (char *) data;
2044 nlen = strlen (name) + 1;
2052 LogBuffer *logbuffer = ensure_logbuf (
2053 EVENT_SIZE /* event */ +
2054 BYTE_SIZE /* type */ +
2055 LEB128_SIZE /* buffer */ +
2056 LEB128_SIZE /* size */ +
2062 emit_event (logbuffer, TYPE_JITHELPER | TYPE_RUNTIME);
2063 emit_byte (logbuffer, type);
2064 emit_ptr (logbuffer, buffer);
2065 emit_value (logbuffer, size);
2068 memcpy (logbuffer->cursor, name, nlen);
2069 logbuffer->cursor += nlen;
2074 process_requests (prof);
2078 throw_exc (MonoProfiler *prof, MonoObject *object)
2080 int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces) ? TYPE_EXCEPTION_BT : 0;
2088 LogBuffer *logbuffer = ensure_logbuf (
2089 EVENT_SIZE /* event */ +
2090 LEB128_SIZE /* object */ +
2092 LEB128_SIZE /* count */ +
2094 LEB128_SIZE /* method */
2099 emit_event (logbuffer, do_bt | TYPE_EXCEPTION);
2100 emit_obj (logbuffer, object);
2103 emit_bt (prof, logbuffer, &data);
2107 process_requests (prof);
2111 clause_exc (MonoProfiler *prof, MonoMethod *method, int clause_type, int clause_num)
2115 LogBuffer *logbuffer = ensure_logbuf (
2116 EVENT_SIZE /* event */ +
2117 BYTE_SIZE /* clause type */ +
2118 LEB128_SIZE /* clause num */ +
2119 LEB128_SIZE /* method */
2122 emit_event (logbuffer, TYPE_EXCEPTION | TYPE_CLAUSE);
2123 emit_byte (logbuffer, clause_type);
2124 emit_value (logbuffer, clause_num);
2125 emit_method (prof, logbuffer, method);
2129 process_requests (prof);
2133 monitor_event (MonoProfiler *profiler, MonoObject *object, MonoProfilerMonitorEvent event)
2135 int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces && event == MONO_PROFILER_MONITOR_CONTENTION) ? TYPE_MONITOR_BT : 0;
2143 LogBuffer *logbuffer = ensure_logbuf (
2144 EVENT_SIZE /* event */ +
2145 LEB128_SIZE /* object */ +
2147 LEB128_SIZE /* count */ +
2149 LEB128_SIZE /* method */
2154 emit_event (logbuffer, (event << 4) | do_bt | TYPE_MONITOR);
2155 emit_obj (logbuffer, object);
2158 emit_bt (profiler, logbuffer, &data);
2162 process_requests (profiler);
2166 thread_start (MonoProfiler *prof, uintptr_t tid)
2172 LogBuffer *logbuffer = ensure_logbuf (
2173 EVENT_SIZE /* event */ +
2174 BYTE_SIZE /* type */ +
2175 LEB128_SIZE /* tid */
2178 emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
2179 emit_byte (logbuffer, TYPE_THREAD);
2180 emit_ptr (logbuffer, (void*) tid);
2184 send_if_needed (prof);
2186 process_requests (prof);
2188 InterlockedIncrement (&thread_starts);
2192 thread_end (MonoProfiler *prof, uintptr_t tid)
2196 LogBuffer *logbuffer = ensure_logbuf (
2197 EVENT_SIZE /* event */ +
2198 BYTE_SIZE /* type */ +
2199 LEB128_SIZE /* tid */
2202 emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
2203 emit_byte (logbuffer, TYPE_THREAD);
2204 emit_ptr (logbuffer, (void*) tid);
2208 // Don't process requests as the thread is detached from the runtime.
2210 remove_thread (prof, PROF_TLS_GET (), TRUE);
2212 InterlockedIncrement (&thread_ends);
2216 domain_loaded (MonoProfiler *prof, MonoDomain *domain, int result)
2218 if (result != MONO_PROFILE_OK)
2223 LogBuffer *logbuffer = ensure_logbuf (
2224 EVENT_SIZE /* event */ +
2225 BYTE_SIZE /* type */ +
2226 LEB128_SIZE /* domain id */
2229 emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
2230 emit_byte (logbuffer, TYPE_DOMAIN);
2231 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
2235 send_if_needed (prof);
2237 process_requests (prof);
2239 InterlockedIncrement (&domain_loads);
2243 domain_unloaded (MonoProfiler *prof, MonoDomain *domain)
2247 LogBuffer *logbuffer = ensure_logbuf (
2248 EVENT_SIZE /* event */ +
2249 BYTE_SIZE /* type */ +
2250 LEB128_SIZE /* domain id */
2253 emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
2254 emit_byte (logbuffer, TYPE_DOMAIN);
2255 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
2259 send_if_needed (prof);
2261 process_requests (prof);
2263 InterlockedIncrement (&domain_unloads);
2267 domain_name (MonoProfiler *prof, MonoDomain *domain, const char *name)
2269 int nlen = strlen (name) + 1;
2273 LogBuffer *logbuffer = ensure_logbuf (
2274 EVENT_SIZE /* event */ +
2275 BYTE_SIZE /* type */ +
2276 LEB128_SIZE /* domain id */ +
2280 emit_event (logbuffer, TYPE_METADATA);
2281 emit_byte (logbuffer, TYPE_DOMAIN);
2282 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
2283 memcpy (logbuffer->cursor, name, nlen);
2284 logbuffer->cursor += nlen;
2288 send_if_needed (prof);
2290 process_requests (prof);
2294 context_loaded (MonoProfiler *prof, MonoAppContext *context)
2298 LogBuffer *logbuffer = ensure_logbuf (
2299 EVENT_SIZE /* event */ +
2300 BYTE_SIZE /* type */ +
2301 LEB128_SIZE /* context id */ +
2302 LEB128_SIZE /* domain id */
2305 emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
2306 emit_byte (logbuffer, TYPE_CONTEXT);
2307 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_id (context));
2308 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_domain_id (context));
2312 send_if_needed (prof);
2314 process_requests (prof);
2316 InterlockedIncrement (&context_loads);
2320 context_unloaded (MonoProfiler *prof, MonoAppContext *context)
2324 LogBuffer *logbuffer = ensure_logbuf (
2325 EVENT_SIZE /* event */ +
2326 BYTE_SIZE /* type */ +
2327 LEB128_SIZE /* context id */ +
2328 LEB128_SIZE /* domain id */
2331 emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
2332 emit_byte (logbuffer, TYPE_CONTEXT);
2333 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_id (context));
2334 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_domain_id (context));
2338 send_if_needed (prof);
2340 process_requests (prof);
2342 InterlockedIncrement (&context_unloads);
2346 thread_name (MonoProfiler *prof, uintptr_t tid, const char *name)
2348 int len = strlen (name) + 1;
2352 LogBuffer *logbuffer = ensure_logbuf (
2353 EVENT_SIZE /* event */ +
2354 BYTE_SIZE /* type */ +
2355 LEB128_SIZE /* tid */ +
2359 emit_event (logbuffer, TYPE_METADATA);
2360 emit_byte (logbuffer, TYPE_THREAD);
2361 emit_ptr (logbuffer, (void*)tid);
2362 memcpy (logbuffer->cursor, name, len);
2363 logbuffer->cursor += len;
2367 send_if_needed (prof);
2369 process_requests (prof);
2380 MonoLockFreeQueueNode node;
2386 AsyncFrameInfo frames [MONO_ZERO_LEN_ARRAY];
2390 async_walk_stack (MonoMethod *method, MonoDomain *domain, void *base_address, int offset, void *data)
2392 SampleHit *sample = (SampleHit *) data;
2394 if (sample->count < num_frames) {
2395 int i = sample->count;
2397 sample->frames [i].method = method;
2398 sample->frames [i].domain = domain;
2399 sample->frames [i].base_address = base_address;
2400 sample->frames [i].offset = offset;
2405 return sample->count == num_frames;
2408 #define SAMPLE_SLOT_SIZE(FRAMES) (sizeof (SampleHit) + sizeof (AsyncFrameInfo) * (FRAMES - MONO_ZERO_LEN_ARRAY))
2409 #define SAMPLE_BLOCK_SIZE (mono_pagesize ())
2412 enqueue_sample_hit (gpointer p)
2414 SampleHit *sample = p;
2416 mono_lock_free_queue_node_unpoison (&sample->node);
2417 mono_lock_free_queue_enqueue (&sample->prof->dumper_queue, &sample->node);
2418 mono_os_sem_post (&sample->prof->dumper_queue_sem);
2420 InterlockedIncrement (&sample_flushes);
2424 mono_sample_hit (MonoProfiler *profiler, unsigned char *ip, void *context)
2427 * Please note: We rely on the runtime loading the profiler with
2428 * MONO_DL_EAGER (RTLD_NOW) so that references to runtime functions within
2429 * this function (and its siblings) are resolved when the profiler is
2430 * loaded. Otherwise, we would potentially invoke the dynamic linker when
2431 * invoking runtime functions, which is not async-signal-safe.
2437 InterlockedIncrement (&sample_hits);
2439 SampleHit *sample = (SampleHit *) mono_lock_free_queue_dequeue (&profiler->sample_reuse_queue);
2443 * If we're out of reusable sample events and we're not allowed to
2444 * allocate more, we have no choice but to drop the event.
2446 if (InterlockedRead (&sample_allocations) >= max_allocated_sample_hits)
2449 sample = mono_lock_free_alloc (&profiler->sample_allocator);
2450 sample->prof = profiler;
2451 mono_lock_free_queue_node_init (&sample->node, TRUE);
2453 InterlockedIncrement (&sample_allocations);
2457 mono_stack_walk_async_safe (&async_walk_stack, context, sample);
2459 sample->time = current_time ();
2460 sample->tid = thread_id ();
2466 snprintf (buf, sizeof (buf), "hit at %p in thread %p after %llu ms\n", ip, (void *) sample->tid, (unsigned long long int) ((sample->time - profiler->startup_time) / 10000 / 100));
2468 ign_res (write (2, buf, len));
2471 mono_thread_hazardous_try_free (sample, enqueue_sample_hit);
2474 static uintptr_t *code_pages = 0;
2475 static int num_code_pages = 0;
2476 static int size_code_pages = 0;
2477 #define CPAGE_SHIFT (9)
2478 #define CPAGE_SIZE (1 << CPAGE_SHIFT)
2479 #define CPAGE_MASK (~(CPAGE_SIZE - 1))
2480 #define CPAGE_ADDR(p) ((p) & CPAGE_MASK)
2483 add_code_page (uintptr_t *hash, uintptr_t hsize, uintptr_t page)
2486 uintptr_t start_pos;
2487 start_pos = (page >> CPAGE_SHIFT) % hsize;
2490 if (hash [i] && CPAGE_ADDR (hash [i]) == CPAGE_ADDR (page)) {
2492 } else if (!hash [i]) {
2499 } while (i != start_pos);
2500 /* should not happen */
2501 printf ("failed code page store\n");
2506 add_code_pointer (uintptr_t ip)
2509 if (num_code_pages * 2 >= size_code_pages) {
2511 uintptr_t old_size = size_code_pages;
2512 size_code_pages *= 2;
2513 if (size_code_pages == 0)
2514 size_code_pages = 16;
2515 n = (uintptr_t *)calloc (sizeof (uintptr_t) * size_code_pages, 1);
2516 for (i = 0; i < old_size; ++i) {
2518 add_code_page (n, size_code_pages, code_pages [i]);
2524 num_code_pages += add_code_page (code_pages, size_code_pages, ip & CPAGE_MASK);
2527 /* ELF code crashes on some systems. */
2528 //#if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
2531 dump_ubin (const char *filename, uintptr_t load_addr, uint64_t offset, uintptr_t size)
2533 int len = strlen (filename) + 1;
2537 LogBuffer *logbuffer = ensure_logbuf (
2538 EVENT_SIZE /* event */ +
2539 LEB128_SIZE /* load address */ +
2540 LEB128_SIZE /* offset */ +
2541 LEB128_SIZE /* size */ +
2542 nlen /* file name */
2545 emit_event (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_UBIN);
2546 emit_svalue (logbuffer, load_addr);
2547 emit_uvalue (logbuffer, offset);
2548 emit_uvalue (logbuffer, size);
2549 memcpy (logbuffer->cursor, filename, len);
2550 logbuffer->cursor += len;
2557 dump_usym (const char *name, uintptr_t value, uintptr_t size)
2559 int len = strlen (name) + 1;
2563 LogBuffer *logbuffer = ensure_logbuf (
2564 EVENT_SIZE /* event */ +
2565 LEB128_SIZE /* value */ +
2566 LEB128_SIZE /* size */ +
2570 emit_event (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_USYM);
2571 emit_ptr (logbuffer, (void*)value);
2572 emit_value (logbuffer, size);
2573 memcpy (logbuffer->cursor, name, len);
2574 logbuffer->cursor += len;
2579 /* ELF code crashes on some systems. */
2580 //#if defined(ELFMAG0)
2583 #if SIZEOF_VOID_P == 4
2584 #define ELF_WSIZE 32
2586 #define ELF_WSIZE 64
2589 #define ElfW(type) _ElfW (Elf, ELF_WSIZE, type)
2590 #define _ElfW(e,w,t) _ElfW_1 (e, w, _##t)
2591 #define _ElfW_1(e,w,t) e##w##t
2595 dump_elf_symbols (ElfW(Sym) *symbols, int num_symbols, const char *strtab, void *load_addr)
2598 for (i = 0; i < num_symbols; ++i) {
2600 sym = strtab + symbols [i].st_name;
2601 if (!symbols [i].st_name || !symbols [i].st_size || (symbols [i].st_info & 0xf) != STT_FUNC)
2603 //printf ("symbol %s at %d\n", sym, symbols [i].st_value);
2604 dump_usym (sym, (uintptr_t)load_addr + symbols [i].st_value, symbols [i].st_size);
2609 read_elf_symbols (MonoProfiler *prof, const char *filename, void *load_addr)
2616 ElfW(Shdr) *sheader;
2617 ElfW(Shdr) *shstrtabh;
2618 ElfW(Shdr) *symtabh = NULL;
2619 ElfW(Shdr) *strtabh = NULL;
2620 ElfW(Sym) *symbols = NULL;
2624 fd = open (filename, O_RDONLY);
2627 if (fstat (fd, &statb) != 0) {
2631 file_size = statb.st_size;
2632 data = mmap (NULL, file_size, PROT_READ, MAP_PRIVATE, fd, 0);
2634 if (data == MAP_FAILED)
2637 if (header->e_ident [EI_MAG0] != ELFMAG0 ||
2638 header->e_ident [EI_MAG1] != ELFMAG1 ||
2639 header->e_ident [EI_MAG2] != ELFMAG2 ||
2640 header->e_ident [EI_MAG3] != ELFMAG3 ) {
2641 munmap (data, file_size);
2644 sheader = (void*)((char*)data + header->e_shoff);
2645 shstrtabh = (void*)((char*)sheader + (header->e_shentsize * header->e_shstrndx));
2646 strtab = (const char*)data + shstrtabh->sh_offset;
2647 for (i = 0; i < header->e_shnum; ++i) {
2648 //printf ("section header: %d\n", sheader->sh_type);
2649 if (sheader->sh_type == SHT_SYMTAB) {
2651 strtabh = (void*)((char*)data + header->e_shoff + sheader->sh_link * header->e_shentsize);
2652 /*printf ("symtab section header: %d, .strstr: %d\n", i, sheader->sh_link);*/
2655 sheader = (void*)((char*)sheader + header->e_shentsize);
2657 if (!symtabh || !strtabh) {
2658 munmap (data, file_size);
2661 strtab = (const char*)data + strtabh->sh_offset;
2662 num_symbols = symtabh->sh_size / symtabh->sh_entsize;
2663 symbols = (void*)((char*)data + symtabh->sh_offset);
2664 dump_elf_symbols (symbols, num_symbols, strtab, load_addr);
2665 munmap (data, file_size);
2670 /* ELF code crashes on some systems. */
2671 //#if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
2674 elf_dl_callback (struct dl_phdr_info *info, size_t size, void *data)
2676 MonoProfiler *prof = data;
2678 const char *filename;
2680 char *a = (void*)info->dlpi_addr;
2682 ElfW(Dyn) *dyn = NULL;
2683 ElfW(Sym) *symtab = NULL;
2684 ElfW(Word) *hash_table = NULL;
2685 ElfW(Ehdr) *header = NULL;
2686 const char* strtab = NULL;
2687 for (obj = prof->binary_objects; obj; obj = obj->next) {
2691 filename = info->dlpi_name;
2694 if (!info->dlpi_addr && !filename [0]) {
2695 int l = readlink ("/proc/self/exe", buf, sizeof (buf) - 1);
2701 obj = calloc (sizeof (BinaryObject), 1);
2702 obj->addr = (void*)info->dlpi_addr;
2703 obj->name = pstrdup (filename);
2704 obj->next = prof->binary_objects;
2705 prof->binary_objects = obj;
2706 //printf ("loaded file: %s at %p, segments: %d\n", filename, (void*)info->dlpi_addr, info->dlpi_phnum);
2708 for (i = 0; i < info->dlpi_phnum; ++i) {
2709 //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);
2710 if (info->dlpi_phdr[i].p_type == PT_LOAD && !header) {
2711 header = (ElfW(Ehdr)*)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
2712 if (header->e_ident [EI_MAG0] != ELFMAG0 ||
2713 header->e_ident [EI_MAG1] != ELFMAG1 ||
2714 header->e_ident [EI_MAG2] != ELFMAG2 ||
2715 header->e_ident [EI_MAG3] != ELFMAG3 ) {
2718 dump_ubin (filename, info->dlpi_addr + info->dlpi_phdr[i].p_vaddr, info->dlpi_phdr[i].p_offset, info->dlpi_phdr[i].p_memsz);
2719 } else if (info->dlpi_phdr[i].p_type == PT_DYNAMIC) {
2720 dyn = (ElfW(Dyn) *)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
2723 if (read_elf_symbols (prof, filename, (void*)info->dlpi_addr))
2725 if (!info->dlpi_name || !info->dlpi_name[0])
2729 for (i = 0; dyn [i].d_tag != DT_NULL; ++i) {
2730 if (dyn [i].d_tag == DT_SYMTAB) {
2731 if (symtab && do_debug)
2732 printf ("multiple symtabs: %d\n", i);
2733 symtab = (ElfW(Sym) *)(a + dyn [i].d_un.d_ptr);
2734 } else if (dyn [i].d_tag == DT_HASH) {
2735 hash_table = (ElfW(Word) *)(a + dyn [i].d_un.d_ptr);
2736 } else if (dyn [i].d_tag == DT_STRTAB) {
2737 strtab = (const char*)(a + dyn [i].d_un.d_ptr);
2742 num_sym = hash_table [1];
2743 dump_elf_symbols (symtab, num_sym, strtab, (void*)info->dlpi_addr);
2748 load_binaries (MonoProfiler *prof)
2750 dl_iterate_phdr (elf_dl_callback, prof);
2755 load_binaries (MonoProfiler *prof)
2762 symbol_for (uintptr_t code)
2765 void *ip = (void*)code;
2767 if (dladdr (ip, &di)) {
2769 return di.dli_sname;
2772 names = backtrace_symbols (&ip, 1);
2774 const char* p = names [0];
2785 dump_unmanaged_coderefs (MonoProfiler *prof)
2788 const char* last_symbol;
2789 uintptr_t addr, page_end;
2791 if (load_binaries (prof))
2793 for (i = 0; i < size_code_pages; ++i) {
2795 if (!code_pages [i] || code_pages [i] & 1)
2798 addr = CPAGE_ADDR (code_pages [i]);
2799 page_end = addr + CPAGE_SIZE;
2800 code_pages [i] |= 1;
2801 /* we dump the symbols for the whole page */
2802 for (; addr < page_end; addr += 16) {
2803 sym = symbol_for (addr);
2804 if (sym && sym == last_symbol)
2809 dump_usym (sym, addr, 0); /* let's not guess the size */
2810 //printf ("found symbol at %p: %s\n", (void*)addr, sym);
2816 mono_cpu_count (void)
2818 #ifdef PLATFORM_ANDROID
2819 /* Android tries really hard to save power by powering off CPUs on SMP phones which
2820 * means the normal way to query cpu count returns a wrong value with userspace API.
2821 * Instead we use /sys entries to query the actual hardware CPU count.
2824 char buffer[8] = {'\0'};
2825 int present = open ("/sys/devices/system/cpu/present", O_RDONLY);
2826 /* Format of the /sys entry is a cpulist of indexes which in the case
2827 * of present is always of the form "0-(n-1)" when there is more than
2828 * 1 core, n being the number of CPU cores in the system. Otherwise
2829 * the value is simply 0
2831 if (present != -1 && read (present, (char*)buffer, sizeof (buffer)) > 3)
2832 count = strtol (((char*)buffer) + 2, NULL, 10);
2839 #if defined(HOST_ARM) || defined (HOST_ARM64)
2841 /* ARM platforms tries really hard to save power by powering off CPUs on SMP phones which
2842 * means the normal way to query cpu count returns a wrong value with userspace API. */
2844 #ifdef _SC_NPROCESSORS_CONF
2846 int count = sysconf (_SC_NPROCESSORS_CONF);
2854 #ifdef HAVE_SCHED_GETAFFINITY
2857 if (sched_getaffinity (getpid (), sizeof (set), &set) == 0)
2858 return CPU_COUNT (&set);
2861 #ifdef _SC_NPROCESSORS_ONLN
2863 int count = sysconf (_SC_NPROCESSORS_ONLN);
2869 #endif /* defined(HOST_ARM) || defined (HOST_ARM64) */
2875 size_t len = sizeof (int);
2878 if (sysctl (mib, 2, &count, &len, NULL, 0) == 0)
2885 GetSystemInfo (&info);
2886 return info.dwNumberOfProcessors;
2897 unsigned int prev_pos;
2899 struct perf_event_mmap_page *page_desc;
2902 static PerfData *perf_data = NULL;
2903 static int num_perf;
2904 #define PERF_PAGES_SHIFT 4
2905 static int num_pages = 1 << PERF_PAGES_SHIFT;
2906 static unsigned int mmap_mask;
2909 struct perf_event_header h;
2919 perf_event_syscall (struct perf_event_attr *attr, pid_t pid, int cpu, int group_fd, unsigned long flags)
2921 attr->size = PERF_ATTR_SIZE_VER0;
2922 //printf ("perf attr size: %d\n", attr->size);
2923 #if defined(__x86_64__)
2924 return syscall(/*__NR_perf_event_open*/ 298, attr, pid, cpu, group_fd, flags);
2925 #elif defined(__i386__)
2926 return syscall(/*__NR_perf_event_open*/ 336, attr, pid, cpu, group_fd, flags);
2927 #elif defined(__arm__) || defined (__aarch64__)
2928 return syscall(/*__NR_perf_event_open*/ 364, attr, pid, cpu, group_fd, flags);
2935 setup_perf_map (PerfData *perf)
2937 perf->mmap_base = mmap (NULL, (num_pages + 1) * getpagesize (), PROT_READ|PROT_WRITE, MAP_SHARED, perf->perf_fd, 0);
2938 if (perf->mmap_base == MAP_FAILED) {
2940 printf ("failed mmap\n");
2943 perf->page_desc = perf->mmap_base;
2945 printf ("mmap version: %d\n", perf->page_desc->version);
2950 dump_perf_hits (MonoProfiler *prof, void *buf, int size)
2954 void *end = (char*)buf + size;
2956 int pid = getpid ();
2962 if (pid != s->pid) {
2964 printf ("event for different pid: %d\n", s->pid);
2965 buf = (char*)buf + s->h.size;
2968 /*ip = (void*)s->ip;
2969 printf ("sample: %d, size: %d, ip: %p (%s), timestamp: %llu, nframes: %llu\n",
2970 s->h.type, s->h.size, ip, symbol_for (ip), s->timestamp, s->nframes);*/
2974 LogBuffer *logbuffer = ensure_logbuf (
2975 EVENT_SIZE /* event */ +
2976 BYTE_SIZE /* type */ +
2977 LEB128_SIZE /* tid */ +
2978 LEB128_SIZE /* count */ +
2980 LEB128_SIZE /* ip */
2982 LEB128_SIZE /* managed count */ +
2984 LEB128_SIZE /* method */
2988 emit_event (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_HIT);
2989 emit_byte (logbuffer, sample_type);
2991 * No useful thread ID to write here, since throughout the
2992 * profiler we use pthread_self () but the ID we get from
2993 * perf is the kernel's thread ID.
2995 emit_ptr (logbuffer, 0);
2996 emit_value (logbuffer, count);
2997 emit_ptr (logbuffer, (void*)(uintptr_t)s->ip);
2998 /* no support here yet for the managed backtrace */
2999 emit_uvalue (logbuffer, mbt_count);
3003 add_code_pointer (s->ip);
3004 buf = (char*)buf + s->h.size;
3008 printf ("dumped %d samples\n", samples);
3009 dump_unmanaged_coderefs (prof);
3012 /* read events from the ring buffer */
3014 read_perf_mmap (MonoProfiler* prof, int cpu)
3016 PerfData *perf = perf_data + cpu;
3018 unsigned char *data = (unsigned char*)perf->mmap_base + getpagesize ();
3019 unsigned int head = perf->page_desc->data_head;
3023 mono_memory_read_barrier ();
3025 old = perf->prev_pos;
3029 printf ("lost mmap events: old: %d, head: %d\n", old, head);
3033 if ((old & mmap_mask) + size != (head & mmap_mask)) {
3034 buf = data + (old & mmap_mask);
3035 size = mmap_mask + 1 - (old & mmap_mask);
3037 /* size bytes at buf */
3039 printf ("found1 bytes of events: %d\n", size);
3040 dump_perf_hits (prof, buf, size);
3042 buf = data + (old & mmap_mask);
3044 /* size bytes at buf */
3046 printf ("found bytes of events: %d\n", size);
3047 dump_perf_hits (prof, buf, size);
3049 perf->prev_pos = old;
3050 perf->page_desc->data_tail = old;
3055 setup_perf_event_for_cpu (PerfData *perf, int cpu)
3057 struct perf_event_attr attr;
3058 memset (&attr, 0, sizeof (attr));
3059 attr.type = PERF_TYPE_HARDWARE;
3060 switch (sample_type) {
3061 case SAMPLE_CYCLES: attr.config = PERF_COUNT_HW_CPU_CYCLES; break;
3062 case SAMPLE_INSTRUCTIONS: attr.config = PERF_COUNT_HW_INSTRUCTIONS; break;
3063 case SAMPLE_CACHE_MISSES: attr.config = PERF_COUNT_HW_CACHE_MISSES; break;
3064 case SAMPLE_CACHE_REFS: attr.config = PERF_COUNT_HW_CACHE_REFERENCES; break;
3065 case SAMPLE_BRANCHES: attr.config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS; break;
3066 case SAMPLE_BRANCH_MISSES: attr.config = PERF_COUNT_HW_BRANCH_MISSES; break;
3067 default: attr.config = PERF_COUNT_HW_CPU_CYCLES; break;
3069 attr.sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID | PERF_SAMPLE_PERIOD | PERF_SAMPLE_TIME;
3070 // attr.sample_type |= PERF_SAMPLE_CALLCHAIN;
3071 attr.read_format = PERF_FORMAT_TOTAL_TIME_ENABLED | PERF_FORMAT_TOTAL_TIME_RUNNING | PERF_FORMAT_ID;
3074 attr.sample_freq = sample_freq;
3076 perf->perf_fd = perf_event_syscall (&attr, getpid (), cpu, -1, 0);
3078 printf ("perf fd: %d, freq: %d, event: %llu\n", perf->perf_fd, sample_freq, attr.config);
3079 if (perf->perf_fd < 0) {
3080 if (perf->perf_fd == -EPERM) {
3081 fprintf (stderr, "Perf syscall denied, do \"echo 1 > /proc/sys/kernel/perf_event_paranoid\" as root to enable.\n");
3084 perror ("open perf event");
3088 if (!setup_perf_map (perf)) {
3089 close (perf->perf_fd);
3097 setup_perf_event (void)
3100 mmap_mask = num_pages * getpagesize () - 1;
3101 num_perf = mono_cpu_count ();
3102 perf_data = calloc (num_perf, sizeof (PerfData));
3103 for (i = 0; i < num_perf; ++i) {
3104 count += setup_perf_event_for_cpu (perf_data + i, i);
3113 #endif /* USE_PERF_EVENTS */
3115 #ifndef DISABLE_HELPER_THREAD
3117 typedef struct MonoCounterAgent {
3118 MonoCounter *counter;
3119 // MonoCounterAgent specific data :
3124 struct MonoCounterAgent *next;
3127 static MonoCounterAgent* counters;
3128 static gboolean counters_initialized = FALSE;
3129 static int counters_index = 1;
3130 static mono_mutex_t counters_mutex;
3133 counters_add_agent (MonoCounter *counter)
3135 MonoCounterAgent *agent, *item;
3137 if (!counters_initialized)
3140 mono_os_mutex_lock (&counters_mutex);
3142 for (agent = counters; agent; agent = agent->next) {
3143 if (agent->counter == counter) {
3144 agent->value_size = 0;
3146 free (agent->value);
3147 agent->value = NULL;
3149 mono_os_mutex_unlock (&counters_mutex);
3154 agent = (MonoCounterAgent *)malloc (sizeof (MonoCounterAgent));
3155 agent->counter = counter;
3156 agent->value = NULL;
3157 agent->value_size = 0;
3158 agent->index = counters_index++;
3171 mono_os_mutex_unlock (&counters_mutex);
3175 counters_init_foreach_callback (MonoCounter *counter, gpointer data)
3177 counters_add_agent (counter);
3182 counters_init (MonoProfiler *profiler)
3184 assert (!counters_initialized);
3186 mono_os_mutex_init (&counters_mutex);
3188 counters_initialized = TRUE;
3190 mono_counters_on_register (&counters_add_agent);
3191 mono_counters_foreach (counters_init_foreach_callback, NULL);
3195 counters_emit (MonoProfiler *profiler)
3197 MonoCounterAgent *agent;
3200 EVENT_SIZE /* event */ +
3201 LEB128_SIZE /* len */
3204 if (!counters_initialized)
3207 mono_os_mutex_lock (&counters_mutex);
3209 for (agent = counters; agent; agent = agent->next) {
3214 LEB128_SIZE /* section */ +
3215 strlen (mono_counter_get_name (agent->counter)) + 1 /* name */ +
3216 BYTE_SIZE /* type */ +
3217 BYTE_SIZE /* unit */ +
3218 BYTE_SIZE /* variance */ +
3219 LEB128_SIZE /* index */
3226 mono_os_mutex_unlock (&counters_mutex);
3232 LogBuffer *logbuffer = ensure_logbuf (size);
3234 emit_event (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
3235 emit_value (logbuffer, len);
3237 for (agent = counters; agent; agent = agent->next) {
3243 name = mono_counter_get_name (agent->counter);
3244 emit_value (logbuffer, mono_counter_get_section (agent->counter));
3245 emit_string (logbuffer, name, strlen (name) + 1);
3246 emit_byte (logbuffer, mono_counter_get_type (agent->counter));
3247 emit_byte (logbuffer, mono_counter_get_unit (agent->counter));
3248 emit_byte (logbuffer, mono_counter_get_variance (agent->counter));
3249 emit_value (logbuffer, agent->index);
3256 mono_os_mutex_unlock (&counters_mutex);
3260 counters_sample (MonoProfiler *profiler, uint64_t timestamp)
3262 MonoCounterAgent *agent;
3263 MonoCounter *counter;
3269 if (!counters_initialized)
3272 counters_emit (profiler);
3275 buffer = calloc (1, buffer_size);
3277 mono_os_mutex_lock (&counters_mutex);
3280 EVENT_SIZE /* event */
3283 for (agent = counters; agent; agent = agent->next) {
3285 LEB128_SIZE /* index */ +
3286 BYTE_SIZE /* type */ +
3287 mono_counter_get_size (agent->counter) /* value */
3292 LEB128_SIZE /* stop marker */
3297 LogBuffer *logbuffer = ensure_logbuf (size);
3299 emit_event_time (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE, timestamp);
3301 for (agent = counters; agent; agent = agent->next) {
3304 counter = agent->counter;
3306 size = mono_counter_get_size (counter);
3308 continue; // FIXME error
3309 } else if (size > buffer_size) {
3311 buffer = realloc (buffer, buffer_size);
3314 memset (buffer, 0, buffer_size);
3316 if (mono_counters_sample (counter, buffer, size) < 0)
3317 continue; // FIXME error
3319 type = mono_counter_get_type (counter);
3321 if (!agent->value) {
3322 agent->value = calloc (1, size);
3323 agent->value_size = size;
3325 if (type == MONO_COUNTER_STRING) {
3326 if (strcmp (agent->value, buffer) == 0)
3329 if (agent->value_size == size && memcmp (agent->value, buffer, size) == 0)
3334 emit_uvalue (logbuffer, agent->index);
3335 emit_byte (logbuffer, type);
3337 case MONO_COUNTER_INT:
3338 #if SIZEOF_VOID_P == 4
3339 case MONO_COUNTER_WORD:
3341 emit_svalue (logbuffer, *(int*)buffer - *(int*)agent->value);
3343 case MONO_COUNTER_UINT:
3344 emit_uvalue (logbuffer, *(guint*)buffer - *(guint*)agent->value);
3346 case MONO_COUNTER_TIME_INTERVAL:
3347 case MONO_COUNTER_LONG:
3348 #if SIZEOF_VOID_P == 8
3349 case MONO_COUNTER_WORD:
3351 emit_svalue (logbuffer, *(gint64*)buffer - *(gint64*)agent->value);
3353 case MONO_COUNTER_ULONG:
3354 emit_uvalue (logbuffer, *(guint64*)buffer - *(guint64*)agent->value);
3356 case MONO_COUNTER_DOUBLE:
3357 emit_double (logbuffer, *(double*)buffer);
3359 case MONO_COUNTER_STRING:
3361 emit_byte (logbuffer, 0);
3363 emit_byte (logbuffer, 1);
3364 emit_string (logbuffer, (char*)buffer, size);
3371 if (type == MONO_COUNTER_STRING && size > agent->value_size) {
3372 agent->value = realloc (agent->value, size);
3373 agent->value_size = size;
3377 memcpy (agent->value, buffer, size);
3381 emit_value (logbuffer, 0);
3385 mono_os_mutex_unlock (&counters_mutex);
3388 typedef struct _PerfCounterAgent PerfCounterAgent;
3389 struct _PerfCounterAgent {
3390 PerfCounterAgent *next;
3392 char *category_name;
3401 static PerfCounterAgent *perfcounters = NULL;
3404 perfcounters_emit (MonoProfiler *profiler)
3406 PerfCounterAgent *pcagent;
3409 EVENT_SIZE /* event */ +
3410 LEB128_SIZE /* len */
3413 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3414 if (pcagent->emitted)
3418 LEB128_SIZE /* section */ +
3419 strlen (pcagent->category_name) + 1 /* category name */ +
3420 strlen (pcagent->name) + 1 /* name */ +
3421 BYTE_SIZE /* type */ +
3422 BYTE_SIZE /* unit */ +
3423 BYTE_SIZE /* variance */ +
3424 LEB128_SIZE /* index */
3435 LogBuffer *logbuffer = ensure_logbuf (size);
3437 emit_event (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
3438 emit_value (logbuffer, len);
3440 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3441 if (pcagent->emitted)
3444 emit_value (logbuffer, MONO_COUNTER_PERFCOUNTERS);
3445 emit_string (logbuffer, pcagent->category_name, strlen (pcagent->category_name) + 1);
3446 emit_string (logbuffer, pcagent->name, strlen (pcagent->name) + 1);
3447 emit_byte (logbuffer, MONO_COUNTER_LONG);
3448 emit_byte (logbuffer, MONO_COUNTER_RAW);
3449 emit_byte (logbuffer, MONO_COUNTER_VARIABLE);
3450 emit_value (logbuffer, pcagent->index);
3452 pcagent->emitted = 1;
3459 perfcounters_foreach (char *category_name, char *name, unsigned char type, gint64 value, gpointer user_data)
3461 PerfCounterAgent *pcagent;
3463 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3464 if (strcmp (pcagent->category_name, category_name) != 0 || strcmp (pcagent->name, name) != 0)
3466 if (pcagent->value == value)
3469 pcagent->value = value;
3470 pcagent->updated = 1;
3471 pcagent->deleted = 0;
3475 pcagent = g_new0 (PerfCounterAgent, 1);
3476 pcagent->next = perfcounters;
3477 pcagent->index = counters_index++;
3478 pcagent->category_name = g_strdup (category_name);
3479 pcagent->name = g_strdup (name);
3480 pcagent->type = (int) type;
3481 pcagent->value = value;
3482 pcagent->emitted = 0;
3483 pcagent->updated = 1;
3484 pcagent->deleted = 0;
3486 perfcounters = pcagent;
3492 perfcounters_sample (MonoProfiler *profiler, uint64_t timestamp)
3494 PerfCounterAgent *pcagent;
3497 if (!counters_initialized)
3500 mono_os_mutex_lock (&counters_mutex);
3502 /* mark all perfcounters as deleted, foreach will unmark them as necessary */
3503 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next)
3504 pcagent->deleted = 1;
3506 mono_perfcounter_foreach (perfcounters_foreach, perfcounters);
3508 perfcounters_emit (profiler);
3511 EVENT_SIZE /* event */
3514 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3515 if (pcagent->deleted || !pcagent->updated)
3519 LEB128_SIZE /* index */ +
3520 BYTE_SIZE /* type */ +
3521 LEB128_SIZE /* value */
3526 LEB128_SIZE /* stop marker */
3531 LogBuffer *logbuffer = ensure_logbuf (size);
3533 emit_event_time (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE, timestamp);
3535 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3536 if (pcagent->deleted || !pcagent->updated)
3538 emit_uvalue (logbuffer, pcagent->index);
3539 emit_byte (logbuffer, MONO_COUNTER_LONG);
3540 emit_svalue (logbuffer, pcagent->value);
3542 pcagent->updated = 0;
3545 emit_value (logbuffer, 0);
3549 mono_os_mutex_unlock (&counters_mutex);
3553 counters_and_perfcounters_sample (MonoProfiler *prof)
3555 uint64_t now = current_time ();
3557 counters_sample (prof, now);
3558 perfcounters_sample (prof, now);
3561 #define COVERAGE_DEBUG(x) if (debug_coverage) {x}
3562 static mono_mutex_t coverage_mutex;
3563 static MonoConcurrentHashTable *coverage_methods = NULL;
3564 static MonoConcurrentHashTable *coverage_assemblies = NULL;
3565 static MonoConcurrentHashTable *coverage_classes = NULL;
3567 static MonoConcurrentHashTable *filtered_classes = NULL;
3568 static MonoConcurrentHashTable *entered_methods = NULL;
3569 static MonoConcurrentHashTable *image_to_methods = NULL;
3570 static MonoConcurrentHashTable *suppressed_assemblies = NULL;
3571 static gboolean coverage_initialized = FALSE;
3573 static GPtrArray *coverage_data = NULL;
3574 static int previous_offset = 0;
3577 MonoLockFreeQueueNode node;
3590 free_coverage_entry (gpointer data, gpointer userdata)
3592 CoverageEntry *entry = (CoverageEntry *)data;
3593 g_free (entry->filename);
3598 obtain_coverage_for_method (MonoProfiler *prof, const MonoProfileCoverageEntry *entry)
3600 int offset = entry->iloffset - previous_offset;
3601 CoverageEntry *e = g_new (CoverageEntry, 1);
3603 previous_offset = entry->iloffset;
3606 e->counter = entry->counter;
3607 e->filename = g_strdup(entry->filename ? entry->filename : "");
3608 e->line = entry->line;
3609 e->column = entry->col;
3611 g_ptr_array_add (coverage_data, e);
3615 parse_generic_type_names(char *name)
3617 char *new_name, *ret;
3618 int within_generic_declaration = 0, generic_members = 1;
3620 if (name == NULL || *name == '\0')
3621 return g_strdup ("");
3623 if (!(ret = new_name = (char *)calloc (strlen (name) * 4 + 1, sizeof (char))))
3629 within_generic_declaration = 1;
3633 within_generic_declaration = 0;
3635 if (*(name - 1) != '<') {
3637 *new_name++ = '0' + generic_members;
3639 memcpy (new_name, "<>", 8);
3643 generic_members = 0;
3651 if (!within_generic_declaration)
3652 *new_name++ = *name;
3661 static int method_id;
3663 build_method_buffer (gpointer key, gpointer value, gpointer userdata)
3665 MonoMethod *method = (MonoMethod *)value;
3666 MonoProfiler *prof = (MonoProfiler *)userdata;
3670 const char *image_name, *method_name, *sig, *first_filename;
3673 previous_offset = 0;
3674 coverage_data = g_ptr_array_new ();
3676 mono_profiler_coverage_get (prof, method, obtain_coverage_for_method);
3678 klass = mono_method_get_class (method);
3679 image = mono_class_get_image (klass);
3680 image_name = mono_image_get_name (image);
3682 sig = mono_signature_get_desc (mono_method_signature (method), TRUE);
3683 class_name = parse_generic_type_names (mono_type_get_name (mono_class_get_type (klass)));
3684 method_name = mono_method_get_name (method);
3686 if (coverage_data->len != 0) {
3687 CoverageEntry *entry = (CoverageEntry *)coverage_data->pdata[0];
3688 first_filename = entry->filename ? entry->filename : "";
3690 first_filename = "";
3692 image_name = image_name ? image_name : "";
3693 sig = sig ? sig : "";
3694 method_name = method_name ? method_name : "";
3698 LogBuffer *logbuffer = ensure_logbuf (
3699 EVENT_SIZE /* event */ +
3700 strlen (image_name) + 1 /* image name */ +
3701 strlen (class_name) + 1 /* class name */ +
3702 strlen (method_name) + 1 /* method name */ +
3703 strlen (sig) + 1 /* signature */ +
3704 strlen (first_filename) + 1 /* first file name */ +
3705 LEB128_SIZE /* token */ +
3706 LEB128_SIZE /* method id */ +
3707 LEB128_SIZE /* entries */
3710 emit_event (logbuffer, TYPE_COVERAGE_METHOD | TYPE_COVERAGE);
3711 emit_string (logbuffer, image_name, strlen (image_name) + 1);
3712 emit_string (logbuffer, class_name, strlen (class_name) + 1);
3713 emit_string (logbuffer, method_name, strlen (method_name) + 1);
3714 emit_string (logbuffer, sig, strlen (sig) + 1);
3715 emit_string (logbuffer, first_filename, strlen (first_filename) + 1);
3717 emit_uvalue (logbuffer, mono_method_get_token (method));
3718 emit_uvalue (logbuffer, method_id);
3719 emit_value (logbuffer, coverage_data->len);
3723 send_if_needed (prof);
3725 for (i = 0; i < coverage_data->len; i++) {
3726 CoverageEntry *entry = (CoverageEntry *)coverage_data->pdata[i];
3730 LogBuffer *logbuffer = ensure_logbuf (
3731 EVENT_SIZE /* event */ +
3732 LEB128_SIZE /* method id */ +
3733 LEB128_SIZE /* offset */ +
3734 LEB128_SIZE /* counter */ +
3735 LEB128_SIZE /* line */ +
3736 LEB128_SIZE /* column */
3739 emit_event (logbuffer, TYPE_COVERAGE_STATEMENT | TYPE_COVERAGE);
3740 emit_uvalue (logbuffer, method_id);
3741 emit_uvalue (logbuffer, entry->offset);
3742 emit_uvalue (logbuffer, entry->counter);
3743 emit_uvalue (logbuffer, entry->line);
3744 emit_uvalue (logbuffer, entry->column);
3748 send_if_needed (prof);
3753 g_free (class_name);
3755 g_ptr_array_foreach (coverage_data, free_coverage_entry, NULL);
3756 g_ptr_array_free (coverage_data, TRUE);
3757 coverage_data = NULL;
3760 /* This empties the queue */
3762 count_queue (MonoLockFreeQueue *queue)
3764 MonoLockFreeQueueNode *node;
3767 while ((node = mono_lock_free_queue_dequeue (queue))) {
3769 mono_thread_hazardous_try_free (node, free);
3776 build_class_buffer (gpointer key, gpointer value, gpointer userdata)
3778 MonoClass *klass = (MonoClass *)key;
3779 MonoLockFreeQueue *class_methods = (MonoLockFreeQueue *)value;
3780 MonoProfiler *prof = (MonoProfiler *)userdata;
3783 const char *assembly_name;
3784 int number_of_methods, partially_covered;
3785 guint fully_covered;
3787 image = mono_class_get_image (klass);
3788 assembly_name = mono_image_get_name (image);
3789 class_name = mono_type_get_name (mono_class_get_type (klass));
3791 assembly_name = assembly_name ? assembly_name : "";
3792 number_of_methods = mono_class_num_methods (klass);
3793 fully_covered = count_queue (class_methods);
3794 /* We don't handle partial covered yet */
3795 partially_covered = 0;
3799 LogBuffer *logbuffer = ensure_logbuf (
3800 EVENT_SIZE /* event */ +
3801 strlen (assembly_name) + 1 /* assembly name */ +
3802 strlen (class_name) + 1 /* class name */ +
3803 LEB128_SIZE /* no. methods */ +
3804 LEB128_SIZE /* fully covered */ +
3805 LEB128_SIZE /* partially covered */
3808 emit_event (logbuffer, TYPE_COVERAGE_CLASS | TYPE_COVERAGE);
3809 emit_string (logbuffer, assembly_name, strlen (assembly_name) + 1);
3810 emit_string (logbuffer, class_name, strlen (class_name) + 1);
3811 emit_uvalue (logbuffer, number_of_methods);
3812 emit_uvalue (logbuffer, fully_covered);
3813 emit_uvalue (logbuffer, partially_covered);
3817 send_if_needed (prof);
3819 g_free (class_name);
3823 get_coverage_for_image (MonoImage *image, int *number_of_methods, guint *fully_covered, int *partially_covered)
3825 MonoLockFreeQueue *image_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (image_to_methods, image);
3827 *number_of_methods = mono_image_get_table_rows (image, MONO_TABLE_METHOD);
3829 *fully_covered = count_queue (image_methods);
3833 // FIXME: We don't handle partially covered yet.
3834 *partially_covered = 0;
3838 build_assembly_buffer (gpointer key, gpointer value, gpointer userdata)
3840 MonoAssembly *assembly = (MonoAssembly *)value;
3841 MonoProfiler *prof = (MonoProfiler *)userdata;
3842 MonoImage *image = mono_assembly_get_image (assembly);
3843 const char *name, *guid, *filename;
3844 int number_of_methods = 0, partially_covered = 0;
3845 guint fully_covered = 0;
3847 name = mono_image_get_name (image);
3848 guid = mono_image_get_guid (image);
3849 filename = mono_image_get_filename (image);
3851 name = name ? name : "";
3852 guid = guid ? guid : "";
3853 filename = filename ? filename : "";
3855 get_coverage_for_image (image, &number_of_methods, &fully_covered, &partially_covered);
3859 LogBuffer *logbuffer = ensure_logbuf (
3860 EVENT_SIZE /* event */ +
3861 strlen (name) + 1 /* name */ +
3862 strlen (guid) + 1 /* guid */ +
3863 strlen (filename) + 1 /* file name */ +
3864 LEB128_SIZE /* no. methods */ +
3865 LEB128_SIZE /* fully covered */ +
3866 LEB128_SIZE /* partially covered */
3869 emit_event (logbuffer, TYPE_COVERAGE_ASSEMBLY | TYPE_COVERAGE);
3870 emit_string (logbuffer, name, strlen (name) + 1);
3871 emit_string (logbuffer, guid, strlen (guid) + 1);
3872 emit_string (logbuffer, filename, strlen (filename) + 1);
3873 emit_uvalue (logbuffer, number_of_methods);
3874 emit_uvalue (logbuffer, fully_covered);
3875 emit_uvalue (logbuffer, partially_covered);
3879 send_if_needed (prof);
3883 dump_coverage (MonoProfiler *prof)
3885 if (!coverage_initialized)
3888 COVERAGE_DEBUG(fprintf (stderr, "Coverage: Started dump\n");)
3891 mono_os_mutex_lock (&coverage_mutex);
3892 mono_conc_hashtable_foreach (coverage_assemblies, build_assembly_buffer, prof);
3893 mono_conc_hashtable_foreach (coverage_classes, build_class_buffer, prof);
3894 mono_conc_hashtable_foreach (coverage_methods, build_method_buffer, prof);
3895 mono_os_mutex_unlock (&coverage_mutex);
3897 COVERAGE_DEBUG(fprintf (stderr, "Coverage: Finished dump\n");)
3901 process_method_enter_coverage (MonoProfiler *prof, MonoMethod *method)
3906 if (!coverage_initialized)
3909 klass = mono_method_get_class (method);
3910 image = mono_class_get_image (klass);
3912 if (mono_conc_hashtable_lookup (suppressed_assemblies, (gpointer) mono_image_get_name (image)))
3915 mono_os_mutex_lock (&coverage_mutex);
3916 mono_conc_hashtable_insert (entered_methods, method, method);
3917 mono_os_mutex_unlock (&coverage_mutex);
3920 static MonoLockFreeQueueNode *
3921 create_method_node (MonoMethod *method)
3923 MethodNode *node = (MethodNode *)g_malloc (sizeof (MethodNode));
3924 mono_lock_free_queue_node_init ((MonoLockFreeQueueNode *) node, FALSE);
3925 node->method = method;
3927 return (MonoLockFreeQueueNode *) node;
3931 coverage_filter (MonoProfiler *prof, MonoMethod *method)
3936 MonoAssembly *assembly;
3937 MonoMethodHeader *header;
3938 guint32 iflags, flags, code_size;
3939 char *fqn, *classname;
3940 gboolean has_positive, found;
3941 MonoLockFreeQueue *image_methods, *class_methods;
3942 MonoLockFreeQueueNode *node;
3944 if (!coverage_initialized)
3947 COVERAGE_DEBUG(fprintf (stderr, "Coverage filter for %s\n", mono_method_get_name (method));)
3949 flags = mono_method_get_flags (method, &iflags);
3950 if ((iflags & 0x1000 /*METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL*/) ||
3951 (flags & 0x2000 /*METHOD_ATTRIBUTE_PINVOKE_IMPL*/)) {
3952 COVERAGE_DEBUG(fprintf (stderr, " Internal call or pinvoke - ignoring\n");)
3956 // Don't need to do anything else if we're already tracking this method
3957 if (mono_conc_hashtable_lookup (coverage_methods, method)) {
3958 COVERAGE_DEBUG(fprintf (stderr, " Already tracking\n");)
3962 klass = mono_method_get_class (method);
3963 image = mono_class_get_image (klass);
3965 // Don't handle coverage for the core assemblies
3966 if (mono_conc_hashtable_lookup (suppressed_assemblies, (gpointer) mono_image_get_name (image)) != NULL)
3969 if (prof->coverage_filters) {
3970 /* Check already filtered classes first */
3971 if (mono_conc_hashtable_lookup (filtered_classes, klass)) {
3972 COVERAGE_DEBUG(fprintf (stderr, " Already filtered\n");)
3976 classname = mono_type_get_name (mono_class_get_type (klass));
3978 fqn = g_strdup_printf ("[%s]%s", mono_image_get_name (image), classname);
3980 COVERAGE_DEBUG(fprintf (stderr, " Looking for %s in filter\n", fqn);)
3981 // Check positive filters first
3982 has_positive = FALSE;
3984 for (guint i = 0; i < prof->coverage_filters->len; ++i) {
3985 char *filter = (char *)g_ptr_array_index (prof->coverage_filters, i);
3987 if (filter [0] == '+') {
3988 filter = &filter [1];
3990 COVERAGE_DEBUG(fprintf (stderr, " Checking against +%s ...", filter);)
3992 if (strstr (fqn, filter) != NULL) {
3993 COVERAGE_DEBUG(fprintf (stderr, "matched\n");)
3996 COVERAGE_DEBUG(fprintf (stderr, "no match\n");)
3998 has_positive = TRUE;
4002 if (has_positive && !found) {
4003 COVERAGE_DEBUG(fprintf (stderr, " Positive match was not found\n");)
4005 mono_os_mutex_lock (&coverage_mutex);
4006 mono_conc_hashtable_insert (filtered_classes, klass, klass);
4007 mono_os_mutex_unlock (&coverage_mutex);
4014 for (guint i = 0; i < prof->coverage_filters->len; ++i) {
4015 // FIXME: Is substring search sufficient?
4016 char *filter = (char *)g_ptr_array_index (prof->coverage_filters, i);
4017 if (filter [0] == '+')
4021 filter = &filter [1];
4022 COVERAGE_DEBUG(fprintf (stderr, " Checking against -%s ...", filter);)
4024 if (strstr (fqn, filter) != NULL) {
4025 COVERAGE_DEBUG(fprintf (stderr, "matched\n");)
4027 mono_os_mutex_lock (&coverage_mutex);
4028 mono_conc_hashtable_insert (filtered_classes, klass, klass);
4029 mono_os_mutex_unlock (&coverage_mutex);
4035 COVERAGE_DEBUG(fprintf (stderr, "no match\n");)
4043 COVERAGE_DEBUG(fprintf (stderr, " Handling coverage for %s\n", mono_method_get_name (method));)
4044 header = mono_method_get_header_checked (method, &error);
4045 mono_error_cleanup (&error);
4047 mono_method_header_get_code (header, &code_size, NULL);
4049 assembly = mono_image_get_assembly (image);
4051 // Need to keep the assemblies around for as long as they are kept in the hashtable
4052 // Nunit, for example, has a habit of unloading them before the coverage statistics are
4053 // generated causing a crash. See https://bugzilla.xamarin.com/show_bug.cgi?id=39325
4054 mono_assembly_addref (assembly);
4056 mono_os_mutex_lock (&coverage_mutex);
4057 mono_conc_hashtable_insert (coverage_methods, method, method);
4058 mono_conc_hashtable_insert (coverage_assemblies, assembly, assembly);
4059 mono_os_mutex_unlock (&coverage_mutex);
4061 image_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (image_to_methods, image);
4063 if (image_methods == NULL) {
4064 image_methods = (MonoLockFreeQueue *)g_malloc (sizeof (MonoLockFreeQueue));
4065 mono_lock_free_queue_init (image_methods);
4066 mono_os_mutex_lock (&coverage_mutex);
4067 mono_conc_hashtable_insert (image_to_methods, image, image_methods);
4068 mono_os_mutex_unlock (&coverage_mutex);
4071 node = create_method_node (method);
4072 mono_lock_free_queue_enqueue (image_methods, node);
4074 class_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (coverage_classes, klass);
4076 if (class_methods == NULL) {
4077 class_methods = (MonoLockFreeQueue *)g_malloc (sizeof (MonoLockFreeQueue));
4078 mono_lock_free_queue_init (class_methods);
4079 mono_os_mutex_lock (&coverage_mutex);
4080 mono_conc_hashtable_insert (coverage_classes, klass, class_methods);
4081 mono_os_mutex_unlock (&coverage_mutex);
4084 node = create_method_node (method);
4085 mono_lock_free_queue_enqueue (class_methods, node);
4090 #define LINE_BUFFER_SIZE 4096
4091 /* Max file limit of 128KB */
4092 #define MAX_FILE_SIZE 128 * 1024
4094 get_file_content (FILE *stream)
4099 int res, offset = 0;
4101 res = fseek (stream, 0, SEEK_END);
4105 filesize = ftell (stream);
4109 res = fseek (stream, 0, SEEK_SET);
4113 if (filesize > MAX_FILE_SIZE)
4116 buffer = (char *)g_malloc ((filesize + 1) * sizeof (char));
4117 while ((bytes_read = fread (buffer + offset, 1, LINE_BUFFER_SIZE, stream)) > 0)
4118 offset += bytes_read;
4120 /* NULL terminate our buffer */
4121 buffer[filesize] = '\0';
4126 get_next_line (char *contents, char **next_start)
4130 if (p == NULL || *p == '\0') {
4135 while (*p != '\n' && *p != '\0')
4140 *next_start = p + 1;
4148 init_suppressed_assemblies (void)
4154 suppressed_assemblies = mono_conc_hashtable_new (g_str_hash, g_str_equal);
4155 sa_file = fopen (SUPPRESSION_DIR "/mono-profiler-log.suppression", "r");
4156 if (sa_file == NULL)
4159 /* Don't need to free @content as it is referred to by the lines stored in @suppressed_assemblies */
4160 content = get_file_content (sa_file);
4161 if (content == NULL) {
4162 g_error ("mono-profiler-log.suppression is greater than 128kb - aborting\n");
4165 while ((line = get_next_line (content, &content))) {
4166 line = g_strchomp (g_strchug (line));
4167 /* No locking needed as we're doing initialization */
4168 mono_conc_hashtable_insert (suppressed_assemblies, line, line);
4174 #endif /* DISABLE_HELPER_THREAD */
4177 coverage_init (MonoProfiler *prof)
4179 #ifndef DISABLE_HELPER_THREAD
4180 assert (!coverage_initialized);
4182 COVERAGE_DEBUG(fprintf (stderr, "Coverage initialized\n");)
4184 mono_os_mutex_init (&coverage_mutex);
4185 coverage_methods = mono_conc_hashtable_new (NULL, NULL);
4186 coverage_assemblies = mono_conc_hashtable_new (NULL, NULL);
4187 coverage_classes = mono_conc_hashtable_new (NULL, NULL);
4188 filtered_classes = mono_conc_hashtable_new (NULL, NULL);
4189 entered_methods = mono_conc_hashtable_new (NULL, NULL);
4190 image_to_methods = mono_conc_hashtable_new (NULL, NULL);
4191 init_suppressed_assemblies ();
4193 coverage_initialized = TRUE;
4194 #endif /* DISABLE_HELPER_THREAD */
4198 unref_coverage_assemblies (gpointer key, gpointer value, gpointer userdata)
4200 MonoAssembly *assembly = (MonoAssembly *)value;
4201 mono_assembly_close (assembly);
4205 free_sample_hit (gpointer p)
4207 mono_lock_free_free (p, SAMPLE_BLOCK_SIZE);
4211 cleanup_reusable_samples (MonoProfiler *prof)
4215 while ((sample = (SampleHit *) mono_lock_free_queue_dequeue (&prof->sample_reuse_queue)))
4216 mono_thread_hazardous_try_free (sample, free_sample_hit);
4220 log_shutdown (MonoProfiler *prof)
4225 #ifndef DISABLE_HELPER_THREAD
4226 counters_and_perfcounters_sample (prof);
4228 dump_coverage (prof);
4230 if (prof->command_port) {
4232 ign_res (write (prof->pipes [1], &c, 1));
4233 pthread_join (prof->helper_thread, &res);
4239 for (i = 0; i < num_perf; ++i)
4240 read_perf_mmap (prof, i);
4245 * Ensure that we empty the LLS completely, even if some nodes are
4246 * not immediately removed upon calling mono_lls_remove (), by
4247 * iterating until the head is NULL.
4249 while (profiler_thread_list.head) {
4250 MONO_LLS_FOREACH_SAFE (&profiler_thread_list, MonoProfilerThread, thread) {
4251 remove_thread (prof, thread, FALSE);
4252 } MONO_LLS_FOREACH_SAFE_END
4255 InterlockedWrite (&prof->run_dumper_thread, 0);
4256 mono_os_sem_post (&prof->dumper_queue_sem);
4257 pthread_join (prof->dumper_thread, &res);
4258 mono_os_sem_destroy (&prof->dumper_queue_sem);
4260 InterlockedWrite (&prof->run_writer_thread, 0);
4261 mono_os_sem_post (&prof->writer_queue_sem);
4262 pthread_join (prof->writer_thread, &res);
4263 mono_os_sem_destroy (&prof->writer_queue_sem);
4265 cleanup_reusable_samples (prof);
4267 g_assert (!InterlockedRead (&buffer_rwlock_count) && "Why is the reader count still non-zero?");
4268 g_assert (!InterlockedReadPointer (&buffer_rwlock_exclusive) && "Why does someone still hold the exclusive lock?");
4270 #if defined (HAVE_SYS_ZLIB)
4272 gzclose (prof->gzfile);
4274 if (prof->pipe_output)
4275 pclose (prof->file);
4277 fclose (prof->file);
4279 mono_conc_hashtable_destroy (prof->method_table);
4280 mono_os_mutex_destroy (&prof->method_table_mutex);
4282 if (coverage_initialized) {
4283 mono_os_mutex_lock (&coverage_mutex);
4284 mono_conc_hashtable_foreach (coverage_assemblies, unref_coverage_assemblies, prof);
4285 mono_os_mutex_unlock (&coverage_mutex);
4287 mono_conc_hashtable_destroy (coverage_methods);
4288 mono_conc_hashtable_destroy (coverage_assemblies);
4289 mono_conc_hashtable_destroy (coverage_classes);
4290 mono_conc_hashtable_destroy (filtered_classes);
4292 mono_conc_hashtable_destroy (entered_methods);
4293 mono_conc_hashtable_destroy (image_to_methods);
4294 mono_conc_hashtable_destroy (suppressed_assemblies);
4295 mono_os_mutex_destroy (&coverage_mutex);
4304 new_filename (const char* filename)
4306 time_t t = time (NULL);
4307 int pid = process_id ();
4312 int count_dates = 0;
4316 for (p = filename; *p; p++) {
4327 if (!count_dates && !count_pids)
4328 return pstrdup (filename);
4329 snprintf (pid_buf, sizeof (pid_buf), "%d", pid);
4331 snprintf (time_buf, sizeof (time_buf), "%d%02d%02d%02d%02d%02d",
4332 1900 + ts->tm_year, 1 + ts->tm_mon, ts->tm_mday, ts->tm_hour, ts->tm_min, ts->tm_sec);
4333 s_date = strlen (time_buf);
4334 s_pid = strlen (pid_buf);
4335 d = res = (char *)malloc (strlen (filename) + s_date * count_dates + s_pid * count_pids);
4336 for (p = filename; *p; p++) {
4343 strcpy (d, time_buf);
4346 } else if (*p == 'p') {
4347 strcpy (d, pid_buf);
4350 } else if (*p == '%') {
4362 //this is exposed by the JIT, but it's not meant to be a supported API for now.
4363 extern void mono_threads_attach_tools_thread (void);
4365 #ifndef DISABLE_HELPER_THREAD
4368 helper_thread (void* arg)
4370 MonoProfiler* prof = (MonoProfiler *)arg;
4375 mono_threads_attach_tools_thread ();
4376 mono_native_thread_set_name (mono_native_thread_id_get (), "Profiler helper");
4378 init_thread (FALSE);
4380 //fprintf (stderr, "Server listening\n");
4381 command_socket = -1;
4387 FD_SET (prof->server_socket, &rfds);
4388 max_fd = prof->server_socket;
4389 FD_SET (prof->pipes [0], &rfds);
4390 if (max_fd < prof->pipes [0])
4391 max_fd = prof->pipes [0];
4392 if (command_socket >= 0) {
4393 FD_SET (command_socket, &rfds);
4394 if (max_fd < command_socket)
4395 max_fd = command_socket;
4400 for ( i = 0; i < num_perf; ++i) {
4401 if (perf_data [i].perf_fd < 0)
4403 FD_SET (perf_data [i].perf_fd, &rfds);
4404 if (max_fd < perf_data [i].perf_fd)
4405 max_fd = perf_data [i].perf_fd;
4410 counters_and_perfcounters_sample (prof);
4412 buffer_lock_excl ();
4414 sync_point (prof, SYNC_POINT_PERIODIC);
4416 buffer_unlock_excl ();
4420 len = select (max_fd + 1, &rfds, NULL, NULL, &tv);
4426 g_warning ("Error in proflog server: %s", strerror (errno));
4430 if (FD_ISSET (prof->pipes [0], &rfds)) {
4432 read (prof->pipes [0], &c, 1);
4434 fprintf (stderr, "helper shutdown\n");
4438 for ( i = 0; i < num_perf; ++i) {
4439 if (perf_data [i].perf_fd < 0)
4441 if (FD_ISSET (perf_data [i].perf_fd, &rfds))
4442 read_perf_mmap (prof, i);
4446 safe_send_threadless (prof);
4452 for ( i = 0; i < num_perf; ++i) {
4453 if (perf_data [i].perf_fd < 0)
4455 if (FD_ISSET (perf_data [i].perf_fd, &rfds)) {
4456 read_perf_mmap (prof, i);
4457 send_if_needed_threadless (prof);
4462 if (command_socket >= 0 && FD_ISSET (command_socket, &rfds)) {
4463 len = read (command_socket, buf, sizeof (buf) - 1);
4467 close (command_socket);
4468 command_socket = -1;
4472 if (strcmp (buf, "heapshot\n") == 0 && hs_mode_ondemand) {
4473 // Rely on the finalization callbacks invoking process_requests ().
4474 heapshot_requested = 1;
4475 mono_gc_finalize_notify ();
4479 if (!FD_ISSET (prof->server_socket, &rfds)) {
4482 command_socket = accept (prof->server_socket, NULL, NULL);
4483 if (command_socket < 0)
4485 //fprintf (stderr, "Accepted connection\n");
4488 mono_thread_info_detach ();
4494 start_helper_thread (MonoProfiler* prof)
4496 struct sockaddr_in server_address;
4499 if (pipe (prof->pipes) < 0) {
4500 fprintf (stderr, "Cannot create pipe\n");
4503 prof->server_socket = socket (PF_INET, SOCK_STREAM, 0);
4504 if (prof->server_socket < 0) {
4505 fprintf (stderr, "Cannot create server socket\n");
4508 memset (&server_address, 0, sizeof (server_address));
4509 server_address.sin_family = AF_INET;
4510 server_address.sin_addr.s_addr = INADDR_ANY;
4511 server_address.sin_port = htons (prof->command_port);
4512 if (bind (prof->server_socket, (struct sockaddr *) &server_address, sizeof (server_address)) < 0) {
4513 fprintf (stderr, "Cannot bind server socket, port: %d: %s\n", prof->command_port, strerror (errno));
4514 close (prof->server_socket);
4517 if (listen (prof->server_socket, 1) < 0) {
4518 fprintf (stderr, "Cannot listen server socket\n");
4519 close (prof->server_socket);
4522 slen = sizeof (server_address);
4523 if (getsockname (prof->server_socket, (struct sockaddr *)&server_address, &slen) == 0) {
4524 prof->command_port = ntohs (server_address.sin_port);
4525 /*fprintf (stderr, "Assigned server port: %d\n", prof->command_port);*/
4528 r = pthread_create (&prof->helper_thread, NULL, helper_thread, prof);
4530 close (prof->server_socket);
4538 free_writer_entry (gpointer p)
4540 mono_lock_free_free (p, WRITER_ENTRY_BLOCK_SIZE);
4544 handle_writer_queue_entry (MonoProfiler *prof)
4546 WriterQueueEntry *entry;
4548 if ((entry = (WriterQueueEntry *) mono_lock_free_queue_dequeue (&prof->writer_queue))) {
4549 if (!entry->methods)
4552 LogBuffer *buf = NULL;
4555 * Encode the method events in a temporary log buffer that we
4556 * flush to disk before the main buffer, ensuring that all
4557 * methods have metadata emitted before they're referenced.
4559 * We use a 'proper' thread-local buffer for this as opposed
4560 * to allocating and freeing a buffer by hand because the call
4561 * to mono_method_full_name () below may trigger class load
4562 * events when it retrieves the signature of the method. So a
4563 * thread-local buffer needs to exist when such events occur.
4565 for (guint i = 0; i < entry->methods->len; i++) {
4566 MethodInfo *info = (MethodInfo *) g_ptr_array_index (entry->methods, i);
4568 if (mono_conc_hashtable_lookup (prof->method_table, info->method))
4569 goto free_info; // This method already has metadata emitted.
4572 * Other threads use this hash table to get a general
4573 * idea of whether a method has already been emitted to
4574 * the stream. Due to the way we add to this table, it
4575 * can easily happen that multiple threads queue up the
4576 * same methods, but that's OK since eventually all
4577 * methods will be in this table and the thread-local
4578 * method lists will just be empty for the rest of the
4581 mono_os_mutex_lock (&prof->method_table_mutex);
4582 mono_conc_hashtable_insert (prof->method_table, info->method, info->method);
4583 mono_os_mutex_unlock (&prof->method_table_mutex);
4585 char *name = mono_method_full_name (info->method, 1);
4586 int nlen = strlen (name) + 1;
4587 void *cstart = info->ji ? mono_jit_info_get_code_start (info->ji) : NULL;
4588 int csize = info->ji ? mono_jit_info_get_code_size (info->ji) : 0;
4590 buf = ensure_logbuf_unsafe (
4591 EVENT_SIZE /* event */ +
4592 LEB128_SIZE /* method */ +
4593 LEB128_SIZE /* start */ +
4594 LEB128_SIZE /* size */ +
4598 emit_event_time (buf, TYPE_JIT | TYPE_METHOD, info->time);
4599 emit_method_inner (buf, info->method);
4600 emit_ptr (buf, cstart);
4601 emit_value (buf, csize);
4603 memcpy (buf->cursor, name, nlen);
4604 buf->cursor += nlen;
4612 g_ptr_array_free (entry->methods, TRUE);
4615 dump_buffer_threadless (prof, buf);
4616 init_buffer_state (PROF_TLS_GET ());
4620 dump_buffer (prof, entry->buffer);
4622 mono_thread_hazardous_try_free (entry, free_writer_entry);
4631 writer_thread (void *arg)
4633 MonoProfiler *prof = (MonoProfiler *)arg;
4635 mono_threads_attach_tools_thread ();
4636 mono_native_thread_set_name (mono_native_thread_id_get (), "Profiler writer");
4640 MonoProfilerThread *thread = init_thread (FALSE);
4642 while (InterlockedRead (&prof->run_writer_thread)) {
4643 mono_os_sem_wait (&prof->writer_queue_sem, MONO_SEM_FLAGS_NONE);
4644 handle_writer_queue_entry (prof);
4647 /* Drain any remaining entries on shutdown. */
4648 while (handle_writer_queue_entry (prof));
4650 free_buffer (thread->buffer, thread->buffer->size);
4651 deinit_thread (thread);
4653 mono_thread_info_detach ();
4659 start_writer_thread (MonoProfiler* prof)
4661 InterlockedWrite (&prof->run_writer_thread, 1);
4663 return !pthread_create (&prof->writer_thread, NULL, writer_thread, prof);
4667 reuse_sample_hit (gpointer p)
4669 SampleHit *sample = p;
4671 mono_lock_free_queue_node_unpoison (&sample->node);
4672 mono_lock_free_queue_enqueue (&sample->prof->sample_reuse_queue, &sample->node);
4676 handle_dumper_queue_entry (MonoProfiler *prof)
4680 if ((sample = (SampleHit *) mono_lock_free_queue_dequeue (&prof->dumper_queue))) {
4681 for (int i = 0; i < sample->count; ++i) {
4682 MonoMethod *method = sample->frames [i].method;
4683 MonoDomain *domain = sample->frames [i].domain;
4684 void *address = sample->frames [i].base_address;
4687 g_assert (domain && "What happened to the domain pointer?");
4688 g_assert (address && "What happened to the instruction pointer?");
4690 MonoJitInfo *ji = mono_jit_info_table_find (domain, (char *) address);
4693 sample->frames [i].method = mono_jit_info_get_method (ji);
4697 LogBuffer *logbuffer = ensure_logbuf_unsafe (
4698 EVENT_SIZE /* event */ +
4699 BYTE_SIZE /* type */ +
4700 LEB128_SIZE /* tid */ +
4701 LEB128_SIZE /* count */ +
4703 LEB128_SIZE /* ip */
4705 LEB128_SIZE /* managed count */ +
4707 LEB128_SIZE /* method */
4711 emit_event_time (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_HIT, sample->time);
4712 emit_byte (logbuffer, sample_type);
4713 emit_ptr (logbuffer, (void *) sample->tid);
4714 emit_value (logbuffer, 1);
4716 // TODO: Actual native unwinding.
4717 for (int i = 0; i < 1; ++i) {
4718 emit_ptr (logbuffer, sample->ip);
4719 add_code_pointer ((uintptr_t) sample->ip);
4722 /* new in data version 6 */
4723 emit_uvalue (logbuffer, sample->count);
4725 for (int i = 0; i < sample->count; ++i)
4726 emit_method (prof, logbuffer, sample->frames [i].method);
4728 mono_thread_hazardous_try_free (sample, reuse_sample_hit);
4730 dump_unmanaged_coderefs (prof);
4732 send_if_needed_threadless (prof);
4739 dumper_thread (void *arg)
4741 MonoProfiler *prof = (MonoProfiler *)arg;
4743 mono_threads_attach_tools_thread ();
4744 mono_native_thread_set_name (mono_native_thread_id_get (), "Profiler dumper");
4746 MonoProfilerThread *thread = init_thread (FALSE);
4748 while (InterlockedRead (&prof->run_dumper_thread)) {
4749 mono_os_sem_wait (&prof->dumper_queue_sem, MONO_SEM_FLAGS_NONE);
4750 handle_dumper_queue_entry (prof);
4753 /* Drain any remaining entries on shutdown. */
4754 while (handle_dumper_queue_entry (prof));
4756 safe_send_threadless (prof);
4757 deinit_thread (thread);
4759 mono_thread_info_detach ();
4765 start_dumper_thread (MonoProfiler* prof)
4767 InterlockedWrite (&prof->run_dumper_thread, 1);
4769 return !pthread_create (&prof->dumper_thread, NULL, dumper_thread, prof);
4773 runtime_initialized (MonoProfiler *profiler)
4775 InterlockedWrite (&runtime_inited, 1);
4777 #ifndef DISABLE_HELPER_THREAD
4778 if (hs_mode_ondemand || need_helper_thread) {
4779 if (!start_helper_thread (profiler))
4780 profiler->command_port = 0;
4784 start_writer_thread (profiler);
4785 start_dumper_thread (profiler);
4787 mono_counters_register ("Sample hits", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &sample_hits);
4788 mono_counters_register ("Sample flushes", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &sample_flushes);
4789 mono_counters_register ("Sample events allocated", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &sample_allocations);
4790 mono_counters_register ("Log buffers allocated", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &buffer_allocations);
4791 mono_counters_register ("Thread start events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &thread_starts);
4792 mono_counters_register ("Thread stop events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &thread_ends);
4793 mono_counters_register ("Domain load events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &domain_loads);
4794 mono_counters_register ("Domain unload events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &domain_unloads);
4795 mono_counters_register ("Context load events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &context_loads);
4796 mono_counters_register ("Context unload events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &context_unloads);
4797 mono_counters_register ("Assembly load events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &assembly_loads);
4798 mono_counters_register ("Assembly unload events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &assembly_unloads);
4799 mono_counters_register ("Image load events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &image_loads);
4800 mono_counters_register ("Image unload events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &image_unloads);
4801 mono_counters_register ("Class load events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &class_loads);
4802 mono_counters_register ("Class unload events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &class_unloads);
4804 #ifndef DISABLE_HELPER_THREAD
4805 counters_init (profiler);
4806 counters_sample (profiler, 0);
4808 /* ensure the main thread data and startup are available soon */
4809 safe_send (profiler);
4812 static MonoProfiler*
4813 create_profiler (const char *filename, GPtrArray *filters)
4817 int force_delete = 0;
4818 prof = (MonoProfiler *)calloc (1, sizeof (MonoProfiler));
4820 prof->command_port = command_port;
4821 if (filename && *filename == '-') {
4827 filename = "|mprof-report -";
4829 filename = "output.mlpd";
4830 nf = (char*)filename;
4832 nf = new_filename (filename);
4834 int s = strlen (nf) + 32;
4835 char *p = (char *)malloc (s);
4836 snprintf (p, s, "|mprof-report '--out=%s' -", nf);
4842 prof->file = popen (nf + 1, "w");
4843 prof->pipe_output = 1;
4844 } else if (*nf == '#') {
4845 int fd = strtol (nf + 1, NULL, 10);
4846 prof->file = fdopen (fd, "a");
4850 prof->file = fopen (nf, "wb");
4853 fprintf (stderr, "Cannot create profiler output: %s\n", nf);
4856 #if defined (HAVE_SYS_ZLIB)
4858 prof->gzfile = gzdopen (fileno (prof->file), "wb");
4861 if (sample_type && !do_mono_sample)
4862 need_helper_thread = setup_perf_event ();
4864 /* FIXME: warn if different freq or sample type */
4868 if (do_mono_sample) {
4869 need_helper_thread = 1;
4871 if (do_counters && !need_helper_thread) {
4872 need_helper_thread = 1;
4876 * If you hit this assert while increasing MAX_FRAMES, you need to increase
4877 * SAMPLE_BLOCK_SIZE as well.
4879 g_assert (SAMPLE_SLOT_SIZE (MAX_FRAMES) * 2 < LOCK_FREE_ALLOC_SB_USABLE_SIZE (SAMPLE_BLOCK_SIZE));
4881 // FIXME: We should free this stuff too.
4882 mono_lock_free_allocator_init_size_class (&prof->sample_size_class, SAMPLE_SLOT_SIZE (num_frames), SAMPLE_BLOCK_SIZE);
4883 mono_lock_free_allocator_init_allocator (&prof->sample_allocator, &prof->sample_size_class);
4885 mono_lock_free_queue_init (&prof->sample_reuse_queue);
4887 #ifdef DISABLE_HELPER_THREAD
4888 if (hs_mode_ondemand)
4889 fprintf (stderr, "Ondemand heapshot unavailable on this arch.\n");
4892 fprintf (stderr, "Coverage unavailable on this arch.\n");
4896 g_assert (sizeof (WriterQueueEntry) * 2 < LOCK_FREE_ALLOC_SB_USABLE_SIZE (WRITER_ENTRY_BLOCK_SIZE));
4898 // FIXME: We should free this stuff too.
4899 mono_lock_free_allocator_init_size_class (&prof->writer_entry_size_class, sizeof (WriterQueueEntry), WRITER_ENTRY_BLOCK_SIZE);
4900 mono_lock_free_allocator_init_allocator (&prof->writer_entry_allocator, &prof->writer_entry_size_class);
4902 mono_lock_free_queue_init (&prof->writer_queue);
4903 mono_os_sem_init (&prof->writer_queue_sem, 0);
4905 mono_lock_free_queue_init (&prof->dumper_queue);
4906 mono_os_sem_init (&prof->dumper_queue_sem, 0);
4908 mono_os_mutex_init (&prof->method_table_mutex);
4909 prof->method_table = mono_conc_hashtable_new (NULL, NULL);
4912 coverage_init (prof);
4913 prof->coverage_filters = filters;
4915 prof->startup_time = current_time ();
4922 printf ("Log profiler version %d.%d (format: %d)\n", LOG_VERSION_MAJOR, LOG_VERSION_MINOR, LOG_DATA_VERSION);
4923 printf ("Usage: mono --profile=log[:OPTION1[,OPTION2...]] program.exe\n");
4924 printf ("Options:\n");
4925 printf ("\thelp show this usage info\n");
4926 printf ("\t[no]alloc enable/disable recording allocation info\n");
4927 printf ("\t[no]calls enable/disable recording enter/leave method events\n");
4928 printf ("\theapshot[=MODE] record heap shot info (by default at each major collection)\n");
4929 printf ("\t MODE: every XXms milliseconds, every YYgc collections, ondemand\n");
4930 printf ("\tcounters sample counters every 1s\n");
4931 printf ("\tsample[=TYPE] use statistical sampling mode (by default cycles/100)\n");
4932 printf ("\t TYPE: cycles,instr,cacherefs,cachemiss,branches,branchmiss\n");
4933 printf ("\t TYPE can be followed by /FREQUENCY\n");
4934 printf ("\ttime=fast use a faster (but more inaccurate) timer\n");
4935 printf ("\tmaxframes=NUM collect up to NUM stack frames\n");
4936 printf ("\tcalldepth=NUM ignore method events for call chain depth bigger than NUM\n");
4937 printf ("\toutput=FILENAME write the data to file FILENAME (-FILENAME to overwrite)\n");
4938 printf ("\toutput=|PROGRAM write the data to the stdin of PROGRAM\n");
4939 printf ("\t %%t is subtituted with date and time, %%p with the pid\n");
4940 printf ("\treport create a report instead of writing the raw data to a file\n");
4941 printf ("\tzip compress the output data\n");
4942 printf ("\tport=PORTNUM use PORTNUM for the listening command server\n");
4943 printf ("\tcoverage enable collection of code coverage data\n");
4944 printf ("\tcovfilter=ASSEMBLY add an assembly to the code coverage filters\n");
4945 printf ("\t add a + to include the assembly or a - to exclude it\n");
4946 printf ("\t filter=-mscorlib\n");
4947 printf ("\tcovfilter-file=FILE use FILE to generate the list of assemblies to be filtered\n");
4953 match_option (const char* p, const char *opt, char **rval)
4955 int len = strlen (opt);
4956 if (strncmp (p, opt, len) == 0) {
4958 if (p [len] == '=' && p [len + 1]) {
4959 const char *opt = p + len + 1;
4960 const char *end = strchr (opt, ',');
4968 val = (char *)malloc (l + 1);
4969 memcpy (val, opt, l);
4974 if (p [len] == 0 || p [len] == ',') {
4976 return p + len + (p [len] == ',');
4994 static const SampleMode sample_modes [] = {
4995 {"cycles", SAMPLE_CYCLES},
4996 {"instr", SAMPLE_INSTRUCTIONS},
4997 {"cachemiss", SAMPLE_CACHE_MISSES},
4998 {"cacherefs", SAMPLE_CACHE_REFS},
4999 {"branches", SAMPLE_BRANCHES},
5000 {"branchmiss", SAMPLE_BRANCH_MISSES},
5005 set_sample_mode (char* val, int allow_empty)
5008 char *maybe_freq = NULL;
5010 const SampleMode *smode = sample_modes;
5011 #ifndef USE_PERF_EVENTS
5014 if (allow_empty && !val) {
5015 sample_type = SAMPLE_CYCLES;
5019 if (strcmp (val, "mono") == 0) {
5021 sample_type = SAMPLE_CYCLES;
5025 for (smode = sample_modes; smode->name; smode++) {
5026 int l = strlen (smode->name);
5027 if (strncmp (val, smode->name, l) == 0) {
5028 sample_type = smode->sample_mode;
5029 maybe_freq = val + l;
5035 if (*maybe_freq == '/') {
5036 count = strtoul (maybe_freq + 1, &end, 10);
5037 if (maybe_freq + 1 == end)
5039 sample_freq = count;
5040 } else if (*maybe_freq != 0) {
5049 set_hsmode (char* val, int allow_empty)
5053 if (allow_empty && !val)
5055 if (strcmp (val, "ondemand") == 0) {
5056 hs_mode_ondemand = 1;
5060 count = strtoul (val, &end, 10);
5063 if (strcmp (end, "ms") == 0)
5065 else if (strcmp (end, "gc") == 0)
5073 * declaration to silence the compiler: this is the entry point that
5074 * mono will load from the shared library and call.
5077 mono_profiler_startup (const char *desc);
5080 mono_profiler_startup_log (const char *desc);
5083 * this is the entry point that will be used when the profiler
5084 * is embedded inside the main executable.
5087 mono_profiler_startup_log (const char *desc)
5089 mono_profiler_startup (desc);
5093 mono_profiler_startup (const char *desc)
5096 GPtrArray *filters = NULL;
5097 char *filename = NULL;
5101 int calls_enabled = 0;
5102 int allocs_enabled = 0;
5103 int only_counters = 0;
5104 int only_coverage = 0;
5105 int events = MONO_PROFILE_GC|MONO_PROFILE_ALLOCATIONS|
5106 MONO_PROFILE_GC_MOVES|MONO_PROFILE_CLASS_EVENTS|MONO_PROFILE_THREADS|
5107 MONO_PROFILE_ENTER_LEAVE|MONO_PROFILE_JIT_COMPILATION|MONO_PROFILE_EXCEPTIONS|
5108 MONO_PROFILE_MONITOR_EVENTS|MONO_PROFILE_MODULE_EVENTS|MONO_PROFILE_GC_ROOTS|
5109 MONO_PROFILE_INS_COVERAGE|MONO_PROFILE_APPDOMAIN_EVENTS|MONO_PROFILE_CONTEXT_EVENTS|
5110 MONO_PROFILE_ASSEMBLY_EVENTS|MONO_PROFILE_GC_FINALIZATION;
5112 max_allocated_sample_hits = mono_cpu_count () * 1000;
5115 if (strncmp (p, "log", 3))
5120 for (; *p; p = opt) {
5126 if ((opt = match_option (p, "help", NULL)) != p) {
5130 if ((opt = match_option (p, "calls", NULL)) != p) {
5134 if ((opt = match_option (p, "nocalls", NULL)) != p) {
5135 events &= ~MONO_PROFILE_ENTER_LEAVE;
5139 if ((opt = match_option (p, "alloc", NULL)) != p) {
5143 if ((opt = match_option (p, "noalloc", NULL)) != p) {
5144 events &= ~MONO_PROFILE_ALLOCATIONS;
5147 if ((opt = match_option (p, "time", &val)) != p) {
5148 if (strcmp (val, "fast") == 0)
5150 else if (strcmp (val, "null") == 0)
5157 if ((opt = match_option (p, "report", NULL)) != p) {
5161 if ((opt = match_option (p, "debug", NULL)) != p) {
5165 if ((opt = match_option (p, "sampling-real", NULL)) != p) {
5166 sampling_mode = MONO_PROFILER_STAT_MODE_REAL;
5169 if ((opt = match_option (p, "sampling-process", NULL)) != p) {
5170 sampling_mode = MONO_PROFILER_STAT_MODE_PROCESS;
5173 if ((opt = match_option (p, "heapshot", &val)) != p) {
5174 events &= ~MONO_PROFILE_ALLOCATIONS;
5175 events &= ~MONO_PROFILE_ENTER_LEAVE;
5178 set_hsmode (val, 1);
5181 if ((opt = match_option (p, "sample", &val)) != p) {
5182 events &= ~MONO_PROFILE_ALLOCATIONS;
5183 events &= ~MONO_PROFILE_ENTER_LEAVE;
5185 set_sample_mode (val, 1);
5188 if ((opt = match_option (p, "hsmode", &val)) != p) {
5189 fprintf (stderr, "The hsmode profiler option is obsolete, use heapshot=MODE.\n");
5190 set_hsmode (val, 0);
5193 if ((opt = match_option (p, "zip", NULL)) != p) {
5197 if ((opt = match_option (p, "output", &val)) != p) {
5201 if ((opt = match_option (p, "port", &val)) != p) {
5203 command_port = strtoul (val, &end, 10);
5207 if ((opt = match_option (p, "maxframes", &val)) != p) {
5209 num_frames = strtoul (val, &end, 10);
5210 if (num_frames > MAX_FRAMES)
5211 num_frames = MAX_FRAMES;
5213 notraces = num_frames == 0;
5216 if ((opt = match_option (p, "maxsamples", &val)) != p) {
5218 max_allocated_sample_hits = strtoul (val, &end, 10);
5219 if (!max_allocated_sample_hits)
5220 max_allocated_sample_hits = G_MAXINT32;
5224 if ((opt = match_option (p, "calldepth", &val)) != p) {
5226 max_call_depth = strtoul (val, &end, 10);
5230 if ((opt = match_option (p, "counters", NULL)) != p) {
5234 if ((opt = match_option (p, "countersonly", NULL)) != p) {
5238 if ((opt = match_option (p, "coverage", NULL)) != p) {
5240 events |= MONO_PROFILE_ENTER_LEAVE;
5241 debug_coverage = (g_getenv ("MONO_PROFILER_DEBUG_COVERAGE") != NULL);
5244 if ((opt = match_option (p, "onlycoverage", NULL)) != p) {
5248 if ((opt = match_option (p, "covfilter-file", &val)) != p) {
5250 char *line, *content;
5252 if (filters == NULL)
5253 filters = g_ptr_array_new ();
5255 filter_file = fopen (val, "r");
5256 if (filter_file == NULL) {
5257 fprintf (stderr, "Unable to open %s\n", val);
5261 /* Don't need to free content as it is referred to by the lines stored in @filters */
5262 content = get_file_content (filter_file);
5263 if (content == NULL)
5264 fprintf (stderr, "WARNING: %s is greater than 128kb - ignoring\n", val);
5266 while ((line = get_next_line (content, &content)))
5267 g_ptr_array_add (filters, g_strchug (g_strchomp (line)));
5269 fclose (filter_file);
5272 if ((opt = match_option (p, "covfilter", &val)) != p) {
5273 if (filters == NULL)
5274 filters = g_ptr_array_new ();
5276 g_ptr_array_add (filters, val);
5284 if (calls_enabled) {
5285 events |= MONO_PROFILE_ENTER_LEAVE;
5289 events |= MONO_PROFILE_ALLOCATIONS;
5293 events = MONO_PROFILE_ENTER_LEAVE | MONO_PROFILE_INS_COVERAGE;
5295 utils_init (fast_time);
5299 prof = create_profiler (filename, filters);
5305 mono_lls_init (&profiler_thread_list, NULL);
5309 mono_profiler_install (prof, log_shutdown);
5310 mono_profiler_install_gc (gc_event, gc_resize);
5311 mono_profiler_install_allocation (gc_alloc);
5312 mono_profiler_install_gc_moves (gc_moves);
5313 mono_profiler_install_gc_roots (gc_handle, gc_roots);
5314 mono_profiler_install_gc_finalize (finalize_begin, finalize_object_begin, finalize_object_end, finalize_end);
5315 mono_profiler_install_appdomain (NULL, domain_loaded, domain_unloaded, NULL);
5316 mono_profiler_install_appdomain_name (domain_name);
5317 mono_profiler_install_context (context_loaded, context_unloaded);
5318 mono_profiler_install_class (NULL, class_loaded, class_unloaded, NULL);
5319 mono_profiler_install_module (NULL, image_loaded, image_unloaded, NULL);
5320 mono_profiler_install_assembly (NULL, assembly_loaded, assembly_unloaded, NULL);
5321 mono_profiler_install_thread (thread_start, thread_end);
5322 mono_profiler_install_thread_name (thread_name);
5323 mono_profiler_install_enter_leave (method_enter, method_leave);
5324 mono_profiler_install_jit_end (method_jitted);
5325 mono_profiler_install_code_buffer_new (code_buffer_new);
5326 mono_profiler_install_exception (throw_exc, method_exc_leave, clause_exc);
5327 mono_profiler_install_monitor (monitor_event);
5328 mono_profiler_install_runtime_initialized (runtime_initialized);
5330 mono_profiler_install_coverage_filter (coverage_filter);
5332 if (do_mono_sample && sample_type == SAMPLE_CYCLES && !only_counters) {
5333 events |= MONO_PROFILE_STATISTICAL;
5334 mono_profiler_set_statistical_mode (sampling_mode, sample_freq);
5335 mono_profiler_install_statistical (mono_sample_hit);
5338 mono_profiler_set_events ((MonoProfileFlags)events);