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/debug-helpers.h>
19 #include <mono/metadata/mono-config.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 * [args size: 4 bytes] size of args
178 * [args: string] arguments passed to the profiler
179 * [arch size: 4 bytes] size of arch
180 * [arch: string] architecture the profiler is running on
181 * [os size: 4 bytes] size of os
182 * [os: string] operating system the profiler is running on
184 * The multiple byte integers are in little-endian format.
187 * [buffer header] [event]*
188 * Buffers have a fixed-size header followed by 0 or more bytes of event data.
189 * Timing information and other values in the event data are usually stored
190 * as uleb128 or sleb128 integers. To save space, as noted for each item below,
191 * some data is represented as a difference between the actual value and
192 * either the last value of the same type (like for timing information) or
193 * as the difference from a value stored in a buffer header.
195 * For timing information the data is stored as uleb128, since timing
196 * increases in a monotonic way in each thread: the value is the number of
197 * nanoseconds to add to the last seen timing data in a buffer. The first value
198 * in a buffer will be calculated from the time_base field in the buffer head.
200 * Object or heap sizes are stored as uleb128.
201 * Pointer differences are stored as sleb128, instead.
203 * If an unexpected value is found, the rest of the buffer should be ignored,
204 * as generally the later values need the former to be interpreted correctly.
206 * buffer header format:
207 * [bufid: 4 bytes] constant value: BUF_ID
208 * [len: 4 bytes] size of the data following the buffer header
209 * [time_base: 8 bytes] time base in nanoseconds since an unspecified epoch
210 * [ptr_base: 8 bytes] base value for pointers
211 * [obj_base: 8 bytes] base value for object addresses
212 * [thread id: 8 bytes] system-specific thread ID (pthread_t for example)
213 * [method_base: 8 bytes] base value for MonoMethod pointers
216 * [extended info: upper 4 bits] [type: lower 4 bits]
217 * [time diff: uleb128] nanoseconds since last timing
219 * The data that follows depends on type and the extended info.
220 * Type is one of the enum values in proflog.h: TYPE_ALLOC, TYPE_GC,
221 * TYPE_METADATA, TYPE_METHOD, TYPE_EXCEPTION, TYPE_MONITOR, TYPE_HEAP.
222 * The extended info bits are interpreted based on type, see
223 * each individual event description below.
224 * strings are represented as a 0-terminated utf8 sequence.
227 * [num: uleb128] number of frames following
228 * [frame: sleb128]* mum MonoMethod* as a pointer difference from the last such
229 * pointer or the buffer method_base
233 * exinfo: flags: TYPE_ALLOC_BT
234 * [ptr: sleb128] class as a byte difference from ptr_base
235 * [obj: sleb128] object address as a byte difference from obj_base
236 * [size: uleb128] size of the object in the heap
237 * If the TYPE_ALLOC_BT flag is set, a backtrace follows.
241 * exinfo: one of TYPE_GC_EVENT, TYPE_GC_RESIZE, TYPE_GC_MOVE, TYPE_GC_HANDLE_CREATED[_BT],
242 * TYPE_GC_HANDLE_DESTROYED[_BT], TYPE_GC_FINALIZE_START, TYPE_GC_FINALIZE_END,
243 * TYPE_GC_FINALIZE_OBJECT_START, TYPE_GC_FINALIZE_OBJECT_END
244 * if exinfo == TYPE_GC_RESIZE
245 * [heap_size: uleb128] new heap size
246 * if exinfo == TYPE_GC_EVENT
247 * [event type: byte] GC event (MONO_GC_EVENT_* from profiler.h)
248 * [generation: byte] GC generation event refers to
249 * if exinfo == TYPE_GC_MOVE
250 * [num_objects: uleb128] number of object moves that follow
251 * [objaddr: sleb128]+ num_objects object pointer differences from obj_base
252 * num is always an even number: the even items are the old
253 * addresses, the odd numbers are the respective new object addresses
254 * if exinfo == TYPE_GC_HANDLE_CREATED[_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 * [objaddr: sleb128] object pointer differences from obj_base
259 * If exinfo == TYPE_GC_HANDLE_CREATED_BT, a backtrace follows.
260 * if exinfo == TYPE_GC_HANDLE_DESTROYED[_BT]
261 * [handle_type: uleb128] GC handle type (System.Runtime.InteropServices.GCHandleType)
262 * upper bits reserved as flags
263 * [handle: uleb128] GC handle value
264 * If exinfo == TYPE_GC_HANDLE_DESTROYED_BT, a backtrace follows.
265 * if exinfo == TYPE_GC_FINALIZE_OBJECT_{START,END}
266 * [object: sleb128] the object as a difference from obj_base
268 * type metadata format:
269 * type: TYPE_METADATA
270 * exinfo: one of: TYPE_END_LOAD, TYPE_END_UNLOAD (optional for TYPE_THREAD and TYPE_DOMAIN)
271 * [mtype: byte] metadata type, one of: TYPE_CLASS, TYPE_IMAGE, TYPE_ASSEMBLY, TYPE_DOMAIN,
272 * TYPE_THREAD, TYPE_CONTEXT
273 * [pointer: sleb128] pointer of the metadata type depending on mtype
274 * if mtype == TYPE_CLASS
275 * [image: sleb128] MonoImage* as a pointer difference from ptr_base
276 * [name: string] full class name
277 * if mtype == TYPE_IMAGE
278 * [name: string] image file name
279 * if mtype == TYPE_ASSEMBLY
280 * [name: string] assembly name
281 * if mtype == TYPE_DOMAIN && exinfo == 0
282 * [name: string] domain friendly name
283 * if mtype == TYPE_CONTEXT
284 * [domain: sleb128] domain id as pointer
285 * if mtype == TYPE_THREAD && exinfo == 0
286 * [name: string] thread name
288 * type method format:
290 * exinfo: one of: TYPE_LEAVE, TYPE_ENTER, TYPE_EXC_LEAVE, TYPE_JIT
291 * [method: sleb128] MonoMethod* as a pointer difference from the last such
292 * pointer or the buffer method_base
293 * if exinfo == TYPE_JIT
294 * [code address: sleb128] pointer to the native code as a diff from ptr_base
295 * [code size: uleb128] size of the generated code
296 * [name: string] full method name
298 * type exception format:
299 * type: TYPE_EXCEPTION
300 * exinfo: TYPE_THROW_BT flag or one of: TYPE_CLAUSE
301 * if exinfo == TYPE_CLAUSE
302 * [clause type: byte] MonoExceptionEnum enum value
303 * [clause index: uleb128] index of the current clause
304 * [method: sleb128] MonoMethod* as a pointer difference from the last such
305 * pointer or the buffer method_base
307 * [object: sleb128] the exception object as a difference from obj_base
308 * if exinfo has TYPE_THROW_BT set, a backtrace follows.
310 * type runtime format:
312 * exinfo: one of: TYPE_JITHELPER
313 * if exinfo == TYPE_JITHELPER
314 * [type: byte] MonoProfilerCodeBufferType enum value
315 * [buffer address: sleb128] pointer to the native code as a diff from ptr_base
316 * [buffer size: uleb128] size of the generated code
317 * if type == MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE
318 * [name: string] buffer description name
320 * type monitor format:
322 * exinfo: TYPE_MONITOR_BT flag and one of: MONO_PROFILER_MONITOR_(CONTENTION|FAIL|DONE)
323 * [object: sleb128] the lock object as a difference from obj_base
324 * if exinfo.low3bits == MONO_PROFILER_MONITOR_CONTENTION
325 * If the TYPE_MONITOR_BT flag is set, a backtrace follows.
329 * exinfo: one of TYPE_HEAP_START, TYPE_HEAP_END, TYPE_HEAP_OBJECT, TYPE_HEAP_ROOT
330 * if exinfo == TYPE_HEAP_OBJECT
331 * [object: sleb128] the object as a difference from obj_base
332 * [class: sleb128] the object MonoClass* as a difference from ptr_base
333 * [size: uleb128] size of the object on the heap
334 * [num_refs: uleb128] number of object references
335 * each referenced objref is preceded by a uleb128 encoded offset: the
336 * first offset is from the object address and each next offset is relative
337 * to the previous one
338 * [objrefs: sleb128]+ object referenced as a difference from obj_base
339 * The same object can appear multiple times, but only the first time
340 * with size != 0: in the other cases this data will only be used to
341 * provide additional referenced objects.
342 * if exinfo == TYPE_HEAP_ROOT
343 * [num_roots: uleb128] number of root references
344 * [num_gc: uleb128] number of major gcs
345 * [object: sleb128] the object as a difference from obj_base
346 * [root_type: byte] the root_type: MonoProfileGCRootType (profiler.h)
347 * [extra_info: uleb128] the extra_info value
348 * object, root_type and extra_info are repeated num_roots times
352 * exinfo: one of TYPE_SAMPLE_HIT, TYPE_SAMPLE_USYM, TYPE_SAMPLE_UBIN, TYPE_SAMPLE_COUNTERS_DESC, TYPE_SAMPLE_COUNTERS
353 * if exinfo == TYPE_SAMPLE_HIT
354 * [sample_type: byte] type of sample (SAMPLE_*)
355 * [thread: sleb128] thread id as difference from ptr_base
356 * [count: uleb128] number of following instruction addresses
357 * [ip: sleb128]* instruction pointer as difference from ptr_base
358 * [mbt_count: uleb128] number of managed backtrace frames
359 * [method: sleb128]* MonoMethod* as a pointer difference from the last such
360 * pointer or the buffer method_base (the first such method can be also indentified by ip, but this is not neccessarily true)
361 * if exinfo == TYPE_SAMPLE_USYM
362 * [address: sleb128] symbol address as a difference from ptr_base
363 * [size: uleb128] symbol size (may be 0 if unknown)
364 * [name: string] symbol name
365 * if exinfo == TYPE_SAMPLE_UBIN
366 * [address: sleb128] address where binary has been loaded
367 * [offset: uleb128] file offset of mapping (the same file can be mapped multiple times)
368 * [size: uleb128] memory size
369 * [name: string] binary name
370 * if exinfo == TYPE_SAMPLE_COUNTERS_DESC
371 * [len: uleb128] number of counters
373 * [section: uleb128] section of counter
374 * if section == MONO_COUNTER_PERFCOUNTERS:
375 * [section_name: string] section name of counter
376 * [name: string] name of counter
377 * [type: byte] type of counter
378 * [unit: byte] unit of counter
379 * [variance: byte] variance of counter
380 * [index: uleb128] unique index of counter
381 * if exinfo == TYPE_SAMPLE_COUNTERS
383 * [index: uleb128] unique index of counter
386 * [type: byte] type of counter value
389 * [0: uleb128] 0 -> value is null
391 * [1: uleb128] 1 -> value is not null
392 * [value: string] counter value
394 * [value: uleb128/sleb128/double] counter value, can be sleb128, uleb128 or double (determined by using type)
396 * type coverage format
397 * type: TYPE_COVERAGE
398 * exinfo: one of TYPE_COVERAGE_METHOD, TYPE_COVERAGE_STATEMENT, TYPE_COVERAGE_ASSEMBLY, TYPE_COVERAGE_CLASS
399 * if exinfo == TYPE_COVERAGE_METHOD
400 * [assembly: string] name of assembly
401 * [class: string] name of the class
402 * [name: string] name of the method
403 * [signature: string] the signature of the method
404 * [filename: string] the file path of the file that contains this method
405 * [token: uleb128] the method token
406 * [method_id: uleb128] an ID for this data to associate with the buffers of TYPE_COVERAGE_STATEMENTS
407 * [len: uleb128] the number of TYPE_COVERAGE_BUFFERS associated with this method
408 * if exinfo == TYPE_COVERAGE_STATEMENTS
409 * [method_id: uleb128] an the TYPE_COVERAGE_METHOD buffer to associate this with
410 * [offset: uleb128] the il offset relative to the previous offset
411 * [counter: uleb128] the counter for this instruction
412 * [line: uleb128] the line of filename containing this instruction
413 * [column: uleb128] the column containing this instruction
414 * if exinfo == TYPE_COVERAGE_ASSEMBLY
415 * [name: string] assembly name
416 * [guid: string] assembly GUID
417 * [filename: string] assembly filename
418 * [number_of_methods: uleb128] the number of methods in this assembly
419 * [fully_covered: uleb128] the number of fully covered methods
420 * [partially_covered: uleb128] the number of partially covered methods
421 * currently partially_covered will always be 0, and fully_covered is the
422 * number of methods that are fully and partially covered.
423 * if exinfo == TYPE_COVERAGE_CLASS
424 * [name: string] assembly name
425 * [class: string] class name
426 * [number_of_methods: uleb128] the number of methods in this class
427 * [fully_covered: uleb128] the number of fully covered methods
428 * [partially_covered: uleb128] the number of partially covered methods
429 * currently partially_covered will always be 0, and fully_covered is the
430 * number of methods that are fully and partially covered.
434 * exinfo: one of: TYPE_SYNC_POINT
435 * if exinfo == TYPE_SYNC_POINT
436 * [type: byte] MonoProfilerSyncPointType enum value
439 // Pending data to be written to the log, for a single thread.
440 // Threads periodically flush their own LogBuffers by calling safe_send
441 typedef struct _LogBuffer LogBuffer;
443 // Next (older) LogBuffer in processing queue
449 uintptr_t method_base;
450 uintptr_t last_method;
454 // Bytes allocated for this LogBuffer
457 // Start of currently unused space in buffer
458 unsigned char* cursor;
460 // Pointer to start-of-structure-plus-size (for convenience)
461 unsigned char* buf_end;
463 // Start of data in buffer. Contents follow "buffer format" described above.
464 unsigned char buf [1];
468 MonoLinkedListSetNode node;
470 // The current log buffer for this thread.
473 // Methods referenced by events in `buffer`, see `MethodInfo`.
476 // Current call depth for enter/leave events.
479 // Indicates whether this thread is currently writing to its `buffer`.
481 } MonoProfilerThread;
484 ign_res (int G_GNUC_UNUSED unused, ...)
489 * These macros create a scope to avoid leaking the buffer returned
490 * from ensure_logbuf () as it may have been invalidated by a GC
491 * thread during STW. If you called init_thread () with add_to_lls =
492 * FALSE, then don't use these macros.
498 g_assert (!PROF_TLS_GET ()->busy++ && "Why are we trying to write a new event while already writing one?")
501 PROF_TLS_GET ()->busy--; \
505 static volatile gint32 buffer_rwlock_count;
506 static volatile gpointer buffer_rwlock_exclusive;
508 // Can be used recursively.
513 * If the thread holding the exclusive lock tries to modify the
514 * reader count, just make it a no-op. This way, we also avoid
515 * invoking the GC safe point macros below, which could break if
516 * done from a thread that is currently the initiator of STW.
518 * In other words, we rely on the fact that the GC thread takes
519 * the exclusive lock in the gc_event () callback when the world
522 if (InterlockedReadPointer (&buffer_rwlock_exclusive) != (gpointer) thread_id ()) {
525 while (InterlockedReadPointer (&buffer_rwlock_exclusive))
526 mono_thread_info_yield ();
528 InterlockedIncrement (&buffer_rwlock_count);
533 mono_memory_barrier ();
539 mono_memory_barrier ();
541 // See the comment in buffer_lock ().
542 if (InterlockedReadPointer (&buffer_rwlock_exclusive) == (gpointer) thread_id ())
545 g_assert (InterlockedRead (&buffer_rwlock_count) && "Why are we trying to decrement a zero reader count?");
547 InterlockedDecrement (&buffer_rwlock_count);
550 // Cannot be used recursively.
552 buffer_lock_excl (void)
554 gpointer tid = (gpointer) thread_id ();
556 g_assert (InterlockedReadPointer (&buffer_rwlock_exclusive) != tid && "Why are we taking the exclusive lock twice?");
560 while (InterlockedCompareExchangePointer (&buffer_rwlock_exclusive, tid, 0))
561 mono_thread_info_yield ();
563 while (InterlockedRead (&buffer_rwlock_count))
564 mono_thread_info_yield ();
568 mono_memory_barrier ();
572 buffer_unlock_excl (void)
574 mono_memory_barrier ();
576 g_assert (InterlockedReadPointer (&buffer_rwlock_exclusive) && "Why is the exclusive lock not held?");
577 g_assert (InterlockedReadPointer (&buffer_rwlock_exclusive) == (gpointer) thread_id () && "Why does another thread hold the exclusive lock?");
578 g_assert (!InterlockedRead (&buffer_rwlock_count) && "Why are there readers when the exclusive lock is held?");
580 InterlockedWritePointer (&buffer_rwlock_exclusive, NULL);
583 typedef struct _BinaryObject BinaryObject;
584 struct _BinaryObject {
590 struct _MonoProfiler {
592 #if defined (HAVE_SYS_ZLIB)
596 uint64_t startup_time;
598 int last_gc_gen_started;
603 pthread_t helper_thread;
604 pthread_t writer_thread;
605 pthread_t dumper_thread;
607 volatile gint32 run_writer_thread;
608 MonoLockFreeAllocSizeClass writer_entry_size_class;
609 MonoLockFreeAllocator writer_entry_allocator;
610 MonoLockFreeQueue writer_queue;
611 MonoSemType writer_queue_sem;
612 MonoConcurrentHashTable *method_table;
613 mono_mutex_t method_table_mutex;
614 volatile gint32 run_dumper_thread;
615 MonoLockFreeQueue dumper_queue;
616 MonoSemType dumper_queue_sem;
617 MonoLockFreeAllocSizeClass sample_size_class;
618 MonoLockFreeAllocator sample_allocator;
619 MonoLockFreeQueue sample_reuse_queue;
620 BinaryObject *binary_objects;
621 GPtrArray *coverage_filters;
625 MonoLockFreeQueueNode node;
630 #define WRITER_ENTRY_BLOCK_SIZE (mono_pagesize ())
640 #define PROF_TLS_SET(VAL) (TlsSetValue (profiler_tls, (VAL)))
641 #define PROF_TLS_GET() ((MonoProfilerThread *) TlsGetValue (profiler_tls))
642 #define PROF_TLS_INIT() (profiler_tls = TlsAlloc ())
643 #define PROF_TLS_FREE() (TlsFree (profiler_tls))
645 static DWORD profiler_tls;
649 #define PROF_TLS_SET(VAL) (profiler_tls = (VAL))
650 #define PROF_TLS_GET() (profiler_tls)
651 #define PROF_TLS_INIT()
652 #define PROF_TLS_FREE()
654 static __thread MonoProfilerThread *profiler_tls;
658 #define PROF_TLS_SET(VAL) (pthread_setspecific (profiler_tls, (VAL)))
659 #define PROF_TLS_GET() ((MonoProfilerThread *) pthread_getspecific (profiler_tls))
660 #define PROF_TLS_INIT() (pthread_key_create (&profiler_tls, NULL))
661 #define PROF_TLS_FREE() (pthread_key_delete (&profiler_tls))
663 static pthread_key_t profiler_tls;
668 pstrdup (const char *s)
670 int len = strlen (s) + 1;
671 char *p = (char *)malloc (len);
679 LogBuffer* buf = (LogBuffer *)alloc_buffer (BUFFER_SIZE);
681 InterlockedIncrement (&buffer_allocations);
683 buf->size = BUFFER_SIZE;
684 buf->time_base = current_time ();
685 buf->last_time = buf->time_base;
686 buf->buf_end = (unsigned char*)buf + buf->size;
687 buf->cursor = buf->buf;
692 init_buffer_state (MonoProfilerThread *thread)
694 thread->buffer = create_buffer ();
695 thread->methods = NULL;
699 clear_hazard_pointers (MonoThreadHazardPointers *hp)
701 mono_hazard_pointer_clear (hp, 0);
702 mono_hazard_pointer_clear (hp, 1);
703 mono_hazard_pointer_clear (hp, 2);
706 static MonoProfilerThread *
707 init_thread (gboolean add_to_lls)
709 MonoProfilerThread *thread = PROF_TLS_GET ();
712 * Sometimes we may try to initialize a thread twice. One example is the
713 * main thread: We initialize it when setting up the profiler, but we will
714 * also get a thread_start () callback for it. Another example is when
715 * attaching new threads to the runtime: We may get a gc_alloc () callback
716 * for that thread's thread object (where we initialize it), soon followed
717 * by a thread_start () callback.
719 * These cases are harmless anyhow. Just return if we've already done the
720 * initialization work.
725 thread = malloc (sizeof (MonoProfilerThread));
726 thread->node.key = thread_id ();
727 thread->call_depth = 0;
730 init_buffer_state (thread);
733 * Some internal profiler threads don't need to be cleaned up
734 * by the main thread on shutdown.
737 MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
738 g_assert (mono_lls_insert (&profiler_thread_list, hp, &thread->node) && "Why can't we insert the thread in the LLS?");
739 clear_hazard_pointers (hp);
742 PROF_TLS_SET (thread);
747 // Only valid if init_thread () was called with add_to_lls = FALSE.
749 deinit_thread (MonoProfilerThread *thread)
756 ensure_logbuf_inner (LogBuffer *old, int bytes)
758 if (old && old->cursor + bytes + 100 < old->buf_end)
761 LogBuffer *new_ = create_buffer ();
767 // Only valid if init_thread () was called with add_to_lls = FALSE.
769 ensure_logbuf_unsafe (int bytes)
771 MonoProfilerThread *thread = PROF_TLS_GET ();
772 LogBuffer *old = thread->buffer;
773 LogBuffer *new_ = ensure_logbuf_inner (old, bytes);
776 return old; // Still enough space.
778 thread->buffer = new_;
784 * Any calls to this function should be wrapped in the ENTER_LOG and
785 * EXIT_LOG macros to prevent the returned pointer from leaking
786 * outside of the critical region created by the calls to buffer_lock ()
787 * and buffer_unlock () that those macros insert. If the pointer leaks,
788 * it can and will lead to crashes as the GC or helper thread may
789 * invalidate the pointer at any time.
791 * Note: If you're calling from a thread that called init_thread () with
792 * add_to_lls = FALSE, you should use ensure_logbuf_unsafe () and omit
796 ensure_logbuf (int bytes)
798 g_assert (PROF_TLS_GET ()->busy && "Why are we trying to expand our buffer without the busy flag set?");
800 return ensure_logbuf_unsafe (bytes);
804 emit_byte (LogBuffer *logbuffer, int value)
806 logbuffer->cursor [0] = value;
808 assert (logbuffer->cursor <= logbuffer->buf_end);
812 emit_value (LogBuffer *logbuffer, int value)
814 encode_uleb128 (value, logbuffer->cursor, &logbuffer->cursor);
815 assert (logbuffer->cursor <= logbuffer->buf_end);
819 emit_time (LogBuffer *logbuffer, uint64_t value)
821 uint64_t tdiff = value - logbuffer->last_time;
822 //if (value < logbuffer->last_time)
823 // printf ("time went backwards\n");
824 //if (tdiff > 1000000)
825 // printf ("large time offset: %llu\n", tdiff);
826 encode_uleb128 (tdiff, logbuffer->cursor, &logbuffer->cursor);
827 /*if (tdiff != decode_uleb128 (p, &p))
828 printf ("incorrect encoding: %llu\n", tdiff);*/
829 logbuffer->last_time = value;
830 assert (logbuffer->cursor <= logbuffer->buf_end);
834 emit_event_time (LogBuffer *logbuffer, int event, uint64_t time)
836 emit_byte (logbuffer, event);
837 emit_time (logbuffer, time);
841 emit_event (LogBuffer *logbuffer, int event)
843 emit_event_time (logbuffer, event, current_time ());
847 emit_svalue (LogBuffer *logbuffer, int64_t value)
849 encode_sleb128 (value, logbuffer->cursor, &logbuffer->cursor);
850 assert (logbuffer->cursor <= logbuffer->buf_end);
854 emit_uvalue (LogBuffer *logbuffer, uint64_t value)
856 encode_uleb128 (value, logbuffer->cursor, &logbuffer->cursor);
857 assert (logbuffer->cursor <= logbuffer->buf_end);
861 emit_ptr (LogBuffer *logbuffer, void *ptr)
863 if (!logbuffer->ptr_base)
864 logbuffer->ptr_base = (uintptr_t)ptr;
865 emit_svalue (logbuffer, (intptr_t)ptr - logbuffer->ptr_base);
866 assert (logbuffer->cursor <= logbuffer->buf_end);
870 emit_method_inner (LogBuffer *logbuffer, void *method)
872 if (!logbuffer->method_base) {
873 logbuffer->method_base = (intptr_t)method;
874 logbuffer->last_method = (intptr_t)method;
876 encode_sleb128 ((intptr_t)((char*)method - (char*)logbuffer->last_method), logbuffer->cursor, &logbuffer->cursor);
877 logbuffer->last_method = (intptr_t)method;
878 assert (logbuffer->cursor <= logbuffer->buf_end);
888 find_method (MonoDomain *domain, void *user_data)
890 MethodSearch *search = user_data;
895 MonoJitInfo *ji = mono_get_jit_info_from_method (domain, search->method);
897 // It could be AOT'd, so we need to get it from the AOT runtime's cache.
899 void *ip = mono_aot_get_method (domain, search->method);
901 // Avoid a slow path in mono_jit_info_table_find ().
903 ji = mono_jit_info_table_find (domain, ip);
912 register_method_local (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *ji)
914 if (!mono_conc_hashtable_lookup (prof->method_table, method)) {
916 * FIXME: In some cases, we crash while looking up JIT info for AOT'd methods.
917 * This usually happens for static constructors. This code is disabled for now
918 * as we don't need this info for anything critical.
920 * https://bugzilla.xamarin.com/show_bug.cgi?id=35171
924 MethodSearch search = { method, NULL };
926 mono_domain_foreach (find_method, &search);
933 * FIXME: We can't always find JIT info for a generic shared method, especially
934 * if we obtained the MonoMethod during an async stack walk. For now, we deal
935 * with this by giving the generic shared method name and dummy code start/size
936 * information (i.e. zeroes).
940 MethodInfo *info = (MethodInfo *) malloc (sizeof (MethodInfo));
942 info->method = method;
944 info->time = current_time ();
946 MonoProfilerThread *thread = PROF_TLS_GET ();
947 GPtrArray *arr = thread->methods ? thread->methods : (thread->methods = g_ptr_array_new ());
948 g_ptr_array_add (arr, info);
953 emit_method (MonoProfiler *prof, LogBuffer *logbuffer, MonoMethod *method)
955 register_method_local (prof, method, NULL);
956 emit_method_inner (logbuffer, method);
960 emit_obj (LogBuffer *logbuffer, void *ptr)
962 if (!logbuffer->obj_base)
963 logbuffer->obj_base = (uintptr_t)ptr >> 3;
964 emit_svalue (logbuffer, ((uintptr_t)ptr >> 3) - logbuffer->obj_base);
965 assert (logbuffer->cursor <= logbuffer->buf_end);
969 emit_string (LogBuffer *logbuffer, const char *str, size_t size)
973 for (; i < size; i++) {
976 emit_byte (logbuffer, str [i]);
979 emit_byte (logbuffer, '\0');
983 emit_double (LogBuffer *logbuffer, double value)
986 unsigned char buffer[8];
987 memcpy (buffer, &value, 8);
988 #if G_BYTE_ORDER == G_BIG_ENDIAN
989 for (i = 7; i >= 0; i--)
991 for (i = 0; i < 8; i++)
993 emit_byte (logbuffer, buffer[i]);
997 write_int16 (char *buf, int32_t value)
1000 for (i = 0; i < 2; ++i) {
1008 write_int32 (char *buf, int32_t value)
1011 for (i = 0; i < 4; ++i) {
1019 write_int64 (char *buf, int64_t value)
1022 for (i = 0; i < 8; ++i) {
1030 write_header_string (char *p, const char *str)
1032 size_t len = strlen (str) + 1;
1034 p = write_int32 (p, len);
1041 dump_header (MonoProfiler *profiler)
1043 const char *args = profiler->args;
1044 const char *arch = mono_config_get_cpu ();
1045 const char *os = mono_config_get_os ();
1047 char *hbuf = malloc (
1048 sizeof (gint32) /* header id */ +
1049 sizeof (gint8) /* major version */ +
1050 sizeof (gint8) /* minor version */ +
1051 sizeof (gint8) /* data version */ +
1052 sizeof (gint8) /* word size */ +
1053 sizeof (gint64) /* startup time */ +
1054 sizeof (gint32) /* timer overhead */ +
1055 sizeof (gint32) /* flags */ +
1056 sizeof (gint32) /* process id */ +
1057 sizeof (gint16) /* command port */ +
1058 sizeof (gint32) + strlen (args) + 1 /* arguments */ +
1059 sizeof (gint32) + strlen (arch) + 1 /* architecture */ +
1060 sizeof (gint32) + strlen (os) + 1 /* operating system */
1064 p = write_int32 (p, LOG_HEADER_ID);
1065 *p++ = LOG_VERSION_MAJOR;
1066 *p++ = LOG_VERSION_MINOR;
1067 *p++ = LOG_DATA_VERSION;
1068 *p++ = sizeof (void *);
1069 p = write_int64 (p, ((uint64_t) time (NULL)) * 1000);
1070 p = write_int32 (p, get_timer_overhead ());
1071 p = write_int32 (p, 0); /* flags */
1072 p = write_int32 (p, process_id ());
1073 p = write_int16 (p, profiler->command_port);
1074 p = write_header_string (p, args);
1075 p = write_header_string (p, arch);
1076 p = write_header_string (p, os);
1078 #if defined (HAVE_SYS_ZLIB)
1079 if (profiler->gzfile) {
1080 gzwrite (profiler->gzfile, hbuf, p - hbuf);
1084 fwrite (hbuf, p - hbuf, 1, profiler->file);
1085 fflush (profiler->file);
1092 send_buffer (MonoProfiler *prof, MonoProfilerThread *thread)
1094 WriterQueueEntry *entry = mono_lock_free_alloc (&prof->writer_entry_allocator);
1095 entry->methods = thread->methods;
1096 entry->buffer = thread->buffer;
1098 mono_lock_free_queue_node_init (&entry->node, FALSE);
1100 mono_lock_free_queue_enqueue (&prof->writer_queue, &entry->node);
1101 mono_os_sem_post (&prof->writer_queue_sem);
1105 remove_thread (MonoProfiler *prof, MonoProfilerThread *thread, gboolean from_callback)
1107 MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
1109 if (mono_lls_remove (&profiler_thread_list, hp, &thread->node)) {
1110 LogBuffer *buffer = thread->buffer;
1113 * No need to take the buffer lock here as no other threads can
1114 * be accessing this buffer anymore.
1117 if (!from_callback) {
1119 * The thread is being cleaned up by the main thread during
1120 * shutdown. This typically happens for internal runtime
1121 * threads. We need to synthesize a thread end event.
1124 buffer = ensure_logbuf_inner (buffer,
1125 EVENT_SIZE /* event */ +
1126 BYTE_SIZE /* type */ +
1127 LEB128_SIZE /* tid */
1130 emit_event (buffer, TYPE_END_UNLOAD | TYPE_METADATA);
1131 emit_byte (buffer, TYPE_THREAD);
1132 emit_ptr (buffer, (void *) thread->node.key);
1135 send_buffer (prof, thread);
1137 mono_thread_hazardous_try_free (thread, free);
1140 clear_hazard_pointers (hp);
1143 PROF_TLS_SET (NULL);
1147 dump_buffer (MonoProfiler *profiler, LogBuffer *buf)
1153 dump_buffer (profiler, buf->next);
1155 p = write_int32 (p, BUF_ID);
1156 p = write_int32 (p, buf->cursor - buf->buf);
1157 p = write_int64 (p, buf->time_base);
1158 p = write_int64 (p, buf->ptr_base);
1159 p = write_int64 (p, buf->obj_base);
1160 p = write_int64 (p, buf->thread_id);
1161 p = write_int64 (p, buf->method_base);
1163 #if defined (HAVE_SYS_ZLIB)
1164 if (profiler->gzfile) {
1165 gzwrite (profiler->gzfile, hbuf, p - hbuf);
1166 gzwrite (profiler->gzfile, buf->buf, buf->cursor - buf->buf);
1170 fwrite (hbuf, p - hbuf, 1, profiler->file);
1171 fwrite (buf->buf, buf->cursor - buf->buf, 1, profiler->file);
1172 fflush (profiler->file);
1175 free_buffer (buf, buf->size);
1179 dump_buffer_threadless (MonoProfiler *profiler, LogBuffer *buf)
1181 for (LogBuffer *iter = buf; iter; iter = iter->next)
1182 iter->thread_id = 0;
1184 dump_buffer (profiler, buf);
1188 process_requests (MonoProfiler *profiler)
1190 if (heapshot_requested)
1191 mono_gc_collect (mono_gc_max_generation ());
1194 static void counters_init (MonoProfiler *profiler);
1195 static void counters_sample (MonoProfiler *profiler, uint64_t timestamp);
1198 safe_send (MonoProfiler *profiler)
1200 /* We need the runtime initialized so that we have threads and hazard
1201 * pointers available. Otherwise, the lock free queue will not work and
1202 * there won't be a thread to process the data.
1204 * While the runtime isn't initialized, we just accumulate data in the
1205 * thread local buffer list.
1207 if (!InterlockedRead (&runtime_inited))
1210 MonoProfilerThread *thread = PROF_TLS_GET ();
1214 send_buffer (profiler, thread);
1215 init_buffer_state (thread);
1221 send_if_needed (MonoProfiler *prof)
1223 if (PROF_TLS_GET ()->buffer->next)
1228 safe_send_threadless (MonoProfiler *prof)
1230 LogBuffer *buf = PROF_TLS_GET ()->buffer;
1232 for (LogBuffer *iter = buf; iter; iter = iter->next)
1233 iter->thread_id = 0;
1239 send_if_needed_threadless (MonoProfiler *prof)
1241 if (PROF_TLS_GET ()->buffer->next)
1242 safe_send_threadless (prof);
1245 // Assumes that the exclusive lock is held.
1247 sync_point_flush (MonoProfiler *prof)
1249 g_assert (InterlockedReadPointer (&buffer_rwlock_exclusive) == (gpointer) thread_id () && "Why don't we hold the exclusive lock?");
1251 MONO_LLS_FOREACH_SAFE (&profiler_thread_list, MonoProfilerThread, thread) {
1252 send_buffer (prof, thread);
1253 init_buffer_state (thread);
1254 } MONO_LLS_FOREACH_SAFE_END
1257 // Assumes that the exclusive lock is held.
1259 sync_point_mark (MonoProfiler *prof, MonoProfilerSyncPointType type)
1261 g_assert (InterlockedReadPointer (&buffer_rwlock_exclusive) == (gpointer) thread_id () && "Why don't we hold the exclusive lock?");
1265 LogBuffer *logbuffer = ensure_logbuf (
1266 EVENT_SIZE /* event */ +
1267 LEB128_SIZE /* type */
1270 emit_event (logbuffer, TYPE_META | TYPE_SYNC_POINT);
1271 emit_byte (logbuffer, type);
1276 case SYNC_POINT_PERIODIC:
1277 safe_send_threadless (prof);
1279 case SYNC_POINT_WORLD_STOP:
1280 case SYNC_POINT_WORLD_START:
1284 g_assert_not_reached ();
1289 // Assumes that the exclusive lock is held.
1291 sync_point (MonoProfiler *prof, MonoProfilerSyncPointType type)
1293 sync_point_flush (prof);
1294 sync_point_mark (prof, type);
1298 gc_reference (MonoObject *obj, MonoClass *klass, uintptr_t size, uintptr_t num, MonoObject **refs, uintptr_t *offsets, void *data)
1300 /* account for object alignment in the heap */
1306 LogBuffer *logbuffer = ensure_logbuf (
1307 EVENT_SIZE /* event */ +
1308 LEB128_SIZE /* obj */ +
1309 LEB128_SIZE /* klass */ +
1310 LEB128_SIZE /* size */ +
1311 LEB128_SIZE /* num */ +
1313 LEB128_SIZE /* offset */ +
1314 LEB128_SIZE /* ref */
1318 emit_event (logbuffer, TYPE_HEAP_OBJECT | TYPE_HEAP);
1319 emit_obj (logbuffer, obj);
1320 emit_ptr (logbuffer, klass);
1321 emit_value (logbuffer, size);
1322 emit_value (logbuffer, num);
1324 uintptr_t last_offset = 0;
1326 for (int i = 0; i < num; ++i) {
1327 emit_value (logbuffer, offsets [i] - last_offset);
1328 last_offset = offsets [i];
1329 emit_obj (logbuffer, refs [i]);
1337 static unsigned int hs_mode_ms = 0;
1338 static unsigned int hs_mode_gc = 0;
1339 static unsigned int hs_mode_ondemand = 0;
1340 static unsigned int gc_count = 0;
1341 static uint64_t last_hs_time = 0;
1344 heap_walk (MonoProfiler *profiler)
1349 gboolean do_walk = 0;
1350 uint64_t now = current_time ();
1352 if (hs_mode_ms && (now - last_hs_time) / 1000000 >= hs_mode_ms)
1354 else if (hs_mode_gc && (gc_count % hs_mode_gc) == 0)
1356 else if (hs_mode_ondemand)
1357 do_walk = heapshot_requested;
1358 else if (!hs_mode_ms && !hs_mode_gc && profiler->last_gc_gen_started == mono_gc_max_generation ())
1364 heapshot_requested = 0;
1368 LogBuffer *logbuffer = ensure_logbuf (
1369 EVENT_SIZE /* event */
1372 emit_event (logbuffer, TYPE_HEAP_START | TYPE_HEAP);
1376 mono_gc_walk_heap (0, gc_reference, NULL);
1380 LogBuffer *logbuffer = ensure_logbuf (
1381 EVENT_SIZE /* event */
1384 now = current_time ();
1386 emit_event (logbuffer, TYPE_HEAP_END | TYPE_HEAP);
1394 gc_event (MonoProfiler *profiler, MonoGCEvent ev, int generation)
1398 LogBuffer *logbuffer = ensure_logbuf (
1399 EVENT_SIZE /* event */ +
1400 BYTE_SIZE /* gc event */ +
1401 BYTE_SIZE /* generation */
1404 emit_event (logbuffer, TYPE_GC_EVENT | TYPE_GC);
1405 emit_byte (logbuffer, ev);
1406 emit_byte (logbuffer, generation);
1411 case MONO_GC_EVENT_START:
1412 /* to deal with nested gen1 after gen0 started */
1413 profiler->last_gc_gen_started = generation;
1415 if (generation == mono_gc_max_generation ())
1418 case MONO_GC_EVENT_PRE_STOP_WORLD_LOCKED:
1420 * Ensure that no thread can be in the middle of writing to
1421 * a buffer when the world stops...
1423 buffer_lock_excl ();
1425 case MONO_GC_EVENT_POST_STOP_WORLD:
1427 * ... So that we now have a consistent view of all buffers.
1428 * This allows us to flush them. We need to do this because
1429 * they may contain object allocation events that need to be
1430 * committed to the log file before any object move events
1431 * that will be produced during this GC.
1433 sync_point (profiler, SYNC_POINT_WORLD_STOP);
1435 case MONO_GC_EVENT_PRE_START_WORLD:
1436 heap_walk (profiler);
1438 case MONO_GC_EVENT_POST_START_WORLD_UNLOCKED:
1440 * Similarly, we must now make sure that any object moves
1441 * written to the GC thread's buffer are flushed. Otherwise,
1442 * object allocation events for certain addresses could come
1443 * after the move events that made those addresses available.
1445 sync_point_mark (profiler, SYNC_POINT_WORLD_START);
1448 * Finally, it is safe to allow other threads to write to
1449 * their buffers again.
1451 buffer_unlock_excl ();
1459 gc_resize (MonoProfiler *profiler, int64_t new_size)
1463 LogBuffer *logbuffer = ensure_logbuf (
1464 EVENT_SIZE /* event */ +
1465 LEB128_SIZE /* new size */
1468 emit_event (logbuffer, TYPE_GC_RESIZE | TYPE_GC);
1469 emit_value (logbuffer, new_size);
1474 // If you alter MAX_FRAMES, you may need to alter SAMPLE_BLOCK_SIZE too.
1475 #define MAX_FRAMES 32
1479 MonoMethod* methods [MAX_FRAMES];
1480 int32_t il_offsets [MAX_FRAMES];
1481 int32_t native_offsets [MAX_FRAMES];
1484 static int num_frames = MAX_FRAMES;
1487 walk_stack (MonoMethod *method, int32_t native_offset, int32_t il_offset, mono_bool managed, void* data)
1489 FrameData *frame = (FrameData *)data;
1490 if (method && frame->count < num_frames) {
1491 frame->il_offsets [frame->count] = il_offset;
1492 frame->native_offsets [frame->count] = native_offset;
1493 frame->methods [frame->count++] = method;
1494 //printf ("In %d %s at %d (native: %d)\n", frame->count, mono_method_get_name (method), il_offset, native_offset);
1496 return frame->count == num_frames;
1500 * a note about stack walks: they can cause more profiler events to fire,
1501 * so we need to make sure they don't happen after we started emitting an
1502 * event, hence the collect_bt/emit_bt split.
1505 collect_bt (FrameData *data)
1508 mono_stack_walk_no_il (walk_stack, data);
1512 emit_bt (MonoProfiler *prof, LogBuffer *logbuffer, FrameData *data)
1514 /* FIXME: this is actually tons of data and we should
1515 * just output it the first time and use an id the next
1517 if (data->count > num_frames)
1518 printf ("bad num frames: %d\n", data->count);
1519 emit_value (logbuffer, data->count);
1520 //if (*p != data.count) {
1521 // 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);}
1522 while (data->count) {
1523 emit_method (prof, logbuffer, data->methods [--data->count]);
1528 gc_alloc (MonoProfiler *prof, MonoObject *obj, MonoClass *klass)
1532 int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces) ? TYPE_ALLOC_BT : 0;
1534 uintptr_t len = mono_object_get_size (obj);
1535 /* account for object alignment in the heap */
1544 LogBuffer *logbuffer = ensure_logbuf (
1545 EVENT_SIZE /* event */ +
1546 LEB128_SIZE /* klass */ +
1547 LEB128_SIZE /* obj */ +
1548 LEB128_SIZE /* size */ +
1550 LEB128_SIZE /* count */ +
1552 LEB128_SIZE /* method */
1557 emit_event (logbuffer, do_bt | TYPE_ALLOC);
1558 emit_ptr (logbuffer, klass);
1559 emit_obj (logbuffer, obj);
1560 emit_value (logbuffer, len);
1563 emit_bt (prof, logbuffer, &data);
1567 send_if_needed (prof);
1569 process_requests (prof);
1573 gc_moves (MonoProfiler *prof, void **objects, int num)
1577 LogBuffer *logbuffer = ensure_logbuf (
1578 EVENT_SIZE /* event */ +
1579 LEB128_SIZE /* num */ +
1581 LEB128_SIZE /* object */
1585 emit_event (logbuffer, TYPE_GC_MOVE | TYPE_GC);
1586 emit_value (logbuffer, num);
1588 for (int i = 0; i < num; ++i)
1589 emit_obj (logbuffer, objects [i]);
1595 gc_roots (MonoProfiler *prof, int num, void **objects, int *root_types, uintptr_t *extra_info)
1599 LogBuffer *logbuffer = ensure_logbuf (
1600 EVENT_SIZE /* event */ +
1601 LEB128_SIZE /* num */ +
1602 LEB128_SIZE /* collections */ +
1604 LEB128_SIZE /* object */ +
1605 LEB128_SIZE /* root type */ +
1606 LEB128_SIZE /* extra info */
1610 emit_event (logbuffer, TYPE_HEAP_ROOT | TYPE_HEAP);
1611 emit_value (logbuffer, num);
1612 emit_value (logbuffer, mono_gc_collection_count (mono_gc_max_generation ()));
1614 for (int i = 0; i < num; ++i) {
1615 emit_obj (logbuffer, objects [i]);
1616 emit_byte (logbuffer, root_types [i]);
1617 emit_value (logbuffer, extra_info [i]);
1624 gc_handle (MonoProfiler *prof, int op, int type, uintptr_t handle, MonoObject *obj)
1626 int do_bt = nocalls && InterlockedRead (&runtime_inited) && !notraces;
1634 LogBuffer *logbuffer = ensure_logbuf (
1635 EVENT_SIZE /* event */ +
1636 LEB128_SIZE /* type */ +
1637 LEB128_SIZE /* handle */ +
1638 (op == MONO_PROFILER_GC_HANDLE_CREATED ? (
1639 LEB128_SIZE /* obj */
1642 LEB128_SIZE /* count */ +
1644 LEB128_SIZE /* method */
1649 if (op == MONO_PROFILER_GC_HANDLE_CREATED)
1650 emit_event (logbuffer, (do_bt ? TYPE_GC_HANDLE_CREATED_BT : TYPE_GC_HANDLE_CREATED) | TYPE_GC);
1651 else if (op == MONO_PROFILER_GC_HANDLE_DESTROYED)
1652 emit_event (logbuffer, (do_bt ? TYPE_GC_HANDLE_DESTROYED_BT : TYPE_GC_HANDLE_DESTROYED) | TYPE_GC);
1654 g_assert_not_reached ();
1656 emit_value (logbuffer, type);
1657 emit_value (logbuffer, handle);
1659 if (op == MONO_PROFILER_GC_HANDLE_CREATED)
1660 emit_obj (logbuffer, obj);
1663 emit_bt (prof, logbuffer, &data);
1667 process_requests (prof);
1671 finalize_begin (MonoProfiler *prof)
1675 LogBuffer *buf = ensure_logbuf (
1676 EVENT_SIZE /* event */
1679 emit_event (buf, TYPE_GC_FINALIZE_START | TYPE_GC);
1683 process_requests (prof);
1687 finalize_end (MonoProfiler *prof)
1691 LogBuffer *buf = ensure_logbuf (
1692 EVENT_SIZE /* event */
1695 emit_event (buf, TYPE_GC_FINALIZE_END | TYPE_GC);
1699 process_requests (prof);
1703 finalize_object_begin (MonoProfiler *prof, MonoObject *obj)
1707 LogBuffer *buf = ensure_logbuf (
1708 EVENT_SIZE /* event */ +
1709 LEB128_SIZE /* obj */
1712 emit_event (buf, TYPE_GC_FINALIZE_OBJECT_START | TYPE_GC);
1713 emit_obj (buf, obj);
1717 process_requests (prof);
1721 finalize_object_end (MonoProfiler *prof, MonoObject *obj)
1725 LogBuffer *buf = ensure_logbuf (
1726 EVENT_SIZE /* event */ +
1727 LEB128_SIZE /* obj */
1730 emit_event (buf, TYPE_GC_FINALIZE_OBJECT_END | TYPE_GC);
1731 emit_obj (buf, obj);
1735 process_requests (prof);
1739 push_nesting (char *p, MonoClass *klass)
1744 nesting = mono_class_get_nesting_type (klass);
1746 p = push_nesting (p, nesting);
1750 name = mono_class_get_name (klass);
1751 nspace = mono_class_get_namespace (klass);
1754 p += strlen (nspace);
1764 type_name (MonoClass *klass)
1768 push_nesting (buf, klass);
1769 p = (char *)malloc (strlen (buf) + 1);
1775 image_loaded (MonoProfiler *prof, MonoImage *image, int result)
1777 if (result != MONO_PROFILE_OK)
1780 const char *name = mono_image_get_filename (image);
1781 int nlen = strlen (name) + 1;
1785 LogBuffer *logbuffer = ensure_logbuf (
1786 EVENT_SIZE /* event */ +
1787 BYTE_SIZE /* type */ +
1788 LEB128_SIZE /* image */ +
1792 emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1793 emit_byte (logbuffer, TYPE_IMAGE);
1794 emit_ptr (logbuffer, image);
1795 memcpy (logbuffer->cursor, name, nlen);
1796 logbuffer->cursor += nlen;
1800 send_if_needed (prof);
1802 process_requests (prof);
1804 InterlockedIncrement (&image_loads);
1808 image_unloaded (MonoProfiler *prof, MonoImage *image)
1810 const char *name = mono_image_get_filename (image);
1811 int nlen = strlen (name) + 1;
1815 LogBuffer *logbuffer = ensure_logbuf (
1816 EVENT_SIZE /* event */ +
1817 BYTE_SIZE /* type */ +
1818 LEB128_SIZE /* image */ +
1822 emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1823 emit_byte (logbuffer, TYPE_IMAGE);
1824 emit_ptr (logbuffer, image);
1825 memcpy (logbuffer->cursor, name, nlen);
1826 logbuffer->cursor += nlen;
1830 send_if_needed (prof);
1832 process_requests (prof);
1834 InterlockedIncrement (&image_unloads);
1838 assembly_loaded (MonoProfiler *prof, MonoAssembly *assembly, int result)
1840 if (result != MONO_PROFILE_OK)
1843 char *name = mono_stringify_assembly_name (mono_assembly_get_name (assembly));
1844 int nlen = strlen (name) + 1;
1848 LogBuffer *logbuffer = ensure_logbuf (
1849 EVENT_SIZE /* event */ +
1850 BYTE_SIZE /* type */ +
1851 LEB128_SIZE /* assembly */ +
1855 emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1856 emit_byte (logbuffer, TYPE_ASSEMBLY);
1857 emit_ptr (logbuffer, assembly);
1858 memcpy (logbuffer->cursor, name, nlen);
1859 logbuffer->cursor += nlen;
1865 send_if_needed (prof);
1867 process_requests (prof);
1869 InterlockedIncrement (&assembly_loads);
1873 assembly_unloaded (MonoProfiler *prof, MonoAssembly *assembly)
1875 char *name = mono_stringify_assembly_name (mono_assembly_get_name (assembly));
1876 int nlen = strlen (name) + 1;
1880 LogBuffer *logbuffer = ensure_logbuf (
1881 EVENT_SIZE /* event */ +
1882 BYTE_SIZE /* type */ +
1883 LEB128_SIZE /* assembly */ +
1887 emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1888 emit_byte (logbuffer, TYPE_ASSEMBLY);
1889 emit_ptr (logbuffer, assembly);
1890 memcpy (logbuffer->cursor, name, nlen);
1891 logbuffer->cursor += nlen;
1897 send_if_needed (prof);
1899 process_requests (prof);
1901 InterlockedIncrement (&assembly_unloads);
1905 class_loaded (MonoProfiler *prof, MonoClass *klass, int result)
1907 if (result != MONO_PROFILE_OK)
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_LOAD | 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_loads);
1952 class_unloaded (MonoProfiler *prof, MonoClass *klass)
1956 if (InterlockedRead (&runtime_inited))
1957 name = mono_type_get_name (mono_class_get_type (klass));
1959 name = type_name (klass);
1961 int nlen = strlen (name) + 1;
1962 MonoImage *image = mono_class_get_image (klass);
1966 LogBuffer *logbuffer = ensure_logbuf (
1967 EVENT_SIZE /* event */ +
1968 BYTE_SIZE /* type */ +
1969 LEB128_SIZE /* klass */ +
1970 LEB128_SIZE /* image */ +
1974 emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1975 emit_byte (logbuffer, TYPE_CLASS);
1976 emit_ptr (logbuffer, klass);
1977 emit_ptr (logbuffer, image);
1978 memcpy (logbuffer->cursor, name, nlen);
1979 logbuffer->cursor += nlen;
1988 send_if_needed (prof);
1990 process_requests (prof);
1992 InterlockedIncrement (&class_unloads);
1995 #ifndef DISABLE_HELPER_THREAD
1996 static void process_method_enter_coverage (MonoProfiler *prof, MonoMethod *method);
1997 #endif /* DISABLE_HELPER_THREAD */
2000 method_enter (MonoProfiler *prof, MonoMethod *method)
2002 #ifndef DISABLE_HELPER_THREAD
2003 process_method_enter_coverage (prof, method);
2004 #endif /* DISABLE_HELPER_THREAD */
2006 if (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_ENTER | TYPE_METHOD);
2015 emit_method (prof, logbuffer, method);
2020 send_if_needed (prof);
2022 process_requests (prof);
2026 method_leave (MonoProfiler *prof, MonoMethod *method)
2028 if (--PROF_TLS_GET ()->call_depth <= max_call_depth) {
2031 LogBuffer *logbuffer = ensure_logbuf (
2032 EVENT_SIZE /* event */ +
2033 LEB128_SIZE /* method */
2036 emit_event (logbuffer, TYPE_LEAVE | TYPE_METHOD);
2037 emit_method (prof, logbuffer, method);
2042 send_if_needed (prof);
2044 process_requests (prof);
2048 method_exc_leave (MonoProfiler *prof, MonoMethod *method)
2050 if (!nocalls && --PROF_TLS_GET ()->call_depth <= max_call_depth) {
2053 LogBuffer *logbuffer = ensure_logbuf (
2054 EVENT_SIZE /* event */ +
2055 LEB128_SIZE /* method */
2058 emit_event (logbuffer, TYPE_EXC_LEAVE | TYPE_METHOD);
2059 emit_method (prof, logbuffer, method);
2064 send_if_needed (prof);
2066 process_requests (prof);
2070 method_jitted (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *ji, int result)
2072 if (result != MONO_PROFILE_OK)
2075 register_method_local (prof, method, ji);
2077 process_requests (prof);
2081 code_buffer_new (MonoProfiler *prof, void *buffer, int size, MonoProfilerCodeBufferType type, void *data)
2086 if (type == MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE) {
2087 name = (char *) data;
2088 nlen = strlen (name) + 1;
2096 LogBuffer *logbuffer = ensure_logbuf (
2097 EVENT_SIZE /* event */ +
2098 BYTE_SIZE /* type */ +
2099 LEB128_SIZE /* buffer */ +
2100 LEB128_SIZE /* size */ +
2106 emit_event (logbuffer, TYPE_JITHELPER | TYPE_RUNTIME);
2107 emit_byte (logbuffer, type);
2108 emit_ptr (logbuffer, buffer);
2109 emit_value (logbuffer, size);
2112 memcpy (logbuffer->cursor, name, nlen);
2113 logbuffer->cursor += nlen;
2118 process_requests (prof);
2122 throw_exc (MonoProfiler *prof, MonoObject *object)
2124 int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces) ? TYPE_THROW_BT : 0;
2132 LogBuffer *logbuffer = ensure_logbuf (
2133 EVENT_SIZE /* event */ +
2134 LEB128_SIZE /* object */ +
2136 LEB128_SIZE /* count */ +
2138 LEB128_SIZE /* method */
2143 emit_event (logbuffer, do_bt | TYPE_EXCEPTION);
2144 emit_obj (logbuffer, object);
2147 emit_bt (prof, logbuffer, &data);
2151 process_requests (prof);
2155 clause_exc (MonoProfiler *prof, MonoMethod *method, int clause_type, int clause_num)
2159 LogBuffer *logbuffer = ensure_logbuf (
2160 EVENT_SIZE /* event */ +
2161 BYTE_SIZE /* clause type */ +
2162 LEB128_SIZE /* clause num */ +
2163 LEB128_SIZE /* method */
2166 emit_event (logbuffer, TYPE_EXCEPTION | TYPE_CLAUSE);
2167 emit_byte (logbuffer, clause_type);
2168 emit_value (logbuffer, clause_num);
2169 emit_method (prof, logbuffer, method);
2173 process_requests (prof);
2177 monitor_event (MonoProfiler *profiler, MonoObject *object, MonoProfilerMonitorEvent event)
2179 int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces && event == MONO_PROFILER_MONITOR_CONTENTION) ? TYPE_MONITOR_BT : 0;
2187 LogBuffer *logbuffer = ensure_logbuf (
2188 EVENT_SIZE /* event */ +
2189 LEB128_SIZE /* object */ +
2191 LEB128_SIZE /* count */ +
2193 LEB128_SIZE /* method */
2198 emit_event (logbuffer, (event << 4) | do_bt | TYPE_MONITOR);
2199 emit_obj (logbuffer, object);
2202 emit_bt (profiler, logbuffer, &data);
2206 process_requests (profiler);
2210 thread_start (MonoProfiler *prof, uintptr_t tid)
2216 LogBuffer *logbuffer = ensure_logbuf (
2217 EVENT_SIZE /* event */ +
2218 BYTE_SIZE /* type */ +
2219 LEB128_SIZE /* tid */
2222 emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
2223 emit_byte (logbuffer, TYPE_THREAD);
2224 emit_ptr (logbuffer, (void*) tid);
2228 send_if_needed (prof);
2230 process_requests (prof);
2232 InterlockedIncrement (&thread_starts);
2236 thread_end (MonoProfiler *prof, uintptr_t tid)
2240 LogBuffer *logbuffer = ensure_logbuf (
2241 EVENT_SIZE /* event */ +
2242 BYTE_SIZE /* type */ +
2243 LEB128_SIZE /* tid */
2246 emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
2247 emit_byte (logbuffer, TYPE_THREAD);
2248 emit_ptr (logbuffer, (void*) tid);
2252 // Don't process requests as the thread is detached from the runtime.
2254 remove_thread (prof, PROF_TLS_GET (), TRUE);
2256 InterlockedIncrement (&thread_ends);
2260 domain_loaded (MonoProfiler *prof, MonoDomain *domain, int result)
2262 if (result != MONO_PROFILE_OK)
2267 LogBuffer *logbuffer = ensure_logbuf (
2268 EVENT_SIZE /* event */ +
2269 BYTE_SIZE /* type */ +
2270 LEB128_SIZE /* domain id */
2273 emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
2274 emit_byte (logbuffer, TYPE_DOMAIN);
2275 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
2279 send_if_needed (prof);
2281 process_requests (prof);
2283 InterlockedIncrement (&domain_loads);
2287 domain_unloaded (MonoProfiler *prof, MonoDomain *domain)
2291 LogBuffer *logbuffer = ensure_logbuf (
2292 EVENT_SIZE /* event */ +
2293 BYTE_SIZE /* type */ +
2294 LEB128_SIZE /* domain id */
2297 emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
2298 emit_byte (logbuffer, TYPE_DOMAIN);
2299 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
2303 send_if_needed (prof);
2305 process_requests (prof);
2307 InterlockedIncrement (&domain_unloads);
2311 domain_name (MonoProfiler *prof, MonoDomain *domain, const char *name)
2313 int nlen = strlen (name) + 1;
2317 LogBuffer *logbuffer = ensure_logbuf (
2318 EVENT_SIZE /* event */ +
2319 BYTE_SIZE /* type */ +
2320 LEB128_SIZE /* domain id */ +
2324 emit_event (logbuffer, TYPE_METADATA);
2325 emit_byte (logbuffer, TYPE_DOMAIN);
2326 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
2327 memcpy (logbuffer->cursor, name, nlen);
2328 logbuffer->cursor += nlen;
2332 send_if_needed (prof);
2334 process_requests (prof);
2338 context_loaded (MonoProfiler *prof, MonoAppContext *context)
2342 LogBuffer *logbuffer = ensure_logbuf (
2343 EVENT_SIZE /* event */ +
2344 BYTE_SIZE /* type */ +
2345 LEB128_SIZE /* context id */ +
2346 LEB128_SIZE /* domain id */
2349 emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
2350 emit_byte (logbuffer, TYPE_CONTEXT);
2351 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_id (context));
2352 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_domain_id (context));
2356 send_if_needed (prof);
2358 process_requests (prof);
2360 InterlockedIncrement (&context_loads);
2364 context_unloaded (MonoProfiler *prof, MonoAppContext *context)
2368 LogBuffer *logbuffer = ensure_logbuf (
2369 EVENT_SIZE /* event */ +
2370 BYTE_SIZE /* type */ +
2371 LEB128_SIZE /* context id */ +
2372 LEB128_SIZE /* domain id */
2375 emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
2376 emit_byte (logbuffer, TYPE_CONTEXT);
2377 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_id (context));
2378 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_domain_id (context));
2382 send_if_needed (prof);
2384 process_requests (prof);
2386 InterlockedIncrement (&context_unloads);
2390 thread_name (MonoProfiler *prof, uintptr_t tid, const char *name)
2392 int len = strlen (name) + 1;
2396 LogBuffer *logbuffer = ensure_logbuf (
2397 EVENT_SIZE /* event */ +
2398 BYTE_SIZE /* type */ +
2399 LEB128_SIZE /* tid */ +
2403 emit_event (logbuffer, TYPE_METADATA);
2404 emit_byte (logbuffer, TYPE_THREAD);
2405 emit_ptr (logbuffer, (void*)tid);
2406 memcpy (logbuffer->cursor, name, len);
2407 logbuffer->cursor += len;
2411 send_if_needed (prof);
2413 process_requests (prof);
2424 MonoLockFreeQueueNode node;
2430 AsyncFrameInfo frames [MONO_ZERO_LEN_ARRAY];
2434 async_walk_stack (MonoMethod *method, MonoDomain *domain, void *base_address, int offset, void *data)
2436 SampleHit *sample = (SampleHit *) data;
2438 if (sample->count < num_frames) {
2439 int i = sample->count;
2441 sample->frames [i].method = method;
2442 sample->frames [i].domain = domain;
2443 sample->frames [i].base_address = base_address;
2444 sample->frames [i].offset = offset;
2449 return sample->count == num_frames;
2452 #define SAMPLE_SLOT_SIZE(FRAMES) (sizeof (SampleHit) + sizeof (AsyncFrameInfo) * (FRAMES - MONO_ZERO_LEN_ARRAY))
2453 #define SAMPLE_BLOCK_SIZE (mono_pagesize ())
2456 enqueue_sample_hit (gpointer p)
2458 SampleHit *sample = p;
2460 mono_lock_free_queue_node_unpoison (&sample->node);
2461 mono_lock_free_queue_enqueue (&sample->prof->dumper_queue, &sample->node);
2462 mono_os_sem_post (&sample->prof->dumper_queue_sem);
2464 InterlockedIncrement (&sample_flushes);
2468 mono_sample_hit (MonoProfiler *profiler, unsigned char *ip, void *context)
2471 * Please note: We rely on the runtime loading the profiler with
2472 * MONO_DL_EAGER (RTLD_NOW) so that references to runtime functions within
2473 * this function (and its siblings) are resolved when the profiler is
2474 * loaded. Otherwise, we would potentially invoke the dynamic linker when
2475 * invoking runtime functions, which is not async-signal-safe.
2481 InterlockedIncrement (&sample_hits);
2483 SampleHit *sample = (SampleHit *) mono_lock_free_queue_dequeue (&profiler->sample_reuse_queue);
2487 * If we're out of reusable sample events and we're not allowed to
2488 * allocate more, we have no choice but to drop the event.
2490 if (InterlockedRead (&sample_allocations) >= max_allocated_sample_hits)
2493 sample = mono_lock_free_alloc (&profiler->sample_allocator);
2494 sample->prof = profiler;
2495 mono_lock_free_queue_node_init (&sample->node, TRUE);
2497 InterlockedIncrement (&sample_allocations);
2501 mono_stack_walk_async_safe (&async_walk_stack, context, sample);
2503 sample->time = current_time ();
2504 sample->tid = thread_id ();
2510 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));
2512 ign_res (write (2, buf, len));
2515 mono_thread_hazardous_try_free (sample, enqueue_sample_hit);
2518 static uintptr_t *code_pages = 0;
2519 static int num_code_pages = 0;
2520 static int size_code_pages = 0;
2521 #define CPAGE_SHIFT (9)
2522 #define CPAGE_SIZE (1 << CPAGE_SHIFT)
2523 #define CPAGE_MASK (~(CPAGE_SIZE - 1))
2524 #define CPAGE_ADDR(p) ((p) & CPAGE_MASK)
2527 add_code_page (uintptr_t *hash, uintptr_t hsize, uintptr_t page)
2530 uintptr_t start_pos;
2531 start_pos = (page >> CPAGE_SHIFT) % hsize;
2534 if (hash [i] && CPAGE_ADDR (hash [i]) == CPAGE_ADDR (page)) {
2536 } else if (!hash [i]) {
2543 } while (i != start_pos);
2544 /* should not happen */
2545 printf ("failed code page store\n");
2550 add_code_pointer (uintptr_t ip)
2553 if (num_code_pages * 2 >= size_code_pages) {
2555 uintptr_t old_size = size_code_pages;
2556 size_code_pages *= 2;
2557 if (size_code_pages == 0)
2558 size_code_pages = 16;
2559 n = (uintptr_t *)calloc (sizeof (uintptr_t) * size_code_pages, 1);
2560 for (i = 0; i < old_size; ++i) {
2562 add_code_page (n, size_code_pages, code_pages [i]);
2568 num_code_pages += add_code_page (code_pages, size_code_pages, ip & CPAGE_MASK);
2571 /* ELF code crashes on some systems. */
2572 //#if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
2575 dump_ubin (const char *filename, uintptr_t load_addr, uint64_t offset, uintptr_t size)
2577 int len = strlen (filename) + 1;
2581 LogBuffer *logbuffer = ensure_logbuf (
2582 EVENT_SIZE /* event */ +
2583 LEB128_SIZE /* load address */ +
2584 LEB128_SIZE /* offset */ +
2585 LEB128_SIZE /* size */ +
2586 nlen /* file name */
2589 emit_event (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_UBIN);
2590 emit_svalue (logbuffer, load_addr);
2591 emit_uvalue (logbuffer, offset);
2592 emit_uvalue (logbuffer, size);
2593 memcpy (logbuffer->cursor, filename, len);
2594 logbuffer->cursor += len;
2601 dump_usym (const char *name, uintptr_t value, uintptr_t size)
2603 int len = strlen (name) + 1;
2607 LogBuffer *logbuffer = ensure_logbuf (
2608 EVENT_SIZE /* event */ +
2609 LEB128_SIZE /* value */ +
2610 LEB128_SIZE /* size */ +
2614 emit_event (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_USYM);
2615 emit_ptr (logbuffer, (void*)value);
2616 emit_value (logbuffer, size);
2617 memcpy (logbuffer->cursor, name, len);
2618 logbuffer->cursor += len;
2623 /* ELF code crashes on some systems. */
2624 //#if defined(ELFMAG0)
2627 #if SIZEOF_VOID_P == 4
2628 #define ELF_WSIZE 32
2630 #define ELF_WSIZE 64
2633 #define ElfW(type) _ElfW (Elf, ELF_WSIZE, type)
2634 #define _ElfW(e,w,t) _ElfW_1 (e, w, _##t)
2635 #define _ElfW_1(e,w,t) e##w##t
2639 dump_elf_symbols (ElfW(Sym) *symbols, int num_symbols, const char *strtab, void *load_addr)
2642 for (i = 0; i < num_symbols; ++i) {
2644 sym = strtab + symbols [i].st_name;
2645 if (!symbols [i].st_name || !symbols [i].st_size || (symbols [i].st_info & 0xf) != STT_FUNC)
2647 //printf ("symbol %s at %d\n", sym, symbols [i].st_value);
2648 dump_usym (sym, (uintptr_t)load_addr + symbols [i].st_value, symbols [i].st_size);
2653 read_elf_symbols (MonoProfiler *prof, const char *filename, void *load_addr)
2660 ElfW(Shdr) *sheader;
2661 ElfW(Shdr) *shstrtabh;
2662 ElfW(Shdr) *symtabh = NULL;
2663 ElfW(Shdr) *strtabh = NULL;
2664 ElfW(Sym) *symbols = NULL;
2668 fd = open (filename, O_RDONLY);
2671 if (fstat (fd, &statb) != 0) {
2675 file_size = statb.st_size;
2676 data = mmap (NULL, file_size, PROT_READ, MAP_PRIVATE, fd, 0);
2678 if (data == MAP_FAILED)
2681 if (header->e_ident [EI_MAG0] != ELFMAG0 ||
2682 header->e_ident [EI_MAG1] != ELFMAG1 ||
2683 header->e_ident [EI_MAG2] != ELFMAG2 ||
2684 header->e_ident [EI_MAG3] != ELFMAG3 ) {
2685 munmap (data, file_size);
2688 sheader = (void*)((char*)data + header->e_shoff);
2689 shstrtabh = (void*)((char*)sheader + (header->e_shentsize * header->e_shstrndx));
2690 strtab = (const char*)data + shstrtabh->sh_offset;
2691 for (i = 0; i < header->e_shnum; ++i) {
2692 //printf ("section header: %d\n", sheader->sh_type);
2693 if (sheader->sh_type == SHT_SYMTAB) {
2695 strtabh = (void*)((char*)data + header->e_shoff + sheader->sh_link * header->e_shentsize);
2696 /*printf ("symtab section header: %d, .strstr: %d\n", i, sheader->sh_link);*/
2699 sheader = (void*)((char*)sheader + header->e_shentsize);
2701 if (!symtabh || !strtabh) {
2702 munmap (data, file_size);
2705 strtab = (const char*)data + strtabh->sh_offset;
2706 num_symbols = symtabh->sh_size / symtabh->sh_entsize;
2707 symbols = (void*)((char*)data + symtabh->sh_offset);
2708 dump_elf_symbols (symbols, num_symbols, strtab, load_addr);
2709 munmap (data, file_size);
2714 /* ELF code crashes on some systems. */
2715 //#if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
2718 elf_dl_callback (struct dl_phdr_info *info, size_t size, void *data)
2720 MonoProfiler *prof = data;
2722 const char *filename;
2724 char *a = (void*)info->dlpi_addr;
2726 ElfW(Dyn) *dyn = NULL;
2727 ElfW(Sym) *symtab = NULL;
2728 ElfW(Word) *hash_table = NULL;
2729 ElfW(Ehdr) *header = NULL;
2730 const char* strtab = NULL;
2731 for (obj = prof->binary_objects; obj; obj = obj->next) {
2735 filename = info->dlpi_name;
2738 if (!info->dlpi_addr && !filename [0]) {
2739 int l = readlink ("/proc/self/exe", buf, sizeof (buf) - 1);
2745 obj = calloc (sizeof (BinaryObject), 1);
2746 obj->addr = (void*)info->dlpi_addr;
2747 obj->name = pstrdup (filename);
2748 obj->next = prof->binary_objects;
2749 prof->binary_objects = obj;
2750 //printf ("loaded file: %s at %p, segments: %d\n", filename, (void*)info->dlpi_addr, info->dlpi_phnum);
2752 for (i = 0; i < info->dlpi_phnum; ++i) {
2753 //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);
2754 if (info->dlpi_phdr[i].p_type == PT_LOAD && !header) {
2755 header = (ElfW(Ehdr)*)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
2756 if (header->e_ident [EI_MAG0] != ELFMAG0 ||
2757 header->e_ident [EI_MAG1] != ELFMAG1 ||
2758 header->e_ident [EI_MAG2] != ELFMAG2 ||
2759 header->e_ident [EI_MAG3] != ELFMAG3 ) {
2762 dump_ubin (filename, info->dlpi_addr + info->dlpi_phdr[i].p_vaddr, info->dlpi_phdr[i].p_offset, info->dlpi_phdr[i].p_memsz);
2763 } else if (info->dlpi_phdr[i].p_type == PT_DYNAMIC) {
2764 dyn = (ElfW(Dyn) *)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
2767 if (read_elf_symbols (prof, filename, (void*)info->dlpi_addr))
2769 if (!info->dlpi_name || !info->dlpi_name[0])
2773 for (i = 0; dyn [i].d_tag != DT_NULL; ++i) {
2774 if (dyn [i].d_tag == DT_SYMTAB) {
2775 if (symtab && do_debug)
2776 printf ("multiple symtabs: %d\n", i);
2777 symtab = (ElfW(Sym) *)(a + dyn [i].d_un.d_ptr);
2778 } else if (dyn [i].d_tag == DT_HASH) {
2779 hash_table = (ElfW(Word) *)(a + dyn [i].d_un.d_ptr);
2780 } else if (dyn [i].d_tag == DT_STRTAB) {
2781 strtab = (const char*)(a + dyn [i].d_un.d_ptr);
2786 num_sym = hash_table [1];
2787 dump_elf_symbols (symtab, num_sym, strtab, (void*)info->dlpi_addr);
2792 load_binaries (MonoProfiler *prof)
2794 dl_iterate_phdr (elf_dl_callback, prof);
2799 load_binaries (MonoProfiler *prof)
2806 symbol_for (uintptr_t code)
2809 void *ip = (void*)code;
2811 if (dladdr (ip, &di)) {
2813 return di.dli_sname;
2816 names = backtrace_symbols (&ip, 1);
2818 const char* p = names [0];
2829 dump_unmanaged_coderefs (MonoProfiler *prof)
2832 const char* last_symbol;
2833 uintptr_t addr, page_end;
2835 if (load_binaries (prof))
2837 for (i = 0; i < size_code_pages; ++i) {
2839 if (!code_pages [i] || code_pages [i] & 1)
2842 addr = CPAGE_ADDR (code_pages [i]);
2843 page_end = addr + CPAGE_SIZE;
2844 code_pages [i] |= 1;
2845 /* we dump the symbols for the whole page */
2846 for (; addr < page_end; addr += 16) {
2847 sym = symbol_for (addr);
2848 if (sym && sym == last_symbol)
2853 dump_usym (sym, addr, 0); /* let's not guess the size */
2854 //printf ("found symbol at %p: %s\n", (void*)addr, sym);
2860 mono_cpu_count (void)
2862 #ifdef PLATFORM_ANDROID
2863 /* Android tries really hard to save power by powering off CPUs on SMP phones which
2864 * means the normal way to query cpu count returns a wrong value with userspace API.
2865 * Instead we use /sys entries to query the actual hardware CPU count.
2868 char buffer[8] = {'\0'};
2869 int present = open ("/sys/devices/system/cpu/present", O_RDONLY);
2870 /* Format of the /sys entry is a cpulist of indexes which in the case
2871 * of present is always of the form "0-(n-1)" when there is more than
2872 * 1 core, n being the number of CPU cores in the system. Otherwise
2873 * the value is simply 0
2875 if (present != -1 && read (present, (char*)buffer, sizeof (buffer)) > 3)
2876 count = strtol (((char*)buffer) + 2, NULL, 10);
2883 #if defined(HOST_ARM) || defined (HOST_ARM64)
2885 /* ARM platforms tries really hard to save power by powering off CPUs on SMP phones which
2886 * means the normal way to query cpu count returns a wrong value with userspace API. */
2888 #ifdef _SC_NPROCESSORS_CONF
2890 int count = sysconf (_SC_NPROCESSORS_CONF);
2898 #ifdef HAVE_SCHED_GETAFFINITY
2901 if (sched_getaffinity (getpid (), sizeof (set), &set) == 0)
2902 return CPU_COUNT (&set);
2905 #ifdef _SC_NPROCESSORS_ONLN
2907 int count = sysconf (_SC_NPROCESSORS_ONLN);
2913 #endif /* defined(HOST_ARM) || defined (HOST_ARM64) */
2919 size_t len = sizeof (int);
2922 if (sysctl (mib, 2, &count, &len, NULL, 0) == 0)
2929 GetSystemInfo (&info);
2930 return info.dwNumberOfProcessors;
2941 unsigned int prev_pos;
2943 struct perf_event_mmap_page *page_desc;
2946 static PerfData *perf_data = NULL;
2947 static int num_perf;
2948 #define PERF_PAGES_SHIFT 4
2949 static int num_pages = 1 << PERF_PAGES_SHIFT;
2950 static unsigned int mmap_mask;
2953 struct perf_event_header h;
2963 perf_event_syscall (struct perf_event_attr *attr, pid_t pid, int cpu, int group_fd, unsigned long flags)
2965 attr->size = PERF_ATTR_SIZE_VER0;
2966 //printf ("perf attr size: %d\n", attr->size);
2967 #if defined(__x86_64__)
2968 return syscall(/*__NR_perf_event_open*/ 298, attr, pid, cpu, group_fd, flags);
2969 #elif defined(__i386__)
2970 return syscall(/*__NR_perf_event_open*/ 336, attr, pid, cpu, group_fd, flags);
2971 #elif defined(__arm__) || defined (__aarch64__)
2972 return syscall(/*__NR_perf_event_open*/ 364, attr, pid, cpu, group_fd, flags);
2979 setup_perf_map (PerfData *perf)
2981 perf->mmap_base = mmap (NULL, (num_pages + 1) * getpagesize (), PROT_READ|PROT_WRITE, MAP_SHARED, perf->perf_fd, 0);
2982 if (perf->mmap_base == MAP_FAILED) {
2984 printf ("failed mmap\n");
2987 perf->page_desc = perf->mmap_base;
2989 printf ("mmap version: %d\n", perf->page_desc->version);
2994 dump_perf_hits (MonoProfiler *prof, void *buf, int size)
2998 void *end = (char*)buf + size;
3000 int pid = getpid ();
3006 if (pid != s->pid) {
3008 printf ("event for different pid: %d\n", s->pid);
3009 buf = (char*)buf + s->h.size;
3012 /*ip = (void*)s->ip;
3013 printf ("sample: %d, size: %d, ip: %p (%s), timestamp: %llu, nframes: %llu\n",
3014 s->h.type, s->h.size, ip, symbol_for (ip), s->timestamp, s->nframes);*/
3018 LogBuffer *logbuffer = ensure_logbuf (
3019 EVENT_SIZE /* event */ +
3020 BYTE_SIZE /* type */ +
3021 LEB128_SIZE /* tid */ +
3022 LEB128_SIZE /* count */ +
3024 LEB128_SIZE /* ip */
3026 LEB128_SIZE /* managed count */ +
3028 LEB128_SIZE /* method */
3032 emit_event (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_HIT);
3033 emit_byte (logbuffer, sample_type);
3035 * No useful thread ID to write here, since throughout the
3036 * profiler we use pthread_self () but the ID we get from
3037 * perf is the kernel's thread ID.
3039 emit_ptr (logbuffer, 0);
3040 emit_value (logbuffer, count);
3041 emit_ptr (logbuffer, (void*)(uintptr_t)s->ip);
3042 /* no support here yet for the managed backtrace */
3043 emit_uvalue (logbuffer, mbt_count);
3047 add_code_pointer (s->ip);
3048 buf = (char*)buf + s->h.size;
3052 printf ("dumped %d samples\n", samples);
3053 dump_unmanaged_coderefs (prof);
3056 /* read events from the ring buffer */
3058 read_perf_mmap (MonoProfiler* prof, int cpu)
3060 PerfData *perf = perf_data + cpu;
3062 unsigned char *data = (unsigned char*)perf->mmap_base + getpagesize ();
3063 unsigned int head = perf->page_desc->data_head;
3067 mono_memory_read_barrier ();
3069 old = perf->prev_pos;
3073 printf ("lost mmap events: old: %d, head: %d\n", old, head);
3077 if ((old & mmap_mask) + size != (head & mmap_mask)) {
3078 buf = data + (old & mmap_mask);
3079 size = mmap_mask + 1 - (old & mmap_mask);
3081 /* size bytes at buf */
3083 printf ("found1 bytes of events: %d\n", size);
3084 dump_perf_hits (prof, buf, size);
3086 buf = data + (old & mmap_mask);
3088 /* size bytes at buf */
3090 printf ("found bytes of events: %d\n", size);
3091 dump_perf_hits (prof, buf, size);
3093 perf->prev_pos = old;
3094 perf->page_desc->data_tail = old;
3099 setup_perf_event_for_cpu (PerfData *perf, int cpu)
3101 struct perf_event_attr attr;
3102 memset (&attr, 0, sizeof (attr));
3103 attr.type = PERF_TYPE_HARDWARE;
3104 switch (sample_type) {
3105 case SAMPLE_CYCLES: attr.config = PERF_COUNT_HW_CPU_CYCLES; break;
3106 case SAMPLE_INSTRUCTIONS: attr.config = PERF_COUNT_HW_INSTRUCTIONS; break;
3107 case SAMPLE_CACHE_MISSES: attr.config = PERF_COUNT_HW_CACHE_MISSES; break;
3108 case SAMPLE_CACHE_REFS: attr.config = PERF_COUNT_HW_CACHE_REFERENCES; break;
3109 case SAMPLE_BRANCHES: attr.config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS; break;
3110 case SAMPLE_BRANCH_MISSES: attr.config = PERF_COUNT_HW_BRANCH_MISSES; break;
3111 default: attr.config = PERF_COUNT_HW_CPU_CYCLES; break;
3113 attr.sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID | PERF_SAMPLE_PERIOD | PERF_SAMPLE_TIME;
3114 // attr.sample_type |= PERF_SAMPLE_CALLCHAIN;
3115 attr.read_format = PERF_FORMAT_TOTAL_TIME_ENABLED | PERF_FORMAT_TOTAL_TIME_RUNNING | PERF_FORMAT_ID;
3118 attr.sample_freq = sample_freq;
3120 perf->perf_fd = perf_event_syscall (&attr, getpid (), cpu, -1, 0);
3122 printf ("perf fd: %d, freq: %d, event: %llu\n", perf->perf_fd, sample_freq, attr.config);
3123 if (perf->perf_fd < 0) {
3124 if (perf->perf_fd == -EPERM) {
3125 fprintf (stderr, "Perf syscall denied, do \"echo 1 > /proc/sys/kernel/perf_event_paranoid\" as root to enable.\n");
3128 perror ("open perf event");
3132 if (!setup_perf_map (perf)) {
3133 close (perf->perf_fd);
3141 setup_perf_event (void)
3144 mmap_mask = num_pages * getpagesize () - 1;
3145 num_perf = mono_cpu_count ();
3146 perf_data = calloc (num_perf, sizeof (PerfData));
3147 for (i = 0; i < num_perf; ++i) {
3148 count += setup_perf_event_for_cpu (perf_data + i, i);
3157 #endif /* USE_PERF_EVENTS */
3159 #ifndef DISABLE_HELPER_THREAD
3161 typedef struct MonoCounterAgent {
3162 MonoCounter *counter;
3163 // MonoCounterAgent specific data :
3168 struct MonoCounterAgent *next;
3171 static MonoCounterAgent* counters;
3172 static gboolean counters_initialized = FALSE;
3173 static int counters_index = 1;
3174 static mono_mutex_t counters_mutex;
3177 counters_add_agent (MonoCounter *counter)
3179 MonoCounterAgent *agent, *item;
3181 if (!counters_initialized)
3184 mono_os_mutex_lock (&counters_mutex);
3186 for (agent = counters; agent; agent = agent->next) {
3187 if (agent->counter == counter) {
3188 agent->value_size = 0;
3190 free (agent->value);
3191 agent->value = NULL;
3193 mono_os_mutex_unlock (&counters_mutex);
3198 agent = (MonoCounterAgent *)malloc (sizeof (MonoCounterAgent));
3199 agent->counter = counter;
3200 agent->value = NULL;
3201 agent->value_size = 0;
3202 agent->index = counters_index++;
3215 mono_os_mutex_unlock (&counters_mutex);
3219 counters_init_foreach_callback (MonoCounter *counter, gpointer data)
3221 counters_add_agent (counter);
3226 counters_init (MonoProfiler *profiler)
3228 assert (!counters_initialized);
3230 mono_os_mutex_init (&counters_mutex);
3232 counters_initialized = TRUE;
3234 mono_counters_on_register (&counters_add_agent);
3235 mono_counters_foreach (counters_init_foreach_callback, NULL);
3239 counters_emit (MonoProfiler *profiler)
3241 MonoCounterAgent *agent;
3244 EVENT_SIZE /* event */ +
3245 LEB128_SIZE /* len */
3248 if (!counters_initialized)
3251 mono_os_mutex_lock (&counters_mutex);
3253 for (agent = counters; agent; agent = agent->next) {
3258 LEB128_SIZE /* section */ +
3259 strlen (mono_counter_get_name (agent->counter)) + 1 /* name */ +
3260 BYTE_SIZE /* type */ +
3261 BYTE_SIZE /* unit */ +
3262 BYTE_SIZE /* variance */ +
3263 LEB128_SIZE /* index */
3270 mono_os_mutex_unlock (&counters_mutex);
3276 LogBuffer *logbuffer = ensure_logbuf (size);
3278 emit_event (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
3279 emit_value (logbuffer, len);
3281 for (agent = counters; agent; agent = agent->next) {
3287 name = mono_counter_get_name (agent->counter);
3288 emit_value (logbuffer, mono_counter_get_section (agent->counter));
3289 emit_string (logbuffer, name, strlen (name) + 1);
3290 emit_byte (logbuffer, mono_counter_get_type (agent->counter));
3291 emit_byte (logbuffer, mono_counter_get_unit (agent->counter));
3292 emit_byte (logbuffer, mono_counter_get_variance (agent->counter));
3293 emit_value (logbuffer, agent->index);
3300 mono_os_mutex_unlock (&counters_mutex);
3304 counters_sample (MonoProfiler *profiler, uint64_t timestamp)
3306 MonoCounterAgent *agent;
3307 MonoCounter *counter;
3313 if (!counters_initialized)
3316 counters_emit (profiler);
3319 buffer = calloc (1, buffer_size);
3321 mono_os_mutex_lock (&counters_mutex);
3324 EVENT_SIZE /* event */
3327 for (agent = counters; agent; agent = agent->next) {
3329 LEB128_SIZE /* index */ +
3330 BYTE_SIZE /* type */ +
3331 mono_counter_get_size (agent->counter) /* value */
3336 LEB128_SIZE /* stop marker */
3341 LogBuffer *logbuffer = ensure_logbuf (size);
3343 emit_event_time (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE, timestamp);
3345 for (agent = counters; agent; agent = agent->next) {
3348 counter = agent->counter;
3350 size = mono_counter_get_size (counter);
3352 continue; // FIXME error
3353 } else if (size > buffer_size) {
3355 buffer = realloc (buffer, buffer_size);
3358 memset (buffer, 0, buffer_size);
3360 if (mono_counters_sample (counter, buffer, size) < 0)
3361 continue; // FIXME error
3363 type = mono_counter_get_type (counter);
3365 if (!agent->value) {
3366 agent->value = calloc (1, size);
3367 agent->value_size = size;
3369 if (type == MONO_COUNTER_STRING) {
3370 if (strcmp (agent->value, buffer) == 0)
3373 if (agent->value_size == size && memcmp (agent->value, buffer, size) == 0)
3378 emit_uvalue (logbuffer, agent->index);
3379 emit_byte (logbuffer, type);
3381 case MONO_COUNTER_INT:
3382 #if SIZEOF_VOID_P == 4
3383 case MONO_COUNTER_WORD:
3385 emit_svalue (logbuffer, *(int*)buffer - *(int*)agent->value);
3387 case MONO_COUNTER_UINT:
3388 emit_uvalue (logbuffer, *(guint*)buffer - *(guint*)agent->value);
3390 case MONO_COUNTER_TIME_INTERVAL:
3391 case MONO_COUNTER_LONG:
3392 #if SIZEOF_VOID_P == 8
3393 case MONO_COUNTER_WORD:
3395 emit_svalue (logbuffer, *(gint64*)buffer - *(gint64*)agent->value);
3397 case MONO_COUNTER_ULONG:
3398 emit_uvalue (logbuffer, *(guint64*)buffer - *(guint64*)agent->value);
3400 case MONO_COUNTER_DOUBLE:
3401 emit_double (logbuffer, *(double*)buffer);
3403 case MONO_COUNTER_STRING:
3405 emit_byte (logbuffer, 0);
3407 emit_byte (logbuffer, 1);
3408 emit_string (logbuffer, (char*)buffer, size);
3415 if (type == MONO_COUNTER_STRING && size > agent->value_size) {
3416 agent->value = realloc (agent->value, size);
3417 agent->value_size = size;
3421 memcpy (agent->value, buffer, size);
3425 emit_value (logbuffer, 0);
3429 mono_os_mutex_unlock (&counters_mutex);
3432 typedef struct _PerfCounterAgent PerfCounterAgent;
3433 struct _PerfCounterAgent {
3434 PerfCounterAgent *next;
3436 char *category_name;
3445 static PerfCounterAgent *perfcounters = NULL;
3448 perfcounters_emit (MonoProfiler *profiler)
3450 PerfCounterAgent *pcagent;
3453 EVENT_SIZE /* event */ +
3454 LEB128_SIZE /* len */
3457 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3458 if (pcagent->emitted)
3462 LEB128_SIZE /* section */ +
3463 strlen (pcagent->category_name) + 1 /* category name */ +
3464 strlen (pcagent->name) + 1 /* name */ +
3465 BYTE_SIZE /* type */ +
3466 BYTE_SIZE /* unit */ +
3467 BYTE_SIZE /* variance */ +
3468 LEB128_SIZE /* index */
3479 LogBuffer *logbuffer = ensure_logbuf (size);
3481 emit_event (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
3482 emit_value (logbuffer, len);
3484 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3485 if (pcagent->emitted)
3488 emit_value (logbuffer, MONO_COUNTER_PERFCOUNTERS);
3489 emit_string (logbuffer, pcagent->category_name, strlen (pcagent->category_name) + 1);
3490 emit_string (logbuffer, pcagent->name, strlen (pcagent->name) + 1);
3491 emit_byte (logbuffer, MONO_COUNTER_LONG);
3492 emit_byte (logbuffer, MONO_COUNTER_RAW);
3493 emit_byte (logbuffer, MONO_COUNTER_VARIABLE);
3494 emit_value (logbuffer, pcagent->index);
3496 pcagent->emitted = 1;
3503 perfcounters_foreach (char *category_name, char *name, unsigned char type, gint64 value, gpointer user_data)
3505 PerfCounterAgent *pcagent;
3507 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3508 if (strcmp (pcagent->category_name, category_name) != 0 || strcmp (pcagent->name, name) != 0)
3510 if (pcagent->value == value)
3513 pcagent->value = value;
3514 pcagent->updated = 1;
3515 pcagent->deleted = 0;
3519 pcagent = g_new0 (PerfCounterAgent, 1);
3520 pcagent->next = perfcounters;
3521 pcagent->index = counters_index++;
3522 pcagent->category_name = g_strdup (category_name);
3523 pcagent->name = g_strdup (name);
3524 pcagent->type = (int) type;
3525 pcagent->value = value;
3526 pcagent->emitted = 0;
3527 pcagent->updated = 1;
3528 pcagent->deleted = 0;
3530 perfcounters = pcagent;
3536 perfcounters_sample (MonoProfiler *profiler, uint64_t timestamp)
3538 PerfCounterAgent *pcagent;
3541 if (!counters_initialized)
3544 mono_os_mutex_lock (&counters_mutex);
3546 /* mark all perfcounters as deleted, foreach will unmark them as necessary */
3547 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next)
3548 pcagent->deleted = 1;
3550 mono_perfcounter_foreach (perfcounters_foreach, perfcounters);
3552 perfcounters_emit (profiler);
3555 EVENT_SIZE /* event */
3558 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3559 if (pcagent->deleted || !pcagent->updated)
3563 LEB128_SIZE /* index */ +
3564 BYTE_SIZE /* type */ +
3565 LEB128_SIZE /* value */
3570 LEB128_SIZE /* stop marker */
3575 LogBuffer *logbuffer = ensure_logbuf (size);
3577 emit_event_time (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE, timestamp);
3579 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3580 if (pcagent->deleted || !pcagent->updated)
3582 emit_uvalue (logbuffer, pcagent->index);
3583 emit_byte (logbuffer, MONO_COUNTER_LONG);
3584 emit_svalue (logbuffer, pcagent->value);
3586 pcagent->updated = 0;
3589 emit_value (logbuffer, 0);
3593 mono_os_mutex_unlock (&counters_mutex);
3597 counters_and_perfcounters_sample (MonoProfiler *prof)
3599 uint64_t now = current_time ();
3601 counters_sample (prof, now);
3602 perfcounters_sample (prof, now);
3605 #define COVERAGE_DEBUG(x) if (debug_coverage) {x}
3606 static mono_mutex_t coverage_mutex;
3607 static MonoConcurrentHashTable *coverage_methods = NULL;
3608 static MonoConcurrentHashTable *coverage_assemblies = NULL;
3609 static MonoConcurrentHashTable *coverage_classes = NULL;
3611 static MonoConcurrentHashTable *filtered_classes = NULL;
3612 static MonoConcurrentHashTable *entered_methods = NULL;
3613 static MonoConcurrentHashTable *image_to_methods = NULL;
3614 static MonoConcurrentHashTable *suppressed_assemblies = NULL;
3615 static gboolean coverage_initialized = FALSE;
3617 static GPtrArray *coverage_data = NULL;
3618 static int previous_offset = 0;
3621 MonoLockFreeQueueNode node;
3634 free_coverage_entry (gpointer data, gpointer userdata)
3636 CoverageEntry *entry = (CoverageEntry *)data;
3637 g_free (entry->filename);
3642 obtain_coverage_for_method (MonoProfiler *prof, const MonoProfileCoverageEntry *entry)
3644 int offset = entry->iloffset - previous_offset;
3645 CoverageEntry *e = g_new (CoverageEntry, 1);
3647 previous_offset = entry->iloffset;
3650 e->counter = entry->counter;
3651 e->filename = g_strdup(entry->filename ? entry->filename : "");
3652 e->line = entry->line;
3653 e->column = entry->col;
3655 g_ptr_array_add (coverage_data, e);
3659 parse_generic_type_names(char *name)
3661 char *new_name, *ret;
3662 int within_generic_declaration = 0, generic_members = 1;
3664 if (name == NULL || *name == '\0')
3665 return g_strdup ("");
3667 if (!(ret = new_name = (char *)calloc (strlen (name) * 4 + 1, sizeof (char))))
3673 within_generic_declaration = 1;
3677 within_generic_declaration = 0;
3679 if (*(name - 1) != '<') {
3681 *new_name++ = '0' + generic_members;
3683 memcpy (new_name, "<>", 8);
3687 generic_members = 0;
3695 if (!within_generic_declaration)
3696 *new_name++ = *name;
3705 static int method_id;
3707 build_method_buffer (gpointer key, gpointer value, gpointer userdata)
3709 MonoMethod *method = (MonoMethod *)value;
3710 MonoProfiler *prof = (MonoProfiler *)userdata;
3714 const char *image_name, *method_name, *sig, *first_filename;
3717 previous_offset = 0;
3718 coverage_data = g_ptr_array_new ();
3720 mono_profiler_coverage_get (prof, method, obtain_coverage_for_method);
3722 klass = mono_method_get_class (method);
3723 image = mono_class_get_image (klass);
3724 image_name = mono_image_get_name (image);
3726 sig = mono_signature_get_desc (mono_method_signature (method), TRUE);
3727 class_name = parse_generic_type_names (mono_type_get_name (mono_class_get_type (klass)));
3728 method_name = mono_method_get_name (method);
3730 if (coverage_data->len != 0) {
3731 CoverageEntry *entry = (CoverageEntry *)coverage_data->pdata[0];
3732 first_filename = entry->filename ? entry->filename : "";
3734 first_filename = "";
3736 image_name = image_name ? image_name : "";
3737 sig = sig ? sig : "";
3738 method_name = method_name ? method_name : "";
3742 LogBuffer *logbuffer = ensure_logbuf (
3743 EVENT_SIZE /* event */ +
3744 strlen (image_name) + 1 /* image name */ +
3745 strlen (class_name) + 1 /* class name */ +
3746 strlen (method_name) + 1 /* method name */ +
3747 strlen (sig) + 1 /* signature */ +
3748 strlen (first_filename) + 1 /* first file name */ +
3749 LEB128_SIZE /* token */ +
3750 LEB128_SIZE /* method id */ +
3751 LEB128_SIZE /* entries */
3754 emit_event (logbuffer, TYPE_COVERAGE_METHOD | TYPE_COVERAGE);
3755 emit_string (logbuffer, image_name, strlen (image_name) + 1);
3756 emit_string (logbuffer, class_name, strlen (class_name) + 1);
3757 emit_string (logbuffer, method_name, strlen (method_name) + 1);
3758 emit_string (logbuffer, sig, strlen (sig) + 1);
3759 emit_string (logbuffer, first_filename, strlen (first_filename) + 1);
3761 emit_uvalue (logbuffer, mono_method_get_token (method));
3762 emit_uvalue (logbuffer, method_id);
3763 emit_value (logbuffer, coverage_data->len);
3767 send_if_needed (prof);
3769 for (i = 0; i < coverage_data->len; i++) {
3770 CoverageEntry *entry = (CoverageEntry *)coverage_data->pdata[i];
3774 LogBuffer *logbuffer = ensure_logbuf (
3775 EVENT_SIZE /* event */ +
3776 LEB128_SIZE /* method id */ +
3777 LEB128_SIZE /* offset */ +
3778 LEB128_SIZE /* counter */ +
3779 LEB128_SIZE /* line */ +
3780 LEB128_SIZE /* column */
3783 emit_event (logbuffer, TYPE_COVERAGE_STATEMENT | TYPE_COVERAGE);
3784 emit_uvalue (logbuffer, method_id);
3785 emit_uvalue (logbuffer, entry->offset);
3786 emit_uvalue (logbuffer, entry->counter);
3787 emit_uvalue (logbuffer, entry->line);
3788 emit_uvalue (logbuffer, entry->column);
3792 send_if_needed (prof);
3797 g_free (class_name);
3799 g_ptr_array_foreach (coverage_data, free_coverage_entry, NULL);
3800 g_ptr_array_free (coverage_data, TRUE);
3801 coverage_data = NULL;
3804 /* This empties the queue */
3806 count_queue (MonoLockFreeQueue *queue)
3808 MonoLockFreeQueueNode *node;
3811 while ((node = mono_lock_free_queue_dequeue (queue))) {
3813 mono_thread_hazardous_try_free (node, free);
3820 build_class_buffer (gpointer key, gpointer value, gpointer userdata)
3822 MonoClass *klass = (MonoClass *)key;
3823 MonoLockFreeQueue *class_methods = (MonoLockFreeQueue *)value;
3824 MonoProfiler *prof = (MonoProfiler *)userdata;
3827 const char *assembly_name;
3828 int number_of_methods, partially_covered;
3829 guint fully_covered;
3831 image = mono_class_get_image (klass);
3832 assembly_name = mono_image_get_name (image);
3833 class_name = mono_type_get_name (mono_class_get_type (klass));
3835 assembly_name = assembly_name ? assembly_name : "";
3836 number_of_methods = mono_class_num_methods (klass);
3837 fully_covered = count_queue (class_methods);
3838 /* We don't handle partial covered yet */
3839 partially_covered = 0;
3843 LogBuffer *logbuffer = ensure_logbuf (
3844 EVENT_SIZE /* event */ +
3845 strlen (assembly_name) + 1 /* assembly name */ +
3846 strlen (class_name) + 1 /* class name */ +
3847 LEB128_SIZE /* no. methods */ +
3848 LEB128_SIZE /* fully covered */ +
3849 LEB128_SIZE /* partially covered */
3852 emit_event (logbuffer, TYPE_COVERAGE_CLASS | TYPE_COVERAGE);
3853 emit_string (logbuffer, assembly_name, strlen (assembly_name) + 1);
3854 emit_string (logbuffer, class_name, strlen (class_name) + 1);
3855 emit_uvalue (logbuffer, number_of_methods);
3856 emit_uvalue (logbuffer, fully_covered);
3857 emit_uvalue (logbuffer, partially_covered);
3861 send_if_needed (prof);
3863 g_free (class_name);
3867 get_coverage_for_image (MonoImage *image, int *number_of_methods, guint *fully_covered, int *partially_covered)
3869 MonoLockFreeQueue *image_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (image_to_methods, image);
3871 *number_of_methods = mono_image_get_table_rows (image, MONO_TABLE_METHOD);
3873 *fully_covered = count_queue (image_methods);
3877 // FIXME: We don't handle partially covered yet.
3878 *partially_covered = 0;
3882 build_assembly_buffer (gpointer key, gpointer value, gpointer userdata)
3884 MonoAssembly *assembly = (MonoAssembly *)value;
3885 MonoProfiler *prof = (MonoProfiler *)userdata;
3886 MonoImage *image = mono_assembly_get_image (assembly);
3887 const char *name, *guid, *filename;
3888 int number_of_methods = 0, partially_covered = 0;
3889 guint fully_covered = 0;
3891 name = mono_image_get_name (image);
3892 guid = mono_image_get_guid (image);
3893 filename = mono_image_get_filename (image);
3895 name = name ? name : "";
3896 guid = guid ? guid : "";
3897 filename = filename ? filename : "";
3899 get_coverage_for_image (image, &number_of_methods, &fully_covered, &partially_covered);
3903 LogBuffer *logbuffer = ensure_logbuf (
3904 EVENT_SIZE /* event */ +
3905 strlen (name) + 1 /* name */ +
3906 strlen (guid) + 1 /* guid */ +
3907 strlen (filename) + 1 /* file name */ +
3908 LEB128_SIZE /* no. methods */ +
3909 LEB128_SIZE /* fully covered */ +
3910 LEB128_SIZE /* partially covered */
3913 emit_event (logbuffer, TYPE_COVERAGE_ASSEMBLY | TYPE_COVERAGE);
3914 emit_string (logbuffer, name, strlen (name) + 1);
3915 emit_string (logbuffer, guid, strlen (guid) + 1);
3916 emit_string (logbuffer, filename, strlen (filename) + 1);
3917 emit_uvalue (logbuffer, number_of_methods);
3918 emit_uvalue (logbuffer, fully_covered);
3919 emit_uvalue (logbuffer, partially_covered);
3923 send_if_needed (prof);
3927 dump_coverage (MonoProfiler *prof)
3929 if (!coverage_initialized)
3932 COVERAGE_DEBUG(fprintf (stderr, "Coverage: Started dump\n");)
3935 mono_os_mutex_lock (&coverage_mutex);
3936 mono_conc_hashtable_foreach (coverage_assemblies, build_assembly_buffer, prof);
3937 mono_conc_hashtable_foreach (coverage_classes, build_class_buffer, prof);
3938 mono_conc_hashtable_foreach (coverage_methods, build_method_buffer, prof);
3939 mono_os_mutex_unlock (&coverage_mutex);
3941 COVERAGE_DEBUG(fprintf (stderr, "Coverage: Finished dump\n");)
3945 process_method_enter_coverage (MonoProfiler *prof, MonoMethod *method)
3950 if (!coverage_initialized)
3953 klass = mono_method_get_class (method);
3954 image = mono_class_get_image (klass);
3956 if (mono_conc_hashtable_lookup (suppressed_assemblies, (gpointer) mono_image_get_name (image)))
3959 mono_os_mutex_lock (&coverage_mutex);
3960 mono_conc_hashtable_insert (entered_methods, method, method);
3961 mono_os_mutex_unlock (&coverage_mutex);
3964 static MonoLockFreeQueueNode *
3965 create_method_node (MonoMethod *method)
3967 MethodNode *node = (MethodNode *)g_malloc (sizeof (MethodNode));
3968 mono_lock_free_queue_node_init ((MonoLockFreeQueueNode *) node, FALSE);
3969 node->method = method;
3971 return (MonoLockFreeQueueNode *) node;
3975 coverage_filter (MonoProfiler *prof, MonoMethod *method)
3980 MonoAssembly *assembly;
3981 MonoMethodHeader *header;
3982 guint32 iflags, flags, code_size;
3983 char *fqn, *classname;
3984 gboolean has_positive, found;
3985 MonoLockFreeQueue *image_methods, *class_methods;
3986 MonoLockFreeQueueNode *node;
3988 if (!coverage_initialized)
3991 COVERAGE_DEBUG(fprintf (stderr, "Coverage filter for %s\n", mono_method_get_name (method));)
3993 flags = mono_method_get_flags (method, &iflags);
3994 if ((iflags & 0x1000 /*METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL*/) ||
3995 (flags & 0x2000 /*METHOD_ATTRIBUTE_PINVOKE_IMPL*/)) {
3996 COVERAGE_DEBUG(fprintf (stderr, " Internal call or pinvoke - ignoring\n");)
4000 // Don't need to do anything else if we're already tracking this method
4001 if (mono_conc_hashtable_lookup (coverage_methods, method)) {
4002 COVERAGE_DEBUG(fprintf (stderr, " Already tracking\n");)
4006 klass = mono_method_get_class (method);
4007 image = mono_class_get_image (klass);
4009 // Don't handle coverage for the core assemblies
4010 if (mono_conc_hashtable_lookup (suppressed_assemblies, (gpointer) mono_image_get_name (image)) != NULL)
4013 if (prof->coverage_filters) {
4014 /* Check already filtered classes first */
4015 if (mono_conc_hashtable_lookup (filtered_classes, klass)) {
4016 COVERAGE_DEBUG(fprintf (stderr, " Already filtered\n");)
4020 classname = mono_type_get_name (mono_class_get_type (klass));
4022 fqn = g_strdup_printf ("[%s]%s", mono_image_get_name (image), classname);
4024 COVERAGE_DEBUG(fprintf (stderr, " Looking for %s in filter\n", fqn);)
4025 // Check positive filters first
4026 has_positive = FALSE;
4028 for (guint i = 0; i < prof->coverage_filters->len; ++i) {
4029 char *filter = (char *)g_ptr_array_index (prof->coverage_filters, i);
4031 if (filter [0] == '+') {
4032 filter = &filter [1];
4034 COVERAGE_DEBUG(fprintf (stderr, " Checking against +%s ...", filter);)
4036 if (strstr (fqn, filter) != NULL) {
4037 COVERAGE_DEBUG(fprintf (stderr, "matched\n");)
4040 COVERAGE_DEBUG(fprintf (stderr, "no match\n");)
4042 has_positive = TRUE;
4046 if (has_positive && !found) {
4047 COVERAGE_DEBUG(fprintf (stderr, " Positive match was not found\n");)
4049 mono_os_mutex_lock (&coverage_mutex);
4050 mono_conc_hashtable_insert (filtered_classes, klass, klass);
4051 mono_os_mutex_unlock (&coverage_mutex);
4058 for (guint i = 0; i < prof->coverage_filters->len; ++i) {
4059 // FIXME: Is substring search sufficient?
4060 char *filter = (char *)g_ptr_array_index (prof->coverage_filters, i);
4061 if (filter [0] == '+')
4065 filter = &filter [1];
4066 COVERAGE_DEBUG(fprintf (stderr, " Checking against -%s ...", filter);)
4068 if (strstr (fqn, filter) != NULL) {
4069 COVERAGE_DEBUG(fprintf (stderr, "matched\n");)
4071 mono_os_mutex_lock (&coverage_mutex);
4072 mono_conc_hashtable_insert (filtered_classes, klass, klass);
4073 mono_os_mutex_unlock (&coverage_mutex);
4079 COVERAGE_DEBUG(fprintf (stderr, "no match\n");)
4087 COVERAGE_DEBUG(fprintf (stderr, " Handling coverage for %s\n", mono_method_get_name (method));)
4088 header = mono_method_get_header_checked (method, &error);
4089 mono_error_cleanup (&error);
4091 mono_method_header_get_code (header, &code_size, NULL);
4093 assembly = mono_image_get_assembly (image);
4095 // Need to keep the assemblies around for as long as they are kept in the hashtable
4096 // Nunit, for example, has a habit of unloading them before the coverage statistics are
4097 // generated causing a crash. See https://bugzilla.xamarin.com/show_bug.cgi?id=39325
4098 mono_assembly_addref (assembly);
4100 mono_os_mutex_lock (&coverage_mutex);
4101 mono_conc_hashtable_insert (coverage_methods, method, method);
4102 mono_conc_hashtable_insert (coverage_assemblies, assembly, assembly);
4103 mono_os_mutex_unlock (&coverage_mutex);
4105 image_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (image_to_methods, image);
4107 if (image_methods == NULL) {
4108 image_methods = (MonoLockFreeQueue *)g_malloc (sizeof (MonoLockFreeQueue));
4109 mono_lock_free_queue_init (image_methods);
4110 mono_os_mutex_lock (&coverage_mutex);
4111 mono_conc_hashtable_insert (image_to_methods, image, image_methods);
4112 mono_os_mutex_unlock (&coverage_mutex);
4115 node = create_method_node (method);
4116 mono_lock_free_queue_enqueue (image_methods, node);
4118 class_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (coverage_classes, klass);
4120 if (class_methods == NULL) {
4121 class_methods = (MonoLockFreeQueue *)g_malloc (sizeof (MonoLockFreeQueue));
4122 mono_lock_free_queue_init (class_methods);
4123 mono_os_mutex_lock (&coverage_mutex);
4124 mono_conc_hashtable_insert (coverage_classes, klass, class_methods);
4125 mono_os_mutex_unlock (&coverage_mutex);
4128 node = create_method_node (method);
4129 mono_lock_free_queue_enqueue (class_methods, node);
4134 #define LINE_BUFFER_SIZE 4096
4135 /* Max file limit of 128KB */
4136 #define MAX_FILE_SIZE 128 * 1024
4138 get_file_content (FILE *stream)
4143 int res, offset = 0;
4145 res = fseek (stream, 0, SEEK_END);
4149 filesize = ftell (stream);
4153 res = fseek (stream, 0, SEEK_SET);
4157 if (filesize > MAX_FILE_SIZE)
4160 buffer = (char *)g_malloc ((filesize + 1) * sizeof (char));
4161 while ((bytes_read = fread (buffer + offset, 1, LINE_BUFFER_SIZE, stream)) > 0)
4162 offset += bytes_read;
4164 /* NULL terminate our buffer */
4165 buffer[filesize] = '\0';
4170 get_next_line (char *contents, char **next_start)
4174 if (p == NULL || *p == '\0') {
4179 while (*p != '\n' && *p != '\0')
4184 *next_start = p + 1;
4192 init_suppressed_assemblies (void)
4198 suppressed_assemblies = mono_conc_hashtable_new (g_str_hash, g_str_equal);
4199 sa_file = fopen (SUPPRESSION_DIR "/mono-profiler-log.suppression", "r");
4200 if (sa_file == NULL)
4203 /* Don't need to free @content as it is referred to by the lines stored in @suppressed_assemblies */
4204 content = get_file_content (sa_file);
4205 if (content == NULL) {
4206 g_error ("mono-profiler-log.suppression is greater than 128kb - aborting\n");
4209 while ((line = get_next_line (content, &content))) {
4210 line = g_strchomp (g_strchug (line));
4211 /* No locking needed as we're doing initialization */
4212 mono_conc_hashtable_insert (suppressed_assemblies, line, line);
4218 #endif /* DISABLE_HELPER_THREAD */
4221 coverage_init (MonoProfiler *prof)
4223 #ifndef DISABLE_HELPER_THREAD
4224 assert (!coverage_initialized);
4226 COVERAGE_DEBUG(fprintf (stderr, "Coverage initialized\n");)
4228 mono_os_mutex_init (&coverage_mutex);
4229 coverage_methods = mono_conc_hashtable_new (NULL, NULL);
4230 coverage_assemblies = mono_conc_hashtable_new (NULL, NULL);
4231 coverage_classes = mono_conc_hashtable_new (NULL, NULL);
4232 filtered_classes = mono_conc_hashtable_new (NULL, NULL);
4233 entered_methods = mono_conc_hashtable_new (NULL, NULL);
4234 image_to_methods = mono_conc_hashtable_new (NULL, NULL);
4235 init_suppressed_assemblies ();
4237 coverage_initialized = TRUE;
4238 #endif /* DISABLE_HELPER_THREAD */
4242 unref_coverage_assemblies (gpointer key, gpointer value, gpointer userdata)
4244 MonoAssembly *assembly = (MonoAssembly *)value;
4245 mono_assembly_close (assembly);
4249 free_sample_hit (gpointer p)
4251 mono_lock_free_free (p, SAMPLE_BLOCK_SIZE);
4255 cleanup_reusable_samples (MonoProfiler *prof)
4259 while ((sample = (SampleHit *) mono_lock_free_queue_dequeue (&prof->sample_reuse_queue)))
4260 mono_thread_hazardous_try_free (sample, free_sample_hit);
4264 log_shutdown (MonoProfiler *prof)
4269 #ifndef DISABLE_HELPER_THREAD
4270 counters_and_perfcounters_sample (prof);
4272 dump_coverage (prof);
4274 if (prof->command_port) {
4276 ign_res (write (prof->pipes [1], &c, 1));
4277 pthread_join (prof->helper_thread, &res);
4283 for (i = 0; i < num_perf; ++i)
4284 read_perf_mmap (prof, i);
4289 * Ensure that we empty the LLS completely, even if some nodes are
4290 * not immediately removed upon calling mono_lls_remove (), by
4291 * iterating until the head is NULL.
4293 while (profiler_thread_list.head) {
4294 MONO_LLS_FOREACH_SAFE (&profiler_thread_list, MonoProfilerThread, thread) {
4295 remove_thread (prof, thread, FALSE);
4296 } MONO_LLS_FOREACH_SAFE_END
4299 InterlockedWrite (&prof->run_dumper_thread, 0);
4300 mono_os_sem_post (&prof->dumper_queue_sem);
4301 pthread_join (prof->dumper_thread, &res);
4302 mono_os_sem_destroy (&prof->dumper_queue_sem);
4304 InterlockedWrite (&prof->run_writer_thread, 0);
4305 mono_os_sem_post (&prof->writer_queue_sem);
4306 pthread_join (prof->writer_thread, &res);
4307 mono_os_sem_destroy (&prof->writer_queue_sem);
4309 cleanup_reusable_samples (prof);
4312 * Pump the entire hazard free queue to make sure that anything we allocated
4313 * in the profiler will be freed. If we don't do this, the runtime could get
4314 * around to freeing some items after the profiler has been unloaded, which
4315 * would mean calling into functions in the profiler library, leading to a
4318 mono_thread_hazardous_try_free_all ();
4320 g_assert (!InterlockedRead (&buffer_rwlock_count) && "Why is the reader count still non-zero?");
4321 g_assert (!InterlockedReadPointer (&buffer_rwlock_exclusive) && "Why does someone still hold the exclusive lock?");
4323 #if defined (HAVE_SYS_ZLIB)
4325 gzclose (prof->gzfile);
4327 if (prof->pipe_output)
4328 pclose (prof->file);
4330 fclose (prof->file);
4332 mono_conc_hashtable_destroy (prof->method_table);
4333 mono_os_mutex_destroy (&prof->method_table_mutex);
4335 if (coverage_initialized) {
4336 mono_os_mutex_lock (&coverage_mutex);
4337 mono_conc_hashtable_foreach (coverage_assemblies, unref_coverage_assemblies, prof);
4338 mono_os_mutex_unlock (&coverage_mutex);
4340 mono_conc_hashtable_destroy (coverage_methods);
4341 mono_conc_hashtable_destroy (coverage_assemblies);
4342 mono_conc_hashtable_destroy (coverage_classes);
4343 mono_conc_hashtable_destroy (filtered_classes);
4345 mono_conc_hashtable_destroy (entered_methods);
4346 mono_conc_hashtable_destroy (image_to_methods);
4347 mono_conc_hashtable_destroy (suppressed_assemblies);
4348 mono_os_mutex_destroy (&coverage_mutex);
4358 new_filename (const char* filename)
4360 time_t t = time (NULL);
4361 int pid = process_id ();
4366 int count_dates = 0;
4370 for (p = filename; *p; p++) {
4381 if (!count_dates && !count_pids)
4382 return pstrdup (filename);
4383 snprintf (pid_buf, sizeof (pid_buf), "%d", pid);
4385 snprintf (time_buf, sizeof (time_buf), "%d%02d%02d%02d%02d%02d",
4386 1900 + ts->tm_year, 1 + ts->tm_mon, ts->tm_mday, ts->tm_hour, ts->tm_min, ts->tm_sec);
4387 s_date = strlen (time_buf);
4388 s_pid = strlen (pid_buf);
4389 d = res = (char *)malloc (strlen (filename) + s_date * count_dates + s_pid * count_pids);
4390 for (p = filename; *p; p++) {
4397 strcpy (d, time_buf);
4400 } else if (*p == 'p') {
4401 strcpy (d, pid_buf);
4404 } else if (*p == '%') {
4416 //this is exposed by the JIT, but it's not meant to be a supported API for now.
4417 extern void mono_threads_attach_tools_thread (void);
4419 #ifndef DISABLE_HELPER_THREAD
4422 helper_thread (void* arg)
4424 MonoProfiler* prof = (MonoProfiler *)arg;
4429 mono_threads_attach_tools_thread ();
4430 mono_native_thread_set_name (mono_native_thread_id_get (), "Profiler helper");
4432 init_thread (FALSE);
4434 //fprintf (stderr, "Server listening\n");
4435 command_socket = -1;
4441 FD_SET (prof->server_socket, &rfds);
4442 max_fd = prof->server_socket;
4443 FD_SET (prof->pipes [0], &rfds);
4444 if (max_fd < prof->pipes [0])
4445 max_fd = prof->pipes [0];
4446 if (command_socket >= 0) {
4447 FD_SET (command_socket, &rfds);
4448 if (max_fd < command_socket)
4449 max_fd = command_socket;
4454 for ( i = 0; i < num_perf; ++i) {
4455 if (perf_data [i].perf_fd < 0)
4457 FD_SET (perf_data [i].perf_fd, &rfds);
4458 if (max_fd < perf_data [i].perf_fd)
4459 max_fd = perf_data [i].perf_fd;
4464 counters_and_perfcounters_sample (prof);
4466 buffer_lock_excl ();
4468 sync_point (prof, SYNC_POINT_PERIODIC);
4470 buffer_unlock_excl ();
4474 len = select (max_fd + 1, &rfds, NULL, NULL, &tv);
4480 g_warning ("Error in proflog server: %s", strerror (errno));
4484 if (FD_ISSET (prof->pipes [0], &rfds)) {
4486 read (prof->pipes [0], &c, 1);
4488 fprintf (stderr, "helper shutdown\n");
4492 for ( i = 0; i < num_perf; ++i) {
4493 if (perf_data [i].perf_fd < 0)
4495 if (FD_ISSET (perf_data [i].perf_fd, &rfds))
4496 read_perf_mmap (prof, i);
4500 safe_send_threadless (prof);
4506 for ( i = 0; i < num_perf; ++i) {
4507 if (perf_data [i].perf_fd < 0)
4509 if (FD_ISSET (perf_data [i].perf_fd, &rfds)) {
4510 read_perf_mmap (prof, i);
4511 send_if_needed_threadless (prof);
4516 if (command_socket >= 0 && FD_ISSET (command_socket, &rfds)) {
4517 len = read (command_socket, buf, sizeof (buf) - 1);
4521 close (command_socket);
4522 command_socket = -1;
4526 if (strcmp (buf, "heapshot\n") == 0 && hs_mode_ondemand) {
4527 // Rely on the finalization callbacks invoking process_requests ().
4528 heapshot_requested = 1;
4529 mono_gc_finalize_notify ();
4533 if (!FD_ISSET (prof->server_socket, &rfds)) {
4536 command_socket = accept (prof->server_socket, NULL, NULL);
4537 if (command_socket < 0)
4539 //fprintf (stderr, "Accepted connection\n");
4542 mono_thread_info_detach ();
4548 start_helper_thread (MonoProfiler* prof)
4550 struct sockaddr_in server_address;
4553 if (pipe (prof->pipes) < 0) {
4554 fprintf (stderr, "Cannot create pipe\n");
4557 prof->server_socket = socket (PF_INET, SOCK_STREAM, 0);
4558 if (prof->server_socket < 0) {
4559 fprintf (stderr, "Cannot create server socket\n");
4562 memset (&server_address, 0, sizeof (server_address));
4563 server_address.sin_family = AF_INET;
4564 server_address.sin_addr.s_addr = INADDR_ANY;
4565 server_address.sin_port = htons (prof->command_port);
4566 if (bind (prof->server_socket, (struct sockaddr *) &server_address, sizeof (server_address)) < 0) {
4567 fprintf (stderr, "Cannot bind server socket, port: %d: %s\n", prof->command_port, strerror (errno));
4568 close (prof->server_socket);
4571 if (listen (prof->server_socket, 1) < 0) {
4572 fprintf (stderr, "Cannot listen server socket\n");
4573 close (prof->server_socket);
4576 slen = sizeof (server_address);
4577 if (getsockname (prof->server_socket, (struct sockaddr *)&server_address, &slen) == 0) {
4578 prof->command_port = ntohs (server_address.sin_port);
4579 /*fprintf (stderr, "Assigned server port: %d\n", prof->command_port);*/
4582 r = pthread_create (&prof->helper_thread, NULL, helper_thread, prof);
4584 close (prof->server_socket);
4592 free_writer_entry (gpointer p)
4594 mono_lock_free_free (p, WRITER_ENTRY_BLOCK_SIZE);
4598 handle_writer_queue_entry (MonoProfiler *prof)
4600 WriterQueueEntry *entry;
4602 if ((entry = (WriterQueueEntry *) mono_lock_free_queue_dequeue (&prof->writer_queue))) {
4603 if (!entry->methods)
4606 LogBuffer *buf = NULL;
4609 * Encode the method events in a temporary log buffer that we
4610 * flush to disk before the main buffer, ensuring that all
4611 * methods have metadata emitted before they're referenced.
4613 * We use a 'proper' thread-local buffer for this as opposed
4614 * to allocating and freeing a buffer by hand because the call
4615 * to mono_method_full_name () below may trigger class load
4616 * events when it retrieves the signature of the method. So a
4617 * thread-local buffer needs to exist when such events occur.
4619 for (guint i = 0; i < entry->methods->len; i++) {
4620 MethodInfo *info = (MethodInfo *) g_ptr_array_index (entry->methods, i);
4622 if (mono_conc_hashtable_lookup (prof->method_table, info->method))
4623 goto free_info; // This method already has metadata emitted.
4626 * Other threads use this hash table to get a general
4627 * idea of whether a method has already been emitted to
4628 * the stream. Due to the way we add to this table, it
4629 * can easily happen that multiple threads queue up the
4630 * same methods, but that's OK since eventually all
4631 * methods will be in this table and the thread-local
4632 * method lists will just be empty for the rest of the
4635 mono_os_mutex_lock (&prof->method_table_mutex);
4636 mono_conc_hashtable_insert (prof->method_table, info->method, info->method);
4637 mono_os_mutex_unlock (&prof->method_table_mutex);
4639 char *name = mono_method_full_name (info->method, 1);
4640 int nlen = strlen (name) + 1;
4641 void *cstart = info->ji ? mono_jit_info_get_code_start (info->ji) : NULL;
4642 int csize = info->ji ? mono_jit_info_get_code_size (info->ji) : 0;
4644 buf = ensure_logbuf_unsafe (
4645 EVENT_SIZE /* event */ +
4646 LEB128_SIZE /* method */ +
4647 LEB128_SIZE /* start */ +
4648 LEB128_SIZE /* size */ +
4652 emit_event_time (buf, TYPE_JIT | TYPE_METHOD, info->time);
4653 emit_method_inner (buf, info->method);
4654 emit_ptr (buf, cstart);
4655 emit_value (buf, csize);
4657 memcpy (buf->cursor, name, nlen);
4658 buf->cursor += nlen;
4666 g_ptr_array_free (entry->methods, TRUE);
4669 dump_buffer_threadless (prof, buf);
4670 init_buffer_state (PROF_TLS_GET ());
4674 dump_buffer (prof, entry->buffer);
4676 mono_thread_hazardous_try_free (entry, free_writer_entry);
4685 writer_thread (void *arg)
4687 MonoProfiler *prof = (MonoProfiler *)arg;
4689 mono_threads_attach_tools_thread ();
4690 mono_native_thread_set_name (mono_native_thread_id_get (), "Profiler writer");
4694 MonoProfilerThread *thread = init_thread (FALSE);
4696 while (InterlockedRead (&prof->run_writer_thread)) {
4697 mono_os_sem_wait (&prof->writer_queue_sem, MONO_SEM_FLAGS_NONE);
4698 handle_writer_queue_entry (prof);
4701 /* Drain any remaining entries on shutdown. */
4702 while (handle_writer_queue_entry (prof));
4704 free_buffer (thread->buffer, thread->buffer->size);
4705 deinit_thread (thread);
4707 mono_thread_info_detach ();
4713 start_writer_thread (MonoProfiler* prof)
4715 InterlockedWrite (&prof->run_writer_thread, 1);
4717 return !pthread_create (&prof->writer_thread, NULL, writer_thread, prof);
4721 reuse_sample_hit (gpointer p)
4723 SampleHit *sample = p;
4725 mono_lock_free_queue_node_unpoison (&sample->node);
4726 mono_lock_free_queue_enqueue (&sample->prof->sample_reuse_queue, &sample->node);
4730 handle_dumper_queue_entry (MonoProfiler *prof)
4734 if ((sample = (SampleHit *) mono_lock_free_queue_dequeue (&prof->dumper_queue))) {
4735 for (int i = 0; i < sample->count; ++i) {
4736 MonoMethod *method = sample->frames [i].method;
4737 MonoDomain *domain = sample->frames [i].domain;
4738 void *address = sample->frames [i].base_address;
4741 g_assert (domain && "What happened to the domain pointer?");
4742 g_assert (address && "What happened to the instruction pointer?");
4744 MonoJitInfo *ji = mono_jit_info_table_find (domain, (char *) address);
4747 sample->frames [i].method = mono_jit_info_get_method (ji);
4751 LogBuffer *logbuffer = ensure_logbuf_unsafe (
4752 EVENT_SIZE /* event */ +
4753 BYTE_SIZE /* type */ +
4754 LEB128_SIZE /* tid */ +
4755 LEB128_SIZE /* count */ +
4757 LEB128_SIZE /* ip */
4759 LEB128_SIZE /* managed count */ +
4761 LEB128_SIZE /* method */
4765 emit_event_time (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_HIT, sample->time);
4766 emit_byte (logbuffer, sample_type);
4767 emit_ptr (logbuffer, (void *) sample->tid);
4768 emit_value (logbuffer, 1);
4770 // TODO: Actual native unwinding.
4771 for (int i = 0; i < 1; ++i) {
4772 emit_ptr (logbuffer, sample->ip);
4773 add_code_pointer ((uintptr_t) sample->ip);
4776 /* new in data version 6 */
4777 emit_uvalue (logbuffer, sample->count);
4779 for (int i = 0; i < sample->count; ++i)
4780 emit_method (prof, logbuffer, sample->frames [i].method);
4782 mono_thread_hazardous_try_free (sample, reuse_sample_hit);
4784 dump_unmanaged_coderefs (prof);
4786 send_if_needed_threadless (prof);
4793 dumper_thread (void *arg)
4795 MonoProfiler *prof = (MonoProfiler *)arg;
4797 mono_threads_attach_tools_thread ();
4798 mono_native_thread_set_name (mono_native_thread_id_get (), "Profiler dumper");
4800 MonoProfilerThread *thread = init_thread (FALSE);
4802 while (InterlockedRead (&prof->run_dumper_thread)) {
4803 mono_os_sem_wait (&prof->dumper_queue_sem, MONO_SEM_FLAGS_NONE);
4804 handle_dumper_queue_entry (prof);
4807 /* Drain any remaining entries on shutdown. */
4808 while (handle_dumper_queue_entry (prof));
4810 safe_send_threadless (prof);
4811 deinit_thread (thread);
4813 mono_thread_info_detach ();
4819 start_dumper_thread (MonoProfiler* prof)
4821 InterlockedWrite (&prof->run_dumper_thread, 1);
4823 return !pthread_create (&prof->dumper_thread, NULL, dumper_thread, prof);
4827 runtime_initialized (MonoProfiler *profiler)
4829 InterlockedWrite (&runtime_inited, 1);
4831 #ifndef DISABLE_HELPER_THREAD
4832 if (hs_mode_ondemand || need_helper_thread) {
4833 if (!start_helper_thread (profiler))
4834 profiler->command_port = 0;
4838 start_writer_thread (profiler);
4839 start_dumper_thread (profiler);
4841 mono_counters_register ("Sample hits", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &sample_hits);
4842 mono_counters_register ("Sample flushes", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &sample_flushes);
4843 mono_counters_register ("Sample events allocated", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &sample_allocations);
4844 mono_counters_register ("Log buffers allocated", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &buffer_allocations);
4845 mono_counters_register ("Thread start events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &thread_starts);
4846 mono_counters_register ("Thread stop events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &thread_ends);
4847 mono_counters_register ("Domain load events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &domain_loads);
4848 mono_counters_register ("Domain unload events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &domain_unloads);
4849 mono_counters_register ("Context load events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &context_loads);
4850 mono_counters_register ("Context unload events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &context_unloads);
4851 mono_counters_register ("Assembly load events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &assembly_loads);
4852 mono_counters_register ("Assembly unload events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &assembly_unloads);
4853 mono_counters_register ("Image load events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &image_loads);
4854 mono_counters_register ("Image unload events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &image_unloads);
4855 mono_counters_register ("Class load events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &class_loads);
4856 mono_counters_register ("Class unload events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &class_unloads);
4858 #ifndef DISABLE_HELPER_THREAD
4859 counters_init (profiler);
4860 counters_sample (profiler, 0);
4862 /* ensure the main thread data and startup are available soon */
4863 safe_send (profiler);
4866 static MonoProfiler*
4867 create_profiler (const char *args, const char *filename, GPtrArray *filters)
4871 int force_delete = 0;
4872 prof = (MonoProfiler *)calloc (1, sizeof (MonoProfiler));
4874 prof->args = pstrdup (args);
4875 prof->command_port = command_port;
4876 if (filename && *filename == '-') {
4882 filename = "|mprof-report -";
4884 filename = "output.mlpd";
4885 nf = (char*)filename;
4887 nf = new_filename (filename);
4889 int s = strlen (nf) + 32;
4890 char *p = (char *)malloc (s);
4891 snprintf (p, s, "|mprof-report '--out=%s' -", nf);
4897 prof->file = popen (nf + 1, "w");
4898 prof->pipe_output = 1;
4899 } else if (*nf == '#') {
4900 int fd = strtol (nf + 1, NULL, 10);
4901 prof->file = fdopen (fd, "a");
4905 prof->file = fopen (nf, "wb");
4908 fprintf (stderr, "Cannot create profiler output: %s\n", nf);
4911 #if defined (HAVE_SYS_ZLIB)
4913 prof->gzfile = gzdopen (fileno (prof->file), "wb");
4916 if (sample_type && sample_freq && !do_mono_sample)
4917 need_helper_thread = setup_perf_event ();
4919 /* FIXME: warn if different freq or sample type */
4923 if (do_mono_sample) {
4924 need_helper_thread = 1;
4926 if (do_counters && !need_helper_thread) {
4927 need_helper_thread = 1;
4931 * If you hit this assert while increasing MAX_FRAMES, you need to increase
4932 * SAMPLE_BLOCK_SIZE as well.
4934 g_assert (SAMPLE_SLOT_SIZE (MAX_FRAMES) * 2 < LOCK_FREE_ALLOC_SB_USABLE_SIZE (SAMPLE_BLOCK_SIZE));
4936 // FIXME: We should free this stuff too.
4937 mono_lock_free_allocator_init_size_class (&prof->sample_size_class, SAMPLE_SLOT_SIZE (num_frames), SAMPLE_BLOCK_SIZE);
4938 mono_lock_free_allocator_init_allocator (&prof->sample_allocator, &prof->sample_size_class);
4940 mono_lock_free_queue_init (&prof->sample_reuse_queue);
4942 #ifdef DISABLE_HELPER_THREAD
4943 if (hs_mode_ondemand)
4944 fprintf (stderr, "Ondemand heapshot unavailable on this arch.\n");
4947 fprintf (stderr, "Coverage unavailable on this arch.\n");
4951 g_assert (sizeof (WriterQueueEntry) * 2 < LOCK_FREE_ALLOC_SB_USABLE_SIZE (WRITER_ENTRY_BLOCK_SIZE));
4953 // FIXME: We should free this stuff too.
4954 mono_lock_free_allocator_init_size_class (&prof->writer_entry_size_class, sizeof (WriterQueueEntry), WRITER_ENTRY_BLOCK_SIZE);
4955 mono_lock_free_allocator_init_allocator (&prof->writer_entry_allocator, &prof->writer_entry_size_class);
4957 mono_lock_free_queue_init (&prof->writer_queue);
4958 mono_os_sem_init (&prof->writer_queue_sem, 0);
4960 mono_lock_free_queue_init (&prof->dumper_queue);
4961 mono_os_sem_init (&prof->dumper_queue_sem, 0);
4963 mono_os_mutex_init (&prof->method_table_mutex);
4964 prof->method_table = mono_conc_hashtable_new (NULL, NULL);
4967 coverage_init (prof);
4968 prof->coverage_filters = filters;
4970 prof->startup_time = current_time ();
4977 printf ("Log profiler version %d.%d (format: %d)\n", LOG_VERSION_MAJOR, LOG_VERSION_MINOR, LOG_DATA_VERSION);
4978 printf ("Usage: mono --profile=log[:OPTION1[,OPTION2...]] program.exe\n");
4979 printf ("Options:\n");
4980 printf ("\thelp show this usage info\n");
4981 printf ("\t[no]alloc enable/disable recording allocation info\n");
4982 printf ("\t[no]calls enable/disable recording enter/leave method events\n");
4983 printf ("\theapshot[=MODE] record heap shot info (by default at each major collection)\n");
4984 printf ("\t MODE: every XXms milliseconds, every YYgc collections, ondemand\n");
4985 printf ("\tcounters sample counters every 1s\n");
4986 printf ("\tsample[=TYPE] use statistical sampling mode (by default cycles/100)\n");
4987 printf ("\t TYPE: cycles,instr,cacherefs,cachemiss,branches,branchmiss\n");
4988 printf ("\t TYPE can be followed by /FREQUENCY\n");
4989 printf ("\ttime=fast use a faster (but more inaccurate) timer\n");
4990 printf ("\tmaxframes=NUM collect up to NUM stack frames\n");
4991 printf ("\tcalldepth=NUM ignore method events for call chain depth bigger than NUM\n");
4992 printf ("\toutput=FILENAME write the data to file FILENAME (-FILENAME to overwrite)\n");
4993 printf ("\toutput=|PROGRAM write the data to the stdin of PROGRAM\n");
4994 printf ("\t %%t is subtituted with date and time, %%p with the pid\n");
4995 printf ("\treport create a report instead of writing the raw data to a file\n");
4996 printf ("\tzip compress the output data\n");
4997 printf ("\tport=PORTNUM use PORTNUM for the listening command server\n");
4998 printf ("\tcoverage enable collection of code coverage data\n");
4999 printf ("\tcovfilter=ASSEMBLY add an assembly to the code coverage filters\n");
5000 printf ("\t add a + to include the assembly or a - to exclude it\n");
5001 printf ("\t filter=-mscorlib\n");
5002 printf ("\tcovfilter-file=FILE use FILE to generate the list of assemblies to be filtered\n");
5008 match_option (const char* p, const char *opt, char **rval)
5010 int len = strlen (opt);
5011 if (strncmp (p, opt, len) == 0) {
5013 if (p [len] == '=' && p [len + 1]) {
5014 const char *opt = p + len + 1;
5015 const char *end = strchr (opt, ',');
5023 val = (char *)malloc (l + 1);
5024 memcpy (val, opt, l);
5029 if (p [len] == 0 || p [len] == ',') {
5031 return p + len + (p [len] == ',');
5049 static const SampleMode sample_modes [] = {
5050 {"cycles", SAMPLE_CYCLES},
5051 {"instr", SAMPLE_INSTRUCTIONS},
5052 {"cachemiss", SAMPLE_CACHE_MISSES},
5053 {"cacherefs", SAMPLE_CACHE_REFS},
5054 {"branches", SAMPLE_BRANCHES},
5055 {"branchmiss", SAMPLE_BRANCH_MISSES},
5060 set_sample_mode (char* val, int allow_empty)
5063 char *maybe_freq = NULL;
5065 const SampleMode *smode = sample_modes;
5066 #ifndef USE_PERF_EVENTS
5069 if (allow_empty && !val) {
5070 sample_type = SAMPLE_CYCLES;
5074 if (strcmp (val, "mono") == 0) {
5076 sample_type = SAMPLE_CYCLES;
5080 for (smode = sample_modes; smode->name; smode++) {
5081 int l = strlen (smode->name);
5082 if (strncmp (val, smode->name, l) == 0) {
5083 sample_type = smode->sample_mode;
5084 maybe_freq = val + l;
5090 if (*maybe_freq == '/') {
5091 count = strtoul (maybe_freq + 1, &end, 10);
5092 if (maybe_freq + 1 == end)
5094 sample_freq = count;
5095 } else if (*maybe_freq != 0) {
5104 set_hsmode (char* val, int allow_empty)
5108 if (allow_empty && !val)
5110 if (strcmp (val, "ondemand") == 0) {
5111 hs_mode_ondemand = 1;
5115 count = strtoul (val, &end, 10);
5118 if (strcmp (end, "ms") == 0)
5120 else if (strcmp (end, "gc") == 0)
5128 * declaration to silence the compiler: this is the entry point that
5129 * mono will load from the shared library and call.
5132 mono_profiler_startup (const char *desc);
5135 mono_profiler_startup_log (const char *desc);
5138 * this is the entry point that will be used when the profiler
5139 * is embedded inside the main executable.
5142 mono_profiler_startup_log (const char *desc)
5144 mono_profiler_startup (desc);
5148 mono_profiler_startup (const char *desc)
5151 GPtrArray *filters = NULL;
5152 char *filename = NULL;
5156 int calls_enabled = 0;
5157 int allocs_enabled = 0;
5158 int only_counters = 0;
5159 int only_coverage = 0;
5160 int events = MONO_PROFILE_GC|MONO_PROFILE_ALLOCATIONS|
5161 MONO_PROFILE_GC_MOVES|MONO_PROFILE_CLASS_EVENTS|MONO_PROFILE_THREADS|
5162 MONO_PROFILE_ENTER_LEAVE|MONO_PROFILE_JIT_COMPILATION|MONO_PROFILE_EXCEPTIONS|
5163 MONO_PROFILE_MONITOR_EVENTS|MONO_PROFILE_MODULE_EVENTS|MONO_PROFILE_GC_ROOTS|
5164 MONO_PROFILE_INS_COVERAGE|MONO_PROFILE_APPDOMAIN_EVENTS|MONO_PROFILE_CONTEXT_EVENTS|
5165 MONO_PROFILE_ASSEMBLY_EVENTS|MONO_PROFILE_GC_FINALIZATION;
5167 max_allocated_sample_hits = mono_cpu_count () * 1000;
5170 if (strncmp (p, "log", 3))
5175 for (; *p; p = opt) {
5181 if ((opt = match_option (p, "help", NULL)) != p) {
5185 if ((opt = match_option (p, "calls", NULL)) != p) {
5189 if ((opt = match_option (p, "nocalls", NULL)) != p) {
5190 events &= ~MONO_PROFILE_ENTER_LEAVE;
5194 if ((opt = match_option (p, "alloc", NULL)) != p) {
5198 if ((opt = match_option (p, "noalloc", NULL)) != p) {
5199 events &= ~MONO_PROFILE_ALLOCATIONS;
5202 if ((opt = match_option (p, "time", &val)) != p) {
5203 if (strcmp (val, "fast") == 0)
5205 else if (strcmp (val, "null") == 0)
5212 if ((opt = match_option (p, "report", NULL)) != p) {
5216 if ((opt = match_option (p, "debug", NULL)) != p) {
5220 if ((opt = match_option (p, "sampling-real", NULL)) != p) {
5221 sampling_mode = MONO_PROFILER_STAT_MODE_REAL;
5224 if ((opt = match_option (p, "sampling-process", NULL)) != p) {
5225 sampling_mode = MONO_PROFILER_STAT_MODE_PROCESS;
5228 if ((opt = match_option (p, "heapshot", &val)) != p) {
5229 events &= ~MONO_PROFILE_ALLOCATIONS;
5230 events &= ~MONO_PROFILE_ENTER_LEAVE;
5233 set_hsmode (val, 1);
5236 if ((opt = match_option (p, "sample", &val)) != p) {
5237 events &= ~MONO_PROFILE_ALLOCATIONS;
5238 events &= ~MONO_PROFILE_ENTER_LEAVE;
5240 set_sample_mode (val, 1);
5243 if ((opt = match_option (p, "hsmode", &val)) != p) {
5244 fprintf (stderr, "The hsmode profiler option is obsolete, use heapshot=MODE.\n");
5245 set_hsmode (val, 0);
5248 if ((opt = match_option (p, "zip", NULL)) != p) {
5252 if ((opt = match_option (p, "output", &val)) != p) {
5256 if ((opt = match_option (p, "port", &val)) != p) {
5258 command_port = strtoul (val, &end, 10);
5262 if ((opt = match_option (p, "maxframes", &val)) != p) {
5264 num_frames = strtoul (val, &end, 10);
5265 if (num_frames > MAX_FRAMES)
5266 num_frames = MAX_FRAMES;
5268 notraces = num_frames == 0;
5271 if ((opt = match_option (p, "maxsamples", &val)) != p) {
5273 max_allocated_sample_hits = strtoul (val, &end, 10);
5274 if (!max_allocated_sample_hits)
5275 max_allocated_sample_hits = G_MAXINT32;
5279 if ((opt = match_option (p, "calldepth", &val)) != p) {
5281 max_call_depth = strtoul (val, &end, 10);
5285 if ((opt = match_option (p, "counters", NULL)) != p) {
5289 if ((opt = match_option (p, "countersonly", NULL)) != p) {
5293 if ((opt = match_option (p, "coverage", NULL)) != p) {
5295 events |= MONO_PROFILE_ENTER_LEAVE;
5296 debug_coverage = (g_getenv ("MONO_PROFILER_DEBUG_COVERAGE") != NULL);
5299 if ((opt = match_option (p, "onlycoverage", NULL)) != p) {
5303 if ((opt = match_option (p, "covfilter-file", &val)) != p) {
5305 char *line, *content;
5307 if (filters == NULL)
5308 filters = g_ptr_array_new ();
5310 filter_file = fopen (val, "r");
5311 if (filter_file == NULL) {
5312 fprintf (stderr, "Unable to open %s\n", val);
5316 /* Don't need to free content as it is referred to by the lines stored in @filters */
5317 content = get_file_content (filter_file);
5318 if (content == NULL)
5319 fprintf (stderr, "WARNING: %s is greater than 128kb - ignoring\n", val);
5321 while ((line = get_next_line (content, &content)))
5322 g_ptr_array_add (filters, g_strchug (g_strchomp (line)));
5324 fclose (filter_file);
5327 if ((opt = match_option (p, "covfilter", &val)) != p) {
5328 if (filters == NULL)
5329 filters = g_ptr_array_new ();
5331 g_ptr_array_add (filters, val);
5339 if (calls_enabled) {
5340 events |= MONO_PROFILE_ENTER_LEAVE;
5344 events |= MONO_PROFILE_ALLOCATIONS;
5348 events = MONO_PROFILE_ENTER_LEAVE | MONO_PROFILE_INS_COVERAGE;
5350 utils_init (fast_time);
5354 prof = create_profiler (desc, filename, filters);
5360 mono_lls_init (&profiler_thread_list, NULL);
5364 mono_profiler_install (prof, log_shutdown);
5365 mono_profiler_install_gc (gc_event, gc_resize);
5366 mono_profiler_install_allocation (gc_alloc);
5367 mono_profiler_install_gc_moves (gc_moves);
5368 mono_profiler_install_gc_roots (gc_handle, gc_roots);
5369 mono_profiler_install_gc_finalize (finalize_begin, finalize_object_begin, finalize_object_end, finalize_end);
5370 mono_profiler_install_appdomain (NULL, domain_loaded, domain_unloaded, NULL);
5371 mono_profiler_install_appdomain_name (domain_name);
5372 mono_profiler_install_context (context_loaded, context_unloaded);
5373 mono_profiler_install_class (NULL, class_loaded, class_unloaded, NULL);
5374 mono_profiler_install_module (NULL, image_loaded, image_unloaded, NULL);
5375 mono_profiler_install_assembly (NULL, assembly_loaded, assembly_unloaded, NULL);
5376 mono_profiler_install_thread (thread_start, thread_end);
5377 mono_profiler_install_thread_name (thread_name);
5378 mono_profiler_install_enter_leave (method_enter, method_leave);
5379 mono_profiler_install_jit_end (method_jitted);
5380 mono_profiler_install_code_buffer_new (code_buffer_new);
5381 mono_profiler_install_exception (throw_exc, method_exc_leave, clause_exc);
5382 mono_profiler_install_monitor (monitor_event);
5383 mono_profiler_install_runtime_initialized (runtime_initialized);
5385 mono_profiler_install_coverage_filter (coverage_filter);
5387 if (do_mono_sample && sample_type == SAMPLE_CYCLES && sample_freq && !only_counters) {
5388 events |= MONO_PROFILE_STATISTICAL;
5389 mono_profiler_set_statistical_mode (sampling_mode, sample_freq);
5390 mono_profiler_install_statistical (mono_sample_hit);
5393 mono_profiler_set_events ((MonoProfileFlags)events);